use prelude::*;
use alloc::collections::LinkedList;
-use std::collections::{HashMap,hash_map,HashSet};
+use std::collections::{HashMap,hash_map};
use std::sync::{Arc, Mutex};
use core::sync::atomic::{AtomicUsize, Ordering};
use core::{cmp, hash, fmt, mem};
struct PeerHolder<Descriptor: SocketDescriptor> {
peers: HashMap<Descriptor, Peer>,
- /// Added to by do_read_event for cases where we pushed a message onto the send buffer but
- /// didn't call do_attempt_write_data to avoid reentrancy. Cleared in process_events()
- peers_needing_send: HashSet<Descriptor>,
/// Only add to this set when noise completes:
node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
}
message_handler,
peers: Mutex::new(PeerHolder {
peers: HashMap::new(),
- peers_needing_send: HashSet::new(),
node_id_to_descriptor: HashMap::new()
}),
our_node_secret,
}
/// Append a message to a peer's pending outbound/write buffer, and update the map of peers needing sends accordingly.
- fn enqueue_message<M: Encode + Writeable>(&self, peers_needing_send: &mut HashSet<Descriptor>, peer: &mut Peer, descriptor: Descriptor, message: &M) {
+ fn enqueue_message<M: Encode + Writeable>(&self, peer: &mut Peer, message: &M) {
let mut buffer = VecWriter(Vec::new());
wire::write(message, &mut buffer).unwrap(); // crash if the write failed
let encoded_message = buffer.0;
log_trace!(self.logger, "Enqueueing message of type {} to {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_message[..]));
- peers_needing_send.insert(descriptor);
}
fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: &[u8]) -> Result<bool, PeerHandleError> {
},
msgs::ErrorAction::SendErrorMessage { msg } => {
log_trace!(self.logger, "Got Err handling message, sending Error message because {}", e.err);
- self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &msg);
+ self.enqueue_message(peer, &msg);
continue;
},
}
insert_node_id!();
let features = InitFeatures::known();
let resp = msgs::Init { features };
- self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &resp);
+ self.enqueue_message(peer, &resp);
},
NextNoiseStep::ActThree => {
let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
insert_node_id!();
let features = InitFeatures::known();
let resp = msgs::Init { features };
- self.enqueue_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), &resp);
+ self.enqueue_message(peer, &resp);
},
NextNoiseStep::NoiseComplete => {
if peer.pending_read_is_header {
}
};
- match self.handle_message(&mut peers.peers_needing_send, peer, peer_descriptor.clone(), message) {
+ match self.handle_message(peer, message) {
Err(handling_error) => match handling_error {
MessageHandlingError::PeerHandleError(e) => { return Err(e) },
MessageHandlingError::LightningError(e) => {
/// Process an incoming message and return a decision (ok, lightning error, peer handling error) regarding the next action with the peer
/// Returns the message back if it needs to be broadcasted to all other peers.
- fn handle_message(&self, peers_needing_send: &mut HashSet<Descriptor>, peer: &mut Peer, peer_descriptor: Descriptor, message: wire::Message) -> Result<Option<wire::Message>, MessageHandlingError> {
+ fn handle_message(&self, peer: &mut Peer, message: wire::Message) -> Result<Option<wire::Message>, MessageHandlingError> {
log_trace!(self.logger, "Received message of type {} from {}", message.type_id(), log_pubkey!(peer.their_node_id.unwrap()));
// Need an Init as first message
if msg.features.initial_routing_sync() {
peer.sync_status = InitSyncTracker::ChannelsSyncing(0);
- peers_needing_send.insert(peer_descriptor.clone());
}
if !msg.features.supports_static_remote_key() {
log_debug!(self.logger, "Peer {} does not support static remote key, disconnecting with no_connection_possible", log_pubkey!(peer.their_node_id.unwrap()));
wire::Message::Ping(msg) => {
if msg.ponglen < 65532 {
let resp = msgs::Pong { byteslen: msg.ponglen };
- self.enqueue_message(peers_needing_send, peer, peer_descriptor.clone(), &resp);
+ self.enqueue_message(peer, &resp);
}
},
wire::Message::Pong(_msg) => {
wire::Message::ChannelAnnouncement(ref msg) => {
let encoded_msg = encode_msg!(msg);
- for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
+ for (_, ref mut peer) in peers.peers.iter_mut() {
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
!peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
continue
continue;
}
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
- peers.peers_needing_send.insert((*descriptor).clone());
}
},
wire::Message::NodeAnnouncement(ref msg) => {
let encoded_msg = encode_msg!(msg);
- for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
+ for (_, ref mut peer) in peers.peers.iter_mut() {
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
!peer.should_forward_node_announcement(msg.contents.node_id) {
continue
continue;
}
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
- peers.peers_needing_send.insert((*descriptor).clone());
}
},
wire::Message::ChannelUpdate(ref msg) => {
let encoded_msg = encode_msg!(msg);
- for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
+ for (_, ref mut peer) in peers.peers.iter_mut() {
if !peer.channel_encryptor.is_ready_for_encryption() || peer.their_features.is_none() ||
!peer.should_forward_channel_announcement(msg.contents.short_channel_id) {
continue
continue;
}
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
- peers.peers_needing_send.insert((*descriptor).clone());
}
},
_ => debug_assert!(false, "We shouldn't attempt to forward anything but gossip messages"),
log_trace!(self.logger, "Handling SendAcceptChannel event in peer_handler for node {} for channel {}",
log_pubkey!(node_id),
log_bytes!(msg.temporary_channel_id));
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::SendOpenChannel { ref node_id, ref msg } => {
log_trace!(self.logger, "Handling SendOpenChannel event in peer_handler for node {} for channel {}",
log_pubkey!(node_id),
log_bytes!(msg.temporary_channel_id));
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::SendFundingCreated { ref node_id, ref msg } => {
log_trace!(self.logger, "Handling SendFundingCreated event in peer_handler for node {} for channel {} (which becomes {})",
log_funding_channel_id!(msg.funding_txid, msg.funding_output_index));
// TODO: If the peer is gone we should generate a DiscardFunding event
// indicating to the wallet that they should just throw away this funding transaction
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::SendFundingSigned { ref node_id, ref msg } => {
log_trace!(self.logger, "Handling SendFundingSigned event in peer_handler for node {} for channel {}",
log_bytes!(msg.channel_id));
// TODO: If the peer is gone we should generate a DiscardFunding event
// indicating to the wallet that they should just throw away this funding transaction
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
log_trace!(self.logger, "Handling SendFundingLocked event in peer_handler for node {} for channel {}",
log_pubkey!(node_id),
log_bytes!(msg.channel_id));
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
log_trace!(self.logger, "Handling SendAnnouncementSignatures event in peer_handler for node {} for channel {})",
log_pubkey!(node_id),
log_bytes!(msg.channel_id));
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
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 } } => {
log_trace!(self.logger, "Handling UpdateHTLCs event in peer_handler for node {} with {} adds, {} fulfills, {} fails for channel {}",
update_fulfill_htlcs.len(),
update_fail_htlcs.len(),
log_bytes!(commitment_signed.channel_id));
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
for msg in update_add_htlcs {
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
}
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
}
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_signed)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
log_trace!(self.logger, "Handling SendRevokeAndACK event in peer_handler for node {} for channel {}",
log_pubkey!(node_id),
log_bytes!(msg.channel_id));
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
log_trace!(self.logger, "Handling SendClosingSigned event in peer_handler for node {} for channel {}",
log_pubkey!(node_id),
log_bytes!(msg.channel_id));
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::SendShutdown { ref node_id, ref msg } => {
log_trace!(self.logger, "Handling Shutdown event in peer_handler for node {} for channel {}",
log_pubkey!(node_id),
log_bytes!(msg.channel_id));
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } => {
log_trace!(self.logger, "Handling SendChannelReestablish event in peer_handler for node {} for channel {}",
log_pubkey!(node_id),
log_bytes!(msg.channel_id));
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::BroadcastChannelAnnouncement { msg, update_msg } => {
log_trace!(self.logger, "Handling BroadcastChannelAnnouncement event in peer_handler for short channel id {}", msg.contents.short_channel_id);
match *action {
msgs::ErrorAction::DisconnectPeer { ref msg } => {
if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
- peers.peers_needing_send.remove(&descriptor);
if let Some(mut peer) = peers.peers.remove(&descriptor) {
if let Some(ref msg) = *msg {
log_trace!(self.logger, "Handling DisconnectPeer HandleError event in peer_handler for node {} with message {}",
log_trace!(self.logger, "Handling SendErrorMessage HandleError event in peer_handler for node {} with message {}",
log_pubkey!(node_id),
msg.data);
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
}
},
MessageSendEvent::SendChannelRangeQuery { ref node_id, ref msg } => {
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
},
MessageSendEvent::SendShortIdsQuery { ref node_id, ref msg } => {
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
}
MessageSendEvent::SendReplyChannelRange { ref node_id, ref msg } => {
log_trace!(self.logger, "Handling SendReplyChannelRange event in peer_handler for node {} with num_scids={} first_blocknum={} number_of_blocks={}, sync_complete={}",
msg.first_blocknum,
msg.number_of_blocks,
msg.sync_complete);
- let (mut descriptor, peer) = get_peer_for_forwarding!(node_id);
+ let (_, peer) = get_peer_for_forwarding!(node_id);
peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg)));
- self.do_attempt_write_data(&mut descriptor, peer);
}
}
}
- for mut descriptor in peers.peers_needing_send.drain() {
- match peers.peers.get_mut(&descriptor) {
- Some(peer) => self.do_attempt_write_data(&mut descriptor, peer),
- None => panic!("Inconsistent peers set state!"),
- }
+ for (descriptor, ref mut peer) in peers.peers.iter_mut() {
+ self.do_attempt_write_data(&mut (*descriptor).clone(), peer);
}
}
}
fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
let mut peers = self.peers.lock().unwrap();
- peers.peers_needing_send.remove(descriptor);
let peer_option = peers.peers.remove(descriptor);
match peer_option {
None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
if let Some(mut descriptor) = peers_lock.node_id_to_descriptor.remove(&node_id) {
log_trace!(self.logger, "Disconnecting peer with id {} due to client request", node_id);
peers_lock.peers.remove(&descriptor);
- peers_lock.peers_needing_send.remove(&descriptor);
self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
descriptor.disconnect_socket();
}
let mut peers_lock = self.peers.lock().unwrap();
{
let peers = &mut *peers_lock;
- let peers_needing_send = &mut peers.peers_needing_send;
let node_id_to_descriptor = &mut peers.node_id_to_descriptor;
let peers = &mut peers.peers;
let mut descriptors_needing_disconnect = Vec::new();
peers.retain(|descriptor, peer| {
if peer.awaiting_pong {
- peers_needing_send.remove(descriptor);
descriptors_needing_disconnect.push(descriptor.clone());
match peer.their_node_id {
Some(node_id) => {