1 use secp256k1::key::{SecretKey,PublicKey};
4 use ln::msgs::{MsgEncodable,MsgDecodable};
5 use ln::peer_channel_encryptor::{PeerChannelEncryptor,NextNoiseStep};
7 use util::events::{EventsProvider,Event};
9 use std::collections::{HashMap,LinkedList};
10 use std::sync::{Arc, Mutex};
11 use std::sync::atomic::{AtomicUsize, Ordering};
12 use std::{cmp,error,mem,hash,fmt};
14 pub struct MessageHandler {
15 pub chan_handler: Arc<msgs::ChannelMessageHandler>,
16 pub route_handler: Arc<msgs::RoutingMessageHandler>,
19 /// Provides an object which can be used to send data to and which uniquely identifies a connection
20 /// to a remote host. You will need to be able to generate multiple of these which meet Eq and
21 /// implement Hash to meet the PeerManager API.
22 /// For efficiency, Clone should be relatively cheap for this type.
23 /// You probably want to just extend an int and put a file descriptor in a struct and implement
24 /// send_data. Note that if you are using a higher-level net library that may close() itself, be
25 /// careful to ensure you don't have races whereby you might register a new connection with an fd
26 /// the same as a yet-to-be-disconnect_event()-ed.
27 pub trait SocketDescriptor : cmp::Eq + hash::Hash + Clone {
28 /// Attempts to send some data from the given Vec starting at the given offset to the peer.
29 /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected.
30 /// Note that in the disconnected case, a disconnect_event must still fire and further write
31 /// attempts may occur until that time.
32 /// If the returned size is smaller than data.len() - write_offset, a write_available event must
33 /// trigger the next time more data can be written. Additionally, until the a send_data event
34 /// completes fully, no further read_events should trigger on the same peer!
35 /// If a read_event on this descriptor had previously returned true (indicating that read
36 /// events should be paused to prevent DoS in the send buffer), resume_read may be set
37 /// indicating that read events on this descriptor should resume. A resume_read of false does
38 /// *not* imply that further read events should be paused.
39 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, resume_read: bool) -> usize;
42 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
43 /// generate no further read/write_events for the descriptor, only triggering a single
44 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
45 /// no such disconnect_event must be generated and the socket be silently disconencted).
46 pub struct PeerHandleError {
47 no_connection_possible: bool,
49 impl fmt::Debug for PeerHandleError {
50 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
51 formatter.write_str("Peer Sent Invalid Data")
54 impl fmt::Display for PeerHandleError {
55 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
56 formatter.write_str("Peer Sent Invalid Data")
59 impl error::Error for PeerHandleError {
60 fn description(&self) -> &str {
61 "Peer Sent Invalid Data"
66 channel_encryptor: PeerChannelEncryptor,
68 their_node_id: Option<PublicKey>,
69 their_global_features: Option<msgs::GlobalFeatures>,
70 their_local_features: Option<msgs::LocalFeatures>,
72 pending_outbound_buffer: LinkedList<Vec<u8>>,
73 pending_outbound_buffer_first_msg_offset: usize,
74 awaiting_write_event: bool,
76 pending_read_buffer: Vec<u8>,
77 pending_read_buffer_pos: usize,
78 pending_read_is_header: bool,
81 struct PeerHolder<Descriptor: SocketDescriptor> {
82 peers: HashMap<Descriptor, Peer>,
83 /// Only add to this set when noise completes:
84 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
87 pub struct PeerManager<Descriptor: SocketDescriptor> {
88 message_handler: MessageHandler,
89 peers: Mutex<PeerHolder<Descriptor>>,
90 pending_events: Mutex<Vec<Event>>,
91 our_node_secret: SecretKey,
92 initial_syncs_sent: AtomicUsize,
96 macro_rules! encode_msg {
97 ($msg: expr, $msg_code: expr) => {
99 let just_msg = $msg.encode();
100 let mut encoded_msg = Vec::with_capacity(just_msg.len() + 2);
101 encoded_msg.extend_from_slice(&byte_utils::be16_to_array($msg_code));
102 encoded_msg.extend_from_slice(&just_msg[..]);
108 //TODO: Really should do something smarter for this
109 const INITIAL_SYNCS_TO_SEND: usize = 5;
111 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
112 /// PeerIds may repeat, but only after disconnect_event() has been called.
113 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
114 pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey) -> PeerManager<Descriptor> {
116 message_handler: message_handler,
117 peers: Mutex::new(PeerHolder { peers: HashMap::new(), node_id_to_descriptor: HashMap::new() }),
118 pending_events: Mutex::new(Vec::new()),
119 our_node_secret: our_node_secret,
120 initial_syncs_sent: AtomicUsize::new(0),
124 /// Indicates a new outbound connection has been established to a node with the given node_id.
125 /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
126 /// descriptor but must disconnect the connection immediately.
127 /// Returns some bytes to send to the remote node.
128 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
129 /// disconnect_event.
130 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
131 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone());
132 let res = peer_encryptor.get_act_one().to_vec();
133 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
135 let mut peers = self.peers.lock().unwrap();
136 if peers.peers.insert(descriptor, Peer {
137 channel_encryptor: peer_encryptor,
139 their_node_id: Some(their_node_id),
140 their_global_features: None,
141 their_local_features: None,
143 pending_outbound_buffer: LinkedList::new(),
144 pending_outbound_buffer_first_msg_offset: 0,
145 awaiting_write_event: false,
147 pending_read_buffer: pending_read_buffer,
148 pending_read_buffer_pos: 0,
149 pending_read_is_header: false,
151 panic!("PeerManager driver duplicated descriptors!");
156 /// Indicates a new inbound connection has been established.
157 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
158 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
159 /// call disconnect_event for the new descriptor but must disconnect the connection
161 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
162 /// disconnect_event.
163 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
164 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
165 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
167 let mut peers = self.peers.lock().unwrap();
168 if peers.peers.insert(descriptor, Peer {
169 channel_encryptor: peer_encryptor,
172 their_global_features: None,
173 their_local_features: None,
175 pending_outbound_buffer: LinkedList::new(),
176 pending_outbound_buffer_first_msg_offset: 0,
177 awaiting_write_event: false,
179 pending_read_buffer: pending_read_buffer,
180 pending_read_buffer_pos: 0,
181 pending_read_is_header: false,
183 panic!("PeerManager driver duplicated descriptors!");
188 fn do_attempt_write_data(descriptor: &mut Descriptor, peer: &mut Peer) {
189 while !peer.awaiting_write_event {
191 let next_buff = match peer.pending_outbound_buffer.front() {
195 let should_be_reading = peer.pending_outbound_buffer.len() < 10;
197 let data_sent = descriptor.send_data(next_buff, peer.pending_outbound_buffer_first_msg_offset, should_be_reading);
198 peer.pending_outbound_buffer_first_msg_offset += data_sent;
199 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
201 peer.pending_outbound_buffer_first_msg_offset = 0;
202 peer.pending_outbound_buffer.pop_front();
204 peer.awaiting_write_event = true;
209 /// Indicates that there is room to write data to the given socket descriptor.
210 /// May return an Err to indicate that the connection should be closed.
211 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
212 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
213 /// invariants around calling write_event in case a write did not fully complete must still
214 /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
215 /// Panics if the descriptor was not previously registered in a new_*_connection event.
216 pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
217 let mut peers = self.peers.lock().unwrap();
218 match peers.peers.get_mut(descriptor) {
219 None => panic!("Descriptor for write_event is not already known to PeerManager"),
221 peer.awaiting_write_event = false;
222 Self::do_attempt_write_data(descriptor, peer);
228 /// Indicates that data was read from the given socket descriptor.
229 /// May return an Err to indicate that the connection should be closed.
230 /// Will very likely call send_data on the descriptor passed in (or a descriptor handed into
231 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
232 /// invariants around calling write_event in case a write did not fully complete must still
233 /// hold. Note that this function will often call send_data on many peers before returning, not
235 /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
236 /// this file descriptor has resume_read set (preventing DoS issues in the send buffer). Note
237 /// that this must be true even if a send_data call with resume_read=true was made during the
238 /// course of this function!
239 /// Panics if the descriptor was not previously registered in a new_*_connection event.
240 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
241 match self.do_read_event(peer_descriptor, data) {
244 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
250 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
252 let mut peers = self.peers.lock().unwrap();
253 let (should_insert_node_id, pause_read) = match peers.peers.get_mut(peer_descriptor) {
254 None => panic!("Descriptor for read_event is not already known to PeerManager"),
256 assert!(peer.pending_read_buffer.len() > 0);
257 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
259 let mut insert_node_id = None;
260 let mut read_pos = 0;
261 while read_pos < data.len() {
263 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
264 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]);
265 read_pos += data_to_copy;
266 peer.pending_read_buffer_pos += data_to_copy;
269 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
270 peer.pending_read_buffer_pos = 0;
272 macro_rules! encode_and_send_msg {
273 ($msg: expr, $msg_code: expr) => {
274 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
278 macro_rules! try_potential_handleerror {
283 println!("Got error handling message: {}!", e.err);
284 if let Some(action) = e.msg {
286 msgs::ErrorAction::UpdateFailHTLC { msg } => {
287 encode_and_send_msg!(msg, 131);
290 msgs::ErrorAction::DisconnectPeer => {
291 return Err(PeerHandleError{ no_connection_possible: false });
293 msgs::ErrorAction::IgnoreError => {
298 return Err(PeerHandleError{ no_connection_possible: false });
305 macro_rules! try_potential_decodeerror {
310 println!("Error decoding message");
312 return Err(PeerHandleError{ no_connection_possible: false });
318 macro_rules! try_ignore_potential_decodeerror {
323 println!("Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
330 let next_step = peer.channel_encryptor.get_noise_step();
332 NextNoiseStep::ActOne => {
333 let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_key(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
334 peer.pending_outbound_buffer.push_back(act_two);
335 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
337 NextNoiseStep::ActTwo => {
338 let act_three = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
339 peer.pending_outbound_buffer.push_back(act_three);
340 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
341 peer.pending_read_is_header = true;
343 insert_node_id = Some(peer.their_node_id.unwrap());
344 let mut local_features = msgs::LocalFeatures::new();
345 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
346 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
347 local_features.set_initial_routing_sync();
349 encode_and_send_msg!(msgs::Init {
350 global_features: msgs::GlobalFeatures::new(),
354 NextNoiseStep::ActThree => {
355 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
356 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
357 peer.pending_read_is_header = true;
358 peer.their_node_id = Some(their_node_id);
359 insert_node_id = Some(peer.their_node_id.unwrap());
361 NextNoiseStep::NoiseComplete => {
362 if peer.pending_read_is_header {
363 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
364 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
365 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
366 if msg_len < 2 { // Need at least the message type tag
367 return Err(PeerHandleError{ no_connection_possible: false });
369 peer.pending_read_is_header = false;
371 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
372 assert!(msg_data.len() >= 2);
375 peer.pending_read_buffer = [0; 18].to_vec();
376 peer.pending_read_is_header = true;
378 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
379 if msg_type != 16 && peer.their_global_features.is_none() {
380 // Need an init message as first message
381 return Err(PeerHandleError{ no_connection_possible: false });
384 // Connection control:
386 let msg = try_potential_decodeerror!(msgs::Init::decode(&msg_data[2..]));
387 if msg.global_features.requires_unknown_bits() {
388 return Err(PeerHandleError{ no_connection_possible: true });
390 if msg.local_features.requires_unknown_bits() {
391 return Err(PeerHandleError{ no_connection_possible: true });
393 peer.their_global_features = Some(msg.global_features);
394 peer.their_local_features = Some(msg.local_features);
397 let mut local_features = msgs::LocalFeatures::new();
398 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
399 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
400 local_features.set_initial_routing_sync();
402 encode_and_send_msg!(msgs::Init {
403 global_features: msgs::GlobalFeatures::new(),
413 let msg = try_potential_decodeerror!(msgs::Ping::decode(&msg_data[2..]));
414 if msg.ponglen < 65532 {
415 let resp = msgs::Pong { byteslen: msg.ponglen };
416 encode_and_send_msg!(resp, 19);
420 try_potential_decodeerror!(msgs::Pong::decode(&msg_data[2..]));
425 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
426 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
427 encode_and_send_msg!(resp, 33);
430 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
431 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
435 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
436 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
437 encode_and_send_msg!(resp, 35);
440 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
441 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
444 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
445 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
447 Some(resp) => encode_and_send_msg!(resp, 259),
453 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
454 let resp_options = try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
455 if let Some(resp) = resp_options.0 {
456 encode_and_send_msg!(resp, 38);
458 if let Some(resp) = resp_options.1 {
459 encode_and_send_msg!(resp, 39);
463 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
464 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
465 if let Some(resp) = resp_option {
466 encode_and_send_msg!(resp, 39);
471 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
472 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
475 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
476 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
479 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
480 let chan_update = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
481 if let Some(update) = chan_update {
482 self.message_handler.route_handler.handle_htlc_fail_channel_update(&update);
486 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
487 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
491 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
492 let resps = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
493 encode_and_send_msg!(resps.0, 133);
494 if let Some(resp) = resps.1 {
495 encode_and_send_msg!(resp, 132);
499 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
500 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
503 for resp in resps.update_add_htlcs {
504 encode_and_send_msg!(resp, 128);
506 for resp in resps.update_fulfill_htlcs {
507 encode_and_send_msg!(resp, 130);
509 for resp in resps.update_fail_htlcs {
510 encode_and_send_msg!(resp, 131);
512 encode_and_send_msg!(resps.commitment_signed, 132);
518 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
519 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
521 136 => { }, // TODO: channel_reestablish
525 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
526 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
529 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
530 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
533 // TODO: forward msg along to all our other peers!
537 let msg = try_ignore_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
538 try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
541 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
542 try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
545 if (msg_type & 1) == 0 {
546 return Err(PeerHandleError{ no_connection_possible: true });
556 Self::do_attempt_write_data(peer_descriptor, peer);
558 (insert_node_id /* should_insert_node_id */, peer.pending_outbound_buffer.len() > 10) // pause_read
562 match should_insert_node_id {
563 Some(node_id) => { peers.node_id_to_descriptor.insert(node_id, peer_descriptor.clone()); },
570 self.process_events();
575 /// Checks for any events generated by our handlers and processes them. May be needed after eg
576 /// calls to ChannelManager::process_pending_htlc_forward.
577 pub fn process_events(&self) {
578 let mut upstream_events = Vec::new();
580 // TODO: There are some DoS attacks here where you can flood someone's outbound send
581 // buffer by doing things like announcing channels on another node. We should be willing to
582 // drop optional-ish messages when send buffers get full!
584 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
585 let mut peers = self.peers.lock().unwrap();
586 for event in events_generated.drain(..) {
587 macro_rules! get_peer_for_forwarding {
588 ($node_id: expr, $handle_no_such_peer: block) => {
590 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
591 Some(descriptor) => descriptor.clone(),
593 $handle_no_such_peer;
597 match peers.peers.get_mut(&descriptor) {
601 None => panic!("Inconsistent peers set state!"),
607 Event::FundingGenerationReady {..} => { /* Hand upstream */ },
608 Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
609 Event::PaymentReceived {..} => { /* Hand upstream */ },
610 Event::PaymentSent {..} => { /* Hand upstream */ },
611 Event::PaymentFailed {..} => { /* Hand upstream */ },
613 Event::PendingHTLCsForwardable {..} => {
614 //TODO: Handle upstream in some confused form so that upstream just knows
615 //to call us somehow?
617 Event::SendOpenChannel { ref node_id, ref msg } => {
618 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
619 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
621 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 32)));
622 Self::do_attempt_write_data(&mut descriptor, peer);
625 Event::SendFundingCreated { ref node_id, ref msg } => {
626 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
627 //TODO: generate a DiscardFunding event indicating to the wallet that
628 //they should just throw away this funding transaction
630 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
631 Self::do_attempt_write_data(&mut descriptor, peer);
634 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
635 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
636 //TODO: Do whatever we're gonna do for handling dropped messages
638 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
639 match announcement_sigs {
640 &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
643 Self::do_attempt_write_data(&mut descriptor, peer);
646 Event::SendHTLCs { ref node_id, ref msgs, ref commitment_msg } => {
647 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
648 //TODO: Do whatever we're gonna do for handling dropped messages
651 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 128)));
653 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
654 Self::do_attempt_write_data(&mut descriptor, peer);
657 Event::SendFulfillHTLC { ref node_id, ref msg, ref commitment_msg } => {
658 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
659 //TODO: Do whatever we're gonna do for handling dropped messages
661 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
662 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
663 Self::do_attempt_write_data(&mut descriptor, peer);
666 Event::SendFailHTLC { ref node_id, ref msg, ref commitment_msg } => {
667 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
668 //TODO: Do whatever we're gonna do for handling dropped messages
670 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
671 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
672 Self::do_attempt_write_data(&mut descriptor, peer);
675 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
676 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
677 let encoded_msg = encode_msg!(msg, 256);
678 let encoded_update_msg = encode_msg!(update_msg, 258);
680 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
681 if !peer.channel_encryptor.is_ready_for_encryption() {
684 match peer.their_node_id {
686 Some(their_node_id) => {
687 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
692 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
693 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
694 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
699 Event::BroadcastChannelUpdate { ref msg } => {
700 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
701 let encoded_msg = encode_msg!(msg, 258);
703 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
704 if !peer.channel_encryptor.is_ready_for_encryption() {
707 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
708 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
715 upstream_events.push(event);
719 let mut pending_events = self.pending_events.lock().unwrap();
720 for event in upstream_events.drain(..) {
721 pending_events.push(event);
725 /// Indicates that the given socket descriptor's connection is now closed.
726 /// This must be called even if a PeerHandleError was given for a read_event or write_event,
727 /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
728 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
729 pub fn disconnect_event(&self, descriptor: &Descriptor) {
730 self.disconnect_event_internal(descriptor, false);
733 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
734 let mut peers = self.peers.lock().unwrap();
735 let peer_option = peers.peers.remove(descriptor);
737 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
739 match peer.their_node_id {
741 peers.node_id_to_descriptor.remove(&node_id);
742 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
751 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
752 fn get_and_clear_pending_events(&self) -> Vec<Event> {
753 let mut pending_events = self.pending_events.lock().unwrap();
754 let mut ret = Vec::new();
755 mem::swap(&mut ret, &mut *pending_events);