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 NetGraphmsgHandler) with messages
16 //! they should handle, and encoding/sending response messages.
18 use bitcoin::secp256k1::key::{SecretKey,PublicKey};
20 use ln::features::InitFeatures;
22 use ln::msgs::{ChannelMessageHandler, LightningError, RoutingMessageHandler};
23 use ln::channelmanager::{SimpleArcChannelManager, SimpleRefChannelManager};
24 use util::ser::{VecWriter, Writeable};
25 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
29 use util::events::{MessageSendEvent, MessageSendEventsProvider};
30 use util::logger::Logger;
31 use routing::network_graph::NetGraphMsgHandler;
34 use alloc::collections::LinkedList;
35 use std::sync::{Arc, Mutex};
36 use core::sync::atomic::{AtomicUsize, Ordering};
37 use core::{cmp, hash, fmt, mem};
41 use bitcoin::hashes::sha256::Hash as Sha256;
42 use bitcoin::hashes::sha256::HashEngine as Sha256Engine;
43 use bitcoin::hashes::{HashEngine, Hash};
45 /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information
46 /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler.
47 pub struct IgnoringMessageHandler{}
48 impl MessageSendEventsProvider for IgnoringMessageHandler {
49 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> { Vec::new() }
51 impl RoutingMessageHandler for IgnoringMessageHandler {
52 fn handle_node_announcement(&self, _msg: &msgs::NodeAnnouncement) -> Result<bool, LightningError> { Ok(false) }
53 fn handle_channel_announcement(&self, _msg: &msgs::ChannelAnnouncement) -> Result<bool, LightningError> { Ok(false) }
54 fn handle_channel_update(&self, _msg: &msgs::ChannelUpdate) -> Result<bool, LightningError> { Ok(false) }
55 fn handle_htlc_fail_channel_update(&self, _update: &msgs::HTLCFailChannelUpdate) {}
56 fn get_next_channel_announcements(&self, _starting_point: u64, _batch_amount: u8) ->
57 Vec<(msgs::ChannelAnnouncement, Option<msgs::ChannelUpdate>, Option<msgs::ChannelUpdate>)> { Vec::new() }
58 fn get_next_node_announcements(&self, _starting_point: Option<&PublicKey>, _batch_amount: u8) -> Vec<msgs::NodeAnnouncement> { Vec::new() }
59 fn sync_routing_table(&self, _their_node_id: &PublicKey, _init: &msgs::Init) {}
60 fn handle_reply_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyChannelRange) -> Result<(), LightningError> { Ok(()) }
61 fn handle_reply_short_channel_ids_end(&self, _their_node_id: &PublicKey, _msg: msgs::ReplyShortChannelIdsEnd) -> Result<(), LightningError> { Ok(()) }
62 fn handle_query_channel_range(&self, _their_node_id: &PublicKey, _msg: msgs::QueryChannelRange) -> Result<(), LightningError> { Ok(()) }
63 fn handle_query_short_channel_ids(&self, _their_node_id: &PublicKey, _msg: msgs::QueryShortChannelIds) -> Result<(), LightningError> { Ok(()) }
65 impl Deref for IgnoringMessageHandler {
66 type Target = IgnoringMessageHandler;
67 fn deref(&self) -> &Self { self }
70 /// A dummy struct which implements `ChannelMessageHandler` without having any channels.
71 /// You can provide one of these as the route_handler in a MessageHandler.
72 pub struct ErroringMessageHandler {
73 message_queue: Mutex<Vec<MessageSendEvent>>
75 impl ErroringMessageHandler {
76 /// Constructs a new ErroringMessageHandler
77 pub fn new() -> Self {
78 Self { message_queue: Mutex::new(Vec::new()) }
80 fn push_error(&self, node_id: &PublicKey, channel_id: [u8; 32]) {
81 self.message_queue.lock().unwrap().push(MessageSendEvent::HandleError {
82 action: msgs::ErrorAction::SendErrorMessage {
83 msg: msgs::ErrorMessage { channel_id, data: "We do not support channel messages, sorry.".to_owned() },
85 node_id: node_id.clone(),
89 impl MessageSendEventsProvider for ErroringMessageHandler {
90 fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
91 let mut res = Vec::new();
92 mem::swap(&mut res, &mut self.message_queue.lock().unwrap());
96 impl ChannelMessageHandler for ErroringMessageHandler {
97 // Any messages which are related to a specific channel generate an error message to let the
98 // peer know we don't care about channels.
99 fn handle_open_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::OpenChannel) {
100 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
102 fn handle_accept_channel(&self, their_node_id: &PublicKey, _their_features: InitFeatures, msg: &msgs::AcceptChannel) {
103 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
105 fn handle_funding_created(&self, their_node_id: &PublicKey, msg: &msgs::FundingCreated) {
106 ErroringMessageHandler::push_error(self, their_node_id, msg.temporary_channel_id);
108 fn handle_funding_signed(&self, their_node_id: &PublicKey, msg: &msgs::FundingSigned) {
109 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
111 fn handle_funding_locked(&self, their_node_id: &PublicKey, msg: &msgs::FundingLocked) {
112 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
114 fn handle_shutdown(&self, their_node_id: &PublicKey, _their_features: &InitFeatures, msg: &msgs::Shutdown) {
115 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
117 fn handle_closing_signed(&self, their_node_id: &PublicKey, msg: &msgs::ClosingSigned) {
118 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
120 fn handle_update_add_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateAddHTLC) {
121 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
123 fn handle_update_fulfill_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) {
124 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
126 fn handle_update_fail_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailHTLC) {
127 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
129 fn handle_update_fail_malformed_htlc(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFailMalformedHTLC) {
130 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
132 fn handle_commitment_signed(&self, their_node_id: &PublicKey, msg: &msgs::CommitmentSigned) {
133 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
135 fn handle_revoke_and_ack(&self, their_node_id: &PublicKey, msg: &msgs::RevokeAndACK) {
136 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
138 fn handle_update_fee(&self, their_node_id: &PublicKey, msg: &msgs::UpdateFee) {
139 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
141 fn handle_announcement_signatures(&self, their_node_id: &PublicKey, msg: &msgs::AnnouncementSignatures) {
142 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
144 fn handle_channel_reestablish(&self, their_node_id: &PublicKey, msg: &msgs::ChannelReestablish) {
145 ErroringMessageHandler::push_error(self, their_node_id, msg.channel_id);
147 // msgs::ChannelUpdate does not contain the channel_id field, so we just drop them.
148 fn handle_channel_update(&self, _their_node_id: &PublicKey, _msg: &msgs::ChannelUpdate) {}
149 fn peer_disconnected(&self, _their_node_id: &PublicKey, _no_connection_possible: bool) {}
150 fn peer_connected(&self, _their_node_id: &PublicKey, _msg: &msgs::Init) {}
151 fn handle_error(&self, _their_node_id: &PublicKey, _msg: &msgs::ErrorMessage) {}
153 impl Deref for ErroringMessageHandler {
154 type Target = ErroringMessageHandler;
155 fn deref(&self) -> &Self { self }
158 /// Provides references to trait impls which handle different types of messages.
159 pub struct MessageHandler<CM: Deref, RM: Deref> where
160 CM::Target: ChannelMessageHandler,
161 RM::Target: RoutingMessageHandler {
162 /// A message handler which handles messages specific to channels. Usually this is just a
163 /// [`ChannelManager`] object or an [`ErroringMessageHandler`].
165 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
166 pub chan_handler: CM,
167 /// A message handler which handles messages updating our knowledge of the network channel
168 /// graph. Usually this is just a [`NetGraphMsgHandler`] object or an
169 /// [`IgnoringMessageHandler`].
171 /// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler
172 pub route_handler: RM,
175 /// Provides an object which can be used to send data to and which uniquely identifies a connection
176 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
177 /// implement Hash to meet the PeerManager API.
179 /// For efficiency, Clone should be relatively cheap for this type.
181 /// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original
182 /// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it
183 /// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no
184 /// further calls to the [`PeerManager`] related to the original socket occur. This allows you to
185 /// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish
186 /// to simply use another value which is guaranteed to be globally unique instead.
187 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
188 /// Attempts to send some data from the given slice to the peer.
190 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
191 /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be
192 /// called and further write attempts may occur until that time.
194 /// If the returned size is smaller than `data.len()`, a
195 /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be
196 /// written. Additionally, until a `send_data` event completes fully, no further
197 /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to
198 /// prevent denial-of-service issues, you should not read or buffer any data from the socket
201 /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true
202 /// (indicating that read events should be paused to prevent DoS in the send buffer),
203 /// `resume_read` may be set indicating that read events on this descriptor should resume. A
204 /// `resume_read` of false carries no meaning, and should not cause any action.
205 fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize;
206 /// Disconnect the socket pointed to by this SocketDescriptor.
208 /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this
209 /// call (doing so is a noop).
210 fn disconnect_socket(&mut self);
213 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
214 /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the
217 pub struct PeerHandleError {
218 /// Used to indicate that we probably can't make any future connections to this peer, implying
219 /// we should go ahead and force-close any channels we have with it.
220 pub no_connection_possible: bool,
222 impl fmt::Debug for PeerHandleError {
223 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
224 formatter.write_str("Peer Sent Invalid Data")
227 impl fmt::Display for PeerHandleError {
228 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
229 formatter.write_str("Peer Sent Invalid Data")
232 impl error::Error for PeerHandleError {
233 fn description(&self) -> &str {
234 "Peer Sent Invalid Data"
238 enum InitSyncTracker{
240 ChannelsSyncing(u64),
241 NodesSyncing(PublicKey),
244 /// When the outbound buffer has this many messages, we'll stop reading bytes from the peer until
245 /// we have fewer than this many messages in the outbound buffer again.
246 /// We also use this as the target number of outbound gossip messages to keep in the write buffer,
247 /// refilled as we send bytes.
248 const OUTBOUND_BUFFER_LIMIT_READ_PAUSE: usize = 10;
249 /// When the outbound buffer has this many messages, we'll simply skip relaying gossip messages to
251 const OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP: usize = 20;
254 channel_encryptor: PeerChannelEncryptor,
255 their_node_id: Option<PublicKey>,
256 their_features: Option<InitFeatures>,
258 pending_outbound_buffer: LinkedList<Vec<u8>>,
259 pending_outbound_buffer_first_msg_offset: usize,
260 awaiting_write_event: bool,
262 pending_read_buffer: Vec<u8>,
263 pending_read_buffer_pos: usize,
264 pending_read_is_header: bool,
266 sync_status: InitSyncTracker,
272 /// Returns true if the channel announcements/updates for the given channel should be
273 /// forwarded to this peer.
274 /// If we are sending our routing table to this peer and we have not yet sent channel
275 /// announcements/updates for the given channel_id then we will send it when we get to that
276 /// point and we shouldn't send it yet to avoid sending duplicate updates. If we've already
277 /// sent the old versions, we should send the update, and so return true here.
278 fn should_forward_channel_announcement(&self, channel_id: u64)->bool{
279 match self.sync_status {
280 InitSyncTracker::NoSyncRequested => true,
281 InitSyncTracker::ChannelsSyncing(i) => i < channel_id,
282 InitSyncTracker::NodesSyncing(_) => true,
286 /// Similar to the above, but for node announcements indexed by node_id.
287 fn should_forward_node_announcement(&self, node_id: PublicKey) -> bool {
288 match self.sync_status {
289 InitSyncTracker::NoSyncRequested => true,
290 InitSyncTracker::ChannelsSyncing(_) => false,
291 InitSyncTracker::NodesSyncing(pk) => pk < node_id,
296 struct PeerHolder<Descriptor: SocketDescriptor> {
297 peers: HashMap<Descriptor, Peer>,
298 /// Only add to this set when noise completes:
299 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
302 #[cfg(not(any(target_pointer_width = "32", target_pointer_width = "64")))]
303 fn _check_usize_is_32_or_64() {
304 // See below, less than 32 bit pointers may be unsafe here!
305 unsafe { mem::transmute::<*const usize, [u8; 4]>(panic!()); }
308 /// SimpleArcPeerManager is useful when you need a PeerManager with a static lifetime, e.g.
309 /// when you're using lightning-net-tokio (since tokio::spawn requires parameters with static
310 /// lifetimes). Other times you can afford a reference, which is more efficient, in which case
311 /// SimpleRefPeerManager is the more appropriate type. Defining these type aliases prevents
312 /// issues such as overly long function definitions.
313 pub type SimpleArcPeerManager<SD, M, T, F, C, L> = PeerManager<SD, Arc<SimpleArcChannelManager<M, T, F, L>>, Arc<NetGraphMsgHandler<Arc<C>, Arc<L>>>, Arc<L>>;
315 /// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
316 /// counterpart to the SimpleArcPeerManager type alias. Use this type by default when you don't
317 /// need a PeerManager with a static lifetime. You'll need a static lifetime in cases such as
318 /// usage of lightning-net-tokio (since tokio::spawn requires parameters with static lifetimes).
319 /// But if this is not necessary, using a reference is more efficient. Defining these type aliases
320 /// helps with issues such as long function definitions.
321 pub type SimpleRefPeerManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, SD, M, T, F, C, L> = PeerManager<SD, SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L>, &'e NetGraphMsgHandler<&'g C, &'f L>, &'f L>;
323 /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls
324 /// socket events into messages which it passes on to its [`MessageHandler`].
326 /// Locks are taken internally, so you must never assume that reentrancy from a
327 /// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock.
329 /// Calls to [`read_event`] will decode relevant messages and pass them to the
330 /// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of
331 /// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any
332 /// [`PeerManager`] functions related to the same connection must occur only in serial, making new
333 /// calls only after previous ones have returned.
335 /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager
336 /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but
337 /// essentially you should default to using a SimpleRefPeerManager, and use a
338 /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when
339 /// you're using lightning-net-tokio.
341 /// [`read_event`]: PeerManager::read_event
342 pub struct PeerManager<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> where
343 CM::Target: ChannelMessageHandler,
344 RM::Target: RoutingMessageHandler,
346 message_handler: MessageHandler<CM, RM>,
347 peers: Mutex<PeerHolder<Descriptor>>,
348 our_node_secret: SecretKey,
349 ephemeral_key_midstate: Sha256Engine,
351 // Usize needs to be at least 32 bits to avoid overflowing both low and high. If usize is 64
352 // bits we will never realistically count into high:
353 peer_counter_low: AtomicUsize,
354 peer_counter_high: AtomicUsize,
359 enum MessageHandlingError {
360 PeerHandleError(PeerHandleError),
361 LightningError(LightningError),
364 impl From<PeerHandleError> for MessageHandlingError {
365 fn from(error: PeerHandleError) -> Self {
366 MessageHandlingError::PeerHandleError(error)
370 impl From<LightningError> for MessageHandlingError {
371 fn from(error: LightningError) -> Self {
372 MessageHandlingError::LightningError(error)
376 macro_rules! encode_msg {
378 let mut buffer = VecWriter(Vec::new());
379 wire::write($msg, &mut buffer).unwrap();
384 impl<Descriptor: SocketDescriptor, CM: Deref, L: Deref> PeerManager<Descriptor, CM, IgnoringMessageHandler, L> where
385 CM::Target: ChannelMessageHandler,
387 /// Constructs a new PeerManager with the given ChannelMessageHandler. No routing message
388 /// handler is used and network graph messages are ignored.
390 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
391 /// cryptographically secure random bytes.
393 /// (C-not exported) as we can't export a PeerManager with a dummy route handler
394 pub fn new_channel_only(channel_message_handler: CM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
395 Self::new(MessageHandler {
396 chan_handler: channel_message_handler,
397 route_handler: IgnoringMessageHandler{},
398 }, our_node_secret, ephemeral_random_data, logger)
402 impl<Descriptor: SocketDescriptor, RM: Deref, L: Deref> PeerManager<Descriptor, ErroringMessageHandler, RM, L> where
403 RM::Target: RoutingMessageHandler,
405 /// Constructs a new PeerManager with the given RoutingMessageHandler. No channel message
406 /// handler is used and messages related to channels will be ignored (or generate error
407 /// messages). Note that some other lightning implementations time-out connections after some
408 /// time if no channel is built with the peer.
410 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
411 /// cryptographically secure random bytes.
413 /// (C-not exported) as we can't export a PeerManager with a dummy channel handler
414 pub fn new_routing_only(routing_message_handler: RM, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
415 Self::new(MessageHandler {
416 chan_handler: ErroringMessageHandler::new(),
417 route_handler: routing_message_handler,
418 }, our_node_secret, ephemeral_random_data, logger)
422 impl<Descriptor: SocketDescriptor, CM: Deref, RM: Deref, L: Deref> PeerManager<Descriptor, CM, RM, L> where
423 CM::Target: ChannelMessageHandler,
424 RM::Target: RoutingMessageHandler,
426 /// Constructs a new PeerManager with the given message handlers and node_id secret key
427 /// ephemeral_random_data is used to derive per-connection ephemeral keys and must be
428 /// cryptographically secure random bytes.
429 pub fn new(message_handler: MessageHandler<CM, RM>, our_node_secret: SecretKey, ephemeral_random_data: &[u8; 32], logger: L) -> Self {
430 let mut ephemeral_key_midstate = Sha256::engine();
431 ephemeral_key_midstate.input(ephemeral_random_data);
435 peers: Mutex::new(PeerHolder {
436 peers: HashMap::new(),
437 node_id_to_descriptor: HashMap::new()
440 ephemeral_key_midstate,
441 peer_counter_low: AtomicUsize::new(0),
442 peer_counter_high: AtomicUsize::new(0),
447 /// Get the list of node ids for peers which have completed the initial handshake.
449 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
450 /// new_outbound_connection, however entries will only appear once the initial handshake has
451 /// completed and we are sure the remote peer has the private key for the given node_id.
452 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
453 let peers = self.peers.lock().unwrap();
454 peers.peers.values().filter_map(|p| {
455 if !p.channel_encryptor.is_ready_for_encryption() || p.their_features.is_none() {
462 fn get_ephemeral_key(&self) -> SecretKey {
463 let mut ephemeral_hash = self.ephemeral_key_midstate.clone();
464 let low = self.peer_counter_low.fetch_add(1, Ordering::AcqRel);
465 let high = if low == 0 {
466 self.peer_counter_high.fetch_add(1, Ordering::AcqRel)
468 self.peer_counter_high.load(Ordering::Acquire)
470 ephemeral_hash.input(&byte_utils::le64_to_array(low as u64));
471 ephemeral_hash.input(&byte_utils::le64_to_array(high as u64));
472 SecretKey::from_slice(&Sha256::from_engine(ephemeral_hash).into_inner()).expect("You broke SHA-256!")
475 /// Indicates a new outbound connection has been established to a node with the given node_id.
476 /// Note that if an Err is returned here you MUST NOT call socket_disconnected for the new
477 /// descriptor but must disconnect the connection immediately.
479 /// Returns a small number of bytes to send to the remote node (currently always 50).
481 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
482 /// [`socket_disconnected()`].
484 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
485 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
486 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone(), self.get_ephemeral_key());
487 let res = peer_encryptor.get_act_one().to_vec();
488 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
490 let mut peers = self.peers.lock().unwrap();
491 if peers.peers.insert(descriptor, Peer {
492 channel_encryptor: peer_encryptor,
494 their_features: None,
496 pending_outbound_buffer: LinkedList::new(),
497 pending_outbound_buffer_first_msg_offset: 0,
498 awaiting_write_event: false,
501 pending_read_buffer_pos: 0,
502 pending_read_is_header: false,
504 sync_status: InitSyncTracker::NoSyncRequested,
506 awaiting_pong: false,
508 panic!("PeerManager driver duplicated descriptors!");
513 /// Indicates a new inbound connection has been established.
515 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
516 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
517 /// call socket_disconnected for the new descriptor but must disconnect the connection
520 /// Panics if descriptor is duplicative with some other descriptor which has not yet been
521 /// [`socket_disconnected()`].
523 /// [`socket_disconnected()`]: PeerManager::socket_disconnected
524 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
525 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
526 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
528 let mut peers = self.peers.lock().unwrap();
529 if peers.peers.insert(descriptor, Peer {
530 channel_encryptor: peer_encryptor,
532 their_features: None,
534 pending_outbound_buffer: LinkedList::new(),
535 pending_outbound_buffer_first_msg_offset: 0,
536 awaiting_write_event: false,
539 pending_read_buffer_pos: 0,
540 pending_read_is_header: false,
542 sync_status: InitSyncTracker::NoSyncRequested,
544 awaiting_pong: false,
546 panic!("PeerManager driver duplicated descriptors!");
551 fn do_attempt_write_data(&self, descriptor: &mut Descriptor, peer: &mut Peer) {
552 while !peer.awaiting_write_event {
553 if peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE {
554 match peer.sync_status {
555 InitSyncTracker::NoSyncRequested => {},
556 InitSyncTracker::ChannelsSyncing(c) if c < 0xffff_ffff_ffff_ffff => {
557 let steps = ((OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len() + 2) / 3) as u8;
558 let all_messages = self.message_handler.route_handler.get_next_channel_announcements(c, steps);
559 for &(ref announce, ref update_a_option, ref update_b_option) in all_messages.iter() {
560 self.enqueue_message(peer, announce);
561 if let &Some(ref update_a) = update_a_option {
562 self.enqueue_message(peer, update_a);
564 if let &Some(ref update_b) = update_b_option {
565 self.enqueue_message(peer, update_b);
567 peer.sync_status = InitSyncTracker::ChannelsSyncing(announce.contents.short_channel_id + 1);
569 if all_messages.is_empty() || all_messages.len() != steps as usize {
570 peer.sync_status = InitSyncTracker::ChannelsSyncing(0xffff_ffff_ffff_ffff);
573 InitSyncTracker::ChannelsSyncing(c) if c == 0xffff_ffff_ffff_ffff => {
574 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
575 let all_messages = self.message_handler.route_handler.get_next_node_announcements(None, steps);
576 for msg in all_messages.iter() {
577 self.enqueue_message(peer, msg);
578 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
580 if all_messages.is_empty() || all_messages.len() != steps as usize {
581 peer.sync_status = InitSyncTracker::NoSyncRequested;
584 InitSyncTracker::ChannelsSyncing(_) => unreachable!(),
585 InitSyncTracker::NodesSyncing(key) => {
586 let steps = (OUTBOUND_BUFFER_LIMIT_READ_PAUSE - peer.pending_outbound_buffer.len()) as u8;
587 let all_messages = self.message_handler.route_handler.get_next_node_announcements(Some(&key), steps);
588 for msg in all_messages.iter() {
589 self.enqueue_message(peer, msg);
590 peer.sync_status = InitSyncTracker::NodesSyncing(msg.contents.node_id);
592 if all_messages.is_empty() || all_messages.len() != steps as usize {
593 peer.sync_status = InitSyncTracker::NoSyncRequested;
600 let next_buff = match peer.pending_outbound_buffer.front() {
605 let should_be_reading = peer.pending_outbound_buffer.len() < OUTBOUND_BUFFER_LIMIT_READ_PAUSE;
606 let pending = &next_buff[peer.pending_outbound_buffer_first_msg_offset..];
607 let data_sent = descriptor.send_data(pending, should_be_reading);
608 peer.pending_outbound_buffer_first_msg_offset += data_sent;
609 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
611 peer.pending_outbound_buffer_first_msg_offset = 0;
612 peer.pending_outbound_buffer.pop_front();
614 peer.awaiting_write_event = true;
619 /// Indicates that there is room to write data to the given socket descriptor.
621 /// May return an Err to indicate that the connection should be closed.
623 /// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before
624 /// returning. Thus, be very careful with reentrancy issues! The invariants around calling
625 /// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be
626 /// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't
629 /// [`send_data`]: SocketDescriptor::send_data
630 /// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail
631 pub fn write_buffer_space_avail(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
632 let mut peers = self.peers.lock().unwrap();
633 match peers.peers.get_mut(descriptor) {
635 // This is most likely a simple race condition where the user found that the socket
636 // was writeable, then we told the user to `disconnect_socket()`, then they called
637 // this method. Return an error to make sure we get disconnected.
638 return Err(PeerHandleError { no_connection_possible: false });
641 peer.awaiting_write_event = false;
642 self.do_attempt_write_data(descriptor, peer);
648 /// Indicates that data was read from the given socket descriptor.
650 /// May return an Err to indicate that the connection should be closed.
652 /// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity.
653 /// Thus, however, you should call [`process_events`] after any `read_event` to generate
654 /// [`send_data`] calls to handle responses.
656 /// If `Ok(true)` is returned, further read_events should not be triggered until a
657 /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the
660 /// [`send_data`]: SocketDescriptor::send_data
661 /// [`process_events`]: PeerManager::process_events
662 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
663 match self.do_read_event(peer_descriptor, data) {
666 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
672 /// Append a message to a peer's pending outbound/write buffer, and update the map of peers needing sends accordingly.
673 fn enqueue_message<M: Encode + Writeable>(&self, peer: &mut Peer, message: &M) {
674 let mut buffer = VecWriter(Vec::new());
675 wire::write(message, &mut buffer).unwrap(); // crash if the write failed
676 let encoded_message = buffer.0;
678 log_trace!(self.logger, "Enqueueing message of type {} to {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
679 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
682 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
684 let mut peers_lock = self.peers.lock().unwrap();
685 let peers = &mut *peers_lock;
686 let mut msgs_to_forward = Vec::new();
687 let mut peer_node_id = None;
688 let pause_read = match peers.peers.get_mut(peer_descriptor) {
690 // This is most likely a simple race condition where the user read some bytes
691 // from the socket, then we told the user to `disconnect_socket()`, then they
692 // called this method. Return an error to make sure we get disconnected.
693 return Err(PeerHandleError { no_connection_possible: false });
696 assert!(peer.pending_read_buffer.len() > 0);
697 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
699 let mut read_pos = 0;
700 while read_pos < data.len() {
702 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
703 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]);
704 read_pos += data_to_copy;
705 peer.pending_read_buffer_pos += data_to_copy;
708 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
709 peer.pending_read_buffer_pos = 0;
711 macro_rules! try_potential_handleerror {
717 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
718 //TODO: Try to push msg
719 log_trace!(self.logger, "Got Err handling message, disconnecting peer because {}", e.err);
720 return Err(PeerHandleError{ no_connection_possible: false });
722 msgs::ErrorAction::IgnoreError => {
723 log_trace!(self.logger, "Got Err handling message, ignoring because {}", e.err);
726 msgs::ErrorAction::SendErrorMessage { msg } => {
727 log_trace!(self.logger, "Got Err handling message, sending Error message because {}", e.err);
728 self.enqueue_message(peer, &msg);
737 macro_rules! insert_node_id {
739 match peers.node_id_to_descriptor.entry(peer.their_node_id.unwrap()) {
740 hash_map::Entry::Occupied(_) => {
741 log_trace!(self.logger, "Got second connection with {}, closing", log_pubkey!(peer.their_node_id.unwrap()));
742 peer.their_node_id = None; // Unset so that we don't generate a peer_disconnected event
743 return Err(PeerHandleError{ no_connection_possible: false })
745 hash_map::Entry::Vacant(entry) => {
746 log_trace!(self.logger, "Finished noise handshake for connection with {}", log_pubkey!(peer.their_node_id.unwrap()));
747 entry.insert(peer_descriptor.clone())
753 let next_step = peer.channel_encryptor.get_noise_step();
755 NextNoiseStep::ActOne => {
756 let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_keys(&peer.pending_read_buffer[..], &self.our_node_secret, self.get_ephemeral_key())).to_vec();
757 peer.pending_outbound_buffer.push_back(act_two);
758 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
760 NextNoiseStep::ActTwo => {
761 let (act_three, their_node_id) = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret));
762 peer.pending_outbound_buffer.push_back(act_three.to_vec());
763 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
764 peer.pending_read_is_header = true;
766 peer.their_node_id = Some(their_node_id);
768 let features = InitFeatures::known();
769 let resp = msgs::Init { features };
770 self.enqueue_message(peer, &resp);
772 NextNoiseStep::ActThree => {
773 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
774 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
775 peer.pending_read_is_header = true;
776 peer.their_node_id = Some(their_node_id);
778 let features = InitFeatures::known();
779 let resp = msgs::Init { features };
780 self.enqueue_message(peer, &resp);
782 NextNoiseStep::NoiseComplete => {
783 if peer.pending_read_is_header {
784 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
785 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
786 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
787 if msg_len < 2 { // Need at least the message type tag
788 return Err(PeerHandleError{ no_connection_possible: false });
790 peer.pending_read_is_header = false;
792 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
793 assert!(msg_data.len() >= 2);
796 peer.pending_read_buffer = [0; 18].to_vec();
797 peer.pending_read_is_header = true;
799 let mut reader = ::std::io::Cursor::new(&msg_data[..]);
800 let message_result = wire::read(&mut reader);
801 let message = match message_result {
805 msgs::DecodeError::UnknownVersion => return Err(PeerHandleError { no_connection_possible: false }),
806 msgs::DecodeError::UnknownRequiredFeature => {
807 log_debug!(self.logger, "Got a channel/node announcement with an known required feature flag, you may want to update!");
810 msgs::DecodeError::InvalidValue => {
811 log_debug!(self.logger, "Got an invalid value while deserializing message");
812 return Err(PeerHandleError { no_connection_possible: false });
814 msgs::DecodeError::ShortRead => {
815 log_debug!(self.logger, "Deserialization failed due to shortness of message");
816 return Err(PeerHandleError { no_connection_possible: false });
818 msgs::DecodeError::BadLengthDescriptor => return Err(PeerHandleError { no_connection_possible: false }),
819 msgs::DecodeError::Io(_) => return Err(PeerHandleError { no_connection_possible: false }),
820 msgs::DecodeError::UnsupportedCompression => {
821 log_debug!(self.logger, "We don't support zlib-compressed message fields, ignoring message");
828 match self.handle_message(peer, message) {
829 Err(handling_error) => match handling_error {
830 MessageHandlingError::PeerHandleError(e) => { return Err(e) },
831 MessageHandlingError::LightningError(e) => {
832 try_potential_handleerror!(Err(e));
836 peer_node_id = Some(peer.their_node_id.expect("After noise is complete, their_node_id is always set"));
837 msgs_to_forward.push(msg);
847 peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_READ_PAUSE // pause_read
851 for msg in msgs_to_forward.drain(..) {
852 self.forward_broadcast_msg(peers, &msg, peer_node_id.as_ref());
861 /// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
862 /// Returns the message back if it needs to be broadcasted to all other peers.
863 fn handle_message(&self, peer: &mut Peer, message: wire::Message) -> Result<Option<wire::Message>, MessageHandlingError> {
864 log_trace!(self.logger, "Received message of type {} from {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
866 // Need an Init as first message
867 if let wire::Message::Init(_) = message {
868 } else if peer.their_features.is_none() {
869 log_trace!(self.logger, "Peer {} sent non-Init first message", log_pubkey!(peer.their_node_id.unwrap()));
870 return Err(PeerHandleError{ no_connection_possible: false }.into());
873 let mut should_forward = None;
876 // Setup and Control messages:
877 wire::Message::Init(msg) => {
878 if msg.features.requires_unknown_bits() {
879 log_info!(self.logger, "Peer features required unknown version bits");
880 return Err(PeerHandleError{ no_connection_possible: true }.into());
882 if peer.their_features.is_some() {
883 return Err(PeerHandleError{ no_connection_possible: false }.into());
887 self.logger, "Received peer Init message: data_loss_protect: {}, initial_routing_sync: {}, upfront_shutdown_script: {}, gossip_queries: {}, static_remote_key: {}, unknown flags (local and global): {}",
888 if msg.features.supports_data_loss_protect() { "supported" } else { "not supported"},
889 if msg.features.initial_routing_sync() { "requested" } else { "not requested" },
890 if msg.features.supports_upfront_shutdown_script() { "supported" } else { "not supported"},
891 if msg.features.supports_gossip_queries() { "supported" } else { "not supported" },
892 if msg.features.supports_static_remote_key() { "supported" } else { "not supported"},
893 if msg.features.supports_unknown_bits() { "present" } else { "none" }
896 if msg.features.initial_routing_sync() {
897 peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
899 if !msg.features.supports_static_remote_key() {
900 log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap()));
901 return Err(PeerHandleError{ no_connection_possible: true }.into());
904 self.message_handler.route_handler.sync_routing_table(&peer.their_node_id.unwrap(), &msg);
906 self.message_handler.chan_handler.peer_connected(&peer.their_node_id.unwrap(), &msg);
907 peer.their_features = Some(msg.features);
909 wire::Message::Error(msg) => {
910 let mut data_is_printable = true;
911 for b in msg.data.bytes() {
912 if b < 32 || b > 126 {
913 data_is_printable = false;
918 if data_is_printable {
919 log_debug!(self.logger, "Got Err message from {}: {}", log_pubkey!(peer.their_node_id.unwrap()), msg.data);
921 log_debug!(self.logger, "Got Err message from {} with non-ASCII error message", log_pubkey!(peer.their_node_id.unwrap()));
923 self.message_handler.chan_handler.handle_error(&peer.their_node_id.unwrap(), &msg);
924 if msg.channel_id == [0; 32] {
925 return Err(PeerHandleError{ no_connection_possible: true }.into());
929 wire::Message::Ping(msg) => {
930 if msg.ponglen < 65532 {
931 let resp = msgs::Pong { byteslen: msg.ponglen };
932 self.enqueue_message(peer, &resp);
935 wire::Message::Pong(_msg) => {
936 peer.awaiting_pong = false;
940 wire::Message::OpenChannel(msg) => {
941 self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
943 wire::Message::AcceptChannel(msg) => {
944 self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), peer.their_features.clone().unwrap(), &msg);
947 wire::Message::FundingCreated(msg) => {
948 self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg);
950 wire::Message::FundingSigned(msg) => {
951 self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg);
953 wire::Message::FundingLocked(msg) => {
954 self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg);
957 wire::Message::Shutdown(msg) => {
958 self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), peer.their_features.as_ref().unwrap(), &msg);
960 wire::Message::ClosingSigned(msg) => {
961 self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg);
964 // Commitment messages:
965 wire::Message::UpdateAddHTLC(msg) => {
966 self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg);
968 wire::Message::UpdateFulfillHTLC(msg) => {
969 self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg);
971 wire::Message::UpdateFailHTLC(msg) => {
972 self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg);
974 wire::Message::UpdateFailMalformedHTLC(msg) => {
975 self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg);
978 wire::Message::CommitmentSigned(msg) => {
979 self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg);
981 wire::Message::RevokeAndACK(msg) => {
982 self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg);
984 wire::Message::UpdateFee(msg) => {
985 self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg);
987 wire::Message::ChannelReestablish(msg) => {
988 self.message_handler.chan_handler.handle_channel_reestablish(&peer.their_node_id.unwrap(), &msg);
992 wire::Message::AnnouncementSignatures(msg) => {
993 self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg);
995 wire::Message::ChannelAnnouncement(msg) => {
996 if self.message_handler.route_handler.handle_channel_announcement(&msg)
997 .map_err(|e| -> MessageHandlingError { e.into() })? {
998 should_forward = Some(wire::Message::ChannelAnnouncement(msg));
1001 wire::Message::NodeAnnouncement(msg) => {
1002 if self.message_handler.route_handler.handle_node_announcement(&msg)
1003 .map_err(|e| -> MessageHandlingError { e.into() })? {
1004 should_forward = Some(wire::Message::NodeAnnouncement(msg));
1007 wire::Message::ChannelUpdate(msg) => {
1008 self.message_handler.chan_handler.handle_channel_update(&peer.their_node_id.unwrap(), &msg);
1009 if self.message_handler.route_handler.handle_channel_update(&msg)
1010 .map_err(|e| -> MessageHandlingError { e.into() })? {
1011 should_forward = Some(wire::Message::ChannelUpdate(msg));
1014 wire::Message::QueryShortChannelIds(msg) => {
1015 self.message_handler.route_handler.handle_query_short_channel_ids(&peer.their_node_id.unwrap(), msg)?;
1017 wire::Message::ReplyShortChannelIdsEnd(msg) => {
1018 self.message_handler.route_handler.handle_reply_short_channel_ids_end(&peer.their_node_id.unwrap(), msg)?;
1020 wire::Message::QueryChannelRange(msg) => {
1021 self.message_handler.route_handler.handle_query_channel_range(&peer.their_node_id.unwrap(), msg)?;
1023 wire::Message::ReplyChannelRange(msg) => {
1024 self.message_handler.route_handler.handle_reply_channel_range(&peer.their_node_id.unwrap(), msg)?;
1026 wire::Message::GossipTimestampFilter(_msg) => {
1027 // TODO: handle message
1030 // Unknown messages:
1031 wire::Message::Unknown(msg_type) if msg_type.is_even() => {
1032 log_debug!(self.logger, "Received unknown even message of type {}, disconnecting peer!", msg_type);
1033 // Fail the channel if message is an even, unknown type as per BOLT #1.
1034 return Err(PeerHandleError{ no_connection_possible: true }.into());
1036 wire::Message::Unknown(msg_type) => {
1037 log_trace!(self.logger, "Received unknown odd message of type {}, ignoring", msg_type);
1043 fn forward_broadcast_msg(&self, peers: &mut PeerHolder<Descriptor>, msg: &wire::Message, except_node: Option<&PublicKey>) {
1045 wire::Message::ChannelAnnouncement(ref msg) => {
1046 let encoded_msg = encode_msg!(msg);
1048 for (_, peer) in peers.peers.iter_mut() {
1049 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1050 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1053 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP {
1056 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id_1) ||
1057 peer.their_node_id.as_ref() == Some(&msg.contents.node_id_2) {
1060 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1063 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1066 wire::Message::NodeAnnouncement(ref msg) => {
1067 let encoded_msg = encode_msg!(msg);
1069 for (_, peer) in peers.peers.iter_mut() {
1070 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1071 !peer.should_forward_node_announcement(msg.contents.node_id) {
1074 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP {
1077 if peer.their_node_id.as_ref() == Some(&msg.contents.node_id) {
1080 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1083 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1086 wire::Message::ChannelUpdate(ref msg) => {
1087 let encoded_msg = encode_msg!(msg);
1089 for (_, peer) in peers.peers.iter_mut() {
1090 if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
1091 !peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
1094 if peer.pending_outbound_buffer.len() > OUTBOUND_BUFFER_LIMIT_DROP_GOSSIP {
1097 if except_node.is_some() && peer.their_node_id.as_ref() == except_node {
1100 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
1103 _ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
1107 /// Checks for any events generated by our handlers and processes them. Includes sending most
1108 /// response messages as well as messages generated by calls to handler functions directly (eg
1109 /// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]).
1111 /// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1114 /// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
1115 /// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards
1116 /// [`send_data`]: SocketDescriptor::send_data
1117 pub fn process_events(&self) {
1119 // TODO: There are some DoS attacks here where you can flood someone's outbound send
1120 // buffer by doing things like announcing channels on another node. We should be willing to
1121 // drop optional-ish messages when send buffers get full!
1123 let mut peers_lock = self.peers.lock().unwrap();
1124 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_msg_events();
1125 events_generated.append(&mut self.message_handler.route_handler.get_and_clear_pending_msg_events());
1126 let peers = &mut *peers_lock;
1127 for event in events_generated.drain(..) {
1128 macro_rules! get_peer_for_forwarding {
1129 ($node_id: expr) => {
1131 match peers.node_id_to_descriptor.get($node_id) {
1132 Some(descriptor) => match peers.peers.get_mut(&descriptor) {
1134 if peer.their_features.is_none() {
1139 None => panic!("Inconsistent peers set state!"),
1149 MessageSendEvent::SendAcceptChannel { ref node_id, ref msg } => {
1150 log_trace!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
1151 log_pubkey!(node_id),
1152 log_bytes!(msg.temporary_channel_id));
1153 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1155 MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
1156 log_trace!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
1157 log_pubkey!(node_id),
1158 log_bytes!(msg.temporary_channel_id));
1159 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1161 MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
1162 log_trace!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
1163 log_pubkey!(node_id),
1164 log_bytes!(msg.temporary_channel_id),
1165 log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
1166 // TODO: If the peer is gone we should generate a DiscardFunding event
1167 // indicating to the wallet that they should just throw away this funding transaction
1168 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1170 MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
1171 log_trace!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
1172 log_pubkey!(node_id),
1173 log_bytes!(msg.channel_id));
1174 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1176 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
1177 log_trace!(self.logger, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
1178 log_pubkey!(node_id),
1179 log_bytes!(msg.channel_id));
1180 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1182 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
1183 log_trace!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
1184 log_pubkey!(node_id),
1185 log_bytes!(msg.channel_id));
1186 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1188 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 } } => {
1189 log_trace!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
1190 log_pubkey!(node_id),
1191 update_add_htlcs.len(),
1192 update_fulfill_htlcs.len(),
1193 update_fail_htlcs.len(),
1194 log_bytes!(commitment_signed.channel_id));
1195 let peer = get_peer_for_forwarding!(node_id);
1196 for msg in update_add_htlcs {
1197 self.enqueue_message(peer, msg);
1199 for msg in update_fulfill_htlcs {
1200 self.enqueue_message(peer, msg);
1202 for msg in update_fail_htlcs {
1203 self.enqueue_message(peer, msg);
1205 for msg in update_fail_malformed_htlcs {
1206 self.enqueue_message(peer, msg);
1208 if let &Some(ref msg) = update_fee {
1209 self.enqueue_message(peer, msg);
1211 self.enqueue_message(peer, commitment_signed);
1213 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
1214 log_trace!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
1215 log_pubkey!(node_id),
1216 log_bytes!(msg.channel_id));
1217 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1219 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
1220 log_trace!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
1221 log_pubkey!(node_id),
1222 log_bytes!(msg.channel_id));
1223 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1225 MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
1226 log_trace!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
1227 log_pubkey!(node_id),
1228 log_bytes!(msg.channel_id));
1229 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1231 MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
1232 log_trace!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
1233 log_pubkey!(node_id),
1234 log_bytes!(msg.channel_id));
1235 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1237 MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
1238 log_trace!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1239 if self.message_handler.route_handler.handle_channel_announcement(&msg).is_ok() && self.message_handler.route_handler.handle_channel_update(&update_msg).is_ok() {
1240 self.forward_broadcast_msg(peers, &wire::Message::ChannelAnnouncement(msg), None);
1241 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(update_msg), None);
1244 MessageSendEvent::BroadcastNodeAnnouncement { msg } => {
1245 log_trace!(self.logger, "Handling BroadcastNodeAnnouncement event in peer_handler");
1246 if self.message_handler.route_handler.handle_node_announcement(&msg).is_ok() {
1247 self.forward_broadcast_msg(peers, &wire::Message::NodeAnnouncement(msg), None);
1250 MessageSendEvent::BroadcastChannelUpdate { msg } => {
1251 log_trace!(self.logger, "Handling BroadcastChannelUpdate event in peer_handler for short channel id {}", msg.contents.short_channel_id);
1252 if self.message_handler.route_handler.handle_channel_update(&msg).is_ok() {
1253 self.forward_broadcast_msg(peers, &wire::Message::ChannelUpdate(msg), None);
1256 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
1257 self.message_handler.route_handler.handle_htlc_fail_channel_update(update);
1259 MessageSendEvent::HandleError { ref node_id, ref action } => {
1261 msgs::ErrorAction::DisconnectPeer { ref msg } => {
1262 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
1263 if let Some(mut peer) = peers.peers.remove(&descriptor) {
1264 if let Some(ref msg) = *msg {
1265 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
1266 log_pubkey!(node_id),
1268 self.enqueue_message(&mut peer, msg);
1269 // This isn't guaranteed to work, but if there is enough free
1270 // room in the send buffer, put the error message there...
1271 self.do_attempt_write_data(&mut descriptor, &mut peer);
1273 log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with no message", log_pubkey!(node_id));
1276 descriptor.disconnect_socket();
1277 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1280 msgs::ErrorAction::IgnoreError => {},
1281 msgs::ErrorAction::SendErrorMessage { ref msg } => {
1282 log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
1283 log_pubkey!(node_id),
1285 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1289 MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
1290 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1292 MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
1293 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1295 MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
1296 log_trace!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
1297 log_pubkey!(node_id),
1298 msg.short_channel_ids.len(),
1300 msg.number_of_blocks,
1302 self.enqueue_message(get_peer_for_forwarding!(node_id), msg);
1307 for (descriptor, peer) in peers.peers.iter_mut() {
1308 self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
1313 /// Indicates that the given socket descriptor's connection is now closed.
1314 pub fn socket_disconnected(&self, descriptor: &Descriptor) {
1315 self.disconnect_event_internal(descriptor, false);
1318 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
1319 let mut peers = self.peers.lock().unwrap();
1320 let peer_option = peers.peers.remove(descriptor);
1323 // This is most likely a simple race condition where the user found that the socket
1324 // was disconnected, then we told the user to `disconnect_socket()`, then they
1325 // called this method. Either way we're disconnected, return.
1328 match peer.their_node_id {
1330 peers.node_id_to_descriptor.remove(&node_id);
1331 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1339 /// Disconnect a peer given its node id.
1341 /// Set `no_connection_possible` to true to prevent any further connection with this peer,
1342 /// force-closing any channels we have with it.
1344 /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the
1345 /// peer. Thus, be very careful about reentrancy issues.
1347 /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket
1348 pub fn disconnect_by_node_id(&self, node_id: PublicKey, no_connection_possible: bool) {
1349 let mut peers_lock = self.peers.lock().unwrap();
1350 if let Some(mut descriptor) = peers_lock.node_id_to_descriptor.remove(&node_id) {
1351 log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
1352 peers_lock.peers.remove(&descriptor);
1353 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
1354 descriptor.disconnect_socket();
1358 /// This function should be called roughly once every 30 seconds.
1359 /// It will send pings to each peer and disconnect those which did not respond to the last
1362 /// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy
1365 /// [`send_data`]: SocketDescriptor::send_data
1366 pub fn timer_tick_occurred(&self) {
1367 let mut peers_lock = self.peers.lock().unwrap();
1369 let peers = &mut *peers_lock;
1370 let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
1371 let peers = &mut peers.peers;
1372 let mut descriptors_needing_disconnect = Vec::new();
1374 peers.retain(|descriptor, peer| {
1375 if peer.awaiting_pong {
1376 descriptors_needing_disconnect.push(descriptor.clone());
1377 match peer.their_node_id {
1379 log_trace!(self.logger, "Disconnecting peer with id {} due to ping timeout", node_id);
1380 node_id_to_descriptor.remove(&node_id);
1381 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
1384 // This can't actually happen as we should have hit
1385 // is_ready_for_encryption() previously on this same peer.
1392 if !peer.channel_encryptor.is_ready_for_encryption() {
1393 // The peer needs to complete its handshake before we can exchange messages
1397 let ping = msgs::Ping {
1401 self.enqueue_message(peer, &ping);
1403 let mut descriptor_clone = descriptor.clone();
1404 self.do_attempt_write_data(&mut descriptor_clone, peer);
1406 peer.awaiting_pong = true;
1410 for mut descriptor in descriptors_needing_disconnect.drain(..) {
1411 descriptor.disconnect_socket();
1419 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
1422 use util::test_utils;
1424 use bitcoin::secp256k1::Secp256k1;
1425 use bitcoin::secp256k1::key::{SecretKey, PublicKey};
1428 use std::sync::{Arc, Mutex};
1429 use core::sync::atomic::Ordering;
1432 struct FileDescriptor {
1434 outbound_data: Arc<Mutex<Vec<u8>>>,
1436 impl PartialEq for FileDescriptor {
1437 fn eq(&self, other: &Self) -> bool {
1441 impl Eq for FileDescriptor { }
1442 impl core::hash::Hash for FileDescriptor {
1443 fn hash<H: core::hash::Hasher>(&self, hasher: &mut H) {
1444 self.fd.hash(hasher)
1448 impl SocketDescriptor for FileDescriptor {
1449 fn send_data(&mut self, data: &[u8], _resume_read: bool) -> usize {
1450 self.outbound_data.lock().unwrap().extend_from_slice(data);
1454 fn disconnect_socket(&mut self) {}
1457 struct PeerManagerCfg {
1458 chan_handler: test_utils::TestChannelMessageHandler,
1459 routing_handler: test_utils::TestRoutingMessageHandler,
1460 logger: test_utils::TestLogger,
1463 fn create_peermgr_cfgs(peer_count: usize) -> Vec<PeerManagerCfg> {
1464 let mut cfgs = Vec::new();
1465 for _ in 0..peer_count {
1468 chan_handler: test_utils::TestChannelMessageHandler::new(),
1469 logger: test_utils::TestLogger::new(),
1470 routing_handler: test_utils::TestRoutingMessageHandler::new(),
1478 fn create_network<'a>(peer_count: usize, cfgs: &'a Vec<PeerManagerCfg>) -> Vec<PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger>> {
1479 let mut peers = Vec::new();
1480 for i in 0..peer_count {
1481 let node_secret = SecretKey::from_slice(&[42 + i as u8; 32]).unwrap();
1482 let ephemeral_bytes = [i as u8; 32];
1483 let msg_handler = MessageHandler { chan_handler: &cfgs[i].chan_handler, route_handler: &cfgs[i].routing_handler };
1484 let peer = PeerManager::new(msg_handler, node_secret, &ephemeral_bytes, &cfgs[i].logger);
1491 fn establish_connection<'a>(peer_a: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger>, peer_b: &PeerManager<FileDescriptor, &'a test_utils::TestChannelMessageHandler, &'a test_utils::TestRoutingMessageHandler, &'a test_utils::TestLogger>) -> (FileDescriptor, FileDescriptor) {
1492 let secp_ctx = Secp256k1::new();
1493 let a_id = PublicKey::from_secret_key(&secp_ctx, &peer_a.our_node_secret);
1494 let mut fd_a = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1495 let mut fd_b = FileDescriptor { fd: 1, outbound_data: Arc::new(Mutex::new(Vec::new())) };
1496 let initial_data = peer_b.new_outbound_connection(a_id, fd_b.clone()).unwrap();
1497 peer_a.new_inbound_connection(fd_a.clone()).unwrap();
1498 assert_eq!(peer_a.read_event(&mut fd_a, &initial_data).unwrap(), false);
1499 peer_a.process_events();
1500 assert_eq!(peer_b.read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1501 peer_b.process_events();
1502 assert_eq!(peer_a.read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap(), false);
1503 (fd_a.clone(), fd_b.clone())
1507 fn test_disconnect_peer() {
1508 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
1509 // push a DisconnectPeer event to remove the node flagged by id
1510 let cfgs = create_peermgr_cfgs(2);
1511 let chan_handler = test_utils::TestChannelMessageHandler::new();
1512 let mut peers = create_network(2, &cfgs);
1513 establish_connection(&peers[0], &peers[1]);
1514 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1516 let secp_ctx = Secp256k1::new();
1517 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret);
1519 chan_handler.pending_events.lock().unwrap().push(events::MessageSendEvent::HandleError {
1521 action: msgs::ErrorAction::DisconnectPeer { msg: None },
1523 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
1524 peers[0].message_handler.chan_handler = &chan_handler;
1526 peers[0].process_events();
1527 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1531 fn test_timer_tick_occurred() {
1532 // Create peers, a vector of two peer managers, perform initial set up and check that peers[0] has one Peer.
1533 let cfgs = create_peermgr_cfgs(2);
1534 let peers = create_network(2, &cfgs);
1535 establish_connection(&peers[0], &peers[1]);
1536 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1538 // peers[0] awaiting_pong is set to true, but the Peer is still connected
1539 peers[0].timer_tick_occurred();
1540 peers[0].process_events();
1541 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
1543 // Since timer_tick_occurred() is called again when awaiting_pong is true, all Peers are disconnected
1544 peers[0].timer_tick_occurred();
1545 peers[0].process_events();
1546 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);
1550 fn test_do_attempt_write_data() {
1551 // Create 2 peers with custom TestRoutingMessageHandlers and connect them.
1552 let cfgs = create_peermgr_cfgs(2);
1553 cfgs[0].routing_handler.request_full_sync.store(true, Ordering::Release);
1554 cfgs[1].routing_handler.request_full_sync.store(true, Ordering::Release);
1555 let peers = create_network(2, &cfgs);
1557 // By calling establish_connect, we trigger do_attempt_write_data between
1558 // the peers. Previously this function would mistakenly enter an infinite loop
1559 // when there were more channel messages available than could fit into a peer's
1560 // buffer. This issue would now be detected by this test (because we use custom
1561 // RoutingMessageHandlers that intentionally return more channel messages
1562 // than can fit into a peer's buffer).
1563 let (mut fd_a, mut fd_b) = establish_connection(&peers[0], &peers[1]);
1565 // Make each peer to read the messages that the other peer just wrote to them.
1566 peers[0].process_events();
1567 peers[1].read_event(&mut fd_b, &fd_a.outbound_data.lock().unwrap().split_off(0)).unwrap();
1568 peers[1].process_events();
1569 peers[0].read_event(&mut fd_a, &fd_b.outbound_data.lock().unwrap().split_off(0)).unwrap();
1571 // Check that each peer has received the expected number of channel updates and channel
1573 assert_eq!(cfgs[0].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1574 assert_eq!(cfgs[0].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);
1575 assert_eq!(cfgs[1].routing_handler.chan_upds_recvd.load(Ordering::Acquire), 100);
1576 assert_eq!(cfgs[1].routing_handler.chan_anns_recvd.load(Ordering::Acquire), 50);