All files / src/peer outbound.ts

98.28% Statements 57/58
94.74% Branches 18/19
92.86% Functions 13/14
98.28% Lines 57/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216                            41x 41x   41x             41x                                   41x                                       41x       3308x 3308x       5x 1x   5x 5x       5x 3x   5x             5153x 5153x 5150x         12491x 3284x     12491x       5230x 1x     5230x       3285x     3285x       3285x                               3285x   3285x   3285x         3290x 1434x     3290x 2032x 2032x   155x   155x     1877x 1877x   2x     1877x     3290x 1252x     3290x     3284x     3284x               3290x   3290x               3290x 3290x                 5151x 5151x 5151x 5151x     5151x 5151x 5151x      
/*
 * Copyright © 2019 Lisk Foundation
 *
 * See the LICENSE file at the top-level directory of this distribution
 * for licensing information.
 *
 * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
 * no part of this software, including this file, may be copied, modified,
 * propagated, or distributed except according to the terms contained in the
 * LICENSE file.
 *
 * Removal or modification of this copyright notice is prohibited.
 *
 */
import * as querystring from 'querystring';
import * as socketClusterClient from 'socketcluster-client';
 
import {
	ConnectionKind,
	DEFAULT_ACK_TIMEOUT,
	DEFAULT_CONNECT_TIMEOUT,
	DEFAULT_HTTP_PATH,
	INTENTIONAL_DISCONNECT_CODE,
} from '../constants';
import {
	EVENT_CLOSE_OUTBOUND,
	EVENT_CONNECT_ABORT_OUTBOUND,
	EVENT_CONNECT_OUTBOUND,
	EVENT_FAILED_TO_COLLECT_PEER_DETAILS_ON_CONNECT,
	EVENT_OUTBOUND_SOCKET_ERROR,
	REMOTE_EVENT_PING,
	REMOTE_EVENT_PONG,
	REMOTE_SC_EVENT_MESSAGE,
	REMOTE_SC_EVENT_RPC_REQUEST,
} from '../events';
import {
	P2PMessagePacket,
	P2PPeerInfo,
	P2PRequestPacket,
	P2PResponsePacket,
} from '../p2p_types';
 
import {
	Peer,
	PeerConfig,
	SCClientSocket,
	socketErrorStatusCodes,
} from './base';
 
interface ClientOptionsUpdated {
	readonly hostname: string;
	readonly path: string;
	readonly port: number;
	readonly query: string;
	readonly autoConnect: boolean;
	readonly autoReconnect: boolean;
	readonly multiplex: boolean;
	readonly ackTimeout?: number;
	readonly connectTimeout?: number;
	readonly maxPayload?: number;
}
 
export class OutboundPeer extends Peer {
	protected _socket: SCClientSocket | undefined;
 
	public constructor(peerInfo: P2PPeerInfo, peerConfig: PeerConfig) {
		super(peerInfo, peerConfig);
		this._peerInfo.internalState.connectionKind = ConnectionKind.OUTBOUND;
	}
 
	public set socket(scClientSocket: SCClientSocket) {
		if (this._socket) {
			this._unbindHandlersFromOutboundSocket(this._socket);
		}
		this._socket = scClientSocket;
		this._bindHandlersToOutboundSocket(this._socket);
	}
 
	public connect(): void {
		if (!this._socket) {
			this._socket = this._createOutboundSocket();
		}
		this._socket.connect();
	}
 
	public disconnect(
		code: number = INTENTIONAL_DISCONNECT_CODE,
		reason?: string,
	): void {
		super.disconnect(code, reason);
		if (this._socket) {
			this._unbindHandlersFromOutboundSocket(this._socket);
		}
	}
 
	public send(packet: P2PMessagePacket): void {
		if (!this._socket) {
			this._socket = this._createOutboundSocket();
		}
 
		super.send(packet);
	}
 
	public async request(packet: P2PRequestPacket): Promise<P2PResponsePacket> {
		if (!this._socket) {
			this._socket = this._createOutboundSocket();
		}
 
		return super.request(packet);
	}
 
