Skip to content

Commit

Permalink
Merge pull request #1777 from ExchangeUnion/p2p/socket-error
Browse files Browse the repository at this point in the history
fix(p2p): handle multiple socket errors
  • Loading branch information
Karl Ranna authored Aug 4, 2020
2 parents 87687a5 + 79134fe commit b219b26
Showing 1 changed file with 25 additions and 14 deletions.
39 changes: 25 additions & 14 deletions lib/p2p/Peer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ class Peer extends EventEmitter {
this.status = PeerStatus.Closed;

if (this.socket) {
this.socket.removeAllListeners();
if (!this.socket.destroyed) {
if (reason !== undefined) {
this.logger.debug(`Peer ${this.label}: closing socket. reason: ${DisconnectionReason[reason]}`);
Expand Down Expand Up @@ -400,19 +401,29 @@ class Peer extends EventEmitter {

public sendPacket = async (packet: Packet): Promise<void> => {
const data = await this.framer.frame(packet, this.outEncryptionKey);
if (this.socket && !this.socket.destroyed) {
try {
this.socket.write(data);
this.logger.trace(`Sent ${PacketType[packet.type]} packet to ${this.label}: ${JSON.stringify(packet)}`);

if (packet.direction === PacketDirection.Request) {
this.addResponseTimeout(packet.header.id, packet.responseType, Peer.RESPONSE_TIMEOUT);
try {
await new Promise((resolve, reject) => {
if (this.socket && !this.socket.destroyed) {
this.socket.write(data, (err) => {
if (err) {
this.logger.trace(`could not send ${PacketType[packet.type]} packet to ${this.label}: ${JSON.stringify(packet)}`);
reject(err);
} else {
this.logger.trace(`Sent ${PacketType[packet.type]} packet to ${this.label}: ${JSON.stringify(packet)}`);

if (packet.direction === PacketDirection.Request) {
this.addResponseTimeout(packet.header.id, packet.responseType, Peer.RESPONSE_TIMEOUT);
}
resolve();
}
});
} else {
this.logger.warn(`could not send packet to ${this.label} because socket is nonexistent or destroyed`);
resolve();
}
} catch (err) {
this.logger.error(`failed sending data to ${this.label}`, err);
}
} else {
this.logger.trace(`could not send ${PacketType[packet.type]} packet to ${this.label}: ${JSON.stringify(packet)}`);
});
} catch (err) {
this.logger.error(`failed sending data to ${this.label}`, err);
}
}

Expand Down Expand Up @@ -724,11 +735,11 @@ class Peer extends EventEmitter {
private bindSocket = () => {
assert(this.socket);

this.socket.once('error', (err) => {
this.socket.on('error', (err) => {
this.logger.error(`Peer (${this.label}) error`, err);
});

this.socket.once('close', async (hadError) => {
this.socket.on('close', async (hadError) => {
// emitted once the socket is fully closed
if (this.nodePubKey === undefined) {
this.logger.info(`Socket closed prior to handshake with ${this.label}`);
Expand Down

0 comments on commit b219b26

Please sign in to comment.