All files validation.ts

90.77% Statements 118/130
88.33% Branches 53/60
88.24% Functions 30/34
91.27% Lines 115/126

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                            2x 2x             2x   2x           2x 33x   2x 5x 1x     4x 1x     3x 1x     2x 1x     1x     2x 4x   2x 14x   2x 10x   2x 5x   2x 31x 1x     30x     2x               2x 4x   2x 2x   2x     2x 3x 1x     2x     2x 3x 1x     2x     2x             3x 3x 3x     3x       3x     2x   2x 2x   2x 2x   2x 2x   2x 2x   2x 5x   2x 4x   3x   3x   2x     4x 11x 1x     10x     2x     3x   2x   2x 33x 18x 2x         16x     2x     3x     2x         3x 2x         1x     2x 2x 2x 2x 17x       4x         13x 3x         10x 2x         8x 8x   8x 2x         6x 2x         4x     2x 8x   2x 8x       2x 8x       2x 2x 1x     1x   1x 1x           2x   2x     2x 2x                      
/*
 * 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 { hexToBuffer } from '@liskhq/lisk-cryptography';
import {
	gte as isVersionGte,
	gtr as isGreaterThanVersionInRange,
	ltr as isLessThanVersionInRange,
	valid as isValidVersion,
	validRange as isValidRangeVersion,
} from 'semver';
import * as validator from 'validator';
 
import {
	MAX_EIGHT_BYTE_NUMBER,
	MAX_INT64,
	MAX_PUBLIC_KEY_LENGTH,
} from './constants';
 
export const isNullCharacterIncluded = (input: string): boolean =>
	new RegExp(/\0|\\u0000|\\x00/).test(input);
 
export const isUsername = (username: string): boolean => {
	if (isNullCharacterIncluded(username)) {
		return false;
	}
 
	if (username !== username.trim().toLowerCase()) {
		return false;
	}
 
	if (/^[0-9]{1,21}[L|l]$/g.test(username)) {
		return false;
	}
 
	if (!/^[a-z0-9!@$&_.]+$/g.test(username)) {
		return false;
	}
 
	return true;
};
 
export const isSignature = (signature: string): boolean =>
	/^[a-f0-9]{128}$/i.test(signature);
 
export const isGreaterThanZero = (amount: bigint): boolean =>
	amount > BigInt(0);
 
export const isGreaterThanMaxTransactionAmount = (amount: bigint): boolean =>
	amount > BigInt(MAX_INT64);
 
export const isGreaterThanMaxTransactionId = (id: bigint): boolean =>
	id > BigInt(MAX_EIGHT_BYTE_NUMBER);
 
export const isNumberString = (num: unknown): boolean => {
	if (typeof num !== 'string') {
		return false;
	}
 
	return validator.isInt(num);
};
 
export const isPositiveNumberString = (num: unknown): boolean => {
	if (typeof num !== 'string') {
		return false;
	}
 
	return /^[0-9]+$/g.test(num);
};
 
export const isValidInteger = (num: unknown): boolean =>
	typeof num === 'number' ? Math.floor(num) === num : false;
 
export const hasNoDuplicate = (values: ReadonlyArray<string>): boolean => {
	const unique = [...new Set(values)];
 
	return unique.length === values.length;
};
 
export const isStringBufferLessThan = (data: unknown, max: number): boolean => {
	if (typeof data !== 'string') {
		return false;
	}
 
	return Buffer.from(data).length <= max;
};
 
export const isHexString = (data: unknown): boolean => {
	if (typeof data !== 'string') {
		return false;
	}
 
	return data === '' || /^[a-f0-9]+$/i.test(data);
};
 
export const isEncryptedPassphrase = (data: string): boolean => {
	// Explanation of regex structure:
	// - 1 or more 'key=value' pairs delimited with '&'
	// Examples:
	// - cipherText=abcd1234
	// - cipherText=abcd1234&iterations=10000&iv=ef012345
	// NOTE: Maximum lengths chosen here are arbitrary
	const keyRegExp = /[a-zA-Z0-9]{2,15}/;
	const valueRegExp = /[a-f0-9]{1,256}/;
	const keyValueRegExp = new RegExp(
		`${keyRegExp.source}=${valueRegExp.source}`,
	);
	const encryptedPassphraseRegExp = new RegExp(
		`^(${keyValueRegExp.source})(?:&(${keyValueRegExp.source})){0,10}$`,
	);
 
	return encryptedPassphraseRegExp.test(data);
};
 
export const isSemVer = (version: string): boolean => !!isValidVersion(version);
 
export const isRangedSemVer = (version: string): boolean =>
	!!isValidRangeVersion(version);
 
export const isLessThanRangedVersion = isLessThanVersionInRange;
export const isGreaterThanRangedVersion = isGreaterThanVersionInRange;
 
export const isProtocolString = (data: string) =>
	/^(\d|[1-9]\d{1,2})\.(\d|[1-9]\d{1,2})$/.test(data);
 
const IPV4_NUMBER = 4;
const IPV6_NUMBER = 6;
 
export const isIPV4 = (data: string): boolean =>
	validator.isIP(data, IPV4_NUMBER);
 
export const isIPV6 = (data: string): boolean =>
	validator.isIP(data, IPV6_NUMBER);
 
export const isIP = (data: string): boolean => isIPV4(data) || isIPV6(data);
 
export const isPort = (port: string) => validator.isPort(port);
 
export const validatePublicKeysForDuplicates = (
	publicKeys: ReadonlyArray<string>,
): boolean =>
	publicKeys.every((element, index) => {
		if (publicKeys.slice(index + 1).includes(element)) {
			throw new Error(`Duplicated public key: ${publicKeys[index]}.`);
		}
 
		return true;
	});
 
export const isStringEndsWith = (
	target: string,
	suffixes: ReadonlyArray<string>,
): boolean => suffixes.some(suffix => target.endsWith(suffix));
 
export const isVersionMatch = isVersionGte;
 
export const validatePublicKey = (publicKey: string): boolean => {
	const publicKeyBuffer = hexToBuffer(publicKey);
	if (publicKeyBuffer.length !== MAX_PUBLIC_KEY_LENGTH) {
		throw new Error(
			`Public key ${publicKey} length differs from the expected 32 bytes for a public key.`,
		);
	}
 
	return true;
};
 
export const validatePublicKeys = (
	publicKeys: ReadonlyArray<string>,
): boolean =>
	publicKeys.every(validatePublicKey) &&
	validatePublicKeysForDuplicates(publicKeys);
 
export const validateKeysgroup = (
	keysgroup: ReadonlyArray<string>,
	min: number,
	max: number,
): boolean => {
	if (keysgroup.length < min || keysgroup.length > max) {
		throw new Error(
			`Expected between ${min} and ${max} public keys in the keysgroup.`,
		);
	}
 
	return validatePublicKeys(keysgroup);
};
 
const MIN_ADDRESS_LENGTH = 2;
const MAX_ADDRESS_LENGTH = 22;
const BASE_TEN = 10;
export const validateAddress = (address: string): boolean => {
	if (
		address.length < MIN_ADDRESS_LENGTH ||
		address.length > MAX_ADDRESS_LENGTH
	) {
		throw new Error(
			'Address length does not match requirements. Expected between 2 and 22 characters.',
		);
	}
 
	if (address[address.length - 1] !== 'L') {
		throw new Error(
			'Address format does not match requirements. Expected "L" at the end.',
		);
	}
 
	if (address.includes('.')) {
		throw new Error(
			'Address format does not match requirements. Address includes invalid character: `.`.',
		);
	}
 
	const addressString = address.slice(0, -1);
	const addressNumber = BigInt(addressString);
 
	if (addressNumber > BigInt(MAX_EIGHT_BYTE_NUMBER)) {
		throw new Error(
			'Address format does not match requirements. Address out of maximum range.',
		);
	}
 
	if (addressString !== addressNumber.toString(BASE_TEN)) {
		throw new Error(
			"Address string format does not match it's number representation.",
		);
	}
 
	return true;
};
 
export const isValidNonTransferAmount = (data: string): boolean =>
	isNumberString(data) && data === '0';
 
export const isValidTransferAmount = (data: string): boolean =>
	isNumberString(data) &&
	isGreaterThanZero(BigInt(data)) &&
	!isGreaterThanMaxTransactionAmount(BigInt(data));
 
export const isValidFee = (data: string): boolean =>
	isNumberString(data) &&
	isGreaterThanZero(BigInt(data)) &&
	!isGreaterThanMaxTransactionAmount(BigInt(data));
 
export const isCsv = (data: string): boolean => {
	if (typeof data !== 'string') {
		return false;
	}
 
	const csvAsArray = data.split(',');
 
	Eif (csvAsArray.length > 0) {
		return true;
	}
 
	return false;
};
 
const MAX_TRANSFER_ASSET_DATA_LENGTH = 64;
 
export const isValidTransferData = (data: string): boolean =>
	Buffer.byteLength(data, 'utf8') <= MAX_TRANSFER_ASSET_DATA_LENGTH;
 
const NETWORK_IDENTIFIER_LENGTH = 32;
export const validateNetworkIdentifier = (networkIdentifier: string) => {
	if (!networkIdentifier) {
		throw new Error(`Network identifier can not be empty.`);
	}
	const networkIdentifierBuffer = hexToBuffer(networkIdentifier);
	if (networkIdentifierBuffer.length !== NETWORK_IDENTIFIER_LENGTH) {
		throw new Error(`Invalid network identifier length: ${networkIdentifier}`);
	}
 
	return true;
};