All files / src hash.ts

100% Statements 17/17
100% Branches 10/10
100% Functions 3/3
100% Lines 17/17

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                            6x   6x   6x 42x 42x   42x     6x 44x 39x     5x 4x 1x         3x   3x     1x         6x       1x  
/*
 * 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 crypto from 'crypto';
 
import { hexToBuffer } from './buffer';
 
const cryptoHashSha256 = (data: Buffer): Buffer => {
	const dataHash = crypto.createHash('sha256');
	dataHash.update(data);
 
	return dataHash.digest();
};
 
export const hash = (data: Buffer | string, format?: string): Buffer => {
	if (Buffer.isBuffer(data)) {
		return cryptoHashSha256(data);
	}
 
	if (typeof data === 'string' && typeof format === 'string') {
		if (!['utf8', 'hex'].includes(format)) {
			throw new Error(
				'Unsupported string format. Currently only `hex` and `utf8` are supported.',
			);
		}
		const encoded =
			format === 'utf8' ? Buffer.from(data, 'utf8') : hexToBuffer(data);
 
		return cryptoHashSha256(encoded);
	}
 
	throw new Error(
		'Unsupported data format. Currently only Buffers or `hex` and `utf8` strings are supported.',
	);
};
 
export const getNetworkIdentifier = (
	genesisBlockPayloadHash: string,
	communityIdentifier: string,
) =>
	hash(genesisBlockPayloadHash + communityIdentifier, 'utf8').toString('hex');