All files / src/peer base.ts

91.45% Statements 139/152
88.52% Branches 54/61
97.44% Functions 38/39
91.39% Lines 138/151

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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569                            41x 41x     41x                 41x         41x                                   41x                 41x                   41x           41x                   41x 41x 41x 41x                                       41x                                 1715x 1715x 1715x     1715x 1715x 796x   1715x 8x   1715x     1715x           882x 882x                     882x       77x   77x       805x 805x       805x                     805x     1715x 3732x       1715x     812x 812x                   812x 812x 812x           812x 812x     812x         5633x       10680x       3652x       5644x       528x           528x                     11721x       1715x                   1224x                   410x 1x               2262x 2262x 2262x 2202x         1591x 1x     1590x             909x         909x 1x   908x             904x 67x   67x     837x 837x   837x                               491x 491x       433x           3200x         60x       2x     60x   60x               489x 433x 3206x     433x           426x 426x       13x   13x         413x 413x   2x     2x       2x           411x     411x       10x 10x 5x         796x       796x   796x         2x           2x   2x         796x   91x     91x 1x     91x       796x   796x   72x   72x       796x   796x         8x       8x       1225x         1225x                 1225x   1225x 2x         1223x         812x 812x                     812x       5x 5x       882x 882x 882x         805x   805x       812x 812x 812x       812x   812x      
/*
 * 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 { EventEmitter } from 'events';
import * as socketClusterClient from 'socketcluster-client';
import { SCServerSocket } from 'socketcluster-server';
 
import {
	DEFAULT_PRODUCTIVITY,
	DEFAULT_PRODUCTIVITY_RESET_INTERVAL,
	FORBIDDEN_CONNECTION,
	FORBIDDEN_CONNECTION_REASON,
	INTENTIONAL_DISCONNECT_CODE,
	INVALID_PEER_INFO_PENALTY,
	INVALID_PEER_LIST_PENALTY,
} from '../constants';
import {
	InvalidPeerInfoError,
	InvalidPeerInfoListError,
	RPCResponseError,
} from '../errors';
import {
	EVENT_BAN_PEER,
	EVENT_DISCOVERED_PEER,
	EVENT_FAILED_PEER_INFO_UPDATE,
	EVENT_FAILED_TO_FETCH_PEER_INFO,
	EVENT_FAILED_TO_FETCH_PEERS,
	EVENT_INVALID_MESSAGE_RECEIVED,
	EVENT_INVALID_REQUEST_RECEIVED,
	EVENT_MESSAGE_RECEIVED,
	EVENT_REQUEST_RECEIVED,
	EVENT_UPDATED_PEER_INFO,
	PROTOCOL_EVENTS_TO_RATE_LIMIT,
	REMOTE_EVENT_POST_NODE_INFO,
	REMOTE_EVENT_RPC_GET_NODE_INFO,
	REMOTE_EVENT_RPC_GET_PEERS_LIST,
	REMOTE_SC_EVENT_MESSAGE,
	REMOTE_SC_EVENT_RPC_REQUEST,
} from '../events';
import { P2PRequest } from '../p2p_request';
import {
	P2PInternalState,
	P2PMessagePacket,
	P2PNodeInfo,
	P2PPeerInfo,
	P2PRequestPacket,
	P2PResponsePacket,
} from '../p2p_types';
import {
	assignInternalInfo,
	sanitizeIncomingPeerInfo,
	validatePeerCompatibility,
	validatePeerInfo,
	validatePeerInfoList,
	validateProtocolMessage,
	validateRPCRequest,
} from '../utils';
 
export const socketErrorStatusCodes = {
	...(socketClusterClient.SCClientSocket as any).errorStatuses,
	1000: 'Intentionally disconnected',
};
 
// Can be used to convert a rate which is based on the rateCalculationInterval into a per-second rate.
const RATE_NORMALIZATION_FACTOR = 1000;
 
export type SCClientSocket = socketClusterClient.SCClientSocket;
 
export type SCServerSocketUpdated = {
	destroy(code?: number, data?: string | object): void;
	on(event: string | unknown, listener: (packet?: unknown) => void): void;
	on(event: string, listener: (packet: any, respond: any) => void): void;
} & SCServerSocket;
 
export enum ConnectionState {
	CONNECTING = 'connecting',
	OPEN = 'open',
	CLOSED = 'closed',
}
// tslint:disable:readonly-keyword
export interface ConnectedPeerInfo extends P2PPeerInfo {
	internalState: P2PInternalState;
}
// tslint:enable:readonly-keyword
export interface PeerConfig {
	readonly connectTimeout?: number;
	readonly ackTimeout?: number;
	readonly rateCalculationInterval: number;
	readonly wsMaxMessageRate: number;
	readonly wsMaxMessageRatePenalty: number;
	readonly wsMaxPayload?: number;
	readonly maxPeerInfoSize: number;
	readonly maxPeerDiscoveryResponseLength: number;
	readonly secret: number;
	readonly serverNodeInfo?: P2PNodeInfo;
}
 
export class Peer extends EventEmitter {
	private readonly _counterResetInterval: NodeJS.Timer;
	protected _peerInfo: ConnectedPeerInfo;
	private readonly _productivityResetInterval: NodeJS.Timer;
	protected readonly _peerConfig: PeerConfig;
	protected _serverNodeInfo: P2PNodeInfo | undefined;
	protected _rateInterval: number;
 
	protected readonly _handleRawRPC: (
		packet: unknown,
		respond: (responseError?: Error, responseData?: unknown) => void,
	) => void;
	protected readonly _handleWSMessage: (message: string) => void;
	protected readonly _handleRawMessage: (packet: unknown) => void;
	protected _socket: SCServerSocketUpdated | SCClientSocket | undefined;
 
	public constructor(peerInfo: P2PPeerInfo, peerConfig: PeerConfig) {
		super();
		this._peerConfig = peerConfig;
		this._peerInfo = this._initializeInternalState(
			peerInfo,
		) as ConnectedPeerInfo;
		this._rateInterval = this._peerConfig.rateCalculationInterval;
		this._counterResetInterval = setInterval(() => {
			this._resetCounters();
		}, this._rateInterval);
		this._productivityResetInterval = setInterval(() => {
			this._resetProductivity();
		}, DEFAULT_PRODUCTIVITY_RESET_INTERVAL);
		this._serverNodeInfo = peerConfig.serverNodeInfo;
 
		// This needs to be an arrow function so that it can be used as a listener.
		this._handleRawRPC = (
			packet: unknown,
			respond: (responseError?: Error, responseData?: unknown) => void,
		): void => {
			// tslint:disable-next-line:no-let
			let rawRequest;
			try {
				rawRequest = validateRPCRequest(packet);
			} catch (error) {
				respond(error);
				this.emit(EVENT_INVALID_REQUEST_RECEIVED, {
					packet,
					peerId: this._peerInfo.peerId,
				});
 
				return;
			}
 
			if (
				PROTOCOL_EVENTS_TO_RATE_LIMIT.has(rawRequest.procedure) &&
				this._peerInfo.internalState.rpcCounter.has(rawRequest.procedure)
			) {
				this._updateRPCCounter(rawRequest);
 
				return;
			}
 
			// Protocol RCP request limiter LIP-0004
			this._updateRPCCounter(rawRequest);
			const rate = this._getRPCRate(rawRequest);
 
			// Each P2PRequest contributes to the Peer's productivity.
			// A P2PRequest can mutate this._productivity from the current Peer instance.
			const request = new P2PRequest(
				{
					procedure: rawRequest.procedure,
					data: rawRequest.data,
					id: this.peerInfo.peerId,
					rate,
					productivity: this.internalState.productivity,
				},
				respond,
			);
 
			this.emit(EVENT_REQUEST_RECEIVED, request);
		};
 
		this._handleWSMessage = () => {
			this._peerInfo.internalState.wsMessageCount += 1;
		};
 
		// This needs to be an arrow function so that it can be used as a listener.
		this._handleRawMessage = (packet: unknown) => {
			// tslint:disable-next-line:no-let
			let message;
			try {
				message = validateProtocolMessage(packet);
			} catch (error) {
				this.emit(EVENT_INVALID_MESSAGE_RECEIVED, {
					packet,
					peerId: this._peerInfo.peerId,
				});
 
				return;
			}
 
			this._updateMessageCounter(message);
			const rate = this._getMessageRate(message);
			const messageWithRateInfo = {
				...message,
				peerId: this._peerInfo.peerId,
				rate,
			};
 
			Eif (message.event === REMOTE_EVENT_POST_NODE_INFO) {
				this._handleUpdatePeerInfo(message);
			}
 
			this.emit(EVENT_MESSAGE_RECEIVED, messageWithRateInfo);
		};
	}
 
	public get id(): string {
		return this._peerInfo.peerId;
	}
 
	public get ipAddress(): string {
		return this._peerInfo.ipAddress;
	}
 
	public get wsPort(): number {
		return this._peerInfo.wsPort;
	}
 
	public get internalState(): P2PInternalState {
		return this.peerInfo.internalState;
	}
 
	public get state(): ConnectionState {
		const state = this._socket
			? this._socket.state === this._socket.OPEN
				? ConnectionState.OPEN
				: ConnectionState.CLOSED
			: ConnectionState.CLOSED;
 
		return state;
	}
 
	public updateInternalState(internalState: P2PInternalState): void {
		this._peerInfo = {
			...this._peerInfo,
			internalState,
		};
	}
 
	public get peerInfo(): ConnectedPeerInfo {
		return this._peerInfo;
	}
 
	private _initializeInternalState(peerInfo: P2PPeerInfo): P2PPeerInfo {
		return peerInfo.internalState
			? peerInfo
			: {
					...peerInfo,
					internalState: assignInternalInfo(peerInfo, this._peerConfig.secret),
			  };
	}
 
	public updatePeerInfo(newPeerInfo: P2PPeerInfo): void {
		// The ipAddress and wsPort properties cannot be updated after the initial discovery.
		this._peerInfo = {
			sharedState: newPeerInfo.sharedState,
			internalState: this._peerInfo.internalState,
			ipAddress: this.ipAddress,
			wsPort: this.wsPort,
			peerId: this.id,
		};
	}
 
	public connect(): void {
		if (!this._socket) {
			throw new Error('Peer socket does not exist');
		}
	}
 
	public disconnect(
		code: number = INTENTIONAL_DISCONNECT_CODE,
		reason?: string,
	): void {
		clearInterval(this._counterResetInterval);
		clearInterval(this._productivityResetInterval);
		if (this._socket) {
			this._socket.destroy(code, reason);
		}
	}
 
	public send(packet: P2PMessagePacket): void {
		if (!this._socket) {
			throw new Error('Peer socket does not exist');
		}
 
		this._socket.emit(REMOTE_SC_EVENT_MESSAGE, {
			event: packet.event,
			data: packet.data,
		});
	}
 
	public async request(packet: P2PRequestPacket): Promise<P2PResponsePacket> {
		return new Promise<P2PResponsePacket>(
			(
				resolve: (result: P2PResponsePacket) => void,
				reject: (result: Error) => void,
			): void => {
				if (!this._socket) {
					throw new Error('Peer socket does not exist');
				}
				this._socket.emit(
					REMOTE_SC_EVENT_RPC_REQUEST,
					{
						procedure: packet.procedure,
						data: packet.data,
					},
					(error: Error | undefined, responseData: unknown) => {
						if (error) {
							reject(error);
 
							return;
						}
 
						Eif (responseData) {
							resolve(responseData as P2PResponsePacket);
 
							return;
						}
 
						reject(
							new RPCResponseError(
								`Failed to handle response for procedure ${packet.procedure}`,
								`${this.ipAddress}:${this.wsPort}`,
							),
						);
					},
				);
			},
		);
	}
 
	public async fetchPeers(): Promise<ReadonlyArray<P2PPeerInfo>> {
		try {
			const response: P2PResponsePacket = await this.request({
				procedure: REMOTE_EVENT_RPC_GET_PEERS_LIST,
			});
 
			const validatedPeers = validatePeerInfoList(
				response.data,
				this._peerConfig.maxPeerDiscoveryResponseLength,
				this._peerConfig.maxPeerInfoSize,
			);
 
			return validatedPeers.map(peerInfo => ({
				...peerInfo,
				sourceAddress: this.ipAddress,
			}));
		} catch (error) {
			if (
				error instanceof InvalidPeerInfoError ||
				error instanceof InvalidPeerInfoListError
			) {
				this.applyPenalty(INVALID_PEER_LIST_PENALTY);
			}
 
			this.emit(EVENT_FAILED_TO_FETCH_PEERS, error);
 
			throw new RPCResponseError(
				'Failed to fetch peer list of peer',
				this.ipAddress,
			);
		}
	}
 
	public async discoverPeers(): Promise<ReadonlyArray<P2PPeerInfo>> {
		const discoveredPeerInfoList = await this.fetchPeers();
		discoveredPeerInfoList.forEach(peerInfo => {
			this.emit(EVENT_DISCOVERED_PEER, peerInfo);
		});
 
		return discoveredPeerInfoList;
	}
 
	public async fetchAndUpdateStatus(): Promise<P2PPeerInfo> {
		// tslint:disable-next-line:no-let
		let response: P2PResponsePacket;
		try {
			response = await this.request({
				procedure: REMOTE_EVENT_RPC_GET_NODE_INFO,
			});
		} catch (error) {
			this.emit(EVENT_FAILED_TO_FETCH_PEER_INFO, error);
 
			throw new RPCResponseError(
				'Failed to fetch peer info of peer',
				`${this.ipAddress}:${this.wsPort}`,
			);
		}
		try {
			this._updateFromProtocolPeerInfo(response.data);
		} catch (error) {
			this.emit(EVENT_FAILED_PEER_INFO_UPDATE, error);
 
			// Apply penalty for malformed PeerInfo
			Iif (error instanceof InvalidPeerInfoError) {
				this.applyPenalty(INVALID_PEER_INFO_PENALTY);
			}
 
			throw new RPCResponseError(
				'Failed to update peer info of peer due to validation of peer compatibility',
				`${this.ipAddress}:${this.wsPort}`,
			);
		}
 
		this.emit(EVENT_UPDATED_PEER_INFO, this._peerInfo);
 
		// Return the updated detailed peer info.
		return this._peerInfo;
	}
 
	public applyPenalty(penalty: number): void {
		this.peerInfo.internalState.reputation -= penalty;
		if (this.internalState.reputation <= 0) {
			this._banPeer();
		}
	}
 
	private _resetCounters(): void {
		this._peerInfo.internalState.wsMessageRate =
			(this.peerInfo.internalState.wsMessageCount * RATE_NORMALIZATION_FACTOR) /
			this._rateInterval;
 
		this._peerInfo.internalState.wsMessageCount = 0;
 
		if (
			this.peerInfo.internalState.wsMessageRate >
			this._peerConfig.wsMaxMessageRate
		) {
			// Allow to increase penalty based on message rate limit exceeded
			const messageRateExceedCoefficient = Math.floor(
				this.peerInfo.internalState.wsMessageRate /
					this._peerConfig.wsMaxMessageRate,
			);
 
			const penaltyRateMultiplier =
				messageRateExceedCoefficient > 1 ? messageRateExceedCoefficient : 1;
 
			this.applyPenalty(
				this._peerConfig.wsMaxMessageRatePenalty * penaltyRateMultiplier,
			);
		}
 
		this._peerInfo.internalState.rpcRates = new Map(
			[...this.internalState.rpcCounter.entries()].map(([key, value]) => {
				const rate = value / this._rateInterval;
 
				// Protocol RCP request limiter LIP-0004
				if (PROTOCOL_EVENTS_TO_RATE_LIMIT.has(key) && value > 1) {
					this.applyPenalty(this._peerConfig.wsMaxMessageRatePenalty);
				}
 
				return [key, rate] as any;
			}),
		);
 
		this._peerInfo.internalState.rpcCounter = new Map();
 
		this._peerInfo.internalState.messageRates = new Map(
			[...this.internalState.messageCounter.entries()].map(([key, value]) => {
				const rate = value / this._rateInterval;
 
				return [key, rate] as any;
			}),
		);
 
		this._peerInfo.internalState.messageCounter = new Map();
 
		return;
	}
 
	private _resetProductivity(): void {
		// If peer has not recently responded, reset productivity to 0
		Eif (
			this.peerInfo.internalState.productivity.lastResponded <
			Date.now() - DEFAULT_PRODUCTIVITY_RESET_INTERVAL
		) {
			this._peerInfo.internalState.productivity = { ...DEFAULT_PRODUCTIVITY };
		}
	}
	private _updateFromProtocolPeerInfo(rawPeerInfo: unknown): void {
		Iif (!this._serverNodeInfo) {
			throw new Error('Missing server node info.');
		}
 
		// Sanitize and validate PeerInfo
		const peerInfo = validatePeerInfo(
			sanitizeIncomingPeerInfo({
				...(rawPeerInfo as object),
				ipAddress: this.ipAddress,
				wsPort: this.wsPort,
			}),
			this._peerConfig.maxPeerInfoSize,
		);
 
		const result = validatePeerCompatibility(peerInfo, this._serverNodeInfo);
 
		if (!result.success && result.error) {
			throw new Error(
				`${result.error} : ${peerInfo.ipAddress}:${peerInfo.wsPort}`,
			);
		}
 
		this.updatePeerInfo(peerInfo);
	}
 
	private _handleUpdatePeerInfo(message: P2PMessagePacket): void {
		// Update peerInfo with the latest values from the remote peer.
		try {
			this._updateFromProtocolPeerInfo(message.data);
		} catch (error) {
			// Apply penalty for malformed PeerInfo update
			if (error instanceof InvalidPeerInfoError) {
				this.applyPenalty(INVALID_PEER_INFO_PENALTY);
			}
 
			this.emit(EVENT_FAILED_PEER_INFO_UPDATE, error);
 
			return;
		}
		this.emit(EVENT_UPDATED_PEER_INFO, this.peerInfo);
	}
 
	private _banPeer(): void {
		this.emit(EVENT_BAN_PEER, this.id);
		this.disconnect(FORBIDDEN_CONNECTION, FORBIDDEN_CONNECTION_REASON);
	}
 
	private _updateRPCCounter(packet: P2PRequestPacket): void {
		const key = packet.procedure;
		const count = (this.internalState.rpcCounter.get(key) || 0) + 1;
		this.peerInfo.internalState.rpcCounter.set(key, count);
	}
 
	private _getRPCRate(packet: P2PRequestPacket): number {
		const rate =
			this.peerInfo.internalState.rpcRates.get(packet.procedure) || 0;
 
		return rate * RATE_NORMALIZATION_FACTOR;
	}
 
	private _updateMessageCounter(packet: P2PMessagePacket): void {
		const key = packet.event;
		const count = (this.internalState.messageCounter.get(key) || 0) + 1;
		this.peerInfo.internalState.messageCounter.set(key, count);
	}
 
	private _getMessageRate(packet: P2PMessagePacket): number {
		const rate = this.internalState.messageRates.get(packet.event) || 0;
 
		return rate * RATE_NORMALIZATION_FACTOR;
	}
}