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;
40 /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no
41 /// more calls to write_event, read_event or disconnect_event may be made with this descriptor.
42 /// No disconnect_event should be generated as a result of this call, though obviously races
43 /// may occur whereby disconnect_socket is called after a call to disconnect_event but prior to
44 /// that event completing.
45 fn disconnect_socket(&mut self);
48 /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and
49 /// generate no further read/write_events for the descriptor, only triggering a single
50 /// disconnect_event (unless it was provided in response to a new_*_connection event, in which case
51 /// no such disconnect_event must be generated and the socket be silently disconencted).
52 pub struct PeerHandleError {
53 no_connection_possible: bool,
55 impl fmt::Debug for PeerHandleError {
56 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
57 formatter.write_str("Peer Sent Invalid Data")
60 impl fmt::Display for PeerHandleError {
61 fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
62 formatter.write_str("Peer Sent Invalid Data")
65 impl error::Error for PeerHandleError {
66 fn description(&self) -> &str {
67 "Peer Sent Invalid Data"
72 channel_encryptor: PeerChannelEncryptor,
74 their_node_id: Option<PublicKey>,
75 their_global_features: Option<msgs::GlobalFeatures>,
76 their_local_features: Option<msgs::LocalFeatures>,
78 pending_outbound_buffer: LinkedList<Vec<u8>>,
79 pending_outbound_buffer_first_msg_offset: usize,
80 awaiting_write_event: bool,
82 pending_read_buffer: Vec<u8>,
83 pending_read_buffer_pos: usize,
84 pending_read_is_header: bool,
87 struct PeerHolder<Descriptor: SocketDescriptor> {
88 peers: HashMap<Descriptor, Peer>,
89 /// Only add to this set when noise completes:
90 node_id_to_descriptor: HashMap<PublicKey, Descriptor>,
93 pub struct PeerManager<Descriptor: SocketDescriptor> {
94 message_handler: MessageHandler,
95 peers: Mutex<PeerHolder<Descriptor>>,
96 pending_events: Mutex<Vec<Event>>,
97 our_node_secret: SecretKey,
98 initial_syncs_sent: AtomicUsize,
102 macro_rules! encode_msg {
103 ($msg: expr, $msg_code: expr) => {
105 let just_msg = $msg.encode();
106 let mut encoded_msg = Vec::with_capacity(just_msg.len() + 2);
107 encoded_msg.extend_from_slice(&byte_utils::be16_to_array($msg_code));
108 encoded_msg.extend_from_slice(&just_msg[..]);
114 //TODO: Really should do something smarter for this
115 const INITIAL_SYNCS_TO_SEND: usize = 5;
117 /// Manages and reacts to connection events. You probably want to use file descriptors as PeerIds.
118 /// PeerIds may repeat, but only after disconnect_event() has been called.
119 impl<Descriptor: SocketDescriptor> PeerManager<Descriptor> {
120 pub fn new(message_handler: MessageHandler, our_node_secret: SecretKey) -> PeerManager<Descriptor> {
122 message_handler: message_handler,
123 peers: Mutex::new(PeerHolder { peers: HashMap::new(), node_id_to_descriptor: HashMap::new() }),
124 pending_events: Mutex::new(Vec::new()),
125 our_node_secret: our_node_secret,
126 initial_syncs_sent: AtomicUsize::new(0),
130 /// Get the list of node ids for peers which have completed the initial handshake.
131 /// For outbound connections, this will be the same as the their_node_id parameter passed in to
132 /// new_outbound_connection, however entries will only appear once the initial handshake has
133 /// completed and we are sure the remote peer has the private key for the given node_id.
134 pub fn get_peer_node_ids(&self) -> Vec<PublicKey> {
135 let peers = self.peers.lock().unwrap();
136 peers.peers.values().filter_map(|p| p.their_node_id).collect()
139 /// Indicates a new outbound connection has been established to a node with the given node_id.
140 /// Note that if an Err is returned here you MUST NOT call disconnect_event for the new
141 /// descriptor but must disconnect the connection immediately.
142 /// Returns some bytes to send to the remote node.
143 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
144 /// disconnect_event.
145 pub fn new_outbound_connection(&self, their_node_id: PublicKey, descriptor: Descriptor) -> Result<Vec<u8>, PeerHandleError> {
146 let mut peer_encryptor = PeerChannelEncryptor::new_outbound(their_node_id.clone());
147 let res = peer_encryptor.get_act_one().to_vec();
148 let pending_read_buffer = [0; 50].to_vec(); // Noise act two is 50 bytes
150 let mut peers = self.peers.lock().unwrap();
151 if peers.peers.insert(descriptor, Peer {
152 channel_encryptor: peer_encryptor,
154 their_node_id: Some(their_node_id),
155 their_global_features: None,
156 their_local_features: None,
158 pending_outbound_buffer: LinkedList::new(),
159 pending_outbound_buffer_first_msg_offset: 0,
160 awaiting_write_event: false,
162 pending_read_buffer: pending_read_buffer,
163 pending_read_buffer_pos: 0,
164 pending_read_is_header: false,
166 panic!("PeerManager driver duplicated descriptors!");
171 /// Indicates a new inbound connection has been established.
172 /// May refuse the connection by returning an Err, but will never write bytes to the remote end
173 /// (outbound connector always speaks first). Note that if an Err is returned here you MUST NOT
174 /// call disconnect_event for the new descriptor but must disconnect the connection
176 /// Panics if descriptor is duplicative with some other descriptor which has not yet has a
177 /// disconnect_event.
178 pub fn new_inbound_connection(&self, descriptor: Descriptor) -> Result<(), PeerHandleError> {
179 let peer_encryptor = PeerChannelEncryptor::new_inbound(&self.our_node_secret);
180 let pending_read_buffer = [0; 50].to_vec(); // Noise act one is 50 bytes
182 let mut peers = self.peers.lock().unwrap();
183 if peers.peers.insert(descriptor, Peer {
184 channel_encryptor: peer_encryptor,
187 their_global_features: None,
188 their_local_features: None,
190 pending_outbound_buffer: LinkedList::new(),
191 pending_outbound_buffer_first_msg_offset: 0,
192 awaiting_write_event: false,
194 pending_read_buffer: pending_read_buffer,
195 pending_read_buffer_pos: 0,
196 pending_read_is_header: false,
198 panic!("PeerManager driver duplicated descriptors!");
203 fn do_attempt_write_data(descriptor: &mut Descriptor, peer: &mut Peer) {
204 while !peer.awaiting_write_event {
206 let next_buff = match peer.pending_outbound_buffer.front() {
210 let should_be_reading = peer.pending_outbound_buffer.len() < 10;
212 let data_sent = descriptor.send_data(next_buff, peer.pending_outbound_buffer_first_msg_offset, should_be_reading);
213 peer.pending_outbound_buffer_first_msg_offset += data_sent;
214 if peer.pending_outbound_buffer_first_msg_offset == next_buff.len() { true } else { false }
216 peer.pending_outbound_buffer_first_msg_offset = 0;
217 peer.pending_outbound_buffer.pop_front();
219 peer.awaiting_write_event = true;
224 /// Indicates that there is room to write data to the given socket descriptor.
225 /// May return an Err to indicate that the connection should be closed.
226 /// Will most likely call send_data on the descriptor passed in (or the descriptor handed into
227 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
228 /// invariants around calling write_event in case a write did not fully complete must still
229 /// hold - be ready to call write_event again if a write call generated here isn't sufficient!
230 /// Panics if the descriptor was not previously registered in a new_*_connection event.
231 pub fn write_event(&self, descriptor: &mut Descriptor) -> Result<(), PeerHandleError> {
232 let mut peers = self.peers.lock().unwrap();
233 match peers.peers.get_mut(descriptor) {
234 None => panic!("Descriptor for write_event is not already known to PeerManager"),
236 peer.awaiting_write_event = false;
237 Self::do_attempt_write_data(descriptor, peer);
243 /// Indicates that data was read from the given socket descriptor.
244 /// May return an Err to indicate that the connection should be closed.
245 /// Will very likely call send_data on the descriptor passed in (or a descriptor handed into
246 /// new_*_connection) before returning. Thus, be very careful with reentrancy issues! The
247 /// invariants around calling write_event in case a write did not fully complete must still
248 /// hold. Note that this function will often call send_data on many peers before returning, not
250 /// If Ok(true) is returned, further read_events should not be triggered until a write_event on
251 /// this file descriptor has resume_read set (preventing DoS issues in the send buffer). Note
252 /// that this must be true even if a send_data call with resume_read=true was made during the
253 /// course of this function!
254 /// Panics if the descriptor was not previously registered in a new_*_connection event.
255 pub fn read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
256 match self.do_read_event(peer_descriptor, data) {
259 self.disconnect_event_internal(peer_descriptor, e.no_connection_possible);
265 fn do_read_event(&self, peer_descriptor: &mut Descriptor, data: Vec<u8>) -> Result<bool, PeerHandleError> {
267 let mut peers = self.peers.lock().unwrap();
268 let (should_insert_node_id, pause_read) = match peers.peers.get_mut(peer_descriptor) {
269 None => panic!("Descriptor for read_event is not already known to PeerManager"),
271 assert!(peer.pending_read_buffer.len() > 0);
272 assert!(peer.pending_read_buffer.len() > peer.pending_read_buffer_pos);
274 let mut insert_node_id = None;
275 let mut read_pos = 0;
276 while read_pos < data.len() {
278 let data_to_copy = cmp::min(peer.pending_read_buffer.len() - peer.pending_read_buffer_pos, data.len() - read_pos);
279 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]);
280 read_pos += data_to_copy;
281 peer.pending_read_buffer_pos += data_to_copy;
284 if peer.pending_read_buffer_pos == peer.pending_read_buffer.len() {
285 peer.pending_read_buffer_pos = 0;
287 macro_rules! encode_and_send_msg {
288 ($msg: expr, $msg_code: expr) => {
289 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!($msg, $msg_code)[..]));
293 macro_rules! try_potential_handleerror {
298 println!("Got error handling message: {}!", e.err);
299 if let Some(action) = e.action {
301 msgs::ErrorAction::UpdateFailHTLC { msg } => {
302 encode_and_send_msg!(msg, 131);
305 msgs::ErrorAction::DisconnectPeer { msg: _ } => {
306 return Err(PeerHandleError{ no_connection_possible: false });
308 msgs::ErrorAction::IgnoreError => {
311 msgs::ErrorAction::SendErrorMessage { msg } => {
312 encode_and_send_msg!(msg, 17);
317 return Err(PeerHandleError{ no_connection_possible: false });
324 macro_rules! try_potential_decodeerror {
329 println!("Error decoding message");
331 return Err(PeerHandleError{ no_connection_possible: false });
337 macro_rules! try_ignore_potential_decodeerror {
342 println!("Error decoding message, ignoring due to lnd spec incompatibility. See https://github.com/lightningnetwork/lnd/issues/1407");
349 let next_step = peer.channel_encryptor.get_noise_step();
351 NextNoiseStep::ActOne => {
352 let act_two = try_potential_handleerror!(peer.channel_encryptor.process_act_one_with_key(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
353 peer.pending_outbound_buffer.push_back(act_two);
354 peer.pending_read_buffer = [0; 66].to_vec(); // act three is 66 bytes long
356 NextNoiseStep::ActTwo => {
357 let act_three = try_potential_handleerror!(peer.channel_encryptor.process_act_two(&peer.pending_read_buffer[..], &self.our_node_secret)).to_vec();
358 peer.pending_outbound_buffer.push_back(act_three);
359 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
360 peer.pending_read_is_header = true;
362 insert_node_id = Some(peer.their_node_id.unwrap());
363 let mut local_features = msgs::LocalFeatures::new();
364 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
365 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
366 local_features.set_initial_routing_sync();
368 encode_and_send_msg!(msgs::Init {
369 global_features: msgs::GlobalFeatures::new(),
373 NextNoiseStep::ActThree => {
374 let their_node_id = try_potential_handleerror!(peer.channel_encryptor.process_act_three(&peer.pending_read_buffer[..]));
375 peer.pending_read_buffer = [0; 18].to_vec(); // Message length header is 18 bytes
376 peer.pending_read_is_header = true;
377 peer.their_node_id = Some(their_node_id);
378 insert_node_id = Some(peer.their_node_id.unwrap());
380 NextNoiseStep::NoiseComplete => {
381 if peer.pending_read_is_header {
382 let msg_len = try_potential_handleerror!(peer.channel_encryptor.decrypt_length_header(&peer.pending_read_buffer[..]));
383 peer.pending_read_buffer = Vec::with_capacity(msg_len as usize + 16);
384 peer.pending_read_buffer.resize(msg_len as usize + 16, 0);
385 if msg_len < 2 { // Need at least the message type tag
386 return Err(PeerHandleError{ no_connection_possible: false });
388 peer.pending_read_is_header = false;
390 let msg_data = try_potential_handleerror!(peer.channel_encryptor.decrypt_message(&peer.pending_read_buffer[..]));
391 assert!(msg_data.len() >= 2);
394 peer.pending_read_buffer = [0; 18].to_vec();
395 peer.pending_read_is_header = true;
397 let msg_type = byte_utils::slice_to_be16(&msg_data[0..2]);
398 if msg_type != 16 && peer.their_global_features.is_none() {
399 // Need an init message as first message
400 return Err(PeerHandleError{ no_connection_possible: false });
403 // Connection control:
405 let msg = try_potential_decodeerror!(msgs::Init::decode(&msg_data[2..]));
406 if msg.global_features.requires_unknown_bits() {
407 return Err(PeerHandleError{ no_connection_possible: true });
409 if msg.local_features.requires_unknown_bits() {
410 return Err(PeerHandleError{ no_connection_possible: true });
412 peer.their_global_features = Some(msg.global_features);
413 peer.their_local_features = Some(msg.local_features);
416 let mut local_features = msgs::LocalFeatures::new();
417 if self.initial_syncs_sent.load(Ordering::Acquire) < INITIAL_SYNCS_TO_SEND {
418 self.initial_syncs_sent.fetch_add(1, Ordering::AcqRel);
419 local_features.set_initial_routing_sync();
421 encode_and_send_msg!(msgs::Init {
422 global_features: msgs::GlobalFeatures::new(),
432 let msg = try_potential_decodeerror!(msgs::Ping::decode(&msg_data[2..]));
433 if msg.ponglen < 65532 {
434 let resp = msgs::Pong { byteslen: msg.ponglen };
435 encode_and_send_msg!(resp, 19);
439 try_potential_decodeerror!(msgs::Pong::decode(&msg_data[2..]));
444 let msg = try_potential_decodeerror!(msgs::OpenChannel::decode(&msg_data[2..]));
445 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_open_channel(&peer.their_node_id.unwrap(), &msg));
446 encode_and_send_msg!(resp, 33);
449 let msg = try_potential_decodeerror!(msgs::AcceptChannel::decode(&msg_data[2..]));
450 try_potential_handleerror!(self.message_handler.chan_handler.handle_accept_channel(&peer.their_node_id.unwrap(), &msg));
454 let msg = try_potential_decodeerror!(msgs::FundingCreated::decode(&msg_data[2..]));
455 let resp = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_created(&peer.their_node_id.unwrap(), &msg));
456 encode_and_send_msg!(resp, 35);
459 let msg = try_potential_decodeerror!(msgs::FundingSigned::decode(&msg_data[2..]));
460 try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_signed(&peer.their_node_id.unwrap(), &msg));
463 let msg = try_potential_decodeerror!(msgs::FundingLocked::decode(&msg_data[2..]));
464 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_funding_locked(&peer.their_node_id.unwrap(), &msg));
466 Some(resp) => encode_and_send_msg!(resp, 259),
472 let msg = try_potential_decodeerror!(msgs::Shutdown::decode(&msg_data[2..]));
473 let resp_options = try_potential_handleerror!(self.message_handler.chan_handler.handle_shutdown(&peer.their_node_id.unwrap(), &msg));
474 if let Some(resp) = resp_options.0 {
475 encode_and_send_msg!(resp, 38);
477 if let Some(resp) = resp_options.1 {
478 encode_and_send_msg!(resp, 39);
482 let msg = try_potential_decodeerror!(msgs::ClosingSigned::decode(&msg_data[2..]));
483 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_closing_signed(&peer.their_node_id.unwrap(), &msg));
484 if let Some(resp) = resp_option {
485 encode_and_send_msg!(resp, 39);
490 let msg = try_potential_decodeerror!(msgs::UpdateAddHTLC::decode(&msg_data[2..]));
491 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_add_htlc(&peer.their_node_id.unwrap(), &msg));
494 let msg = try_potential_decodeerror!(msgs::UpdateFulfillHTLC::decode(&msg_data[2..]));
495 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fulfill_htlc(&peer.their_node_id.unwrap(), &msg));
498 let msg = try_potential_decodeerror!(msgs::UpdateFailHTLC::decode(&msg_data[2..]));
499 let chan_update = try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_htlc(&peer.their_node_id.unwrap(), &msg));
500 if let Some(update) = chan_update {
501 self.message_handler.route_handler.handle_htlc_fail_channel_update(&update);
505 let msg = try_potential_decodeerror!(msgs::UpdateFailMalformedHTLC::decode(&msg_data[2..]));
506 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fail_malformed_htlc(&peer.their_node_id.unwrap(), &msg));
510 let msg = try_potential_decodeerror!(msgs::CommitmentSigned::decode(&msg_data[2..]));
511 let resps = try_potential_handleerror!(self.message_handler.chan_handler.handle_commitment_signed(&peer.their_node_id.unwrap(), &msg));
512 encode_and_send_msg!(resps.0, 133);
513 if let Some(resp) = resps.1 {
514 encode_and_send_msg!(resp, 132);
518 let msg = try_potential_decodeerror!(msgs::RevokeAndACK::decode(&msg_data[2..]));
519 let resp_option = try_potential_handleerror!(self.message_handler.chan_handler.handle_revoke_and_ack(&peer.their_node_id.unwrap(), &msg));
522 for resp in resps.update_add_htlcs {
523 encode_and_send_msg!(resp, 128);
525 for resp in resps.update_fulfill_htlcs {
526 encode_and_send_msg!(resp, 130);
528 for resp in resps.update_fail_htlcs {
529 encode_and_send_msg!(resp, 131);
531 encode_and_send_msg!(resps.commitment_signed, 132);
537 let msg = try_potential_decodeerror!(msgs::UpdateFee::decode(&msg_data[2..]));
538 try_potential_handleerror!(self.message_handler.chan_handler.handle_update_fee(&peer.their_node_id.unwrap(), &msg));
540 136 => { }, // TODO: channel_reestablish
544 let msg = try_potential_decodeerror!(msgs::AnnouncementSignatures::decode(&msg_data[2..]));
545 try_potential_handleerror!(self.message_handler.chan_handler.handle_announcement_signatures(&peer.their_node_id.unwrap(), &msg));
548 let msg = try_potential_decodeerror!(msgs::ChannelAnnouncement::decode(&msg_data[2..]));
549 let should_forward = try_potential_handleerror!(self.message_handler.route_handler.handle_channel_announcement(&msg));
552 // TODO: forward msg along to all our other peers!
556 let msg = try_ignore_potential_decodeerror!(msgs::NodeAnnouncement::decode(&msg_data[2..]));
557 try_potential_handleerror!(self.message_handler.route_handler.handle_node_announcement(&msg));
560 let msg = try_potential_decodeerror!(msgs::ChannelUpdate::decode(&msg_data[2..]));
561 try_potential_handleerror!(self.message_handler.route_handler.handle_channel_update(&msg));
564 if (msg_type & 1) == 0 {
565 return Err(PeerHandleError{ no_connection_possible: true });
575 Self::do_attempt_write_data(peer_descriptor, peer);
577 (insert_node_id /* should_insert_node_id */, peer.pending_outbound_buffer.len() > 10) // pause_read
581 match should_insert_node_id {
582 Some(node_id) => { peers.node_id_to_descriptor.insert(node_id, peer_descriptor.clone()); },
589 self.process_events();
594 /// Checks for any events generated by our handlers and processes them. May be needed after eg
595 /// calls to ChannelManager::process_pending_htlc_forward.
596 pub fn process_events(&self) {
597 let mut upstream_events = Vec::new();
599 // TODO: There are some DoS attacks here where you can flood someone's outbound send
600 // buffer by doing things like announcing channels on another node. We should be willing to
601 // drop optional-ish messages when send buffers get full!
603 let mut events_generated = self.message_handler.chan_handler.get_and_clear_pending_events();
604 let mut peers = self.peers.lock().unwrap();
605 for event in events_generated.drain(..) {
606 macro_rules! get_peer_for_forwarding {
607 ($node_id: expr, $handle_no_such_peer: block) => {
609 let descriptor = match peers.node_id_to_descriptor.get($node_id) {
610 Some(descriptor) => descriptor.clone(),
612 $handle_no_such_peer;
616 match peers.peers.get_mut(&descriptor) {
620 None => panic!("Inconsistent peers set state!"),
626 Event::FundingGenerationReady {..} => { /* Hand upstream */ },
627 Event::FundingBroadcastSafe {..} => { /* Hand upstream */ },
628 Event::PaymentReceived {..} => { /* Hand upstream */ },
629 Event::PaymentSent {..} => { /* Hand upstream */ },
630 Event::PaymentFailed {..} => { /* Hand upstream */ },
632 Event::PendingHTLCsForwardable {..} => {
633 //TODO: Handle upstream in some confused form so that upstream just knows
634 //to call us somehow?
636 Event::SendOpenChannel { ref node_id, ref msg } => {
637 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
638 //TODO: Drop the pending channel? (or just let it timeout, but that sucks)
640 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 32)));
641 Self::do_attempt_write_data(&mut descriptor, peer);
644 Event::SendFundingCreated { ref node_id, ref msg } => {
645 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
646 //TODO: generate a DiscardFunding event indicating to the wallet that
647 //they should just throw away this funding transaction
649 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 34)));
650 Self::do_attempt_write_data(&mut descriptor, peer);
653 Event::SendFundingLocked { ref node_id, ref msg, ref announcement_sigs } => {
654 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
655 //TODO: Do whatever we're gonna do for handling dropped messages
657 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 36)));
658 match announcement_sigs {
659 &Some(ref announce_msg) => peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(announce_msg, 259))),
662 Self::do_attempt_write_data(&mut descriptor, peer);
665 Event::SendHTLCs { ref node_id, ref msgs, ref commitment_msg } => {
666 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
667 //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, 128)));
672 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
673 Self::do_attempt_write_data(&mut descriptor, peer);
676 Event::SendFulfillHTLC { ref node_id, ref msg, ref commitment_msg } => {
677 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
678 //TODO: Do whatever we're gonna do for handling dropped messages
680 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 130)));
681 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
682 Self::do_attempt_write_data(&mut descriptor, peer);
685 Event::SendFailHTLC { ref node_id, ref msg, ref commitment_msg } => {
686 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
687 //TODO: Do whatever we're gonna do for handling dropped messages
689 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 131)));
690 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(commitment_msg, 132)));
691 Self::do_attempt_write_data(&mut descriptor, peer);
694 Event::SendShutdown { ref node_id, ref msg } => {
695 let (mut descriptor, peer) = get_peer_for_forwarding!(node_id, {
696 //TODO: Do whatever we're gonna do for handling dropped messages
698 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 38)));
699 Self::do_attempt_write_data(&mut descriptor, peer);
702 Event::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
703 if self.message_handler.route_handler.handle_channel_announcement(msg).is_ok() && self.message_handler.route_handler.handle_channel_update(update_msg).is_ok() {
704 let encoded_msg = encode_msg!(msg, 256);
705 let encoded_update_msg = encode_msg!(update_msg, 258);
707 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
708 if !peer.channel_encryptor.is_ready_for_encryption() {
711 match peer.their_node_id {
713 Some(their_node_id) => {
714 if their_node_id == msg.contents.node_id_1 || their_node_id == msg.contents.node_id_2 {
719 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
720 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_update_msg[..]));
721 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
726 Event::BroadcastChannelUpdate { ref msg } => {
727 if self.message_handler.route_handler.handle_channel_update(msg).is_ok() {
728 let encoded_msg = encode_msg!(msg, 258);
730 for (ref descriptor, ref mut peer) in peers.peers.iter_mut() {
731 if !peer.channel_encryptor.is_ready_for_encryption() {
734 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encoded_msg[..]));
735 Self::do_attempt_write_data(&mut (*descriptor).clone(), peer);
740 Event::DisconnectPeer { ref node_id, ref msg } => {
741 if let Some(mut descriptor) = peers.node_id_to_descriptor.remove(node_id) {
742 if let Some(mut peer) = peers.peers.remove(&descriptor) {
743 if let Some(ref msg) = *msg {
744 peer.pending_outbound_buffer.push_back(peer.channel_encryptor.encrypt_message(&encode_msg!(msg, 17)));
745 // This isn't guaranteed to work, but if there is enough free
746 // room in the send buffer, put the error message there...
747 Self::do_attempt_write_data(&mut descriptor, &mut peer);
750 descriptor.disconnect_socket();
751 self.message_handler.chan_handler.peer_disconnected(&node_id, false);
756 upstream_events.push(event);
760 let mut pending_events = self.pending_events.lock().unwrap();
761 for event in upstream_events.drain(..) {
762 pending_events.push(event);
766 /// Indicates that the given socket descriptor's connection is now closed.
767 /// This must be called even if a PeerHandleError was given for a read_event or write_event,
768 /// but must NOT be called if a PeerHandleError was provided out of a new_*_connection event!
769 /// Panics if the descriptor was not previously registered in a successful new_*_connection event.
770 pub fn disconnect_event(&self, descriptor: &Descriptor) {
771 self.disconnect_event_internal(descriptor, false);
774 fn disconnect_event_internal(&self, descriptor: &Descriptor, no_connection_possible: bool) {
775 let mut peers = self.peers.lock().unwrap();
776 let peer_option = peers.peers.remove(descriptor);
778 None => panic!("Descriptor for disconnect_event is not already known to PeerManager"),
780 match peer.their_node_id {
782 peers.node_id_to_descriptor.remove(&node_id);
783 self.message_handler.chan_handler.peer_disconnected(&node_id, no_connection_possible);
792 impl<Descriptor: SocketDescriptor> EventsProvider for PeerManager<Descriptor> {
793 fn get_and_clear_pending_events(&self) -> Vec<Event> {
794 let mut pending_events = self.pending_events.lock().unwrap();
795 let mut ret = Vec::new();
796 mem::swap(&mut ret, &mut *pending_events);
803 use ln::peer_handler::{PeerManager, MessageHandler, SocketDescriptor};
805 use util::test_utils;
807 use secp256k1::Secp256k1;
808 use secp256k1::key::{SecretKey, PublicKey};
810 use rand::{thread_rng, Rng};
812 use std::sync::{Arc};
814 #[derive(PartialEq, Eq, Clone, Hash)]
815 struct FileDescriptor {
819 impl SocketDescriptor for FileDescriptor {
820 fn send_data(&mut self, data: &Vec<u8>, write_offset: usize, _resume_read: bool) -> usize {
821 assert!(write_offset < data.len());
822 data.len() - write_offset
825 fn disconnect_socket(&mut self) {}
828 fn create_network(peer_count: usize) -> Vec<PeerManager<FileDescriptor>> {
829 let secp_ctx = Secp256k1::new();
830 let mut peers = Vec::new();
831 let mut rng = thread_rng();
833 for _ in 0..peer_count {
834 let chan_handler = test_utils::TestChannelMessageHandler::new();
835 let router = test_utils::TestRoutingMessageHandler::new();
837 let mut key_slice = [0;32];
838 rng.fill_bytes(&mut key_slice);
839 SecretKey::from_slice(&secp_ctx, &key_slice).unwrap()
841 let msg_handler = MessageHandler { chan_handler: Arc::new(chan_handler), route_handler: Arc::new(router) };
842 let peer = PeerManager::new(msg_handler, node_id);
849 fn establish_connection(peer_a: &PeerManager<FileDescriptor>, peer_b: &PeerManager<FileDescriptor>) {
850 let secp_ctx = Secp256k1::new();
851 let their_id = PublicKey::from_secret_key(&secp_ctx, &peer_b.our_node_secret).unwrap();
852 let fd = FileDescriptor { fd: 1};
853 peer_a.new_inbound_connection(fd.clone()).unwrap();
854 peer_a.peers.lock().unwrap().node_id_to_descriptor.insert(their_id, fd.clone());
858 fn test_disconnect_peer() {
859 // Simple test which builds a network of PeerManager, connects and brings them to NoiseState::Finished and
860 // push an DisconnectPeer event to remove the node flagged by id
861 let mut peers = create_network(2);
862 establish_connection(&peers[0], &peers[1]);
863 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 1);
865 let secp_ctx = Secp256k1::new();
866 let their_id = PublicKey::from_secret_key(&secp_ctx, &peers[1].our_node_secret).unwrap();
868 let chan_handler = test_utils::TestChannelMessageHandler::new();
869 chan_handler.pending_events.lock().unwrap().push(events::Event::DisconnectPeer {
873 assert_eq!(chan_handler.pending_events.lock().unwrap().len(), 1);
874 peers[0].message_handler.chan_handler = Arc::new(chan_handler);
876 peers[0].process_events();
877 assert_eq!(peers[0].peers.lock().unwrap().peers.len(), 0);