All files / src/utils misc.ts

97.78% Statements 88/90
97.37% Branches 37/38
100% Functions 13/13
97.78% Lines 88/90

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                            43x 43x       43x 43x   43x 43x 43x                   43x 1929270x 1x     1929269x       43x 307468x 307468x 307468x 307468x 307468x 307468x 307468x 307468x   307468x               43x 43x 43x 43x 43x     43x 43x 43x     43x 173146x       43x 179170x     43x 179169x 6024x     173145x 1335x     171810x 171808x     2x     43x 22695x 22695x 22695x 22695x 22695x     22695x     22695x 1x     22694x             22694x     43x 6574x   43x 5877x   43x     13956x 13956x 13956x 13956x 13956x   13956x     43x       12355x 395266x       395266x             12355x       43x                         156471x 156471x 156471x 156471x 156471x 156471x 156471x               156471x     156471x 1x       156470x 4866x           151604x                 151604x     151604x     151604x                             151604x         151604x                               151604x    
/*
 * 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 { hash } from '@liskhq/lisk-cryptography';
import { isIPv4 } from 'net';
 
import { P2PEnhancedPeerInfo } from '../p2p_types';
 
const BYTES_4 = 4;
const BYTES_16 = 16;
 
export const SECRET_BUFFER_LENGTH = 4;
export const NETWORK_BUFFER_LENGTH = 1;
const PREFIX_BUFFER_LENGTH = 1;
 
interface AddressBytes {
	readonly aBytes: Buffer;
	readonly bBytes: Buffer;
	readonly cBytes: Buffer;
	readonly dBytes: Buffer;
}
 
/* tslint:disable no-magic-numbers */
export const getIPGroup = (address: string, groupNumber: number): number => {
	if (groupNumber > 3) {
		throw new Error('Invalid IP group.');
	}
 
	return parseInt(address.split('.')[groupNumber], 10);
};
 
// Each byte represents the corresponding subsection of the IP address e.g. AAA.BBB.CCC.DDD
export const getIPBytes = (address: string): AddressBytes => {
	const aBytes = Buffer.alloc(PREFIX_BUFFER_LENGTH);
	aBytes.writeUInt8(getIPGroup(address, 0), 0);
	const bBytes = Buffer.alloc(PREFIX_BUFFER_LENGTH);
	bBytes.writeUInt8(getIPGroup(address, 1), 0);
	const cBytes = Buffer.alloc(PREFIX_BUFFER_LENGTH);
	cBytes.writeUInt8(getIPGroup(address, 2), 0);
	const dBytes = Buffer.alloc(PREFIX_BUFFER_LENGTH);
	dBytes.writeUInt8(getIPGroup(address, 3), 0);
 
	return {
		aBytes,
		bBytes,
		cBytes,
		dBytes,
	};
};
 
export enum NETWORK {
	NET_IPV4 = 0,
	NET_PRIVATE,
	NET_LOCAL,
	NET_OTHER,
}
 
export enum PEER_TYPE {
	NEW_PEER = 'newPeer',
	TRIED_PEER = 'triedPeer',
}
 
export const isPrivate = (address: string) =>
	getIPGroup(address, 0) === 10 ||
	(getIPGroup(address, 0) === 172 &&
		(getIPGroup(address, 1) >= 16 || getIPGroup(address, 1) <= 31));
 
export const isLocal = (address: string) =>
	getIPGroup(address, 0) === 127 || getIPGroup(address, 0) === 0;
/* tslint:enable no-magic-numbers */
 
export const getNetwork = (address: string): NETWORK => {
	if (isLocal(address)) {
		return NETWORK.NET_LOCAL;
	}
 
	if (isPrivate(address)) {
		return NETWORK.NET_PRIVATE;
	}
 
	if (isIPv4(address)) {
		return NETWORK.NET_IPV4;
	}
 
	return NETWORK.NET_OTHER;
};
 
export const getNetgroup = (address: string, secret: number): number => {
	const secretBytes = Buffer.alloc(SECRET_BUFFER_LENGTH);
	secretBytes.writeUInt32BE(secret, 0);
	const network = getNetwork(address);
	const networkBytes = Buffer.alloc(NETWORK_BUFFER_LENGTH);
	networkBytes.writeUInt8(network, 0);
 
	// Get prefix bytes of ipAddress to bucket
	const { aBytes, bBytes } = getIPBytes(address);
 
	// Check if ipAddress is unsupported network type
	if (network === NETWORK.NET_OTHER) {
		throw Error('IP address is unsupported.');
	}
 
	const netgroupBytes = Buffer.concat([
		secretBytes,
		networkBytes,
		aBytes,
		bBytes,
	]);
 
	return hash(netgroupBytes).readUInt32BE(0);
};
 