	private _createOutboundSocket(): SCClientSocket {
		const connectTimeout = this._peerConfig.connectTimeout
			? this._peerConfig.connectTimeout
			: DEFAULT_CONNECT_TIMEOUT;
		const ackTimeout = this._peerConfig.ackTimeout
			? this._peerConfig.ackTimeout
			: DEFAULT_ACK_TIMEOUT;
		// Ideally, we should JSON-serialize the whole NodeInfo object but this cannot be done for compatibility reasons, so instead we put it inside an options property.
		const clientOptions: ClientOptionsUpdated = {
			hostname: this.ipAddress,
			path: DEFAULT_HTTP_PATH,
			port: this.wsPort,
			query: querystring.stringify({
				...this._serverNodeInfo,
				options: JSON.stringify(this._serverNodeInfo),
			}),
			connectTimeout,
			ackTimeout,
			multiplex: false,
			autoConnect: false,
			autoReconnect: false,
			maxPayload: this._peerConfig.wsMaxPayload,
		};
 
		const outboundSocket = socketClusterClient.create(clientOptions);
 
		this._bindHandlersToOutboundSocket(outboundSocket);
 
		return outboundSocket;
	}
 
	// All event handlers for the outbound socket should be bound in this method.
	private _bindHandlersToOutboundSocket(outboundSocket: SCClientSocket): void {
		outboundSocket.on('error', (error: Error) => {
			this.emit(EVENT_OUTBOUND_SOCKET_ERROR, error);
		});
 
		outboundSocket.on('connect', async () => {
			try {
				await this.fetchAndUpdateStatus();
			} catch (error) {
				this.emit(EVENT_FAILED_TO_COLLECT_PEER_DETAILS_ON_CONNECT, error);
 
				return;
			}
 
			try {
				await this.discoverPeers();
			} catch (error) {
				this.emit(EVENT_FAILED_TO_COLLECT_PEER_DETAILS_ON_CONNECT, error);
			}
 
			this.emit(EVENT_CONNECT_OUTBOUND, this._peerInfo);
		});
 
		outboundSocket.on('connectAbort', () => {
			this.emit(EVENT_CONNECT_ABORT_OUTBOUND, this._peerInfo);
		});
 
		outboundSocket.on(
			'close',
			(code: number, reasonMessage: string | undefined) => {
				const reason = reasonMessage
					? reasonMessage
					: socketErrorStatusCodes[code] || 'Unknown reason';
				this.emit(EVENT_CLOSE_OUTBOUND, {
					peerInfo: this._peerInfo,
					code,
					reason,
				});
			},
		);
 
		outboundSocket.on('message', this._handleWSMessage);
 
		outboundSocket.on(
			REMOTE_EVENT_PING,
			(_: undefined, res: (_: undefined, data: string) => void) => {
				res(undefined, REMOTE_EVENT_PONG);
			},
		);
 
		// Bind RPC and remote event handlers
		outboundSocket.on(REMOTE_SC_EVENT_RPC_REQUEST, this._handleRawRPC);
		outboundSocket.on(REMOTE_SC_EVENT_MESSAGE, this._handleRawMessage);
	}
 
	// All event handlers for the outbound socket should be unbound in this method.
	private _unbindHandlersFromOutboundSocket(
		outboundSocket: SCClientSocket,
	): void {
		// Do not unbind the error handler because error could still throw after disconnect.
		// We don't want to have uncaught errors.
		outboundSocket.off('connect');
		outboundSocket.off('connectAbort');
		outboundSocket.off('close');
		outboundSocket.off('message', this._handleWSMessage);
 
		// Unbind RPC and remote event handlers
		outboundSocket.off(REMOTE_SC_EVENT_RPC_REQUEST, this._handleRawRPC);
		outboundSocket.off(REMOTE_SC_EVENT_MESSAGE, this._handleRawMessage);
		outboundSocket.off(REMOTE_EVENT_PING);
	}
}