export const constructPeerId = (ipAddress: string, wsPort: number): string =>
	`${ipAddress}:${wsPort}`;
 
export const getByteSize = (object: any): number =>
	Buffer.byteLength(JSON.stringify(object));
 
export const evictPeerRandomlyFromBucket = (
	bucket: Map<string, P2PEnhancedPeerInfo>,
): P2PEnhancedPeerInfo | undefined => {
	const bucketPeerIds = Array.from(bucket.keys());
	const randomPeerIndex = Math.floor(Math.random() * bucketPeerIds.length);
	const randomPeerId = bucketPeerIds[randomPeerIndex];
	const evictedPeer = bucket.get(randomPeerId);
	bucket.delete(randomPeerId);
 
	return evictedPeer;
};
 
export const expirePeerFromBucket = (
	bucket: Map<string, P2PEnhancedPeerInfo>,
	thresholdTime: number,
): P2PEnhancedPeerInfo | undefined => {
	for (const [peerId, peer] of bucket) {
		const timeDifference = Math.round(
			Math.abs((peer.dateAdded as Date).getTime() - new Date().getTime()),
		);
 
		Iif (timeDifference >= thresholdTime) {
			bucket.delete(peerId);
 
			return peer;
		}
	}
 
	return undefined;
};
 
// For new peer buckets, provide the source IP address from which the peer list was received
export const getBucketId = (options: {
	readonly secret: number;
	readonly peerType: PEER_TYPE;
	readonly targetAddress: string;
	readonly sourceAddress?: string;
	readonly bucketCount: number;
}): number => {
	const {
		secret,
		targetAddress,
		sourceAddress,
		peerType,
		bucketCount,
	} = options;
	const firstMod = peerType === PEER_TYPE.NEW_PEER ? BYTES_16 : BYTES_4;
	const secretBytes = Buffer.alloc(SECRET_BUFFER_LENGTH);
	secretBytes.writeUInt32BE(secret, 0);
	const network = getNetwork(targetAddress);
	const networkBytes = Buffer.alloc(NETWORK_BUFFER_LENGTH);
	networkBytes.writeUInt8(network, 0);
 
	// Get bytes of ipAddress to bucket
	const {
		aBytes: targetABytes,
		bBytes: targetBBytes,
		cBytes: targetCBytes,
		dBytes: targetDBytes,
	} = getIPBytes(targetAddress);
 
	// Check if ip address is unsupported network type
	if (network === NETWORK.NET_OTHER) {
		throw Error('IP address is unsupported.');
	}
 
	// Seperate buckets for local and private addresses
	if (network !== NETWORK.NET_IPV4) {
		return (
			hash(Buffer.concat([secretBytes, networkBytes])).readUInt32BE(0) %
			bucketCount
		);
	}
 
	const addressBytes = Buffer.concat([
		targetABytes,
		targetBBytes,
		targetCBytes,
		targetDBytes,
	]);
 
	// New peers: k = Hash(random_secret, source_group, group) % 16
	// Tried peers: k = Hash(random_secret, IP) % 4
	const kBytes = Buffer.alloc(firstMod);
 
	// Get bytes of ip address to bucket
	const sourceBytes = sourceAddress ? getIPBytes(sourceAddress) : undefined;
 
	const k =
		peerType === PEER_TYPE.NEW_PEER && sourceBytes
			? hash(
					Buffer.concat([
						secretBytes,
						networkBytes,
						sourceBytes.aBytes,
						sourceBytes.bBytes,
						targetABytes,
						targetBBytes,
					]),
			  ).readUInt32BE(0) % firstMod
			: hash(
					Buffer.concat([secretBytes, networkBytes, addressBytes]),
			  ).readUInt32BE(0) % firstMod;
 
	kBytes.writeUInt32BE(k, 0);
 
	// New peers: b = Hash(random_secret, source_group, k) % 128
	// Tried peers: b = Hash(random_secret, group, k) % 64
	const bucketBytes =
		peerType === PEER_TYPE.NEW_PEER && sourceBytes
			? Buffer.concat([
					secretBytes,
					networkBytes,
					sourceBytes.aBytes,
					sourceBytes.bBytes,
					kBytes,
			  ])
			: Buffer.concat([
					secretBytes,
					networkBytes,
					targetABytes,
					targetBBytes,
					kBytes,
			  ]);
 
	return hash(bucketBytes).readUInt32BE(0) % bucketCount;
};