From 74fd7d6a792ad0eb4a86a4735eb3c5cc1d6c496f Mon Sep 17 00:00:00 2001 From: shuse2 Date: Sat, 16 Jul 2022 23:33:55 +0200 Subject: [PATCH 1/6] :seedling: Update crypto structure --- .../src/{keys.ts => address.ts} | 42 +++- elements/lisk-cryptography/src/bls.ts | 96 +++++++- elements/lisk-cryptography/src/buffer.ts | 85 ------- elements/lisk-cryptography/src/convert.ts | 184 -------------- .../lisk-cryptography/src/{sign.ts => ed.ts} | 71 +++++- elements/lisk-cryptography/src/encrypt.ts | 128 ++++++++-- elements/lisk-cryptography/src/hash.ts | 48 ---- elements/lisk-cryptography/src/hash_onion.ts | 52 ---- elements/lisk-cryptography/src/index.ts | 23 +- .../lisk-cryptography/src/legacy_address.ts | 19 +- elements/lisk-cryptography/src/message_tag.ts | 43 ---- elements/lisk-cryptography/src/utils.ts | 233 +++++++++++------- 12 files changed, 467 insertions(+), 557 deletions(-) rename elements/lisk-cryptography/src/{keys.ts => address.ts} (82%) delete mode 100644 elements/lisk-cryptography/src/buffer.ts delete mode 100644 elements/lisk-cryptography/src/convert.ts rename elements/lisk-cryptography/src/{sign.ts => ed.ts} (69%) delete mode 100644 elements/lisk-cryptography/src/hash.ts delete mode 100644 elements/lisk-cryptography/src/hash_onion.ts delete mode 100644 elements/lisk-cryptography/src/message_tag.ts diff --git a/elements/lisk-cryptography/src/keys.ts b/elements/lisk-cryptography/src/address.ts similarity index 82% rename from elements/lisk-cryptography/src/keys.ts rename to elements/lisk-cryptography/src/address.ts index 60a024db922..cbb73443bb7 100644 --- a/elements/lisk-cryptography/src/keys.ts +++ b/elements/lisk-cryptography/src/address.ts @@ -13,11 +13,42 @@ * */ import { BINARY_ADDRESS_LENGTH, DEFAULT_LISK32_ADDRESS_PREFIX } from './constants'; -// eslint-disable-next-line import/no-cycle -import { convertUInt5ToBase32, convertUIntArray } from './convert'; -import { hash } from './hash'; import { getKeyPair, getPublicKey } from './nacl'; import { Keypair } from './types'; +import { hash } from './utils'; + +const CHARSET = 'zxvcpmbn3465o978uyrtkqew2adsjhfg'; + +const convertUIntArray = (uintArray: number[], fromBits: number, toBits: number): number[] => { + // eslint-disable-next-line no-bitwise + const maxValue = (1 << toBits) - 1; + let accumulator = 0; + let bits = 0; + const result = []; + // eslint-disable-next-line + for (let p = 0; p < uintArray.length; p += 1) { + const byte = uintArray[p]; + // check that the entry is a value between 0 and 2^frombits-1 + // eslint-disable-next-line no-bitwise + if (byte < 0 || byte >> fromBits !== 0) { + return []; + } + + // eslint-disable-next-line no-bitwise + accumulator = (accumulator << fromBits) | byte; + bits += fromBits; + while (bits >= toBits) { + bits -= toBits; + // eslint-disable-next-line no-bitwise + result.push((accumulator >> bits) & maxValue); + } + } + + return result; +}; + +const convertUInt5ToBase32 = (uint5Array: number[]): string => + uint5Array.map((val: number) => CHARSET[val]).join(''); export const getPrivateAndPublicKeyFromPassphrase = (passphrase: string): Keypair => { const hashed = hash(passphrase, 'utf8'); @@ -83,7 +114,7 @@ const polymod = (uint5Array: number[]): number => { return chk; }; -export const createChecksum = (uint5Array: number[]): number[] => { +const createChecksum = (uint5Array: number[]): number[] => { const values = uint5Array.concat([0, 0, 0, 0, 0, 0]); // eslint-disable-next-line no-bitwise const mod = polymod(values) ^ 1; @@ -95,8 +126,7 @@ export const createChecksum = (uint5Array: number[]): number[] => { return result; }; -export const verifyChecksum = (integerSequence: number[]): boolean => - polymod(integerSequence) === 1; +const verifyChecksum = (integerSequence: number[]): boolean => polymod(integerSequence) === 1; const addressToLisk32 = (address: Buffer): string => { const byteSequence = []; diff --git a/elements/lisk-cryptography/src/bls.ts b/elements/lisk-cryptography/src/bls.ts index 0b79f673e08..4df7b832c37 100644 --- a/elements/lisk-cryptography/src/bls.ts +++ b/elements/lisk-cryptography/src/bls.ts @@ -12,7 +12,8 @@ * Removal or modification of this copyright notice is prohibited. * */ - +import * as crypto from 'crypto'; +import { Mnemonic } from '@liskhq/lisk-passphrase'; import { blsSign, blsVerify, @@ -22,15 +23,39 @@ import { blsFastAggregateVerify, blsSkToPk, BLS_SUPPORTED, + blsPopVerify, + blsPopProve, } from './bls_lib'; -import { tagMessage } from './message_tag'; -import { readBit, writeBit } from './utils'; -import { hash } from './hash'; +import { hash, parseKeyDerivationPath, tagMessage } from './utils'; +import { EMPTY_SALT, HASH_LENGTH, L, SHA256 } from './constants'; export { BLS_SUPPORTED }; export const generatePrivateKey = blsKeyGen; export const getPublicKeyFromPrivateKey = blsSkToPk; export const validateKey = blsKeyValidate; +export const popVerify = blsPopVerify; +export const popProve = blsPopProve; + +const readBit = (buf: Buffer, bit: number): boolean => { + const byteIndex = Math.floor(bit / 8); + const bitIndex = bit % 8; + + // eslint-disable-next-line no-bitwise + return (buf[byteIndex] >> bitIndex) % 2 === 1; +}; + +const writeBit = (buf: Buffer, bit: number, val: boolean): void => { + const byteIndex = Math.floor(bit / 8); + const bitIndex = bit % 8; + + if (val) { + // eslint-disable-next-line no-bitwise, no-param-reassign + buf[byteIndex] |= 1 << bitIndex; + } else { + // eslint-disable-next-line no-bitwise, no-param-reassign + buf[byteIndex] &= ~(1 << bitIndex); + } +}; export const signBLS = ( tag: string, @@ -115,3 +140,66 @@ export const verifyWeightedAggSig = ( return blsFastAggregateVerify(keys, hash(taggedMessage), signature); }; + +// eslint-disable-next-line no-bitwise +const flipBits = (buf: Buffer) => Buffer.from(buf.map(x => x ^ 0xff)); + +const sha256 = (x: Buffer) => crypto.createHash(SHA256).update(x).digest(); + +const hmacSHA256 = (key: Buffer, message: Buffer, hashValue: string) => + crypto.createHmac(hashValue, key).update(message).digest(); + +const hkdfSHA256 = (ikm: Buffer, length: number, salt: Buffer, info: Buffer) => { + if (salt.length === 0) { + // eslint-disable-next-line no-param-reassign + salt = EMPTY_SALT; + } + const PRK = hmacSHA256(salt, ikm, SHA256); + let t = Buffer.from([]); + let OKM = Buffer.from([]); + + for (let i = 0; i < Math.ceil(length / HASH_LENGTH); i += 1) { + t = hmacSHA256(PRK, Buffer.concat([t, info, Buffer.from([1 + i])]), SHA256); + OKM = Buffer.concat([OKM, t]); + } + return OKM.slice(0, length); +}; + +const toLamportSK = (IKM: Buffer, salt: Buffer) => { + const info = Buffer.from([]); + const OKM = hkdfSHA256(IKM, L, salt, info); + + const lamportSK = []; + for (let i = 0; i < 255; i += 1) { + lamportSK.push(OKM.slice(i * 32, (i + 1) * 32)); + } + return lamportSK; +}; + +const parentSKToLamportPK = (parentSK: Buffer, index: number) => { + const salt = Buffer.allocUnsafe(4); + salt.writeUIntBE(index, 0, 4); + + const IKM = parentSK; + const hashedLamport0 = toLamportSK(IKM, salt).map(x => sha256(x)); + const hashedLamport1 = toLamportSK(flipBits(IKM), salt).map(x => sha256(x)); + + const lamportPK = Buffer.concat(hashedLamport0.concat(hashedLamport1)); + return sha256(lamportPK); +}; + +const deriveChildSK = (parentSK: Buffer, index: number) => { + const lamportPK = parentSKToLamportPK(parentSK, index); + return blsKeyGen(lamportPK); +}; + +export const getPrivateKeyFromPhraseAndPath = async (phrase: string, path: string) => { + const masterSeed = await Mnemonic.mnemonicToSeed(phrase); + let key = blsKeyGen(masterSeed); + + for (const segment of parseKeyDerivationPath(path)) { + key = deriveChildSK(key, segment); + } + + return key; +}; diff --git a/elements/lisk-cryptography/src/buffer.ts b/elements/lisk-cryptography/src/buffer.ts deleted file mode 100644 index fc474fe34ba..00000000000 --- a/elements/lisk-cryptography/src/buffer.ts +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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. - * - */ - -export const BIG_ENDIAN = 'big'; -export const LITTLE_ENDIAN = 'little'; -const MAX_NUMBER_BYTE_LENGTH = 6; - -export const intToBuffer = ( - value: number | string, - byteLength: number, - endianness = BIG_ENDIAN, - signed = false, -): Buffer => { - if (![BIG_ENDIAN, LITTLE_ENDIAN].includes(endianness)) { - throw new Error(`Endianness must be either ${BIG_ENDIAN} or ${LITTLE_ENDIAN}`); - } - const buffer = Buffer.alloc(byteLength); - if (endianness === 'big') { - if (byteLength <= MAX_NUMBER_BYTE_LENGTH) { - if (signed) { - buffer.writeIntBE(Number(value), 0, byteLength); - } else { - buffer.writeUIntBE(Number(value), 0, byteLength); - } - } else { - // eslint-disable-next-line no-lonely-if - if (signed) { - buffer.writeBigInt64BE(BigInt(value)); - } else { - buffer.writeBigUInt64BE(BigInt(value)); - } - } - } else { - // eslint-disable-next-line no-lonely-if - if (byteLength <= MAX_NUMBER_BYTE_LENGTH) { - if (signed) { - buffer.writeIntLE(Number(value), 0, byteLength); - } else { - buffer.writeUIntLE(Number(value), 0, byteLength); - } - } else { - // eslint-disable-next-line no-lonely-if - if (signed) { - buffer.writeBigInt64LE(BigInt(value)); - } else { - buffer.writeBigUInt64LE(BigInt(value)); - } - } - } - - return buffer; -}; - -export const bufferToHex = (buffer: Buffer): string => Buffer.from(buffer).toString('hex'); - -const hexRegex = /^[0-9a-f]+/i; -export const hexToBuffer = (hex: string, argumentName = 'Argument'): Buffer => { - if (typeof hex !== 'string') { - throw new TypeError(`${argumentName} must be a string.`); - } - // eslint-disable-next-line @typescript-eslint/prefer-regexp-exec - const matchedHex = (hex.match(hexRegex) ?? [])[0]; - if (!matchedHex || matchedHex.length !== hex.length) { - throw new TypeError(`${argumentName} must be a valid hex string.`); - } - if (matchedHex.length % 2 !== 0) { - throw new TypeError(`${argumentName} must have a valid length of hex string.`); - } - - return Buffer.from(matchedHex, 'hex'); -}; - -export const stringToBuffer = (str: string): Buffer => Buffer.from(str, 'utf8'); diff --git a/elements/lisk-cryptography/src/convert.ts b/elements/lisk-cryptography/src/convert.ts deleted file mode 100644 index 188afe29f5a..00000000000 --- a/elements/lisk-cryptography/src/convert.ts +++ /dev/null @@ -1,184 +0,0 @@ -/* - * 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. - * - */ -// Required because first level function export -import * as ed2curve from 'ed2curve'; -import * as querystring from 'querystring'; - -// eslint-disable-next-line import/no-cycle -import { EncryptedPassphraseObject, Cipher, KDF } from './encrypt'; - -// eslint-disable-next-line import/order -import reverse = require('buffer-reverse'); - -const CHARSET = 'zxvcpmbn3465o978uyrtkqew2adsjhfg'; - -export const convertUIntArray = ( - uintArray: number[], - fromBits: number, - toBits: number, -): number[] => { - // eslint-disable-next-line no-bitwise - const maxValue = (1 << toBits) - 1; - let accumulator = 0; - let bits = 0; - const result = []; - // eslint-disable-next-line - for (let p = 0; p < uintArray.length; p += 1) { - const byte = uintArray[p]; - // check that the entry is a value between 0 and 2^frombits-1 - // eslint-disable-next-line no-bitwise - if (byte < 0 || byte >> fromBits !== 0) { - return []; - } - - // eslint-disable-next-line no-bitwise - accumulator = (accumulator << fromBits) | byte; - bits += fromBits; - while (bits >= toBits) { - bits -= toBits; - // eslint-disable-next-line no-bitwise - result.push((accumulator >> bits) & maxValue); - } - } - - return result; -}; - -export const convertUInt5ToBase32 = (uint5Array: number[]): string => - uint5Array.map((val: number) => CHARSET[val]).join(''); - -export const getFirstEightBytesReversed = (input: string | Buffer): Buffer => { - const BUFFER_SIZE = 8; - // Union type arguments on overloaded functions do not work in typescript. - // Relevant discussion: https://github.com/Microsoft/TypeScript/issues/23155 - if (typeof input === 'string') { - return reverse(Buffer.from(input).slice(0, BUFFER_SIZE)); - } - - return reverse(Buffer.from(input).slice(0, BUFFER_SIZE)); -}; - -export const convertPublicKeyEd2Curve = ed2curve.convertPublicKey; - -export const convertPrivateKeyEd2Curve = ed2curve.convertSecretKey; - -export const stringifyEncryptedPassphrase = ( - encryptedPassphrase: EncryptedPassphraseObject, -): string => { - if (typeof encryptedPassphrase !== 'object' || encryptedPassphrase === null) { - throw new Error('Encrypted passphrase to stringify must be an object.'); - } - const objectToStringify = { - kdf: encryptedPassphrase.kdf, - cipher: encryptedPassphrase.cipher, - version: encryptedPassphrase.version, - ciphertext: encryptedPassphrase.ciphertext, - mac: encryptedPassphrase.mac, - salt: encryptedPassphrase.kdfparams.salt, - iv: encryptedPassphrase.cipherparams.iv, - tag: encryptedPassphrase.cipherparams.tag, - iterations: encryptedPassphrase.kdfparams.iterations, - parallelism: encryptedPassphrase.kdfparams.parallelism, - memorySize: encryptedPassphrase.kdfparams.memorySize, - }; - - return querystring.stringify(objectToStringify); -}; - -const parseOption = (optionString?: string): number | undefined => { - const option = !optionString ? undefined : parseInt(optionString, 10); - - if (typeof option !== 'undefined' && Number.isNaN(option)) { - throw new Error('Could not parse option.'); - } - - return option; -}; - -interface ParsedEncryptedPassphrase { - readonly version: string; - readonly ciphertext: string; - readonly mac: string; - readonly kdf: string | KDF; - readonly kdfparams?: { - parallelism?: number; - iterations?: number; - memorySize?: number; - salt: string; - }; - readonly cipher: string | Cipher; - readonly cipherparams: { - iv: string; - tag: string; - }; -} - -export const parseEncryptedPassphrase = ( - encryptedPassphrase: string, -): ParsedEncryptedPassphrase => { - if (typeof encryptedPassphrase !== 'string') { - throw new Error('Encrypted passphrase to parse must be a string.'); - } - const keyValuePairs = querystring.parse(encryptedPassphrase); - - const { - kdf, - cipher, - iterations, - salt, - ciphertext, - iv, - tag, - version, - mac, - parallelism, - memorySize, - } = keyValuePairs; - - // Review, and find a better solution - if ( - typeof kdf !== 'string' || - typeof cipher !== 'string' || - typeof ciphertext !== 'string' || - typeof iv !== 'string' || - typeof tag !== 'string' || - typeof salt !== 'string' || - typeof version !== 'string' || - (typeof mac !== 'string' && typeof mac !== 'undefined') || - (typeof iterations !== 'string' && typeof iterations !== 'undefined') || - (typeof parallelism !== 'string' && typeof parallelism !== 'undefined') || - (typeof memorySize !== 'string' && typeof memorySize !== 'undefined') - ) { - throw new Error('Encrypted passphrase to parse must have only one value per key.'); - } - - return { - version, - ciphertext, - mac, - kdf, - kdfparams: { - parallelism: parseOption(parallelism), - iterations: parseOption(iterations), - memorySize: parseOption(memorySize), - salt, - }, - cipher, - cipherparams: { - iv, - tag, - }, - }; -}; diff --git a/elements/lisk-cryptography/src/sign.ts b/elements/lisk-cryptography/src/ed.ts similarity index 69% rename from elements/lisk-cryptography/src/sign.ts rename to elements/lisk-cryptography/src/ed.ts index 926438d7334..cacc1fd2d3e 100644 --- a/elements/lisk-cryptography/src/sign.ts +++ b/elements/lisk-cryptography/src/ed.ts @@ -1,5 +1,5 @@ /* - * Copyright © 2019 Lisk Foundation + * Copyright © 2022 Lisk Foundation * * See the LICENSE file at the top-level directory of this distribution * for licensing information. @@ -12,14 +12,16 @@ * Removal or modification of this copyright notice is prohibited. * */ +import * as crypto from 'crypto'; +import { Mnemonic } from '@liskhq/lisk-passphrase'; import { encode as encodeVarInt } from 'varuint-bitcoin'; -import { SIGNED_MESSAGE_PREFIX } from './constants'; -import { hash } from './hash'; -import { getPrivateAndPublicKeyFromPassphrase } from './keys'; -import { tagMessage } from './message_tag'; +import { parseKeyDerivationPath, hash, tagMessage } from './utils'; +import { ED25519_CURVE, SIGNED_MESSAGE_PREFIX } from './constants'; import { NACL_SIGN_PUBLICKEY_LENGTH, NACL_SIGN_SIGNATURE_LENGTH, + getKeyPair, + getPublicKey, signDetached, verifyDetached, } from './nacl'; @@ -34,12 +36,7 @@ const signatureFooter = createHeader('END LISK SIGNED MESSAGE'); const SIGNED_MESSAGE_PREFIX_BYTES = Buffer.from(SIGNED_MESSAGE_PREFIX, 'utf8'); const SIGNED_MESSAGE_PREFIX_LENGTH = encodeVarInt(SIGNED_MESSAGE_PREFIX.length); -export interface SignedMessageWithOnePassphrase { - readonly message: string; - readonly publicKey: Buffer; - readonly signature: Buffer; -} -export const digestMessage = (message: string): Buffer => { +const digestMessage = (message: string): Buffer => { const msgBytes = Buffer.from(message, 'utf8'); const msgLenBytes = encodeVarInt(message.length); const dataBytes = Buffer.concat([ @@ -52,6 +49,58 @@ export const digestMessage = (message: string): Buffer => { return hash(hash(dataBytes)); }; +export const getPublicKeyFromPrivateKey = (pk: Buffer): Buffer => getPublicKey(pk); + +export const getPrivateAndPublicKeyFromPassphrase = (passphrase: string) => { + const hashed = hash(passphrase, 'utf8'); + return getKeyPair(hashed); +}; + +const getMasterKeyFromSeed = (seed: Buffer) => { + const hmac = crypto.createHmac('sha512', ED25519_CURVE); + const digest = hmac.update(seed).digest(); + const leftBytes = digest.slice(0, 32); + const rightBytes = digest.slice(32); + return { + key: leftBytes, + chainCode: rightBytes, + }; +}; + +const getChildKey = (node: { key: Buffer; chainCode: Buffer }, index: number) => { + const indexBuffer = Buffer.allocUnsafe(4); + indexBuffer.writeUInt32BE(index, 0); + const data = Buffer.concat([Buffer.alloc(1, 0), node.key, indexBuffer]); + const digest = crypto.createHmac('sha512', node.chainCode).update(data).digest(); + const leftBytes = digest.slice(0, 32); + const rightBytes = digest.slice(32); + + return { + key: leftBytes, + chainCode: rightBytes, + }; +}; + +export const getKeyPairFromPhraseAndPath = async ( + phrase: string, + path: string, +): Promise => { + const masterSeed = await Mnemonic.mnemonicToSeed(phrase); + let node = getMasterKeyFromSeed(masterSeed); + + for (const segment of parseKeyDerivationPath(path)) { + node = getChildKey(node, segment); + } + + return getKeyPair(node.key).privateKey; +}; + +export interface SignedMessageWithOnePassphrase { + readonly message: string; + readonly publicKey: Buffer; + readonly signature: Buffer; +} + export const signMessageWithPassphrase = ( message: string, passphrase: string, diff --git a/elements/lisk-cryptography/src/encrypt.ts b/elements/lisk-cryptography/src/encrypt.ts index fd5ffbcdb56..962be470145 100644 --- a/elements/lisk-cryptography/src/encrypt.ts +++ b/elements/lisk-cryptography/src/encrypt.ts @@ -13,18 +13,15 @@ * */ import { argon2id } from 'hash-wasm'; +import * as querystring from 'querystring'; import * as crypto from 'crypto'; -import { Mnemonic } from '@liskhq/lisk-passphrase'; +import * as ed2curve from 'ed2curve'; -import { bufferToHex, hexToBuffer } from './buffer'; // eslint-disable-next-line import/no-cycle -import { convertPrivateKeyEd2Curve, convertPublicKeyEd2Curve } from './convert'; +import { getPrivateAndPublicKeyFromPassphrase } from './address'; // eslint-disable-next-line import/no-cycle -import { getPrivateAndPublicKeyFromPassphrase } from './keys'; -// eslint-disable-next-line import/no-cycle -import { box, getRandomBytes, openBox, getKeyPair } from './nacl'; -import { getMasterKeyFromSeed, getChildKey, parseKeyDerivationPath, deriveChildSK } from './utils'; -import { blsKeyGen } from './bls_lib'; +import { box, getRandomBytes, openBox } from './nacl'; +import { bufferToHex, hexToBuffer } from './utils'; const PBKDF2_ITERATIONS = 1e6; const PBKDF2_KEYLEN = 32; @@ -35,6 +32,10 @@ const ARGON2_ITERATIONS = 1; const ARGON2_PARALLELISM = 4; const ARGON2_MEMORY = 2024; +const convertPublicKeyEd2Curve = ed2curve.convertPublicKey; + +const convertPrivateKeyEd2Curve = ed2curve.convertSecretKey; + export interface EncryptedMessageWithNonce { readonly encryptedMessage: string; readonly nonce: string; @@ -254,24 +255,111 @@ export const encryptPassphraseWithPassword = encryptAES256GCMWithPassword; export const decryptPassphraseWithPassword = decryptAES256GCMWithPassword; -export const getKeyPairFromPhraseAndPath = async (phrase: string, path: string) => { - const masterSeed = await Mnemonic.mnemonicToSeed(phrase); - let node = getMasterKeyFromSeed(masterSeed); +interface ParsedEncryptedPassphrase { + readonly version: string; + readonly ciphertext: string; + readonly mac: string; + readonly kdf: string | KDF; + readonly kdfparams?: { + parallelism?: number; + iterations?: number; + memorySize?: number; + salt: string; + }; + readonly cipher: string | Cipher; + readonly cipherparams: { + iv: string; + tag: string; + }; +} - for (const segment of parseKeyDerivationPath(path)) { - node = getChildKey(node, segment); +const parseOption = (optionString?: string): number | undefined => { + const option = !optionString ? undefined : parseInt(optionString, 10); + + if (typeof option !== 'undefined' && Number.isNaN(option)) { + throw new Error('Could not parse option.'); } - return getKeyPair(node.key); + return option; }; -export const getBLSPrivateKeyFromPhraseAndPath = async (phrase: string, path: string) => { - const masterSeed = await Mnemonic.mnemonicToSeed(phrase); - let key = blsKeyGen(masterSeed); +export const parseEncryptedPassphrase = ( + encryptedPassphrase: string, +): ParsedEncryptedPassphrase => { + if (typeof encryptedPassphrase !== 'string') { + throw new Error('Encrypted passphrase to parse must be a string.'); + } + const keyValuePairs = querystring.parse(encryptedPassphrase); - for (const segment of parseKeyDerivationPath(path)) { - key = deriveChildSK(key, segment); + const { + kdf, + cipher, + iterations, + salt, + ciphertext, + iv, + tag, + version, + mac, + parallelism, + memorySize, + } = keyValuePairs; + + // Review, and find a better solution + if ( + typeof kdf !== 'string' || + typeof cipher !== 'string' || + typeof ciphertext !== 'string' || + typeof iv !== 'string' || + typeof tag !== 'string' || + typeof salt !== 'string' || + typeof version !== 'string' || + (typeof mac !== 'string' && typeof mac !== 'undefined') || + (typeof iterations !== 'string' && typeof iterations !== 'undefined') || + (typeof parallelism !== 'string' && typeof parallelism !== 'undefined') || + (typeof memorySize !== 'string' && typeof memorySize !== 'undefined') + ) { + throw new Error('Encrypted passphrase to parse must have only one value per key.'); + } + + return { + version, + ciphertext, + mac, + kdf, + kdfparams: { + parallelism: parseOption(parallelism), + iterations: parseOption(iterations), + memorySize: parseOption(memorySize), + salt, + }, + cipher, + cipherparams: { + iv, + tag, + }, + }; +}; + +export const stringifyEncryptedPassphrase = ( + encryptedPassphrase: EncryptedPassphraseObject, +): string => { + if (typeof encryptedPassphrase !== 'object' || encryptedPassphrase === null) { + throw new Error('Encrypted passphrase to stringify must be an object.'); } + const objectToStringify = { + kdf: encryptedPassphrase.kdf, + cipher: encryptedPassphrase.cipher, + version: encryptedPassphrase.version, + ciphertext: encryptedPassphrase.ciphertext, + mac: encryptedPassphrase.mac, + salt: encryptedPassphrase.kdfparams.salt, + iv: encryptedPassphrase.cipherparams.iv, + tag: encryptedPassphrase.cipherparams.tag, + iterations: encryptedPassphrase.kdfparams.iterations, + parallelism: encryptedPassphrase.kdfparams.parallelism, + memorySize: encryptedPassphrase.kdfparams.memorySize, + }; - return key; + return querystring.stringify(objectToStringify); }; diff --git a/elements/lisk-cryptography/src/hash.ts b/elements/lisk-cryptography/src/hash.ts deleted file mode 100644 index c3fc2d1f1e3..00000000000 --- a/elements/lisk-cryptography/src/hash.ts +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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:${data} and format:${ - format ?? 'undefined' - }. Currently only Buffers or hex and utf8 strings are supported.`, - ); -}; - -export const getNetworkIdentifier = (genesisBlockID: Buffer, communityIdentifier: string): Buffer => - hash(Buffer.concat([genesisBlockID, Buffer.from(communityIdentifier, 'utf8')])); diff --git a/elements/lisk-cryptography/src/hash_onion.ts b/elements/lisk-cryptography/src/hash_onion.ts deleted file mode 100644 index 30d31e436f0..00000000000 --- a/elements/lisk-cryptography/src/hash_onion.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright © 2020 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 './hash'; -import { getRandomBytes } from './nacl'; - -const HASH_SIZE = 16; -const INPUT_SIZE = 64; -const defaultCount = 1000000; -const defaultDistance = 1000; - -export const generateHashOnionSeed = (): Buffer => - hash(getRandomBytes(INPUT_SIZE)).slice(0, HASH_SIZE); - -export const hashOnion = ( - seed: Buffer, - count: number = defaultCount, - distance: number = defaultDistance, -): ReadonlyArray => { - if (count < distance) { - throw new Error('Invalid count or distance. Count must be greater than distance'); - } - - if (count % distance !== 0) { - throw new Error('Invalid count. Count must be multiple of distance'); - } - - let previousHash = seed; - const hashes = [seed]; - - for (let i = 1; i <= count; i += 1) { - const nextHash = hash(previousHash).slice(0, HASH_SIZE); - if (i % distance === 0) { - hashes.push(nextHash); - } - previousHash = nextHash; - } - - return hashes.reverse(); -}; diff --git a/elements/lisk-cryptography/src/index.ts b/elements/lisk-cryptography/src/index.ts index d2e98253e94..42f27878be2 100644 --- a/elements/lisk-cryptography/src/index.ts +++ b/elements/lisk-cryptography/src/index.ts @@ -13,19 +13,10 @@ * */ -import * as constants from './constants'; - -export * from './buffer'; -export * from './convert'; -export * from './encrypt'; -export * from './hash'; -export * from './keys'; -export * from './legacy_address'; -export * from './sign'; -export * from './hash_onion'; -export * from './message_tag'; -export * from './bls'; -export { blsPopVerify, blsPopProve } from './bls_lib/lib'; -export { getRandomBytes, getPublicKey } from './nacl'; - -export { constants }; +export * as constants from './constants'; +export * as encrypt from './encrypt'; +export * as address from './address'; +export * as legacyAddress from './legacy_address'; +export * as bls from './bls'; +export * as ed from './ed'; +export * as utils from './utils'; diff --git a/elements/lisk-cryptography/src/legacy_address.ts b/elements/lisk-cryptography/src/legacy_address.ts index c1f17e12ddc..194405ad213 100644 --- a/elements/lisk-cryptography/src/legacy_address.ts +++ b/elements/lisk-cryptography/src/legacy_address.ts @@ -13,10 +13,23 @@ * */ -import { hash } from './hash'; -import { getKeys } from './keys'; -import { getFirstEightBytesReversed } from './convert'; +import { getKeys } from './address'; import { getPublicKey } from './nacl'; +import { hash } from './utils'; + +// eslint-disable-next-line import/order +import reverse = require('buffer-reverse'); + +export const getFirstEightBytesReversed = (input: string | Buffer): Buffer => { + const BUFFER_SIZE = 8; + // Union type arguments on overloaded functions do not work in typescript. + // Relevant discussion: https://github.com/Microsoft/TypeScript/issues/23155 + if (typeof input === 'string') { + return reverse(Buffer.from(input).slice(0, BUFFER_SIZE)); + } + + return reverse(Buffer.from(input).slice(0, BUFFER_SIZE)); +}; export const getLegacyAddressFromPublicKey = (publicKey: Buffer): string => { const publicKeyHash = hash(publicKey); diff --git a/elements/lisk-cryptography/src/message_tag.ts b/elements/lisk-cryptography/src/message_tag.ts deleted file mode 100644 index 17bc20e5ace..00000000000 --- a/elements/lisk-cryptography/src/message_tag.ts +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright © 2021 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. - * - */ - -const TAG_REGEX = /^([A-Za-z0-9])+$/; - -export const createMessageTag = (domain: string, version?: number | string): string => { - if (!TAG_REGEX.test(domain)) { - throw new Error( - `Message tag domain must be alpha numeric without special characters. Got "${domain}".`, - ); - } - - if (version && !TAG_REGEX.test(version.toString())) { - throw new Error( - `Message tag version must be alpha numeric without special characters. Got "${version}"`, - ); - } - - return `LSK_${version ? `${domain}:${version}` : domain}_`; -}; - -export const tagMessage = ( - tag: string, - networkIdentifier: Buffer, - message: string | Buffer, -): Buffer => - Buffer.concat([ - Buffer.from(tag, 'utf8'), - networkIdentifier, - typeof message === 'string' ? Buffer.from(message, 'utf8') : message, - ]); diff --git a/elements/lisk-cryptography/src/utils.ts b/elements/lisk-cryptography/src/utils.ts index b03db008f05..2e79a618930 100644 --- a/elements/lisk-cryptography/src/utils.ts +++ b/elements/lisk-cryptography/src/utils.ts @@ -14,38 +14,41 @@ */ import * as crypto from 'crypto'; -import { blsKeyGen } from './bls_lib'; -import { - HARDENED_OFFSET, - ED25519_CURVE, - MAX_UINT32, - HASH_LENGTH, - L, - EMPTY_SALT, - SHA256, -} from './constants'; - -export const readBit = (buf: Buffer, bit: number): boolean => { - const byteIndex = Math.floor(bit / 8); - const bitIndex = bit % 8; - - // eslint-disable-next-line no-bitwise - return (buf[byteIndex] >> bitIndex) % 2 === 1; +import { HARDENED_OFFSET, MAX_UINT32 } from './constants'; + +import { getRandomBytes } from './nacl'; + +const cryptoHashSha256 = (data: Buffer): Buffer => { + const dataHash = crypto.createHash('sha256'); + dataHash.update(data); + + return dataHash.digest(); }; -export const writeBit = (buf: Buffer, bit: number, val: boolean): void => { - const byteIndex = Math.floor(bit / 8); - const bitIndex = bit % 8; +export const hash = (data: Buffer | string, format?: string): Buffer => { + if (Buffer.isBuffer(data)) { + return cryptoHashSha256(data); + } - if (val) { - // eslint-disable-next-line no-bitwise, no-param-reassign - buf[byteIndex] |= 1 << bitIndex; - } else { - // eslint-disable-next-line no-bitwise, no-param-reassign - buf[byteIndex] &= ~(1 << bitIndex); + 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') : Buffer.from(data, 'hex'); + + return cryptoHashSha256(encoded); } + + throw new Error( + `Unsupported data:${data} and format:${ + format ?? 'undefined' + }. Currently only Buffers or hex and utf8 strings are supported.`, + ); }; +export const getNetworkIdentifier = (genesisBlockID: Buffer, communityIdentifier: string): Buffer => + hash(Buffer.concat([genesisBlockID, Buffer.from(communityIdentifier, 'utf8')])); + export const parseKeyDerivationPath = (path: string) => { if (!path.startsWith('m') || !path.includes('/')) { throw new Error('Invalid path format'); @@ -78,79 +81,139 @@ export const parseKeyDerivationPath = (path: string) => { ); }; -export const getMasterKeyFromSeed = (seed: Buffer) => { - const hmac = crypto.createHmac('sha512', ED25519_CURVE); - const digest = hmac.update(seed).digest(); - const leftBytes = digest.slice(0, 32); - const rightBytes = digest.slice(32); - return { - key: leftBytes, - chainCode: rightBytes, - }; -}; +const TAG_REGEX = /^([A-Za-z0-9])+$/; + +export const createMessageTag = (domain: string, version?: number | string): string => { + if (!TAG_REGEX.test(domain)) { + throw new Error( + `Message tag domain must be alpha numeric without special characters. Got "${domain}".`, + ); + } + + if (version && !TAG_REGEX.test(version.toString())) { + throw new Error( + `Message tag version must be alpha numeric without special characters. Got "${version}"`, + ); + } -export const getChildKey = (node: { key: Buffer; chainCode: Buffer }, index: number) => { - const indexBuffer = Buffer.allocUnsafe(4); - indexBuffer.writeUInt32BE(index, 0); - const data = Buffer.concat([Buffer.alloc(1, 0), node.key, indexBuffer]); - const digest = crypto.createHmac('sha512', node.chainCode).update(data).digest(); - const leftBytes = digest.slice(0, 32); - const rightBytes = digest.slice(32); - - return { - key: leftBytes, - chainCode: rightBytes, - }; + return `LSK_${version ? `${domain}:${version}` : domain}_`; }; -// eslint-disable-next-line no-bitwise -const flipBits = (buf: Buffer) => Buffer.from(buf.map(x => x ^ 0xff)); +export const tagMessage = ( + tag: string, + networkIdentifier: Buffer, + message: string | Buffer, +): Buffer => + Buffer.concat([ + Buffer.from(tag, 'utf8'), + networkIdentifier, + typeof message === 'string' ? Buffer.from(message, 'utf8') : message, + ]); + +export const BIG_ENDIAN = 'big'; +export const LITTLE_ENDIAN = 'little'; +const MAX_NUMBER_BYTE_LENGTH = 6; + +export const intToBuffer = ( + value: number | string, + byteLength: number, + endianness = BIG_ENDIAN, + signed = false, +): Buffer => { + if (![BIG_ENDIAN, LITTLE_ENDIAN].includes(endianness)) { + throw new Error(`Endianness must be either ${BIG_ENDIAN} or ${LITTLE_ENDIAN}`); + } + const buffer = Buffer.alloc(byteLength); + if (endianness === 'big') { + if (byteLength <= MAX_NUMBER_BYTE_LENGTH) { + if (signed) { + buffer.writeIntBE(Number(value), 0, byteLength); + } else { + buffer.writeUIntBE(Number(value), 0, byteLength); + } + } else { + // eslint-disable-next-line no-lonely-if + if (signed) { + buffer.writeBigInt64BE(BigInt(value)); + } else { + buffer.writeBigUInt64BE(BigInt(value)); + } + } + } else { + // eslint-disable-next-line no-lonely-if + if (byteLength <= MAX_NUMBER_BYTE_LENGTH) { + if (signed) { + buffer.writeIntLE(Number(value), 0, byteLength); + } else { + buffer.writeUIntLE(Number(value), 0, byteLength); + } + } else { + // eslint-disable-next-line no-lonely-if + if (signed) { + buffer.writeBigInt64LE(BigInt(value)); + } else { + buffer.writeBigUInt64LE(BigInt(value)); + } + } + } -const sha256 = (x: Buffer) => crypto.createHash(SHA256).update(x).digest(); + return buffer; +}; -const hmacSHA256 = (key: Buffer, message: Buffer, hash: string) => - crypto.createHmac(hash, key).update(message).digest(); +export const bufferToHex = (buffer: Buffer): string => Buffer.from(buffer).toString('hex'); -const hkdfSHA256 = (ikm: Buffer, length: number, salt: Buffer, info: Buffer) => { - if (salt.length === 0) { - // eslint-disable-next-line no-param-reassign - salt = EMPTY_SALT; +const hexRegex = /^[0-9a-f]+/i; +export const hexToBuffer = (hex: string, argumentName = 'Argument'): Buffer => { + if (typeof hex !== 'string') { + throw new TypeError(`${argumentName} must be a string.`); } - const PRK = hmacSHA256(salt, ikm, SHA256); - let t = Buffer.from([]); - let OKM = Buffer.from([]); - - for (let i = 0; i < Math.ceil(length / HASH_LENGTH); i += 1) { - t = hmacSHA256(PRK, Buffer.concat([t, info, Buffer.from([1 + i])]), SHA256); - OKM = Buffer.concat([OKM, t]); + // eslint-disable-next-line @typescript-eslint/prefer-regexp-exec + const matchedHex = (hex.match(hexRegex) ?? [])[0]; + if (!matchedHex || matchedHex.length !== hex.length) { + throw new TypeError(`${argumentName} must be a valid hex string.`); + } + if (matchedHex.length % 2 !== 0) { + throw new TypeError(`${argumentName} must have a valid length of hex string.`); } - return OKM.slice(0, length); + + return Buffer.from(matchedHex, 'hex'); }; -const toLamportSK = (IKM: Buffer, salt: Buffer) => { - const info = Buffer.from([]); - const OKM = hkdfSHA256(IKM, L, salt, info); +export const stringToBuffer = (str: string): Buffer => Buffer.from(str, 'utf8'); - const lamportSK = []; - for (let i = 0; i < 255; i += 1) { - lamportSK.push(OKM.slice(i * 32, (i + 1) * 32)); +const HASH_SIZE = 16; +const INPUT_SIZE = 64; +const defaultCount = 1000000; +const defaultDistance = 1000; + +export const generateHashOnionSeed = (): Buffer => + hash(getRandomBytes(INPUT_SIZE)).slice(0, HASH_SIZE); + +export const hashOnion = ( + seed: Buffer, + count: number = defaultCount, + distance: number = defaultDistance, +): ReadonlyArray => { + if (count < distance) { + throw new Error('Invalid count or distance. Count must be greater than distance'); } - return lamportSK; -}; -const parentSKToLamportPK = (parentSK: Buffer, index: number) => { - const salt = Buffer.allocUnsafe(4); - salt.writeUIntBE(index, 0, 4); + if (count % distance !== 0) { + throw new Error('Invalid count. Count must be multiple of distance'); + } - const IKM = parentSK; - const hashedLamport0 = toLamportSK(IKM, salt).map(x => sha256(x)); - const hashedLamport1 = toLamportSK(flipBits(IKM), salt).map(x => sha256(x)); + let previousHash = seed; + const hashes = [seed]; - const lamportPK = Buffer.concat(hashedLamport0.concat(hashedLamport1)); - return sha256(lamportPK); -}; + for (let i = 1; i <= count; i += 1) { + const nextHash = hash(previousHash).slice(0, HASH_SIZE); + if (i % distance === 0) { + hashes.push(nextHash); + } + previousHash = nextHash; + } -export const deriveChildSK = (parentSK: Buffer, index: number) => { - const lamportPK = parentSKToLamportPK(parentSK, index); - return blsKeyGen(lamportPK); + return hashes.reverse(); }; + +export { getRandomBytes }; From 2abd70a75ff8bb7509a19ae976b1c2daec1e25e9 Mon Sep 17 00:00:00 2001 From: shuse2 Date: Mon, 18 Jul 2022 11:34:10 +0200 Subject: [PATCH 2/6] :recycle: Update source code --- .../bootstrapping/commands/account/create.ts | 12 +- .../commands/account/validate.ts | 6 +- .../bootstrapping/commands/blskey/create.ts | 4 +- .../bootstrapping/commands/forging/config.ts | 6 +- .../commands/genesis-block/create.ts | 8 +- .../src/bootstrapping/commands/hash-onion.ts | 4 +- .../commands/passphrase/decrypt.ts | 6 +- .../commands/transaction/create.ts | 12 +- .../commands/transaction/sign.ts | 2 +- commander/src/commands/message/decrypt.ts | 4 +- commander/src/commands/message/encrypt.ts | 8 +- commander/src/commands/message/sign.ts | 4 +- commander/src/commands/message/verify.ts | 4 +- commander/src/commands/network-identifier.ts | 4 +- commander/src/utils/commons.ts | 8 +- commander/src/utils/genesis_creation.ts | 32 +-- commander/src/utils/transaction.ts | 2 +- .../commands/account/create.spec.ts | 36 +-- .../commands/blskey/create.spec.ts | 6 +- .../commands/transaction/create.spec.ts | 10 +- .../commands/transaction/get.spec.ts | 6 +- .../commands/transaction/send.spec.ts | 6 +- .../commands/transaction/sign.spec.ts | 30 +-- commander/test/helpers/account.ts | 6 +- commander/test/helpers/transactions.ts | 6 +- elements/lisk-api-client/src/codec.ts | 8 +- elements/lisk-api-client/src/transaction.ts | 9 +- .../lisk-api-client/test/unit/block.spec.ts | 14 +- .../test/unit/transaction.spec.ts | 8 +- .../lisk-api-client/test/utils/transaction.ts | 22 +- elements/lisk-chain/src/block_header.ts | 8 +- elements/lisk-chain/src/constants.ts | 8 +- .../lisk-chain/src/data_access/storage.ts | 8 +- elements/lisk-chain/src/event.ts | 4 +- elements/lisk-chain/src/state_store/utils.ts | 7 +- elements/lisk-chain/src/transaction.ts | 8 +- .../integration/data_access/blocks.spec.ts | 28 ++- elements/lisk-chain/test/unit/block.spec.ts | 42 ++-- .../lisk-chain/test/unit/block_assets.spec.ts | 156 ++++++------- .../lisk-chain/test/unit/block_header.spec.ts | 30 ++- elements/lisk-chain/test/unit/chain.spec.ts | 6 +- .../test/unit/data_access/data_access.spec.ts | 12 +- elements/lisk-chain/test/unit/event.spec.ts | 4 +- .../test/unit/state_store/state_store.spec.ts | 79 ++++--- .../lisk-chain/test/unit/transactions.spec.ts | 34 +-- elements/lisk-chain/test/utils/block.ts | 26 +-- elements/lisk-chain/test/utils/transaction.ts | 6 +- .../test/lisk-cryptography/buffer.spec.ts | 20 +- .../test/lisk-cryptography/keys.spec.ts | 4 +- elements/lisk-cryptography/benchmark/nacl.js | 4 +- .../lisk-cryptography/test/buffer.spec.ts | 20 +- .../lisk-cryptography/test/nacl/index.spec.ts | 8 +- .../lisk-cryptography/test/nacl/nacl.spec.ts | 2 +- elements/lisk-p2p/src/constants.ts | 4 +- elements/lisk-p2p/src/p2p.ts | 4 +- elements/lisk-p2p/src/utils/network.ts | 33 +-- .../src/transaction_pool.ts | 6 +- .../test/unit/transaction_pool.spec.ts | 45 ++-- .../test/utils/cryptography.ts | 2 +- elements/lisk-transactions/src/constants.ts | 4 +- elements/lisk-transactions/src/sign.ts | 30 +-- elements/lisk-transactions/test/fee.spec.ts | 20 +- elements/lisk-transactions/test/sign.spec.ts | 12 +- .../lisk-transactions/test/validate.spec.ts | 6 +- elements/lisk-tree/benchmark/merkle_root.js | 2 +- .../lisk-tree/src/merkle_tree/calculate.ts | 4 +- .../lisk-tree/src/merkle_tree/constants.ts | 4 +- .../lisk-tree/src/merkle_tree/merkle_tree.ts | 6 +- elements/lisk-tree/src/merkle_tree/utils.ts | 8 +- .../lisk-tree/src/merkle_tree/verify_proof.ts | 4 +- .../src/sparse_merkle_tree/branch.ts | 6 +- .../src/sparse_merkle_tree/constants.ts | 4 +- .../lisk-tree/src/sparse_merkle_tree/leaf.ts | 6 +- .../lisk-tree/src/sparse_merkle_tree/utils.ts | 8 +- .../test/sparse_merkle_tree/utils.spec.ts | 10 +- .../src/ui/pages/MainPage.tsx | 6 +- .../src/plugin/endpoint.ts | 13 +- .../src/plugin/faucet_plugin.ts | 5 +- .../src/ui/app.tsx | 8 +- .../src/forger_plugin.ts | 8 +- .../test/utils/accounts.ts | 6 +- .../test/utils/transactions.ts | 10 +- .../test/unit/blocks.spec.ts | 2 +- .../test/unit/forks.spec.ts | 2 +- .../src/db.ts | 4 +- .../src/endpoint.ts | 14 +- .../src/report_misbehavior_plugin.ts | 8 +- .../test/integration/cleanup_job.spec.ts | 6 +- .../test/unit/send_pom_transaction.spec.ts | 8 +- framework/src/abi_handler/abi_handler.ts | 4 +- framework/src/engine/bft/api.ts | 14 +- framework/src/engine/bft/bft_params.ts | 16 +- framework/src/engine/bft/constants.ts | 4 +- framework/src/engine/bft/utils.ts | 12 +- .../certificate_generation/commit_pool.ts | 4 +- .../consensus/certificate_generation/utils.ts | 8 +- framework/src/engine/consensus/consensus.ts | 4 +- framework/src/engine/consensus/constants.ts | 4 +- framework/src/engine/engine.ts | 4 +- framework/src/engine/generator/constants.ts | 6 +- framework/src/engine/generator/endpoint.ts | 31 ++- framework/src/engine/generator/generator.ts | 26 +-- framework/src/engine/generator/strategies.ts | 4 +- framework/src/engine/network/network.ts | 4 +- framework/src/genesis_block.ts | 10 +- framework/src/modules/auth/constants.ts | 4 +- framework/src/modules/auth/endpoint.ts | 6 +- framework/src/modules/auth/utils.ts | 6 +- framework/src/modules/dpos_v2/constants.ts | 4 +- framework/src/modules/dpos_v2/module.ts | 16 +- framework/src/modules/dpos_v2/utils.ts | 8 +- framework/src/modules/fee/module.ts | 6 +- .../base_interoperability_store.ts | 8 +- .../src/modules/interoperability/constants.ts | 31 +-- .../mainchain/commands/message_recovery.ts | 4 +- .../commands/sidechain_registration.ts | 16 +- .../mainchain/commands/state_recovery.ts | 4 +- .../mainchain/commands/state_recovery_init.ts | 8 +- .../commands/mainchain_registration.ts | 10 +- .../sidechain/commands/message_recovery.ts | 4 +- .../src/modules/interoperability/utils.ts | 12 +- framework/src/modules/random/constants.ts | 4 +- framework/src/modules/random/module.ts | 8 +- framework/src/modules/random/utils.ts | 12 +- framework/src/modules/reward/constants.ts | 11 +- framework/src/modules/reward/module.ts | 4 +- framework/src/modules/token/constants.ts | 13 +- framework/src/modules/token/utils.ts | 4 +- framework/src/modules/validators/api.ts | 6 +- framework/src/modules/validators/endpoint.ts | 6 +- framework/src/modules/validators/module.ts | 4 +- framework/src/testing/block_processing_env.ts | 6 +- framework/src/testing/create_block.ts | 31 ++- framework/src/testing/create_contexts.ts | 50 ++-- framework/src/testing/create_transaction.ts | 6 +- framework/src/testing/fixtures/config.ts | 17 +- .../src/testing/fixtures/genesis-asset.ts | 6 +- framework/src/testing/utils.ts | 4 +- framework/test/fixtures/blocks.ts | 38 +-- .../banning/invalid_block_property.spec.ts | 4 +- .../test/functional/network/blocks.spec.ts | 6 +- .../functional/network/transactions.spec.ts | 4 +- .../node/processor/delete_block.spec.ts | 12 +- .../testing/block_processing_env.spec.ts | 2 +- .../test/unit/abi_handler/abi_handler.spec.ts | 180 +++++++-------- .../commit_list.spec.ts | 30 +-- .../commit_pool.spec.ts | 142 ++++++------ .../certificate_generation/utils.spec.ts | 24 +- .../unit/engine/consensus/consensus.spec.ts | 30 +-- .../engine/consensus/network_endpoint.spec.ts | 18 +- .../block_synchronization_mechanism.spec.ts | 2 +- .../fast_chain_switching_mechanism.spec.ts | 22 +- .../test/unit/engine/endpoint/chain.spec.ts | 16 +- .../test/unit/engine/endpoint/system.spec.ts | 2 +- .../test/unit/engine/endpoint/txpool.spec.ts | 6 +- .../unit/engine/generator/broadcaster.spec.ts | 12 +- .../unit/engine/generator/endpoint.spec.ts | 2 +- .../unit/engine/generator/generator.spec.ts | 34 +-- .../engine/generator/network_endpoint.spec.ts | 10 +- .../unit/engine/generator/strategies.spec.ts | 14 +- .../test/unit/engine/network/network.spec.ts | 4 +- framework/test/unit/modules/auth/api.spec.ts | 6 +- .../unit/modules/auth/auth_module.spec.ts | 96 ++++---- .../test/unit/modules/auth/endpoint.spec.ts | 48 ++-- .../auth/register_multisignature.spec.ts | 26 +-- framework/test/unit/modules/bft/api.spec.ts | 216 ++++++++++-------- .../test/unit/modules/bft/bft_params.spec.ts | 58 ++--- .../unit/modules/bft/bft_processing.spec.ts | 10 +- .../test/unit/modules/bft/bft_votes.spec.ts | 20 +- framework/test/unit/modules/bft/utils.spec.ts | 4 +- .../test/unit/modules/dpos_v2/api.spec.ts | 6 +- .../commands/delegate_registration.spec.ts | 24 +- .../unit/modules/dpos_v2/commands/pom.spec.ts | 20 +- .../modules/dpos_v2/commands/unlock.spec.ts | 28 ++- .../modules/dpos_v2/commands/vote.spec.ts | 60 ++--- .../unit/modules/dpos_v2/endpoint.spec.ts | 10 +- .../dpos_v2/genesis_block_test_data.ts | 2 +- .../test/unit/modules/dpos_v2/module.spec.ts | 32 +-- .../dpos_v2/update_generator_key.spec.ts | 10 +- .../test/unit/modules/fee/fee_module.spec.ts | 62 ++--- .../interoperability/mainchain/api.spec.ts | 6 +- .../cc_commands/channel_terminated.spec.ts | 10 +- .../cc_commands/registration.spec.ts | 54 ++--- .../cc_commands/sidechain_terminated.spec.ts | 14 +- .../mainchain/commands/cc_update.spec.ts | 86 +++---- .../commands/message_recovery.spec.ts | 88 +++---- .../commands/sidechain_registration.spec.ts | 22 +- .../mainchain/commands/state_recovery.spec.ts | 20 +- .../commands/state_recovery_init.spec.ts | 22 +- .../interoperability/mainchain/store.spec.ts | 58 ++--- .../interoperability/sidechain/api.spec.ts | 6 +- .../cc_commands/channel_terminated.spec.ts | 10 +- .../cc_commands/registration.spec.ts | 46 ++-- .../cc_commands/sidechain_terminated.spec.ts | 14 +- .../sidechain/commands/cc_update.spec.ts | 82 +++---- .../commands/mainchain_registration.spec.ts | 44 ++-- .../commands/message_recovery.spec.ts | 36 +-- .../interoperability/sidechain/store.spec.ts | 40 ++-- .../modules/interoperability/store.spec.ts | 68 +++--- .../modules/interoperability/utils.spec.ts | 124 +++++----- .../test/unit/modules/random/api.spec.ts | 30 +-- .../unit/modules/random/random_module.spec.ts | 46 ++-- .../test/unit/modules/reward/api.spec.ts | 4 +- .../test/unit/modules/reward/endpoint.spec.ts | 4 +- .../unit/modules/reward/reward_module.spec.ts | 4 +- framework/test/unit/modules/token/api.spec.ts | 57 +++-- .../token/cc_commands/cc_forward.spec.ts | 36 +-- .../token/cc_commands/cc_transfer.spec.ts | 32 +-- .../modules/token/commands/transfer.spec.ts | 48 ++-- .../test/unit/modules/token/endpoint.spec.ts | 8 +- .../token/init_genesis_state_fixture.ts | 36 +-- .../modules/token/interoperable_api.spec.ts | 92 ++++---- .../test/unit/modules/validators/api.spec.ts | 20 +- .../unit/modules/validators/endpoint.spec.ts | 6 +- .../test/unit/state_machine/custom_modules.ts | 18 +- .../unit/state_machine/event_queue.spec.ts | 55 +++-- .../unit/state_machine/state_machine.spec.ts | 10 +- .../test/unit/testing/create_block.spec.ts | 2 +- .../test/utils/configs/config_constants.ts | 6 +- framework/test/utils/mocks/endpoint.ts | 2 +- framework/test/utils/mocks/transaction.ts | 24 +- .../generators/address_generation/index.js | 2 +- .../dpos_delegate_shuffling/index.js | 2 +- .../sample_generator.js | 2 +- .../dpos_forger_selection/sample_generator.js | 2 +- .../dpos_random_seed_generation/index.js | 4 +- .../multisignature_registration/index.js | 20 +- .../proof_of_misbehavior_transaction/index.js | 12 +- .../index.js | 12 +- 229 files changed, 2271 insertions(+), 2166 deletions(-) diff --git a/commander/src/bootstrapping/commands/account/create.ts b/commander/src/bootstrapping/commands/account/create.ts index d90a4a5dd64..ee640eae7b9 100644 --- a/commander/src/bootstrapping/commands/account/create.ts +++ b/commander/src/bootstrapping/commands/account/create.ts @@ -30,11 +30,13 @@ interface AccountInfo { const createAccount = (prefix: string): AccountInfo => { const generatedPassphrase = passphrase.Mnemonic.generateMnemonic(); - const { privateKey, publicKey } = cryptography.getKeys(generatedPassphrase); - const blsPrivateKey = cryptography.generatePrivateKey(Buffer.from(generatedPassphrase, 'utf-8')); - const blsPublicKey = cryptography.getPublicKeyFromPrivateKey(blsPrivateKey); - const binaryAddress = cryptography.getAddressFromPublicKey(publicKey); - const address = cryptography.getLisk32AddressFromPublicKey(publicKey, prefix); + const { privateKey, publicKey } = cryptography.address.getKeys(generatedPassphrase); + const blsPrivateKey = cryptography.bls.generatePrivateKey( + Buffer.from(generatedPassphrase, 'utf-8'), + ); + const blsPublicKey = cryptography.bls.getPublicKeyFromPrivateKey(blsPrivateKey); + const binaryAddress = cryptography.address.getAddressFromPublicKey(publicKey); + const address = cryptography.address.getLisk32AddressFromPublicKey(publicKey, prefix); return { passphrase: generatedPassphrase, diff --git a/commander/src/bootstrapping/commands/account/validate.ts b/commander/src/bootstrapping/commands/account/validate.ts index e18b301478a..d5ef70698e4 100644 --- a/commander/src/bootstrapping/commands/account/validate.ts +++ b/commander/src/bootstrapping/commands/account/validate.ts @@ -39,8 +39,10 @@ export class ValidateCommand extends Command { try { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - cryptography.validateLisk32Address(address, this.config.pjson.lisk.addressPrefix); - const binaryAddress = cryptography.getAddressFromLisk32Address(address).toString('hex'); + cryptography.address.validateLisk32Address(address, this.config.pjson.lisk.addressPrefix); + const binaryAddress = cryptography.address + .getAddressFromLisk32Address(address) + .toString('hex'); // eslint-disable-next-line @typescript-eslint/restrict-template-expressions this.log( diff --git a/commander/src/bootstrapping/commands/blskey/create.ts b/commander/src/bootstrapping/commands/blskey/create.ts index ae9ac9de23a..2ab98beb8ba 100644 --- a/commander/src/bootstrapping/commands/blskey/create.ts +++ b/commander/src/bootstrapping/commands/blskey/create.ts @@ -25,8 +25,8 @@ interface BlsKey { } const createBlsKey = (passphrase: string): BlsKey => { - const blsPrivateKey = cryptography.generatePrivateKey(Buffer.from(passphrase, 'utf-8')); - const blsPublicKey = cryptography.getPublicKeyFromPrivateKey(blsPrivateKey); + const blsPrivateKey = cryptography.bls.generatePrivateKey(Buffer.from(passphrase, 'utf-8')); + const blsPublicKey = cryptography.bls.getPublicKeyFromPrivateKey(blsPrivateKey); return { blsPrivateKey: blsPrivateKey.toString('hex'), diff --git a/commander/src/bootstrapping/commands/forging/config.ts b/commander/src/bootstrapping/commands/forging/config.ts index 7289247d96b..0a06d91baad 100644 --- a/commander/src/bootstrapping/commands/forging/config.ts +++ b/commander/src/bootstrapping/commands/forging/config.ts @@ -74,14 +74,14 @@ export class ConfigCommand extends Command { fs.ensureDirSync(dir); } - const seed = cryptography.generateHashOnionSeed(); + const seed = cryptography.utils.generateHashOnionSeed(); - const hashBuffers = cryptography.hashOnion(seed, count, distance); + const hashBuffers = cryptography.utils.hashOnion(seed, count, distance); const hashes = hashBuffers.map(buf => buf.toString('hex')); const hashOnion = { count, distance, hashes }; const passphrase = passphraseSource ?? (await getPassphraseFromPrompt('passphrase', true)); - const address = cryptography.getAddressFromPassphrase(passphrase).toString('hex'); + const address = cryptography.address.getAddressFromPassphrase(passphrase).toString('hex'); const password = passwordSource ?? (await getPasswordFromPrompt('password', true)); const { encryptedPassphrase } = await encryptPassphrase(passphrase, password, false); const message = { address, encryptedPassphrase, hashOnion }; diff --git a/commander/src/bootstrapping/commands/genesis-block/create.ts b/commander/src/bootstrapping/commands/genesis-block/create.ts index 46ece5b646d..7dfdc8cf50d 100644 --- a/commander/src/bootstrapping/commands/genesis-block/create.ts +++ b/commander/src/bootstrapping/commands/genesis-block/create.ts @@ -229,22 +229,22 @@ export abstract class BaseGenesisBlockCommand extends Command { width: 20, total: validators - 1, }); - const onionSeed = cryptography.generateHashOnionSeed(); + const onionSeed = cryptography.utils.generateHashOnionSeed(); const password = createMnemonicPassphrase(); const passwordList = { defaultPassword: password }; const generatorInfo = validatorList.map(async (val, index) => { - const encryptedPassphrase = await cryptography.encryptPassphraseWithPassword( + const encryptedPassphrase = await cryptography.encrypt.encryptPassphraseWithPassword( val.passphrase, password, { kdfparams: { iterations: validatorsPassphraseEncryptionIterations } }, ); const info = { // TODO: use a better password, user sourced using flag - encryptedPassphrase: cryptography.stringifyEncryptedPassphrase(encryptedPassphrase), + encryptedPassphrase: cryptography.encrypt.stringifyEncryptedPassphrase(encryptedPassphrase), hashOnion: { count: validatorsHashOnionCount, distance: validatorsHashOnionDistance, - hashes: cryptography + hashes: cryptography.utils .hashOnion(onionSeed, validatorsHashOnionCount, validatorsHashOnionDistance) .map(buf => buf.toString('hex')), }, diff --git a/commander/src/bootstrapping/commands/hash-onion.ts b/commander/src/bootstrapping/commands/hash-onion.ts index ba66e53a9c9..230e0fdf074 100644 --- a/commander/src/bootstrapping/commands/hash-onion.ts +++ b/commander/src/bootstrapping/commands/hash-onion.ts @@ -64,9 +64,9 @@ export class HashOnionCommand extends Command { fs.ensureDirSync(dir); } - const seed = cryptography.generateHashOnionSeed(); + const seed = cryptography.utils.generateHashOnionSeed(); - const hashBuffers = cryptography.hashOnion(seed, count, distance); + const hashBuffers = cryptography.utils.hashOnion(seed, count, distance); const hashes = hashBuffers.map(buf => buf.toString('hex')); const result = { count, distance, hashes }; diff --git a/commander/src/bootstrapping/commands/passphrase/decrypt.ts b/commander/src/bootstrapping/commands/passphrase/decrypt.ts index 0faf53d292d..ecff9dc7c3f 100644 --- a/commander/src/bootstrapping/commands/passphrase/decrypt.ts +++ b/commander/src/bootstrapping/commands/passphrase/decrypt.ts @@ -25,8 +25,10 @@ const processInputs = async ( password: string, encryptedPassphrase: string, ): Promise> => { - const encryptedPassphraseObject = cryptography.parseEncryptedPassphrase(encryptedPassphrase); - const passphrase = await cryptography.decryptPassphraseWithPassword( + const encryptedPassphraseObject = cryptography.encrypt.parseEncryptedPassphrase( + encryptedPassphrase, + ); + const passphrase = await cryptography.encrypt.decryptPassphraseWithPassword( encryptedPassphraseObject as never, password, ); diff --git a/commander/src/bootstrapping/commands/transaction/create.ts b/commander/src/bootstrapping/commands/transaction/create.ts index 0a8d649b3e4..fa26da9fd20 100644 --- a/commander/src/bootstrapping/commands/transaction/create.ts +++ b/commander/src/bootstrapping/commands/transaction/create.ts @@ -71,8 +71,8 @@ interface Transaction { const getParamsObject = async (metadata: ModuleMetadataJSON[], flags: CreateFlags, args: Args) => { const paramsSchema = getParamsSchema( metadata, - cryptography.intToBuffer(args.moduleID, 4).toString('hex'), - cryptography.intToBuffer(args.commandID, 4).toString('hex'), + cryptography.utils.intToBuffer(args.moduleID, 4).toString('hex'), + cryptography.utils.intToBuffer(args.commandID, 4).toString('hex'), ) as Schema; const params = flags.params ? JSON.parse(flags.params) : await getParamsFromPrompt(paramsSchema); @@ -86,11 +86,11 @@ const getPassphraseAddressAndPublicKey = async (flags: CreateFlags) => { if (flags['no-signature']) { publicKey = Buffer.from(flags['sender-public-key'] as string, 'hex'); - address = cryptography.getAddressFromPublicKey(publicKey); + address = cryptography.address.getAddressFromPublicKey(publicKey); passphrase = ''; } else { passphrase = flags.passphrase ?? (await getPassphraseFromPrompt('passphrase', true)); - const result = cryptography.getAddressAndPublicKeyFromPassphrase(passphrase); + const result = cryptography.address.getAddressAndPublicKeyFromPassphrase(passphrase); publicKey = result.publicKey; address = result.address; } @@ -271,8 +271,8 @@ export abstract class CreateCommand extends Command { const { args, flags } = this.parse(CreateCommand); const incompleteTransaction = { - moduleID: cryptography.intToBuffer(args.moduleID, 4).toString('hex'), - commandID: cryptography.intToBuffer(args.commandID, 4).toString('hex'), + moduleID: cryptography.utils.intToBuffer(args.moduleID, 4).toString('hex'), + commandID: cryptography.utils.intToBuffer(args.commandID, 4).toString('hex'), fee: args.fee, nonce: '0', senderPublicKey: '', diff --git a/commander/src/bootstrapping/commands/transaction/sign.ts b/commander/src/bootstrapping/commands/transaction/sign.ts index 3c74cba02a9..d780ef88f32 100644 --- a/commander/src/bootstrapping/commands/transaction/sign.ts +++ b/commander/src/bootstrapping/commands/transaction/sign.ts @@ -165,7 +165,7 @@ const signTransactionOnline = async ( // Sign non multi-sig transaction const transactionObject = decodeTransaction(registeredSchema, metadata, transactionHexStr); const passphrase = flags.passphrase ?? (await getPassphraseFromPrompt('passphrase', true)); - const address = cryptography.getAddressFromPassphrase(passphrase); + const address = cryptography.address.getAddressFromPassphrase(passphrase); let signedTransaction: Record; diff --git a/commander/src/commands/message/decrypt.ts b/commander/src/commands/message/decrypt.ts index c71d82a521b..194b783f94e 100644 --- a/commander/src/commands/message/decrypt.ts +++ b/commander/src/commands/message/decrypt.ts @@ -13,7 +13,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { decryptMessageWithPassphrase } from '@liskhq/lisk-cryptography'; +import { encrypt } from '@liskhq/lisk-cryptography'; import { flags as flagParser } from '@oclif/command'; import BaseCommand from '../../base'; @@ -37,7 +37,7 @@ const processInputs = ( throw new ValidationError('No message was provided.'); } - return decryptMessageWithPassphrase( + return encrypt.decryptMessageWithPassphrase( message, nonce, passphrase, diff --git a/commander/src/commands/message/encrypt.ts b/commander/src/commands/message/encrypt.ts index ab6c0985b63..75096bcead1 100644 --- a/commander/src/commands/message/encrypt.ts +++ b/commander/src/commands/message/encrypt.ts @@ -13,7 +13,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { encryptMessageWithPassphrase } from '@liskhq/lisk-cryptography'; +import { encrypt } from '@liskhq/lisk-cryptography'; import { flags as flagParser } from '@oclif/command'; import BaseCommand from '../../base'; @@ -32,7 +32,11 @@ const processInputs = (recipientPublicKey: string, passphrase: string, message?: } return { - ...encryptMessageWithPassphrase(message, passphrase, Buffer.from(recipientPublicKey, 'hex')), + ...encrypt.encryptMessageWithPassphrase( + message, + passphrase, + Buffer.from(recipientPublicKey, 'hex'), + ), recipientPublicKey, }; }; diff --git a/commander/src/commands/message/sign.ts b/commander/src/commands/message/sign.ts index 0eb9579cd4e..36c605b9916 100644 --- a/commander/src/commands/message/sign.ts +++ b/commander/src/commands/message/sign.ts @@ -13,7 +13,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { signMessageWithPassphrase } from '@liskhq/lisk-cryptography'; +import { ed } from '@liskhq/lisk-cryptography'; import { flags as flagParser } from '@oclif/command'; import BaseCommand from '../../base'; @@ -30,7 +30,7 @@ const processInputs = (passphrase: string, message?: string) => { throw new ValidationError('No message was provided.'); } - const signedMessageWithOnePassphrase = signMessageWithPassphrase(message, passphrase); + const signedMessageWithOnePassphrase = ed.signMessageWithPassphrase(message, passphrase); return { ...signedMessageWithOnePassphrase, publicKey: signedMessageWithOnePassphrase.publicKey.toString('hex'), diff --git a/commander/src/commands/message/verify.ts b/commander/src/commands/message/verify.ts index 5fadd8105c9..1f8b59cc893 100644 --- a/commander/src/commands/message/verify.ts +++ b/commander/src/commands/message/verify.ts @@ -13,7 +13,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { verifyMessageWithPublicKey } from '@liskhq/lisk-cryptography'; +import { ed } from '@liskhq/lisk-cryptography'; import { flags as flagParser } from '@oclif/command'; import BaseCommand from '../../base'; @@ -33,7 +33,7 @@ const processInputs = (publicKey: string, signature: string, message?: string) = } return { - verified: verifyMessageWithPublicKey({ + verified: ed.verifyMessageWithPublicKey({ publicKey: Buffer.from(publicKey, 'hex'), signature: Buffer.from(signature, 'hex'), message, diff --git a/commander/src/commands/network-identifier.ts b/commander/src/commands/network-identifier.ts index 9c3b9cbd981..ffdfb081cf9 100644 --- a/commander/src/commands/network-identifier.ts +++ b/commander/src/commands/network-identifier.ts @@ -13,7 +13,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { getNetworkIdentifier } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { flags as flagParser } from '@oclif/command'; import BaseCommand from '../base'; @@ -49,7 +49,7 @@ export default class NetworkIdentifierCommand extends BaseCommand { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment args: { genesisBlockID }, } = this.parse(NetworkIdentifierCommand); - const networkIdentifier = getNetworkIdentifier( + const networkIdentifier = utils.getNetworkIdentifier( Buffer.from(genesisBlockID, 'hex'), communityIdentifier, ); diff --git a/commander/src/utils/commons.ts b/commander/src/utils/commons.ts index c9152a89e91..58a7ed0ac7f 100644 --- a/commander/src/utils/commons.ts +++ b/commander/src/utils/commons.ts @@ -31,16 +31,18 @@ export const encryptPassphrase = async ( password: string, outputPublicKey: boolean, ): Promise> => { - const encryptedPassphraseObject = await cryptography.encryptPassphraseWithPassword( + const encryptedPassphraseObject = await cryptography.encrypt.encryptPassphraseWithPassword( passphrase, password, ); - const encryptedPassphrase = cryptography.stringifyEncryptedPassphrase(encryptedPassphraseObject); + const encryptedPassphrase = cryptography.encrypt.stringifyEncryptedPassphrase( + encryptedPassphraseObject, + ); return outputPublicKey ? { encryptedPassphrase, - publicKey: cryptography.getKeys(passphrase).publicKey.toString('hex'), + publicKey: cryptography.address.getKeys(passphrase).publicKey.toString('hex'), } : { encryptedPassphrase }; }; diff --git a/commander/src/utils/genesis_creation.ts b/commander/src/utils/genesis_creation.ts index 9dee0608550..cfe381f8240 100644 --- a/commander/src/utils/genesis_creation.ts +++ b/commander/src/utils/genesis_creation.ts @@ -15,15 +15,7 @@ */ import { Mnemonic } from '@liskhq/lisk-passphrase'; import { Schema } from '@liskhq/lisk-codec'; -import { - generatePrivateKey, - getAddressFromPublicKey, - getKeys, - getLisk32AddressFromPublicKey, - getPublicKeyFromPrivateKey, - blsPopProve, - intToBuffer, -} from '@liskhq/lisk-cryptography'; +import { bls, address, utils } from '@liskhq/lisk-cryptography'; import { dposGenesisStoreSchema, DPoSModule, @@ -73,22 +65,22 @@ export const generateGenesisBlockDefaultDPoSAssets = (input: GenesisBlockDefault const accountList = []; for (let i = 0; i < input.numberOfAccounts; i += 1) { const passphrase = Mnemonic.generateMnemonic(256); - const keys = getKeys(passphrase); + const keys = address.getKeys(passphrase); accountList.push({ publicKey: keys.publicKey, privateKey: keys.privateKey, passphrase, - address: getAddressFromPublicKey(keys.publicKey), - lisk32Address: getLisk32AddressFromPublicKey(keys.publicKey), + address: address.getAddressFromPublicKey(keys.publicKey), + lisk32Address: address.getLisk32AddressFromPublicKey(keys.publicKey), }); } const validatorList = []; for (let i = 0; i < input.numberOfValidators; i += 1) { const passphrase = Mnemonic.generateMnemonic(256); - const keys = getKeys(passphrase); - const blsPrivateKey = generatePrivateKey(Buffer.from(passphrase, 'utf-8')); - const blsPublicKey = getPublicKeyFromPrivateKey(blsPrivateKey); - const blsPoP = blsPopProve(blsPrivateKey); + const keys = address.getKeys(passphrase); + const blsPrivateKey = bls.generatePrivateKey(Buffer.from(passphrase, 'utf-8')); + const blsPublicKey = bls.getPublicKeyFromPrivateKey(blsPrivateKey); + const blsPoP = bls.popProve(blsPrivateKey); validatorList.push({ publicKey: keys.publicKey, name: `genesis_${i}`, @@ -97,8 +89,8 @@ export const generateGenesisBlockDefaultDPoSAssets = (input: GenesisBlockDefault blsPrivateKey, blsPoP, passphrase, - address: getAddressFromPublicKey(keys.publicKey), - lisk32Address: getLisk32AddressFromPublicKey(keys.publicKey), + address: address.getAddressFromPublicKey(keys.publicKey), + lisk32Address: address.getLisk32AddressFromPublicKey(keys.publicKey), }); } @@ -109,8 +101,8 @@ export const generateGenesisBlockDefaultDPoSAssets = (input: GenesisBlockDefault userSubstore: accountList.map(a => ({ address: a.address, tokenID: { - chainID: intToBuffer(0, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(0, 4), + localID: utils.intToBuffer(0, 4), }, availableBalance: BigInt(input.tokenDistribution), lockedBalances: [], diff --git a/commander/src/utils/transaction.ts b/commander/src/utils/transaction.ts index 16fa939fb3d..df125a91188 100644 --- a/commander/src/utils/transaction.ts +++ b/commander/src/utils/transaction.ts @@ -44,7 +44,7 @@ export const decodeTransaction = ( transactionHexStr: string, ) => { const transactionBytes = Buffer.from(transactionHexStr, 'hex'); - const id = cryptography.hash(transactionBytes); + const id = cryptography.utils.hash(transactionBytes); const transaction = codec.decodeJSON(schema.transaction, transactionBytes); const paramsSchema = getParamsSchema(metadata, transaction.moduleID, transaction.commandID); const params = codec.decodeJSON>( diff --git a/commander/test/bootstrapping/commands/account/create.spec.ts b/commander/test/bootstrapping/commands/account/create.spec.ts index 56ec4bce4e9..a6ae951b818 100644 --- a/commander/test/bootstrapping/commands/account/create.spec.ts +++ b/commander/test/bootstrapping/commands/account/create.spec.ts @@ -47,15 +47,17 @@ describe('account:create', () => { await CreateCommand.run([], config); expect(JSON.parse(results[0])).toEqual([ { - publicKey: cryptography.getKeys(defaultMnemonic).publicKey.toString('hex'), - privateKey: cryptography.getKeys(defaultMnemonic).privateKey.toString('hex'), - blsPublicKey: cryptography.getPublicKeyFromPrivateKey(blsPrivateKey).toString('hex'), + publicKey: cryptography.utils.getKeys(defaultMnemonic).publicKey.toString('hex'), + privateKey: cryptography.utils.getKeys(defaultMnemonic).privateKey.toString('hex'), + blsPublicKey: cryptography.ed.getPublicKeyFromPrivateKey(blsPrivateKey).toString('hex'), blsPrivateKey: blsPrivateKey.toString('hex'), - address: cryptography.getLisk32AddressFromPublicKey( - cryptography.getKeys(defaultMnemonic).publicKey, + address: cryptography.address.getLisk32AddressFromPublicKey( + cryptography.utils.getKeys(defaultMnemonic).publicKey, 'lsk', ), - binaryAddress: cryptography.getAddressFromPassphrase(defaultMnemonic).toString('hex'), + binaryAddress: cryptography.address + .getAddressFromPassphrase(defaultMnemonic) + .toString('hex'), passphrase: defaultMnemonic, }, ]); @@ -68,26 +70,28 @@ describe('account:create', () => { await CreateCommand.run(['--count', defaultNumber.toString()], config); const result = [ { - publicKey: cryptography.getKeys(defaultMnemonic).publicKey.toString('hex'), - privateKey: cryptography.getKeys(defaultMnemonic).privateKey.toString('hex'), - blsPublicKey: cryptography.getPublicKeyFromPrivateKey(blsPrivateKey).toString('hex'), + publicKey: cryptography.utils.getKeys(defaultMnemonic).publicKey.toString('hex'), + privateKey: cryptography.utils.getKeys(defaultMnemonic).privateKey.toString('hex'), + blsPublicKey: cryptography.ed.getPublicKeyFromPrivateKey(blsPrivateKey).toString('hex'), blsPrivateKey: blsPrivateKey.toString('hex'), - address: cryptography.getLisk32AddressFromPublicKey( - cryptography.getKeys(defaultMnemonic).publicKey, + address: cryptography.address.getLisk32AddressFromPublicKey( + cryptography.utils.getKeys(defaultMnemonic).publicKey, 'lsk', ), - binaryAddress: cryptography.getAddressFromPassphrase(defaultMnemonic).toString('hex'), + binaryAddress: cryptography.address + .getAddressFromPassphrase(defaultMnemonic) + .toString('hex'), passphrase: defaultMnemonic, }, { - publicKey: cryptography.getKeys(secondDefaultMnemonic).publicKey.toString('hex'), - privateKey: cryptography.getKeys(secondDefaultMnemonic).privateKey.toString('hex'), + publicKey: cryptography.utils.getKeys(secondDefaultMnemonic).publicKey.toString('hex'), + privateKey: cryptography.utils.getKeys(secondDefaultMnemonic).privateKey.toString('hex'), blsPublicKey: cryptography .getPublicKeyFromPrivateKey(secondBlsPrivateKey) .toString('hex'), blsPrivateKey: secondBlsPrivateKey.toString('hex'), - address: cryptography.getLisk32AddressFromPublicKey( - cryptography.getKeys(secondDefaultMnemonic).publicKey, + address: cryptography.address.getLisk32AddressFromPublicKey( + cryptography.utils.getKeys(secondDefaultMnemonic).publicKey, 'lsk', ), binaryAddress: cryptography diff --git a/commander/test/bootstrapping/commands/blskey/create.spec.ts b/commander/test/bootstrapping/commands/blskey/create.spec.ts index a08ed5f8de2..d82e2ea6ade 100644 --- a/commander/test/bootstrapping/commands/blskey/create.spec.ts +++ b/commander/test/bootstrapping/commands/blskey/create.spec.ts @@ -30,7 +30,7 @@ describe('passphrase:encrypt', () => { const defaultBlsPrivateKey = cryptography.generatePrivateKey( Buffer.from(defaultPassphrase, 'utf-8'), ); - const defaultBlsPublicKey = cryptography.getPublicKeyFromPrivateKey(defaultBlsPrivateKey); + const defaultBlsPublicKey = cryptography.ed.getPublicKeyFromPrivateKey(defaultBlsPrivateKey); const consoleWarnSpy = jest.spyOn(console, 'warn'); let stdout: string[]; @@ -60,7 +60,7 @@ describe('passphrase:encrypt', () => { expect(cryptography.generatePrivateKey).toHaveBeenCalledWith( Buffer.from(defaultPassphrase, 'utf-8'), ); - expect(cryptography.getPublicKeyFromPrivateKey).toHaveBeenCalledWith(defaultBlsPrivateKey); + expect(cryptography.ed.getPublicKeyFromPrivateKey).toHaveBeenCalledWith(defaultBlsPrivateKey); expect(readerUtils.getPassphraseFromPrompt).toHaveBeenCalledWith('passphrase', true); expect(CreateCommand.prototype.printJSON).toHaveBeenCalledWith( @@ -83,7 +83,7 @@ describe('passphrase:encrypt', () => { expect(cryptography.generatePrivateKey).toHaveBeenCalledWith( Buffer.from(defaultPassphrase, 'utf-8'), ); - expect(cryptography.getPublicKeyFromPrivateKey).toHaveBeenCalledWith(defaultBlsPrivateKey); + expect(cryptography.ed.getPublicKeyFromPrivateKey).toHaveBeenCalledWith(defaultBlsPrivateKey); expect(readerUtils.getPassphraseFromPrompt).not.toHaveBeenCalledWith('passphrase', true); expect(CreateCommand.prototype.printJSON).toHaveBeenCalledWith( diff --git a/commander/test/bootstrapping/commands/transaction/create.spec.ts b/commander/test/bootstrapping/commands/transaction/create.spec.ts index 71f109c2461..95f65bbca76 100644 --- a/commander/test/bootstrapping/commands/transaction/create.spec.ts +++ b/commander/test/bootstrapping/commands/transaction/create.spec.ts @@ -35,7 +35,7 @@ describe('transaction:create command', () => { '{"votes":[{"delegateAddress":"ab0041a7d3f7b2c290b5b834d46bdc7b7eb85815","amount":100},{"delegateAddress":"ab0041a7d3f7b2c290b5b834d46bdc7b7eb85815","amount":-50}]}'; const unVoteParams = '{"votes":[{"delegateAddress":"ab0041a7d3f7b2c290b5b834d46bdc7b7eb85815","amount":-50}]}'; - const { publicKey } = cryptography.getAddressAndPublicKeyFromPassphrase(passphrase); + const { publicKey } = cryptography.address.getAddressAndPublicKeyFromPassphrase(passphrase); const senderPublicKey = publicKey.toString('hex'); const mockEncodedTransaction = Buffer.from('encoded transaction'); const mockJSONTransaction = { @@ -84,19 +84,19 @@ describe('transaction:create command', () => { }, metadata: [ { - id: cryptography.intToBuffer(2, 4).toString('hex'), + id: cryptography.utils.intToBuffer(2, 4).toString('hex'), commands: [ { - id: cryptography.intToBuffer(0, 4).toString('hex'), + id: cryptography.utils.intToBuffer(0, 4).toString('hex'), params: tokenTransferParamsSchema, }, ], }, { - id: cryptography.intToBuffer(13, 4).toString('hex'), + id: cryptography.utils.intToBuffer(13, 4).toString('hex'), commands: [ { - id: cryptography.intToBuffer(1, 4).toString('hex'), + id: cryptography.utils.intToBuffer(1, 4).toString('hex'), params: dposVoteParamsSchema, }, ], diff --git a/commander/test/bootstrapping/commands/transaction/get.spec.ts b/commander/test/bootstrapping/commands/transaction/get.spec.ts index 337fccd569a..d0bf45b704a 100644 --- a/commander/test/bootstrapping/commands/transaction/get.spec.ts +++ b/commander/test/bootstrapping/commands/transaction/get.spec.ts @@ -13,7 +13,7 @@ * */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import * as fs from 'fs-extra'; import { transactionSchema } from 'lisk-framework'; import * as apiClient from '@liskhq/lisk-api-client'; @@ -32,8 +32,8 @@ import { getConfig } from '../../../helpers/config'; describe('transaction:get command', () => { const commands = [ { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), schema: tokenTransferParamsSchema, }, ]; diff --git a/commander/test/bootstrapping/commands/transaction/send.spec.ts b/commander/test/bootstrapping/commands/transaction/send.spec.ts index 9cbfd875b81..e3268a4c07f 100644 --- a/commander/test/bootstrapping/commands/transaction/send.spec.ts +++ b/commander/test/bootstrapping/commands/transaction/send.spec.ts @@ -13,7 +13,7 @@ * */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import * as fs from 'fs-extra'; import { join } from 'path'; import { transactionSchema } from 'lisk-framework'; @@ -33,8 +33,8 @@ import { getConfig } from '../../../helpers/config'; describe('transaction:send command', () => { const transactionsAssetSchemas = [ { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), schema: tokenTransferParamsSchema, }, ]; diff --git a/commander/test/bootstrapping/commands/transaction/sign.spec.ts b/commander/test/bootstrapping/commands/transaction/sign.spec.ts index b978eb4990c..907c67599d4 100644 --- a/commander/test/bootstrapping/commands/transaction/sign.spec.ts +++ b/commander/test/bootstrapping/commands/transaction/sign.spec.ts @@ -14,7 +14,7 @@ */ import * as fs from 'fs-extra'; -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Application, IPCChannel, transactionSchema } from 'lisk-framework'; import * as apiClient from '@liskhq/lisk-api-client'; import { codec } from '@liskhq/lisk-codec'; @@ -34,18 +34,18 @@ import { getConfig } from '../../../helpers/config'; describe('transaction:sign command', () => { const commands = [ { - moduleID: intToBuffer(2, 4).toString('hex'), - commandID: intToBuffer(0, 4).toString('hex'), + moduleID: utils.intToBuffer(2, 4).toString('hex'), + commandID: utils.intToBuffer(0, 4).toString('hex'), schema: tokenTransferParamsSchema, }, { - moduleID: intToBuffer(12, 4).toString('hex'), - commandID: intToBuffer(0, 4).toString('hex'), + moduleID: utils.intToBuffer(12, 4).toString('hex'), + commandID: utils.intToBuffer(0, 4).toString('hex'), schema: keysRegisterParamsSchema, }, { - moduleID: intToBuffer(13, 4).toString('hex'), - commandID: intToBuffer(1, 4).toString('hex'), + moduleID: utils.intToBuffer(13, 4).toString('hex'), + commandID: utils.intToBuffer(1, 4).toString('hex'), schema: dposVoteParamsSchema, }, ]; @@ -58,9 +58,9 @@ describe('transaction:sign command', () => { data: 'send token', recipientAddress: 'ab0041a7d3f7b2c290b5b834d46bdc7b7eb85815', }, - commandID: intToBuffer(0, 4).toString('hex'), + commandID: utils.intToBuffer(0, 4).toString('hex'), fee: '100000000', - moduleID: intToBuffer(2, 4).toString('hex'), + moduleID: utils.intToBuffer(2, 4).toString('hex'), nonce: '0', senderPublicKey: '0fe9a3f1a21b5530f27f87a414b549e79a940bf24fdf2b2f05e7f22aeeecc86a', signatures: [ @@ -155,28 +155,28 @@ describe('transaction:sign command', () => { }, metadata: [ { - id: intToBuffer(2, 4).toString('hex'), + id: utils.intToBuffer(2, 4).toString('hex'), commands: [ { - id: intToBuffer(0, 4).toString('hex'), + id: utils.intToBuffer(0, 4).toString('hex'), params: tokenTransferParamsSchema, }, ], }, { - id: intToBuffer(12, 4).toString('hex'), + id: utils.intToBuffer(12, 4).toString('hex'), commands: [ { - id: intToBuffer(0, 4).toString('hex'), + id: utils.intToBuffer(0, 4).toString('hex'), params: keysRegisterParamsSchema, }, ], }, { - id: intToBuffer(13, 4).toString('hex'), + id: utils.intToBuffer(13, 4).toString('hex'), commands: [ { - id: intToBuffer(1, 4).toString('hex'), + id: utils.intToBuffer(1, 4).toString('hex'), params: dposVoteParamsSchema, }, ], diff --git a/commander/test/helpers/account.ts b/commander/test/helpers/account.ts index a4410c02dd7..e1a67c7f962 100644 --- a/commander/test/helpers/account.ts +++ b/commander/test/helpers/account.ts @@ -21,8 +21,8 @@ const { Mnemonic } = liskPassphrase; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const createAccount = () => { const passphrase = Mnemonic.generateMnemonic(); - const { privateKey, publicKey } = cryptography.getKeys(passphrase); - const address = cryptography.getAddressFromPublicKey(publicKey); + const { privateKey, publicKey } = cryptography.utils.getKeys(passphrase); + const address = cryptography.address.getAddressFromPublicKey(publicKey); return { passphrase, @@ -40,7 +40,7 @@ export const createAccounts = (numberOfAccounts = 1) => { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const createFakeDefaultAccount = (account: any) => ({ - address: account?.address ?? cryptography.getRandomBytes(20), + address: account?.address ?? cryptography.utils.getRandomBytes(20), token: { balance: account?.token?.balance ?? BigInt(0), }, diff --git a/commander/test/helpers/transactions.ts b/commander/test/helpers/transactions.ts index e6cfbca55b4..9f8184a435e 100644 --- a/commander/test/helpers/transactions.ts +++ b/commander/test/helpers/transactions.ts @@ -16,7 +16,7 @@ import {} from 'lisk-framework'; import * as cryptography from '@liskhq/lisk-cryptography'; import * as transactions from '@liskhq/lisk-transactions'; import { codec, Schema } from '@liskhq/lisk-codec'; -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; const account = { passphrase: 'endless focus guilt bronze hold economy bulk parent soon tower cement venue', @@ -145,8 +145,8 @@ export const createTransferTransaction = ({ }): Record => { const transaction = transactions.signTransaction( { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt(nonce), fee: BigInt(transactions.convertLSKToBeddows(fee)), senderPublicKey: Buffer.from(account.publicKey, 'hex'), diff --git a/elements/lisk-api-client/src/codec.ts b/elements/lisk-api-client/src/codec.ts index 79571955bf2..0cc04eb01e8 100644 --- a/elements/lisk-api-client/src/codec.ts +++ b/elements/lisk-api-client/src/codec.ts @@ -14,7 +14,7 @@ */ import { codec, Schema } from '@liskhq/lisk-codec'; -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Block, BlockAsset, @@ -108,7 +108,7 @@ export const decodeTransaction = >( metadata, ); const params = paramsSchema ? codec.decode(paramsSchema, transaction.params) : ({} as T); - const id = hash(encodedTransaction); + const id = utils.hash(encodedTransaction); return { ...transaction, params, @@ -307,7 +307,7 @@ export const decodeBlock = ( ); const header = codec.decode(registeredSchema.header, block.header); - const id = hash(block.header); + const id = utils.hash(block.header); const transactions = []; for (const tx of block.transactions) { transactions.push(decodeTransaction(tx, registeredSchema, metadata)); @@ -357,7 +357,7 @@ export const fromBlockJSON = ( metadata: ModuleMetadata[], ): DecodedBlock => { const header = codec.fromJSON(registeredSchema.header, block.header); - const id = hash(codec.encode(registeredSchema.header, header)); + const id = utils.hash(codec.encode(registeredSchema.header, header)); const transactions = []; for (const transaction of block.transactions) { transactions.push(fromTransactionJSON(transaction, registeredSchema, metadata)); diff --git a/elements/lisk-api-client/src/transaction.ts b/elements/lisk-api-client/src/transaction.ts index 28a4a31b628..353630e7224 100644 --- a/elements/lisk-api-client/src/transaction.ts +++ b/elements/lisk-api-client/src/transaction.ts @@ -17,10 +17,7 @@ import { signMultiSignatureTransaction, computeMinFee, } from '@liskhq/lisk-transactions'; -import { - getAddressAndPublicKeyFromPassphrase, - getAddressFromPublicKey, -} from '@liskhq/lisk-cryptography'; +import { address as cryptoAddress } from '@liskhq/lisk-cryptography'; import { LiskValidationError, validator } from '@liskhq/lisk-validator'; import { codec } from '@liskhq/lisk-codec'; import { @@ -101,7 +98,7 @@ export class Transaction { ): Promise> { const txInput = input; const networkIdentifier = Buffer.from(this._nodeInfo.networkIdentifier, 'hex'); - const { publicKey, address } = getAddressAndPublicKeyFromPassphrase(passphrase); + const { publicKey, address } = cryptoAddress.getAddressAndPublicKeyFromPassphrase(passphrase); let authAccount: AuthAccount | undefined; try { authAccount = await this._channel.invoke('auth_getAuthAccount', { @@ -232,7 +229,7 @@ export class Transaction { const decodedTx = this.fromJSON(transaction as TransactionJSON); this._validateTransaction(decodedTx); const networkIdentifier = Buffer.from(this._nodeInfo.networkIdentifier, 'hex'); - const address = getAddressFromPublicKey(decodedTx.senderPublicKey); + const address = cryptoAddress.getAddressFromPublicKey(decodedTx.senderPublicKey); const authAccount = await this._channel.invoke('auth_getAuthAccount', { address: address.toString('hex'), }); diff --git a/elements/lisk-api-client/test/unit/block.spec.ts b/elements/lisk-api-client/test/unit/block.spec.ts index cb3d9afc3de..d2a06a14c77 100644 --- a/elements/lisk-api-client/test/unit/block.spec.ts +++ b/elements/lisk-api-client/test/unit/block.spec.ts @@ -13,7 +13,7 @@ * */ -import { hash, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Channel } from '../../src/types'; import { Block } from '../../src/block'; import { metadata, schema } from '../utils/transaction'; @@ -41,7 +41,7 @@ describe('block', () => { generatorAddress: Buffer.from('be63fb1c0426573352556f18b21efd5b6183c39c', 'hex'), maxHeightPrevoted: 1000988, maxHeightGenerated: 1000988, - validatorsHash: hash(Buffer.alloc(0)), + validatorsHash: utils.hash(Buffer.alloc(0)), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), @@ -67,7 +67,7 @@ describe('block', () => { generatorAddress: 'be63fb1c0426573352556f18b21efd5b6183c39c', maxHeightPrevoted: 1000988, maxHeightGenerated: 1000988, - validatorsHash: hash(Buffer.alloc(0)).toString('hex'), + validatorsHash: utils.hash(Buffer.alloc(0)).toString('hex'), aggregateCommit: { height: 0, aggregationBits: '', @@ -174,8 +174,8 @@ describe('block', () => { it('should return decoded block in JSON', () => { // Arrange const tx = { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('54'), fee: BigInt('10000000'), senderPublicKey: Buffer.from( @@ -208,8 +208,8 @@ describe('block', () => { it('should return object from JSON block', () => { // Arrange const tx = { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('54'), fee: BigInt('10000000'), senderPublicKey: Buffer.from( diff --git a/elements/lisk-api-client/test/unit/transaction.spec.ts b/elements/lisk-api-client/test/unit/transaction.spec.ts index 359c77fd83e..d644b0f5922 100644 --- a/elements/lisk-api-client/test/unit/transaction.spec.ts +++ b/elements/lisk-api-client/test/unit/transaction.spec.ts @@ -36,8 +36,8 @@ describe('transaction', () => { const encodedTx = Buffer.from(txHex, 'hex'); const validTransaction = { - moduleID: intToBuffer(2, 4).toString('hex'), - commandID: intToBuffer(0, 4).toString('hex'), + moduleID: utils.intToBuffer(2, 4).toString('hex'), + commandID: utils.intToBuffer(0, 4).toString('hex'), nonce: '1', fee: '10000000', senderPublicKey: publicKey1.toString('hex'), @@ -50,8 +50,8 @@ describe('transaction', () => { }; const validTransactionJSON = { id: tx.id, - moduleID: intToBuffer(2, 4).toString('hex'), - commandID: intToBuffer(0, 4).toString('hex'), + moduleID: utils.intToBuffer(2, 4).toString('hex'), + commandID: utils.intToBuffer(0, 4).toString('hex'), nonce: '1', fee: '10000000', senderPublicKey: publicKey1.toString('hex'), diff --git a/elements/lisk-api-client/test/utils/transaction.ts b/elements/lisk-api-client/test/utils/transaction.ts index ac241dd8dc9..bd9ca3944ec 100644 --- a/elements/lisk-api-client/test/utils/transaction.ts +++ b/elements/lisk-api-client/test/utils/transaction.ts @@ -19,7 +19,7 @@ import { eventSchema, transactionSchema, } from '@liskhq/lisk-chain'; -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { ModuleMetadata, NodeInfo } from '../../src/types'; export const nodeInfo: NodeInfo = { @@ -40,8 +40,8 @@ export const nodeInfo: NodeInfo = { minFeePerByte: 1000, baseFees: [ { - moduleID: intToBuffer(5, 4).toString('hex'), - commandID: intToBuffer(0, 4).toString('hex'), + moduleID: utils.intToBuffer(5, 4).toString('hex'), + commandID: utils.intToBuffer(0, 4).toString('hex'), baseFee: '1000000000', }, ], @@ -72,14 +72,14 @@ export const schema = { export const metadata: ModuleMetadata[] = [ { - id: intToBuffer(2, 4).toString('hex'), + id: utils.intToBuffer(2, 4).toString('hex'), name: 'token', events: [], assets: [], endpoints: [], commands: [ { - id: intToBuffer(0, 4).toString('hex'), + id: utils.intToBuffer(0, 4).toString('hex'), name: 'transfer', params: { $id: '/lisk/transferParams', @@ -95,14 +95,14 @@ export const metadata: ModuleMetadata[] = [ ], }, { - id: intToBuffer(4, 4).toString('hex'), + id: utils.intToBuffer(4, 4).toString('hex'), name: 'keys', events: [], assets: [], endpoints: [], commands: [ { - id: intToBuffer(0, 4).toString('hex'), + id: utils.intToBuffer(0, 4).toString('hex'), name: 'registerMultisignatureGroup', params: { $id: '/lisk/keys/register', @@ -130,14 +130,14 @@ export const metadata: ModuleMetadata[] = [ ], }, { - id: intToBuffer(5, 4).toString('hex'), + id: utils.intToBuffer(5, 4).toString('hex'), name: 'dpos', events: [], assets: [], endpoints: [], commands: [ { - id: intToBuffer(0, 4).toString('hex'), + id: utils.intToBuffer(0, 4).toString('hex'), name: 'transfer', params: { $id: '/lisk/dpos/pom', @@ -160,8 +160,8 @@ export const metadata: ModuleMetadata[] = [ ]; export const tx = { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('54'), fee: BigInt('10000000'), senderPublicKey: Buffer.from( diff --git a/elements/lisk-chain/src/block_header.ts b/elements/lisk-chain/src/block_header.ts index d7989d5212a..e0ad3cfd35d 100644 --- a/elements/lisk-chain/src/block_header.ts +++ b/elements/lisk-chain/src/block_header.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { signDataWithPrivateKey, hash, verifyData } from '@liskhq/lisk-cryptography'; +import { ed, utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { validator, LiskValidationError } from '@liskhq/lisk-validator'; import { EMPTY_BUFFER, EMPTY_HASH, SIGNATURE_LENGTH_BYTES, TAG_BLOCK_HEADER } from './constants'; @@ -287,7 +287,7 @@ export class BlockHeader { public validateSignature(publicKey: Buffer, networkIdentifier: Buffer): void { const signingBytes = this.getSigningBytes(); - const valid = verifyData( + const valid = ed.verifyData( TAG_BLOCK_HEADER, networkIdentifier, signingBytes, @@ -307,7 +307,7 @@ export class BlockHeader { } public sign(networkIdentifier: Buffer, privateKey: Buffer): void { - this._signature = signDataWithPrivateKey( + this._signature = ed.signDataWithPrivateKey( TAG_BLOCK_HEADER, networkIdentifier, this.getSigningBytes(), @@ -334,7 +334,7 @@ export class BlockHeader { signature: this._signature, }); - this._id = hash(blockHeaderBytes); + this._id = utils.hash(blockHeaderBytes); } return this._id; diff --git a/elements/lisk-chain/src/constants.ts b/elements/lisk-chain/src/constants.ts index 68352b9f579..3c6acae7778 100644 --- a/elements/lisk-chain/src/constants.ts +++ b/elements/lisk-chain/src/constants.ts @@ -12,14 +12,14 @@ * Removal or modification of this copyright notice is prohibited. */ -import { createMessageTag, hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const DEFAULT_KEEP_EVENTS_FOR_HEIGHTS = 300; export const DEFAULT_MIN_BLOCK_HEADER_CACHE = 309; export const DEFAULT_MAX_BLOCK_HEADER_CACHE = 515; export const EMPTY_BUFFER = Buffer.alloc(0); -export const EMPTY_HASH = hash(EMPTY_BUFFER); +export const EMPTY_HASH = utils.hash(EMPTY_BUFFER); export const MAX_UINT32 = 4294967295; export const GENESIS_BLOCK_VERSION = 0; @@ -28,8 +28,8 @@ export const GENESIS_BLOCK_REWARD = BigInt(0); export const GENESIS_BLOCK_SIGNATURE = EMPTY_BUFFER; export const GENESIS_BLOCK_TRANSACTION_ROOT = EMPTY_HASH; -export const TAG_BLOCK_HEADER = createMessageTag('BH'); -export const TAG_TRANSACTION = createMessageTag('TX'); +export const TAG_BLOCK_HEADER = utils.createMessageTag('BH'); +export const TAG_TRANSACTION = utils.createMessageTag('TX'); // TODO: Actual size TBD export const MAX_ASSET_DATA_SIZE_BYTES = 64; diff --git a/elements/lisk-chain/src/data_access/storage.ts b/elements/lisk-chain/src/data_access/storage.ts index 5e26a1ea6ae..fa58719274c 100644 --- a/elements/lisk-chain/src/data_access/storage.ts +++ b/elements/lisk-chain/src/data_access/storage.ts @@ -13,7 +13,7 @@ */ import { Batch, Database, NotFoundError } from '@liskhq/lisk-db'; import { codec } from '@liskhq/lisk-codec'; -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { RawBlock, StateDiff } from '../types'; import { Event } from '../event'; import { @@ -206,7 +206,7 @@ export class Storage { public async getBlockByHeight(height: number): Promise { const header = await this.getBlockHeaderByHeight(height); - const blockID = hash(header); + const blockID = utils.hash(header); const transactions = await this._getTransactions(blockID); const assets = await this._getBlockAssets(blockID); @@ -221,7 +221,7 @@ export class Storage { const headers = await this.getBlockHeadersByHeightBetween(fromHeight, toHeight); const blocks = []; for (const header of headers) { - const blockID = hash(header); + const blockID = utils.hash(header); const transactions = await this._getTransactions(blockID); const assets = await this._getBlockAssets(blockID); blocks.push({ header, transactions, assets }); @@ -232,7 +232,7 @@ export class Storage { public async getLastBlock(): Promise { const header = await this.getLastBlockHeader(); - const blockID = hash(header); + const blockID = utils.hash(header); const transactions = await this._getTransactions(blockID); const assets = await this._getBlockAssets(blockID); diff --git a/elements/lisk-chain/src/event.ts b/elements/lisk-chain/src/event.ts index cfbd6b6e61d..7f9cd5e0f21 100644 --- a/elements/lisk-chain/src/event.ts +++ b/elements/lisk-chain/src/event.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { EVENT_ID_LENGTH_BYTES, EVENT_TOPIC_HASH_LENGTH_BYTES, @@ -78,7 +78,7 @@ export class Event { const indexBytes = Buffer.alloc(EVENT_TOTAL_INDEX_LENGTH_BYTES); indexBytes.writeUIntBE(indexBit, 0, EVENT_TOTAL_INDEX_LENGTH_BYTES); const key = Buffer.concat([ - hash(this._topics[i]).slice(0, EVENT_TOPIC_HASH_LENGTH_BYTES), + utils.hash(this._topics[i]).slice(0, EVENT_TOPIC_HASH_LENGTH_BYTES), indexBytes, ]); result.push({ diff --git a/elements/lisk-chain/src/state_store/utils.ts b/elements/lisk-chain/src/state_store/utils.ts index 274a1358792..85a56c20be0 100644 --- a/elements/lisk-chain/src/state_store/utils.ts +++ b/elements/lisk-chain/src/state_store/utils.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { SMT_PREFIX_SIZE } from '../constants'; export const copyBuffer = (value: Buffer): Buffer => { @@ -23,4 +23,7 @@ export const copyBuffer = (value: Buffer): Buffer => { export const toSMTKey = (value: Buffer): Buffer => // First byte is the DB prefix - Buffer.concat([value.slice(1, SMT_PREFIX_SIZE + 1), hash(value.slice(SMT_PREFIX_SIZE + 1))]); + Buffer.concat([ + value.slice(1, SMT_PREFIX_SIZE + 1), + utils.hash(value.slice(SMT_PREFIX_SIZE + 1)), + ]); diff --git a/elements/lisk-chain/src/transaction.ts b/elements/lisk-chain/src/transaction.ts index a651b52c234..6b573c9336e 100644 --- a/elements/lisk-chain/src/transaction.ts +++ b/elements/lisk-chain/src/transaction.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { hash, getAddressFromPublicKey, signDataWithPrivateKey } from '@liskhq/lisk-cryptography'; +import { utils, address, ed } from '@liskhq/lisk-cryptography'; import { validator, LiskValidationError } from '@liskhq/lisk-validator'; import { TAG_TRANSACTION } from './constants'; import { JSONObject } from './types'; @@ -117,14 +117,14 @@ export class Transaction { public get id(): Buffer { if (!this._id) { - this._id = hash(this.getBytes()); + this._id = utils.hash(this.getBytes()); } return this._id; } public get senderAddress(): Buffer { if (!this._senderAddress) { - this._senderAddress = getAddressFromPublicKey(this.senderPublicKey); + this._senderAddress = address.getAddressFromPublicKey(this.senderPublicKey); } return this._senderAddress; } @@ -145,7 +145,7 @@ export class Transaction { } public sign(networkIdentifier: Buffer, privateKey: Buffer): void { - const signature = signDataWithPrivateKey( + const signature = ed.signDataWithPrivateKey( TAG_TRANSACTION, networkIdentifier, this.getSigningBytes(), diff --git a/elements/lisk-chain/test/integration/data_access/blocks.spec.ts b/elements/lisk-chain/test/integration/data_access/blocks.spec.ts index f2cdb0f00cd..940b405a7b8 100644 --- a/elements/lisk-chain/test/integration/data_access/blocks.spec.ts +++ b/elements/lisk-chain/test/integration/data_access/blocks.spec.ts @@ -75,27 +75,31 @@ describe('dataAccess.blocks', () => { const block302 = await createValidDefaultBlock({ header: { height: 302 }, transactions: [getTransaction({ nonce: BigInt(1) }), getTransaction({ nonce: BigInt(2) })], - assets: new BlockAssets([{ moduleID: intToBuffer(3, 4), data: getRandomBytes(64) }]), + assets: new BlockAssets([ + { moduleID: utils.intToBuffer(3, 4), data: utils.getRandomBytes(64) }, + ]), }); const block303 = await createValidDefaultBlock({ header: { height: 303 }, - assets: new BlockAssets([{ moduleID: intToBuffer(3, 4), data: getRandomBytes(64) }]), + assets: new BlockAssets([ + { moduleID: utils.intToBuffer(3, 4), data: utils.getRandomBytes(64) }, + ]), }); const events = [ new Event({ - data: getRandomBytes(20), + data: utils.getRandomBytes(20), index: 0, moduleID: Buffer.from([0, 0, 0, 2]), - topics: [getRandomBytes(32)], + topics: [utils.getRandomBytes(32)], typeID: Buffer.from([0, 0, 0, 0]), }), new Event({ - data: getRandomBytes(20), + data: utils.getRandomBytes(20), index: 1, moduleID: Buffer.from([0, 0, 0, 3]), - topics: [getRandomBytes(32)], + topics: [utils.getRandomBytes(32)], typeID: Buffer.from([0, 0, 0, 0]), }), ]; @@ -309,8 +313,8 @@ describe('dataAccess.blocks', () => { expect(block.header.toObject()).toStrictEqual(blocks[0].header.toObject()); expect(block.transactions[0]).toBeInstanceOf(Transaction); expect(block.transactions[0].id).toStrictEqual(blocks[0].transactions[0].id); - expect(block.assets.getAsset(intToBuffer(3, 4))).toEqual( - blocks[0].assets.getAsset(intToBuffer(3, 4)), + expect(block.assets.getAsset(utils.intToBuffer(3, 4))).toEqual( + blocks[0].assets.getAsset(utils.intToBuffer(3, 4)), ); }); }); @@ -372,17 +376,17 @@ describe('dataAccess.blocks', () => { const events = [ new Event({ - data: getRandomBytes(20), + data: utils.getRandomBytes(20), index: 0, moduleID: Buffer.from([0, 0, 0, 2]), - topics: [getRandomBytes(32)], + topics: [utils.getRandomBytes(32)], typeID: Buffer.from([0, 0, 0, 0]), }), new Event({ - data: getRandomBytes(20), + data: utils.getRandomBytes(20), index: 1, moduleID: Buffer.from([0, 0, 0, 3]), - topics: [getRandomBytes(32)], + topics: [utils.getRandomBytes(32)], typeID: Buffer.from([0, 0, 0, 0]), }), ]; diff --git a/elements/lisk-chain/test/unit/block.spec.ts b/elements/lisk-chain/test/unit/block.spec.ts index 38c82014c2d..c81c80f2b7e 100644 --- a/elements/lisk-chain/test/unit/block.spec.ts +++ b/elements/lisk-chain/test/unit/block.spec.ts @@ -27,12 +27,12 @@ describe('block', () => { beforeEach(() => { assetList = [ { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(6, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(6, 4), + data: utils.getRandomBytes(64), }, ]; blockAssets = new BlockAssets(assetList); @@ -77,7 +77,7 @@ describe('block', () => { // Arrange const txs = new Array(20).fill(0).map(() => tx); block = await createValidDefaultBlock({ transactions: txs }); - block['header']['_transactionRoot'] = getRandomBytes(32); + block['header']['_transactionRoot'] = utils.getRandomBytes(32); // Act & assert expect(() => block.validate()).toThrow('Invalid transaction root'); @@ -89,12 +89,12 @@ describe('block', () => { // Arrange const assets = [ { - moduleID: intToBuffer(2, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(2, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, ]; const txs = new Array(20).fill(0).map(() => tx); @@ -102,7 +102,7 @@ describe('block', () => { transactions: txs, assets: new BlockAssets(assets), }); - block['header']['_assetRoot'] = getRandomBytes(32); + block['header']['_assetRoot'] = utils.getRandomBytes(32); // Act & assert expect(() => block.validate()).toThrow('Invalid assets root'); @@ -115,14 +115,14 @@ describe('block', () => { version: 1, timestamp: 1009988, height: 1009988, - previousBlockID: getRandomBytes(32), + previousBlockID: utils.getRandomBytes(32), stateRoot: Buffer.from('7f9d96a09a3fd17f3478eb7bef3a8bda00e1238b', 'hex'), transactionRoot: EMPTY_HASH, assetRoot: EMPTY_HASH, generatorAddress: EMPTY_BUFFER, maxHeightPrevoted: 1009988, maxHeightGenerated: 0, - validatorsHash: hash(Buffer.alloc(0)), + validatorsHash: utils.hash(Buffer.alloc(0)), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), @@ -138,12 +138,12 @@ describe('block', () => { beforeEach(() => { assetList = [ { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(6, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(6, 4), + data: utils.getRandomBytes(64), }, ]; blockAssets = new BlockAssets(assetList); @@ -180,12 +180,12 @@ describe('block', () => { // Arrange const assets = [ { - moduleID: intToBuffer(2, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(2, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, ]; block = await createValidDefaultBlock({ @@ -194,7 +194,7 @@ describe('block', () => { assets: new BlockAssets(assets), }); block['header']['_signature'] = EMPTY_BUFFER; - block['header']['_assetRoot'] = getRandomBytes(32); + block['header']['_assetRoot'] = utils.getRandomBytes(32); // Act & assert expect(() => block.validateGenesis()).toThrow('Invalid assets root'); diff --git a/elements/lisk-chain/test/unit/block_assets.spec.ts b/elements/lisk-chain/test/unit/block_assets.spec.ts index 6914dfa2b0b..9ddba84e4f1 100644 --- a/elements/lisk-chain/test/unit/block_assets.spec.ts +++ b/elements/lisk-chain/test/unit/block_assets.spec.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { MerkleTree } from '@liskhq/lisk-tree'; import { BlockAsset, BlockAssets } from '../../src'; import { MAX_ASSET_DATA_SIZE_BYTES } from '../../src/constants'; @@ -23,12 +23,12 @@ describe('block assets', () => { beforeEach(() => { assetList = [ { - moduleID: intToBuffer(6, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(6, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); @@ -43,23 +43,23 @@ describe('block assets', () => { describe('getAsset', () => { it('it should return undefined if no matching asset exists ', () => { - expect(assets.getAsset(intToBuffer(5, 4))).toBeUndefined(); + expect(assets.getAsset(utils.intToBuffer(5, 4))).toBeUndefined(); }); it('it should return asset data if matching asset exists ', () => { - expect(assets.getAsset(intToBuffer(3, 4))).toBeInstanceOf(Buffer); + expect(assets.getAsset(utils.intToBuffer(3, 4))).toBeInstanceOf(Buffer); }); }); describe('setAsset', () => { it('it should not overwrite existing asset', () => { - const data = getRandomBytes(32); - expect(() => assets.setAsset(intToBuffer(3, 4), data)).toThrow(); + const data = utils.getRandomBytes(32); + expect(() => assets.setAsset(utils.intToBuffer(3, 4), data)).toThrow(); }); it('it should add asset data if matching asset does not exist ', () => { - const data = getRandomBytes(32); - assets.setAsset(intToBuffer(4, 4), data); + const data = utils.getRandomBytes(32); + assets.setAsset(utils.intToBuffer(4, 4), data); expect(assets['_assets']).toHaveLength(3); }); }); @@ -68,12 +68,12 @@ describe('block assets', () => { it('should create BlockAssets from JSON format', () => { assets = BlockAssets.fromJSON([ { - moduleID: intToBuffer(4, 4).toString('hex'), - data: getRandomBytes(30).toString('hex'), + moduleID: utils.intToBuffer(4, 4).toString('hex'), + data: utils.getRandomBytes(30).toString('hex'), }, ]); expect(assets['_assets']).toHaveLength(1); - expect(assets.getAsset(intToBuffer(4, 4))).toBeInstanceOf(Buffer); + expect(assets.getAsset(utils.intToBuffer(4, 4))).toBeInstanceOf(Buffer); }); }); @@ -97,12 +97,12 @@ describe('block assets', () => { it(`should throw error when data type is incorrect`, () => { assetList = [ { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(4, 4), - data: getRandomBytes(128), + moduleID: utils.intToBuffer(4, 4), + data: utils.getRandomBytes(128), }, ]; assets = new BlockAssets(assetList); @@ -116,12 +116,12 @@ describe('block assets', () => { it(`should throw error when asset data length is greater than ${MAX_ASSET_DATA_SIZE_BYTES}`, () => { assetList = [ { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(4, 4), - data: getRandomBytes(128), + moduleID: utils.intToBuffer(4, 4), + data: utils.getRandomBytes(128), }, ]; assets = new BlockAssets(assetList); @@ -135,12 +135,12 @@ describe('block assets', () => { it(`should pass when asset data length is equal or less than ${MAX_ASSET_DATA_SIZE_BYTES}`, () => { assetList = [ { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(4, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(4, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); @@ -152,12 +152,12 @@ describe('block assets', () => { it('should throw error when assets are not sorted by moduleID', () => { assetList = [ { - moduleID: intToBuffer(4, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(4, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); @@ -169,12 +169,12 @@ describe('block assets', () => { it('should pass when assets are sorted by moduleID', () => { assetList = [ { - moduleID: intToBuffer(2, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(2, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); @@ -186,16 +186,16 @@ describe('block assets', () => { it('should throw error when there are more than 1 assets for a module', () => { assetList = [ { - moduleID: intToBuffer(2, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(2, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); @@ -207,16 +207,16 @@ describe('block assets', () => { it('should pass when there is atmost 1 asset for a module', () => { assetList = [ { - moduleID: intToBuffer(2, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(2, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(4, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(4, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); @@ -230,12 +230,12 @@ describe('block assets', () => { it(`should throw error when data type is incorrect`, () => { assetList = [ { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(4, 4), - data: getRandomBytes(128), + moduleID: utils.intToBuffer(4, 4), + data: utils.getRandomBytes(128), }, ]; assets = new BlockAssets(assetList); @@ -248,12 +248,12 @@ describe('block assets', () => { it(`should pass when asset data length is greater than ${MAX_ASSET_DATA_SIZE_BYTES}`, () => { assetList = [ { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(4, 4), - data: getRandomBytes(128), + moduleID: utils.intToBuffer(4, 4), + data: utils.getRandomBytes(128), }, ]; assets = new BlockAssets(assetList); @@ -263,12 +263,12 @@ describe('block assets', () => { it(`should pass when asset data length is equal or less than ${MAX_ASSET_DATA_SIZE_BYTES}`, () => { assetList = [ { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(4, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(4, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); @@ -280,12 +280,12 @@ describe('block assets', () => { it('should throw error when assets are not sorted by moduleID', () => { assetList = [ { - moduleID: intToBuffer(4, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(4, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); @@ -297,12 +297,12 @@ describe('block assets', () => { it('should pass when assets are sorted by moduleID', () => { assetList = [ { - moduleID: intToBuffer(2, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(2, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); @@ -314,16 +314,16 @@ describe('block assets', () => { it('should throw error when there are more than 1 assets for a module', () => { assetList = [ { - moduleID: intToBuffer(2, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(2, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); @@ -335,16 +335,16 @@ describe('block assets', () => { it('should pass when there is atmost 1 asset for a module', () => { assetList = [ { - moduleID: intToBuffer(2, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(2, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(3, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(3, 4), + data: utils.getRandomBytes(64), }, { - moduleID: intToBuffer(4, 4), - data: getRandomBytes(64), + moduleID: utils.intToBuffer(4, 4), + data: utils.getRandomBytes(64), }, ]; assets = new BlockAssets(assetList); diff --git a/elements/lisk-chain/test/unit/block_header.spec.ts b/elements/lisk-chain/test/unit/block_header.spec.ts index e2c590242e6..36f031cf225 100644 --- a/elements/lisk-chain/test/unit/block_header.spec.ts +++ b/elements/lisk-chain/test/unit/block_header.spec.ts @@ -32,7 +32,7 @@ const getBlockAttrs = () => ({ generatorAddress: Buffer.from('be63fb1c0426573352556f18b21efd5b6183c39c', 'hex'), maxHeightPrevoted: 1000988, maxHeightGenerated: 1000988, - validatorsHash: hash(Buffer.alloc(0)), + validatorsHash: utils.hash(Buffer.alloc(0)), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), @@ -45,7 +45,7 @@ const getGenesisBlockAttrs = () => ({ version: 1, timestamp: 1009988, height: 1009988, - previousBlockID: getRandomBytes(32), + previousBlockID: utils.getRandomBytes(32), stateRoot: Buffer.from('7f9d96a09a3fd17f3478eb7bef3a8bda00e1238b', 'hex'), transactionRoot: EMPTY_HASH, assetRoot: EMPTY_HASH, @@ -53,7 +53,7 @@ const getGenesisBlockAttrs = () => ({ generatorAddress: EMPTY_BUFFER, maxHeightPrevoted: 1009988, maxHeightGenerated: 0, - validatorsHash: hash(Buffer.alloc(0)), + validatorsHash: utils.hash(Buffer.alloc(0)), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), @@ -212,7 +212,10 @@ describe('block_header', () => { describe('validateGenesis', () => { it('should throw error if previousBlockID is not 32 bytes', () => { const block = getGenesisBlockAttrs(); - const blockHeader = new BlockHeader({ ...block, previousBlockID: getRandomBytes(31) }); + const blockHeader = new BlockHeader({ + ...block, + previousBlockID: utils.getRandomBytes(31), + }); expect(() => blockHeader.validateGenesis()).toThrow( 'Genesis block header previousBlockID must be 32 bytes', @@ -221,7 +224,10 @@ describe('block_header', () => { it('should throw error if transactionRoot is not empty hash', () => { const block = getGenesisBlockAttrs(); - const blockHeader = new BlockHeader({ ...block, transactionRoot: getRandomBytes(32) }); + const blockHeader = new BlockHeader({ + ...block, + transactionRoot: utils.getRandomBytes(32), + }); expect(() => blockHeader.validateGenesis()).toThrow( 'Genesis block header transaction root must be empty hash', @@ -230,7 +236,10 @@ describe('block_header', () => { it('should throw error if generatorAddress is not empty buffer', () => { const block = getGenesisBlockAttrs(); - const blockHeader = new BlockHeader({ ...block, generatorAddress: getRandomBytes(32) }); + const blockHeader = new BlockHeader({ + ...block, + generatorAddress: utils.getRandomBytes(32), + }); expect(() => blockHeader.validateGenesis()).toThrow( 'Genesis block header generatorAddress must be empty bytes', @@ -262,7 +271,10 @@ describe('block_header', () => { const block = getGenesisBlockAttrs(); const blockHeader = new BlockHeader({ ...block, - aggregateCommit: { ...block.aggregateCommit, certificateSignature: getRandomBytes(32) }, + aggregateCommit: { + ...block.aggregateCommit, + certificateSignature: utils.getRandomBytes(32), + }, }); expect(() => blockHeader.validateGenesis()).toThrow( @@ -274,7 +286,7 @@ describe('block_header', () => { const block = getGenesisBlockAttrs(); const blockHeader = new BlockHeader({ ...block, - aggregateCommit: { ...block.aggregateCommit, aggregationBits: getRandomBytes(32) }, + aggregateCommit: { ...block.aggregateCommit, aggregationBits: utils.getRandomBytes(32) }, }); expect(() => blockHeader.validateGenesis()).toThrow( @@ -284,7 +296,7 @@ describe('block_header', () => { it('should throw error if signature is not empty buffer', () => { const block = getGenesisBlockAttrs(); - const blockHeader = new BlockHeader({ ...block, signature: getRandomBytes(32) }); + const blockHeader = new BlockHeader({ ...block, signature: utils.getRandomBytes(32) }); expect(() => blockHeader.validateGenesis()).toThrow( 'Genesis block header signature must be empty bytes', diff --git a/elements/lisk-chain/test/unit/chain.spec.ts b/elements/lisk-chain/test/unit/chain.spec.ts index 27d0d8622f8..4379bac239d 100644 --- a/elements/lisk-chain/test/unit/chain.spec.ts +++ b/elements/lisk-chain/test/unit/chain.spec.ts @@ -202,8 +202,8 @@ describe('chain', () => { beforeEach(async () => { stateStore = new StateStore(db); jest.spyOn(stateStore, 'finalize'); - const subStore = stateStore.getStore(intToBuffer(2, 4), 0); - await subStore.set(getRandomBytes(20), getRandomBytes(100)); + const subStore = stateStore.getStore(utils.intToBuffer(2, 4), 0); + await subStore.set(utils.getRandomBytes(20), utils.getRandomBytes(100)); batch = new Batch(); jest.spyOn(batch, 'set'); jest.spyOn(batch, 'del'); @@ -347,7 +347,7 @@ describe('chain', () => { (chainInstance as any).constants.maxTransactionsSize = 100; const txs = new Array(200).fill(0).map(() => getTransaction()); const assets = new BlockAssets([ - { moduleID: intToBuffer(1515, 4), data: getRandomBytes(32) }, + { moduleID: utils.intToBuffer(1515, 4), data: utils.getRandomBytes(32) }, ]); block = await createValidDefaultBlock({ transactions: txs, assets }); // Act & assert diff --git a/elements/lisk-chain/test/unit/data_access/data_access.spec.ts b/elements/lisk-chain/test/unit/data_access/data_access.spec.ts index 982307454b3..c5c8a32f44c 100644 --- a/elements/lisk-chain/test/unit/data_access/data_access.spec.ts +++ b/elements/lisk-chain/test/unit/data_access/data_access.spec.ts @@ -368,17 +368,17 @@ describe('data_access', () => { it('should get the events related to heights', async () => { const original = [ new Event({ - data: getRandomBytes(20), + data: utils.getRandomBytes(20), index: 0, moduleID: Buffer.from([0, 0, 0, 2]), - topics: [getRandomBytes(32)], + topics: [utils.getRandomBytes(32)], typeID: Buffer.from([0, 0, 0, 0]), }), new Event({ - data: getRandomBytes(20), + data: utils.getRandomBytes(20), index: 1, moduleID: Buffer.from([0, 0, 0, 3]), - topics: [getRandomBytes(32)], + topics: [utils.getRandomBytes(32)], typeID: Buffer.from([0, 0, 0, 0]), }), ]; @@ -461,8 +461,8 @@ describe('data_access', () => { describe('#getTransactionsByIDs', () => { it('should get transaction by id', async () => { const tx = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt('10000000'), nonce: BigInt('0'), senderPublicKey: Buffer.from( diff --git a/elements/lisk-chain/test/unit/event.spec.ts b/elements/lisk-chain/test/unit/event.spec.ts index 3f765b2af37..9b47d0ae328 100644 --- a/elements/lisk-chain/test/unit/event.spec.ts +++ b/elements/lisk-chain/test/unit/event.spec.ts @@ -23,9 +23,9 @@ describe('event', () => { const eventObj = { moduleID: Buffer.from([0, 0, 0, 2]), typeID: Buffer.from([0, 0, 0, 1]), - topics: [getRandomBytes(32), getRandomBytes(20), getRandomBytes(2)], + topics: [utils.getRandomBytes(32), utils.getRandomBytes(20), utils.getRandomBytes(2)], index: 3, - data: getRandomBytes(200), + data: utils.getRandomBytes(200), }; const encodedEvent = codec.encode(eventSchema, eventObj); diff --git a/elements/lisk-chain/test/unit/state_store/state_store.spec.ts b/elements/lisk-chain/test/unit/state_store/state_store.spec.ts index 978c171feec..226d70b99db 100644 --- a/elements/lisk-chain/test/unit/state_store/state_store.spec.ts +++ b/elements/lisk-chain/test/unit/state_store/state_store.spec.ts @@ -30,12 +30,12 @@ const sampleSchema = { }; describe('state store', () => { - let moduleID = intToBuffer(2, 4); + let moduleID = utils.intToBuffer(2, 4); const storePrefix = 0; - const existingKey = getRandomBytes(20); - const existingKey2 = getRandomBytes(20); - const existingValue = getRandomBytes(64); - const existingValue2 = getRandomBytes(64); + const existingKey = utils.getRandomBytes(20); + const existingKey2 = utils.getRandomBytes(20); + const existingValue = utils.getRandomBytes(64); + const existingValue2 = utils.getRandomBytes(64); let stateStore: StateStore; let db: InMemoryDatabase; @@ -57,19 +57,19 @@ describe('state store', () => { describe('getStore', () => { it('should keep the same cache as the original state store', async () => { - const address = getRandomBytes(20); - const value = getRandomBytes(64); - const subStore = stateStore.getStore(intToBuffer(2, 4), 0); + const address = utils.getRandomBytes(20); + const value = utils.getRandomBytes(64); + const subStore = stateStore.getStore(utils.intToBuffer(2, 4), 0); await subStore.set(address, value); // create different store from the state store - const newSubStore = stateStore.getStore(intToBuffer(2, 4), 0); + const newSubStore = stateStore.getStore(utils.intToBuffer(2, 4), 0); const valueFromNewStore = await newSubStore.get(address); expect(valueFromNewStore).toEqual(value); }); it('should append the prefix', () => { - const subStore = stateStore.getStore(intToBuffer(2, 4), 0); + const subStore = stateStore.getStore(utils.intToBuffer(2, 4), 0); // db prefix(1) + moduleID(4) + storePrefix(2) expect(subStore['_prefix']).toHaveLength(1 + 4 + 2); }); @@ -78,8 +78,8 @@ describe('state store', () => { describe('get', () => { it('should get from the cache if the key already exist', async () => { const subStore = stateStore.getStore(moduleID, storePrefix); - const newKey = getRandomBytes(20); - await subStore.set(newKey, getRandomBytes(10)); + const newKey = utils.getRandomBytes(20); + await subStore.set(newKey, utils.getRandomBytes(10)); jest.spyOn(db, 'get'); await subStore.get(newKey); @@ -118,7 +118,7 @@ describe('state store', () => { describe('getWithSchema', () => { it('should return decoded value', async () => { - const address = getRandomBytes(20); + const address = utils.getRandomBytes(20); const encodedValue = codec.encode(sampleSchema, { address }); const subStore = stateStore.getStore(moduleID, storePrefix); await subStore.set(address, encodedValue); @@ -131,8 +131,8 @@ describe('state store', () => { describe('set', () => { it('should update the cached value if it exist in the cache', async () => { - const address = getRandomBytes(20); - const value = getRandomBytes(50); + const address = utils.getRandomBytes(20); + const value = utils.getRandomBytes(50); const subStore = stateStore.getStore(moduleID, storePrefix); await subStore.set(address, value); @@ -148,8 +148,8 @@ describe('state store', () => { it('should cache the original value and update the cache if it does not exist in the cache', async () => { jest.spyOn(db, 'get'); - const address = getRandomBytes(20); - const value = getRandomBytes(50); + const address = utils.getRandomBytes(20); + const value = utils.getRandomBytes(50); const subStore = stateStore.getStore(moduleID, storePrefix); await subStore.set(address, value); @@ -162,7 +162,7 @@ describe('state store', () => { describe('setWithSchema', () => { it('should set encoded value', async () => { - const address = getRandomBytes(20); + const address = utils.getRandomBytes(20); const encodedValue = codec.encode(sampleSchema, { address }); const subStore = stateStore.getStore(moduleID, storePrefix); await subStore.setWithSchema(address, { address }, sampleSchema); @@ -174,8 +174,8 @@ describe('state store', () => { }); describe('del', () => { - const address = getRandomBytes(20); - const value = getRandomBytes(50); + const address = utils.getRandomBytes(20); + const value = utils.getRandomBytes(50); it('should mark as deleted if it exists in the cache', async () => { const subStore = stateStore.getStore(moduleID, storePrefix); @@ -199,9 +199,9 @@ describe('state store', () => { describe('iterate', () => { it('should return all the key-values with the prefix', async () => { const subStore = stateStore.getStore(moduleID, 1); - await subStore.set(Buffer.from([0]), getRandomBytes(40)); - await subStore.set(Buffer.from([1]), getRandomBytes(40)); - await subStore.set(Buffer.from([2]), getRandomBytes(40)); + await subStore.set(Buffer.from([0]), utils.getRandomBytes(40)); + await subStore.set(Buffer.from([1]), utils.getRandomBytes(40)); + await subStore.set(Buffer.from([2]), utils.getRandomBytes(40)); const result = await subStore.iterate({ gte: Buffer.from([0]), @@ -215,11 +215,11 @@ describe('state store', () => { it('should return all the key-values with the prefix in reverse order', async () => { const existingStore = stateStore.getStore(moduleID, storePrefix); - await existingStore.set(Buffer.from([0]), getRandomBytes(40)); + await existingStore.set(Buffer.from([0]), utils.getRandomBytes(40)); const subStore = stateStore.getStore(moduleID, 1); - await subStore.set(Buffer.from([0]), getRandomBytes(40)); - await subStore.set(Buffer.from([1]), getRandomBytes(40)); - await subStore.set(Buffer.from([2]), getRandomBytes(40)); + await subStore.set(Buffer.from([0]), utils.getRandomBytes(40)); + await subStore.set(Buffer.from([1]), utils.getRandomBytes(40)); + await subStore.set(Buffer.from([2]), utils.getRandomBytes(40)); const result = await subStore.iterate({ gte: Buffer.from([0]), @@ -235,9 +235,9 @@ describe('state store', () => { it('should not return the deleted values', async () => { const subStore = stateStore.getStore(moduleID, 1); - await subStore.set(Buffer.from([0]), getRandomBytes(40)); - await subStore.set(Buffer.from([1]), getRandomBytes(40)); - await subStore.set(Buffer.from([2]), getRandomBytes(40)); + await subStore.set(Buffer.from([0]), utils.getRandomBytes(40)); + await subStore.set(Buffer.from([1]), utils.getRandomBytes(40)); + await subStore.set(Buffer.from([2]), utils.getRandomBytes(40)); await subStore.del(Buffer.from([1])); const result = await subStore.iterate({ @@ -253,9 +253,9 @@ describe('state store', () => { it('should return the updated values in the cache', async () => { const expectedValue = Buffer.from('random'); const subStore = stateStore.getStore(moduleID, storePrefix); - await subStore.set(Buffer.from([0]), getRandomBytes(40)); - await subStore.set(Buffer.from([1]), getRandomBytes(40)); - await subStore.set(Buffer.from([2]), getRandomBytes(40)); + await subStore.set(Buffer.from([0]), utils.getRandomBytes(40)); + await subStore.set(Buffer.from([1]), utils.getRandomBytes(40)); + await subStore.set(Buffer.from([2]), utils.getRandomBytes(40)); await subStore.set(existingKey, expectedValue); @@ -271,7 +271,7 @@ describe('state store', () => { describe('iterateWithSchema', () => { it('should return decoded value', async () => { - const address = getRandomBytes(20); + const address = utils.getRandomBytes(20); const encodedValue = codec.encode(sampleSchema, { address }); const subStore = stateStore.getStore(moduleID, 1); await subStore.set(Buffer.from([0]), encodedValue); @@ -296,7 +296,7 @@ describe('state store', () => { it('should not change the snapshot data when other operation is triggered', async () => { const subStore = stateStore.getStore(moduleID, storePrefix); subStore.createSnapshot(); - const expected = getRandomBytes(64); + const expected = utils.getRandomBytes(64); await subStore.set(Buffer.from([0]), expected); await subStore.del(existingKey); @@ -307,7 +307,7 @@ describe('state store', () => { it('should restore to snapshot value when the restore is called', async () => { const subStore = stateStore.getStore(moduleID, storePrefix); subStore.createSnapshot(); - await subStore.set(Buffer.from([0]), getRandomBytes(64)); + await subStore.set(Buffer.from([0]), utils.getRandomBytes(64)); await subStore.del(existingKey); subStore.restoreSnapshot(); @@ -317,7 +317,10 @@ describe('state store', () => { }); describe('finalize', () => { - const getRandomData = () => ({ key: getRandomBytes(20), value: getRandomBytes(50) }); + const getRandomData = () => ({ + key: utils.getRandomBytes(20), + value: utils.getRandomBytes(50), + }); const getKey = (mID: number, prefix: number) => { moduleID = Buffer.alloc(4); moduleID.writeInt32BE(mID, 0); @@ -332,7 +335,7 @@ describe('state store', () => { beforeEach(async () => { data = [getRandomData(), getRandomData(), getRandomData()]; const subStore = stateStore.getStore(moduleID, storePrefix); - await subStore.set(existingKey, getRandomBytes(40)); + await subStore.set(existingKey, utils.getRandomBytes(40)); await subStore.del(existingKey2); const anotherStore = stateStore.getStore(moduleID, 1); for (const sample of data) { diff --git a/elements/lisk-chain/test/unit/transactions.spec.ts b/elements/lisk-chain/test/unit/transactions.spec.ts index 851985f6083..9d8e64c81f0 100644 --- a/elements/lisk-chain/test/unit/transactions.spec.ts +++ b/elements/lisk-chain/test/unit/transactions.spec.ts @@ -31,25 +31,25 @@ describe('blocks/transactions', () => { it('should throw when sender public key is not 32 bytes', () => { transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(613000), - params: getRandomBytes(500), + params: utils.getRandomBytes(500), nonce: BigInt(2), - senderPublicKey: getRandomBytes(31), - signatures: [getRandomBytes(64)], + senderPublicKey: utils.getRandomBytes(31), + signatures: [utils.getRandomBytes(64)], }); expect(() => transaction.validate()).toThrow('Lisk validator found 1 error[s]'); }); it('should throw when signatures is empty', () => { transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(613000), - params: getRandomBytes(500), + params: utils.getRandomBytes(500), nonce: BigInt(2), - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [], }); expect(() => transaction.validate()).toThrow('Signatures must not be empty'); @@ -57,17 +57,17 @@ describe('blocks/transactions', () => { it('should throw when any of signatures are not 64 bytes', () => { transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(613000), - params: getRandomBytes(500), + params: utils.getRandomBytes(500), nonce: BigInt(2), - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [ - getRandomBytes(64), - getRandomBytes(32), - getRandomBytes(32), - getRandomBytes(64), + utils.getRandomBytes(64), + utils.getRandomBytes(32), + utils.getRandomBytes(32), + utils.getRandomBytes(64), ], }); expect(() => transaction.validate()).toThrow('Signature must be empty or 64 bytes'); diff --git a/elements/lisk-chain/test/utils/block.ts b/elements/lisk-chain/test/utils/block.ts index 00bb05d5e0c..247ae0c06b4 100644 --- a/elements/lisk-chain/test/utils/block.ts +++ b/elements/lisk-chain/test/utils/block.ts @@ -36,25 +36,25 @@ const getKeyPair = (): { publicKey: Buffer; privateKey: Buffer } => { export const createFakeBlockHeader = (header?: Partial): BlockHeader => new BlockHeader({ - id: hash(getRandomBytes(8)), + id: utils.hash(utils.getRandomBytes(8)), version: 2, timestamp: header?.timestamp ?? 0, height: header?.height ?? 0, - previousBlockID: header?.previousBlockID ?? hash(getRandomBytes(4)), - transactionRoot: header?.transactionRoot ?? hash(getRandomBytes(4)), - generatorAddress: header?.generatorAddress ?? getRandomBytes(32), + previousBlockID: header?.previousBlockID ?? utils.hash(utils.getRandomBytes(4)), + transactionRoot: header?.transactionRoot ?? utils.hash(utils.getRandomBytes(4)), + generatorAddress: header?.generatorAddress ?? utils.getRandomBytes(32), maxHeightGenerated: header?.maxHeightGenerated ?? 0, maxHeightPrevoted: header?.maxHeightPrevoted ?? 0, - eventRoot: header?.eventRoot ?? hash(getRandomBytes(32)), - stateRoot: header?.stateRoot ?? hash(getRandomBytes(32)), - assetRoot: header?.assetRoot ?? hash(getRandomBytes(32)), - validatorsHash: header?.validatorsHash ?? hash(getRandomBytes(32)), + eventRoot: header?.eventRoot ?? utils.hash(utils.getRandomBytes(32)), + stateRoot: header?.stateRoot ?? utils.hash(utils.getRandomBytes(32)), + assetRoot: header?.assetRoot ?? utils.hash(utils.getRandomBytes(32)), + validatorsHash: header?.validatorsHash ?? utils.hash(utils.getRandomBytes(32)), aggregateCommit: header?.aggregateCommit ?? { height: 0, aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - signature: header?.signature ?? getRandomBytes(64), + signature: header?.signature ?? utils.getRandomBytes(64), }); /** @@ -82,10 +82,10 @@ export const createValidDefaultBlock = async ( previousBlockID: Buffer.from(genesis.header.id, 'hex'), timestamp: genesis.header.timestamp + 10, transactionRoot: txTree.root, - stateRoot: getRandomBytes(32), - eventRoot: getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), + eventRoot: utils.getRandomBytes(32), assetRoot, - validatorsHash: hash(getRandomBytes(32)), + validatorsHash: utils.hash(utils.getRandomBytes(32)), maxHeightGenerated: 0, maxHeightPrevoted: 0, aggregateCommit: { @@ -93,7 +93,7 @@ export const createValidDefaultBlock = async ( aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - generatorAddress: getAddressFromPublicKey(keypair.publicKey), + generatorAddress: address.getAddressFromPublicKey(keypair.publicKey), ...block?.header, }); diff --git a/elements/lisk-chain/test/utils/transaction.ts b/elements/lisk-chain/test/utils/transaction.ts index 497a72cf6bb..1c759f4dad8 100644 --- a/elements/lisk-chain/test/utils/transaction.ts +++ b/elements/lisk-chain/test/utils/transaction.ts @@ -29,12 +29,12 @@ export const genesisAddress = { export const getTransaction = (input?: { nonce?: bigint }): Transaction => { const tx = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt('10000000'), nonce: input?.nonce ?? BigInt(0), senderPublicKey: genesisAddress.publicKey, - params: getRandomBytes(128), + params: utils.getRandomBytes(128), signatures: [], }); const signature = signData( diff --git a/elements/lisk-client/test/lisk-cryptography/buffer.spec.ts b/elements/lisk-client/test/lisk-cryptography/buffer.spec.ts index cf5f3840081..c708f37456a 100644 --- a/elements/lisk-client/test/lisk-cryptography/buffer.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/buffer.spec.ts @@ -88,7 +88,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt8(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 1 byte buffer when size=1, endian=little', () => { @@ -99,7 +99,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt8(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 2 bytes big endian buffer when size=2, endian=big', () => { @@ -110,7 +110,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt16BE(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 2 bytes little endian buffer when size=2, endian=little', () => { @@ -121,7 +121,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt16LE(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 4 bytes big endian buffer when size=4, endian=big', () => { @@ -132,7 +132,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt32BE(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 4 bytes little endian buffer when size=4, endian=little', () => { @@ -143,7 +143,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt32LE(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 4 bytes big endian buffer when no size or endian is given', () => { @@ -153,7 +153,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt32BE(value, 0); - expect(intToBuffer(value, size)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size)).toEqual(expectedBuffer); }); it('should convert a integer to a 8 bytes big endian buffer when size=8, endian=big', () => { @@ -163,7 +163,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.from('00cebcaa8d34153d', 'hex'); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 8 bytes little endian buffer when size=8, endian=little', () => { @@ -173,7 +173,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.from('3d15348daabcce00', 'hex'); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 8 bytes big endian buffer when size=8 and endian is not given', () => { @@ -182,7 +182,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.from('00cebcaa8d34153d', 'hex'); - expect(intToBuffer(value, size)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size)).toEqual(expectedBuffer); }); }); }); diff --git a/elements/lisk-client/test/lisk-cryptography/keys.spec.ts b/elements/lisk-client/test/lisk-cryptography/keys.spec.ts index 767f6998889..5be91867459 100644 --- a/elements/lisk-client/test/lisk-cryptography/keys.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/keys.spec.ts @@ -97,9 +97,9 @@ describe('keys', () => { }); }); - describe('#getAddressFromPublicKey', () => { + describe('#address.getAddressFromPublicKey', () => { it('should generate address from publicKey', () => { - const address = getAddressFromPublicKey(defaultPublicKey); + const address = address.getAddressFromPublicKey(defaultPublicKey); expect(address).toEqual(defaultAddress); }); }); diff --git a/elements/lisk-cryptography/benchmark/nacl.js b/elements/lisk-cryptography/benchmark/nacl.js index 3968533e0c3..948702a1ad5 100644 --- a/elements/lisk-cryptography/benchmark/nacl.js +++ b/elements/lisk-cryptography/benchmark/nacl.js @@ -96,10 +96,10 @@ const verifyDetachedBenchmark = new Benchmark.Suite('verifyDetached') const getRandomBytesBenchmark = new Benchmark.Suite('getRandomBytes') .add('fast.getRandomBytes', () => { - fast.getRandomBytes(24); + fast.utils.getRandomBytes(24); }) .add('slow.getRandomBytes', () => { - slow.getRandomBytes(24); + slow.utils.getRandomBytes(24); }); const getKeyPairBenchmark = new Benchmark.Suite('getKeyPair') diff --git a/elements/lisk-cryptography/test/buffer.spec.ts b/elements/lisk-cryptography/test/buffer.spec.ts index 8c52aba5da4..83bd3faaa96 100644 --- a/elements/lisk-cryptography/test/buffer.spec.ts +++ b/elements/lisk-cryptography/test/buffer.spec.ts @@ -85,7 +85,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt8(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 1 byte buffer when size=1, endian=little', () => { @@ -96,7 +96,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt8(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 2 bytes big endian buffer when size=2, endian=big', () => { @@ -107,7 +107,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt16BE(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 2 bytes little endian buffer when size=2, endian=little', () => { @@ -118,7 +118,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt16LE(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 4 bytes big endian buffer when size=4, endian=big', () => { @@ -129,7 +129,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt32BE(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 4 bytes little endian buffer when size=4, endian=little', () => { @@ -140,7 +140,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt32LE(value, 0); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 4 bytes big endian buffer when no size or endian is given', () => { @@ -150,7 +150,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt32BE(value, 0); - expect(intToBuffer(value, size)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size)).toEqual(expectedBuffer); }); it('should convert a integer to a 8 bytes big endian buffer when size=8, endian=big', () => { @@ -160,7 +160,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.from('00cebcaa8d34153d', 'hex'); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 8 bytes little endian buffer when size=8, endian=little', () => { @@ -170,7 +170,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.from('3d15348daabcce00', 'hex'); - expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 8 bytes big endian buffer when size=8 and endian is not given', () => { @@ -179,7 +179,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.from('00cebcaa8d34153d', 'hex'); - expect(intToBuffer(value, size)).toEqual(expectedBuffer); + expect(utils.intToBuffer(value, size)).toEqual(expectedBuffer); }); }); }); diff --git a/elements/lisk-cryptography/test/nacl/index.spec.ts b/elements/lisk-cryptography/test/nacl/index.spec.ts index 3234866ada7..3820b4aacb7 100644 --- a/elements/lisk-cryptography/test/nacl/index.spec.ts +++ b/elements/lisk-cryptography/test/nacl/index.spec.ts @@ -56,7 +56,7 @@ describe('nacl index.js', () => { // Act // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require const nacl = require('../../src/nacl'); - nacl.getRandomBytes(8); + nacl.utils.getRandomBytes(8); // Assert expect(sodiumMock).toHaveBeenCalledTimes(1); }); @@ -66,7 +66,7 @@ describe('nacl index.js', () => { process.env.NACL_FAST = 'disable'; // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require const nacl = require('../../src/nacl'); - nacl.getRandomBytes(8); + nacl.utils.getRandomBytes(8); // Assert expect(tweetMock).toHaveBeenCalledTimes(1); }); @@ -77,7 +77,7 @@ describe('nacl index.js', () => { // Act // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require const nacl = require('../../src/nacl'); - nacl.getRandomBytes(8); + nacl.utils.getRandomBytes(8); // Assert expect(sodiumMock).toHaveBeenCalledTimes(1); }); @@ -103,7 +103,7 @@ describe('nacl index.js', () => { // Act // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require const nacl = require('../../src/nacl'); - nacl.getRandomBytes(8); + nacl.utils.getRandomBytes(8); // Assert expect(tweetMock).toHaveBeenCalledTimes(1); }); diff --git a/elements/lisk-cryptography/test/nacl/nacl.spec.ts b/elements/lisk-cryptography/test/nacl/nacl.spec.ts index d385ea62cf6..de6c6b3f180 100644 --- a/elements/lisk-cryptography/test/nacl/nacl.spec.ts +++ b/elements/lisk-cryptography/test/nacl/nacl.spec.ts @@ -68,7 +68,7 @@ describe('nacl', () => { let randomBuffer: Buffer; beforeEach(async () => { - randomBuffer = getRandomBytes(size); + randomBuffer = utils.getRandomBytes(size); return Promise.resolve(); }); diff --git a/elements/lisk-p2p/src/constants.ts b/elements/lisk-p2p/src/constants.ts index eb68b329117..f25e484a785 100644 --- a/elements/lisk-p2p/src/constants.ts +++ b/elements/lisk-p2p/src/constants.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; // General P2P constants export const DEFAULT_MESSAGE_ENCODING_FORMAT = 'base64'; @@ -30,7 +30,7 @@ export const DEFAULT_RATE_CALCULATION_INTERVAL = 1000; export const DEFAULT_WS_MAX_PAYLOAD = 3048576; // Size in bytes export const DEFAULT_NONCE_LENGTH_BYTES = 8; const SECRET_BYTE_LENGTH = 4; -export const DEFAULT_RANDOM_SECRET = getRandomBytes(SECRET_BYTE_LENGTH).readUInt32BE(0); +export const DEFAULT_RANDOM_SECRET = utils.getRandomBytes(SECRET_BYTE_LENGTH).readUInt32BE(0); export const DEFAULT_MAX_OUTBOUND_CONNECTIONS = 20; export const DEFAULT_MAX_INBOUND_CONNECTIONS = 100; diff --git a/elements/lisk-p2p/src/p2p.ts b/elements/lisk-p2p/src/p2p.ts index d940bc92f9f..ef89d27f80c 100644 --- a/elements/lisk-p2p/src/p2p.ts +++ b/elements/lisk-p2p/src/p2p.ts @@ -14,7 +14,7 @@ */ import { EventEmitter } from 'events'; import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { isIPV4 } from '@liskhq/lisk-validator'; import { @@ -568,7 +568,7 @@ export class P2P extends EventEmitter { this._nodeInfo = { ...config.nodeInfo, - nonce: getRandomBytes(DEFAULT_NONCE_LENGTH_BYTES).toString('hex'), + nonce: utils.getRandomBytes(DEFAULT_NONCE_LENGTH_BYTES).toString('hex'), }; this.applyNodeInfo(this._nodeInfo); diff --git a/elements/lisk-p2p/src/utils/network.ts b/elements/lisk-p2p/src/utils/network.ts index bbd7644d270..87ed419e0a7 100644 --- a/elements/lisk-p2p/src/utils/network.ts +++ b/elements/lisk-p2p/src/utils/network.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { isIPv4 } from 'net'; // eslint-disable-next-line import/no-cycle @@ -111,7 +111,7 @@ export const getNetgroup = (address: string, secret: number): number => { const netgroupBytes = Buffer.concat([secretBytes, networkBytes, aBytes, bBytes]); - return hash(netgroupBytes).readUInt32BE(0); + return utils.hash(netgroupBytes).readUInt32BE(0); }; export const constructPeerId = (ipAddress: string, port: number): string => `${ipAddress}:${port}`; @@ -187,7 +187,7 @@ export const getBucketId = (options: { // Separate buckets for local and private addresses if (network !== NETWORK.NET_IPV4) { - return hash(Buffer.concat([secretBytes, networkBytes])).readUInt32BE(0) % bucketCount; + return utils.hash(Buffer.concat([secretBytes, networkBytes])).readUInt32BE(0) % bucketCount; } const addressBytes = Buffer.concat([targetABytes, targetBBytes, targetCBytes, targetDBytes]); @@ -201,17 +201,20 @@ export const getBucketId = (options: { 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; + ? utils + .hash( + Buffer.concat([ + secretBytes, + networkBytes, + sourceBytes.aBytes, + sourceBytes.bBytes, + targetABytes, + targetBBytes, + ]), + ) + .readUInt32BE(0) % firstMod + : utils.hash(Buffer.concat([secretBytes, networkBytes, addressBytes])).readUInt32BE(0) % + firstMod; kBytes.writeUInt32BE(k, 0); @@ -222,5 +225,5 @@ export const getBucketId = (options: { ? Buffer.concat([secretBytes, networkBytes, sourceBytes.aBytes, sourceBytes.bBytes, kBytes]) : Buffer.concat([secretBytes, networkBytes, targetABytes, targetBBytes, kBytes]); - return hash(bucketBytes).readUInt32BE(0) % bucketCount; + return utils.hash(bucketBytes).readUInt32BE(0) % bucketCount; }; diff --git a/elements/lisk-transaction-pool/src/transaction_pool.ts b/elements/lisk-transaction-pool/src/transaction_pool.ts index 92ef2c0dee5..54e21cbdc4d 100644 --- a/elements/lisk-transaction-pool/src/transaction_pool.ts +++ b/elements/lisk-transaction-pool/src/transaction_pool.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { getAddressFromPublicKey } from '@liskhq/lisk-cryptography'; +import { address } from '@liskhq/lisk-cryptography'; import * as createDebug from 'debug'; import { EventEmitter } from 'events'; import { dataStructures } from '@liskhq/lisk-utils'; @@ -209,7 +209,7 @@ export class TransactionPool { } } - const incomingTxAddress = getAddressFromPublicKey(incomingTx.senderPublicKey); + const incomingTxAddress = address.getAddressFromPublicKey(incomingTx.senderPublicKey); // _applyFunction is injected from chain module applyTransaction let txStatus; @@ -296,7 +296,7 @@ export class TransactionPool { this._allTransactions.delete(tx.id); debug('Removing from transaction pool with id', tx.id); - const senderId = getAddressFromPublicKey(foundTx.senderPublicKey); + const senderId = address.getAddressFromPublicKey(foundTx.senderPublicKey); (this._transactionList.get(senderId) as TransactionList).remove(tx.nonce); if ((this._transactionList.get(senderId) as TransactionList).size === 0) { this._transactionList.delete(senderId); diff --git a/elements/lisk-transaction-pool/test/unit/transaction_pool.spec.ts b/elements/lisk-transaction-pool/test/unit/transaction_pool.spec.ts index b5a9ec9aa60..a8b53f55ec1 100644 --- a/elements/lisk-transaction-pool/test/unit/transaction_pool.spec.ts +++ b/elements/lisk-transaction-pool/test/unit/transaction_pool.spec.ts @@ -189,24 +189,24 @@ describe('TransactionPool class', () => { await transactionPool.add(tx); } (transactionPool as any)._transactionList - .get(getAddressFromPublicKey(senderPublicKeys[0])) + .get(address.getAddressFromPublicKey(senderPublicKeys[0])) .promote([txs[0]]); (transactionPool as any)._transactionList - .get(getAddressFromPublicKey(senderPublicKeys[1])) + .get(address.getAddressFromPublicKey(senderPublicKeys[1])) .promote([txs[3]]); // Force to make it unprocessable (transactionPool['_transactionList'].get( - getAddressFromPublicKey(senderPublicKeys[2]), + address.getAddressFromPublicKey(senderPublicKeys[2]), ) as TransactionList)['_demoteAfter'](BigInt(0)); }); it('should return copy of processable transactions list', () => { const processableTransactions = transactionPool.getProcessableTransactions(); const transactionFromSender0 = processableTransactions.get( - getAddressFromPublicKey(senderPublicKeys[0]), + address.getAddressFromPublicKey(senderPublicKeys[0]), ); const transactionFromSender1 = processableTransactions.get( - getAddressFromPublicKey(senderPublicKeys[1]), + address.getAddressFromPublicKey(senderPublicKeys[1]), ); expect(transactionFromSender0).toHaveLength(1); @@ -214,24 +214,27 @@ describe('TransactionPool class', () => { expect(transactionFromSender1).toHaveLength(1); expect((transactionFromSender1 as Transaction[])[0].nonce.toString()).toEqual('1'); // Check if it is a copy - processableTransactions.delete(getAddressFromPublicKey(senderPublicKeys[0])); - (processableTransactions as any).get(getAddressFromPublicKey(senderPublicKeys[1]))[0] = - 'random thing'; + processableTransactions.delete(address.getAddressFromPublicKey(senderPublicKeys[0])); + (processableTransactions as any).get( + address.getAddressFromPublicKey(senderPublicKeys[1]), + )[0] = 'random thing'; expect( - (transactionPool as any)._transactionList.get(getAddressFromPublicKey(senderPublicKeys[0])), + (transactionPool as any)._transactionList.get( + address.getAddressFromPublicKey(senderPublicKeys[0]), + ), ).not.toBeUndefined(); expect( transactionPool .getProcessableTransactions() - .get(getAddressFromPublicKey(senderPublicKeys[1])), + .get(address.getAddressFromPublicKey(senderPublicKeys[1])), ).toHaveLength(1); }); it('should not include the sender key if processable transactions are empty', () => { const processableTransactions = transactionPool.getProcessableTransactions(); const transactionFromSender2 = processableTransactions.get( - getAddressFromPublicKey(senderPublicKeys[2]), + address.getAddressFromPublicKey(senderPublicKeys[2]), ); expect(transactionFromSender2).toBeUndefined(); }); @@ -256,7 +259,7 @@ describe('TransactionPool class', () => { it('should throw error when transaction size is higher than maxPayloadLength', async () => { // Arrange const txGetBytesTempStub = jest.fn(); - tx.getBytes = txGetBytesTempStub.mockReturnValue(getRandomBytes(15400)); + tx.getBytes = txGetBytesTempStub.mockReturnValue(utils.getRandomBytes(15400)); // Act const { status } = await transactionPool.add(tx); txGetBytesTempStub.mockReset(); @@ -274,12 +277,12 @@ describe('TransactionPool class', () => { const originalTrxObj = transactionPool['_transactionList'] - .get(getAddressFromPublicKey(tx.senderPublicKey)) + .get(address.getAddressFromPublicKey(tx.senderPublicKey)) ?.get(BigInt(1)) ?? {}; expect(originalTrxObj).toEqual(tx); const trxSenderAddressList = transactionPool['_transactionList'].get( - getAddressFromPublicKey(tx.senderPublicKey), + address.getAddressFromPublicKey(tx.senderPublicKey), ); expect(trxSenderAddressList?.getProcessable()).toContain(originalTrxObj); }); @@ -300,12 +303,12 @@ describe('TransactionPool class', () => { const originalTrxObj = transactionPool['_transactionList'] - .get(getAddressFromPublicKey(tx.senderPublicKey)) + .get(address.getAddressFromPublicKey(tx.senderPublicKey)) ?.get(BigInt(1)) ?? {}; expect(originalTrxObj).toEqual(tx); const trxSenderAddressList = transactionPool['_transactionList'].get( - getAddressFromPublicKey(tx.senderPublicKey), + address.getAddressFromPublicKey(tx.senderPublicKey), ); expect(trxSenderAddressList?.getUnprocessable()).toContain(originalTrxObj); }); @@ -709,7 +712,7 @@ describe('TransactionPool class', () => { it('should return false when a tx id does not exist', () => { expect( transactionPool['_transactionList'] - .get(getAddressFromPublicKey(tx.senderPublicKey)) + .get(address.getAddressFromPublicKey(tx.senderPublicKey)) ?.get(tx.nonce), ).toEqual(tx); expect(transactionPool['_feePriorityQueue'].values).toContain(tx.id); @@ -730,7 +733,7 @@ describe('TransactionPool class', () => { it('should remove the transaction from _allTransactions, _transactionList and _feePriorityQueue', () => { expect( transactionPool['_transactionList'] - .get(getAddressFromPublicKey(tx.senderPublicKey)) + .get(address.getAddressFromPublicKey(tx.senderPublicKey)) ?.get(tx.nonce), ).toEqual(tx); expect(transactionPool['_feePriorityQueue'].values).toContain(tx.id); @@ -741,7 +744,7 @@ describe('TransactionPool class', () => { expect(transactionPool.getAll()).toHaveLength(1); expect( transactionPool['_transactionList'] - .get(getAddressFromPublicKey(tx.senderPublicKey)) + .get(address.getAddressFromPublicKey(tx.senderPublicKey)) ?.get(tx.nonce), ).toBeUndefined(); expect(transactionPool['_feePriorityQueue'].values).not.toContain(tx.id); @@ -751,7 +754,9 @@ describe('TransactionPool class', () => { transactionPool.remove(tx); transactionPool.remove(additionalTx); expect( - transactionPool['_transactionList'].get(getAddressFromPublicKey(tx.senderPublicKey)), + transactionPool['_transactionList'].get( + address.getAddressFromPublicKey(tx.senderPublicKey), + ), ).toBeUndefined(); }); }); diff --git a/elements/lisk-transaction-pool/test/utils/cryptography.ts b/elements/lisk-transaction-pool/test/utils/cryptography.ts index 77ba1ff830f..7b4cb4e8d02 100644 --- a/elements/lisk-transaction-pool/test/utils/cryptography.ts +++ b/elements/lisk-transaction-pool/test/utils/cryptography.ts @@ -20,4 +20,4 @@ export const generateRandomPublicKeys = (amount = 1): Array => return publicKey; }); -export const getIDAsKeyForStore = (id: number) => intToBuffer(id, 4); +export const getIDAsKeyForStore = (id: number) => utils.intToBuffer(id, 4); diff --git a/elements/lisk-transactions/src/constants.ts b/elements/lisk-transactions/src/constants.ts index d0d5160ee35..2874169d4eb 100644 --- a/elements/lisk-transactions/src/constants.ts +++ b/elements/lisk-transactions/src/constants.ts @@ -12,6 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -import { createMessageTag } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; -export const TAG_TRANSACTION = createMessageTag('TX'); +export const TAG_TRANSACTION = utils.createMessageTag('TX'); diff --git a/elements/lisk-transactions/src/sign.ts b/elements/lisk-transactions/src/sign.ts index 8a1c4a5bddf..7d9bfa8e47e 100644 --- a/elements/lisk-transactions/src/sign.ts +++ b/elements/lisk-transactions/src/sign.ts @@ -14,13 +14,7 @@ */ import { codec, Schema } from '@liskhq/lisk-codec'; -import { - getAddressAndPublicKeyFromPassphrase, - signData, - signDataWithPrivateKey, - hash, - getPublicKey, -} from '@liskhq/lisk-cryptography'; +import { utils, ed, address } from '@liskhq/lisk-cryptography'; import { validateTransaction } from './validate'; import { baseTransactionSchema } from './schema'; import { TAG_TRANSACTION } from './constants'; @@ -97,7 +91,7 @@ export const signTransaction = ( if (validationErrors) { throw validationErrors; } - const { publicKey } = getAddressAndPublicKeyFromPassphrase(passphrase); + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(passphrase); if ( !Buffer.isBuffer(transactionObject.senderPublicKey) || @@ -106,7 +100,7 @@ export const signTransaction = ( throw new Error('Transaction senderPublicKey does not match public key from passphrase'); } - const signature = signData( + const signature = ed.signData( TAG_TRANSACTION, networkIdentifier, getSigningBytes(transactionObject, paramsSchema), @@ -114,7 +108,7 @@ export const signTransaction = ( ); // eslint-disable-next-line no-param-reassign transactionObject.signatures = [signature]; - return { ...transactionObject, id: hash(getBytes(transactionObject, paramsSchema)) }; + return { ...transactionObject, id: utils.hash(getBytes(transactionObject, paramsSchema)) }; }; const sanitizeSignaturesArray = ( @@ -165,8 +159,8 @@ export const signMultiSignatureTransaction = ( keys.mandatoryKeys.sort((publicKeyA, publicKeyB) => publicKeyA.compare(publicKeyB)); keys.optionalKeys.sort((publicKeyA, publicKeyB) => publicKeyA.compare(publicKeyB)); - const { publicKey } = getAddressAndPublicKeyFromPassphrase(passphrase); - const signature = signData( + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(passphrase); + const signature = ed.signData( TAG_TRANSACTION, networkIdentifier, getSigningBytes(transactionObject, paramsSchema), @@ -205,7 +199,7 @@ export const signMultiSignatureTransaction = ( sanitizeSignaturesArray(transactionObject, keys, includeSenderSignature); - return { ...transactionObject, id: hash(getBytes(transactionObject, paramsSchema)) }; + return { ...transactionObject, id: utils.hash(getBytes(transactionObject, paramsSchema)) }; }; export const signTransactionWithPrivateKey = ( @@ -232,7 +226,7 @@ export const signTransactionWithPrivateKey = ( getSigningBytes(transactionObject, paramsSchema), ]); - const signature = signDataWithPrivateKey( + const signature = ed.signDataWithPrivateKey( TAG_TRANSACTION, networkIdentifier, transactionWithNetworkIdentifierBytes, @@ -241,7 +235,7 @@ export const signTransactionWithPrivateKey = ( // eslint-disable-next-line no-param-reassign transactionObject.signatures = [signature]; - return { ...transactionObject, id: hash(getBytes(transactionObject, paramsSchema)) }; + return { ...transactionObject, id: utils.hash(getBytes(transactionObject, paramsSchema)) }; }; export const signMultiSignatureTransactionWithPrivateKey = ( @@ -278,14 +272,14 @@ export const signMultiSignatureTransactionWithPrivateKey = ( getSigningBytes(transactionObject, paramsSchema), ]); - const signature = signDataWithPrivateKey( + const signature = ed.signDataWithPrivateKey( TAG_TRANSACTION, networkIdentifier, transactionWithNetworkIdentifierBytes, privateKey, ); - const signerPublicKey = getPublicKey(privateKey); + const signerPublicKey = ed.getPublicKeyFromPrivateKey(privateKey); if ( includeSenderSignature && @@ -321,5 +315,5 @@ export const signMultiSignatureTransactionWithPrivateKey = ( sanitizeSignaturesArray(transactionObject, keys, includeSenderSignature); - return { ...transactionObject, id: hash(getBytes(transactionObject, paramsSchema)) }; + return { ...transactionObject, id: utils.hash(getBytes(transactionObject, paramsSchema)) }; }; diff --git a/elements/lisk-transactions/test/fee.spec.ts b/elements/lisk-transactions/test/fee.spec.ts index 854e2dda163..f4d7a7eb961 100644 --- a/elements/lisk-transactions/test/fee.spec.ts +++ b/elements/lisk-transactions/test/fee.spec.ts @@ -44,8 +44,8 @@ describe('fee', () => { const passphrase1 = 'trim elegant oven term access apple obtain error grain excite lawn neck'; const { publicKey: publicKey1 } = getAddressAndPublicKeyFromPassphrase(passphrase1); const validTransaction = { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('1'), senderPublicKey: publicKey1, params: { @@ -56,18 +56,18 @@ describe('fee', () => { }; const baseFees = [ { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), baseFee: '10000000', }, { - moduleID: intToBuffer(5, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(5, 4), + commandID: utils.intToBuffer(0, 4), baseFee: '1', }, { - moduleID: intToBuffer(3, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(3, 4), + commandID: utils.intToBuffer(0, 4), baseFee: '1', }, ]; @@ -131,8 +131,8 @@ describe('fee', () => { // Arrange const delegateRegisterTransaction = { ...validTransaction, - moduleID: intToBuffer(5, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(5, 4), + commandID: utils.intToBuffer(0, 4), params: { username: 'delegate1' }, }; const options = { minFeePerByte: 1000, baseFees, numberOfSignatures: 1 }; diff --git a/elements/lisk-transactions/test/sign.spec.ts b/elements/lisk-transactions/test/sign.spec.ts index 4fe1f0ca163..2688f358aa6 100644 --- a/elements/lisk-transactions/test/sign.spec.ts +++ b/elements/lisk-transactions/test/sign.spec.ts @@ -112,8 +112,8 @@ describe('sign', () => { }; const validTransaction = { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('1'), fee: BigInt('10000000'), senderPublicKey: publicKey1, @@ -534,8 +534,8 @@ describe('sign', () => { const optionalKeys = [account3.publicKey]; const multisignatureRegistrationTrx = { - moduleID: intToBuffer(4, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(4, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('1'), fee: BigInt('10000000'), senderPublicKey: account1.publicKey, @@ -598,8 +598,8 @@ describe('sign', () => { const account2 = getPrivateAndPublicKeyFromPassphrase(passphrase2); // Sender public key of account1 const transaction = { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('1'), fee: BigInt('10000000'), senderPublicKey: account1.publicKey, diff --git a/elements/lisk-transactions/test/validate.spec.ts b/elements/lisk-transactions/test/validate.spec.ts index 653abb41c7a..a9b47e65adf 100644 --- a/elements/lisk-transactions/test/validate.spec.ts +++ b/elements/lisk-transactions/test/validate.spec.ts @@ -13,14 +13,14 @@ * */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { validateTransaction } from '../src/validate'; describe('validateTransaction', () => { // Arrange const validTransaction = { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('1'), fee: BigInt('10000000'), senderPublicKey: Buffer.from( diff --git a/elements/lisk-tree/benchmark/merkle_root.js b/elements/lisk-tree/benchmark/merkle_root.js index 93c6e5bb29b..8b5402e3d99 100644 --- a/elements/lisk-tree/benchmark/merkle_root.js +++ b/elements/lisk-tree/benchmark/merkle_root.js @@ -21,7 +21,7 @@ const size = 150; const testSamples = []; for (let i = 0; i < size; i += 1) { - testSamples.push(getRandomBytes(32)); + testSamples.push(utils.getRandomBytes(32)); } suite diff --git a/elements/lisk-tree/src/merkle_tree/calculate.ts b/elements/lisk-tree/src/merkle_tree/calculate.ts index ff1b5041228..49ff7d8c4f6 100644 --- a/elements/lisk-tree/src/merkle_tree/calculate.ts +++ b/elements/lisk-tree/src/merkle_tree/calculate.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash } from '../../../lisk-cryptography/dist-node'; +import { utils } from '../../../lisk-cryptography'; import { LEAF_PREFIX } from './constants'; import { calculatePathNodes, ROOT_INDEX } from './utils'; @@ -41,7 +41,7 @@ export const calculateRootFromUpdateData = ( [LEAF_PREFIX, data], LEAF_PREFIX.length + data.length, ); - const leafHash = hash(leafValueWithoutNodeIndex); + const leafHash = utils.hash(leafValueWithoutNodeIndex); updateHashes.push(leafHash); } diff --git a/elements/lisk-tree/src/merkle_tree/constants.ts b/elements/lisk-tree/src/merkle_tree/constants.ts index fa67be4f6dd..272b6e858de 100644 --- a/elements/lisk-tree/src/merkle_tree/constants.ts +++ b/elements/lisk-tree/src/merkle_tree/constants.ts @@ -11,9 +11,9 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; -export const EMPTY_HASH = hash(Buffer.alloc(0)); +export const EMPTY_HASH = utils.hash(Buffer.alloc(0)); export const LEAF_PREFIX = Buffer.from('00', 'hex'); export const BRANCH_PREFIX = Buffer.from('01', 'hex'); export const LAYER_INDEX_SIZE = 1; diff --git a/elements/lisk-tree/src/merkle_tree/merkle_tree.ts b/elements/lisk-tree/src/merkle_tree/merkle_tree.ts index d5b375d7b3f..696065be818 100644 --- a/elements/lisk-tree/src/merkle_tree/merkle_tree.ts +++ b/elements/lisk-tree/src/merkle_tree/merkle_tree.ts @@ -14,7 +14,7 @@ /* eslint-disable no-bitwise */ /* eslint-disable @typescript-eslint/prefer-for-of */ -import { hash } from '../../../lisk-cryptography/dist-node'; +import { utils } from '../../../lisk-cryptography'; import { LAYER_INDEX_SIZE, NODE_HASH_SIZE, @@ -180,7 +180,7 @@ export class MerkleTree { [LEAF_PREFIX, data], LEAF_PREFIX.length + data.length, ); - const leafHash = hash(leafValueWithoutNodeIndex); + const leafHash = utils.hash(leafValueWithoutNodeIndex); updateHashes.push(leafHash); } const siblingHashes = await this._getSiblingHashes(idxs); @@ -278,7 +278,7 @@ export class MerkleTree { [LEAF_PREFIX, value], LEAF_PREFIX.length + value.length, ); - const leafHash = this._preHashedLeaf ? value : hash(leafValueWithoutNodeIndex); + const leafHash = this._preHashedLeaf ? value : utils.hash(leafValueWithoutNodeIndex); // We include nodeIndex into the value to allow for nodeIndex retrieval for leaf nodes const leafValueWithNodeIndex = Buffer.concat( [LEAF_PREFIX, nodeIndexBuffer, value], diff --git a/elements/lisk-tree/src/merkle_tree/utils.ts b/elements/lisk-tree/src/merkle_tree/utils.ts index 69248b203af..059bef2a8d1 100644 --- a/elements/lisk-tree/src/merkle_tree/utils.ts +++ b/elements/lisk-tree/src/merkle_tree/utils.ts @@ -13,7 +13,7 @@ */ /* eslint-disable no-bitwise */ -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { binarySearch } from '../utils'; import { BRANCH_PREFIX, LEAF_PREFIX, EMPTY_HASH } from './constants'; import { NodeLocation, MerkleRootInfo } from './types'; @@ -21,7 +21,7 @@ import { NodeLocation, MerkleRootInfo } from './types'; export const isLeaf = (value: Buffer): boolean => value[0] === LEAF_PREFIX[0]; export const generateHash = (prefix: Buffer, leftHash: Buffer, rightHash: Buffer): Buffer => - hash( + utils.hash( Buffer.concat( [prefix, leftHash, rightHash], prefix.length + leftHash.length + rightHash.length, @@ -91,7 +91,7 @@ export const calculateMerkleRoot = ({ value, appendPath, size }: MerkleRootInfo) ); // Set current hash to hash of value - const newLeafHash = hash(leafValueWithPrefix); + const newLeafHash = utils.hash(leafValueWithPrefix); let currentHash = newLeafHash; // Count the 1's in binaryLength @@ -147,7 +147,7 @@ export const calculateMerkleRootWithLeaves = (data: Buffer[]): Buffer => { LEAF_PREFIX.length + data[0].length, ); - return hash(leafValueWithPrefix); + return utils.hash(leafValueWithPrefix); } const k = largestPowerOfTwoSmallerThan(data.length); diff --git a/elements/lisk-tree/src/merkle_tree/verify_proof.ts b/elements/lisk-tree/src/merkle_tree/verify_proof.ts index cc98e2c5a0c..6d9fa48d060 100644 --- a/elements/lisk-tree/src/merkle_tree/verify_proof.ts +++ b/elements/lisk-tree/src/merkle_tree/verify_proof.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { LEAF_PREFIX } from './constants'; import { Proof } from './types'; import { calculatePathNodes, ROOT_INDEX } from './utils'; @@ -49,7 +49,7 @@ export const verifyDataBlock = ( [LEAF_PREFIX, data], LEAF_PREFIX.length + data.length, ); - const leafHash = hash(leafValueWithoutNodeIndex); + const leafHash = utils.hash(leafValueWithoutNodeIndex); queryHashes.push(leafHash); } diff --git a/elements/lisk-tree/src/sparse_merkle_tree/branch.ts b/elements/lisk-tree/src/sparse_merkle_tree/branch.ts index 6f402f39691..dca59d51877 100644 --- a/elements/lisk-tree/src/sparse_merkle_tree/branch.ts +++ b/elements/lisk-tree/src/sparse_merkle_tree/branch.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { branchData } from './utils'; import { NodeSide } from './constants'; @@ -26,7 +26,7 @@ export class Branch { this._leftHash = leftHash; this._rightHash = rightHash; this._data = branchData(this._leftHash, this._rightHash); - this._hash = hash(this._data); + this._hash = utils.hash(this._data); } public get hash() { @@ -49,6 +49,6 @@ export class Branch { this._rightHash = newChild; } this._data = branchData(this.leftHash, this.rightHash); - this._hash = hash(this.data); + this._hash = utils.hash(this.data); } } diff --git a/elements/lisk-tree/src/sparse_merkle_tree/constants.ts b/elements/lisk-tree/src/sparse_merkle_tree/constants.ts index a899614034d..c480789d371 100644 --- a/elements/lisk-tree/src/sparse_merkle_tree/constants.ts +++ b/elements/lisk-tree/src/sparse_merkle_tree/constants.ts @@ -12,10 +12,10 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const EMPTY_VALUE = Buffer.alloc(0); -export const EMPTY_HASH = hash(EMPTY_VALUE); +export const EMPTY_HASH = utils.hash(EMPTY_VALUE); export const LEAF_HASH_PREFIX = Buffer.from('00', 'hex'); export const BRANCH_HASH_PREFIX = Buffer.from('01', 'hex'); diff --git a/elements/lisk-tree/src/sparse_merkle_tree/leaf.ts b/elements/lisk-tree/src/sparse_merkle_tree/leaf.ts index 2df902f066c..a075df5111f 100644 --- a/elements/lisk-tree/src/sparse_merkle_tree/leaf.ts +++ b/elements/lisk-tree/src/sparse_merkle_tree/leaf.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { leafData } from './utils'; export class Leaf { @@ -25,7 +25,7 @@ export class Leaf { this._key = key; this._value = value; this._data = leafData(this._key, this._value); - this._hash = hash(this._data); + this._hash = utils.hash(this._data); } public get hash() { @@ -44,6 +44,6 @@ export class Leaf { public update(newValue: Buffer) { this._value = newValue; this._data = leafData(this._key, this._value); - this._hash = hash(this._data); + this._hash = utils.hash(this._data); } } diff --git a/elements/lisk-tree/src/sparse_merkle_tree/utils.ts b/elements/lisk-tree/src/sparse_merkle_tree/utils.ts index 43fbfaea633..ab15bf27a24 100644 --- a/elements/lisk-tree/src/sparse_merkle_tree/utils.ts +++ b/elements/lisk-tree/src/sparse_merkle_tree/utils.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { objects } from '@liskhq/lisk-utils'; import { BRANCH_HASH_PREFIX, EMPTY_HASH, LEAF_HASH_PREFIX, NODE_HASH_SIZE } from './constants'; import { Query, Proof } from './types'; @@ -167,7 +167,7 @@ export const calculateRoot = (sibHashes: Buffer[], queries: Query[], keyLength: key: q.key, value: q.value, binaryBitmap: bufferToBinaryString(q.bitmap), - hash: q.value.byteLength === 0 ? EMPTY_HASH : hash(leafData(q.key, q.value)), + hash: q.value.byteLength === 0 ? EMPTY_HASH : utils.hash(leafData(q.key, q.value)), }); } @@ -210,9 +210,9 @@ export const calculateRoot = (sibHashes: Buffer[], queries: Query[], keyLength: const d = binaryKey[h - 1]; if (d === '0') { - q.hash = hash(branchData(q.hash, siblingHash)); + q.hash = utils.hash(branchData(q.hash, siblingHash)); } else if (d === '1') { - q.hash = hash(branchData(siblingHash, q.hash)); + q.hash = utils.hash(branchData(siblingHash, q.hash)); } q.binaryBitmap = q.binaryBitmap.substring(1); diff --git a/elements/lisk-tree/test/sparse_merkle_tree/utils.spec.ts b/elements/lisk-tree/test/sparse_merkle_tree/utils.spec.ts index a6a07068614..9082afd4fc1 100644 --- a/elements/lisk-tree/test/sparse_merkle_tree/utils.spec.ts +++ b/elements/lisk-tree/test/sparse_merkle_tree/utils.spec.ts @@ -58,12 +58,12 @@ describe('utils', () => { describe('sortByBitmapAndKey', () => { it('should sort by longest bitmap', () => { const res1 = { - key: getRandomBytes(2), + key: utils.getRandomBytes(2), binaryBitmap: '011', }; const res2 = { - key: getRandomBytes(2), + key: utils.getRandomBytes(2), binaryBitmap: '0011', }; @@ -72,12 +72,12 @@ describe('utils', () => { it('should sort by longest bitmap breaking tie with smaller key', () => { const res1 = { - key: getRandomBytes(2), + key: utils.getRandomBytes(2), binaryBitmap: '111', }; const res2 = { - key: getRandomBytes(1), + key: utils.getRandomBytes(1), binaryBitmap: '111', }; @@ -503,7 +503,7 @@ describe('utils', () => { })); it('should get key value of 38 bytes from leaf data buffer', () => { - const key38Bytes = getRandomBytes(38); + const key38Bytes = utils.getRandomBytes(38); const leafDataWith38ByteKey = leafData(key38Bytes, sampleValue); expect(parseLeafData(leafDataWith38ByteKey, key38Bytes.byteLength)).toEqual({ diff --git a/framework-plugins/lisk-framework-dashboard-plugin/src/ui/pages/MainPage.tsx b/framework-plugins/lisk-framework-dashboard-plugin/src/ui/pages/MainPage.tsx index 72ce81d35c6..8dc9b4a371b 100644 --- a/framework-plugins/lisk-framework-dashboard-plugin/src/ui/pages/MainPage.tsx +++ b/framework-plugins/lisk-framework-dashboard-plugin/src/ui/pages/MainPage.tsx @@ -227,10 +227,10 @@ const MainPage: React.FC = () => { const generateNewAccount = () => { const accountPassphrase = (passphrase.Mnemonic.generateMnemonic() as unknown) as string; - const { address, publicKey } = cryptography.getAddressAndPublicKeyFromPassphrase( + const { address, publicKey } = cryptography.address.getAddressAndPublicKeyFromPassphrase( accountPassphrase, ); - const lisk32Address = cryptography.getLisk32AddressFromAddress(address); + const lisk32Address = cryptography.address.getLisk32AddressFromAddress(address); const newAccount: Account = { passphrase: accountPassphrase, publicKey: publicKey.toString('hex'), @@ -275,7 +275,7 @@ const MainPage: React.FC = () => { // Send Transaction const handleSendTransaction = async (data: SendTransactionOptions) => { try { - const { publicKey, address } = cryptography.getAddressAndPublicKeyFromPassphrase( + const { publicKey, address } = cryptography.address.getAddressAndPublicKeyFromPassphrase( data.passphrase, ); const moduleMeta = getClient().metadata.find(a => a.id === data.moduleID); diff --git a/framework-plugins/lisk-framework-faucet-plugin/src/plugin/endpoint.ts b/framework-plugins/lisk-framework-faucet-plugin/src/plugin/endpoint.ts index ec13c7d20b1..58583cb2cdc 100644 --- a/framework-plugins/lisk-framework-faucet-plugin/src/plugin/endpoint.ts +++ b/framework-plugins/lisk-framework-faucet-plugin/src/plugin/endpoint.ts @@ -12,7 +12,6 @@ * Removal or modification of this copyright notice is prohibited. */ -import { EncryptedPassphraseObject, intToBuffer } from '@liskhq/lisk-cryptography'; import axios from 'axios'; import { BasePluginEndpoint, @@ -48,16 +47,16 @@ export class Endpoint extends BasePluginEndpoint { const { enable, password } = context.params; try { - const parsedEncryptedPassphrase = cryptography.parseEncryptedPassphrase( + const parsedEncryptedPassphrase = cryptography.encrypt.parseEncryptedPassphrase( this._config.encryptedPassphrase, ); - const passphrase = await cryptography.decryptPassphraseWithPassword( - parsedEncryptedPassphrase as EncryptedPassphraseObject, + const passphrase = await cryptography.encrypt.decryptPassphraseWithPassword( + parsedEncryptedPassphrase as cryptography.encrypt.EncryptedPassphraseObject, password as string, ); - const { publicKey } = cryptography.getAddressAndPublicKeyFromPassphrase(passphrase); + const { publicKey } = cryptography.address.getAddressAndPublicKeyFromPassphrase(passphrase); this._state.publicKey = enable ? publicKey : undefined; this._state.passphrase = enable ? passphrase : undefined; @@ -113,8 +112,8 @@ export class Endpoint extends BasePluginEndpoint { const transaction = await this._client.transaction.create( { - moduleID: intToBuffer(2, 4).toString('hex'), - commandID: intToBuffer(0, 4).toString('hex'), + moduleID: cryptography.utils.intToBuffer(2, 4).toString('hex'), + commandID: cryptography.utils.intToBuffer(0, 4).toString('hex'), senderPublicKey: this._state.publicKey?.toString('hex'), fee: transactions.convertLSKToBeddows(this._config.fee), // TODO: The static fee should be replaced by fee estimation calculation params: transferTransactionParams, diff --git a/framework-plugins/lisk-framework-faucet-plugin/src/plugin/faucet_plugin.ts b/framework-plugins/lisk-framework-faucet-plugin/src/plugin/faucet_plugin.ts index 47ba55f51ec..1a5327c50b8 100644 --- a/framework-plugins/lisk-framework-faucet-plugin/src/plugin/faucet_plugin.ts +++ b/framework-plugins/lisk-framework-faucet-plugin/src/plugin/faucet_plugin.ts @@ -11,8 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { getLisk32AddressFromPublicKey } from '@liskhq/lisk-cryptography'; -import { BasePlugin, PluginInitContext } from 'lisk-sdk'; +import { BasePlugin, PluginInitContext, cryptography } from 'lisk-sdk'; import * as express from 'express'; import { join } from 'path'; import { Server } from 'http'; @@ -48,7 +47,7 @@ export class FaucetPlugin extends BasePlugin { captchaSitekey: this.config.captchaSitekey, logoURL: this.config.logoURL, faucetAddress: this._state.publicKey - ? getLisk32AddressFromPublicKey(this._state.publicKey) + ? cryptography.address.getLisk32AddressFromPublicKey(this._state.publicKey) : undefined, }; res.json(config); diff --git a/framework-plugins/lisk-framework-faucet-plugin/src/ui/app.tsx b/framework-plugins/lisk-framework-faucet-plugin/src/ui/app.tsx index 60c6590945f..dad55a5a951 100644 --- a/framework-plugins/lisk-framework-faucet-plugin/src/ui/app.tsx +++ b/framework-plugins/lisk-framework-faucet-plugin/src/ui/app.tsx @@ -7,11 +7,9 @@ import logo from './logo.svg'; import illustration from './illustration.svg'; import styles from './app.module.scss'; -const { validateLisk32Address, getAddressFromLisk32Address } = cryptography; - const validateAddress = (address: string, prefix: string): boolean => { try { - return validateLisk32Address(address, prefix); + return cryptography.address.validateLisk32Address(address, prefix); } catch (error) { return false; } @@ -138,7 +136,9 @@ export const App: React.FC = () => { try { const client = await apiClient.createWSClient(config.applicationUrl); await client.invoke('faucet:fundTokens', { - address: getAddressFromLisk32Address(input, config.tokenPrefix).toString('hex'), + address: cryptography.address + .getAddressFromLisk32Address(input, config.tokenPrefix) + .toString('hex'), token, }); updateErrorMsg(''); diff --git a/framework-plugins/lisk-framework-forger-plugin/src/forger_plugin.ts b/framework-plugins/lisk-framework-forger-plugin/src/forger_plugin.ts index c4e5f14e38b..d6814ed1a67 100644 --- a/framework-plugins/lisk-framework-forger-plugin/src/forger_plugin.ts +++ b/framework-plugins/lisk-framework-forger-plugin/src/forger_plugin.ts @@ -33,16 +33,16 @@ import { Forger, TransactionFees, Voters } from './types'; import { Endpoint } from './endpoint'; const { Block } = chain; -const { intToBuffer } = cryptography; +const { utils: cryptoUtils } = cryptography; type BlockHeaderJSON = chain.BlockHeaderJSON; type BlockJSON = chain.BlockJSON; type TransactionJSON = chain.TransactionJSON; const BLOCKS_BATCH_TO_SYNC = 1000; const MODULE_ID_DPOS = 5; -const MODULE_ID_DPOS_BUFFER = intToBuffer(MODULE_ID_DPOS, 4); +const MODULE_ID_DPOS_BUFFER = cryptoUtils.intToBuffer(MODULE_ID_DPOS, 4); const COMMAND_ID_VOTE = 1; -const COMMAND_ID_VOTE_BUFFER = intToBuffer(COMMAND_ID_VOTE, 4); +const COMMAND_ID_VOTE_BUFFER = cryptoUtils.intToBuffer(COMMAND_ID_VOTE, 4); interface Data { readonly blockHeader: BlockHeaderJSON; @@ -322,7 +322,7 @@ export class ForgerPlugin extends BasePlugin { acc[curr.delegateAddress].amount += BigInt(curr.amount); } else { acc[curr.delegateAddress] = { - address: cryptography.getAddressFromPublicKey( + address: cryptography.address.getAddressFromPublicKey( Buffer.from(trx.senderPublicKey, 'hex'), ), amount: BigInt(curr.amount), diff --git a/framework-plugins/lisk-framework-forger-plugin/test/utils/accounts.ts b/framework-plugins/lisk-framework-forger-plugin/test/utils/accounts.ts index 17b69c8c2a2..0962c208a7f 100644 --- a/framework-plugins/lisk-framework-forger-plugin/test/utils/accounts.ts +++ b/framework-plugins/lisk-framework-forger-plugin/test/utils/accounts.ts @@ -15,10 +15,10 @@ import { cryptography } from 'lisk-sdk'; export const getRandomAccount = () => { - const { publicKey, privateKey } = cryptography.getKeys( - cryptography.getRandomBytes(20).toString('hex'), + const { publicKey, privateKey } = cryptography.utils.getKeys( + cryptography.utils.getRandomBytes(20).toString('hex'), ); - const address = cryptography.getAddressFromPublicKey(publicKey); + const address = cryptography.address.getAddressFromPublicKey(publicKey); return { address: address.toString('hex'), diff --git a/framework-plugins/lisk-framework-forger-plugin/test/utils/transactions.ts b/framework-plugins/lisk-framework-forger-plugin/test/utils/transactions.ts index adf202869e2..18500bd86d1 100644 --- a/framework-plugins/lisk-framework-forger-plugin/test/utils/transactions.ts +++ b/framework-plugins/lisk-framework-forger-plugin/test/utils/transactions.ts @@ -26,7 +26,7 @@ export const createTransferTransaction = ({ nonce: number; networkIdentifier: Buffer; }): Transaction => { - const { intToBuffer } = cryptography; + const { utils } = cryptography; const genesisAccount = testing.fixtures.defaultFaucetAccount; const encodedAsset = codec.encode(new TokenTransferAsset(BigInt(5000000)).schema, { recipientAddress: Buffer.from(recipientAddress, 'hex'), @@ -34,8 +34,8 @@ export const createTransferTransaction = ({ data: '', }); const tx = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt(nonce), senderPublicKey: genesisAccount.publicKey, fee: BigInt(transactions.convertLSKToBeddows(fee)), @@ -77,8 +77,8 @@ export const createVoteTransaction = ({ }); const tx = new Transaction({ - moduleID: intToBuffer(5, 4), - commandID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(5, 4), + commandID: utils.intToBuffer(1, 4), nonce: BigInt(nonce), senderPublicKey: genesisAccount.publicKey, fee: BigInt(transactions.convertLSKToBeddows(fee)), diff --git a/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts b/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts index 91bededa374..a564eca7a06 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts @@ -71,7 +71,7 @@ describe('_handlePostBlock', () => { maxHeightGenerated: 0, maxHeightPrevoted: 0, assetRoot: cryptography.hash(Buffer.alloc(0)), - validatorsHash: cryptography.getRandomBytes(32), + validatorsHash: cryptography.utils.getRandomBytes(32), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), diff --git a/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts b/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts index 25eaaf512af..627acb5eede 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts @@ -69,7 +69,7 @@ describe('_handleFork', () => { maxHeightGenerated: 0, maxHeightPrevoted: 0, assetRoot: cryptography.hash(Buffer.alloc(0)), - validatorsHash: cryptography.getRandomBytes(32), + validatorsHash: cryptography.utils.getRandomBytes(32), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/db.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/db.ts index 8b2c6ea32ac..11746618eab 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/db.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/db.ts @@ -18,7 +18,7 @@ import { ensureDir } from 'fs-extra'; import { cryptography, codec, chain, db as liskDB, BasePlugin } from 'lisk-sdk'; const { BlockHeader } = chain; -const { hash } = cryptography; +const { utils } = cryptography; export const blockHeadersSchema = { $id: '/lisk/reportMisbehavior/blockHeaders', @@ -77,7 +77,7 @@ export const saveBlockHeaders = async ( const dbKey = Buffer.concat([header.generatorAddress, Buffer.from(':', 'utf8'), heightBytes]); const { blockHeaders } = await getBlockHeaders(db, dbKey); - if (!blockHeaders.find(blockHeader => hash(blockHeader).equals(header.id))) { + if (!blockHeaders.find(blockHeader => utils.hash(blockHeader).equals(header.id))) { await db.set( dbKey, codec.encode(blockHeadersSchema, { diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/endpoint.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/endpoint.ts index cdfb0f577ec..87178933774 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/endpoint.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/endpoint.ts @@ -21,11 +21,7 @@ import { actionParamsSchema } from './schemas'; import { ReportMisbehaviorPluginConfig, State } from './types'; const { validator, LiskValidationError } = liskValidator; -const { - parseEncryptedPassphrase, - decryptPassphraseWithPassword, - getAddressAndPublicKeyFromPassphrase, -} = cryptography; +const { encrypt, address } = cryptography; export class Endpoint extends BasePluginEndpoint { private _state!: State; @@ -47,14 +43,16 @@ export class Endpoint extends BasePluginEndpoint { const { enable, password } = context.params; try { - const parsedEncryptedPassphrase = parseEncryptedPassphrase(this._config.encryptedPassphrase); + const parsedEncryptedPassphrase = encrypt.parseEncryptedPassphrase( + this._config.encryptedPassphrase, + ); - const passphrase = await decryptPassphraseWithPassword( + const passphrase = await encrypt.decryptPassphraseWithPassword( parsedEncryptedPassphrase as any, password as string, ); - const { publicKey } = getAddressAndPublicKeyFromPassphrase(passphrase); + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(passphrase); this._state.publicKey = enable ? publicKey : undefined; this._state.passphrase = enable ? passphrase : undefined; diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/report_misbehavior_plugin.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/report_misbehavior_plugin.ts index 0e5d067d631..395e39fa227 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/src/report_misbehavior_plugin.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/src/report_misbehavior_plugin.ts @@ -30,7 +30,7 @@ import { ReportMisbehaviorPluginConfig, State } from './types'; import { configSchema } from './schemas'; import { Endpoint } from './endpoint'; -const { getAddressAndPublicKeyFromPassphrase, getAddressFromPassphrase, signData } = cryptography; +const { address, ed } = cryptography; const { BlockHeader, Transaction, TAG_TRANSACTION } = chain; export class ReportMisbehaviorPlugin extends BasePlugin { @@ -145,7 +145,7 @@ export class ReportMisbehaviorPlugin extends BasePlugin('auth_getAuthAccount', { - address: getAddressFromPassphrase(passphrase).toString('hex'), + address: address.getAddressFromPassphrase(passphrase).toString('hex'), }); const pomTransactionParams = { @@ -164,14 +164,14 @@ export class ReportMisbehaviorPlugin extends BasePlugin { transaction: chain.transactionSchema, commands: [ { - moduleID: intToBuffer(5, 4), + moduleID: utils.intToBuffer(5, 4), moduleName: 'dpos', - commandID: intToBuffer(3, 4), + commandID: utils.intToBuffer(3, 4), commandName: 'reportDelegateMisbehavior', schema: { $id: '/lisk/dpos/pom', diff --git a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/send_pom_transaction.spec.ts b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/send_pom_transaction.spec.ts index fb9e800bb95..0d2e58aca48 100644 --- a/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/send_pom_transaction.spec.ts +++ b/framework-plugins/lisk-framework-report-misbehavior-plugin/test/unit/send_pom_transaction.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { GenesisConfig, testing, chain, ApplicationConfigForPlugin } from 'lisk-sdk'; import { when } from 'jest-when'; @@ -123,11 +123,11 @@ describe('Send PoM transaction', () => { }, metadata: [ { - id: intToBuffer(13, 4).toString('hex'), + id: utils.intToBuffer(13, 4).toString('hex'), name: 'dpos', commands: [ { - id: intToBuffer(3, 4).toString('hex'), + id: utils.intToBuffer(3, 4).toString('hex'), name: 'reportDelegateMisbehavior', params: { $id: '/lisk/dpos/pom', @@ -184,7 +184,7 @@ describe('Send PoM transaction', () => { }, metadata: [ { - id: intToBuffer(13, 4).toString('hex'), + id: utils.intToBuffer(13, 4).toString('hex'), name: 'dpos', commands: [], }, diff --git a/framework/src/abi_handler/abi_handler.ts b/framework/src/abi_handler/abi_handler.ts index 3af20727368..edb99c8b2e9 100644 --- a/framework/src/abi_handler/abi_handler.ts +++ b/framework/src/abi_handler/abi_handler.ts @@ -29,7 +29,7 @@ import { DEFAULT_MIN_ENTRANCE_FEE_PRIORITY, } from '@liskhq/lisk-transaction-pool'; import { codec } from '@liskhq/lisk-codec'; -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { SparseMerkleTree } from '@liskhq/lisk-tree'; import { ABI, @@ -237,7 +237,7 @@ export class ABIHandler implements ABI { )}`, ); } - const id = hash(codec.encode(blockHeaderSchema, req.header)); + const id = utils.hash(codec.encode(blockHeaderSchema, req.header)); this._executionContext = { id, header: new BlockHeader(req.header), diff --git a/framework/src/engine/bft/api.ts b/framework/src/engine/bft/api.ts index 11f6f507ee1..56ac4774483 100644 --- a/framework/src/engine/bft/api.ts +++ b/framework/src/engine/bft/api.ts @@ -13,7 +13,7 @@ */ import { BlockHeader, StateStore } from '@liskhq/lisk-chain'; -import { BIG_ENDIAN, hash, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { BaseAPI } from '../../modules/base_api'; import { @@ -80,7 +80,7 @@ export class BFTAPI extends BaseAPI { public async existBFTParameters(stateStore: StateStore, height: number): Promise { const paramsStore = stateStore.getStore(this.moduleID, STORE_PREFIX_BFT_PARAMETERS); - return paramsStore.has(intToBuffer(height, 4, BIG_ENDIAN)); + return paramsStore.has(utils.intToBuffer(height, 4)); } public async getBFTParameters(stateStore: StateStore, height: number): Promise { @@ -126,8 +126,8 @@ export class BFTAPI extends BaseAPI { public async getNextHeightBFTParameters(stateStore: StateStore, height: number): Promise { const paramsStore = stateStore.getStore(this.moduleID, STORE_PREFIX_BFT_PARAMETERS); - const start = intToBuffer(height + 1, 4, BIG_ENDIAN); - const end = intToBuffer(MAX_UINT32, 4, BIG_ENDIAN); + const start = utils.intToBuffer(height + 1, 4); + const end = utils.intToBuffer(MAX_UINT32, 4); const results = await paramsStore.iterate({ limit: 1, gte: start, @@ -212,7 +212,7 @@ export class BFTAPI extends BaseAPI { const paramsStore = stateStore.getStore(this.moduleID, STORE_PREFIX_BFT_PARAMETERS); - const nextHeightBytes = intToBuffer(nextHeight, 4, BIG_ENDIAN); + const nextHeightBytes = utils.intToBuffer(nextHeight, 4); await paramsStore.setWithSchema(nextHeightBytes, bftParams, bftParametersSchema); const nextActiveValidators: BFTVotesActiveValidatorsVoteInfo[] = []; @@ -252,7 +252,7 @@ export class BFTAPI extends BaseAPI { : bftVotes.maxHeightPrevoted + 1; const keysStore = stateStore.getStore(this.moduleID, STORE_PREFIX_GENERATOR_KEYS); - const nextHeightBytes = intToBuffer(nextHeight, 4, BIG_ENDIAN); + const nextHeightBytes = utils.intToBuffer(nextHeight, 4); await keysStore.setWithSchema(nextHeightBytes, { generators }, generatorKeysSchema); } @@ -271,6 +271,6 @@ export class BFTAPI extends BaseAPI { certificateThreshold, }; const encodedValidatorsHashInput = codec.encode(validatorsHashInputSchema, input); - return hash(encodedValidatorsHashInput); + return utils.hash(encodedValidatorsHashInput); } } diff --git a/framework/src/engine/bft/bft_params.ts b/framework/src/engine/bft/bft_params.ts index 5a842672f0c..84f9a650429 100644 --- a/framework/src/engine/bft/bft_params.ts +++ b/framework/src/engine/bft/bft_params.ts @@ -14,7 +14,7 @@ import { StateStore } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { BIG_ENDIAN, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { BFTParameterNotFoundError } from './errors'; import { BFTParameters, bftParametersSchema } from './schemas'; @@ -22,8 +22,8 @@ export const getBFTParameters = async ( paramsStore: StateStore, height: number, ): Promise => { - const start = intToBuffer(0, 4, BIG_ENDIAN); - const end = intToBuffer(height, 4, BIG_ENDIAN); + const start = utils.intToBuffer(0, 4); + const end = utils.intToBuffer(height, 4); const results = await paramsStore.iterate({ limit: 1, gte: start, @@ -41,8 +41,8 @@ export const deleteBFTParameters = async ( paramsStore: StateStore, height: number, ): Promise => { - const start = intToBuffer(0, 4, BIG_ENDIAN); - const end = intToBuffer(height, 4, BIG_ENDIAN); + const start = utils.intToBuffer(0, 4); + const end = utils.intToBuffer(height, 4); const results = await paramsStore.iterate({ gte: start, lte: end, @@ -66,8 +66,8 @@ export class BFTParametersCache { } public async cache(from: number, to: number): Promise { - const start = intToBuffer(from, 4, BIG_ENDIAN); - const end = intToBuffer(to, 4, BIG_ENDIAN); + const start = utils.intToBuffer(from, 4); + const end = utils.intToBuffer(to, 4); const results = await this._paramsStore.iterateWithSchema( { gte: start, @@ -79,7 +79,7 @@ export class BFTParametersCache { if (from > 0) { const nextLowest = await getBFTParameters(this._paramsStore, from); results.push({ - key: intToBuffer(from, 4, BIG_ENDIAN), + key: utils.intToBuffer(from, 4), value: nextLowest, }); } diff --git a/framework/src/engine/bft/constants.ts b/framework/src/engine/bft/constants.ts index b78494af1b7..ad0ba0683d0 100644 --- a/framework/src/engine/bft/constants.ts +++ b/framework/src/engine/bft/constants.ts @@ -12,10 +12,10 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const MODULE_ID_BFT = 9; -export const MODULE_ID_BFT_BUFFER = intToBuffer(MODULE_ID_BFT, 4); +export const MODULE_ID_BFT_BUFFER = utils.intToBuffer(MODULE_ID_BFT, 4); export const STORE_PREFIX_BFT_PARAMETERS = 0x0000; export const STORE_PREFIX_GENERATOR_KEYS = 0x4000; diff --git a/framework/src/engine/bft/utils.ts b/framework/src/engine/bft/utils.ts index 40807fb5c72..586c386d96d 100644 --- a/framework/src/engine/bft/utils.ts +++ b/framework/src/engine/bft/utils.ts @@ -14,7 +14,7 @@ import { StateStore, BlockHeader } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { hash, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { GeneratorKeysNotFoundError } from './errors'; import { BFTVotesBlockInfo, @@ -102,8 +102,8 @@ export const getGeneratorKeys = async ( keysStore: StateStore, height: number, ): Promise => { - const start = intToBuffer(0, 4); - const end = intToBuffer(height, 4); + const start = utils.intToBuffer(0, 4); + const end = utils.intToBuffer(height, 4); const results = await keysStore.iterate({ limit: 1, gte: start, @@ -119,8 +119,8 @@ export const getGeneratorKeys = async ( }; export const deleteGeneratorKeys = async (keysStore: StateStore, height: number): Promise => { - const start = intToBuffer(0, 4); - const end = intToBuffer(height, 4); + const start = utils.intToBuffer(0, 4); + const end = utils.intToBuffer(height, 4); const results = await keysStore.iterate({ gte: start, lte: end, @@ -148,5 +148,5 @@ export const computeValidatorsHash = (validators: BFTValidator[], certificateThr certificateThreshold, }; const encodedValidatorsHashInput = codec.encode(validatorsHashInputSchema, input); - return hash(encodedValidatorsHashInput); + return utils.hash(encodedValidatorsHashInput); }; diff --git a/framework/src/engine/consensus/certificate_generation/commit_pool.ts b/framework/src/engine/consensus/certificate_generation/commit_pool.ts index 736c35475bc..d2bd7af41cc 100644 --- a/framework/src/engine/consensus/certificate_generation/commit_pool.ts +++ b/framework/src/engine/consensus/certificate_generation/commit_pool.ts @@ -14,7 +14,7 @@ import { BlockHeader, Chain, StateStore } from '@liskhq/lisk-chain'; import { dataStructures } from '@liskhq/lisk-utils'; -import { createAggSig } from '@liskhq/lisk-cryptography'; +import { bls } from '@liskhq/lisk-cryptography'; import { Database } from '@liskhq/lisk-db'; import { codec } from '@liskhq/lisk-codec'; import { EMPTY_BUFFER, NETWORK_EVENT_COMMIT_MESSAGES, COMMIT_RANGE_STORED } from './constants'; @@ -284,7 +284,7 @@ export class CommitPool { validatorKeys.sort((blsKeyA, blsKeyB) => blsKeyA.compare(blsKeyB)); - const { aggregationBits, signature: aggregateSignature } = createAggSig( + const { aggregationBits, signature: aggregateSignature } = bls.createAggSig( validatorKeys, pubKeySignaturePairs, ); diff --git a/framework/src/engine/consensus/certificate_generation/utils.ts b/framework/src/engine/consensus/certificate_generation/utils.ts index 1255d80a786..e17acc17096 100644 --- a/framework/src/engine/consensus/certificate_generation/utils.ts +++ b/framework/src/engine/consensus/certificate_generation/utils.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { signBLS, verifyBLS, verifyWeightedAggSig } from '@liskhq/lisk-cryptography'; +import { bls } from '@liskhq/lisk-cryptography'; import { BlockHeader } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; import { Certificate } from './types'; @@ -44,7 +44,7 @@ export const signCertificate = ( ): Buffer => { const { aggregationBits, signature, ...rawCertificate } = certificate; - return signBLS( + return bls.signBLS( MESSAGE_TAG_CERTIFICATE, networkIdentifier, codec.encode(certificateSchema, rawCertificate), @@ -66,7 +66,7 @@ export const verifySingleCertificateSignature = ( validatorsHash: certificate.validatorsHash, }); - return verifyBLS(MESSAGE_TAG_CERTIFICATE, networkIdentifier, message, signature, pk); + return bls.verifyBLS(MESSAGE_TAG_CERTIFICATE, networkIdentifier, message, signature, pk); }; export const verifyAggregateCertificateSignature = ( @@ -89,7 +89,7 @@ export const verifyAggregateCertificateSignature = ( validatorsHash: certificate.validatorsHash, }); - return verifyWeightedAggSig( + return bls.verifyWeightedAggSig( keysList, aggregationBits, signature, diff --git a/framework/src/engine/consensus/consensus.ts b/framework/src/engine/consensus/consensus.ts index 7427245c8be..a56aa77b20e 100644 --- a/framework/src/engine/consensus/consensus.ts +++ b/framework/src/engine/consensus/consensus.ts @@ -25,7 +25,7 @@ import { import { jobHandlers, objects } from '@liskhq/lisk-utils'; import { Database, Batch, SparseMerkleTree } from '@liskhq/lisk-db'; import { codec } from '@liskhq/lisk-codec'; -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Logger } from '../../logger'; import { BlockSynchronizationMechanism, @@ -1014,7 +1014,7 @@ export class Consensus { await this._abi.commit({ contextID, dryRun: false, - stateRoot: hash(Buffer.alloc(0)), + stateRoot: utils.hash(Buffer.alloc(0)), expectedStateRoot: genesisBlock.header.stateRoot, }); return result.events.map(e => new Event(e)); diff --git a/framework/src/engine/consensus/constants.ts b/framework/src/engine/consensus/constants.ts index 53e21037224..dedd413c713 100644 --- a/framework/src/engine/consensus/constants.ts +++ b/framework/src/engine/consensus/constants.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const CONSENSUS_EVENT_FORK_DETECTED = 'CONSENSUS_EVENT_FORK_DETECTED'; export const CONSENSUS_EVENT_BLOCK_BROADCAST = 'CONSENSUS_EVENT_BLOCK_BROADCAST'; @@ -29,4 +29,4 @@ export const NETWORK_RPC_GET_BLOCKS_FROM_ID = 'getBlocksFromId'; export const NETWORK_RPC_GET_HIGHEST_COMMON_BLOCK = 'getHighestCommonBlock'; export const NETWORK_RPC_GET_SINGLE_COMMIT_FROM_ID = 'getSingleCommit'; -export const EMPTY_HASH = hash(Buffer.alloc(0)); +export const EMPTY_HASH = utils.hash(Buffer.alloc(0)); diff --git a/framework/src/engine/engine.ts b/framework/src/engine/engine.ts index 48046b54072..752275e8663 100644 --- a/framework/src/engine/engine.ts +++ b/framework/src/engine/engine.ts @@ -13,7 +13,7 @@ */ import * as path from 'path'; import { Chain, Block, BlockHeader, BlockAssets, TransactionJSON } from '@liskhq/lisk-chain'; -import { getNetworkIdentifier } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Database } from '@liskhq/lisk-db'; import { createLogger, Logger } from '../logger'; import { Network } from './network'; @@ -182,7 +182,7 @@ export class Engine { ); this._nodeDB = new Database(path.join(this._config.system.dataPath, 'data', 'node.db')); - this._networkIdentifier = getNetworkIdentifier( + this._networkIdentifier = utils.getNetworkIdentifier( genesis.header.id, this._config.genesis.communityIdentifier, ); diff --git a/framework/src/engine/generator/constants.ts b/framework/src/engine/generator/constants.ts index 5ab5dda6d90..d843fe54bdb 100644 --- a/framework/src/engine/generator/constants.ts +++ b/framework/src/engine/generator/constants.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const DEFAULT_RELEASE_LIMIT = 100; export const DEFAULT_RELEASE_INTERVAL = 5000; @@ -24,13 +24,13 @@ export const NETWORK_RPC_GET_TRANSACTIONS = 'getTransactions'; export const NETWORK_EVENT_POST_TRANSACTIONS_ANNOUNCEMENT = 'postTransactionsAnnouncement'; export const GENERATOR_STORE_RESERVED_PREFIX = 0; -export const GENERATOR_STORE_RESERVED_PREFIX_BUFFER = intToBuffer( +export const GENERATOR_STORE_RESERVED_PREFIX_BUFFER = utils.intToBuffer( GENERATOR_STORE_RESERVED_PREFIX, 4, ); export const EMPTY_BUFFER = Buffer.alloc(0); -export const EMPTY_HASH = hash(Buffer.alloc(0)); +export const EMPTY_HASH = utils.hash(Buffer.alloc(0)); export const GENESIS_BLOCK_VERSION = 0; export const GENERATOR_EVENT_NEW_TRANSACTION = 'GENERATOR_EVENT_NEW_TRANSACTION'; diff --git a/framework/src/engine/generator/endpoint.ts b/framework/src/engine/generator/endpoint.ts index 6f377f22387..40e4937a3dc 100644 --- a/framework/src/engine/generator/endpoint.ts +++ b/framework/src/engine/generator/endpoint.ts @@ -12,14 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - decryptPassphraseWithPassword, - EncryptedPassphraseObject, - generatePrivateKey, - getAddressFromPublicKey, - getPrivateAndPublicKeyFromPassphrase, - parseEncryptedPassphrase, -} from '@liskhq/lisk-cryptography'; +import { encrypt, ed, bls, address as cryptoAddress } from '@liskhq/lisk-cryptography'; import { Batch, Database } from '@liskhq/lisk-db'; import { dataStructures } from '@liskhq/lisk-utils'; import { LiskValidationError, validator } from '@liskhq/lisk-validator'; @@ -100,27 +93,31 @@ export class Endpoint { } try { - passphrase = await decryptPassphraseWithPassword( - parseEncryptedPassphrase( + passphrase = await encrypt.decryptPassphraseWithPassword( + encrypt.parseEncryptedPassphrase( encryptedGenerator.encryptedPassphrase, - ) as EncryptedPassphraseObject, + ) as encrypt.EncryptedPassphraseObject, req.password, ); } catch (e) { throw new Error('Invalid password and public key combination.'); } - const blsSK = generatePrivateKey(Buffer.from(passphrase, 'utf-8')); + const blsSK = bls.generatePrivateKey(Buffer.from(passphrase, 'utf-8')); const keypair = { - ...getPrivateAndPublicKeyFromPassphrase(passphrase), + ...ed.getPrivateAndPublicKeyFromPassphrase(passphrase), blsSecretKey: blsSK, }; - if (!getAddressFromPublicKey(keypair.publicKey).equals(Buffer.from(req.address, 'hex'))) { + if ( + !cryptoAddress + .getAddressFromPublicKey(keypair.publicKey) + .equals(Buffer.from(req.address, 'hex')) + ) { throw new Error( - `Invalid keypair: ${getAddressFromPublicKey(keypair.publicKey).toString( - 'hex', - )} and address: ${req.address} combination`, + `Invalid keypair: ${cryptoAddress + .getAddressFromPublicKey(keypair.publicKey) + .toString('hex')} and address: ${req.address} combination`, ); } diff --git a/framework/src/engine/generator/generator.ts b/framework/src/engine/generator/generator.ts index c2588dd69f5..f2c955093d6 100644 --- a/framework/src/engine/generator/generator.ts +++ b/framework/src/engine/generator/generator.ts @@ -23,15 +23,7 @@ import { EVENT_KEY_LENGTH, } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { - decryptPassphraseWithPassword, - EncryptedPassphraseObject, - generatePrivateKey, - getAddressFromPublicKey, - getPrivateAndPublicKeyFromPassphrase, - getPublicKeyFromPrivateKey, - parseEncryptedPassphrase, -} from '@liskhq/lisk-cryptography'; +import { encrypt, bls, ed, address as cryptoAddress } from '@liskhq/lisk-cryptography'; import { Database, Batch, SparseMerkleTree } from '@liskhq/lisk-db'; import { TransactionPool, events } from '@liskhq/lisk-transaction-pool'; import { MerkleTree } from '@liskhq/lisk-tree'; @@ -336,8 +328,10 @@ export class Generator { for (const encryptedItem of encryptedList) { let passphrase; try { - passphrase = await decryptPassphraseWithPassword( - parseEncryptedPassphrase(encryptedItem.encryptedPassphrase) as EncryptedPassphraseObject, + passphrase = await encrypt.decryptPassphraseWithPassword( + encrypt.parseEncryptedPassphrase( + encryptedItem.encryptedPassphrase, + ) as encrypt.EncryptedPassphraseObject, this._config.password, ); } catch (error) { @@ -348,9 +342,9 @@ export class Generator { throw new Error(decryptionError); } - const keypair = getPrivateAndPublicKeyFromPassphrase(passphrase); - const delegateAddress = getAddressFromPublicKey(keypair.publicKey); - const blsSK = generatePrivateKey(Buffer.from(passphrase, 'utf-8')); + const keypair = ed.getPrivateAndPublicKeyFromPassphrase(passphrase); + const delegateAddress = cryptoAddress.getAddressFromPublicKey(keypair.publicKey); + const blsSK = bls.generatePrivateKey(Buffer.from(passphrase, 'utf-8')); if (!delegateAddress.equals(encryptedItem.address)) { throw new Error( @@ -360,7 +354,7 @@ export class Generator { ); } - const validatorAddress = getAddressFromPublicKey(keypair.publicKey); + const validatorAddress = cryptoAddress.getAddressFromPublicKey(keypair.publicKey); this._keypairs.set(validatorAddress, { ...keypair, @@ -671,7 +665,7 @@ export class Generator { const blockHeader = await this._chain.dataAccess.getBlockHeaderByHeight(height); const validatorInfo = { address: generatorAddress, - blsPublicKey: getPublicKeyFromPrivateKey(blsSK), + blsPublicKey: bls.getPublicKeyFromPrivateKey(blsSK), blsSecretKey: blsSK, }; this._consensus.certifySingleCommit(blockHeader, validatorInfo); diff --git a/framework/src/engine/generator/strategies.ts b/framework/src/engine/generator/strategies.ts index 5077f89bf35..ae918c3d5da 100644 --- a/framework/src/engine/generator/strategies.ts +++ b/framework/src/engine/generator/strategies.ts @@ -14,7 +14,7 @@ import { TransactionPool, PooledTransaction } from '@liskhq/lisk-transaction-pool'; import { dataStructures } from '@liskhq/lisk-utils'; import { Transaction, BlockHeader, BlockAssets, Event } from '@liskhq/lisk-chain'; -import { getAddressFromPublicKey } from '@liskhq/lisk-cryptography'; +import { address } from '@liskhq/lisk-cryptography'; import { ABI, Consensus, TransactionExecutionResult, TransactionVerifyResult } from '../../abi'; export class HighFeeGenerationStrategy { @@ -70,7 +70,7 @@ export class HighFeeGenerationStrategy { if (!lowestNonceHighestFeeTrx) { throw new Error('lowest nonce tx must exist'); } - const senderId = getAddressFromPublicKey(lowestNonceHighestFeeTrx.senderPublicKey); + const senderId = address.getAddressFromPublicKey(lowestNonceHighestFeeTrx.senderPublicKey); // Try to process transaction try { const { result: verifyResult } = await this._abi.verifyTransaction({ diff --git a/framework/src/engine/network/network.ts b/framework/src/engine/network/network.ts index e3875da3682..fe28e474535 100644 --- a/framework/src/engine/network/network.ts +++ b/framework/src/engine/network/network.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Database, NotFoundError } from '@liskhq/lisk-db'; import { EventEmitter } from 'events'; import * as liskP2P from '@liskhq/lisk-p2p'; @@ -150,7 +150,7 @@ export class Network { } if (!secret) { - secret = getRandomBytes(4); + secret = utils.getRandomBytes(4); await this._nodeDB.set(DB_KEY_NETWORK_NODE_SECRET, secret); } diff --git a/framework/src/genesis_block.ts b/framework/src/genesis_block.ts index ec6a29c94dc..fc36c130860 100644 --- a/framework/src/genesis_block.ts +++ b/framework/src/genesis_block.ts @@ -15,7 +15,7 @@ import * as os from 'os'; import * as path from 'path'; import { Block, BlockAssets, BlockHeader, EVENT_KEY_LENGTH, SMTStore } from '@liskhq/lisk-chain'; import { codec, Schema } from '@liskhq/lisk-codec'; -import { getRandomBytes, hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase, StateDB } from '@liskhq/lisk-db'; import { SparseMerkleTree } from '@liskhq/lisk-tree'; import { Logger } from './logger'; @@ -36,7 +36,7 @@ export interface GenesisBlockGenerateInput { const GENESIS_BLOCK_VERSION = 0; const EMPTY_BUFFER = Buffer.alloc(0); -const EMPTY_HASH = hash(EMPTY_BUFFER); +const EMPTY_HASH = utils.hash(EMPTY_BUFFER); export const generateGenesisBlock = async ( stateMachine: StateMachine, @@ -72,7 +72,11 @@ export const generateGenesisBlock = async ( }, }); - const tempPath = path.join(os.tmpdir(), getRandomBytes(3).toString('hex'), Date.now().toString()); + const tempPath = path.join( + os.tmpdir(), + utils.getRandomBytes(3).toString('hex'), + Date.now().toString(), + ); const stateDB = new StateDB(tempPath); const stateStore = new PrefixedStateReadWriter(stateDB.newReadWriter()); diff --git a/framework/src/modules/auth/constants.ts b/framework/src/modules/auth/constants.ts index 2e635ca0c86..026e42c197b 100644 --- a/framework/src/modules/auth/constants.ts +++ b/framework/src/modules/auth/constants.ts @@ -12,10 +12,10 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const MODULE_ID_AUTH = 12; // TBD -export const MODULE_ID_AUTH_BUFFER = intToBuffer(MODULE_ID_AUTH, 4); +export const MODULE_ID_AUTH_BUFFER = utils.intToBuffer(MODULE_ID_AUTH, 4); export const STORE_PREFIX_AUTH = 0x0000; export const MAX_KEYS_COUNT = 64; diff --git a/framework/src/modules/auth/endpoint.ts b/framework/src/modules/auth/endpoint.ts index 102bd94f360..cc0c79a6314 100644 --- a/framework/src/modules/auth/endpoint.ts +++ b/framework/src/modules/auth/endpoint.ts @@ -13,7 +13,7 @@ */ import { TAG_TRANSACTION, NotFoundError } from '@liskhq/lisk-chain'; -import { getAddressFromPublicKey } from '@liskhq/lisk-cryptography'; +import { address as cryptoAddress } from '@liskhq/lisk-cryptography'; import { isHexString } from '@liskhq/lisk-validator'; import { ModuleEndpointContext } from '../../types'; import { VerifyStatus } from '../../state_machine'; @@ -73,7 +73,7 @@ export class AuthEndpoint extends BaseEndpoint { const { senderPublicKey, signatures } = transaction; - const accountAddress = getAddressFromPublicKey(senderPublicKey); + const accountAddress = cryptoAddress.getAddressFromPublicKey(senderPublicKey); const store = getStore(MODULE_ID_AUTH_BUFFER, STORE_PREFIX_AUTH); const account = await store.getWithSchema(accountAddress, authAccountSchema); @@ -127,7 +127,7 @@ export class AuthEndpoint extends BaseEndpoint { const { senderPublicKey } = transaction; - const accountAddress = getAddressFromPublicKey(senderPublicKey); + const accountAddress = cryptoAddress.getAddressFromPublicKey(senderPublicKey); const store = getStore(MODULE_ID_AUTH_BUFFER, STORE_PREFIX_AUTH); const account = await store.getWithSchema(accountAddress, authAccountSchema); diff --git a/framework/src/modules/auth/utils.ts b/framework/src/modules/auth/utils.ts index 46ba208af22..29bd3e15429 100644 --- a/framework/src/modules/auth/utils.ts +++ b/framework/src/modules/auth/utils.ts @@ -14,7 +14,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec, Schema } from '@liskhq/lisk-codec'; -import { intToBuffer, verifyData } from '@liskhq/lisk-cryptography'; +import { utils, ed } from '@liskhq/lisk-cryptography'; import { isHexString } from '@liskhq/lisk-validator'; import { VerificationResult, VerifyStatus } from '../../state_machine'; import { InvalidNonceError } from './errors'; @@ -31,7 +31,7 @@ export const validateSignature = ( transactionBytes: Buffer, id: Buffer, ): void => { - const valid = verifyData(tag, networkIdentifier, transactionBytes, signature, publicKey); + const valid = ed.verifyData(tag, networkIdentifier, transactionBytes, signature, publicKey); if (!valid) { throw new Error( @@ -205,4 +205,4 @@ export const getTransactionFromParameter = (transactionParameter: unknown) => { return transaction; }; -export const getIDAsKeyForStore = (id: number) => intToBuffer(id, 4); +export const getIDAsKeyForStore = (id: number) => utils.intToBuffer(id, 4); diff --git a/framework/src/modules/dpos_v2/constants.ts b/framework/src/modules/dpos_v2/constants.ts index e420b781742..de3d08a78e4 100644 --- a/framework/src/modules/dpos_v2/constants.ts +++ b/framework/src/modules/dpos_v2/constants.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const MODULE_ID_DPOS = 13; // TBD @@ -46,7 +46,7 @@ export const REPORTING_PUNISHMENT_REWARD = BigInt(100000000); export const DELEGATE_LIST_ROUND_OFFSET = 2; export const EMPTY_KEY = Buffer.alloc(0); export const MAX_SNAPSHOT = 3; -export const MODULE_ID_DPOS_BUFFER = intToBuffer(MODULE_ID_DPOS, 4); +export const MODULE_ID_DPOS_BUFFER = utils.intToBuffer(MODULE_ID_DPOS, 4); export const defaultConfig = { factorSelfVotes: 10, diff --git a/framework/src/modules/dpos_v2/module.ts b/framework/src/modules/dpos_v2/module.ts index 30aff7779af..44b436f3524 100644 --- a/framework/src/modules/dpos_v2/module.ts +++ b/framework/src/modules/dpos_v2/module.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { objects as objectUtils, dataStructures, objects } from '@liskhq/lisk-utils'; import { isUInt64, LiskValidationError, validator } from '@liskhq/lisk-validator'; import { codec } from '@liskhq/lisk-codec'; @@ -349,7 +349,7 @@ export class DPoSModule extends BaseModule { const snapshotStore = context.getStore(this.id, STORE_PREFIX_SNAPSHOT); for (const snapshot of genesisStore.snapshots) { - const storeKey = intToBuffer(snapshot.roundNumber, 4); + const storeKey = utils.intToBuffer(snapshot.roundNumber, 4); await snapshotStore.setWithSchema( storeKey, { @@ -448,8 +448,8 @@ export class DPoSModule extends BaseModule { const MAX_UINT32 = 2 ** 32 - 1; const snapshotStore = context.getStore(this.id, STORE_PREFIX_SNAPSHOT); const allSnapshots = await snapshotStore.iterate({ - gte: intToBuffer(0, 4), - lte: intToBuffer(MAX_UINT32, 4), + gte: utils.intToBuffer(0, 4), + lte: utils.intToBuffer(MAX_UINT32, 4), }); if (context.header.height === 0 && allSnapshots.length > 0) { throw new Error('When genensis height is zero, there should not be a snapshot.'); @@ -578,14 +578,14 @@ export class DPoSModule extends BaseModule { } const snapshotStore = context.getStore(this.id, STORE_PREFIX_SNAPSHOT); - const storeKey = intToBuffer(snapshotRound, 4); + const storeKey = utils.intToBuffer(snapshotRound, 4); await snapshotStore.setWithSchema(storeKey, snapshotData, snapshotStoreSchema); // Remove outdated information const oldData = await snapshotStore.iterate({ - gte: intToBuffer(0, 4), - lte: intToBuffer(Math.max(0, snapshotRound - DELEGATE_LIST_ROUND_OFFSET - 1), 4), + gte: utils.intToBuffer(0, 4), + lte: utils.intToBuffer(Math.max(0, snapshotRound - DELEGATE_LIST_ROUND_OFFSET - 1), 4), }); for (const { key } of oldData) { await snapshotStore.del(key); @@ -600,7 +600,7 @@ export class DPoSModule extends BaseModule { const snapshotStore = context.getStore(this.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(nextRound, 4), + utils.intToBuffer(nextRound, 4), snapshotStoreSchema, ); diff --git a/framework/src/modules/dpos_v2/utils.ts b/framework/src/modules/dpos_v2/utils.ts index 4f8e4639250..a11f7462950 100644 --- a/framework/src/modules/dpos_v2/utils.ts +++ b/framework/src/modules/dpos_v2/utils.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash, intToBuffer, verifyData } from '@liskhq/lisk-cryptography'; +import { utils, ed } from '@liskhq/lisk-cryptography'; import { NotFoundError } from '@liskhq/lisk-chain'; import { ModuleConfig, ModuleConfigJSON, UnlockingObject, VoterData } from './types'; import { @@ -71,7 +71,7 @@ export const validateSignature = ( publicKey: Buffer, signature: Buffer, bytes: Buffer, -): boolean => verifyData(tag, networkIdentifier, bytes, signature, publicKey); +): boolean => ed.verifyData(tag, networkIdentifier, bytes, signature, publicKey); export const getVoterOrDefault = async (voterStore: SubStore, address: Buffer) => { try { @@ -127,7 +127,7 @@ export const shuffleDelegateList = ( for (const delegate of delegateList) { const seedSource = Buffer.concat([previousRoundSeed1, delegate.address]); - delegate.roundHash = hash(seedSource); + delegate.roundHash = utils.hash(seedSource); } delegateList.sort((delegate1, delegate2) => { @@ -264,7 +264,7 @@ export const getPunishmentPeriod = ( return remainingBlocks < 0 ? 0 : remainingBlocks; }; -export const getIDAsKeyForStore = (id: number) => intToBuffer(id, 4); +export const getIDAsKeyForStore = (id: number) => utils.intToBuffer(id, 4); export function getModuleConfig(config: ModuleConfigJSON): ModuleConfig { return { diff --git a/framework/src/modules/fee/module.ts b/framework/src/modules/fee/module.ts index 40cd80191e5..ba93299db39 100644 --- a/framework/src/modules/fee/module.ts +++ b/framework/src/modules/fee/module.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getAddressFromPublicKey, intToBuffer } from '@liskhq/lisk-cryptography'; +import { address, utils } from '@liskhq/lisk-cryptography'; import { objects } from '@liskhq/lisk-utils'; import { LiskValidationError, validator } from '@liskhq/lisk-validator'; import { BaseModule, ModuleInitArgs, ModuleMetadata } from '../base_module'; @@ -29,7 +29,7 @@ import { FeeEndpoint } from './endpoint'; import { configSchema } from './schemas'; export class FeeModule extends BaseModule { - public id = intToBuffer(MODULE_ID_FEE, 4); + public id = utils.intToBuffer(MODULE_ID_FEE, 4); public name = 'fee'; public api = new FeeAPI(this.id); public configSchema = configSchema; @@ -86,7 +86,7 @@ export class FeeModule extends BaseModule { const minFee = BigInt(this._minFeePerByte * context.transaction.getBytes().length) + this._extraFee(context.transaction.moduleID, context.transaction.commandID); - const senderAddress = getAddressFromPublicKey(context.transaction.senderPublicKey); + const senderAddress = address.getAddressFromPublicKey(context.transaction.senderPublicKey); const apiContext = context.getAPIContext(); const isNative = await this._tokenAPI.isNative(apiContext, this._tokenID); diff --git a/framework/src/modules/interoperability/base_interoperability_store.ts b/framework/src/modules/interoperability/base_interoperability_store.ts index 28843d05364..de1f0aa4e82 100644 --- a/framework/src/modules/interoperability/base_interoperability_store.ts +++ b/framework/src/modules/interoperability/base_interoperability_store.ts @@ -14,7 +14,7 @@ import { codec } from '@liskhq/lisk-codec'; import { NotFoundError } from '@liskhq/lisk-chain'; -import { hash, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { regularMerkleTree } from '@liskhq/lisk-tree'; import { SubStore } from '../../state_machine/types'; import { @@ -118,7 +118,7 @@ export abstract class BaseInteroperabilityStore { ) as SubStore; const channel = await channelSubstore.getWithSchema(chainID, channelSchema); const updatedInbox = regularMerkleTree.calculateMerkleRoot({ - value: hash(appendData), + value: utils.hash(appendData), appendPath: channel.inbox.appendPath, size: channel.inbox.size, }); @@ -136,7 +136,7 @@ export abstract class BaseInteroperabilityStore { ) as SubStore; const channel = await channelSubstore.getWithSchema(chainID, channelSchema); const updatedOutbox = regularMerkleTree.calculateMerkleRoot({ - value: hash(appendData), + value: utils.hash(appendData), appendPath: channel.outbox.appendPath, size: channel.outbox.size, }); @@ -373,7 +373,7 @@ export abstract class BaseInteroperabilityStore { ): Promise { const messageSent = await this.sendInternal({ moduleID: getIDAsKeyForStore(MODULE_ID_INTEROPERABILITY), - crossChainCommandID: intToBuffer(CROSS_CHAIN_COMMAND_ID_CHANNEL_TERMINATED, 4), + crossChainCommandID: utils.intToBuffer(CROSS_CHAIN_COMMAND_ID_CHANNEL_TERMINATED, 4), receivingChainID: chainID, fee: BigInt(0), status: CCM_STATUS_OK, diff --git a/framework/src/modules/interoperability/constants.ts b/framework/src/modules/interoperability/constants.ts index ec4f5d6f4af..c5eb3a17d10 100644 --- a/framework/src/modules/interoperability/constants.ts +++ b/framework/src/modules/interoperability/constants.ts @@ -12,15 +12,15 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const MODULE_ID_INTEROPERABILITY = 64; -export const MODULE_ID_INTEROPERABILITY_BUFFER = intToBuffer(MODULE_ID_INTEROPERABILITY, 4); +export const MODULE_ID_INTEROPERABILITY_BUFFER = utils.intToBuffer(MODULE_ID_INTEROPERABILITY, 4); export const MODULE_NAME_INTEROPERABILITY = 'interoperability'; // General constants export const MAINCHAIN_ID = 1; -export const MAINCHAIN_ID_BUFFER = intToBuffer(MAINCHAIN_ID, 4); +export const MAINCHAIN_ID_BUFFER = utils.intToBuffer(MAINCHAIN_ID, 4); export const MAINCHAIN_NAME = 'lisk-mainchain'; export const MAINCHAIN_NETWORK_ID = Buffer.from( '03693f3126b9d0df3096c4ebd59e5c42af4a7f0e313cd7c96a07b6e9f8f54924', @@ -34,7 +34,7 @@ export const LIVENESS_LIMIT = 2592000; // 30*24*3600 export const MAX_CCM_SIZE = 10240; export const EMPTY_FEE_ADDRESS = Buffer.alloc(0); export const EMPTY_BYTES = Buffer.alloc(0); -export const EMPTY_HASH = hash(EMPTY_BYTES); +export const EMPTY_HASH = utils.hash(EMPTY_BYTES); export const REGISTRATION_FEE = BigInt(1000000000); export const MAX_NUM_VALIDATORS = 199; export const MAX_LENGTH_NAME = 40; @@ -61,17 +61,17 @@ export const CHAIN_TERMINATED = 2; // Cross chain commands export const CROSS_CHAIN_COMMAND_ID_REGISTRATION = 0; -export const CROSS_CHAIN_COMMAND_ID_REGISTRATION_BUFFER = intToBuffer( +export const CROSS_CHAIN_COMMAND_ID_REGISTRATION_BUFFER = utils.intToBuffer( CROSS_CHAIN_COMMAND_ID_REGISTRATION, 4, ); export const CROSS_CHAIN_COMMAND_ID_CHANNEL_TERMINATED = 1; -export const CROSS_CHAIN_COMMAND_ID_CHANNEL_TERMINATED_BUFFER = intToBuffer( +export const CROSS_CHAIN_COMMAND_ID_CHANNEL_TERMINATED_BUFFER = utils.intToBuffer( CROSS_CHAIN_COMMAND_ID_CHANNEL_TERMINATED, 4, ); export const CROSS_CHAIN_COMMAND_ID_SIDECHAIN_TERMINATED = 2; -export const CROSS_CHAIN_COMMAND_ID_SIDECHAIN_TERMINATED_BUFFER = intToBuffer( +export const CROSS_CHAIN_COMMAND_ID_SIDECHAIN_TERMINATED_BUFFER = utils.intToBuffer( CROSS_CHAIN_COMMAND_ID_SIDECHAIN_TERMINATED, 4, ); @@ -84,16 +84,19 @@ export const MIN_RETURN_FEE = BigInt(1000); // Commands export const COMMAND_ID_SIDECHAIN_REG = 0; -export const COMMAND_ID_SIDECHAIN_REG_BUFFER = intToBuffer(COMMAND_ID_SIDECHAIN_REG, 4); +export const COMMAND_ID_SIDECHAIN_REG_BUFFER = utils.intToBuffer(COMMAND_ID_SIDECHAIN_REG, 4); export const COMMAND_ID_MAINCHAIN_REG = 1; -export const COMMAND_ID_MAINCHAIN_REG_BUFFER = intToBuffer(COMMAND_ID_MAINCHAIN_REG, 4); +export const COMMAND_ID_MAINCHAIN_REG_BUFFER = utils.intToBuffer(COMMAND_ID_MAINCHAIN_REG, 4); export const COMMAND_ID_SIDECHAIN_CCU = 2; -export const COMMAND_ID_SIDECHAIN_CCU_BUFFER = intToBuffer(COMMAND_ID_SIDECHAIN_CCU, 4); +export const COMMAND_ID_SIDECHAIN_CCU_BUFFER = utils.intToBuffer(COMMAND_ID_SIDECHAIN_CCU, 4); export const COMMAND_ID_MAINCHAIN_CCU = 3; -export const COMMAND_ID_MAINCHAIN_CCU_BUFFER = intToBuffer(COMMAND_ID_MAINCHAIN_CCU, 4); +export const COMMAND_ID_MAINCHAIN_CCU_BUFFER = utils.intToBuffer(COMMAND_ID_MAINCHAIN_CCU, 4); export const COMMAND_ID_STATE_RECOVERY = 4; -export const COMMAND_ID_STATE_RECOVERY_BUFFER = intToBuffer(COMMAND_ID_STATE_RECOVERY, 4); +export const COMMAND_ID_STATE_RECOVERY_BUFFER = utils.intToBuffer(COMMAND_ID_STATE_RECOVERY, 4); export const COMMAND_ID_MESSAGE_RECOVERY = 5; -export const COMMAND_ID_MESSAGE_RECOVERY_BUFFER = intToBuffer(COMMAND_ID_MESSAGE_RECOVERY, 4); +export const COMMAND_ID_MESSAGE_RECOVERY_BUFFER = utils.intToBuffer(COMMAND_ID_MESSAGE_RECOVERY, 4); export const COMMAND_ID_STATE_RECOVERY_INIT = 6; -export const COMMAND_ID_STATE_RECOVERY_INIT_BUFFER = intToBuffer(COMMAND_ID_MESSAGE_RECOVERY, 4); +export const COMMAND_ID_STATE_RECOVERY_INIT_BUFFER = utils.intToBuffer( + COMMAND_ID_MESSAGE_RECOVERY, + 4, +); diff --git a/framework/src/modules/interoperability/mainchain/commands/message_recovery.ts b/framework/src/modules/interoperability/mainchain/commands/message_recovery.ts index b3cf91769fa..21c21d40a87 100644 --- a/framework/src/modules/interoperability/mainchain/commands/message_recovery.ts +++ b/framework/src/modules/interoperability/mainchain/commands/message_recovery.ts @@ -14,7 +14,7 @@ import { codec } from '@liskhq/lisk-codec'; import { regularMerkleTree } from '@liskhq/lisk-tree'; -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { NotFoundError } from '@liskhq/lisk-chain'; import { CommandExecuteContext, @@ -129,7 +129,7 @@ export class MainchainMessageRecoveryCommand extends BaseInteroperabilityCommand siblingHashes: params.siblingHashes, }; - const hashedUpdatedCCMs = updatedCCMs.map(ccm => hash(ccm)); + const hashedUpdatedCCMs = updatedCCMs.map(ccm => utils.hash(ccm)); const outboxRoot = regularMerkleTree.calculateRootFromUpdateData(hashedUpdatedCCMs, proof); diff --git a/framework/src/modules/interoperability/mainchain/commands/sidechain_registration.ts b/framework/src/modules/interoperability/mainchain/commands/sidechain_registration.ts index 52565414fb3..922bdb0ad96 100644 --- a/framework/src/modules/interoperability/mainchain/commands/sidechain_registration.ts +++ b/framework/src/modules/interoperability/mainchain/commands/sidechain_registration.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { hash, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { validator, LiskValidationError } from '@liskhq/lisk-validator'; import { MainchainInteroperabilityStore } from '../store'; import { BaseInteroperabilityCommand } from '../../base_interoperability_command'; @@ -96,7 +96,7 @@ export class SidechainRegistrationCommand extends BaseInteroperabilityCommand { }; } - const networkID = hash(Buffer.concat([genesisBlockID, transaction.senderAddress])); + const networkID = utils.hash(Buffer.concat([genesisBlockID, transaction.senderAddress])); // networkId has to be unique with respect to the set of already registered sidechain network IDs in the blockchain state. const networkIDSubstore = context.getStore( @@ -174,20 +174,20 @@ export class SidechainRegistrationCommand extends BaseInteroperabilityCommand { getStore, } = context; - const networkID = hash(Buffer.concat([genesisBlockID, transaction.senderAddress])); + const networkID = utils.hash(Buffer.concat([genesisBlockID, transaction.senderAddress])); // Add an entry in the chain substore const chainSubstore = getStore(MODULE_ID_INTEROPERABILITY_BUFFER, STORE_PREFIX_CHAIN_DATA); // Find the latest chainID from db - const gte = intToBuffer(0, 4); - const lte = intToBuffer(MAX_UINT32, 4); + const gte = utils.intToBuffer(0, 4); + const lte = utils.intToBuffer(MAX_UINT32, 4); const chainIDs = await chainSubstore.iterate({ gte, lte, limit: 1, reverse: true }); if (!chainIDs.length) { throw new Error('No existing entries found in chain store'); } const chainID = chainIDs[0].key.readUInt32BE(0) + 1; - const chainIDBuffer = intToBuffer(chainID, 4); + const chainIDBuffer = utils.intToBuffer(chainID, 4); await chainSubstore.setWithSchema( chainIDBuffer, @@ -213,7 +213,7 @@ export class SidechainRegistrationCommand extends BaseInteroperabilityCommand { inbox: { root: EMPTY_HASH, appendPath: [], size: 0 }, outbox: { root: EMPTY_HASH, appendPath: [], size: 0 }, partnerChainOutboxRoot: EMPTY_HASH, - messageFeeTokenID: { chainID: intToBuffer(1, 4), localID: intToBuffer(0, 4) }, + messageFeeTokenID: { chainID: utils.intToBuffer(1, 4), localID: utils.intToBuffer(0, 4) }, }, channelSchema, ); @@ -224,7 +224,7 @@ export class SidechainRegistrationCommand extends BaseInteroperabilityCommand { const encodedParams = codec.encode(registrationCCMParamsSchema, { networkID, name, - messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: intToBuffer(0, 4) }, + messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: utils.intToBuffer(0, 4) }, }); await interoperabilityStore.sendInternal({ diff --git a/framework/src/modules/interoperability/mainchain/commands/state_recovery.ts b/framework/src/modules/interoperability/mainchain/commands/state_recovery.ts index 24d40c1a3d0..5e2f0f3d203 100644 --- a/framework/src/modules/interoperability/mainchain/commands/state_recovery.ts +++ b/framework/src/modules/interoperability/mainchain/commands/state_recovery.ts @@ -13,7 +13,7 @@ */ import { sparseMerkleTree } from '@liskhq/lisk-tree'; -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { validator, LiskValidationError } from '@liskhq/lisk-validator'; import { MainchainInteroperabilityStore } from '../store'; import { BaseInteroperabilityCommand } from '../../base_interoperability_command'; @@ -86,7 +86,7 @@ export class StateRecoveryCommand extends BaseInteroperabilityCommand { queryKeys.push(entry.storeKey); storeQueries.push({ key: entry.storeKey, - value: hash(entry.storeValue), + value: utils.hash(entry.storeValue), bitmap: entry.bitmap, }); } diff --git a/framework/src/modules/interoperability/mainchain/commands/state_recovery_init.ts b/framework/src/modules/interoperability/mainchain/commands/state_recovery_init.ts index 6191e8c55e6..9ec50732897 100644 --- a/framework/src/modules/interoperability/mainchain/commands/state_recovery_init.ts +++ b/framework/src/modules/interoperability/mainchain/commands/state_recovery_init.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { intToBuffer, hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { sparseMerkleTree } from '@liskhq/lisk-tree'; import { CommandExecuteContext, @@ -108,12 +108,12 @@ export class StateRecoveryInitCommand extends BaseInteroperabilityCommand { } const interopAccKey = Buffer.concat([ - intToBuffer(MODULE_ID_INTEROPERABILITY, 4), - intToBuffer(STORE_PREFIX_CHAIN_DATA, 4), + utils.intToBuffer(MODULE_ID_INTEROPERABILITY, 4), + utils.intToBuffer(STORE_PREFIX_CHAIN_DATA, 4), chainID, ]); - const query = { key: interopAccKey, value: hash(sidechainChainAccount), bitmap }; + const query = { key: interopAccKey, value: utils.hash(sidechainChainAccount), bitmap }; const proofOfInclusion = { siblingHashes, queries: [query] }; diff --git a/framework/src/modules/interoperability/sidechain/commands/mainchain_registration.ts b/framework/src/modules/interoperability/sidechain/commands/mainchain_registration.ts index b4850431fb1..a3de4458955 100644 --- a/framework/src/modules/interoperability/sidechain/commands/mainchain_registration.ts +++ b/framework/src/modules/interoperability/sidechain/commands/mainchain_registration.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { intToBuffer, verifyWeightedAggSig } from '@liskhq/lisk-cryptography'; +import { utils, bls } from '@liskhq/lisk-cryptography'; import { validator, LiskValidationError } from '@liskhq/lisk-validator'; import { CCM_STATUS_OK, @@ -136,7 +136,7 @@ export class MainchainRegistrationCommand extends BaseInteroperabilityCommand { ownName, mainchainValidators, }); - verifyWeightedAggSig( + bls.verifyWeightedAggSig( keyList, aggregationBits, signature, @@ -171,7 +171,7 @@ export class MainchainRegistrationCommand extends BaseInteroperabilityCommand { inbox: { root: EMPTY_HASH, appendPath: [], size: 0 }, outbox: { root: EMPTY_HASH, appendPath: [], size: 0 }, partnerChainOutboxRoot: EMPTY_HASH, - messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: intToBuffer(0, 4) }, + messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: utils.intToBuffer(0, 4) }, }, channelSchema, ); @@ -181,7 +181,7 @@ export class MainchainRegistrationCommand extends BaseInteroperabilityCommand { const encodedParams = codec.encode(registrationCCMParamsSchema, { networkID: MAINCHAIN_NETWORK_ID, name: MAINCHAIN_NAME, - messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: intToBuffer(0, 4) }, + messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: utils.intToBuffer(0, 4) }, }); await interoperabilityStore.sendInternal({ @@ -229,7 +229,7 @@ export class MainchainRegistrationCommand extends BaseInteroperabilityCommand { STORE_PREFIX_OWN_CHAIN_DATA, ); await ownChainAccountSubstore.setWithSchema( - intToBuffer(0, 4), + utils.intToBuffer(0, 4), { name: ownName, id: ownChainID, nonce: BigInt(0) }, ownChainAccountSchema, ); diff --git a/framework/src/modules/interoperability/sidechain/commands/message_recovery.ts b/framework/src/modules/interoperability/sidechain/commands/message_recovery.ts index e39ad43cae7..58d3dc15509 100644 --- a/framework/src/modules/interoperability/sidechain/commands/message_recovery.ts +++ b/framework/src/modules/interoperability/sidechain/commands/message_recovery.ts @@ -14,7 +14,7 @@ import { codec } from '@liskhq/lisk-codec'; import { regularMerkleTree } from '@liskhq/lisk-tree'; -import { hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { NotFoundError } from '@liskhq/lisk-chain'; import { CommandExecuteContext, @@ -129,7 +129,7 @@ export class SidechainMessageRecoveryCommand extends BaseInteroperabilityCommand siblingHashes: params.siblingHashes, }; - const hashedUpdatedCCMs = updatedCCMs.map(ccm => hash(ccm)); + const hashedUpdatedCCMs = updatedCCMs.map(ccm => utils.hash(ccm)); const outboxRoot = regularMerkleTree.calculateRootFromUpdateData(hashedUpdatedCCMs, proof); diff --git a/framework/src/modules/interoperability/utils.ts b/framework/src/modules/interoperability/utils.ts index 2e135dce8fa..537d29b0388 100644 --- a/framework/src/modules/interoperability/utils.ts +++ b/framework/src/modules/interoperability/utils.ts @@ -14,7 +14,7 @@ import { regularMerkleTree, sparseMerkleTree } from '@liskhq/lisk-tree'; import { codec } from '@liskhq/lisk-codec'; -import { hash, intToBuffer, verifyWeightedAggSig } from '@liskhq/lisk-cryptography'; +import { utils, bls } from '@liskhq/lisk-cryptography'; import { LiskValidationError, validator } from '@liskhq/lisk-validator'; import { DB_KEY_STATE_STORE } from '@liskhq/lisk-chain'; import { @@ -64,7 +64,7 @@ interface CommonExecutionLogicArgs { chainIDBuffer: Buffer; } // Returns the big endian uint32 serialization of an integer x, with 0 <= x < 2^32 which is 4 bytes long. -export const getIDAsKeyForStore = (id: number) => intToBuffer(id, 4); +export const getIDAsKeyForStore = (id: number) => utils.intToBuffer(id, 4); export const validateFormat = (ccm: CCMsg) => { const errors = validator.validate(ccmSchema, ccm); @@ -145,7 +145,7 @@ export const computeValidatorsHash = ( }; const encodedValidatorsHashInput = codec.encode(validatorsHashInputSchema, input); - return hash(encodedValidatorsHashInput); + return utils.hash(encodedValidatorsHashInput); }; export const sortValidatorsByBLSKey = (validators: ActiveValidators[]) => @@ -189,7 +189,7 @@ export const verifyMessageRecovery = ( idxs, siblingHashes, }; - const hashedCCMs = crossChainMessages.map(ccm => hash(ccm)); + const hashedCCMs = crossChainMessages.map(ccm => utils.hash(ccm)); const isVerified = regularMerkleTree.verifyDataBlock( hashedCCMs, proof, @@ -335,7 +335,7 @@ export const checkInboxUpdateValidity = ( } const decodedCertificate = codec.decode(certificateSchema, txParams.certificate); const { crossChainMessages, messageWitness, outboxRootWitness } = txParams.inboxUpdate; - const ccmHashes = crossChainMessages.map(ccm => hash(ccm)); + const ccmHashes = crossChainMessages.map(ccm => utils.hash(ccm)); let newInboxRoot; let newInboxAppendPath = partnerChannelData.inbox.appendPath; @@ -451,7 +451,7 @@ export const verifyCertificateSignature = ( }; } const { activeValidators, certificateThreshold } = partnerValidators; - const verifySignature = verifyWeightedAggSig( + const verifySignature = bls.verifyWeightedAggSig( activeValidators.map(v => v.blsKey), decodedCertificate.aggregationBits as Buffer, decodedCertificate.signature as Buffer, diff --git a/framework/src/modules/random/constants.ts b/framework/src/modules/random/constants.ts index 883482d07cf..6e5543b9d2f 100644 --- a/framework/src/modules/random/constants.ts +++ b/framework/src/modules/random/constants.ts @@ -12,10 +12,10 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const MODULE_ID_RANDOM = 15; -export const MODULE_ID_RANDOM_BUFFER = intToBuffer(MODULE_ID_RANDOM, 4); +export const MODULE_ID_RANDOM_BUFFER = utils.intToBuffer(MODULE_ID_RANDOM, 4); export const DEFAULT_MAX_LENGTH_REVEALS = 206; export const STORE_PREFIX_RANDOM = 0x0000; export const STORE_PREFIX_REGISTERED_HASH_ONION = Buffer.from('00', 'hex'); diff --git a/framework/src/modules/random/module.ts b/framework/src/modules/random/module.ts index f6d771b7d92..db7b3d70957 100644 --- a/framework/src/modules/random/module.ts +++ b/framework/src/modules/random/module.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hashOnion, generateHashOnionSeed } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { dataStructures, objects } from '@liskhq/lisk-utils'; import { LiskValidationError, validator } from '@liskhq/lisk-validator'; @@ -280,7 +280,7 @@ export class RandomModule extends BaseModule { const hashOnionConfig = this._getHashOnionConfig(address); if (!hashOnionConfig) { return { - hash: generateHashOnionSeed(), + hash: utils.generateHashOnionSeed(), count: 0, }; } @@ -298,7 +298,7 @@ export class RandomModule extends BaseModule { 'All of the hash onion has been used already. Please update to the new hash onion.', ); return { - hash: generateHashOnionSeed(), + hash: utils.generateHashOnionSeed(), count: 0, }; } @@ -308,7 +308,7 @@ export class RandomModule extends BaseModule { ? Math.ceil(nextCount / hashOnionConfig.distance) + 1 : Math.ceil(nextCount / hashOnionConfig.distance); const nextCheckpoint = hashOnionConfig.hashes[nextCheckpointIndex]; - const hashes = hashOnion(nextCheckpoint, hashOnionConfig.distance, 1); + const hashes = utils.hashOnion(nextCheckpoint, hashOnionConfig.distance, 1); const checkpointIndex = nextCount % hashOnionConfig.distance; return { hash: hashes[checkpointIndex], diff --git a/framework/src/modules/random/utils.ts b/framework/src/modules/random/utils.ts index 41240ca0694..ab5455c5109 100644 --- a/framework/src/modules/random/utils.ts +++ b/framework/src/modules/random/utils.ts @@ -13,7 +13,7 @@ */ import * as cryptography from '@liskhq/lisk-cryptography'; -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { SEED_REVEAL_HASH_SIZE } from './constants'; import { ValidatorSeedReveal } from './types'; @@ -35,7 +35,9 @@ export const isSeedValidInput = ( if (!lastSeed) { return false; } - return lastSeed.seedReveal.equals(cryptography.hash(seedReveal).slice(0, SEED_REVEAL_HASH_SIZE)); + return lastSeed.seedReveal.equals( + cryptography.utils.hash(seedReveal).slice(0, SEED_REVEAL_HASH_SIZE), + ); }; export const getSeedRevealValidity = ( @@ -58,7 +60,7 @@ export const getSeedRevealValidity = ( if ( !lastSeed || - lastSeed.seedReveal.equals(cryptography.hash(seedReveal).slice(0, SEED_REVEAL_HASH_SIZE)) + lastSeed.seedReveal.equals(cryptography.utils.hash(seedReveal).slice(0, SEED_REVEAL_HASH_SIZE)) ) { return true; } @@ -74,8 +76,8 @@ export const getRandomSeed = ( if (height < 0 || numberOfSeeds < 0) { throw new Error('Height or number of seeds cannot be negative.'); } - const initRandomBuffer = intToBuffer(height + numberOfSeeds, 4); - let randomSeed = cryptography.hash(initRandomBuffer).slice(0, 16); + const initRandomBuffer = utils.intToBuffer(height + numberOfSeeds, 4); + let randomSeed = cryptography.utils.hash(initRandomBuffer).slice(0, 16); const currentSeeds = validatorsReveal.filter( v => height <= v.height && v.height <= height + numberOfSeeds, ); diff --git a/framework/src/modules/reward/constants.ts b/framework/src/modules/reward/constants.ts index 428c9aa71f4..80b2c76f1e0 100644 --- a/framework/src/modules/reward/constants.ts +++ b/framework/src/modules/reward/constants.ts @@ -12,16 +12,19 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const MODULE_ID_REWARD = 10; -export const TOKEN_ID_LSK_MAINCHAIN = { chainID: intToBuffer(0, 4), localID: intToBuffer(0, 4) }; +export const TOKEN_ID_LSK_MAINCHAIN = { + chainID: utils.intToBuffer(0, 4), + localID: utils.intToBuffer(0, 4), +}; export const REWARD_REDUCTION_FACTOR_BFT = 4; export const defaultConfig = { tokenIDReward: { - chainID: intToBuffer(0, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(0, 4), + localID: utils.intToBuffer(0, 4), }, offset: 2160, distance: 3000000, diff --git a/framework/src/modules/reward/module.ts b/framework/src/modules/reward/module.ts index eeac9c38745..e80c5a9ed13 100644 --- a/framework/src/modules/reward/module.ts +++ b/framework/src/modules/reward/module.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { objects } from '@liskhq/lisk-utils'; import { LiskValidationError, validator } from '@liskhq/lisk-validator'; import { BaseModule, ModuleInitArgs, ModuleMetadata } from '../base_module'; @@ -28,7 +28,7 @@ import { } from './schemas'; export class RewardModule extends BaseModule { - public id = intToBuffer(MODULE_ID_REWARD, 4); + public id = utils.intToBuffer(MODULE_ID_REWARD, 4); public name = 'reward'; public api = new RewardAPI(this.id); public configSchema = configSchema; diff --git a/framework/src/modules/token/constants.ts b/framework/src/modules/token/constants.ts index 6a4ff7ec676..d7dd4cb8de2 100644 --- a/framework/src/modules/token/constants.ts +++ b/framework/src/modules/token/constants.ts @@ -12,19 +12,22 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const MODULE_ID_TOKEN = 2; -export const MODULE_ID_TOKEN_BUFFER = intToBuffer(MODULE_ID_TOKEN, 4); +export const MODULE_ID_TOKEN_BUFFER = utils.intToBuffer(MODULE_ID_TOKEN, 4); export const COMMAND_ID_TRANSFER = 0; -export const COMMAND_ID_TRANSFER_BUFFER = intToBuffer(COMMAND_ID_TRANSFER, 4); +export const COMMAND_ID_TRANSFER_BUFFER = utils.intToBuffer(COMMAND_ID_TRANSFER, 4); export const CROSS_CHAIN_COMMAND_ID_TRANSFER = 0; -export const CROSS_CHAIN_COMMAND_ID_TRANSFER_BUFFER = intToBuffer( +export const CROSS_CHAIN_COMMAND_ID_TRANSFER_BUFFER = utils.intToBuffer( CROSS_CHAIN_COMMAND_ID_TRANSFER, 4, ); export const CROSS_CHAIN_COMMAND_ID_FORWARD = 1; -export const CROSS_CHAIN_COMMAND_ID_FORWARD_BUFFER = intToBuffer(CROSS_CHAIN_COMMAND_ID_FORWARD, 4); +export const CROSS_CHAIN_COMMAND_ID_FORWARD_BUFFER = utils.intToBuffer( + CROSS_CHAIN_COMMAND_ID_FORWARD, + 4, +); export const ADDRESS_LENGTH = 20; export const MAX_DATA_LENGTH = 64; diff --git a/framework/src/modules/token/utils.ts b/framework/src/modules/token/utils.ts index b8a6a637bd8..9746877f4ce 100644 --- a/framework/src/modules/token/utils.ts +++ b/framework/src/modules/token/utils.ts @@ -13,7 +13,7 @@ */ import { NotFoundError } from '@liskhq/lisk-chain'; -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { APIContext } from '../../state_machine'; import { CHAIN_ID_ALIAS_NATIVE, @@ -151,4 +151,4 @@ export const deductEscrowAmountWithTerminate = async ( await escrowStore.setWithSchema(escrowKey, escrowData, escrowStoreSchema); }; -export const getIDAsKeyForStore = (id: number) => intToBuffer(id, 4); +export const getIDAsKeyForStore = (id: number) => utils.intToBuffer(id, 4); diff --git a/framework/src/modules/validators/api.ts b/framework/src/modules/validators/api.ts index 5156fd9e39d..b6a4adc4078 100644 --- a/framework/src/modules/validators/api.ts +++ b/framework/src/modules/validators/api.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { blsPopVerify } from '@liskhq/lisk-cryptography'; +import { bls } from '@liskhq/lisk-cryptography'; import { BaseAPI } from '../base_api'; import { APIContext, ImmutableAPIContext } from '../../state_machine'; import { @@ -52,7 +52,7 @@ export class ValidatorsAPI extends BaseAPI { return false; } - if (!blsPopVerify(blsKey, proofOfPossession)) { + if (!bls.popVerify(blsKey, proofOfPossession)) { return false; } @@ -119,7 +119,7 @@ export class ValidatorsAPI extends BaseAPI { return false; } - if (!blsPopVerify(blsKey, proofOfPossession)) { + if (!bls.popVerify(blsKey, proofOfPossession)) { return false; } diff --git a/framework/src/modules/validators/endpoint.ts b/framework/src/modules/validators/endpoint.ts index 3f4e601b03c..280d4134581 100644 --- a/framework/src/modules/validators/endpoint.ts +++ b/framework/src/modules/validators/endpoint.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { blsPopVerify, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils, bls } from '@liskhq/lisk-cryptography'; import { LiskValidationError, validator } from '@liskhq/lisk-validator'; import { NotFoundError } from '@liskhq/lisk-db'; import { ModuleEndpointContext } from '../../types'; @@ -31,7 +31,7 @@ export class ValidatorsEndpoint extends BaseEndpoint { const { proofOfPossession, blsKey } = req; const blsKeysSubStore = ctx.getStore( - intToBuffer(MODULE_ID_VALIDATORS, 4), + utils.intToBuffer(MODULE_ID_VALIDATORS, 4), STORE_PREFIX_BLS_KEYS, ); @@ -50,7 +50,7 @@ export class ValidatorsEndpoint extends BaseEndpoint { } return { - valid: blsPopVerify(Buffer.from(blsKey, 'hex'), Buffer.from(proofOfPossession, 'hex')), + valid: bls.popVerify(Buffer.from(blsKey, 'hex'), Buffer.from(proofOfPossession, 'hex')), }; } } diff --git a/framework/src/modules/validators/module.ts b/framework/src/modules/validators/module.ts index 59864d949a3..2d589096675 100644 --- a/framework/src/modules/validators/module.ts +++ b/framework/src/modules/validators/module.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { objects } from '@liskhq/lisk-utils'; import { LiskValidationError, validator } from '@liskhq/lisk-validator'; import { BaseModule, ModuleInitArgs, ModuleMetadata } from '../base_module'; @@ -33,7 +33,7 @@ import { } from './schemas'; export class ValidatorsModule extends BaseModule { - public id = intToBuffer(MODULE_ID_VALIDATORS, 4); + public id = utils.intToBuffer(MODULE_ID_VALIDATORS, 4); public name = 'validators'; public api = new ValidatorsAPI(this.id); public endpoint = new ValidatorsEndpoint(this.id); diff --git a/framework/src/testing/block_processing_env.ts b/framework/src/testing/block_processing_env.ts index c86440f1aaf..74e75a255da 100644 --- a/framework/src/testing/block_processing_env.ts +++ b/framework/src/testing/block_processing_env.ts @@ -18,7 +18,7 @@ import * as fs from 'fs-extra'; import * as path from 'path'; import * as os from 'os'; import { Block, Chain, DataAccess, BlockHeader, Transaction, StateStore } from '@liskhq/lisk-chain'; -import { getNetworkIdentifier, getKeys } from '@liskhq/lisk-cryptography'; +import { utils, address } from '@liskhq/lisk-cryptography'; import { Database, StateDB } from '@liskhq/lisk-db'; import { objects } from '@liskhq/lisk-utils'; import { codec } from '@liskhq/lisk-codec'; @@ -116,7 +116,7 @@ const createProcessableBlock = async ( for (const tx of transactions) { await engine['_generator']['_pool'].add(tx); } - const { privateKey } = getKeys(passphrase); + const { privateKey } = address.getKeys(passphrase); const block = await engine.generateBlock({ generatorAddress: validator, height: previousBlockHeader.height + 1, @@ -197,7 +197,7 @@ export const getBlockProcessingEnv = async ( const engine = new Engine(abiHandler); await engine['_init'](); - const networkIdentifier = getNetworkIdentifier( + const networkIdentifier = utils.getNetworkIdentifier( genesisBlock.header.id, appConfig.genesis.communityIdentifier, ); diff --git a/framework/src/testing/create_block.ts b/framework/src/testing/create_block.ts index 3b01e4c8c5b..b82803b18eb 100644 --- a/framework/src/testing/create_block.ts +++ b/framework/src/testing/create_block.ts @@ -14,12 +14,7 @@ */ /* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access */ import { Block, BlockHeader, Transaction, BlockHeaderAttrs, BlockAssets } from '@liskhq/lisk-chain'; -import { - getAddressFromPublicKey, - getPrivateAndPublicKeyFromPassphrase, - getRandomBytes, - hash, -} from '@liskhq/lisk-cryptography'; +import { address, utils, ed } from '@liskhq/lisk-cryptography'; import { MerkleTree } from '@liskhq/lisk-tree'; interface CreateBlock { @@ -37,11 +32,11 @@ export const createBlockHeaderWithDefaults = (header?: Partial version: header?.version ?? 2, timestamp: header?.timestamp ?? 0, height: header?.height ?? 1, - previousBlockID: header?.previousBlockID ?? hash(getRandomBytes(4)), - transactionRoot: header?.transactionRoot ?? hash(getRandomBytes(4)), - stateRoot: header?.stateRoot ?? hash(getRandomBytes(4)), - eventRoot: header?.eventRoot ?? hash(getRandomBytes(4)), - generatorAddress: header?.generatorAddress ?? getRandomBytes(32), + previousBlockID: header?.previousBlockID ?? utils.hash(utils.getRandomBytes(4)), + transactionRoot: header?.transactionRoot ?? utils.hash(utils.getRandomBytes(4)), + stateRoot: header?.stateRoot ?? utils.hash(utils.getRandomBytes(4)), + eventRoot: header?.eventRoot ?? utils.hash(utils.getRandomBytes(4)), + generatorAddress: header?.generatorAddress ?? utils.getRandomBytes(32), aggregateCommit: header?.aggregateCommit ?? { height: 0, aggregationBits: Buffer.alloc(0), @@ -49,14 +44,16 @@ export const createBlockHeaderWithDefaults = (header?: Partial }, maxHeightGenerated: header?.maxHeightGenerated ?? 0, maxHeightPrevoted: header?.maxHeightPrevoted ?? 0, - assetRoot: header?.assetRoot ?? hash(getRandomBytes(4)), - validatorsHash: header?.validatorsHash ?? hash(getRandomBytes(4)), + assetRoot: header?.assetRoot ?? utils.hash(utils.getRandomBytes(4)), + validatorsHash: header?.validatorsHash ?? utils.hash(utils.getRandomBytes(4)), }); export const createFakeBlockHeader = (header?: Partial): BlockHeader => { const headerWithDefault = createBlockHeaderWithDefaults(header); - const { privateKey } = getPrivateAndPublicKeyFromPassphrase(getRandomBytes(10).toString('hex')); - headerWithDefault.sign(getRandomBytes(32), privateKey); + const { privateKey } = ed.getPrivateAndPublicKeyFromPassphrase( + utils.getRandomBytes(10).toString('hex'), + ); + headerWithDefault.sign(utils.getRandomBytes(32), privateKey); return headerWithDefault; }; @@ -69,7 +66,7 @@ export const createBlock = async ({ assets, header, }: CreateBlock): Promise => { - const { publicKey, privateKey } = getPrivateAndPublicKeyFromPassphrase(passphrase); + const { publicKey, privateKey } = ed.getPrivateAndPublicKeyFromPassphrase(passphrase); const txTree = new MerkleTree(); await txTree.init(transactions?.map(tx => tx.id) ?? []); @@ -79,7 +76,7 @@ export const createBlock = async ({ transactionRoot: header?.transactionRoot ?? txTree.root, eventRoot: header?.eventRoot, stateRoot: header?.stateRoot, - generatorAddress: getAddressFromPublicKey(publicKey), + generatorAddress: address.getAddressFromPublicKey(publicKey), ...header, }); diff --git a/framework/src/testing/create_contexts.ts b/framework/src/testing/create_contexts.ts index 91b5ecc1fc4..763c025c2cb 100644 --- a/framework/src/testing/create_contexts.ts +++ b/framework/src/testing/create_contexts.ts @@ -14,7 +14,7 @@ */ import { BlockAssets, BlockHeader, StateStore, Transaction } from '@liskhq/lisk-chain'; -import { getRandomBytes, hash } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase } from '@liskhq/lisk-db'; import { ModuleEndpointContext } from '../types'; import { Logger } from '../logger'; @@ -62,21 +62,21 @@ export const createGenesisBlockContext = (params: { params.header ?? new BlockHeader({ height: 0, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), previousBlockID: Buffer.alloc(0), timestamp: Math.floor(Date.now() / 1000), version: 0, - transactionRoot: hash(Buffer.alloc(0)), - stateRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), + stateRoot: utils.hash(Buffer.alloc(0)), maxHeightGenerated: 0, maxHeightPrevoted: 0, - assetRoot: hash(Buffer.alloc(0)), + assetRoot: utils.hash(Buffer.alloc(0)), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - validatorsHash: hash(Buffer.alloc(0)), + validatorsHash: utils.hash(Buffer.alloc(0)), }); const ctx = new GenesisBlockContext({ eventQueue, @@ -105,21 +105,21 @@ export const createBlockContext = (params: { params.header ?? new BlockHeader({ height: 0, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), previousBlockID: Buffer.alloc(0), timestamp: Math.floor(Date.now() / 1000), version: 0, - transactionRoot: hash(Buffer.alloc(0)), - stateRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), + stateRoot: utils.hash(Buffer.alloc(0)), maxHeightGenerated: 0, maxHeightPrevoted: 0, - assetRoot: hash(Buffer.alloc(0)), + assetRoot: utils.hash(Buffer.alloc(0)), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - validatorsHash: hash(Buffer.alloc(0)), + validatorsHash: utils.hash(Buffer.alloc(0)), }); const ctx = new BlockContext({ stateStore, @@ -128,7 +128,7 @@ export const createBlockContext = (params: { transactions: params.transactions ?? [], header, assets: params.assets ?? new BlockAssets(), - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), currentValidators: params.validators ?? [], impliesMaxPrevote: true, maxHeightCertified: 0, @@ -156,21 +156,21 @@ export const createBlockGenerateContext = (params: { params.header ?? new BlockHeader({ height: 0, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), previousBlockID: Buffer.alloc(0), timestamp: Math.floor(Date.now() / 1000), version: 0, - transactionRoot: hash(Buffer.alloc(0)), - stateRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), + stateRoot: utils.hash(Buffer.alloc(0)), maxHeightGenerated: 0, maxHeightPrevoted: 0, - assetRoot: hash(Buffer.alloc(0)), + assetRoot: utils.hash(Buffer.alloc(0)), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - validatorsHash: hash(Buffer.alloc(0)), + validatorsHash: utils.hash(Buffer.alloc(0)), }); const stateStore = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); const getStore = (moduleID: Buffer, storePrefix: number) => @@ -180,7 +180,7 @@ export const createBlockGenerateContext = (params: { assets: params.assets ?? new BlockAssets([]), getGeneratorStore: params.getGeneratorStore ?? getGeneratorStore, logger: params.logger ?? loggerMock, - networkIdentifier: params.networkIdentifier ?? getRandomBytes(32), + networkIdentifier: params.networkIdentifier ?? utils.getRandomBytes(32), getAPIContext: params.getAPIContext ?? (() => ({ getStore, eventQueue: new EventQueue() })), getStore: params.getStore ?? getStore, getFinalizedHeight: () => params.finalizedHeight ?? 0, @@ -211,21 +211,21 @@ export const createTransactionContext = (params: { params.header ?? new BlockHeader({ height: 0, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), previousBlockID: Buffer.alloc(0), timestamp: Math.floor(Date.now() / 1000), version: 0, - transactionRoot: hash(Buffer.alloc(0)), - stateRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), + stateRoot: utils.hash(Buffer.alloc(0)), maxHeightGenerated: 0, maxHeightPrevoted: 0, - assetRoot: hash(Buffer.alloc(0)), + assetRoot: utils.hash(Buffer.alloc(0)), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - validatorsHash: hash(Buffer.alloc(0)), + validatorsHash: utils.hash(Buffer.alloc(0)), }); const ctx = new TransactionContext({ stateStore, @@ -233,7 +233,7 @@ export const createTransactionContext = (params: { eventQueue, header, assets: params.assets ?? new BlockAssets(), - networkIdentifier: params.networkIdentifier ?? getRandomBytes(32), + networkIdentifier: params.networkIdentifier ?? utils.getRandomBytes(32), transaction: params.transaction, currentValidators: params.currentValidators ?? [], impliesMaxPrevote: params.impliesMaxPrevote ?? true, @@ -308,7 +308,7 @@ const createCCAPIContext = (params: { getAPIContext: params.getAPIContext ?? (() => ({ getStore, eventQueue })), eventQueue, ccm, - feeAddress: params.feeAddress ?? getRandomBytes(20), + feeAddress: params.feeAddress ?? utils.getRandomBytes(20), }; }; diff --git a/framework/src/testing/create_transaction.ts b/framework/src/testing/create_transaction.ts index a00d18af93c..e5ce46fe29e 100644 --- a/framework/src/testing/create_transaction.ts +++ b/framework/src/testing/create_transaction.ts @@ -15,7 +15,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { getAddressAndPublicKeyFromPassphrase, getKeys } from '@liskhq/lisk-cryptography'; +import { address } from '@liskhq/lisk-cryptography'; import { validateTransaction } from '@liskhq/lisk-transactions'; import { CommandClass } from './types'; @@ -38,7 +38,7 @@ export const createTransaction = ({ passphrase, networkIdentifier, }: CreateTransactionInput): Transaction => { - const { publicKey } = getAddressAndPublicKeyFromPassphrase(passphrase ?? ''); + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(passphrase ?? ''); // eslint-disable-next-line new-cap const commandInstance = new commandClass(); const commandID = commandInstance.id; @@ -73,7 +73,7 @@ export const createTransaction = ({ throw new Error('Network identifier is required to sign a transaction'); } - const keys = getKeys(passphrase); + const keys = address.getKeys(passphrase); result.sign(networkIdentifier, keys.privateKey); return result; diff --git a/framework/src/testing/fixtures/config.ts b/framework/src/testing/fixtures/config.ts index ef5605c386c..b996d8f1ab8 100644 --- a/framework/src/testing/fixtures/config.ts +++ b/framework/src/testing/fixtures/config.ts @@ -12,12 +12,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { - decryptPassphraseWithPassword, - intToBuffer, - EncryptedPassphraseObject, - parseEncryptedPassphrase, -} from '@liskhq/lisk-cryptography'; +import { utils, encrypt } from '@liskhq/lisk-cryptography'; export const defaultPassword = 'tiger grit rigid pipe athlete cheese guitar hurdle remind gap peasant pond'; @@ -42,8 +37,8 @@ export const defaultConfig = { minFeePerByte: 1000, baseFees: [ { - moduleID: intToBuffer(12, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(12, 4), + commandID: utils.intToBuffer(0, 4), baseFee: '1000000000', }, ], @@ -2627,10 +2622,10 @@ const getDelegateFromDefaultConfig = (address: Buffer) => { export const getPassphraseFromDefaultConfig = async (address: Buffer): Promise => { const delegateConfig = getDelegateFromDefaultConfig(address); - const encryptedPassphraseObject = parseEncryptedPassphrase( + const encryptedPassphraseObject = encrypt.parseEncryptedPassphrase( delegateConfig.encryptedPassphrase, - ) as EncryptedPassphraseObject; - const passphrase = await decryptPassphraseWithPassword( + ) as encrypt.EncryptedPassphraseObject; + const passphrase = await encrypt.decryptPassphraseWithPassword( encryptedPassphraseObject, defaultPassword, ); diff --git a/framework/src/testing/fixtures/genesis-asset.ts b/framework/src/testing/fixtures/genesis-asset.ts index 478d0926ce4..20fa7b1ab1f 100644 --- a/framework/src/testing/fixtures/genesis-asset.ts +++ b/framework/src/testing/fixtures/genesis-asset.ts @@ -13,12 +13,12 @@ * */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { genesisTokenStoreSchema } from '../../modules/token'; export const blockAssetsJSON = [ { - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), data: { userSubstore: [ { @@ -709,7 +709,7 @@ export const blockAssetsJSON = [ schema: genesisTokenStoreSchema, }, { - moduleID: intToBuffer(13, 4), + moduleID: utils.intToBuffer(13, 4), data: { validators: [ { diff --git a/framework/src/testing/utils.ts b/framework/src/testing/utils.ts index 71b76ab815c..a04bdbd1676 100644 --- a/framework/src/testing/utils.ts +++ b/framework/src/testing/utils.ts @@ -16,7 +16,7 @@ import * as os from 'os'; import * as path from 'path'; import * as fs from 'fs-extra'; import { Database, StateDB } from '@liskhq/lisk-db'; -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { EVENT_CHAIN_BLOCK_NEW } from '../engine/events'; import { Data, WaitUntilBlockHeightOptions } from './types'; @@ -65,4 +65,4 @@ export const removeDB = (dbPath = defaultDatabasePath): void => fs.removeSync(getDBPath(name, dbPath)), ); -export const getIDAsKeyForStore = (id: number) => intToBuffer(id, 4); +export const getIDAsKeyForStore = (id: number) => utils.intToBuffer(id, 4); diff --git a/framework/test/fixtures/blocks.ts b/framework/test/fixtures/blocks.ts index d85dfff9b49..2c1a9e37080 100644 --- a/framework/test/fixtures/blocks.ts +++ b/framework/test/fixtures/blocks.ts @@ -32,20 +32,20 @@ export const genesisBlock = (): Block => { generatorAddress: Buffer.alloc(0), height: 0, version: 0, - previousBlockID: getRandomBytes(32), + previousBlockID: utils.getRandomBytes(32), timestamp: Math.floor(Date.now() / 1000 - 24 * 60 * 60), - stateRoot: hash(Buffer.alloc(0)), - eventRoot: hash(Buffer.alloc(0)), + stateRoot: utils.hash(Buffer.alloc(0)), + eventRoot: utils.hash(Buffer.alloc(0)), maxHeightGenerated: 0, maxHeightPrevoted: 0, - assetRoot: hash(Buffer.alloc(0)), - validatorsHash: getRandomBytes(32), + assetRoot: utils.hash(Buffer.alloc(0)), + validatorsHash: utils.getRandomBytes(32), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - transactionRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), signature: Buffer.alloc(0), }); @@ -62,21 +62,21 @@ export const createFakeBlockHeader = (header?: Partial): Block version: 2, timestamp: header?.timestamp ?? 0, height: header?.height ?? 0, - previousBlockID: header?.previousBlockID ?? hash(getRandomBytes(4)), - transactionRoot: header?.transactionRoot ?? hash(getRandomBytes(4)), + previousBlockID: header?.previousBlockID ?? utils.hash(utils.getRandomBytes(4)), + transactionRoot: header?.transactionRoot ?? utils.hash(utils.getRandomBytes(4)), maxHeightGenerated: header?.maxHeightGenerated ?? 0, maxHeightPrevoted: header?.maxHeightPrevoted ?? 0, - assetRoot: header?.assetRoot ?? hash(getRandomBytes(4)), + assetRoot: header?.assetRoot ?? utils.hash(utils.getRandomBytes(4)), aggregateCommit: header?.aggregateCommit ?? { height: 0, aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - validatorsHash: header?.validatorsHash ?? getRandomBytes(32), - stateRoot: header?.stateRoot ?? hash(getRandomBytes(4)), - eventRoot: header?.eventRoot ?? hash(getRandomBytes(4)), - generatorAddress: header?.generatorAddress ?? getRandomBytes(32), - signature: header?.signature ?? getRandomBytes(64), + validatorsHash: header?.validatorsHash ?? utils.getRandomBytes(32), + stateRoot: header?.stateRoot ?? utils.hash(utils.getRandomBytes(4)), + eventRoot: header?.eventRoot ?? utils.hash(utils.getRandomBytes(4)), + generatorAddress: header?.generatorAddress ?? utils.getRandomBytes(32), + signature: header?.signature ?? utils.getRandomBytes(64), }); /** @@ -102,18 +102,18 @@ export const createValidDefaultBlock = async ( previousBlockID: genesisBlock().header.id, timestamp: 1000, transactionRoot: txTree.root, - stateRoot: getRandomBytes(32), - eventRoot: getRandomBytes(32), - generatorAddress: getAddressFromPublicKey(keypair.publicKey), + stateRoot: utils.getRandomBytes(32), + eventRoot: utils.getRandomBytes(32), + generatorAddress: address.getAddressFromPublicKey(keypair.publicKey), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - assetRoot: hash(Buffer.alloc(0)), + assetRoot: utils.hash(Buffer.alloc(0)), maxHeightPrevoted: 0, maxHeightGenerated: 0, - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), ...block?.header, }); diff --git a/framework/test/functional/network/banning/invalid_block_property.spec.ts b/framework/test/functional/network/banning/invalid_block_property.spec.ts index 8431bf18740..db2e8fd5056 100644 --- a/framework/test/functional/network/banning/invalid_block_property.spec.ts +++ b/framework/test/functional/network/banning/invalid_block_property.spec.ts @@ -55,11 +55,11 @@ describe('Public block related P2P endpoints with invalid block property', () => const block = await app['_node']['_forger']['_create']({ keypair, previousBlock: lastBlock, - seedReveal: getRandomBytes(16), + seedReveal: utils.getRandomBytes(16), timestamp, transactions: [], }); - (block.header as any).transactionRoot = getRandomBytes(32); + (block.header as any).transactionRoot = utils.getRandomBytes(32); const invalidEncodedBlock = app['_node']['_chain'].dataAccess.encode(block); const data = codec.encode(postBlockEventSchema, { block: invalidEncodedBlock }); diff --git a/framework/test/functional/network/blocks.spec.ts b/framework/test/functional/network/blocks.spec.ts index 49a6fc62b57..2ef0c2c7952 100644 --- a/framework/test/functional/network/blocks.spec.ts +++ b/framework/test/functional/network/blocks.spec.ts @@ -84,7 +84,7 @@ describe('Public block related P2P endpoints', () => { }); it('should be rejected if blockId does not exist', async () => { - const blockId = encodeBlockId(getRandomBytes(32)); + const blockId = encodeBlockId(utils.getRandomBytes(32)); await expect( p2p.requestFromPeer( @@ -100,7 +100,7 @@ describe('Public block related P2P endpoints', () => { describe('getHighestCommonBlock', () => { it('should return decodable block', async () => { - const ids = [app['_node']['_chain'].lastBlock.header.id, getRandomBytes(32)]; + const ids = [app['_node']['_chain'].lastBlock.header.id, utils.getRandomBytes(32)]; const blockIds = encodeBlockIds(ids); const { data } = await p2p.requestFromPeer( { @@ -118,7 +118,7 @@ describe('Public block related P2P endpoints', () => { }); it('should return undefined', async () => { - const ids = [getRandomBytes(32)]; + const ids = [utils.getRandomBytes(32)]; const blockIds = encodeBlockIds(ids); const { data } = await p2p.requestFromPeer( { diff --git a/framework/test/functional/network/transactions.spec.ts b/framework/test/functional/network/transactions.spec.ts index f5711796874..41762b1d087 100644 --- a/framework/test/functional/network/transactions.spec.ts +++ b/framework/test/functional/network/transactions.spec.ts @@ -50,7 +50,9 @@ describe('Public transaction related P2P endpoints', () => { describe('getTransactions', () => { it('should return empty array if unknown transaction is queried', async () => { // Act - const { transactions } = await getTransactionsFromNetwork(app, p2p, [getRandomBytes(32)]); + const { transactions } = await getTransactionsFromNetwork(app, p2p, [ + utils.getRandomBytes(32), + ]); // Assert expect(transactions).toHaveLength(0); diff --git a/framework/test/integration/node/processor/delete_block.spec.ts b/framework/test/integration/node/processor/delete_block.spec.ts index d0382fbd420..a10fd3df073 100644 --- a/framework/test/integration/node/processor/delete_block.spec.ts +++ b/framework/test/integration/node/processor/delete_block.spec.ts @@ -23,7 +23,7 @@ import { } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { nodeUtils } from '../../../utils'; import { createDelegateRegisterTransaction, @@ -102,7 +102,7 @@ describe('Delete block', () => { await processEnv .getBlockchainDB() .set( - concatDBKeys(DB_KEY_DIFF_STATE, intToBuffer(newBlock.header.height, 4)), + concatDBKeys(DB_KEY_DIFF_STATE, utils.intToBuffer(newBlock.header.height, 4)), emptyDiffState, ); await processEnv.process(newBlock); @@ -153,7 +153,7 @@ describe('Delete block', () => { await expect( processEnv .getBlockchainDB() - .get(concatDBKeys(DB_KEY_DIFF_STATE, intToBuffer(newBlock.header.height, 4))), + .get(concatDBKeys(DB_KEY_DIFF_STATE, utils.intToBuffer(newBlock.header.height, 4))), ).rejects.toBeInstanceOf(NotFoundError); }); }); @@ -185,7 +185,11 @@ describe('Delete block', () => { await processEnv.process(newBlock); await processEnv.getConsensus()['_deleteLastBlock'](); // Assert - const dbKey = concatDBKeys(DB_KEY_STATE_STORE, new TokenModule().id, intToBuffer(0, 2)); + const dbKey = concatDBKeys( + DB_KEY_STATE_STORE, + new TokenModule().id, + utils.intToBuffer(0, 2), + ); await expect(processEnv.getBlockchainDB().get(dbKey)).rejects.toThrow( `Specified key ${dbKey.toString('hex')} does not exist`, ); diff --git a/framework/test/integration/testing/block_processing_env.spec.ts b/framework/test/integration/testing/block_processing_env.spec.ts index 20066e00996..eae456905b9 100644 --- a/framework/test/integration/testing/block_processing_env.spec.ts +++ b/framework/test/integration/testing/block_processing_env.spec.ts @@ -86,6 +86,6 @@ describe('getBlockProcessingEnv', () => { // Act & Assert const block = await processEnv.createBlock(); - expect(block.header.generatorAddress).toEqual(getAddressFromPublicKey(publicKey)); + expect(block.header.generatorAddress).toEqual(address.getAddressFromPublicKey(publicKey)); }); }); diff --git a/framework/test/unit/abi_handler/abi_handler.spec.ts b/framework/test/unit/abi_handler/abi_handler.spec.ts index edb9e71f261..5e4e873dea2 100644 --- a/framework/test/unit/abi_handler/abi_handler.spec.ts +++ b/framework/test/unit/abi_handler/abi_handler.spec.ts @@ -62,7 +62,7 @@ describe('abi handler', () => { modules: [mod2, mod], config: applicationConfigSchema.default, }); - abiHandler['_networkIdentifier'] = getRandomBytes(32); + abiHandler['_networkIdentifier'] = utils.getRandomBytes(32); }); describe('init', () => { @@ -97,7 +97,7 @@ describe('abi handler', () => { config: applicationConfigSchema.default, }); - const networkIdentifier = getRandomBytes(32); + const networkIdentifier = utils.getRandomBytes(32); await abiHandler.ready({ networkIdentifier, lastBlockHeight: 21 }); expect(abiHandler.networkIdentifier).toEqual(networkIdentifier); @@ -107,7 +107,7 @@ describe('abi handler', () => { describe('initStateMachine', () => { it('should fail if execution context exists', async () => { abiHandler['_executionContext'] = { - id: getRandomBytes(32), + id: utils.getRandomBytes(32), } as never; await expect( abiHandler.initStateMachine({ @@ -130,8 +130,8 @@ describe('abi handler', () => { it('should fail if execution context does not exist', async () => { await expect( abiHandler.initGenesisState({ - contextID: getRandomBytes(32), - stateRoot: getRandomBytes(32), + contextID: utils.getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), }), ).rejects.toThrow('Context is not initialized or different'); }); @@ -142,8 +142,8 @@ describe('abi handler', () => { }); await expect( abiHandler.initGenesisState({ - contextID: getRandomBytes(32), - stateRoot: getRandomBytes(32), + contextID: utils.getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), }), ).rejects.toThrow('Context is not initialized or different'); }); @@ -155,7 +155,7 @@ describe('abi handler', () => { }); const resp = await abiHandler.initGenesisState({ contextID, - stateRoot: getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), }); expect(abiHandler['_stateMachine'].executeGenesisBlock).toHaveBeenCalledTimes(1); @@ -171,7 +171,7 @@ describe('abi handler', () => { it('should fail if execution context does not exist', async () => { await expect( abiHandler.insertAssets({ - contextID: getRandomBytes(32), + contextID: utils.getRandomBytes(32), finalizedHeight: 0, }), ).rejects.toThrow('Context is not initialized or different'); @@ -183,7 +183,7 @@ describe('abi handler', () => { }); await expect( abiHandler.insertAssets({ - contextID: getRandomBytes(32), + contextID: utils.getRandomBytes(32), finalizedHeight: 0, }), ).rejects.toThrow('Context is not initialized or different'); @@ -208,8 +208,8 @@ describe('abi handler', () => { it('should fail if execution context does not exist', async () => { await expect( abiHandler.verifyAssets({ - contextID: getRandomBytes(32), - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + contextID: utils.getRandomBytes(32), + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], }), ).rejects.toThrow('Context is not initialized or different'); }); @@ -220,8 +220,8 @@ describe('abi handler', () => { }); await expect( abiHandler.verifyAssets({ - contextID: getRandomBytes(32), - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + contextID: utils.getRandomBytes(32), + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], }), ).rejects.toThrow('Context is not initialized or different'); }); @@ -233,7 +233,7 @@ describe('abi handler', () => { }); const resp = await abiHandler.verifyAssets({ contextID, - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], }); expect(abiHandler['_stateMachine'].verifyAssets).toHaveBeenCalledTimes(1); @@ -245,15 +245,15 @@ describe('abi handler', () => { it('should fail if execution context does not exist', async () => { await expect( abiHandler.beforeTransactionsExecute({ - contextID: getRandomBytes(32), - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + contextID: utils.getRandomBytes(32), + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], consensus: { currentValidators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }, ], implyMaxPrevote: false, @@ -270,15 +270,15 @@ describe('abi handler', () => { }); await expect( abiHandler.beforeTransactionsExecute({ - contextID: getRandomBytes(32), - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + contextID: utils.getRandomBytes(32), + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], consensus: { currentValidators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }, ], implyMaxPrevote: false, @@ -296,14 +296,14 @@ describe('abi handler', () => { }); const resp = await abiHandler.beforeTransactionsExecute({ contextID, - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], consensus: { currentValidators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }, ], implyMaxPrevote: false, @@ -321,15 +321,15 @@ describe('abi handler', () => { it('should fail if execution context does not exist', async () => { await expect( abiHandler.afterTransactionsExecute({ - contextID: getRandomBytes(32), - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + contextID: utils.getRandomBytes(32), + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], consensus: { currentValidators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }, ], implyMaxPrevote: false, @@ -347,15 +347,15 @@ describe('abi handler', () => { }); await expect( abiHandler.afterTransactionsExecute({ - contextID: getRandomBytes(32), - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + contextID: utils.getRandomBytes(32), + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], consensus: { currentValidators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }, ], implyMaxPrevote: false, @@ -374,14 +374,14 @@ describe('abi handler', () => { }); const resp = await abiHandler.afterTransactionsExecute({ contextID, - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], consensus: { currentValidators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }, ], implyMaxPrevote: false, @@ -404,17 +404,17 @@ describe('abi handler', () => { }); // Add random data to check if new state store is used or not await abiHandler['_executionContext']?.stateStore.set( - getRandomBytes(20), - getRandomBytes(100), + utils.getRandomBytes(20), + utils.getRandomBytes(100), ); const tx = new Transaction({ - commandID: intToBuffer(2, 4), + commandID: utils.intToBuffer(2, 4), fee: BigInt(30), - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), nonce: BigInt(2), - params: getRandomBytes(100), - senderPublicKey: getRandomBytes(32), - signatures: [getRandomBytes(64)], + params: utils.getRandomBytes(100), + senderPublicKey: utils.getRandomBytes(32), + signatures: [utils.getRandomBytes(64)], }); const resp = await abiHandler.verifyTransaction({ contextID, @@ -436,16 +436,16 @@ describe('abi handler', () => { header: createFakeBlockHeader().toObject(), }); // Add random data to check if new state store is used or not - const key = getRandomBytes(20); - await abiHandler['_executionContext']?.stateStore.set(key, getRandomBytes(100)); + const key = utils.getRandomBytes(20); + await abiHandler['_executionContext']?.stateStore.set(key, utils.getRandomBytes(100)); const tx = new Transaction({ - commandID: intToBuffer(2, 4), + commandID: utils.intToBuffer(2, 4), fee: BigInt(30), - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), nonce: BigInt(2), - params: getRandomBytes(100), - senderPublicKey: getRandomBytes(32), - signatures: [getRandomBytes(64)], + params: utils.getRandomBytes(100), + senderPublicKey: utils.getRandomBytes(32), + signatures: [utils.getRandomBytes(64)], }); const resp = await abiHandler.verifyTransaction({ contextID: Buffer.alloc(0), @@ -469,31 +469,31 @@ describe('abi handler', () => { }); // Add random data to check if new state store is used or not await abiHandler['_executionContext']?.stateStore.set( - getRandomBytes(20), - getRandomBytes(100), + utils.getRandomBytes(20), + utils.getRandomBytes(100), ); const tx = new Transaction({ - commandID: intToBuffer(0, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(30), - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), nonce: BigInt(2), params: codec.encode(transferParamsSchema, {}), - senderPublicKey: getRandomBytes(32), - signatures: [getRandomBytes(64)], + senderPublicKey: utils.getRandomBytes(32), + signatures: [utils.getRandomBytes(64)], }); const resp = await abiHandler.executeTransaction({ contextID, - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], dryRun: false, header: createFakeBlockHeader().toObject(), transaction: tx.toObject(), consensus: { currentValidators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }, ], implyMaxPrevote: false, @@ -517,30 +517,30 @@ describe('abi handler', () => { header: createFakeBlockHeader().toObject(), }); // Add random data to check if new state store is used or not - const key = getRandomBytes(20); - await abiHandler['_executionContext']?.stateStore.set(key, getRandomBytes(100)); + const key = utils.getRandomBytes(20); + await abiHandler['_executionContext']?.stateStore.set(key, utils.getRandomBytes(100)); const tx = new Transaction({ - commandID: intToBuffer(0, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(30), - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), nonce: BigInt(2), params: codec.encode(transferParamsSchema, {}), - senderPublicKey: getRandomBytes(32), - signatures: [getRandomBytes(64)], + senderPublicKey: utils.getRandomBytes(32), + signatures: [utils.getRandomBytes(64)], }); const resp = await abiHandler.executeTransaction({ - contextID: getRandomBytes(0), - assets: [{ data: getRandomBytes(30), moduleID: intToBuffer(2, 4) }], + contextID: utils.getRandomBytes(0), + assets: [{ data: utils.getRandomBytes(30), moduleID: utils.intToBuffer(2, 4) }], dryRun: true, header: createFakeBlockHeader().toObject(), transaction: tx.toObject(), consensus: { currentValidators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }, ], implyMaxPrevote: false, @@ -562,10 +562,10 @@ describe('abi handler', () => { it('should fail if execution context does not exist', async () => { await expect( abiHandler.commit({ - contextID: getRandomBytes(32), + contextID: utils.getRandomBytes(32), dryRun: true, - expectedStateRoot: getRandomBytes(32), - stateRoot: getRandomBytes(32), + expectedStateRoot: utils.getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), }), ).rejects.toThrow('Context is not initialized or different'); }); @@ -576,10 +576,10 @@ describe('abi handler', () => { }); await expect( abiHandler.commit({ - contextID: getRandomBytes(32), + contextID: utils.getRandomBytes(32), dryRun: true, - expectedStateRoot: getRandomBytes(32), - stateRoot: getRandomBytes(32), + expectedStateRoot: utils.getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), }), ).rejects.toThrow('Context is not initialized or different'); }); @@ -597,9 +597,9 @@ describe('abi handler', () => { it('should fail if execution context does not exist', async () => { await expect( abiHandler.revert({ - contextID: getRandomBytes(32), - expectedStateRoot: getRandomBytes(32), - stateRoot: getRandomBytes(32), + contextID: utils.getRandomBytes(32), + expectedStateRoot: utils.getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), }), ).rejects.toThrow('Context is not initialized or different'); }); @@ -610,9 +610,9 @@ describe('abi handler', () => { }); await expect( abiHandler.revert({ - contextID: getRandomBytes(32), - expectedStateRoot: getRandomBytes(32), - stateRoot: getRandomBytes(32), + contextID: utils.getRandomBytes(32), + expectedStateRoot: utils.getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), }), ).rejects.toThrow('Context is not initialized or different'); }); diff --git a/framework/test/unit/engine/consensus/certificate_generation/commit_list.spec.ts b/framework/test/unit/engine/consensus/certificate_generation/commit_list.spec.ts index eb1bd362311..d992a3d81e6 100644 --- a/framework/test/unit/engine/consensus/certificate_generation/commit_list.spec.ts +++ b/framework/test/unit/engine/consensus/certificate_generation/commit_list.spec.ts @@ -22,19 +22,19 @@ import { SingleCommit } from '../../../../../src/engine/consensus/certificate_ge describe('CommitList', () => { const sampleHeight = 10; const singleSampleCommit = { - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height: sampleHeight, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), }; const sampleCommits = Array.from( { length: 10 }, index => ({ - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height: sampleHeight * (index as number), - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), } as SingleCommit), ); @@ -46,10 +46,10 @@ describe('CommitList', () => { { length: 5 }, _ => ({ - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height: height10, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), } as SingleCommit), ); @@ -57,10 +57,10 @@ describe('CommitList', () => { { length: 5 }, _ => ({ - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height: height20, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), } as SingleCommit), ); @@ -68,10 +68,10 @@ describe('CommitList', () => { { length: 5 }, _ => ({ - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height: height30, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), } as SingleCommit), ); diff --git a/framework/test/unit/engine/consensus/certificate_generation/commit_pool.spec.ts b/framework/test/unit/engine/consensus/certificate_generation/commit_pool.spec.ts index cf42062866f..d8b6377e5d6 100644 --- a/framework/test/unit/engine/consensus/certificate_generation/commit_pool.spec.ts +++ b/framework/test/unit/engine/consensus/certificate_generation/commit_pool.spec.ts @@ -110,23 +110,23 @@ describe('CommitPool', () => { put: jest.fn(), batch: jest.fn(), }; - const blockID = getRandomBytes(32); + const blockID = utils.getRandomBytes(32); const height = 1020; const maxHeightCertified = 950; const maxHeightPrecommitted = 1000; const numActiveValidators = 103; const staleGossipedCommit = { blockID, - certificateSignature: getRandomBytes(96), + certificateSignature: utils.getRandomBytes(96), height: maxHeightCertified - 1, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), }; const staleNonGossipedCommit = { blockID, - certificateSignature: getRandomBytes(96), + certificateSignature: utils.getRandomBytes(96), height: maxHeightCertified - 1, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), }; let nonGossipedCommits: SingleCommit[]; @@ -135,16 +135,16 @@ describe('CommitPool', () => { beforeEach(() => { nonGossipedCommits = Array.from({ length: 5 }, () => ({ blockID, - certificateSignature: getRandomBytes(96), + certificateSignature: utils.getRandomBytes(96), height, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), })); gossipedCommits = Array.from({ length: 5 }, () => ({ blockID, - certificateSignature: getRandomBytes(96), + certificateSignature: utils.getRandomBytes(96), height, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), })); commitPool = new CommitPool({ @@ -169,7 +169,7 @@ describe('CommitPool', () => { commitPool['_bftAPI'].getBFTHeights = jest.fn().mockResolvedValue({ maxHeightPrecommitted }); commitPool['_bftAPI'].getBFTParameters = jest.fn().mockResolvedValue({ - validators: Array.from({ length: numActiveValidators }, () => getRandomBytes(32)), + validators: Array.from({ length: numActiveValidators }, () => utils.getRandomBytes(32)), }); }); @@ -203,16 +203,16 @@ describe('CommitPool', () => { it('should clean all the commits from nonGossipedCommit that does not have bftParams change', async () => { commitPool['_nonGossipedCommits'].add({ - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height: 1070, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), }); commitPool['_gossipedCommits'].add({ - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height: 1070, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), }); // Assert expect(commitPool['_nonGossipedCommits'].getAll()).toHaveLength(7); @@ -237,11 +237,11 @@ describe('CommitPool', () => { it('should select non gossiped commits that are created by the generator of the engine', async () => { // Arrange - const generatorAddress = getRandomBytes(20); + const generatorAddress = utils.getRandomBytes(20); commitPool.addCommit( { - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height: 1070, validatorAddress: generatorAddress, }, @@ -250,10 +250,10 @@ describe('CommitPool', () => { // Added to nonGossipedCommitsLocal expect(commitPool['_nonGossipedCommitsLocal'].getAll()).toHaveLength(1); commitPool.addCommit({ - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height: 1070, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), }); // Assert expect(commitPool['_gossipedCommits'].getAll()).toHaveLength(6); @@ -323,16 +323,16 @@ describe('CommitPool', () => { Array.from({ length: 105 }, () => ({ blockID, - certificateSignature: getRandomBytes(96), + certificateSignature: utils.getRandomBytes(96), height: commitHeight, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), })).forEach(c => commitPool['_nonGossipedCommits'].add(c)); Array.from({ length: 105 }, () => ({ blockID, - certificateSignature: getRandomBytes(96), + certificateSignature: utils.getRandomBytes(96), height: commitHeight, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), })).forEach(c => commitPool['_gossipedCommits'].add(c)); expect(commitPool['_nonGossipedCommits'].getAll()).toHaveLength(105); @@ -370,15 +370,15 @@ describe('CommitPool', () => { let height: number; beforeEach(() => { - const blockID = getRandomBytes(32); + const blockID = utils.getRandomBytes(32); height = 1031; nonGossipedCommits = Array.from({ length: 1 }, () => ({ blockID, - certificateSignature: getRandomBytes(96), + certificateSignature: utils.getRandomBytes(96), height, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), })); // We add commits by .add() method because properties are readonly @@ -388,8 +388,8 @@ describe('CommitPool', () => { it('should add commit successfully', () => { const newCommit: SingleCommit = { ...nonGossipedCommits[0], - certificateSignature: getRandomBytes(96), - validatorAddress: getRandomBytes(20), + certificateSignature: utils.getRandomBytes(96), + validatorAddress: utils.getRandomBytes(20), }; commitPool.addCommit(newCommit); @@ -415,8 +415,8 @@ describe('CommitPool', () => { const newCommit: SingleCommit = { ...nonGossipedCommits[0], height, - certificateSignature: getRandomBytes(96), - validatorAddress: getRandomBytes(20), + certificateSignature: utils.getRandomBytes(96), + validatorAddress: utils.getRandomBytes(20), }; commitPool.addCommit(newCommit); @@ -448,7 +448,7 @@ describe('CommitPool', () => { blockHeader = createFakeBlockHeader({ height: 1031, timestamp: 10310, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), }); blockHeaderOfFinalizedHeight = createFakeBlockHeader({ @@ -461,7 +461,7 @@ describe('CommitPool', () => { certificate = computeCertificateFromBlockHeader(blockHeader); - privateKey = generatePrivateKey(getRandomBytes(32)); + privateKey = generatePrivateKey(utils.getRandomBytes(32)); publicKey = getPublicKeyFromPrivateKey(privateKey); signature = signCertificate(privateKey, networkIdentifier, certificate); @@ -476,9 +476,9 @@ describe('CommitPool', () => { weights = Array.from({ length: 103 }, _ => 1); validators = weights.map(weight => ({ - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(weight), - blsKey: getRandomBytes(48), + blsKey: utils.getRandomBytes(48), })); // Single commit owner must be an active validator validators[0] = { @@ -521,7 +521,7 @@ describe('CommitPool', () => { it('should return false when single commit block id is not equal to chain block id at same height', async () => { when(chain.dataAccess.getBlockHeaderByHeight) .calledWith(commit.height) - .mockReturnValue(createFakeBlockHeader({ id: getRandomBytes(32) })); + .mockReturnValue(createFakeBlockHeader({ id: utils.getRandomBytes(32) })); const isCommitValid = await commitPool.validateCommit(stateStore, commit); @@ -637,7 +637,7 @@ describe('CommitPool', () => { it('should throw error when generator is not in active validators of the height', async () => { // Change generator to another random validator validators[0] = { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), }; @@ -650,7 +650,7 @@ describe('CommitPool', () => { when(bftAPI.getBFTParameters) .calledWith(stateStore, commit.height) .mockReturnValue({ - validators: [{ address: commit.validatorAddress, blsKey: getRandomBytes(48) }], + validators: [{ address: commit.validatorAddress, blsKey: utils.getRandomBytes(48) }], }); await expect(commitPool.validateCommit(stateStore, commit)).rejects.toThrow( @@ -664,22 +664,22 @@ describe('CommitPool', () => { let height: number; beforeEach(() => { - const blockID = getRandomBytes(32); + const blockID = utils.getRandomBytes(32); height = 1031; nonGossipedCommits = Array.from({ length: 1 }, () => ({ blockID, - certificateSignature: getRandomBytes(96), + certificateSignature: utils.getRandomBytes(96), height, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), })); gossipedCommits = Array.from({ length: 1 }, () => ({ blockID, - certificateSignature: getRandomBytes(96), + certificateSignature: utils.getRandomBytes(96), height, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), })); // We add commits by .set() method because properties are readonly @@ -702,10 +702,10 @@ describe('CommitPool', () => { it('should return just gossiped commits when just gossiped commits set for that height', () => { height = 1032; gossipedCommits = Array.from({ length: 1 }, () => ({ - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), })); commitPool['_gossipedCommits'].add(gossipedCommits[0]); @@ -717,10 +717,10 @@ describe('CommitPool', () => { it('should return just non-gossiped commits when just non-gossiped commits set for that height', () => { height = 1032; nonGossipedCommits = Array.from({ length: 1 }, () => ({ - blockID: getRandomBytes(32), - certificateSignature: getRandomBytes(96), + blockID: utils.getRandomBytes(32), + certificateSignature: utils.getRandomBytes(96), height, - validatorAddress: getRandomBytes(20), + validatorAddress: utils.getRandomBytes(20), })); commitPool['_nonGossipedCommits'].add(nonGossipedCommits[0]); @@ -733,9 +733,9 @@ describe('CommitPool', () => { describe('createSingleCommit', () => { const blockHeader = createFakeBlockHeader(); const validatorInfo = { - address: getRandomBytes(20), - blsPublicKey: getRandomBytes(48), - blsSecretKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + blsPublicKey: utils.getRandomBytes(48), + blsSecretKey: utils.getRandomBytes(32), }; const certificate = computeCertificateFromBlockHeader(blockHeader); let expectedCommit: SingleCommit; @@ -793,7 +793,7 @@ describe('CommitPool', () => { stateStore = new StateStore(new InMemoryDatabase()); - privateKeys = Array.from({ length: 103 }, _ => generatePrivateKey(getRandomBytes(32))); + privateKeys = Array.from({ length: 103 }, _ => generatePrivateKey(utils.getRandomBytes(32))); publicKeys = privateKeys.map(priv => getPublicKeyFromPrivateKey(priv)); keysList = [...publicKeys]; @@ -831,7 +831,7 @@ describe('CommitPool', () => { }; validators = weights.map((weight, i) => ({ - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(weight), blsKey: keysList[i], })); @@ -999,19 +999,19 @@ describe('CommitPool', () => { const blockHeader2 = createFakeBlockHeader({ height }); const blockHeader3 = createFakeBlockHeader({ height }); const validatorInfo1 = { - address: getRandomBytes(20), - blsPublicKey: getRandomBytes(48), - blsSecretKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + blsPublicKey: utils.getRandomBytes(48), + blsSecretKey: utils.getRandomBytes(32), }; const validatorInfo2 = { - address: getRandomBytes(20), - blsPublicKey: getRandomBytes(48), - blsSecretKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + blsPublicKey: utils.getRandomBytes(48), + blsSecretKey: utils.getRandomBytes(32), }; const validatorInfo3 = { - address: getRandomBytes(20), - blsPublicKey: getRandomBytes(48), - blsSecretKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + blsPublicKey: utils.getRandomBytes(48), + blsSecretKey: utils.getRandomBytes(32), }; const certificate1 = computeCertificateFromBlockHeader(blockHeader1); const certificate2 = computeCertificateFromBlockHeader(blockHeader2); @@ -1167,14 +1167,14 @@ describe('CommitPool', () => { const blockHeader1 = createFakeBlockHeader({ height: 1051 }); const blockHeader2 = createFakeBlockHeader({ height: 1052 }); const validatorInfo1 = { - address: getRandomBytes(20), - blsPublicKey: getRandomBytes(48), - blsSecretKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + blsPublicKey: utils.getRandomBytes(48), + blsSecretKey: utils.getRandomBytes(32), }; const validatorInfo2 = { - address: getRandomBytes(20), - blsPublicKey: getRandomBytes(48), - blsSecretKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + blsPublicKey: utils.getRandomBytes(48), + blsSecretKey: utils.getRandomBytes(32), }; const certificate1 = computeCertificateFromBlockHeader(blockHeader1); const certificate2 = computeCertificateFromBlockHeader(blockHeader2); diff --git a/framework/test/unit/engine/consensus/certificate_generation/utils.spec.ts b/framework/test/unit/engine/consensus/certificate_generation/utils.spec.ts index bd58521c010..61f720b8baa 100644 --- a/framework/test/unit/engine/consensus/certificate_generation/utils.spec.ts +++ b/framework/test/unit/engine/consensus/certificate_generation/utils.spec.ts @@ -75,7 +75,7 @@ describe('utils', () => { let signature: Buffer; beforeEach(() => { - privateKey = generatePrivateKey(getRandomBytes(32)); + privateKey = generatePrivateKey(utils.getRandomBytes(32)); certificate = { blockID: Buffer.alloc(0), height: 1000, @@ -90,8 +90,8 @@ describe('utils', () => { encodedCertificate, privateKey, ); - (certificate as any).aggregationBits = getRandomBytes(4); - (certificate as any).signature = getRandomBytes(4); + (certificate as any).aggregationBits = utils.getRandomBytes(4); + (certificate as any).signature = utils.getRandomBytes(4); }); it('should sign certificate', () => { @@ -105,7 +105,7 @@ describe('utils', () => { let signature: Buffer; beforeEach(() => { - privateKey = generatePrivateKey(getRandomBytes(32)); + privateKey = generatePrivateKey(utils.getRandomBytes(32)); publicKey = getPublicKeyFromPrivateKey(privateKey); certificate = { blockID: Buffer.alloc(0), @@ -124,8 +124,8 @@ describe('utils', () => { privateKey, ); - (certificate as any).aggregationBits = getRandomBytes(4); - (certificate as any).signature = getRandomBytes(4); + (certificate as any).aggregationBits = utils.getRandomBytes(4); + (certificate as any).signature = utils.getRandomBytes(4); }); it('should return true with proper parameters', () => { @@ -140,7 +140,7 @@ describe('utils', () => { }); it('should return false for wrong public key', () => { - publicKey = getRandomBytes(48); + publicKey = utils.getRandomBytes(48); const isVerifiedSignature = verifySingleCertificateSignature( publicKey, @@ -153,7 +153,7 @@ describe('utils', () => { }); it('should return false for wrong signature', () => { - signature = getRandomBytes(32); + signature = utils.getRandomBytes(32); const isVerifiedSignature = verifySingleCertificateSignature( publicKey, @@ -178,7 +178,7 @@ describe('utils', () => { let aggregationBits: Buffer; beforeEach(() => { - privateKeys = Array.from({ length: 103 }, _ => generatePrivateKey(getRandomBytes(32))); + privateKeys = Array.from({ length: 103 }, _ => generatePrivateKey(utils.getRandomBytes(32))); publicKeys = privateKeys.map(priv => getPublicKeyFromPrivateKey(priv)); keysList = [...publicKeys]; @@ -226,7 +226,7 @@ describe('utils', () => { }); it('should return false for one unmatching publicKey in keysList', () => { - keysList[102] = getRandomBytes(32); + keysList[102] = utils.getRandomBytes(32); const isVerifiedSignature = verifyAggregateCertificateSignature( keysList, @@ -282,7 +282,7 @@ describe('utils', () => { }); it('should return false for wrong aggregationBits', () => { - (certificate as any).aggregationBits = getRandomBytes(32); + (certificate as any).aggregationBits = utils.getRandomBytes(32); const isVerifiedSignature = verifyAggregateCertificateSignature( keysList, @@ -296,7 +296,7 @@ describe('utils', () => { }); it('should return false for wrong signature', () => { - (certificate as any).signature = getRandomBytes(32); + (certificate as any).signature = utils.getRandomBytes(32); const isVerifiedSignature = verifyAggregateCertificateSignature( keysList, diff --git a/framework/test/unit/engine/consensus/consensus.spec.ts b/framework/test/unit/engine/consensus/consensus.spec.ts index 710e96b6bc9..c334f63300c 100644 --- a/framework/test/unit/engine/consensus/consensus.spec.ts +++ b/framework/test/unit/engine/consensus/consensus.spec.ts @@ -113,11 +113,11 @@ describe('consensus', () => { }), clear: jest.fn(), revert: jest.fn(), - commit: jest.fn().mockResolvedValue({ stateRoot: getRandomBytes(32) }), + commit: jest.fn().mockResolvedValue({ stateRoot: utils.getRandomBytes(32) }), verifyAssets: jest.fn(), verifyTransaction: jest.fn(), executeTransaction: jest.fn().mockResolvedValue({ events: [] }), - initStateMachine: jest.fn().mockResolvedValue({ contextID: getRandomBytes(32) }), + initStateMachine: jest.fn().mockResolvedValue({ contextID: utils.getRandomBytes(32) }), initGenesisState: jest.fn().mockResolvedValue({ events: [], nextValidators: [], @@ -230,7 +230,7 @@ describe('consensus', () => { // Arrange (chain.genesisBlockExist as jest.Mock).mockResolvedValue(false); jest.spyOn(consensus['_bft'].api, 'getBFTParameters').mockResolvedValue({ - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), } as never); await expect( consensus.init({ @@ -756,7 +756,7 @@ describe('consensus', () => { describe('previousBlockID', () => { it('should throw error for invalid previousBlockID', () => { const invalidBlock = { ...block }; - (invalidBlock.header as any).previousBlockID = getRandomBytes(64); + (invalidBlock.header as any).previousBlockID = utils.getRandomBytes(64); expect(() => consensus['_verifyPreviousBlockID'](block as any)).toThrow( `Invalid previousBlockID ${invalidBlock.header.previousBlockID.toString( @@ -775,7 +775,7 @@ describe('consensus', () => { describe('generatorAddress', () => { it('should throw error if [generatorAddress.length !== 20]', async () => { const invalidBlock = { ...block }; - (invalidBlock.header as any).generatorAddress = getRandomBytes(64); + (invalidBlock.header as any).generatorAddress = utils.getRandomBytes(64); await expect( consensus['_verifyGeneratorAddress'](stateStore, invalidBlock as any), ).rejects.toThrow( @@ -789,7 +789,7 @@ describe('consensus', () => { jest.spyOn(consensus, 'getGeneratorAtTimestamp'); when(consensus.getGeneratorAtTimestamp as never) .calledWith(stateStore, block.header.height, (block.header as any).timestamp) - .mockResolvedValue(getRandomBytes(20) as never); + .mockResolvedValue(utils.getRandomBytes(20) as never); await expect( consensus['_verifyGeneratorAddress'](stateStore, block as any), @@ -858,7 +858,7 @@ describe('consensus', () => { describe('signature', () => { it('should throw error for invalid signature', async () => { - const generatorKey = getRandomBytes(32); + const generatorKey = utils.getRandomBytes(32); when(consensus['_bft'].api.getGeneratorKeys as never) .calledWith(stateStore, block.header.height) @@ -878,7 +878,9 @@ describe('consensus', () => { const keyPair = getPrivateAndPublicKeyFromPassphrase(passphrase); const blockHeader = createFakeBlockHeader(); - (blockHeader as any).generatorAddress = getAddressFromPublicKey(keyPair.publicKey); + (blockHeader as any).generatorAddress = address.getAddressFromPublicKey( + keyPair.publicKey, + ); (consensus['_chain'] as any).networkIdentifier = defaultNetworkIdentifier; blockHeader.sign(consensus['_chain'].networkIdentifier, keyPair.privateKey); @@ -901,12 +903,12 @@ describe('consensus', () => { when(consensus['_bft'].api.getBFTParameters as never) .calledWith(stateStore, block.header.height + 1) .mockResolvedValue({ - validatorsHash: hash(getRandomBytes(32)), + validatorsHash: utils.hash(utils.getRandomBytes(32)), } as never); block.header.validatorsHash = undefined; - block.header['_signature'] = getRandomBytes(64); - block.header['_id'] = getRandomBytes(64); + block.header['_signature'] = utils.getRandomBytes(64); + block.header['_id'] = utils.getRandomBytes(64); await expect( consensus['_verifyValidatorsHash'](stateStore, block as any), @@ -921,7 +923,7 @@ describe('consensus', () => { when(consensus['_bft'].api.getBFTParameters as never) .calledWith(stateStore, block.header.height + 1) .mockResolvedValue({ - validatorsHash: hash(getRandomBytes(32)), + validatorsHash: utils.hash(utils.getRandomBytes(32)), } as never); await expect( @@ -987,7 +989,7 @@ describe('consensus', () => { await expect( consensus['_verifyEventRoot'](block as any, [ new Event({ - data: getRandomBytes(20), + data: utils.getRandomBytes(20), index: 0, moduleID: Buffer.from([0, 0, 0, 2]), topics: [Buffer.from([0])], @@ -1000,7 +1002,7 @@ describe('consensus', () => { }); it('should be success when eventRoot is equal to blocks eventRoot', async () => { - block.header.eventRoot = hash(Buffer.alloc(0)); + block.header.eventRoot = utils.hash(Buffer.alloc(0)); await expect(consensus['_verifyEventRoot'](block as any, [])).resolves.toBeUndefined(); }); }); diff --git a/framework/test/unit/engine/consensus/network_endpoint.spec.ts b/framework/test/unit/engine/consensus/network_endpoint.spec.ts index 9beaf6cc56e..d047b736867 100644 --- a/framework/test/unit/engine/consensus/network_endpoint.spec.ts +++ b/framework/test/unit/engine/consensus/network_endpoint.spec.ts @@ -107,7 +107,7 @@ describe('p2p endpoint', () => { it('should apply penalty if call exceeds rate limit', () => { // Arrange const blockIds = codec.encode(getBlocksFromIdRequestSchema, { - blockId: getRandomBytes(32), + blockId: utils.getRandomBytes(32), }); // Act [...new Array(DEFAULT_BLOCKS_FROM_IDS_RATE_LIMIT_FREQUENCY + 1)].map(async () => @@ -138,7 +138,7 @@ describe('p2p endpoint', () => { it('should apply penalty on the peer if request format is invalid', async () => { // Arrange const blockIds = codec.encode(getBlocksFromIdRequestSchema, { - blockId: getRandomBytes(1), + blockId: utils.getRandomBytes(1), }); // Act await expect(endpoint.handleRPCGetBlocksFromId(blockIds, defaultPeerId)).rejects.toThrow(); @@ -152,7 +152,7 @@ describe('p2p endpoint', () => { it('should return blocks from next height', async () => { // Arrange - const id = getRandomBytes(32); + const id = utils.getRandomBytes(32); const blockIds = codec.encode(getBlocksFromIdRequestSchema, { blockId: id, }); @@ -169,7 +169,7 @@ describe('p2p endpoint', () => { it('should apply penalty if call exceeds rate limit', () => { const blockIds = codec.encode(getHighestCommonBlockRequestSchema, { - ids: [getRandomBytes(32)], + ids: [utils.getRandomBytes(32)], }); [...new Array(DEFAULT_COMMON_BLOCK_RATE_LIMIT_FREQUENCY + 1)].map(async () => endpoint.handleRPCGetHighestCommonBlock(blockIds, defaultPeerId), @@ -190,7 +190,7 @@ describe('p2p endpoint', () => { it('should return null', async () => { // Arrange - const ids = [getRandomBytes(32)]; + const ids = [utils.getRandomBytes(32)]; const blockIds = codec.encode(getHighestCommonBlockRequestSchema, { ids }); // Act @@ -236,9 +236,9 @@ describe('p2p endpoint', () => { const blockHeader = createFakeBlockHeader(); const certificate = computeCertificateFromBlockHeader(blockHeader); const validatorInfo = { - address: getRandomBytes(20), - blsPublicKey: getRandomBytes(48), - blsSecretKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + blsPublicKey: utils.getRandomBytes(48), + blsSecretKey: utils.getRandomBytes(32), }; let validCommit: { singleCommit: SingleCommit }; let encodedValidCommit: Buffer; @@ -282,7 +282,7 @@ describe('p2p endpoint', () => { it('should apply penalty when invalid data value is received', async () => { const invalidCommit = { - singleCommit: { ...validCommit, certificateSignature: getRandomBytes(2) }, + singleCommit: { ...validCommit, certificateSignature: utils.getRandomBytes(2) }, }; const encodedInvalidCommit = codec.encode(getSingleCommitEventSchema, invalidCommit); await expect( diff --git a/framework/test/unit/engine/consensus/synchronizer/block_synchronization_mechanism/block_synchronization_mechanism.spec.ts b/framework/test/unit/engine/consensus/synchronizer/block_synchronization_mechanism/block_synchronization_mechanism.spec.ts index 901392b2d15..195df1395b5 100644 --- a/framework/test/unit/engine/consensus/synchronizer/block_synchronization_mechanism/block_synchronization_mechanism.spec.ts +++ b/framework/test/unit/engine/consensus/synchronizer/block_synchronization_mechanism/block_synchronization_mechanism.spec.ts @@ -120,7 +120,7 @@ describe('block_synchronization_mechanism', () => { getSlotNumber: jest.fn().mockImplementation(t => Math.floor(t / 10)), getCurrentValidators: jest.fn().mockResolvedValue( new Array(numberOfValidators).fill(0).map(() => ({ - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), })), ), diff --git a/framework/test/unit/engine/consensus/synchronizer/fast_chain_switching_mechanism/fast_chain_switching_mechanism.spec.ts b/framework/test/unit/engine/consensus/synchronizer/fast_chain_switching_mechanism/fast_chain_switching_mechanism.spec.ts index 20483439f3d..58b510c863f 100644 --- a/framework/test/unit/engine/consensus/synchronizer/fast_chain_switching_mechanism/fast_chain_switching_mechanism.spec.ts +++ b/framework/test/unit/engine/consensus/synchronizer/fast_chain_switching_mechanism/fast_chain_switching_mechanism.spec.ts @@ -94,7 +94,7 @@ describe('fast_chain_switching_mechanism', () => { getSlotNumber: jest.fn(), getCurrentValidators: jest.fn().mockResolvedValue( new Array(numberOfValidators).fill(0).map(() => ({ - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), })), ), @@ -125,18 +125,18 @@ describe('fast_chain_switching_mechanism', () => { it('should return true when the receivedBlock is from consensus participant', async () => { blockExecutor.getCurrentValidators.mockResolvedValue([ { - address: getAddressFromPublicKey(defaultGenerator.publicKey), + address: address.getAddressFromPublicKey(defaultGenerator.publicKey), bftWeight: BigInt(1), }, ...new Array(102).fill(0).map(() => ({ - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), })), ]); const isValid = await fastChainSwitchingMechanism.isValidFor( { header: { - generatorAddress: getAddressFromPublicKey(defaultGenerator.publicKey), + generatorAddress: address.getAddressFromPublicKey(defaultGenerator.publicKey), height: 515, }, } as Block, @@ -148,14 +148,14 @@ describe('fast_chain_switching_mechanism', () => { it('should return true when the receivedBlock is not from consensus participant', async () => { blockExecutor.getCurrentValidators.mockResolvedValue([ { - address: getAddressFromPublicKey(defaultGenerator.publicKey), + address: address.getAddressFromPublicKey(defaultGenerator.publicKey), voteWeight: BigInt(0), }, ]); const isValid = await fastChainSwitchingMechanism.isValidFor( { header: { - generatorAddress: getAddressFromPublicKey(defaultGenerator.publicKey), + generatorAddress: address.getAddressFromPublicKey(defaultGenerator.publicKey), height: 515, }, } as Block, @@ -166,12 +166,12 @@ describe('fast_chain_switching_mechanism', () => { it('should return true when the receivedBlock is not current validator', async () => { blockExecutor.getCurrentValidators.mockResolvedValue([ - { address: getRandomBytes(20), isConsensusParticipant: false }, + { address: utils.getRandomBytes(20), isConsensusParticipant: false }, ]); const isValid = await fastChainSwitchingMechanism.isValidFor( { header: { - generatorAddress: getAddressFromPublicKey(defaultGenerator.publicKey), + generatorAddress: address.getAddressFromPublicKey(defaultGenerator.publicKey), height: 515, }, } as Block, @@ -185,14 +185,14 @@ describe('fast_chain_switching_mechanism', () => { it('should return false even when the block is from consensus participant', async () => { blockExecutor.getCurrentValidators.mockResolvedValue([ { - address: getAddressFromPublicKey(defaultGenerator.publicKey), + address: address.getAddressFromPublicKey(defaultGenerator.publicKey), bftWeight: BigInt(1), }, ]); const isValid = await fastChainSwitchingMechanism.isValidFor( { header: { - generatorAddress: getAddressFromPublicKey(defaultGenerator.publicKey), + generatorAddress: address.getAddressFromPublicKey(defaultGenerator.publicKey), height: 619, }, } as Block, @@ -227,7 +227,7 @@ describe('fast_chain_switching_mechanism', () => { bftWeight: BigInt(1), }, ...new Array(numberOfValidators - 1).fill(0).map(() => ({ - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), })), ]); diff --git a/framework/test/unit/engine/endpoint/chain.spec.ts b/framework/test/unit/engine/endpoint/chain.spec.ts index 23bbb39c132..5d016f2076a 100644 --- a/framework/test/unit/engine/endpoint/chain.spec.ts +++ b/framework/test/unit/engine/endpoint/chain.spec.ts @@ -39,16 +39,16 @@ describe('Chain endpoint', () => { new Event({ index: 0, moduleID: Buffer.from([0, 0, 0, 2]), - topics: [getRandomBytes(32)], + topics: [utils.getRandomBytes(32)], typeID: Buffer.from([0, 0, 0, 1]), - data: getRandomBytes(32), + data: utils.getRandomBytes(32), }), new Event({ index: 1, moduleID: Buffer.from([0, 0, 0, 2]), - topics: [getRandomBytes(32)], + topics: [utils.getRandomBytes(32)], typeID: Buffer.from([0, 0, 0, 1]), - data: getRandomBytes(32), + data: utils.getRandomBytes(32), }), ]); }); @@ -84,16 +84,16 @@ describe('Chain endpoint', () => { new Event({ index: 0, moduleID: Buffer.from([0, 0, 0, 2]), - topics: [getRandomBytes(32)], + topics: [utils.getRandomBytes(32)], typeID: Buffer.from([0, 0, 0, 1]), - data: getRandomBytes(32), + data: utils.getRandomBytes(32), }), new Event({ index: 1, moduleID: Buffer.from([0, 0, 0, 2]), - topics: [getRandomBytes(32)], + topics: [utils.getRandomBytes(32)], typeID: Buffer.from([0, 0, 0, 1]), - data: getRandomBytes(32), + data: utils.getRandomBytes(32), }), ]); }); diff --git a/framework/test/unit/engine/endpoint/system.spec.ts b/framework/test/unit/engine/endpoint/system.spec.ts index 7febb9df8e6..81446021370 100644 --- a/framework/test/unit/engine/endpoint/system.spec.ts +++ b/framework/test/unit/engine/endpoint/system.spec.ts @@ -25,7 +25,7 @@ describe('system endpoint', () => { beforeEach(() => { endpoint = new SystemEndpoint({ chain: { - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), lastBlock: new Block(createFakeBlockHeader(), [], new BlockAssets()), }, consensus: { diff --git a/framework/test/unit/engine/endpoint/txpool.spec.ts b/framework/test/unit/engine/endpoint/txpool.spec.ts index 2311f79f42a..5f068a9cba1 100644 --- a/framework/test/unit/engine/endpoint/txpool.spec.ts +++ b/framework/test/unit/engine/endpoint/txpool.spec.ts @@ -29,9 +29,9 @@ describe('generator endpoint', () => { const logger: Logger = fakeLogger; const tx = new Transaction({ params: Buffer.alloc(20), - commandID: intToBuffer(0, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(100000), - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), nonce: BigInt(0), senderPublicKey: Buffer.alloc(32), signatures: [Buffer.alloc(64)], @@ -39,7 +39,7 @@ describe('generator endpoint', () => { const networkIdentifier = Buffer.alloc(0); const events = [ { - data: getRandomBytes(32), + data: utils.getRandomBytes(32), index: 0, moduleID: Buffer.from([0, 0, 0, 3]), topics: [Buffer.from([0])], diff --git a/framework/test/unit/engine/generator/broadcaster.spec.ts b/framework/test/unit/engine/generator/broadcaster.spec.ts index f98a5d22dae..4c1757d865f 100644 --- a/framework/test/unit/engine/generator/broadcaster.spec.ts +++ b/framework/test/unit/engine/generator/broadcaster.spec.ts @@ -27,9 +27,9 @@ describe('broadcaster', () => { const defaultReleaseLimit = 25; const tx = new Transaction({ params: Buffer.alloc(20), - commandID: intToBuffer(0, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(100000), - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), nonce: BigInt(0), senderPublicKey: Buffer.alloc(32), signatures: [Buffer.alloc(64)], @@ -120,7 +120,7 @@ describe('broadcaster', () => { // Arrange // Act for (let i = 0; i < 25; i += 1) { - broadcaster.enqueueTransactionId(getRandomBytes(32)); + broadcaster.enqueueTransactionId(utils.getRandomBytes(32)); } // Assert @@ -131,7 +131,7 @@ describe('broadcaster', () => { // Arrange const ids = []; for (let i = 0; i < 25; i += 1) { - ids.push(getRandomBytes(32)); + ids.push(utils.getRandomBytes(32)); } const transactionIdsBuffer = codec.encode(postTransactionsAnnouncementSchema, { transactionIds: ids, @@ -157,7 +157,7 @@ describe('broadcaster', () => { // Arrange const ids = []; for (let i = 0; i < 50; i += 1) { - ids.push(getRandomBytes(32)); + ids.push(utils.getRandomBytes(32)); } // Act @@ -173,7 +173,7 @@ describe('broadcaster', () => { // Arrange const ids = []; for (let i = 0; i < 50; i += 1) { - ids.push(getRandomBytes(32)); + ids.push(utils.getRandomBytes(32)); } const transactionIdsBuffer = codec.encode(postTransactionsAnnouncementSchema, { transactionIds: ids.slice(0, defaultReleaseLimit), diff --git a/framework/test/unit/engine/generator/endpoint.spec.ts b/framework/test/unit/engine/generator/endpoint.spec.ts index fbe39d8c5fb..c643939bae9 100644 --- a/framework/test/unit/engine/generator/endpoint.spec.ts +++ b/framework/test/unit/engine/generator/endpoint.spec.ts @@ -89,7 +89,7 @@ describe('generator endpoint', () => { endpoint.updateStatus({ logger, params: { - address: getRandomBytes(20).toString('hex'), + address: utils.getRandomBytes(20).toString('hex'), enable: true, password: defaultPassword, overwrite: true, diff --git a/framework/test/unit/engine/generator/generator.spec.ts b/framework/test/unit/engine/generator/generator.spec.ts index 4d8ff418df9..19e1edb728b 100644 --- a/framework/test/unit/engine/generator/generator.spec.ts +++ b/framework/test/unit/engine/generator/generator.spec.ts @@ -48,7 +48,7 @@ describe('generator', () => { 'c24ec443a9e0f18f67275dea31fa3083292e249db7347ac62958ff3ba9ab9b9b', 'hex', ), - address: getAddressFromPublicKey( + address: address.getAddressFromPublicKey( Buffer.from('c24ec443a9e0f18f67275dea31fa3083292e249db7347ac62958ff3ba9ab9b9b', 'hex'), ), encryptedPassphrase: @@ -59,7 +59,7 @@ describe('generator', () => { 'e2ab259cabe2b00f4f3760f3cdd989e09c2abb828150ddd2a30f004634c6d825', 'hex', ), - address: getAddressFromPublicKey( + address: address.getAddressFromPublicKey( Buffer.from('e2ab259cabe2b00f4f3760f3cdd989e09c2abb828150ddd2a30f004634c6d825', 'hex'), ), encryptedPassphrase: @@ -70,7 +70,7 @@ describe('generator', () => { 'fc1fa2e4f57f9e6d142328b12f17fd5739e44c07e4026bfb41dd877912511fa3', 'hex', ), - address: getAddressFromPublicKey( + address: address.getAddressFromPublicKey( Buffer.from('fc1fa2e4f57f9e6d142328b12f17fd5739e44c07e4026bfb41dd877912511fa3', 'hex'), ), encryptedPassphrase: @@ -81,9 +81,9 @@ describe('generator', () => { '0805100118012080ade2042a20f7e7627120dab14b80b6e4f361ba89db251ee838708c3a74c6c2cc08ad793f58321d0a1b0a1432fc1c23b73db1c6205327b1cab44318e61678ea1080dac4093a40a0be9e52d9e0a53406c55a74ab0d7d106eb276a47dd88d3dc2284ed62024b2448e0bd5af1623ae7d793606a58c27d742e8855ba339f757d56972c4c6efad750c'; const tx = new Transaction({ params: Buffer.alloc(20), - commandID: intToBuffer(0, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(100000000), - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), nonce: BigInt(0), senderPublicKey: Buffer.alloc(32), signatures: [Buffer.alloc(64)], @@ -103,7 +103,7 @@ describe('generator', () => { blockchainDB = new InMemoryDatabase() as never; generatorDB = new InMemoryDatabase() as never; chain = { - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), lastBlock: { header: { id: Buffer.from('6846255774763267134'), @@ -157,10 +157,10 @@ describe('generator', () => { certificateThreshold: 0, }), clear: jest.fn(), - commit: jest.fn().mockResolvedValue({ stateRoot: getRandomBytes(32) }), + commit: jest.fn().mockResolvedValue({ stateRoot: utils.getRandomBytes(32) }), verifyTransaction: jest.fn(), executeTransaction: jest.fn().mockResolvedValue({ events: [] }), - initStateMachine: jest.fn().mockResolvedValue({ contextID: getRandomBytes(32) }), + initStateMachine: jest.fn().mockResolvedValue({ contextID: utils.getRandomBytes(32) }), insertAssets: jest.fn().mockResolvedValue({ assets: [] }), } as never; bft = { @@ -205,7 +205,7 @@ describe('generator', () => { beforeEach(() => { accountDetails = { - address: getAddressFromPublicKey( + address: address.getAddressFromPublicKey( Buffer.from('75e99d6f2359ebaba661d0651c04f3d9cb8cd405d452e30af9f5d10e1cf732ed'), ), encryptedPassphrase: @@ -443,7 +443,7 @@ describe('generator', () => { (consensus.getSlotNumber as jest.Mock) .mockReturnValueOnce(currentSlot) .mockReturnValueOnce(lastBlockSlot); - (consensus.getGeneratorAtTimestamp as jest.Mock).mockResolvedValue(getRandomBytes(20)); + (consensus.getGeneratorAtTimestamp as jest.Mock).mockResolvedValue(utils.getRandomBytes(20)); jest.spyOn(generator, '_generateBlock' as never); await generator['_generateLoop'](); @@ -499,17 +499,17 @@ describe('generator', () => { }); describe('generateBlock', () => { - const generatorAddress = getRandomBytes(20); + const generatorAddress = utils.getRandomBytes(20); const keypair = { - publicKey: getRandomBytes(32), - privateKey: getRandomBytes(64), + publicKey: utils.getRandomBytes(32), + privateKey: utils.getRandomBytes(64), }; const currentTime = Math.floor(Date.now() / 1000); - const validatorsHash = hash(getRandomBytes(32)); - const assetHash = hash(getRandomBytes(32)); + const validatorsHash = utils.hash(utils.getRandomBytes(32)); + const assetHash = utils.hash(utils.getRandomBytes(32)); const aggregateCommit = { aggregationBits: Buffer.alloc(0), - certificateSignature: getRandomBytes(96), + certificateSignature: utils.getRandomBytes(96), height: 3456, }; @@ -600,7 +600,7 @@ describe('generator', () => { jest.spyOn(abi, 'beforeTransactionsExecute').mockResolvedValue({ events: [ { - data: getRandomBytes(32), + data: utils.getRandomBytes(32), index: 0, moduleID: Buffer.from([0, 0, 0, 3]), topics: [Buffer.from([0])], diff --git a/framework/test/unit/engine/generator/network_endpoint.spec.ts b/framework/test/unit/engine/generator/network_endpoint.spec.ts index 674ccff7b95..084f3dcb7f0 100644 --- a/framework/test/unit/engine/generator/network_endpoint.spec.ts +++ b/framework/test/unit/engine/generator/network_endpoint.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Chain, Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; import { TransactionPool } from '@liskhq/lisk-transaction-pool'; @@ -34,18 +34,18 @@ describe('generator network endpoint', () => { const logger: Logger = fakeLogger; const tx = new Transaction({ params: Buffer.alloc(20), - commandID: intToBuffer(0, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(100000), - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), nonce: BigInt(0), senderPublicKey: Buffer.alloc(32), signatures: [Buffer.alloc(64)], }); const tx2 = new Transaction({ params: Buffer.alloc(20), - commandID: intToBuffer(1, 4), + commandID: utils.intToBuffer(1, 4), fee: BigInt(200000), - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), nonce: BigInt(0), senderPublicKey: Buffer.alloc(32), signatures: [Buffer.alloc(64)], diff --git a/framework/test/unit/engine/generator/strategies.spec.ts b/framework/test/unit/engine/generator/strategies.spec.ts index 904e2846247..b972ac3fc15 100644 --- a/framework/test/unit/engine/generator/strategies.spec.ts +++ b/framework/test/unit/engine/generator/strategies.spec.ts @@ -73,7 +73,7 @@ const buildProcessableTxMock = (input: any, abi: ABI) => { return getTxMock(tx, abi); }) .reduce((res: any, tx: any) => { - const senderId = getAddressFromPublicKey(tx.senderPublicKey); + const senderId = address.getAddressFromPublicKey(tx.senderPublicKey); let txs = res.get(senderId); if (!txs) { txs = []; @@ -98,7 +98,7 @@ describe('strategies', () => { const mockTxPool = { getProcessableTransactions: jest.fn().mockReturnValue(new dataStructures.BufferMap()), } as any; - const contextID = getRandomBytes(32); + const contextID = utils.getRandomBytes(32); const consensus = { currentValidators: [], implyMaxPrevote: true, @@ -118,12 +118,12 @@ describe('strategies', () => { previousBlockID: Buffer.from('id'), maxHeightGenerated: 0, maxHeightPrevoted: 0, - assetRoot: hash(Buffer.alloc(0)), - transactionRoot: hash(Buffer.alloc(0)), - eventRoot: hash(Buffer.alloc(0)), - validatorsHash: hash(Buffer.alloc(0)), + assetRoot: utils.hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), + eventRoot: utils.hash(Buffer.alloc(0)), + validatorsHash: utils.hash(Buffer.alloc(0)), signature: Buffer.alloc(0), - stateRoot: hash(Buffer.alloc(0)), + stateRoot: utils.hash(Buffer.alloc(0)), aggregateCommit: { aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), diff --git a/framework/test/unit/engine/network/network.spec.ts b/framework/test/unit/engine/network/network.spec.ts index d23ce3349c2..c23580008fa 100644 --- a/framework/test/unit/engine/network/network.spec.ts +++ b/framework/test/unit/engine/network/network.spec.ts @@ -35,7 +35,7 @@ describe('network', () => { }); await network.init({ logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), nodeDB: db as never, }); }); @@ -190,7 +190,7 @@ describe('network', () => { const parseSpy = jest.spyOn(JSON, 'parse'); await network.init({ logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), nodeDB: db as never, }); await network.start(); diff --git a/framework/test/unit/modules/auth/api.spec.ts b/framework/test/unit/modules/auth/api.spec.ts index 0d3cfd665a7..aeb6f374035 100644 --- a/framework/test/unit/modules/auth/api.spec.ts +++ b/framework/test/unit/modules/auth/api.spec.ts @@ -28,8 +28,8 @@ describe('AuthAPI', () => { const expectedAuthData = { nonce: 1, numberOfSignatures: 1, - mandatoryKeys: [getRandomBytes(64), getRandomBytes(64)], - optionalKeys: [getRandomBytes(64), getRandomBytes(64)], + mandatoryKeys: [utils.getRandomBytes(64), utils.getRandomBytes(64)], + optionalKeys: [utils.getRandomBytes(64), utils.getRandomBytes(64)], }; beforeEach(async () => { @@ -50,7 +50,7 @@ describe('AuthAPI', () => { }); it('should return empty object given address not in db', async () => { - const authData = await authAPI.getAuthAccount(context, getRandomBytes(20)); + const authData = await authAPI.getAuthAccount(context, utils.getRandomBytes(20)); expect(authData).toHaveProperty('nonce', BigInt(0)); expect(authData).toHaveProperty('numberOfSignatures', 0); diff --git a/framework/test/unit/modules/auth/auth_module.spec.ts b/framework/test/unit/modules/auth/auth_module.spec.ts index 2dd4dd78a76..904abbb655f 100644 --- a/framework/test/unit/modules/auth/auth_module.spec.ts +++ b/framework/test/unit/modules/auth/auth_module.spec.ts @@ -56,7 +56,7 @@ describe('AuthModule', () => { beforeEach(() => { authModule = new AuthModule(); const buffer = Buffer.from(defaultTestCase.output.transaction, 'hex'); - const id = hash(buffer); + const id = utils.hash(buffer); decodedBaseTransaction = codec.decode(transactionSchema, buffer); decodedMultiSignature = { @@ -85,7 +85,7 @@ describe('AuthModule', () => { passphrase = Mnemonic.generateMnemonic(); passphraseDerivedKeys = getPrivateAndPublicKeyFromPassphrase(passphrase); - const address = getAddressFromPublicKey(passphraseDerivedKeys.publicKey); + const address = address.getAddressFromPublicKey(passphraseDerivedKeys.publicKey); when(subStoreMock) .calledWith(address, authAccountSchema) @@ -98,8 +98,8 @@ describe('AuthModule', () => { }); describe('initGenesisState', () => { - const address = getRandomBytes(20); - const publicKey = getRandomBytes(32); + const address = utils.getRandomBytes(20); + const publicKey = utils.getRandomBytes(32); const validAsset = { authDataSubstore: [ { @@ -112,11 +112,15 @@ describe('AuthModule', () => { }, }, { - storeKey: getRandomBytes(20), + storeKey: utils.getRandomBytes(20), storeValue: { numberOfSignatures: 3, - mandatoryKeys: [getRandomBytes(32), getRandomBytes(32)].sort((a, b) => a.compare(b)), - optionalKeys: [getRandomBytes(32), getRandomBytes(32)].sort((a, b) => a.compare(b)), + mandatoryKeys: [utils.getRandomBytes(32), utils.getRandomBytes(32)].sort((a, b) => + a.compare(b), + ), + optionalKeys: [utils.getRandomBytes(32), utils.getRandomBytes(32)].sort((a, b) => + a.compare(b), + ), nonce: BigInt(1), }, }, @@ -128,7 +132,7 @@ describe('AuthModule', () => { { authDataSubstore: [ { - storeKey: getRandomBytes(8), + storeKey: utils.getRandomBytes(8), storeValue: { numberOfSignatures: 0, mandatoryKeys: [], @@ -144,10 +148,10 @@ describe('AuthModule', () => { { authDataSubstore: [ { - storeKey: getRandomBytes(20), + storeKey: utils.getRandomBytes(20), storeValue: { numberOfSignatures: 3, - mandatoryKeys: [getRandomBytes(32), getRandomBytes(32)].sort((a, b) => + mandatoryKeys: [utils.getRandomBytes(32), utils.getRandomBytes(32)].sort((a, b) => b.compare(a), ), optionalKeys: [], @@ -162,7 +166,7 @@ describe('AuthModule', () => { { authDataSubstore: [ { - storeKey: getRandomBytes(20), + storeKey: utils.getRandomBytes(20), storeValue: { numberOfSignatures: 2, mandatoryKeys: [publicKey, publicKey], @@ -178,11 +182,13 @@ describe('AuthModule', () => { { authDataSubstore: [ { - storeKey: getRandomBytes(20), + storeKey: utils.getRandomBytes(20), storeValue: { numberOfSignatures: 3, mandatoryKeys: [], - optionalKeys: [getRandomBytes(32), getRandomBytes(32)].sort((a, b) => b.compare(a)), + optionalKeys: [utils.getRandomBytes(32), utils.getRandomBytes(32)].sort((a, b) => + b.compare(a), + ), nonce: BigInt(1), }, }, @@ -194,7 +200,7 @@ describe('AuthModule', () => { { authDataSubstore: [ { - storeKey: getRandomBytes(20), + storeKey: utils.getRandomBytes(20), storeValue: { numberOfSignatures: 2, mandatoryKeys: [], @@ -210,15 +216,15 @@ describe('AuthModule', () => { { authDataSubstore: [ { - storeKey: getRandomBytes(20), + storeKey: utils.getRandomBytes(20), storeValue: { numberOfSignatures: 36, - mandatoryKeys: Array.from({ length: 33 }, () => getRandomBytes(32)).sort((a, b) => - b.compare(a), - ), - optionalKeys: Array.from({ length: 33 }, () => getRandomBytes(32)).sort((a, b) => - b.compare(a), - ), + mandatoryKeys: Array.from({ length: 33 }, () => + utils.getRandomBytes(32), + ).sort((a, b) => b.compare(a)), + optionalKeys: Array.from({ length: 33 }, () => + utils.getRandomBytes(32), + ).sort((a, b) => b.compare(a)), nonce: BigInt(1), }, }, @@ -230,11 +236,13 @@ describe('AuthModule', () => { { authDataSubstore: [ { - storeKey: getRandomBytes(20), + storeKey: utils.getRandomBytes(20), storeValue: { numberOfSignatures: 3, mandatoryKeys: [], - optionalKeys: [getRandomBytes(32), getRandomBytes(32)].sort((a, b) => b.compare(a)), + optionalKeys: [utils.getRandomBytes(32), utils.getRandomBytes(32)].sort((a, b) => + b.compare(a), + ), nonce: BigInt(1), }, }, @@ -246,10 +254,10 @@ describe('AuthModule', () => { { authDataSubstore: [ { - storeKey: getRandomBytes(20), + storeKey: utils.getRandomBytes(20), storeValue: { numberOfSignatures: 1, - mandatoryKeys: [getRandomBytes(32), getRandomBytes(32)].sort((a, b) => + mandatoryKeys: [utils.getRandomBytes(32), utils.getRandomBytes(32)].sort((a, b) => b.compare(a), ), optionalKeys: [], @@ -339,12 +347,12 @@ describe('AuthModule', () => { it('should return PENDING status with no error when trx nonce is higher than account nonce', async () => { // Arrange const transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('2'), fee: BigInt('100000000'), senderPublicKey: passphraseDerivedKeys.publicKey, - params: getRandomBytes(100), + params: utils.getRandomBytes(100), signatures: [], }); @@ -396,12 +404,12 @@ describe('AuthModule', () => { it('should not throw for valid transaction', async () => { // Arrange const transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('0'), fee: BigInt('100000000'), senderPublicKey: passphraseDerivedKeys.publicKey, - params: getRandomBytes(100), + params: utils.getRandomBytes(100), signatures: [], }); @@ -431,12 +439,12 @@ describe('AuthModule', () => { it('should throw if signature is missing', async () => { // Arrange const transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('0'), fee: BigInt('100000000'), senderPublicKey: passphraseDerivedKeys.publicKey, - params: getRandomBytes(100), + params: utils.getRandomBytes(100), signatures: [], }); @@ -459,12 +467,12 @@ describe('AuthModule', () => { it('should throw error if account is not multi signature and more than one signature present', async () => { // Arrange const transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('0'), fee: BigInt('100000000'), senderPublicKey: passphraseDerivedKeys.publicKey, - params: getRandomBytes(100), + params: utils.getRandomBytes(100), signatures: [], }); @@ -532,7 +540,7 @@ describe('AuthModule', () => { for (const aMember of Object.values(members)) { aMember.keys = { ...getPrivateAndPublicKeyFromPassphrase(aMember.passphrase) }; - aMember.address = getAddressFromPublicKey(aMember.keys.publicKey); + aMember.address = address.getAddressFromPublicKey(aMember.keys.publicKey); } const multisigAccount = { @@ -555,12 +563,12 @@ describe('AuthModule', () => { }); transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('0'), fee: BigInt('100000000'), senderPublicKey: (members as any).mainAccount.keys.publicKey, - params: getRandomBytes(100), + params: utils.getRandomBytes(100), signatures: [], }); }); @@ -1127,12 +1135,12 @@ describe('AuthModule', () => { it('should correctly increment the nonce', async () => { const stateStore1 = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); const authStore1 = stateStore1.getStore(authModule.id, STORE_PREFIX_AUTH); - const address = getAddressFromPublicKey(validTestTransaction.senderPublicKey); + const address = address.getAddressFromPublicKey(validTestTransaction.senderPublicKey); const authAccount1 = { nonce: validTestTransaction.nonce, numberOfSignatures: 5, - mandatoryKeys: [getRandomBytes(64), getRandomBytes(64)], - optionalKeys: [getRandomBytes(64), getRandomBytes(64)], + mandatoryKeys: [utils.getRandomBytes(64), utils.getRandomBytes(64)], + optionalKeys: [utils.getRandomBytes(64), utils.getRandomBytes(64)], }; await authStore1.setWithSchema(address, authAccount1, authAccountSchema); diff --git a/framework/test/unit/modules/auth/endpoint.spec.ts b/framework/test/unit/modules/auth/endpoint.spec.ts index 772401ab378..2131dd09065 100644 --- a/framework/test/unit/modules/auth/endpoint.spec.ts +++ b/framework/test/unit/modules/auth/endpoint.spec.ts @@ -63,10 +63,10 @@ describe('AuthEndpoint', () => { // Existing is an abbr. for existing account const existingSenderPublicKey = accounts.targetAccount.publicKey as Buffer; - const nonExistingSenderPublicKey = getRandomBytes(32); + const nonExistingSenderPublicKey = utils.getRandomBytes(32); const existingAddress = accounts.targetAccount.address as Buffer; - const nonExistingAddress = getAddressFromPublicKey(nonExistingSenderPublicKey); + const nonExistingAddress = address.getAddressFromPublicKey(nonExistingSenderPublicKey); const existingPassphrase = accounts.targetAccount.passphrase; @@ -88,8 +88,8 @@ describe('AuthEndpoint', () => { }); const expectedAuthAccount = { - mandatoryKeys: [getRandomBytes(64)], - optionalKeys: [getRandomBytes(64)], + mandatoryKeys: [utils.getRandomBytes(64)], + optionalKeys: [utils.getRandomBytes(64)], nonce: BigInt(2), numberOfSignatures: 1, }; @@ -151,12 +151,12 @@ describe('AuthEndpoint', () => { it('should verify the transaction with single signature', async () => { // Arrange const transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('0'), fee: BigInt('100000000'), senderPublicKey: existingSenderPublicKey, - params: getRandomBytes(100), + params: utils.getRandomBytes(100), signatures: [], }); @@ -197,12 +197,12 @@ describe('AuthEndpoint', () => { it('should verify the transaction with multi-signature', async () => { // Arrange const transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('0'), fee: BigInt('100000000'), senderPublicKey: existingSenderPublicKey, - params: getRandomBytes(100), + params: utils.getRandomBytes(100), signatures: [], }); @@ -268,8 +268,8 @@ describe('AuthEndpoint', () => { }); const transaction = new Transaction({ - moduleID: intToBuffer(12, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(12, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('0'), fee: BigInt('100000000'), senderPublicKey: existingSenderPublicKey, @@ -352,13 +352,13 @@ describe('AuthEndpoint', () => { it('should verify equal transaction nonce and account nonce', async () => { // Arrange const transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('2'), fee: BigInt('100000000'), senderPublicKey: existingSenderPublicKey, - params: getRandomBytes(100), - signatures: [getRandomBytes(64)], + params: utils.getRandomBytes(100), + signatures: [utils.getRandomBytes(64)], }); const transactionAsString = transaction.getBytes().toString('hex'); @@ -387,13 +387,13 @@ describe('AuthEndpoint', () => { it('should fail to verify greater transaction nonce than account nonce', async () => { // Arrange const transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('3'), fee: BigInt('100000000'), senderPublicKey: existingSenderPublicKey, - params: getRandomBytes(100), - signatures: [getRandomBytes(64)], + params: utils.getRandomBytes(100), + signatures: [utils.getRandomBytes(64)], }); const transactionAsString = transaction.getBytes().toString('hex'); @@ -424,13 +424,13 @@ describe('AuthEndpoint', () => { const accountNonce = BigInt(2); const transaction = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: BigInt('1'), fee: BigInt('100000000'), senderPublicKey: existingSenderPublicKey, - params: getRandomBytes(100), - signatures: [getRandomBytes(64)], + params: utils.getRandomBytes(100), + signatures: [utils.getRandomBytes(64)], }); const transactionAsString = transaction.getBytes().toString('hex'); diff --git a/framework/test/unit/modules/auth/register_multisignature.spec.ts b/framework/test/unit/modules/auth/register_multisignature.spec.ts index e26e41c620a..15c4a9ccc5d 100644 --- a/framework/test/unit/modules/auth/register_multisignature.spec.ts +++ b/framework/test/unit/modules/auth/register_multisignature.spec.ts @@ -66,8 +66,8 @@ describe('Register Multisignature command', () => { it('should return error if params has numberOfSignatures > 64', async () => { const params = codec.encode(registerMultisignatureParamsSchema, { numberOfSignatures: 100, - mandatoryKeys: [getRandomBytes(32)], - optionalKeys: [getRandomBytes(32)], + mandatoryKeys: [utils.getRandomBytes(32)], + optionalKeys: [utils.getRandomBytes(32)], }); const context = testing .createTransactionContext({ @@ -85,8 +85,8 @@ describe('Register Multisignature command', () => { it('should return error if params has numberOfSignatures < 1', async () => { const params = codec.encode(registerMultisignatureParamsSchema, { numberOfSignatures: 0, - mandatoryKeys: [getRandomBytes(32)], - optionalKeys: [getRandomBytes(32)], + mandatoryKeys: [utils.getRandomBytes(32)], + optionalKeys: [utils.getRandomBytes(32)], }); const context = testing .createTransactionContext({ @@ -104,7 +104,7 @@ describe('Register Multisignature command', () => { it('should return error if params has more than 64 mandatory keys', async () => { const params = codec.encode(registerMultisignatureParamsSchema, { numberOfSignatures: 2, - mandatoryKeys: [...Array(65).keys()].map(() => getRandomBytes(32)), + mandatoryKeys: [...Array(65).keys()].map(() => utils.getRandomBytes(32)), optionalKeys: [], }); const context = testing @@ -123,7 +123,7 @@ describe('Register Multisignature command', () => { it('should return error if params mandatory keys contains items with length bigger than 32', async () => { const params = codec.encode(registerMultisignatureParamsSchema, { numberOfSignatures: 3, - mandatoryKeys: [getRandomBytes(32), getRandomBytes(64)], + mandatoryKeys: [utils.getRandomBytes(32), utils.getRandomBytes(64)], optionalKeys: [], }); const context = testing @@ -142,8 +142,8 @@ describe('Register Multisignature command', () => { it('should return error if params mandatory keys contains items with length smaller than 32', async () => { const params = codec.encode(registerMultisignatureParamsSchema, { numberOfSignatures: 3, - mandatoryKeys: [getRandomBytes(10), getRandomBytes(32)], - optionalKeys: [getRandomBytes(10), getRandomBytes(32)], + mandatoryKeys: [utils.getRandomBytes(10), utils.getRandomBytes(32)], + optionalKeys: [utils.getRandomBytes(10), utils.getRandomBytes(32)], }); const context = testing .createTransactionContext({ @@ -161,7 +161,7 @@ describe('Register Multisignature command', () => { const params = codec.encode(registerMultisignatureParamsSchema, { numberOfSignatures: 2, mandatoryKeys: [], - optionalKeys: [...Array(1).keys()].map(() => getRandomBytes(64)), + optionalKeys: [...Array(1).keys()].map(() => utils.getRandomBytes(64)), }); const context = testing .createTransactionContext({ @@ -179,7 +179,7 @@ describe('Register Multisignature command', () => { const params = codec.encode(registerMultisignatureParamsSchema, { numberOfSignatures: 2, mandatoryKeys: [], - optionalKeys: [...Array(1).keys()].map(() => getRandomBytes(31)), + optionalKeys: [...Array(1).keys()].map(() => utils.getRandomBytes(31)), }); const context = testing .createTransactionContext({ @@ -197,7 +197,7 @@ describe('Register Multisignature command', () => { const params = codec.encode(registerMultisignatureParamsSchema, { numberOfSignatures: 2, mandatoryKeys: [], - optionalKeys: [...Array(65).keys()].map(() => getRandomBytes(32)), + optionalKeys: [...Array(65).keys()].map(() => utils.getRandomBytes(32)), }); const context = testing .createTransactionContext({ @@ -358,8 +358,8 @@ describe('Register Multisignature command', () => { it('should return error when the number of optional and mandatory keys is more than 64', async () => { const params = codec.encode(registerMultisignatureParamsSchema, { numberOfSignatures: 2, - optionalKeys: [...Array(65).keys()].map(() => getRandomBytes(32)), - mandatoryKeys: [...Array(65).keys()].map(() => getRandomBytes(32)), + optionalKeys: [...Array(65).keys()].map(() => utils.getRandomBytes(32)), + mandatoryKeys: [...Array(65).keys()].map(() => utils.getRandomBytes(32)), }); const context = testing .createTransactionContext({ diff --git a/framework/test/unit/modules/bft/api.spec.ts b/framework/test/unit/modules/bft/api.spec.ts index 8fa475908b2..41bbb62ede4 100644 --- a/framework/test/unit/modules/bft/api.spec.ts +++ b/framework/test/unit/modules/bft/api.spec.ts @@ -51,13 +51,13 @@ describe('BFT API', () => { describe('areHeadersContradicting', () => { it('should return false when blocks are identical', () => { const header1 = createFakeBlockHeader({ - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), }); expect(bftAPI.areHeadersContradicting(header1, header1)).toBeFalse(); }); it('should return true when blocks contradicting', () => { - const generatorAddress = getRandomBytes(20); + const generatorAddress = utils.getRandomBytes(20); const header1 = createFakeBlockHeader({ height: 10999, maxHeightPrevoted: 1099, @@ -75,19 +75,19 @@ describe('BFT API', () => { const header1 = createFakeBlockHeader({ height: 10999, maxHeightPrevoted: 1099, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), }); const header2 = createFakeBlockHeader({ height: 10999, maxHeightPrevoted: 1099, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), }); expect(bftAPI.areHeadersContradicting(header1, header2)).toBeFalse(); }); }); describe('isHeaderContradictingChain', () => { - const generatorAddress = getRandomBytes(20); + const generatorAddress = utils.getRandomBytes(20); beforeEach(async () => { stateStore = new StateStore(new InMemoryDatabase()); @@ -109,7 +109,7 @@ describe('BFT API', () => { }, { height: 2, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -117,7 +117,7 @@ describe('BFT API', () => { }, { height: 1, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -164,7 +164,7 @@ describe('BFT API', () => { stateStore, createFakeBlockHeader({ height: 4, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 1, maxHeightPrevoted: 1, }), @@ -184,7 +184,7 @@ describe('BFT API', () => { precommitThreshold: BigInt(68), certificateThreshold: BigInt(68), validators: [], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }, bftParametersSchema, ); @@ -206,17 +206,17 @@ describe('BFT API', () => { certificateThreshold: BigInt(68), validators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }); const params20 = createParam(); const params30 = createParam(); @@ -224,8 +224,16 @@ describe('BFT API', () => { beforeEach(async () => { stateStore = new StateStore(new InMemoryDatabase()); const votesStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); - await votesStore.setWithSchema(intToBuffer(20, 4, BIG_ENDIAN), params20, bftParametersSchema); - await votesStore.setWithSchema(intToBuffer(30, 4, BIG_ENDIAN), params30, bftParametersSchema); + await votesStore.setWithSchema( + utils.intToBuffer(20, 4, BIG_ENDIAN), + params20, + bftParametersSchema, + ); + await votesStore.setWithSchema( + utils.intToBuffer(30, 4, BIG_ENDIAN), + params30, + bftParametersSchema, + ); }); it('should return BFT parameters if it exists for the lower height', async () => { @@ -244,7 +252,7 @@ describe('BFT API', () => { }); describe('getBFTHeights', () => { - const generatorAddress = getRandomBytes(20); + const generatorAddress = utils.getRandomBytes(20); beforeEach(async () => { stateStore = new StateStore(new InMemoryDatabase()); @@ -266,7 +274,7 @@ describe('BFT API', () => { }, { height: 2, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -274,7 +282,7 @@ describe('BFT API', () => { }, { height: 1, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -297,7 +305,7 @@ describe('BFT API', () => { }); describe('currentHeaderImpliesMaximalPrevotes', () => { - const generatorAddress = getRandomBytes(20); + const generatorAddress = utils.getRandomBytes(20); beforeEach(() => { stateStore = new StateStore(new InMemoryDatabase()); @@ -314,7 +322,7 @@ describe('BFT API', () => { blockBFTInfos: [ { height: 103, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 120, maxHeightPrevoted: 0, }, @@ -328,7 +336,7 @@ describe('BFT API', () => { }, { height: 101, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -354,7 +362,7 @@ describe('BFT API', () => { blockBFTInfos: [ { height: 103, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 1, maxHeightPrevoted: 0, }, @@ -368,7 +376,7 @@ describe('BFT API', () => { }, { height: 101, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -394,7 +402,7 @@ describe('BFT API', () => { blockBFTInfos: [ { height: 103, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 101, maxHeightPrevoted: 0, }, @@ -408,7 +416,7 @@ describe('BFT API', () => { }, { height: 101, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -448,7 +456,7 @@ describe('BFT API', () => { }, { height: 101, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -471,23 +479,31 @@ describe('BFT API', () => { certificateThreshold: BigInt(68), validators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }); const params20 = createParam(); const params30 = createParam(); beforeEach(async () => { stateStore = new StateStore(new InMemoryDatabase()); const votesStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); - await votesStore.setWithSchema(intToBuffer(20, 4, BIG_ENDIAN), params20, bftParametersSchema); - await votesStore.setWithSchema(intToBuffer(30, 4, BIG_ENDIAN), params30, bftParametersSchema); + await votesStore.setWithSchema( + utils.intToBuffer(20, 4, BIG_ENDIAN), + params20, + bftParametersSchema, + ); + await votesStore.setWithSchema( + utils.intToBuffer(30, 4, BIG_ENDIAN), + params30, + bftParametersSchema, + ); }); it('should return the next height strictly higher than the input where BFT parameter exists', async () => { @@ -508,22 +524,22 @@ describe('BFT API', () => { certificateThreshold: BigInt(68), validators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }); - const generatorAddress = getRandomBytes(20); + const generatorAddress = utils.getRandomBytes(20); const params20 = createParam(); const params30 = createParam(); beforeEach(async () => { - validatorsAPI.getValidatorAccount.mockResolvedValue({ blsKey: getRandomBytes(32) }); + validatorsAPI.getValidatorAccount.mockResolvedValue({ blsKey: utils.getRandomBytes(32) }); stateStore = new StateStore(new InMemoryDatabase()); const paramsStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); await paramsStore.setWithSchema( @@ -537,7 +553,7 @@ describe('BFT API', () => { bftParametersSchema, ); const votesStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_VOTES); - const addresses = [getRandomBytes(20), getRandomBytes(20)]; + const addresses = [utils.getRandomBytes(20), utils.getRandomBytes(20)]; await votesStore.setWithSchema( EMPTY_KEY, { @@ -599,9 +615,9 @@ describe('BFT API', () => { BigInt(68), BigInt(68), new Array(bftAPI['_batchSize'] + 1).fill(0).map(() => ({ - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), })), ), ).rejects.toThrow('Invalid validators size.'); @@ -611,19 +627,19 @@ describe('BFT API', () => { await expect( bftAPI.setBFTParameters(stateStore, BigInt(34), BigInt(68), [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(3), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ]), ).rejects.toThrow('Invalid precommitThreshold input.'); @@ -633,19 +649,19 @@ describe('BFT API', () => { await expect( bftAPI.setBFTParameters(stateStore, BigInt(104), BigInt(68), [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(3), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ]), ).rejects.toThrow('Invalid precommitThreshold input.'); @@ -655,19 +671,19 @@ describe('BFT API', () => { await expect( bftAPI.setBFTParameters(stateStore, BigInt(68), BigInt(34), [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(3), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ]), ).rejects.toThrow('Invalid certificateThreshold input.'); @@ -677,19 +693,19 @@ describe('BFT API', () => { await expect( bftAPI.setBFTParameters(stateStore, BigInt(68), BigInt(104), [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(3), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ]), ).rejects.toThrow('Invalid certificateThreshold input.'); @@ -700,17 +716,17 @@ describe('BFT API', () => { { address: generatorAddress, bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(3), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ]; beforeEach(async () => { @@ -720,7 +736,7 @@ describe('BFT API', () => { it('should not create set BFTParameters when there is no change from previous params', async () => { const votesStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_VOTES); const currentVotes = await votesStore.getWithSchema(EMPTY_KEY, bftVotesSchema); - const addresses = [getRandomBytes(20), getRandomBytes(20)]; + const addresses = [utils.getRandomBytes(20), utils.getRandomBytes(20)]; currentVotes.blockBFTInfos = [ { height: 104, @@ -795,17 +811,17 @@ describe('BFT API', () => { { address: generatorAddress, bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(50), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(3), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ]); @@ -868,13 +884,13 @@ describe('BFT API', () => { it('should sort validators ordered lexicographically by blsKey and include certificateThreshold', () => { const accounts = [ { - address: getRandomBytes(20), - blsKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + blsKey: utils.getRandomBytes(32), bftWeight: BigInt(20), }, { - address: getRandomBytes(20), - blsKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + blsKey: utils.getRandomBytes(32), bftWeight: BigInt(20), }, ]; @@ -911,12 +927,12 @@ describe('BFT API', () => { const createKeys = () => ({ generators: [ { - address: getRandomBytes(20), - generatorKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + generatorKey: utils.getRandomBytes(32), }, { - address: getRandomBytes(20), - generatorKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + generatorKey: utils.getRandomBytes(32), }, ], }); @@ -925,8 +941,16 @@ describe('BFT API', () => { beforeEach(async () => { stateStore = new StateStore(new InMemoryDatabase()); const keysStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_GENERATOR_KEYS); - await keysStore.setWithSchema(intToBuffer(20, 4, BIG_ENDIAN), keys20, generatorKeysSchema); - await keysStore.setWithSchema(intToBuffer(30, 4, BIG_ENDIAN), keys30, generatorKeysSchema); + await keysStore.setWithSchema( + utils.intToBuffer(20, 4, BIG_ENDIAN), + keys20, + generatorKeysSchema, + ); + await keysStore.setWithSchema( + utils.intToBuffer(30, 4, BIG_ENDIAN), + keys30, + generatorKeysSchema, + ); }); it('should current generators', async () => { @@ -940,7 +964,7 @@ describe('BFT API', () => { blockBFTInfos: [ { height: 35, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -948,7 +972,7 @@ describe('BFT API', () => { }, { height: 34, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -956,7 +980,7 @@ describe('BFT API', () => { }, { height: 33, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -975,12 +999,12 @@ describe('BFT API', () => { const createKeys = () => ({ generators: [ { - address: getRandomBytes(20), - generatorKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + generatorKey: utils.getRandomBytes(32), }, { - address: getRandomBytes(20), - generatorKey: getRandomBytes(32), + address: utils.getRandomBytes(20), + generatorKey: utils.getRandomBytes(32), }, ], }); @@ -999,7 +1023,7 @@ describe('BFT API', () => { blockBFTInfos: [ { height: 35, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -1007,7 +1031,7 @@ describe('BFT API', () => { }, { height: 34, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -1015,7 +1039,7 @@ describe('BFT API', () => { }, { height: 33, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), maxHeightGenerated: 0, maxHeightPrevoted: 0, prevoteWeight: 0, @@ -1030,7 +1054,7 @@ describe('BFT API', () => { bftAPI.setGeneratorKeys(stateStore, createKeys().generators), ).resolves.toBeUndefined(); const keysStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_GENERATOR_KEYS); - await expect(keysStore.has(intToBuffer(36, 4, BIG_ENDIAN))).resolves.toBeTrue(); + await expect(keysStore.has(utils.intToBuffer(36, 4, BIG_ENDIAN))).resolves.toBeTrue(); }); }); }); diff --git a/framework/test/unit/modules/bft/bft_params.spec.ts b/framework/test/unit/modules/bft/bft_params.spec.ts index 45f64cf4ce0..d08f6575943 100644 --- a/framework/test/unit/modules/bft/bft_params.spec.ts +++ b/framework/test/unit/modules/bft/bft_params.spec.ts @@ -39,34 +39,34 @@ describe('BFT parameters', () => { db = new InMemoryDatabase() as never; const rootStore = new StateStore(db); const paramsStore = rootStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); - const height1Bytes = intToBuffer(309, 4, BIG_ENDIAN); + const height1Bytes = utils.intToBuffer(309, 4, BIG_ENDIAN); bftParams1 = { prevoteThreshold: BigInt(20), precommitThreshold: BigInt(30), certificateThreshold: BigInt(40), validators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(10), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height1Bytes, codec.encode(bftParametersSchema, bftParams1)); - const height2Bytes = intToBuffer(515, 4, BIG_ENDIAN); + const height2Bytes = utils.intToBuffer(515, 4, BIG_ENDIAN); bftParams2 = { prevoteThreshold: BigInt(40), precommitThreshold: BigInt(50), certificateThreshold: BigInt(60), validators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(5), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height2Bytes, codec.encode(bftParametersSchema, bftParams2)); const batch = new Batch(); @@ -105,34 +105,34 @@ describe('BFT parameters', () => { db = new InMemoryDatabase() as never; const rootStore = new StateStore(db); const paramsStore = rootStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); - const height1Bytes = intToBuffer(309, 4, BIG_ENDIAN); + const height1Bytes = utils.intToBuffer(309, 4, BIG_ENDIAN); bftParams1 = { prevoteThreshold: BigInt(20), precommitThreshold: BigInt(30), certificateThreshold: BigInt(40), validators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(10), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height1Bytes, codec.encode(bftParametersSchema, bftParams1)); - const height2Bytes = intToBuffer(515, 4, BIG_ENDIAN); + const height2Bytes = utils.intToBuffer(515, 4, BIG_ENDIAN); bftParams2 = { prevoteThreshold: BigInt(40), precommitThreshold: BigInt(50), certificateThreshold: BigInt(60), validators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(5), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height2Bytes, codec.encode(bftParametersSchema, bftParams2)); const batch = new Batch(); @@ -156,7 +156,7 @@ describe('BFT parameters', () => { await deleteBFTParameters(paramsStore, 515); expect(paramsStore.del).toHaveBeenCalledTimes(1); - expect(paramsStore.del).toHaveBeenCalledWith(intToBuffer(309, 4, BIG_ENDIAN)); + expect(paramsStore.del).toHaveBeenCalledWith(utils.intToBuffer(309, 4, BIG_ENDIAN)); }); }); @@ -168,49 +168,49 @@ describe('BFT parameters', () => { db = new InMemoryDatabase() as never; const rootStore = new StateStore(db); const paramsStore = rootStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); - const height1Bytes = intToBuffer(104, 4, BIG_ENDIAN); + const height1Bytes = utils.intToBuffer(104, 4, BIG_ENDIAN); const bftParams1 = { prevoteThreshold: BigInt(20), precommitThreshold: BigInt(30), certificateThreshold: BigInt(40), validators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(10), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height1Bytes, codec.encode(bftParametersSchema, bftParams1)); - const height2Bytes = intToBuffer(207, 4, BIG_ENDIAN); + const height2Bytes = utils.intToBuffer(207, 4, BIG_ENDIAN); const bftParams2 = { prevoteThreshold: BigInt(40), precommitThreshold: BigInt(50), certificateThreshold: BigInt(60), validators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(5), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height2Bytes, codec.encode(bftParametersSchema, bftParams2)); - const height3Bytes = intToBuffer(310, 4, BIG_ENDIAN); + const height3Bytes = utils.intToBuffer(310, 4, BIG_ENDIAN); const bftParams3 = { prevoteThreshold: BigInt(40), precommitThreshold: BigInt(50), certificateThreshold: BigInt(60), validators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(5), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height3Bytes, codec.encode(bftParametersSchema, bftParams3)); const batch = new Batch(); diff --git a/framework/test/unit/modules/bft/bft_processing.spec.ts b/framework/test/unit/modules/bft/bft_processing.spec.ts index 94ae8139f0a..05d1ba6275e 100644 --- a/framework/test/unit/modules/bft/bft_processing.spec.ts +++ b/framework/test/unit/modules/bft/bft_processing.spec.ts @@ -60,7 +60,7 @@ describe('BFT processing', () => { const threshold = Math.floor((scenario.config.activeDelegates * 2) / 3) + 1; const validators: (BFTValidator & GeneratorKey & { minHeightActive: number })[] = []; for (const testCase of scenario.testCases) { - const generatorAddress = getAddressFromPublicKey( + const generatorAddress = address.getAddressFromPublicKey( Buffer.from(testCase.input.blockHeader.generatorPublicKey, 'hex'), ); if (validators.find(v => v.address.equals(generatorAddress)) === undefined) { @@ -69,7 +69,7 @@ describe('BFT processing', () => { minHeightActive: testCase.input.blockHeader.delegateMinHeightActive, bftWeight: BigInt(1), generatorKey: Buffer.from(testCase.input.blockHeader.generatorPublicKey, 'hex'), - blsKey: getRandomBytes(42), + blsKey: utils.getRandomBytes(42), }); } } @@ -80,7 +80,7 @@ describe('BFT processing', () => { precommitThreshold: BigInt(threshold), certificateThreshold: BigInt(threshold), validators, - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }, bftParametersSchema, ); @@ -105,7 +105,7 @@ describe('BFT processing', () => { for (const testCase of scenario.testCases) { it(`should have accurate information when ${testCase.input.delegateName} forge block at height = ${testCase.input.blockHeader.height}`, async () => { // Arrange - const generatorAddress = getAddressFromPublicKey( + const generatorAddress = address.getAddressFromPublicKey( Buffer.from(testCase.input.blockHeader.generatorPublicKey, 'hex'), ); const header = new BlockHeader({ @@ -119,7 +119,7 @@ describe('BFT processing', () => { height: testCase.input.blockHeader.height, maxHeightGenerated: testCase.input.blockHeader.maxHeightPreviouslyForged, maxHeightPrevoted: testCase.input.blockHeader.maxHeightPrevoted, - previousBlockID: getRandomBytes(32), + previousBlockID: utils.getRandomBytes(32), timestamp: 0, }); diff --git a/framework/test/unit/modules/bft/bft_votes.spec.ts b/framework/test/unit/modules/bft/bft_votes.spec.ts index 0bbabe9f93f..831125a9e6c 100644 --- a/framework/test/unit/modules/bft/bft_votes.spec.ts +++ b/framework/test/unit/modules/bft/bft_votes.spec.ts @@ -37,7 +37,7 @@ describe('BFT votes', () => { let bftVotes: BFTVotes; beforeEach(() => { - accounts = [getRandomBytes(20), getRandomBytes(20), getRandomBytes(20)]; + accounts = [utils.getRandomBytes(20), utils.getRandomBytes(20), utils.getRandomBytes(20)]; bftVotes = { maxHeightPrevoted: 103, maxHeightPrecommitted: 56, @@ -150,7 +150,7 @@ describe('BFT votes', () => { createFakeBlockHeader({ height: 152, maxHeightGenerated: 149, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), }), 5, ); @@ -210,7 +210,7 @@ describe('BFT votes', () => { bftWeight: BigInt(1), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }, bftParametersSchema, ); @@ -238,7 +238,7 @@ describe('BFT votes', () => { createFakeBlockHeader({ height: 152, maxHeightGenerated: 151, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), }), 5, ); @@ -354,7 +354,7 @@ describe('BFT votes', () => { bftWeight: BigInt(1), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }, bftParametersSchema, ); @@ -386,7 +386,7 @@ describe('BFT votes', () => { bftWeight: BigInt(1), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }, bftParametersSchema, ); @@ -422,7 +422,7 @@ describe('BFT votes', () => { bftWeight: BigInt(1), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }, bftParametersSchema, ); @@ -454,7 +454,7 @@ describe('BFT votes', () => { bftWeight: BigInt(1), }, ], - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }, bftParametersSchema, ); @@ -471,8 +471,8 @@ describe('BFT votes', () => { createFakeBlockHeader({ height: 152, aggregateCommit: { - aggregationBits: getRandomBytes(3), - certificateSignature: getRandomBytes(64), + aggregationBits: utils.getRandomBytes(3), + certificateSignature: utils.getRandomBytes(64), height: 10, }, }), diff --git a/framework/test/unit/modules/bft/utils.spec.ts b/framework/test/unit/modules/bft/utils.spec.ts index f29d00d1fdc..c9522dd4b46 100644 --- a/framework/test/unit/modules/bft/utils.spec.ts +++ b/framework/test/unit/modules/bft/utils.spec.ts @@ -20,14 +20,14 @@ import { } from '../../../../src/engine/bft/utils'; describe('bft utils', () => { - const generatorAddress = getRandomBytes(20); + const generatorAddress = utils.getRandomBytes(20); it('should return false when generatorAddress does not match', () => { const header1 = createFakeBlockHeader({ generatorAddress, }); const header2 = createFakeBlockHeader({ - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), }); expect(areDistinctHeadersContradicting(header1, header2)).toBeFalse(); diff --git a/framework/test/unit/modules/dpos_v2/api.spec.ts b/framework/test/unit/modules/dpos_v2/api.spec.ts index 176c32ef326..fe3daa2b32e 100644 --- a/framework/test/unit/modules/dpos_v2/api.spec.ts +++ b/framework/test/unit/modules/dpos_v2/api.spec.ts @@ -37,17 +37,17 @@ describe('DposModuleApi', () => { let voterSubStore: PrefixedStateReadWriter; let delegateSubStore: PrefixedStateReadWriter; let nameSubStore: PrefixedStateReadWriter; - const address = getRandomBytes(20); + const address = utils.getRandomBytes(20); const voterData = { sentVotes: [ { - delegateAddress: getRandomBytes(20), + delegateAddress: utils.getRandomBytes(20), amount: BigInt(0), }, ], pendingUnlocks: [ { - delegateAddress: getRandomBytes(20), + delegateAddress: utils.getRandomBytes(20), amount: BigInt(0), unvoteHeight: 0, }, diff --git a/framework/test/unit/modules/dpos_v2/commands/delegate_registration.spec.ts b/framework/test/unit/modules/dpos_v2/commands/delegate_registration.spec.ts index aebe759e67c..53634929c92 100644 --- a/framework/test/unit/modules/dpos_v2/commands/delegate_registration.spec.ts +++ b/framework/test/unit/modules/dpos_v2/commands/delegate_registration.spec.ts @@ -45,9 +45,9 @@ describe('Delegate registration command', () => { const transactionParams = { name: 'gojosatoru', - generatorKey: getRandomBytes(32), - blsKey: getRandomBytes(48), - proofOfPossession: getRandomBytes(96), + generatorKey: utils.getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + proofOfPossession: utils.getRandomBytes(96), }; const defaultDelegateInfo = { name: transactionParams.name, @@ -62,10 +62,10 @@ describe('Delegate registration command', () => { delegateRegistrationCommandParamsSchema, transactionParams, ); - const publicKey = getRandomBytes(32); + const publicKey = utils.getRandomBytes(32); const transaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_DELEGATE_REGISTRATION, 4), + commandID: utils.intToBuffer(COMMAND_ID_DELEGATE_REGISTRATION, 4), senderPublicKey: publicKey, nonce: BigInt(0), fee: BigInt(100000000), @@ -113,7 +113,7 @@ describe('Delegate registration command', () => { }); const invalidTransaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_DELEGATE_REGISTRATION, 4), + commandID: utils.intToBuffer(COMMAND_ID_DELEGATE_REGISTRATION, 4), senderPublicKey: publicKey, nonce: BigInt(0), fee: BigInt(100000000), @@ -137,11 +137,11 @@ describe('Delegate registration command', () => { it('should return error if generatorKey is invalid', async () => { const invalidParams = codec.encode(delegateRegistrationCommandParamsSchema, { ...transactionParams, - generatorKey: getRandomBytes(64), + generatorKey: utils.getRandomBytes(64), }); const invalidTransaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_DELEGATE_REGISTRATION, 4), + commandID: utils.intToBuffer(COMMAND_ID_DELEGATE_REGISTRATION, 4), senderPublicKey: publicKey, nonce: BigInt(0), fee: BigInt(100000000), @@ -165,11 +165,11 @@ describe('Delegate registration command', () => { it('should return error if blsKey is invalid', async () => { const invalidParams = codec.encode(delegateRegistrationCommandParamsSchema, { ...transactionParams, - blsKey: getRandomBytes(64), + blsKey: utils.getRandomBytes(64), }); const invalidTransaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_DELEGATE_REGISTRATION, 4), + commandID: utils.intToBuffer(COMMAND_ID_DELEGATE_REGISTRATION, 4), senderPublicKey: publicKey, nonce: BigInt(0), fee: BigInt(100000000), @@ -193,11 +193,11 @@ describe('Delegate registration command', () => { it('should return error if proofOfPossession is invalid', async () => { const invalidParams = codec.encode(delegateRegistrationCommandParamsSchema, { ...transactionParams, - proofOfPossession: getRandomBytes(64), + proofOfPossession: utils.getRandomBytes(64), }); const invalidTransaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_DELEGATE_REGISTRATION, 4), + commandID: utils.intToBuffer(COMMAND_ID_DELEGATE_REGISTRATION, 4), senderPublicKey: publicKey, nonce: BigInt(0), fee: BigInt(100000000), diff --git a/framework/test/unit/modules/dpos_v2/commands/pom.spec.ts b/framework/test/unit/modules/dpos_v2/commands/pom.spec.ts index c2134d34bf8..18e904ac699 100644 --- a/framework/test/unit/modules/dpos_v2/commands/pom.spec.ts +++ b/framework/test/unit/modules/dpos_v2/commands/pom.spec.ts @@ -59,15 +59,15 @@ describe('ReportDelegateMisbehaviorCommand', () => { let transaction: any; let transactionParams: Buffer; let transactionParamsDecoded: PomTransactionParams; - const publicKey = getRandomBytes(32); - const senderAddress = getAddressFromPublicKey(publicKey); + const publicKey = utils.getRandomBytes(32); + const senderAddress = address.getAddressFromPublicKey(publicKey); const header = testing.createFakeBlockHeader({ height: blockHeight, }); const { address: delegate1Address, publicKey: delegate1PublicKey, - } = getAddressAndPublicKeyFromPassphrase(getRandomBytes(20).toString('utf8')); + } = getAddressAndPublicKeyFromPassphrase(utils.getRandomBytes(20).toString('utf8')); const defaultDelegateInfo = { totalVotesReceived: BigInt(100000000), selfVotes: BigInt(0), @@ -128,7 +128,7 @@ describe('ReportDelegateMisbehaviorCommand', () => { delegateSubstore = stateStore.getStore(MODULE_ID_DPOS_BUFFER, STORE_PREFIX_DELEGATE); transaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_POM, 4), + commandID: utils.intToBuffer(COMMAND_ID_POM, 4), senderPublicKey: publicKey, nonce: BigInt(0), fee: BigInt(100000000), @@ -179,7 +179,7 @@ describe('ReportDelegateMisbehaviorCommand', () => { }), header2: codec.encode(blockHeaderSchema, { ...header2, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), }), }; transactionParams = codec.encode(pomCommand.schema, transactionParamsDecoded); @@ -199,7 +199,7 @@ describe('ReportDelegateMisbehaviorCommand', () => { it('should throw error when header1 cannot be decoded', async () => { transactionParamsDecoded = { - header1: getRandomBytes(32), + header1: utils.getRandomBytes(32), header2: codec.encode(blockHeaderSchema, { ...header2 }), }; transactionParams = codec.encode(pomCommand.schema, transactionParamsDecoded); @@ -217,7 +217,7 @@ describe('ReportDelegateMisbehaviorCommand', () => { it('should throw error when header2 cannot be decoded', async () => { transactionParamsDecoded = { header1: codec.encode(blockHeaderSchema, { ...header1 }), - header2: getRandomBytes(32), + header2: utils.getRandomBytes(32), }; transactionParams = codec.encode(pomCommand.schema, transactionParamsDecoded); transaction.params = transactionParams; @@ -238,7 +238,7 @@ describe('ReportDelegateMisbehaviorCommand', () => { }), header2: codec.encode(blockHeaderSchema, { ...header2, - generatorAddress: getRandomBytes(20), + generatorAddress: utils.getRandomBytes(20), }), }; transactionParams = codec.encode(pomCommand.schema, transactionParamsDecoded); @@ -501,7 +501,7 @@ describe('ReportDelegateMisbehaviorCommand', () => { transactionParamsDecoded = { header1: codec.encode(blockHeaderSchema, { ...transactionParamsPreDecoded.header1, - generatorAddress: getRandomBytes(32), + generatorAddress: utils.getRandomBytes(32), }), header2: codec.encode(blockHeaderSchema, transactionParamsPreDecoded.header2), }; @@ -736,7 +736,7 @@ describe('ReportDelegateMisbehaviorCommand', () => { it('should not return balance if sender and delegate account are same', async () => { transaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_POM, 4), + commandID: utils.intToBuffer(COMMAND_ID_POM, 4), senderPublicKey: delegate1PublicKey, nonce: BigInt(0), fee: BigInt(100000000), diff --git a/framework/test/unit/modules/dpos_v2/commands/unlock.spec.ts b/framework/test/unit/modules/dpos_v2/commands/unlock.spec.ts index 5cc0287b241..ce6523acff1 100644 --- a/framework/test/unit/modules/dpos_v2/commands/unlock.spec.ts +++ b/framework/test/unit/modules/dpos_v2/commands/unlock.spec.ts @@ -54,10 +54,26 @@ describe('UnlockCommand', () => { let nonUnlockableObject: UnlockingObject; let context: CommandExecuteContext; let storedData: VoterData; - const delegate1 = { name: 'delegate1', address: getRandomBytes(32), amount: liskToBeddows(100) }; - const delegate2 = { name: 'delegate2', address: getRandomBytes(32), amount: liskToBeddows(200) }; - const delegate3 = { name: 'delegate3', address: getRandomBytes(32), amount: liskToBeddows(300) }; - const delegate4 = { name: 'delegate4', address: getRandomBytes(32), amount: liskToBeddows(400) }; + const delegate1 = { + name: 'delegate1', + address: utils.getRandomBytes(32), + amount: liskToBeddows(100), + }; + const delegate2 = { + name: 'delegate2', + address: utils.getRandomBytes(32), + amount: liskToBeddows(200), + }; + const delegate3 = { + name: 'delegate3', + address: utils.getRandomBytes(32), + amount: liskToBeddows(300), + }; + const delegate4 = { + name: 'delegate4', + address: utils.getRandomBytes(32), + amount: liskToBeddows(400), + }; const defaultDelegateInfo = { totalVotesReceived: BigInt(100000000), selfVotes: BigInt(0), @@ -66,10 +82,10 @@ describe('UnlockCommand', () => { pomHeights: [], consecutiveMissedBlocks: 0, }; - const publicKey = getRandomBytes(32); + const publicKey = utils.getRandomBytes(32); const transaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_UNLOCK, 4), + commandID: utils.intToBuffer(COMMAND_ID_UNLOCK, 4), senderPublicKey: publicKey, nonce: BigInt(0), fee: BigInt(100000000), diff --git a/framework/test/unit/modules/dpos_v2/commands/vote.spec.ts b/framework/test/unit/modules/dpos_v2/commands/vote.spec.ts index 82e093ccb1b..c73ca37288c 100644 --- a/framework/test/unit/modules/dpos_v2/commands/vote.spec.ts +++ b/framework/test/unit/modules/dpos_v2/commands/vote.spec.ts @@ -37,11 +37,11 @@ import { DEFAULT_TOKEN_ID } from '../../../../utils/mocks/transaction'; describe('VoteCommand', () => { const lastBlockHeight = 200; const tokenIDDPoS = DEFAULT_TOKEN_ID; - const senderPublicKey = getRandomBytes(32); - const senderAddress = getAddressFromPublicKey(senderPublicKey); - const delegateAddress1 = getRandomBytes(20); - const delegateAddress2 = getRandomBytes(20); - const delegateAddress3 = getRandomBytes(20); + const senderPublicKey = utils.getRandomBytes(32); + const senderAddress = address.getAddressFromPublicKey(senderPublicKey); + const delegateAddress1 = utils.getRandomBytes(20); + const delegateAddress2 = utils.getRandomBytes(20); + const delegateAddress3 = utils.getRandomBytes(20); const delegate1VoteAmount = liskToBeddows(90); const delegate2VoteAmount = liskToBeddows(50); const getWithSchemaMock = jest.fn(); @@ -151,11 +151,11 @@ describe('VoteCommand', () => { beforeEach(() => { transaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_VOTE, 4), + commandID: utils.intToBuffer(COMMAND_ID_VOTE, 4), fee: BigInt(1500000), nonce: BigInt(0), params: Buffer.alloc(0), - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [], }); }); @@ -191,7 +191,7 @@ describe('VoteCommand', () => { transactionParamsDecoded = { votes: Array(21) .fill(0) - .map(() => ({ delegateAddress: getRandomBytes(20), amount: liskToBeddows(0) })), + .map(() => ({ delegateAddress: utils.getRandomBytes(20), amount: liskToBeddows(0) })), }; transactionParams = codec.encode(command.schema, transactionParamsDecoded); @@ -218,7 +218,7 @@ describe('VoteCommand', () => { transactionParamsDecoded = { votes: [ { - delegateAddress: getRandomBytes(20), + delegateAddress: utils.getRandomBytes(20), amount: BigInt(-1) * BigInt(2) ** BigInt(63) - BigInt(1), }, ], @@ -236,7 +236,7 @@ describe('VoteCommand', () => { transactionParamsDecoded = { votes: [ { - delegateAddress: getRandomBytes(20), + delegateAddress: utils.getRandomBytes(20), amount: BigInt(2) ** BigInt(63) + BigInt(1), }, ], @@ -254,7 +254,7 @@ describe('VoteCommand', () => { it('should not throw errors with valid upvote case', async () => { // Arrange transactionParamsDecoded = { - votes: [{ delegateAddress: getRandomBytes(20), amount: liskToBeddows(20) }], + votes: [{ delegateAddress: utils.getRandomBytes(20), amount: liskToBeddows(20) }], }; transactionParams = codec.encode(command.schema, transactionParamsDecoded); @@ -272,7 +272,7 @@ describe('VoteCommand', () => { it('should not throw errors with valid downvote cast', async () => { // Arrange transactionParamsDecoded = { - votes: [{ delegateAddress: getRandomBytes(20), amount: liskToBeddows(-20) }], + votes: [{ delegateAddress: utils.getRandomBytes(20), amount: liskToBeddows(-20) }], }; transactionParams = codec.encode(command.schema, transactionParamsDecoded); @@ -291,8 +291,8 @@ describe('VoteCommand', () => { // Arrange transactionParamsDecoded = { votes: [ - { delegateAddress: getRandomBytes(20), amount: liskToBeddows(20) }, - { delegateAddress: getRandomBytes(20), amount: liskToBeddows(-20) }, + { delegateAddress: utils.getRandomBytes(20), amount: liskToBeddows(20) }, + { delegateAddress: utils.getRandomBytes(20), amount: liskToBeddows(-20) }, ], }; @@ -315,7 +315,7 @@ describe('VoteCommand', () => { transactionParamsDecoded = { votes: Array(11) .fill(0) - .map(() => ({ delegateAddress: getRandomBytes(20), amount: liskToBeddows(10) })), + .map(() => ({ delegateAddress: utils.getRandomBytes(20), amount: liskToBeddows(10) })), }; transactionParams = codec.encode(command.schema, transactionParamsDecoded); @@ -340,7 +340,7 @@ describe('VoteCommand', () => { transactionParamsDecoded = { votes: Array(11) .fill(0) - .map(() => ({ delegateAddress: getRandomBytes(20), amount: liskToBeddows(-10) })), + .map(() => ({ delegateAddress: utils.getRandomBytes(20), amount: liskToBeddows(-10) })), }; transactionParams = codec.encode(command.schema, transactionParamsDecoded); @@ -362,7 +362,7 @@ describe('VoteCommand', () => { describe('when transaction.params.votes includes duplicate delegates within positive amount', () => { it('should throw error', async () => { // Arrange - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); transactionParamsDecoded = { votes: Array(2) .fill(0) @@ -388,7 +388,7 @@ describe('VoteCommand', () => { describe('when transaction.params.votes includes duplicate delegates within positive and negative amount', () => { it('should throw error', async () => { // Arrange - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); transactionParamsDecoded = { votes: [ { delegateAddress, amount: liskToBeddows(10) }, @@ -415,7 +415,7 @@ describe('VoteCommand', () => { describe('when transaction.params.votes includes zero amount', () => { it('should throw error', async () => { // Arrange - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); transactionParamsDecoded = { votes: [{ delegateAddress, amount: liskToBeddows(0) }], }; @@ -439,7 +439,7 @@ describe('VoteCommand', () => { describe('when transaction.params.votes includes positive amount which is not multiple of 10 * 10^8', () => { it('should throw an error', async () => { // Arrange - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); transactionParamsDecoded = { votes: [{ delegateAddress, amount: BigInt(20) }], }; @@ -463,7 +463,7 @@ describe('VoteCommand', () => { describe('when transaction.params.votes includes negative amount which is not multiple of 10 * 10^8', () => { it('should throw error', async () => { // Arrange - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); transactionParamsDecoded = { votes: [{ delegateAddress, amount: BigInt(-20) }], }; @@ -489,7 +489,7 @@ describe('VoteCommand', () => { beforeEach(() => { transaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_VOTE, 4), + commandID: utils.intToBuffer(COMMAND_ID_VOTE, 4), fee: BigInt(1500000), nonce: BigInt(0), params: transactionParams, @@ -520,7 +520,7 @@ describe('VoteCommand', () => { it('should throw error if vote amount is more than balance', async () => { // Arrange transactionParamsDecoded = { - votes: [{ delegateAddress: getRandomBytes(20), amount: liskToBeddows(100) }], + votes: [{ delegateAddress: utils.getRandomBytes(20), amount: liskToBeddows(100) }], }; transactionParams = codec.encode(command.schema, transactionParamsDecoded); @@ -1042,7 +1042,7 @@ describe('VoteCommand', () => { describe('when transaction.params.votes contain delegate address which is not registered', () => { it('should throw error', async () => { // Arrange - const nonExistingDelegateAddress = getRandomBytes(20); + const nonExistingDelegateAddress = utils.getRandomBytes(20); transactionParamsDecoded = { ...transactionParamsDecoded, @@ -1072,7 +1072,7 @@ describe('VoteCommand', () => { const votes = []; for (let i = 0; i < 12; i += 1) { - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); const delegateInfo = { consecutiveMissedBlocks: 0, @@ -1115,7 +1115,7 @@ describe('VoteCommand', () => { // Suppose account already voted for 8 delegates for (let i = 0; i < initialDelegateAmount; i += 1) { - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); const delegateInfo = { consecutiveMissedBlocks: 0, @@ -1152,7 +1152,7 @@ describe('VoteCommand', () => { // We have 3 positive votes for (let i = 0; i < 3; i += 1) { - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); const delegateInfo = { consecutiveMissedBlocks: 0, @@ -1199,7 +1199,7 @@ describe('VoteCommand', () => { // Suppose account already 19 unlocking for (let i = 0; i < initialDelegateAmountForUnlocks; i += 1) { - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); const delegateInfo = { consecutiveMissedBlocks: 0, @@ -1223,7 +1223,7 @@ describe('VoteCommand', () => { // Suppose account have 5 positive votes for (let i = 0; i < 5; i += 1) { - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); const delegateInfo = { consecutiveMissedBlocks: 0, @@ -1433,7 +1433,7 @@ describe('VoteCommand', () => { const senderVoteAmountPositive = liskToBeddows(80); const senderVoteAmountNegative = liskToBeddows(20); const delegateSelfVote = liskToBeddows(2000); - const delegateAddress = getRandomBytes(20); + const delegateAddress = utils.getRandomBytes(20); let delegateInfo: any; beforeEach(async () => { delegateInfo = { diff --git a/framework/test/unit/modules/dpos_v2/endpoint.spec.ts b/framework/test/unit/modules/dpos_v2/endpoint.spec.ts index 39eefe9c3b6..a98030b7a82 100644 --- a/framework/test/unit/modules/dpos_v2/endpoint.spec.ts +++ b/framework/test/unit/modules/dpos_v2/endpoint.spec.ts @@ -34,21 +34,21 @@ describe('DposModuleEndpoint', () => { let stateStore: PrefixedStateReadWriter; let voterSubStore: PrefixedStateReadWriter; let delegateSubStore: PrefixedStateReadWriter; - const address = getRandomBytes(20); - const address1 = getRandomBytes(20); - const address2 = getRandomBytes(20); + const address = utils.getRandomBytes(20); + const address1 = utils.getRandomBytes(20); + const address2 = utils.getRandomBytes(20); const getStore1 = jest.fn(); const networkIdentifier = Buffer.alloc(0); const voterData = { sentVotes: [ { - delegateAddress: getRandomBytes(20), + delegateAddress: utils.getRandomBytes(20), amount: BigInt(0), }, ], pendingUnlocks: [ { - delegateAddress: getRandomBytes(20), + delegateAddress: utils.getRandomBytes(20), amount: BigInt(0), unvoteHeight: 0, }, diff --git a/framework/test/unit/modules/dpos_v2/genesis_block_test_data.ts b/framework/test/unit/modules/dpos_v2/genesis_block_test_data.ts index f35e66da412..84d4ee75d3e 100644 --- a/framework/test/unit/modules/dpos_v2/genesis_block_test_data.ts +++ b/framework/test/unit/modules/dpos_v2/genesis_block_test_data.ts @@ -23,7 +23,7 @@ import { Mnemonic } from '@liskhq/lisk-passphrase'; export const validators = new Array(120).fill(0).map((_, i) => { const passphrase = Mnemonic.generateMnemonic(); const keys = getKeys(passphrase); - const address = getAddressFromPublicKey(keys.publicKey); + const address = address.getAddressFromPublicKey(keys.publicKey); const blsPrivateKey = generatePrivateKey(Buffer.from(passphrase, 'utf-8')); const blsPublicKey = getPublicKeyFromPrivateKey(blsPrivateKey); const blsPoP = blsPopProve(blsPrivateKey); diff --git a/framework/test/unit/modules/dpos_v2/module.spec.ts b/framework/test/unit/modules/dpos_v2/module.spec.ts index bfae0ba713c..bb1099c084f 100644 --- a/framework/test/unit/modules/dpos_v2/module.spec.ts +++ b/framework/test/unit/modules/dpos_v2/module.spec.ts @@ -124,9 +124,10 @@ describe('DPoS module', () => { const validatorAPI = { setValidatorGeneratorKey: jest.fn(), registerValidatorKeys: jest.fn().mockResolvedValue(true), - getValidatorAccount: jest - .fn() - .mockResolvedValue({ blsKey: getRandomBytes(48), generatorKey: getRandomBytes(32) }), + getValidatorAccount: jest.fn().mockResolvedValue({ + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), + }), getGeneratorsBetweenTimestamps: jest.fn(), }; const tokenAPI = { @@ -655,9 +656,9 @@ describe('DPoS module', () => { ); } const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); - await snapshotStore.set(intToBuffer(10, 4), Buffer.alloc(10)); - await snapshotStore.set(intToBuffer(11, 4), Buffer.alloc(10)); - await snapshotStore.set(intToBuffer(12, 4), Buffer.alloc(10)); + await snapshotStore.set(utils.intToBuffer(10, 4), Buffer.alloc(10)); + await snapshotStore.set(utils.intToBuffer(11, 4), Buffer.alloc(10)); + await snapshotStore.set(utils.intToBuffer(12, 4), Buffer.alloc(10)); context = createBlockContext({ stateStore, header: createFakeBlockHeader({ height: 1030 }), @@ -695,9 +696,9 @@ describe('DPoS module', () => { it('should create a snapshot which remove the snapshot older than 3 rounds', async () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); - await expect(snapshotStore.has(intToBuffer(10, 4))).resolves.toBeFalse(); - await expect(snapshotStore.has(intToBuffer(11, 4))).resolves.toBeTrue(); - await expect(snapshotStore.has(intToBuffer(12, 4))).resolves.toBeTrue(); + await expect(snapshotStore.has(utils.intToBuffer(10, 4))).resolves.toBeFalse(); + await expect(snapshotStore.has(utils.intToBuffer(11, 4))).resolves.toBeTrue(); + await expect(snapshotStore.has(utils.intToBuffer(12, 4))).resolves.toBeTrue(); }); }); }); @@ -769,8 +770,8 @@ describe('DPoS module', () => { setValidatorGeneratorKey: jest.fn(), registerValidatorKeys: jest.fn(), getValidatorAccount: jest.fn().mockResolvedValue({ - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }), getGeneratorsBetweenTimestamps: jest.fn(), }; @@ -848,9 +849,10 @@ describe('DPoS module', () => { validatorAPI = { setValidatorGeneratorKey: jest.fn(), registerValidatorKeys: jest.fn(), - getValidatorAccount: jest - .fn() - .mockResolvedValue({ blsKey: getRandomBytes(48), generatorKey: getRandomBytes(32) }), + getValidatorAccount: jest.fn().mockResolvedValue({ + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), + }), getGeneratorsBetweenTimestamps: jest.fn(), }; const tokenAPI = { @@ -938,7 +940,7 @@ describe('DPoS module', () => { pomHeights: [], consecutiveMissedBlocks: 0, })); - delegateAddresses = Array.from({ length: 103 }, _ => getRandomBytes(20)); + delegateAddresses = Array.from({ length: 103 }, _ => utils.getRandomBytes(20)); previousTimestampStore = stateStore.getStore( MODULE_ID_DPOS_BUFFER, diff --git a/framework/test/unit/modules/dpos_v2/update_generator_key.spec.ts b/framework/test/unit/modules/dpos_v2/update_generator_key.spec.ts index 646d845d05b..83fe2c197c0 100644 --- a/framework/test/unit/modules/dpos_v2/update_generator_key.spec.ts +++ b/framework/test/unit/modules/dpos_v2/update_generator_key.spec.ts @@ -37,12 +37,12 @@ describe('Update generator key command', () => { let delegateSubstore: PrefixedStateReadWriter; const transactionParams = codec.encode(updateGeneratorKeyCommandParamsSchema, { - generatorKey: getRandomBytes(32), + generatorKey: utils.getRandomBytes(32), }); - const publicKey = getRandomBytes(32); + const publicKey = utils.getRandomBytes(32); const transaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_UPDATE_GENERATOR_KEY, 4), + commandID: utils.intToBuffer(COMMAND_ID_UPDATE_GENERATOR_KEY, 4), senderPublicKey: publicKey, nonce: BigInt(0), fee: BigInt(100000000), @@ -93,11 +93,11 @@ describe('Update generator key command', () => { it('should return error if generatorKey is invalid', async () => { const invalidParams = codec.encode(updateGeneratorKeyCommandParamsSchema, { - generatorKey: getRandomBytes(64), + generatorKey: utils.getRandomBytes(64), }); const invalidTransaction = new Transaction({ moduleID: MODULE_ID_DPOS_BUFFER, - commandID: intToBuffer(COMMAND_ID_UPDATE_GENERATOR_KEY, 4), + commandID: utils.intToBuffer(COMMAND_ID_UPDATE_GENERATOR_KEY, 4), senderPublicKey: publicKey, nonce: BigInt(0), fee: BigInt(100000000), diff --git a/framework/test/unit/modules/fee/fee_module.spec.ts b/framework/test/unit/modules/fee/fee_module.spec.ts index 982b0af9171..58a1d14338a 100644 --- a/framework/test/unit/modules/fee/fee_module.spec.ts +++ b/framework/test/unit/modules/fee/fee_module.spec.ts @@ -28,14 +28,16 @@ describe('FeeModule', () => { genesisConfig = { baseFees: [ { - commandID: intToBuffer(0, 4), + commandID: utils.intToBuffer(0, 4), baseFee: '1', - moduleID: intToBuffer(5, 4), + moduleID: utils.intToBuffer(5, 4), }, ], minFeePerByte: 1000, }; - moduleConfig = { feeTokenID: { chainID: intToBuffer(0, 4), localID: intToBuffer(0, 4) } }; + moduleConfig = { + feeTokenID: { chainID: utils.intToBuffer(0, 4), localID: utils.intToBuffer(0, 4) }, + }; generatorConfig = {}; feeModule = new FeeModule(); await feeModule.init({ genesisConfig, moduleConfig, generatorConfig }); @@ -66,13 +68,13 @@ describe('FeeModule', () => { describe('verifyTransaction', () => { it('should validate transaction with sufficient min fee', async () => { const transaction = new Transaction({ - moduleID: intToBuffer(5, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(5, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(1000000000), nonce: BigInt(0), - senderPublicKey: getRandomBytes(32), - signatures: [getRandomBytes(20)], - params: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), + signatures: [utils.getRandomBytes(20)], + params: utils.getRandomBytes(32), }); const context = createTransactionContext({ transaction }); const transactionVerifyContext = context.createTransactionVerifyContext(); @@ -84,13 +86,13 @@ describe('FeeModule', () => { it('should validate transaction with exactly the min fee', async () => { const exactMinFee = BigInt(108001); const transaction = new Transaction({ - moduleID: intToBuffer(5, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(5, 4), + commandID: utils.intToBuffer(0, 4), fee: exactMinFee, nonce: BigInt(0), - senderPublicKey: getRandomBytes(32), - signatures: [getRandomBytes(20)], - params: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), + signatures: [utils.getRandomBytes(20)], + params: utils.getRandomBytes(32), }); const context = createTransactionContext({ transaction }); const transactionVerifyContext = context.createTransactionVerifyContext(); @@ -101,13 +103,13 @@ describe('FeeModule', () => { it('should invalidate transaction with insufficient min fee', async () => { const transaction = new Transaction({ - moduleID: intToBuffer(5, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(5, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(0), nonce: BigInt(0), - senderPublicKey: getRandomBytes(32), - signatures: [getRandomBytes(20)], - params: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), + signatures: [utils.getRandomBytes(20)], + params: utils.getRandomBytes(32), }); const result = await feeModule.verifyTransaction({ transaction } as any); const expectedMinFee = @@ -126,17 +128,17 @@ describe('FeeModule', () => { jest.spyOn(feeModule['_tokenAPI'], 'isNative').mockResolvedValue(true); const transaction = new Transaction({ - moduleID: intToBuffer(5, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(5, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(1000000000), nonce: BigInt(0), - senderPublicKey: getRandomBytes(32), - signatures: [getRandomBytes(20)], - params: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), + signatures: [utils.getRandomBytes(20)], + params: utils.getRandomBytes(32), }); const context = createTransactionContext({ transaction }); const transactionExecuteContext = context.createTransactionExecuteContext(); - const senderAddress = getAddressFromPublicKey(context.transaction.senderPublicKey); + const senderAddress = address.getAddressFromPublicKey(context.transaction.senderPublicKey); const minFee = BigInt(feeModule['_minFeePerByte'] * transaction.getBytes().length) + feeModule['_extraFee'](transaction.moduleID, transaction.commandID); @@ -160,17 +162,17 @@ describe('FeeModule', () => { it('should transfer transaction fee to generator and not burn min fee when non-native token', async () => { jest.spyOn(feeModule['_tokenAPI'], 'isNative').mockResolvedValue(false); const transaction = new Transaction({ - moduleID: intToBuffer(5, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(5, 4), + commandID: utils.intToBuffer(0, 4), fee: BigInt(1000000000), nonce: BigInt(0), - senderPublicKey: getRandomBytes(32), - signatures: [getRandomBytes(20)], - params: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), + signatures: [utils.getRandomBytes(20)], + params: utils.getRandomBytes(32), }); const context = createTransactionContext({ transaction }); const transactionExecuteContext = context.createTransactionExecuteContext(); - const senderAddress = getAddressFromPublicKey(context.transaction.senderPublicKey); + const senderAddress = address.getAddressFromPublicKey(context.transaction.senderPublicKey); await feeModule.beforeCommandExecute(transactionExecuteContext); diff --git a/framework/test/unit/modules/interoperability/mainchain/api.spec.ts b/framework/test/unit/modules/interoperability/mainchain/api.spec.ts index 6f22aea4739..de01f804234 100644 --- a/framework/test/unit/modules/interoperability/mainchain/api.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/api.spec.ts @@ -12,13 +12,13 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { MainchainInteroperabilityAPI } from '../../../../../src/modules/interoperability/mainchain/api'; import { MainchainInteroperabilityStore } from '../../../../../src/modules/interoperability/mainchain/store'; describe('Mainchain API', () => { - const moduleID = intToBuffer(1, 4); - const chainID = intToBuffer(1, 4); + const moduleID = utils.intToBuffer(1, 4); + const chainID = utils.intToBuffer(1, 4); const interoperableCCAPIs = new Map(); const getStore = jest.fn().mockReturnValue({ getWithSchema: jest.fn() }); const apiContext = { diff --git a/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts b/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts index eaddff35ad7..c77c11f80d9 100644 --- a/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts @@ -32,13 +32,13 @@ describe('MainchainCCChannelTerminatedCommand', () => { const ccAPIsMap = new Map(); ccAPIsMap.set(1, ccAPIMod1); ccAPIsMap.set(2, ccAPIMod2); - const networkIdentifier = getRandomBytes(32); + const networkIdentifier = utils.getRandomBytes(32); const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(20000), status: 0, params: Buffer.alloc(0), diff --git a/framework/test/unit/modules/interoperability/mainchain/cc_commands/registration.spec.ts b/framework/test/unit/modules/interoperability/mainchain/cc_commands/registration.spec.ts index c1f65782251..932efa6f61e 100644 --- a/framework/test/unit/modules/interoperability/mainchain/cc_commands/registration.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/cc_commands/registration.spec.ts @@ -27,7 +27,7 @@ describe('MainchainCCRegistrationCommand', () => { const ownChainAccount = { name: 'mainchain', - id: intToBuffer(1, 4), + id: utils.intToBuffer(1, 4), nonce: BigInt(0), }; @@ -45,14 +45,14 @@ describe('MainchainCCRegistrationCommand', () => { ccAPIsMap.set(1, ccAPIMod1); ccAPIsMap.set(2, ccAPIMod2); - const networkIdentifier = getRandomBytes(32); + const networkIdentifier = utils.getRandomBytes(32); const ccmRegistrationParams = { networkID: networkIdentifier, name: ownChainAccount.name, messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(0, 4), }, }; @@ -63,10 +63,10 @@ describe('MainchainCCRegistrationCommand', () => { const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(1, 4), fee: BigInt(20000), status: 0, params: encodedRegistrationParams, @@ -78,8 +78,8 @@ describe('MainchainCCRegistrationCommand', () => { size: 1, }, messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(0, 4), }, outbox: { appendPath: [], @@ -106,7 +106,7 @@ describe('MainchainCCRegistrationCommand', () => { mainchainInteroperabilityStore.getChannel = getChannelMock; mainchainInteroperabilityStore.getOwnChainAccount = getOwnChainAccountMock; - ccRegistrationCommand = new MainchainCCRegistrationCommand(intToBuffer(1, 4), ccAPIsMap); + ccRegistrationCommand = new MainchainCCRegistrationCommand(utils.intToBuffer(1, 4), ccAPIsMap); (ccRegistrationCommand as any)['getInteroperabilityStore'] = jest .fn() .mockReturnValue(mainchainInteroperabilityStore); @@ -121,8 +121,8 @@ describe('MainchainCCRegistrationCommand', () => { size: 2, }, messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(0, 4), }, outbox: { appendPath: [], @@ -152,10 +152,10 @@ describe('MainchainCCRegistrationCommand', () => { // Arrange const invalidCCM = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(1, 4), fee: BigInt(20000), status: 1, params: encodedRegistrationParams, @@ -179,7 +179,7 @@ describe('MainchainCCRegistrationCommand', () => { // Arrange getChannelMock.mockResolvedValue(channelData); - getOwnChainAccountMock.mockResolvedValue({ ...ownChainAccount, id: intToBuffer(3, 4) }); + getOwnChainAccountMock.mockResolvedValue({ ...ownChainAccount, id: utils.intToBuffer(3, 4) }); await ccRegistrationCommand.execute(sampleExecuteContext); @@ -220,8 +220,8 @@ describe('MainchainCCRegistrationCommand', () => { size: 2, }, messageFeeTokenID: { - chainID: intToBuffer(3, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(3, 4), + localID: utils.intToBuffer(0, 4), }, outbox: { appendPath: [], @@ -255,8 +255,8 @@ describe('MainchainCCRegistrationCommand', () => { size: 2, }, messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(5, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(5, 4), }, outbox: { appendPath: [], @@ -287,7 +287,7 @@ describe('MainchainCCRegistrationCommand', () => { getOwnChainAccountMock.mockResolvedValue(ownChainAccount); - const differentNetworkID = getRandomBytes(32); + const differentNetworkID = utils.getRandomBytes(32); await ccRegistrationCommand.execute({ ...sampleExecuteContext, networkIdentifier: differentNetworkID, @@ -307,10 +307,10 @@ describe('MainchainCCRegistrationCommand', () => { // Arrange const invalidCCM = { nonce: BigInt(1), // nonce not equal to 0 - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(1, 4), fee: BigInt(20000), status: 0, params: encodedRegistrationParams, diff --git a/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts b/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts index 078b7047da0..e9e6eae633a 100644 --- a/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts @@ -40,11 +40,11 @@ describe('MainchainCCSidechainTerminatedCommand', () => { ccAPIsMap.set(1, ccAPIMod1); ccAPIsMap.set(2, ccAPIMod2); - const networkIdentifier = getRandomBytes(32); + const networkIdentifier = utils.getRandomBytes(32); const ccmSidechainTerminatedParams = { - chainID: intToBuffer(5, 4), - stateRoot: getRandomBytes(32), + chainID: utils.intToBuffer(5, 4), + stateRoot: utils.getRandomBytes(32), }; const encodedSidechainTerminatedParams = codec.encode( @@ -54,17 +54,17 @@ describe('MainchainCCSidechainTerminatedCommand', () => { const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), sendingChainID: MAINCHAIN_ID_BUFFER, - receivingChainID: intToBuffer(1, 4), + receivingChainID: utils.intToBuffer(1, 4), fee: BigInt(20000), status: 0, params: encodedSidechainTerminatedParams, }; const ccmNew = { ...ccm, - sendingChainID: intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(2, 4), }; const sampleExecuteContext: CCCommandExecuteContext = createExecuteCCMsgAPIContext({ ccm, diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/cc_update.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/cc_update.spec.ts index dd5e54975c5..c1dc2d462f6 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/cc_update.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/cc_update.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { when } from 'jest-when'; import * as cryptography from '@liskhq/lisk-cryptography'; import { BlockAssets } from '@liskhq/lisk-chain'; @@ -65,49 +65,49 @@ jest.mock('@liskhq/lisk-cryptography', () => ({ describe('CrossChainUpdateCommand', () => { const getAPIContextMock = jest.fn(); const getStoreMock = jest.fn(); - const moduleID = intToBuffer(1, 4); - const networkIdentifier = cryptography.getRandomBytes(32); + const moduleID = utils.intToBuffer(1, 4); + const networkIdentifier = cryptography.utils.getRandomBytes(32); const defaultCertificateValues: Certificate = { - blockID: cryptography.getRandomBytes(20), + blockID: cryptography.utils.getRandomBytes(20), height: 21, timestamp: Math.floor(Date.now() / 1000), - stateRoot: cryptography.getRandomBytes(38), - validatorsHash: cryptography.getRandomBytes(48), - aggregationBits: cryptography.getRandomBytes(38), - signature: cryptography.getRandomBytes(32), + stateRoot: cryptography.utils.getRandomBytes(38), + validatorsHash: cryptography.utils.getRandomBytes(48), + aggregationBits: cryptography.utils.getRandomBytes(38), + signature: cryptography.utils.getRandomBytes(32), }; const defaultNewCertificateThreshold = BigInt(20); const defaultSendingChainID = 20; - const defaultSendingChainIDBuffer = cryptography.intToBuffer(defaultSendingChainID, 4); + const defaultSendingChainIDBuffer = cryptography.utils.intToBuffer(defaultSendingChainID, 4); const defaultCCMs: CCMsg[] = [ { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(2), - receivingChainID: intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(2, 4), sendingChainID: defaultSendingChainIDBuffer, status: CCM_STATUS_OK, }, { - crossChainCommandID: intToBuffer(2, 4), + crossChainCommandID: utils.intToBuffer(2, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(2), - receivingChainID: intToBuffer(3, 4), + receivingChainID: utils.intToBuffer(3, 4), sendingChainID: defaultSendingChainIDBuffer, status: CCM_STATUS_OK, }, { - crossChainCommandID: intToBuffer(3, 4), + crossChainCommandID: utils.intToBuffer(3, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(2), - receivingChainID: intToBuffer(4, 4), + receivingChainID: utils.intToBuffer(4, 4), sendingChainID: defaultSendingChainIDBuffer, status: CCM_STATUS_OK, }, @@ -124,7 +124,7 @@ describe('CrossChainUpdateCommand', () => { siblingHashes: [Buffer.alloc(1)], }, }; - const defaultTransaction = { moduleID: intToBuffer(1, 4) }; + const defaultTransaction = { moduleID: utils.intToBuffer(1, 4) }; const partnerChainStore = { getWithSchema: jest.fn(), @@ -151,10 +151,10 @@ describe('CrossChainUpdateCommand', () => { beforeEach(async () => { activeValidatorsUpdate = [ - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(1) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(3) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(4) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(3) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(1) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(3) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(4) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(3) }, ].sort((v1, v2) => v2.blsKey.compare(v1.blsKey)); // unsorted list const partnerValidators: any = { @@ -183,27 +183,27 @@ describe('CrossChainUpdateCommand', () => { partnerChainAccount = { lastCertificate: { height: 10, - stateRoot: cryptography.getRandomBytes(38), + stateRoot: cryptography.utils.getRandomBytes(38), timestamp: Math.floor(Date.now() / 1000), - validatorsHash: cryptography.getRandomBytes(48), + validatorsHash: cryptography.utils.getRandomBytes(48), }, name: 'sidechain1', - networkID: cryptography.getRandomBytes(32), + networkID: cryptography.utils.getRandomBytes(32), status: CHAIN_ACTIVE, }; partnerChannelAccount = { inbox: { appendPath: [Buffer.alloc(1), Buffer.alloc(1)], - root: cryptography.getRandomBytes(38), + root: cryptography.utils.getRandomBytes(38), size: 18, }, - messageFeeTokenID: { chainID: intToBuffer(1, 4), localID: intToBuffer(0, 4) }, + messageFeeTokenID: { chainID: utils.intToBuffer(1, 4), localID: utils.intToBuffer(0, 4) }, outbox: { appendPath: [Buffer.alloc(1), Buffer.alloc(1)], - root: cryptography.getRandomBytes(38), + root: cryptography.utils.getRandomBytes(38), size: 18, }, - partnerChainOutboxRoot: cryptography.getRandomBytes(38), + partnerChainOutboxRoot: cryptography.utils.getRandomBytes(38), }; params = { @@ -326,7 +326,7 @@ describe('CrossChainUpdateCommand', () => { it('should return VerifyStatus.FAIL when checkValidatorsHashWithCertificate() throws error', async () => { const certificateWithIncorrectValidatorHash = codec.encode(certificateSchema, { ...defaultCertificateValues, - validatorsHash: cryptography.getRandomBytes(48), + validatorsHash: cryptography.utils.getRandomBytes(48), }); const { status, error } = await mainchainCCUUpdateCommand.verify({ @@ -493,13 +493,13 @@ describe('CrossChainUpdateCommand', () => { it('should call terminateChainInternal() for a ccm when txParams.sendingChainID !== ccm.deserilized.sendingChainID', async () => { const invalidCCM = codec.encode(ccmSchema, { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(2), - receivingChainID: intToBuffer(1, 4), - sendingChainID: intToBuffer(50, 4), + receivingChainID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(50, 4), status: CCM_STATUS_OK, }); jest @@ -523,12 +523,12 @@ describe('CrossChainUpdateCommand', () => { it('should call terminateChainInternal() for a ccm when it fails on validateFormat', async () => { const invalidCCM = { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(MAX_CCM_SIZE + 10), - receivingChainID: intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(2, 4), sendingChainID: defaultSendingChainIDBuffer, status: CCM_STATUS_OK, }; @@ -562,12 +562,12 @@ describe('CrossChainUpdateCommand', () => { it('should call forward() when ccm.deserilized.receivingChainID !== MAINCHAIN_ID', async () => { const nonMainchainCCM = { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(10), - receivingChainID: intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(2, 4), sendingChainID: defaultSendingChainIDBuffer, status: CCM_STATUS_OK, }; @@ -601,9 +601,9 @@ describe('CrossChainUpdateCommand', () => { it('should call apply() when ccm.deserilized.receivingChainID === MAINCHAIN_ID', async () => { const mainchainCCM = { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(10), receivingChainID: MAINCHAIN_ID_BUFFER, diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/message_recovery.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/message_recovery.spec.ts index dbf1cfe8c11..075044257ca 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/message_recovery.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/message_recovery.spec.ts @@ -94,20 +94,20 @@ describe('Mainchain MessageRecoveryCommand', () => { ccms = [ { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 0, params: Buffer.alloc(0), }, { nonce: BigInt(1), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(4, 4), - receivingChainID: intToBuffer(5, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(4, 4), + receivingChainID: utils.intToBuffer(5, 4), fee: BigInt(2), status: 0, params: Buffer.alloc(0), @@ -122,7 +122,7 @@ describe('Mainchain MessageRecoveryCommand', () => { [LEAF_PREFIX, data], LEAF_PREFIX.length + data.length, ); - const leafHash = hash(leafValueWithoutNodeIndex); + const leafHash = utils.hash(leafValueWithoutNodeIndex); queryHashes.push(leafHash); } generatedProof = await merkleTree.generateProof(queryHashes); @@ -132,10 +132,10 @@ describe('Mainchain MessageRecoveryCommand', () => { indexes: generatedProof.idxs as number[], siblingHashes: generatedProof.siblingHashes as Buffer[], }; - hashedCCMs = ccmsEncoded.map(ccm => hash(ccm)); + hashedCCMs = ccmsEncoded.map(ccm => utils.hash(ccm)); outboxRoot = regularMerkleTree.calculateRootFromUpdateData(hashedCCMs, proof); transactionParams = { - chainID: intToBuffer(3, 4), + chainID: utils.intToBuffer(3, 4), crossChainMessages: [...ccmsEncoded], idxs: proof.indexes, siblingHashes: proof.siblingHashes, @@ -149,7 +149,7 @@ describe('Mainchain MessageRecoveryCommand', () => { fee: BigInt(100000000), nonce: BigInt(0), params: encodedTransactionParams, - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [], }); commandVerifyContext = createTransactionContext({ @@ -175,7 +175,7 @@ describe('Mainchain MessageRecoveryCommand', () => { await terminatedOutboxSubstore.setWithSchema( chainID, { - outboxRoot: getRandomBytes(32), + outboxRoot: utils.getRandomBytes(32), outboxSize: terminatedChainOutboxSize, partnerChainInboxSize: 1, }, @@ -204,7 +204,7 @@ describe('Mainchain MessageRecoveryCommand', () => { fee: BigInt(100000000), nonce: BigInt(0), params: encodedTransactionParams, - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [], }); commandVerifyContext = createTransactionContext({ @@ -221,20 +221,20 @@ describe('Mainchain MessageRecoveryCommand', () => { ccms = [ { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), }, { nonce: BigInt(1), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(4, 4), - receivingChainID: intToBuffer(5, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(4, 4), + receivingChainID: utils.intToBuffer(5, 4), fee: BigInt(2), status: 0, params: Buffer.alloc(0), @@ -249,7 +249,7 @@ describe('Mainchain MessageRecoveryCommand', () => { [LEAF_PREFIX, data], LEAF_PREFIX.length + data.length, ); - const leafHash = hash(leafValueWithoutNodeIndex); + const leafHash = utils.hash(leafValueWithoutNodeIndex); queryHashes.push(leafHash); } generatedProof = await merkleTree.generateProof(queryHashes); @@ -259,10 +259,10 @@ describe('Mainchain MessageRecoveryCommand', () => { indexes: generatedProof.idxs as number[], siblingHashes: generatedProof.siblingHashes as Buffer[], }; - hashedCCMs = ccmsEncoded.map(ccm => hash(ccm)); + hashedCCMs = ccmsEncoded.map(ccm => utils.hash(ccm)); outboxRoot = regularMerkleTree.calculateRootFromUpdateData(hashedCCMs, proof); transactionParams = { - chainID: intToBuffer(3, 4), + chainID: utils.intToBuffer(3, 4), crossChainMessages: [...ccmsEncoded], idxs: proof.indexes, siblingHashes: proof.siblingHashes, @@ -274,7 +274,7 @@ describe('Mainchain MessageRecoveryCommand', () => { fee: BigInt(100000000), nonce: BigInt(0), params: encodedTransactionParams, - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [], }); commandVerifyContext = createTransactionContext({ @@ -310,10 +310,10 @@ describe('Mainchain MessageRecoveryCommand', () => { const ccmsEncoded = ccms.map(ccm => codec.encode(ccmSchema, ccm)); transactionParams = { - chainID: intToBuffer(3, 4), + chainID: utils.intToBuffer(3, 4), crossChainMessages: [...ccmsEncoded], idxs: [0], - siblingHashes: [getRandomBytes(32)], + siblingHashes: [utils.getRandomBytes(32)], }; encodedTransactionParams = codec.encode(messageRecoveryParamsSchema, transactionParams); @@ -324,7 +324,7 @@ describe('Mainchain MessageRecoveryCommand', () => { fee: BigInt(100000000), nonce: BigInt(0), params: encodedTransactionParams, - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [], }); @@ -351,8 +351,8 @@ describe('Mainchain MessageRecoveryCommand', () => { | 'getOwnChainAccount' >; - const moduleID = intToBuffer(1, 4); - const networkID = getRandomBytes(32); + const moduleID = utils.intToBuffer(1, 4); + const networkID = utils.getRandomBytes(32); let messageRecoveryCommand: MainchainMessageRecoveryCommand; let commandExecuteContext: CommandExecuteContext; @@ -379,19 +379,19 @@ describe('Mainchain MessageRecoveryCommand', () => { { nonce: BigInt(0), moduleID, - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), }, { nonce: BigInt(1), - moduleID: intToBuffer(moduleID.readInt32BE(0) + 1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(moduleID.readInt32BE(0) + 1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), @@ -413,7 +413,7 @@ describe('Mainchain MessageRecoveryCommand', () => { storeMock.getOwnChainAccount.mockResolvedValue({ name: `mainchain`, - id: intToBuffer(0, 4), + id: utils.intToBuffer(0, 4), nonce: BigInt(0), }); @@ -448,7 +448,7 @@ describe('Mainchain MessageRecoveryCommand', () => { when(storeMock.getTerminatedOutboxAccount) .calledWith(chainID) .mockResolvedValue({ - outboxRoot: getRandomBytes(32), + outboxRoot: utils.getRandomBytes(32), outboxSize: 1, partnerChainInboxSize: 1, }); @@ -573,7 +573,7 @@ describe('Mainchain MessageRecoveryCommand', () => { commandExecuteContext = createCommandExecuteContext( ccms.map(ccm => ({ ...ccm, - receivingChainID: intToBuffer(0, 4), + receivingChainID: utils.intToBuffer(0, 4), })), ); @@ -607,14 +607,14 @@ describe('Mainchain MessageRecoveryCommand', () => { commandExecuteContext = createCommandExecuteContext( ccms.map(ccm => ({ ...ccm, - receivingChainID: intToBuffer(0, 4), + receivingChainID: utils.intToBuffer(0, 4), })), ); for (const ccm of ccms) { ccCommands.set(ccm.moduleID.readInt32BE(0), ([ { - ID: intToBuffer(500, 4), + ID: utils.intToBuffer(500, 4), execute: jest.fn(), }, ] as unknown) as BaseCCCommand[]); @@ -638,7 +638,7 @@ describe('Mainchain MessageRecoveryCommand', () => { commandExecuteContext = createCommandExecuteContext( ccms.map(ccm => ({ ...ccm, - receivingChainID: intToBuffer(0, 4), + receivingChainID: utils.intToBuffer(0, 4), })), ); diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/sidechain_registration.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/sidechain_registration.spec.ts index 9a0f6eea21f..9079f354bfa 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/sidechain_registration.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/sidechain_registration.spec.ts @@ -79,7 +79,7 @@ describe('Sidechain registration command', () => { certificateThreshold: BigInt(10), }; const encodedTransactionParams = codec.encode(sidechainRegParams, transactionParams); - const publicKey = getRandomBytes(32); + const publicKey = utils.getRandomBytes(32); const transaction = new Transaction({ moduleID: MODULE_ID_INTEROPERABILITY_BUFFER, commandID: COMMAND_ID_SIDECHAIN_REG_BUFFER, @@ -93,7 +93,7 @@ describe('Sidechain registration command', () => { 'e48feb88db5b5cf5ad71d93cdcd1d879b6d5ed187a36b0002cc34e0ef9883255', 'hex', ); - const networkID = hash(Buffer.concat([Buffer.alloc(0), transaction.senderAddress])); + const networkID = utils.hash(Buffer.concat([Buffer.alloc(0), transaction.senderAddress])); let sidechainRegistrationCommand: SidechainRegistrationCommand; let stateStore: PrefixedStateReadWriter; let nameSubstore: SubStore; @@ -156,7 +156,7 @@ describe('Sidechain registration command', () => { it('should return error if store key name already exists in name store', async () => { await nameSubstore.setWithSchema( Buffer.from(transactionParams.name, 'utf8'), - { chainID: intToBuffer(0, 4) }, + { chainID: utils.intToBuffer(0, 4) }, nameSchema, ); const result = await sidechainRegistrationCommand.verify(verifyContext); @@ -170,7 +170,7 @@ describe('Sidechain registration command', () => { it('should return error if store key networkID already exists in networkID store', async () => { await networkIDSubstore.setWithSchema( networkID, - { chainID: intToBuffer(0, 4) }, + { chainID: utils.intToBuffer(0, 4) }, chainIDSchema, ); @@ -184,7 +184,7 @@ describe('Sidechain registration command', () => { it(`should return error if initValidators array count exceeds ${MAX_NUM_VALIDATORS}`, async () => { verifyContext.params.initValidators = new Array(MAX_NUM_VALIDATORS + 2).fill({ - blsKey: getRandomBytes(48), + blsKey: utils.getRandomBytes(48), bftWeight: BigInt(1), }); const result = await sidechainRegistrationCommand.verify(verifyContext); @@ -207,7 +207,7 @@ describe('Sidechain registration command', () => { it('should return error if bls key is below minimum length', async () => { verifyContext.params.initValidators = [ { - blsKey: getRandomBytes(2), + blsKey: utils.getRandomBytes(2), bftWeight: BigInt(10), }, ]; @@ -223,7 +223,7 @@ describe('Sidechain registration command', () => { it('should return error if bls key is above maximum length', async () => { verifyContext.params.initValidators = [ { - blsKey: getRandomBytes(50), + blsKey: utils.getRandomBytes(50), bftWeight: BigInt(10), }, ]; @@ -357,7 +357,7 @@ describe('Sidechain registration command', () => { describe('execute', () => { const genesisBlockID = Buffer.alloc(0); - const newChainID = intToBuffer(2, 4); + const newChainID = utils.intToBuffer(2, 4); const existingChainID = Buffer.alloc(4); existingChainID.writeUInt32BE(1, 0); const params = { @@ -495,7 +495,7 @@ describe('Sidechain registration command', () => { inbox: { root: EMPTY_HASH, appendPath: [], size: 0 }, outbox: { root: EMPTY_HASH, appendPath: [], size: 0 }, partnerChainOutboxRoot: EMPTY_HASH, - messageFeeTokenID: { chainID: intToBuffer(1, 4), localID: intToBuffer(0, 4) }, + messageFeeTokenID: { chainID: utils.intToBuffer(1, 4), localID: utils.intToBuffer(0, 4) }, }; // Act @@ -511,11 +511,11 @@ describe('Sidechain registration command', () => { it('should call sendInternal with a registration ccm', async () => { // Arrange - const receivingChainID = intToBuffer(2, 4); + const receivingChainID = utils.intToBuffer(2, 4); const encodedParams = codec.encode(registrationCCMParamsSchema, { networkID, name: chainAccount.name, - messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: intToBuffer(0, 4) }, + messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: utils.intToBuffer(0, 4) }, }); // Act diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery.spec.ts index 0bd55cd3bf9..66141a15232 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery.spec.ts @@ -58,7 +58,7 @@ describe('Mainchain StateRecoveryCommand', () => { beforeEach(async () => { interoperableCCAPIs = new Map(); interoperableAPI = { - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), recover: jest.fn(), }; interoperableCCAPIs.set(1, interoperableAPI); @@ -69,17 +69,17 @@ describe('Mainchain StateRecoveryCommand', () => { ccCommands, ); transactionParams = { - chainID: intToBuffer(3, 4), - moduleID: intToBuffer(1, 4), + chainID: utils.intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), storeEntries: [ { storePrefix: 1, - storeKey: getRandomBytes(32), - storeValue: getRandomBytes(32), - bitmap: getRandomBytes(32), + storeKey: utils.getRandomBytes(32), + storeValue: utils.getRandomBytes(32), + bitmap: utils.getRandomBytes(32), }, ], - siblingHashes: [getRandomBytes(32)], + siblingHashes: [utils.getRandomBytes(32)], }; chainIDAsBuffer = transactionParams.chainID; encodedTransactionParams = codec.encode(stateRecoveryParamsSchema, transactionParams); @@ -89,7 +89,7 @@ describe('Mainchain StateRecoveryCommand', () => { fee: BigInt(100000000), nonce: BigInt(0), params: encodedTransactionParams, - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [], }); stateStore = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); @@ -120,7 +120,7 @@ describe('Mainchain StateRecoveryCommand', () => { stateRecoveryParamsSchema, ); jest.spyOn(sparseMerkleTree, 'verify').mockReturnValue(true); - jest.spyOn(sparseMerkleTree, 'calculateRoot').mockReturnValue(getRandomBytes(32)); + jest.spyOn(sparseMerkleTree, 'calculateRoot').mockReturnValue(utils.getRandomBytes(32)); }); describe('verify', () => { @@ -181,7 +181,7 @@ describe('Mainchain StateRecoveryCommand', () => { }); it('should set root value for terminated state substore', async () => { - const newStateRoot = getRandomBytes(32); + const newStateRoot = utils.getRandomBytes(32); jest.spyOn(sparseMerkleTree, 'calculateRoot').mockReturnValue(newStateRoot); await stateRecoveryCommand.execute(commandExecuteContext); diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery_init.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery_init.spec.ts index 1855e66a8b1..b05d17c1dbf 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery_init.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery_init.spec.ts @@ -48,7 +48,7 @@ describe('Mainchain StateRecoveryInitCommand', () => { | 'getChainAccount' >; - const networkID = getRandomBytes(32); + const networkID = utils.getRandomBytes(32); let stateRecoveryInitCommand: StateRecoveryInitCommand; let commandExecuteContext: CommandExecuteContext; @@ -77,9 +77,9 @@ describe('Mainchain StateRecoveryInitCommand', () => { networkID, lastCertificate: { height: 10, - stateRoot: getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), timestamp: 100, - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }, status: CHAIN_TERMINATED, }; @@ -87,7 +87,7 @@ describe('Mainchain StateRecoveryInitCommand', () => { sidechainChainAccountEncoded = codec.encode(chainAccountSchema, sidechainChainAccount); transactionParams = { - chainID: intToBuffer(3, 4), + chainID: utils.intToBuffer(3, 4), bitmap: Buffer.alloc(0), siblingHashes: [], sidechainChainAccount: sidechainChainAccountEncoded, @@ -101,7 +101,7 @@ describe('Mainchain StateRecoveryInitCommand', () => { fee: BigInt(100000000), nonce: BigInt(0), params: encodedTransactionParams, - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [], }); @@ -152,9 +152,9 @@ describe('Mainchain StateRecoveryInitCommand', () => { networkID, lastCertificate: { height: 10, - stateRoot: getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), timestamp: 100 + LIVENESS_LIMIT, - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }, status: CHAIN_ACTIVE, }; @@ -210,15 +210,15 @@ describe('Mainchain StateRecoveryInitCommand', () => { networkID, lastCertificate: { height: 10, - stateRoot: getRandomBytes(32), + stateRoot: utils.getRandomBytes(32), timestamp: 100, - validatorsHash: getRandomBytes(32), + validatorsHash: utils.getRandomBytes(32), }, status: CHAIN_ACTIVE, }; sidechainChainAccountEncoded = codec.encode(chainAccountSchema, sidechainChainAccount); transactionParams = { - chainID: intToBuffer(3, 4), + chainID: utils.intToBuffer(3, 4), bitmap: Buffer.alloc(0), siblingHashes: [], sidechainChainAccount: sidechainChainAccountEncoded, @@ -230,7 +230,7 @@ describe('Mainchain StateRecoveryInitCommand', () => { fee: BigInt(100000000), nonce: BigInt(0), params: encodedTransactionParams, - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [], }); transactionContext = createTransactionContext({ diff --git a/framework/test/unit/modules/interoperability/mainchain/store.spec.ts b/framework/test/unit/modules/interoperability/mainchain/store.spec.ts index 688f41c6f39..8c3e2d01fca 100644 --- a/framework/test/unit/modules/interoperability/mainchain/store.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/store.spec.ts @@ -132,10 +132,10 @@ describe('Mainchain interoperability store', () => { describe('bounce', () => { const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), @@ -216,21 +216,21 @@ describe('Mainchain interoperability store', () => { const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), }; - const randomOutboxRoot = getRandomBytes(32); + const randomOutboxRoot = utils.getRandomBytes(32); const channelData = { inbox: { appendPath: [], size: 0, - root: getRandomBytes(32), + root: utils.getRandomBytes(32), }, outbox: { appendPath: [], @@ -239,8 +239,8 @@ describe('Mainchain interoperability store', () => { }, partnerChainOutboxRoot: Buffer.alloc(0), messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(2, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(2, 4), }, }; @@ -258,7 +258,7 @@ describe('Mainchain interoperability store', () => { const beforeSendCCMContext = testing.createBeforeSendCCMsgAPIContext({ ccm, - feeAddress: getRandomBytes(32), + feeAddress: utils.getRandomBytes(32), }); const sendInternalContext: SendInternalContext = { @@ -297,10 +297,10 @@ describe('Mainchain interoperability store', () => { it('should return false if the created ccm is of invalid size', async () => { const invalidCCM = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(MAX_CCM_SIZE), // invalid size @@ -308,7 +308,7 @@ describe('Mainchain interoperability store', () => { const beforeSendCCMContextLocal = testing.createBeforeSendCCMsgAPIContext({ ccm: invalidCCM, - feeAddress: getRandomBytes(32), + feeAddress: utils.getRandomBytes(32), }); const sendInternalContextLocal: SendInternalContext = { @@ -334,10 +334,10 @@ describe('Mainchain interoperability store', () => { it('should return false if the ccm created is invalid schema', async () => { const invalidCCM = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 'ccm', // invalid field params: Buffer.alloc(0), @@ -345,7 +345,7 @@ describe('Mainchain interoperability store', () => { const beforeSendCCMContextLocal = testing.createBeforeSendCCMsgAPIContext({ ccm: invalidCCM as any, - feeAddress: getRandomBytes(32), + feeAddress: utils.getRandomBytes(32), }); const sendInternalContextLocal = { @@ -420,7 +420,7 @@ describe('Mainchain interoperability store', () => { receivingChainAccount = { name: 'receivingAccount1', - networkID: getRandomBytes(32), + networkID: utils.getRandomBytes(32), lastCertificate: { height: 567467, timestamp: timestamp - 500000, @@ -432,10 +432,10 @@ describe('Mainchain interoperability store', () => { ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: CCM_STATUS_OK, params: Buffer.alloc(0), @@ -458,7 +458,7 @@ describe('Mainchain interoperability store', () => { }, }, newCertificateThreshold: BigInt(1), - sendingChainID: intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(2, 4), }; context = { diff --git a/framework/test/unit/modules/interoperability/sidechain/api.spec.ts b/framework/test/unit/modules/interoperability/sidechain/api.spec.ts index 14b5146a224..230d3a3f4d5 100644 --- a/framework/test/unit/modules/interoperability/sidechain/api.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/api.spec.ts @@ -12,13 +12,13 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { SidechainInteroperabilityAPI } from '../../../../../src/modules/interoperability/sidechain/api'; import { SidechainInteroperabilityStore } from '../../../../../src/modules/interoperability/sidechain/store'; describe('Sidechain API', () => { - const moduleID = intToBuffer(1, 4); - const chainID = intToBuffer(1, 4); + const moduleID = utils.intToBuffer(1, 4); + const chainID = utils.intToBuffer(1, 4); const interoperableCCAPIs = new Map(); const getStore = jest.fn().mockReturnValue({ getWithSchema: jest.fn() }); const apiContext = { diff --git a/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts b/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts index 93309f16ea7..1ba07e22efb 100644 --- a/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts @@ -32,13 +32,13 @@ describe('SidechainCCChannelTerminatedCommand', () => { const ccAPIsMap = new Map(); ccAPIsMap.set(1, ccAPIMod1); ccAPIsMap.set(2, ccAPIMod2); - const networkIdentifier = getRandomBytes(32); + const networkIdentifier = utils.getRandomBytes(32); const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(20000), status: 0, params: Buffer.alloc(0), diff --git a/framework/test/unit/modules/interoperability/sidechain/cc_commands/registration.spec.ts b/framework/test/unit/modules/interoperability/sidechain/cc_commands/registration.spec.ts index 6cf3499cfb4..f4f33819e20 100644 --- a/framework/test/unit/modules/interoperability/sidechain/cc_commands/registration.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/cc_commands/registration.spec.ts @@ -27,7 +27,7 @@ describe('SidechainCCRegistrationCommand', () => { const ownChainAccount = { name: 'sidechain', - id: intToBuffer(1, 4), + id: utils.intToBuffer(1, 4), nonce: BigInt(0), }; @@ -45,14 +45,14 @@ describe('SidechainCCRegistrationCommand', () => { ccAPIsMap.set(1, ccAPIMod1); ccAPIsMap.set(2, ccAPIMod2); - const networkIdentifier = getRandomBytes(32); + const networkIdentifier = utils.getRandomBytes(32); const ccmRegistrationParams = { networkID: networkIdentifier, name: ownChainAccount.name, messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(0, 4), }, }; @@ -63,10 +63,10 @@ describe('SidechainCCRegistrationCommand', () => { const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(1, 4), fee: BigInt(20000), status: 0, params: encodedRegistrationParams, @@ -78,8 +78,8 @@ describe('SidechainCCRegistrationCommand', () => { size: 1, }, messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(0, 4), }, outbox: { appendPath: [], @@ -106,7 +106,7 @@ describe('SidechainCCRegistrationCommand', () => { sidechainInteroperabilityStore.getChannel = getChannelMock; sidechainInteroperabilityStore.getOwnChainAccount = getOwnChainAccountMock; - ccRegistrationCommand = new SidechainCCRegistrationCommand(intToBuffer(1, 4), ccAPIsMap); + ccRegistrationCommand = new SidechainCCRegistrationCommand(utils.intToBuffer(1, 4), ccAPIsMap); (ccRegistrationCommand as any)['getInteroperabilityStore'] = jest .fn() .mockReturnValue(sidechainInteroperabilityStore); @@ -121,8 +121,8 @@ describe('SidechainCCRegistrationCommand', () => { size: 2, }, messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(0, 4), }, outbox: { appendPath: [], @@ -152,10 +152,10 @@ describe('SidechainCCRegistrationCommand', () => { // Arrange const invalidCCM = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(1, 4), fee: BigInt(20000), status: 1, params: encodedRegistrationParams, @@ -179,7 +179,7 @@ describe('SidechainCCRegistrationCommand', () => { // Arrange getChannelMock.mockResolvedValue(channelData); - getOwnChainAccountMock.mockResolvedValue({ ...ownChainAccount, id: intToBuffer(3, 4) }); + getOwnChainAccountMock.mockResolvedValue({ ...ownChainAccount, id: utils.intToBuffer(3, 4) }); await ccRegistrationCommand.execute(sampleExecuteContext); @@ -220,8 +220,8 @@ describe('SidechainCCRegistrationCommand', () => { size: 2, }, messageFeeTokenID: { - chainID: intToBuffer(3, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(3, 4), + localID: utils.intToBuffer(0, 4), }, outbox: { appendPath: [], @@ -255,8 +255,8 @@ describe('SidechainCCRegistrationCommand', () => { size: 2, }, messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(5, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(5, 4), }, outbox: { appendPath: [], @@ -287,7 +287,7 @@ describe('SidechainCCRegistrationCommand', () => { getOwnChainAccountMock.mockResolvedValue(ownChainAccount); - const differentNetworkID = getRandomBytes(32); + const differentNetworkID = utils.getRandomBytes(32); await ccRegistrationCommand.execute({ ...sampleExecuteContext, networkIdentifier: differentNetworkID, diff --git a/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts b/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts index 585f7cacb44..a36d51926d5 100644 --- a/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts @@ -40,11 +40,11 @@ describe('SidechainCCSidechainTerminatedCommand', () => { ccAPIsMap.set(1, ccAPIMod1); ccAPIsMap.set(2, ccAPIMod2); - const networkIdentifier = getRandomBytes(32); + const networkIdentifier = utils.getRandomBytes(32); const ccmSidechainTerminatedParams = { - chainID: intToBuffer(5, 4), - stateRoot: getRandomBytes(32), + chainID: utils.intToBuffer(5, 4), + stateRoot: utils.getRandomBytes(32), }; const encodedSidechainTerminatedParams = codec.encode( @@ -54,17 +54,17 @@ describe('SidechainCCSidechainTerminatedCommand', () => { const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), sendingChainID: MAINCHAIN_ID_BUFFER, - receivingChainID: intToBuffer(1, 4), + receivingChainID: utils.intToBuffer(1, 4), fee: BigInt(20000), status: 0, params: encodedSidechainTerminatedParams, }; const ccmNew = { ...ccm, - sendingChainID: intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(2, 4), }; const sampleExecuteContext: CCCommandExecuteContext = createExecuteCCMsgAPIContext({ ccm, diff --git a/framework/test/unit/modules/interoperability/sidechain/commands/cc_update.spec.ts b/framework/test/unit/modules/interoperability/sidechain/commands/cc_update.spec.ts index 003069e6843..6f68912c05c 100644 --- a/framework/test/unit/modules/interoperability/sidechain/commands/cc_update.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/commands/cc_update.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { when } from 'jest-when'; import * as cryptography from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; @@ -64,48 +64,48 @@ jest.mock('@liskhq/lisk-cryptography', () => ({ describe('CrossChainUpdateCommand', () => { const getAPIContextMock = jest.fn(); const getStoreMock = jest.fn(); - const moduleID = intToBuffer(1, 4); - const networkIdentifier = cryptography.getRandomBytes(32); + const moduleID = utils.intToBuffer(1, 4); + const networkIdentifier = cryptography.utils.getRandomBytes(32); const defaultCertificateValues: Certificate = { - blockID: cryptography.getRandomBytes(20), + blockID: cryptography.utils.getRandomBytes(20), height: 21, timestamp: Math.floor(Date.now() / 1000), - stateRoot: cryptography.getRandomBytes(38), - validatorsHash: cryptography.getRandomBytes(48), - aggregationBits: cryptography.getRandomBytes(38), - signature: cryptography.getRandomBytes(32), + stateRoot: cryptography.utils.getRandomBytes(38), + validatorsHash: cryptography.utils.getRandomBytes(48), + aggregationBits: cryptography.utils.getRandomBytes(38), + signature: cryptography.utils.getRandomBytes(32), }; const defaultNewCertificateThreshold = BigInt(20); - const defaultSendingChainID = intToBuffer(20, 4); + const defaultSendingChainID = utils.intToBuffer(20, 4); const defaultCCMs: CCMsg[] = [ { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(2), - receivingChainID: intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(2, 4), sendingChainID: defaultSendingChainID, status: CCM_STATUS_OK, }, { - crossChainCommandID: intToBuffer(2, 4), + crossChainCommandID: utils.intToBuffer(2, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(2), - receivingChainID: intToBuffer(3, 4), + receivingChainID: utils.intToBuffer(3, 4), sendingChainID: defaultSendingChainID, status: CCM_STATUS_OK, }, { - crossChainCommandID: intToBuffer(3, 4), + crossChainCommandID: utils.intToBuffer(3, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(2), - receivingChainID: intToBuffer(4, 4), + receivingChainID: utils.intToBuffer(4, 4), sendingChainID: defaultSendingChainID, status: CCM_STATUS_OK, }, @@ -122,7 +122,7 @@ describe('CrossChainUpdateCommand', () => { siblingHashes: [Buffer.alloc(1)], }, }; - const defaultTransaction = { moduleID: intToBuffer(1, 4) }; + const defaultTransaction = { moduleID: utils.intToBuffer(1, 4) }; const partnerChainStore = { getWithSchema: jest.fn(), @@ -149,10 +149,10 @@ describe('CrossChainUpdateCommand', () => { beforeEach(async () => { activeValidatorsUpdate = [ - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(1) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(3) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(4) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(3) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(1) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(3) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(4) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(3) }, ].sort((v1, v2) => v2.blsKey.compare(v1.blsKey)); // unsorted list const partnerValidators: any = { certificateThreshold: BigInt(10), @@ -180,27 +180,27 @@ describe('CrossChainUpdateCommand', () => { partnerChainAccount = { lastCertificate: { height: 10, - stateRoot: cryptography.getRandomBytes(38), + stateRoot: cryptography.utils.getRandomBytes(38), timestamp: Math.floor(Date.now() / 1000), - validatorsHash: cryptography.getRandomBytes(48), + validatorsHash: cryptography.utils.getRandomBytes(48), }, name: 'sidechain1', - networkID: cryptography.getRandomBytes(32), + networkID: cryptography.utils.getRandomBytes(32), status: CHAIN_ACTIVE, }; partnerChannelAccount = { inbox: { appendPath: [Buffer.alloc(1), Buffer.alloc(1)], - root: cryptography.getRandomBytes(38), + root: cryptography.utils.getRandomBytes(38), size: 18, }, - messageFeeTokenID: { chainID: intToBuffer(1, 4), localID: intToBuffer(0, 4) }, + messageFeeTokenID: { chainID: utils.intToBuffer(1, 4), localID: utils.intToBuffer(0, 4) }, outbox: { appendPath: [Buffer.alloc(1), Buffer.alloc(1)], - root: cryptography.getRandomBytes(38), + root: cryptography.utils.getRandomBytes(38), size: 18, }, - partnerChainOutboxRoot: cryptography.getRandomBytes(38), + partnerChainOutboxRoot: cryptography.utils.getRandomBytes(38), }; params = { @@ -324,7 +324,7 @@ describe('CrossChainUpdateCommand', () => { it('should return VerifyStatus.FAIL when checkValidatorsHashWithCertificate() throws error', async () => { const certificateWithIncorrectValidatorHash = codec.encode(certificateSchema, { ...defaultCertificateValues, - validatorsHash: cryptography.getRandomBytes(48), + validatorsHash: cryptography.utils.getRandomBytes(48), }); const { status, error } = await sidechainCCUUpdateCommand.verify({ @@ -491,13 +491,13 @@ describe('CrossChainUpdateCommand', () => { it('should call terminateChainInternal() for a ccm when txParams.sendingChainID !== ccm.deserilized.sendingChainID', async () => { const invalidCCM = codec.encode(ccmSchema, { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(2), - receivingChainID: intToBuffer(2, 4), - sendingChainID: intToBuffer(50, 4), + receivingChainID: utils.intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(50, 4), status: CCM_STATUS_OK, }); jest @@ -521,12 +521,12 @@ describe('CrossChainUpdateCommand', () => { it('should call terminateChainInternal() for a ccm when it fails on validateFormat', async () => { const invalidCCM = { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(MAX_CCM_SIZE + 10), - receivingChainID: intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(2, 4), sendingChainID: defaultSendingChainID, status: CCM_STATUS_OK, }; @@ -560,12 +560,12 @@ describe('CrossChainUpdateCommand', () => { it('should call apply() for all the valid CCMs', async () => { const sidechainCCM = { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(10), - receivingChainID: intToBuffer(80, 4), + receivingChainID: utils.intToBuffer(80, 4), sendingChainID: defaultSendingChainID, status: CCM_STATUS_OK, }; diff --git a/framework/test/unit/modules/interoperability/sidechain/commands/mainchain_registration.spec.ts b/framework/test/unit/modules/interoperability/sidechain/commands/mainchain_registration.spec.ts index 8cdd95dbf97..9f7dcfb2c66 100644 --- a/framework/test/unit/modules/interoperability/sidechain/commands/mainchain_registration.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/commands/mainchain_registration.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import * as crypto from '@liskhq/lisk-cryptography'; import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; @@ -72,18 +72,18 @@ describe('Mainchain registration command', () => { const { getRandomBytes } = crypto; const unsortedMainchainValidators: ActiveValidators[] = []; for (let i = 0; i < NUMBER_MAINCHAIN_VALIDATORS; i += 1) { - unsortedMainchainValidators.push({ blsKey: getRandomBytes(48), bftWeight: BigInt(1) }); + unsortedMainchainValidators.push({ blsKey: utils.getRandomBytes(48), bftWeight: BigInt(1) }); } const mainchainValidators = sortValidatorsByBLSKey(unsortedMainchainValidators); const transactionParams: MainchainRegistrationParams = { - ownChainID: intToBuffer(11, 4), + ownChainID: utils.intToBuffer(11, 4), ownName: 'testchain', mainchainValidators, aggregationBits: Buffer.alloc(0), signature: Buffer.alloc(0), }; const encodedTransactionParams = codec.encode(mainchainRegParams, transactionParams); - const publicKey = getRandomBytes(32); + const publicKey = utils.getRandomBytes(32); const transaction = new Transaction({ moduleID: MODULE_ID_INTEROPERABILITY_BUFFER, commandID: COMMAND_ID_MAINCHAIN_REG_BUFFER, @@ -117,16 +117,16 @@ describe('Mainchain registration command', () => { certificateThreshold: BigInt(40), currentValidators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(10), - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(5), - generatorKey: getRandomBytes(32), - blsKey: getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), + blsKey: utils.getRandomBytes(48), }, ], }) @@ -139,7 +139,7 @@ describe('Mainchain registration command', () => { }); it('should return error if own chain id is greater than maximum uint32 number', async () => { - verifyContext.params.ownChainID = intToBuffer(MAX_UINT32 + 1, 5); + verifyContext.params.ownChainID = utils.intToBuffer(MAX_UINT32 + 1, 5); const result = await mainchainRegistrationCommand.verify(verifyContext); expect(result.status).toBe(VerifyStatus.FAIL); @@ -149,7 +149,7 @@ describe('Mainchain registration command', () => { }); it('should return error if bls key is not 48 bytes', async () => { - verifyContext.params.mainchainValidators[1].blsKey = getRandomBytes(47); + verifyContext.params.mainchainValidators[1].blsKey = utils.getRandomBytes(47); const result = await mainchainRegistrationCommand.verify(verifyContext); expect(result.status).toBe(VerifyStatus.FAIL); @@ -157,7 +157,7 @@ describe('Mainchain registration command', () => { }); it('should return error if name is greater than max length of name', async () => { - verifyContext.params.ownName = getRandomBytes(21).toString('hex'); + verifyContext.params.ownName = utils.getRandomBytes(21).toString('hex'); const result = await mainchainRegistrationCommand.verify(verifyContext); expect(result.status).toBe(VerifyStatus.FAIL); @@ -218,7 +218,7 @@ describe('Mainchain registration command', () => { describe('execute', () => { const mainchainIdAsKey = getIDAsKeyForStore(MAINCHAIN_ID); const params = { - ownChainID: intToBuffer(11, 4), + ownChainID: utils.intToBuffer(11, 4), ownName: 'testchain', mainchainValidators, aggregationBits: Buffer.alloc(0), @@ -235,19 +235,19 @@ describe('Mainchain registration command', () => { }, status: CHAIN_REGISTERED, }; - const blsKey1 = getRandomBytes(48); - const blsKey2 = getRandomBytes(48); + const blsKey1 = utils.getRandomBytes(48); + const blsKey2 = utils.getRandomBytes(48); const validatorAccounts = [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(10), - generatorKey: getRandomBytes(32), + generatorKey: utils.getRandomBytes(32), blsKey: blsKey1, }, { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(5), - generatorKey: getRandomBytes(32), + generatorKey: utils.getRandomBytes(32), blsKey: blsKey2, }, ]; @@ -349,7 +349,7 @@ describe('Mainchain registration command', () => { inbox: { root: EMPTY_HASH, appendPath: [], size: 0 }, outbox: { root: EMPTY_HASH, appendPath: [], size: 0 }, partnerChainOutboxRoot: EMPTY_HASH, - messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: intToBuffer(0, 4) }, + messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: utils.intToBuffer(0, 4) }, }; // Act @@ -368,7 +368,7 @@ describe('Mainchain registration command', () => { const encodedParams = codec.encode(registrationCCMParamsSchema, { networkID: MAINCHAIN_NETWORK_ID, name: MAINCHAIN_NAME, - messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: intToBuffer(0, 4) }, + messageFeeTokenID: { chainID: MAINCHAIN_ID_BUFFER, localID: utils.intToBuffer(0, 4) }, }); // Act await mainchainRegistrationCommand.execute(context); diff --git a/framework/test/unit/modules/interoperability/sidechain/commands/message_recovery.spec.ts b/framework/test/unit/modules/interoperability/sidechain/commands/message_recovery.spec.ts index 4fb276ce735..aad08d438a9 100644 --- a/framework/test/unit/modules/interoperability/sidechain/commands/message_recovery.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/commands/message_recovery.spec.ts @@ -41,10 +41,10 @@ describe('Sidechain MessageRecoveryCommand', () => { const ccmsEncoded = ccms.map(ccm => codec.encode(ccmSchema, ccm)); transactionParams = { - chainID: intToBuffer(3, 4), + chainID: utils.intToBuffer(3, 4), crossChainMessages: [...ccmsEncoded], idxs: [0], - siblingHashes: [getRandomBytes(32)], + siblingHashes: [utils.getRandomBytes(32)], }; encodedTransactionParams = codec.encode(messageRecoveryParamsSchema, transactionParams); @@ -55,7 +55,7 @@ describe('Sidechain MessageRecoveryCommand', () => { fee: BigInt(100000000), nonce: BigInt(0), params: encodedTransactionParams, - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), signatures: [], }); @@ -78,7 +78,7 @@ describe('Sidechain MessageRecoveryCommand', () => { | 'terminatedOutboxAccountExist' >; - const moduleID = intToBuffer(1, 4); + const moduleID = utils.intToBuffer(1, 4); let messageRecoveryCommand: SidechainMessageRecoveryCommand; let commandExecuteContext: CommandExecuteContext; @@ -105,19 +105,19 @@ describe('Sidechain MessageRecoveryCommand', () => { { nonce: BigInt(0), moduleID, - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), }, { nonce: BigInt(1), - moduleID: intToBuffer(moduleID.readInt32BE(0) + 1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(moduleID.readInt32BE(0) + 1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), @@ -174,7 +174,7 @@ describe('Sidechain MessageRecoveryCommand', () => { when(storeMock.getTerminatedOutboxAccount) .calledWith(chainID) .mockResolvedValue({ - outboxRoot: getRandomBytes(32), + outboxRoot: utils.getRandomBytes(32), outboxSize: 1, partnerChainInboxSize: 1, }); @@ -207,10 +207,10 @@ describe('Sidechain MessageRecoveryCommand', () => { // Arrange & Assign const newCcm = { nonce: BigInt(2), - moduleID: intToBuffer(moduleID.readInt32BE(0) + 1, 4), - crossChainCommandID: intToBuffer(2, 4), - sendingChainID: intToBuffer(3, 4), - receivingChainID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(moduleID.readInt32BE(0) + 1, 4), + crossChainCommandID: utils.intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(3, 4), + receivingChainID: utils.intToBuffer(2, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), @@ -296,7 +296,7 @@ describe('Sidechain MessageRecoveryCommand', () => { .calledWith() .mockResolvedValue({ name: `chain${chainID.toString('hex')}`, - id: intToBuffer(0, 4), + id: utils.intToBuffer(0, 4), nonce: BigInt(0), }); } @@ -335,7 +335,7 @@ describe('Sidechain MessageRecoveryCommand', () => { ccCommands.set(moduleID.readInt32BE(0), ([ { moduleID, - ID: intToBuffer(3000, 4), + ID: utils.intToBuffer(3000, 4), name: 'ccCommand', execute: jest.fn(), schema: { diff --git a/framework/test/unit/modules/interoperability/sidechain/store.spec.ts b/framework/test/unit/modules/interoperability/sidechain/store.spec.ts index fe85b9058d1..87a0a1d322c 100644 --- a/framework/test/unit/modules/interoperability/sidechain/store.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/store.spec.ts @@ -69,7 +69,7 @@ describe('Sidechain interoperability store', () => { ownChainAccount = { name: 'mainchain', - id: intToBuffer(2, 4), + id: utils.intToBuffer(2, 4), nonce: BigInt('0'), }; @@ -144,10 +144,10 @@ describe('Sidechain interoperability store', () => { const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), @@ -165,12 +165,12 @@ describe('Sidechain interoperability store', () => { status: 1, }; - const randomOutboxRoot = getRandomBytes(32); + const randomOutboxRoot = utils.getRandomBytes(32); const channelData: ChannelData = { inbox: { appendPath: [], size: 0, - root: getRandomBytes(32), + root: utils.getRandomBytes(32), }, outbox: { appendPath: [], @@ -179,14 +179,14 @@ describe('Sidechain interoperability store', () => { }, partnerChainOutboxRoot: Buffer.alloc(0), messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(2, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(2, 4), }, }; const beforeSendCCMContext = testing.createBeforeSendCCMsgAPIContext({ ccm, - feeAddress: getRandomBytes(32), + feeAddress: utils.getRandomBytes(32), }); const sendInternalContext: SendInternalContext = { @@ -273,10 +273,10 @@ describe('Sidechain interoperability store', () => { it('should return false if the created ccm is of invalid size', async () => { const invalidCCM = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(MAX_CCM_SIZE), // invalid size @@ -284,7 +284,7 @@ describe('Sidechain interoperability store', () => { const beforeSendCCMContextLocal = testing.createBeforeSendCCMsgAPIContext({ ccm: invalidCCM, - feeAddress: getRandomBytes(32), + feeAddress: utils.getRandomBytes(32), }); const sendInternalContextLocal: SendInternalContext = { @@ -309,10 +309,10 @@ describe('Sidechain interoperability store', () => { it('should return false if the ccm created is invalid schema', async () => { const invalidCCM = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 'ccm', // invalid field params: Buffer.alloc(0), @@ -320,7 +320,7 @@ describe('Sidechain interoperability store', () => { const beforeSendCCMContextLocal = testing.createBeforeSendCCMsgAPIContext({ ccm: invalidCCM as any, - feeAddress: getRandomBytes(32), + feeAddress: utils.getRandomBytes(32), }); const sendInternalContextLocal = { diff --git a/framework/test/unit/modules/interoperability/store.spec.ts b/framework/test/unit/modules/interoperability/store.spec.ts index 0f0e4afd840..0ebd5332f61 100644 --- a/framework/test/unit/modules/interoperability/store.spec.ts +++ b/framework/test/unit/modules/interoperability/store.spec.ts @@ -56,10 +56,10 @@ describe('Base interoperability store', () => { ); const CCM = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), @@ -101,8 +101,8 @@ describe('Base interoperability store', () => { outbox: outboxTree, partnerChainOutboxRoot: Buffer.alloc(0), messageFeeTokenID: { - chainID: intToBuffer(0, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(0, 4), + localID: utils.intToBuffer(0, 4), }, }; let mainchainInteroperabilityStore: MainchainInteroperabilityStore; @@ -226,7 +226,7 @@ describe('Base interoperability store', () => { }); describe('createTerminatedStateAccount', () => { - const chainId = intToBuffer(5, 4); + const chainId = utils.intToBuffer(5, 4); const chainAccount = { name: 'account1', networkID: Buffer.alloc(0), @@ -247,7 +247,7 @@ describe('Base interoperability store', () => { const ownChainAccount2 = { name: 'chain1', - id: intToBuffer(7, 4), + id: utils.intToBuffer(7, 4), nonce: BigInt('0'), }; @@ -278,7 +278,7 @@ describe('Base interoperability store', () => { }); it('should return false if chain account does not exist for the id and ownchain account id is not the same as mainchain id', async () => { - const chainIdNew = intToBuffer(9, 4); + const chainIdNew = utils.intToBuffer(9, 4); jest .spyOn(mainchainInteroperabilityStore, 'getOwnChainAccount') .mockResolvedValue(ownChainAccount1 as never); @@ -289,7 +289,7 @@ describe('Base interoperability store', () => { }); it('should set appropriate terminated state for chain id in the terminatedState sub store if chain account does not exist for the id but ownchain account id is the same as mainchain id', async () => { - const chainIdNew = intToBuffer(10, 4); + const chainIdNew = utils.intToBuffer(10, 4); jest .spyOn(mainchainInteroperabilityStore, 'getOwnChainAccount') .mockResolvedValue(ownChainAccount2 as never); @@ -311,20 +311,20 @@ describe('Base interoperability store', () => { }); describe('terminateChainInternal', () => { - const SIDECHAIN_ID = intToBuffer(2, 4); + const SIDECHAIN_ID = utils.intToBuffer(2, 4); const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(1), status: 1, params: Buffer.alloc(0), }; const beforeSendCCMContext = testing.createBeforeSendCCMsgAPIContext({ ccm, - feeAddress: getRandomBytes(32), + feeAddress: utils.getRandomBytes(32), }); beforeEach(() => { @@ -375,10 +375,10 @@ describe('Base interoperability store', () => { const ccm = { nonce: BigInt(0), - moduleID: intToBuffer(1, 4), - crossChainCommandID: intToBuffer(1, 4), - sendingChainID: intToBuffer(2, 4), - receivingChainID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), + sendingChainID: utils.intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(3, 4), fee: BigInt(34000), status: 0, params: Buffer.alloc(0), @@ -423,12 +423,12 @@ describe('Base interoperability store', () => { certificate: Buffer.alloc(0), inboxUpdate, newCertificateThreshold: BigInt(0), - sendingChainID: intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(2, 4), }; const beforeSendCCMContext = testing.createBeforeSendCCMsgAPIContext({ ccm, - feeAddress: getRandomBytes(32), + feeAddress: utils.getRandomBytes(32), }); const beforeApplyCCMContext = testing.createBeforeApplyCCMsgAPIContext({ @@ -436,7 +436,7 @@ describe('Base interoperability store', () => { ccm, ccu, payFromAddress: EMPTY_FEE_ADDRESS, - trsSender: getRandomBytes(20), + trsSender: utils.getRandomBytes(20), }); const ccmApplyContext: CCMApplyContext = { @@ -499,7 +499,7 @@ describe('Base interoperability store', () => { // Arrange const localCCCommandsMap = new Map().set(4, [ { - ID: intToBuffer(4, 4), + ID: utils.intToBuffer(4, 4), execute: jest.fn(), }, ]); @@ -529,7 +529,7 @@ describe('Base interoperability store', () => { // Arrange const localCCCommandsMap = new Map().set(1, [ { - ID: intToBuffer(3, 4), + ID: utils.intToBuffer(3, 4), execute: jest.fn(), }, ]); @@ -605,7 +605,7 @@ describe('Base interoperability store', () => { .calledWith(MODULE_ID_INTEROPERABILITY_BUFFER, STORE_PREFIX_TERMINATED_OUTBOX) .mockReturnValue(terminatedOutboxSubstore); - terminatedChainID = getRandomBytes(32); + terminatedChainID = utils.getRandomBytes(32); terminatedOutboxAccount = { outboxRoot: Buffer.alloc(32), @@ -629,7 +629,7 @@ describe('Base interoperability store', () => { it('should throw when terminated outbox account does not exist', async () => { await expect( - mainchainInteroperabilityStore.getTerminatedOutboxAccount(getRandomBytes(32)), + mainchainInteroperabilityStore.getTerminatedOutboxAccount(utils.getRandomBytes(32)), ).rejects.toThrow(); }); }); @@ -647,7 +647,7 @@ describe('Base interoperability store', () => { .calledWith(MODULE_ID_INTEROPERABILITY_BUFFER, STORE_PREFIX_TERMINATED_OUTBOX) .mockReturnValue(terminatedOutboxSubstore); - terminatedChainID = getRandomBytes(32); + terminatedChainID = utils.getRandomBytes(32); terminatedOutboxAccount = { outboxRoot: Buffer.alloc(32), @@ -665,8 +665,8 @@ describe('Base interoperability store', () => { it('should return false when outbox account does not exist', async () => { // Assign const isValueChanged = await mainchainInteroperabilityStore.setTerminatedOutboxAccount( - getRandomBytes(32), - { outboxRoot: getRandomBytes(32) }, + utils.getRandomBytes(32), + { outboxRoot: utils.getRandomBytes(32) }, ); // Assert @@ -676,7 +676,7 @@ describe('Base interoperability store', () => { it('should return false when no params provided', async () => { // Assign const isValueChanged = await mainchainInteroperabilityStore.setTerminatedOutboxAccount( - getRandomBytes(32), + utils.getRandomBytes(32), {}, ); @@ -689,20 +689,20 @@ describe('Base interoperability store', () => { { title: 'should change outboxRoot', changedValues: { - outboxRoot: getRandomBytes(32), + outboxRoot: utils.getRandomBytes(32), }, }, { title: 'should change outboxRoot and outboxSize', changedValues: { - outboxRoot: getRandomBytes(32), + outboxRoot: utils.getRandomBytes(32), outboxSize: 2, }, }, { title: 'should change outboxRoot, outboxSize and partnerChainInboxSize', changedValues: { - outboxRoot: getRandomBytes(32), + outboxRoot: utils.getRandomBytes(32), outboxSize: 3, partnerChainInboxSize: 3, }, diff --git a/framework/test/unit/modules/interoperability/utils.spec.ts b/framework/test/unit/modules/interoperability/utils.spec.ts index 2ed78b124c8..291b9abf7ad 100644 --- a/framework/test/unit/modules/interoperability/utils.spec.ts +++ b/framework/test/unit/modules/interoperability/utils.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import * as cryptography from '@liskhq/lisk-cryptography'; import * as merkleTree from '@liskhq/lisk-tree'; @@ -55,19 +55,19 @@ jest.mock('@liskhq/lisk-cryptography', () => ({ describe('Utils', () => { const defaultActiveValidatorsUpdate = [ - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(1) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(3) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(4) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(3) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(1) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(3) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(4) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(3) }, ]; describe('updateActiveValidators', () => { const validator1 = { - blsKey: cryptography.getRandomBytes(48), + blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(1), }; const validator2 = { - blsKey: cryptography.getRandomBytes(48), + blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(2), }; const activeValidators = [validator1, validator2]; @@ -84,7 +84,7 @@ describe('Utils', () => { const activeValidatorsUpdate = [ validator1, validator2, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(1) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(1) }, ]; // Should be in lexicographical order @@ -97,7 +97,7 @@ describe('Utils', () => { it('should remove a validator when its bftWeight=0', () => { const activeValidatorsLocal = [...activeValidators]; - const validator3 = { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(3) }; + const validator3 = { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(3) }; activeValidatorsLocal.push(validator3); const activeValidatorsUpdate = [ validator1, @@ -121,11 +121,11 @@ describe('Utils', () => { const txParamsEmptyCertificate = { certificate: EMPTY_BYTES, - sendingChainID: intToBuffer(4, 4), + sendingChainID: utils.intToBuffer(4, 4), }; const txParamsNonEmptyCertificate = { - certificate: cryptography.getRandomBytes(32), + certificate: cryptography.utils.getRandomBytes(32), }; it(`should return VerifyStatus.FAIL status when chain status ${CHAIN_REGISTERED} && certificate is empty`, () => { @@ -159,15 +159,15 @@ describe('Utils', () => { }; const certificate = { - blockID: cryptography.getRandomBytes(20), + blockID: cryptography.utils.getRandomBytes(20), height: 23, stateRoot: Buffer.alloc(2), timestamp: Date.now(), - validatorsHash: cryptography.getRandomBytes(20), + validatorsHash: cryptography.utils.getRandomBytes(20), }; const certificateWithEmptyValues = { - blockID: cryptography.getRandomBytes(20), + blockID: cryptography.utils.getRandomBytes(20), height: 23, stateRoot: EMPTY_BYTES, timestamp: Date.now(), @@ -225,7 +225,7 @@ describe('Utils', () => { activeValidatorsUpdate, newCertificateThreshold: BigInt(10), certificate: Buffer.alloc(2), - sendingChainID: intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(2, 4), inboxUpdate: {}, }; @@ -233,7 +233,7 @@ describe('Utils', () => { activeValidatorsUpdate, newCertificateThreshold: BigInt(10), certificate: EMPTY_BYTES, - sendingChainID: intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(2, 4), inboxUpdate: {}, }; @@ -241,7 +241,7 @@ describe('Utils', () => { activeValidatorsUpdate: sortedValidatorsList, newCertificateThreshold: BigInt(10), certificate: Buffer.alloc(2), - sendingChainID: intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(2, 4), inboxUpdate: {}, }; @@ -338,13 +338,13 @@ describe('Utils', () => { describe('verifyCertificateSignature', () => { const activeValidatorsUpdate = [...defaultActiveValidatorsUpdate]; const ceritificate: Certificate = { - blockID: cryptography.getRandomBytes(20), + blockID: cryptography.utils.getRandomBytes(20), height: 21, timestamp: Math.floor(Date.now() / 1000), - stateRoot: cryptography.getRandomBytes(38), - validatorsHash: cryptography.getRandomBytes(48), - aggregationBits: cryptography.getRandomBytes(38), - signature: cryptography.getRandomBytes(32), + stateRoot: cryptography.utils.getRandomBytes(38), + validatorsHash: cryptography.utils.getRandomBytes(48), + aggregationBits: cryptography.utils.getRandomBytes(38), + signature: cryptography.utils.getRandomBytes(32), }; const encodedCertificate = codec.encode(certificateSchema, ceritificate); const txParams: any = { @@ -357,7 +357,7 @@ describe('Utils', () => { activeValidators: activeValidatorsUpdate, certificateThreshold: 10, }; - const partnerChainAccount: any = { networkID: cryptography.getRandomBytes(32) }; + const partnerChainAccount: any = { networkID: cryptography.utils.getRandomBytes(32) }; it('should return VerifyStatus.OK if certificate is empty', () => { jest.spyOn(cryptography, 'verifyWeightedAggSig').mockReturnValue(true); @@ -456,9 +456,9 @@ describe('Utils', () => { aggregationBits: Buffer.alloc(2), signature: Buffer.alloc(2), validatorsHash, - blockID: cryptography.getRandomBytes(20), + blockID: cryptography.utils.getRandomBytes(20), height: 20, - stateRoot: cryptography.getRandomBytes(32), + stateRoot: cryptography.utils.getRandomBytes(32), timestamp: Math.floor(Date.now() / 1000), }; @@ -500,10 +500,10 @@ describe('Utils', () => { const certificateInvalidValidatorHash: Certificate = { aggregationBits: Buffer.alloc(2), signature: Buffer.alloc(2), - validatorsHash: cryptography.getRandomBytes(48), - blockID: cryptography.getRandomBytes(20), + validatorsHash: cryptography.utils.getRandomBytes(48), + blockID: cryptography.utils.getRandomBytes(20), height: 20, - stateRoot: cryptography.getRandomBytes(32), + stateRoot: cryptography.utils.getRandomBytes(32), timestamp: Math.floor(Date.now() / 1000), }; const invalidEncodedCertificate = codec.encode( @@ -571,7 +571,7 @@ describe('Utils', () => { describe('checkInboxUpdateValidity', () => { const activeValidatorsUpdate = [...defaultActiveValidatorsUpdate]; - const partnerChainOutboxRoot = cryptography.getRandomBytes(32); + const partnerChainOutboxRoot = cryptography.utils.getRandomBytes(32); const inboxTree = { root: Buffer.from('7f9d96a09a3fd17f3478eb7bef3a8bda00e1238b', 'hex'), appendPath: [ @@ -589,33 +589,33 @@ describe('Utils', () => { const partnerChannelData: ChannelData = { inbox: inboxTree, messageFeeTokenID: { - chainID: intToBuffer(1, 4), - localID: intToBuffer(0, 4), + chainID: utils.intToBuffer(1, 4), + localID: utils.intToBuffer(0, 4), }, outbox: outboxTree, partnerChainOutboxRoot, }; - const defaultSendingChainID = intToBuffer(20, 4); + const defaultSendingChainID = utils.intToBuffer(20, 4); const defaultCCMs = [ { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(2), - receivingChainID: intToBuffer(2, 4), + receivingChainID: utils.intToBuffer(2, 4), sendingChainID: defaultSendingChainID, status: CCM_STATUS_OK, }, { - crossChainCommandID: intToBuffer(2, 4), + crossChainCommandID: utils.intToBuffer(2, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(1), params: Buffer.alloc(2), - receivingChainID: intToBuffer(3, 4), + receivingChainID: utils.intToBuffer(3, 4), sendingChainID: defaultSendingChainID, status: CCM_STATUS_OK, }, @@ -623,22 +623,22 @@ describe('Utils', () => { const inboxUpdateCCMs = [ { - crossChainCommandID: intToBuffer(1, 4), + crossChainCommandID: utils.intToBuffer(1, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(2), params: Buffer.alloc(4), - receivingChainID: intToBuffer(90, 4), + receivingChainID: utils.intToBuffer(90, 4), sendingChainID: defaultSendingChainID, status: CCM_STATUS_OK, }, { - crossChainCommandID: intToBuffer(2, 4), + crossChainCommandID: utils.intToBuffer(2, 4), fee: BigInt(0), - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), nonce: BigInt(10), params: Buffer.alloc(4), - receivingChainID: intToBuffer(70, 4), + receivingChainID: utils.intToBuffer(70, 4), sendingChainID: defaultSendingChainID, status: CCM_STATUS_OK, }, @@ -661,19 +661,19 @@ describe('Utils', () => { crossChainMessages: inboxUpdateCCMsEncoded, messageWitness: { partnerChainOutboxSize: BigInt(1), - siblingHashes: [cryptography.getRandomBytes(32)], + siblingHashes: [cryptography.utils.getRandomBytes(32)], }, outboxRootWitness: { - bitmap: cryptography.getRandomBytes(32), - siblingHashes: [cryptography.getRandomBytes(32)], + bitmap: cryptography.utils.getRandomBytes(32), + siblingHashes: [cryptography.utils.getRandomBytes(32)], }, }; const certificate: Certificate = { - blockID: cryptography.getRandomBytes(20), + blockID: cryptography.utils.getRandomBytes(20), height: 20, - stateRoot: cryptography.getRandomBytes(32), + stateRoot: cryptography.utils.getRandomBytes(32), timestamp: Math.floor(Date.now() / 1000), - validatorsHash: cryptography.getRandomBytes(48), + validatorsHash: cryptography.utils.getRandomBytes(48), }; const encodedCertificate = codec.encode(certificateSchema, certificate); @@ -682,7 +682,7 @@ describe('Utils', () => { activeValidatorsUpdate, newCertificateThreshold: BigInt(10), inboxUpdate, - sendingChainID: intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(2, 4), }; let newInboxRoot: Buffer; @@ -740,8 +740,8 @@ describe('Utils', () => { siblingHashes: [], }, outboxRootWitness: { - bitmap: cryptography.getRandomBytes(32), - siblingHashes: [cryptography.getRandomBytes(32)], + bitmap: cryptography.utils.getRandomBytes(32), + siblingHashes: [cryptography.utils.getRandomBytes(32)], }, }; @@ -750,7 +750,7 @@ describe('Utils', () => { activeValidatorsUpdate, newCertificateThreshold: BigInt(10), inboxUpdate: inboxUpdateMessageWitnessEmpty, - sendingChainID: intToBuffer(2, 4), + sendingChainID: utils.intToBuffer(2, 4), }; const { status, error } = checkInboxUpdateValidity( txParamsEmptyMessageWitness, @@ -857,7 +857,7 @@ describe('Utils', () => { ); const calculateMerkleRootSpy = jest .spyOn(merkleTree.regularMerkleTree, 'calculateMerkleRoot') - .mockReturnValue({ root: cryptography.getRandomBytes(32) } as never); + .mockReturnValue({ root: cryptography.utils.getRandomBytes(32) } as never); const { status, error } = checkInboxUpdateValidity( txParamsEmptyMessageWitness, @@ -875,7 +875,7 @@ describe('Utils', () => { describe('commonCCUExecutelogic', () => { const chainIDBuffer = getIDAsKeyForStore(1); - const defaultCalculatedRootFromRightWitness = cryptography.getRandomBytes(20); + const defaultCalculatedRootFromRightWitness = cryptography.utils.getRandomBytes(20); let activeValidatorsUpdate: any; let inboxUpdate: InboxUpdate; let certificate: any; @@ -891,10 +891,10 @@ describe('Utils', () => { beforeEach(async () => { activeValidatorsUpdate = [ - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(1) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(3) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(4) }, - { blsKey: cryptography.getRandomBytes(48), bftWeight: BigInt(3) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(1) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(3) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(4) }, + { blsKey: cryptography.utils.getRandomBytes(48), bftWeight: BigInt(3) }, ]; inboxUpdate = { crossChainMessages: [Buffer.alloc(1)], @@ -943,14 +943,14 @@ describe('Utils', () => { inbox: { size: BigInt(2), appendPath: [Buffer.alloc(1)], - root: cryptography.getRandomBytes(20), + root: cryptography.utils.getRandomBytes(20), }, }; context = { getStore: jest.fn(), params, transaction: { - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), }, }; diff --git a/framework/test/unit/modules/random/api.spec.ts b/framework/test/unit/modules/random/api.spec.ts index b94a68e666f..873fa49cf0a 100644 --- a/framework/test/unit/modules/random/api.spec.ts +++ b/framework/test/unit/modules/random/api.spec.ts @@ -15,7 +15,7 @@ import { BlockAsset, BlockAssets } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; import * as cryptography from '@liskhq/lisk-cryptography'; -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { RandomAPI } from '../../../../src/modules/random/api'; import { MODULE_ID_RANDOM_BUFFER, @@ -36,7 +36,7 @@ import { testCases } from './dpos_random_seed_generation/dpos_random_seed_genera import * as randomSeedsMultipleRounds from '../../../fixtures/dpos_random_seed_generation/dpos_random_seed_generation_other_rounds.json'; const strippedHashOfIntegerBuffer = (num: number) => - cryptography.hash(intToBuffer(num, 4)).slice(0, SEED_REVEAL_HASH_SIZE); + cryptography.hash(utils.intToBuffer(num, 4)).slice(0, SEED_REVEAL_HASH_SIZE); describe('RandomModuleAPI', () => { let randomAPI: RandomAPI; @@ -50,7 +50,7 @@ describe('RandomModuleAPI', () => { const twoRoundsDelegatesHashes: { [key: string]: Buffer[] } = {}; for (const generator of testCases[0].input.blocks) { - const generatorAddress = cryptography.getAddressFromPublicKey( + const generatorAddress = cryptography.address.getAddressFromPublicKey( Buffer.from(generator.generatorPublicKey, 'hex'), ); const seedReveal = Buffer.from(generator.asset.seedReveal, 'hex'); @@ -81,7 +81,7 @@ describe('RandomModuleAPI', () => { it('should throw error when asset is undefined', async () => { // Arrange - const delegateAddress = cryptography.getAddressFromPublicKey( + const delegateAddress = cryptography.address.getAddressFromPublicKey( Buffer.from(testCases[0].input.blocks[0].generatorPublicKey, 'hex'), ); @@ -213,7 +213,7 @@ describe('RandomModuleAPI', () => { const numberOfSeeds = 2; // Create a buffer from height + numberOfSeeds - await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).rejects.toThrow( + await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).rejects.toThrow( 'Height or number of seeds cannot be negative.', ); }); @@ -223,7 +223,7 @@ describe('RandomModuleAPI', () => { const numberOfSeeds = -2; // Create a buffer from height + numberOfSeeds - await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).rejects.toThrow( + await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).rejects.toThrow( 'Height or number of seeds cannot be negative.', ); }); @@ -244,7 +244,7 @@ describe('RandomModuleAPI', () => { hashesExpected[1], ]); - await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( xorExpected, ); }); @@ -266,7 +266,7 @@ describe('RandomModuleAPI', () => { hashesExpected[2], ]); - await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( xorExpected, ); }); @@ -288,7 +288,7 @@ describe('RandomModuleAPI', () => { hashesExpected[2], ]); - await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( xorExpected, ); }); @@ -305,7 +305,7 @@ describe('RandomModuleAPI', () => { // Do XOR of randomSeed with hashes of seed reveal with height >= randomStoreValidator.height >= height + numberOfSeeds const xorExpected = bitwiseXOR([randomSeed, hashesExpected[0]]); - await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( xorExpected, ); }); @@ -316,7 +316,7 @@ describe('RandomModuleAPI', () => { // Create a buffer from height + numberOfSeeds const randomSeed = strippedHashOfIntegerBuffer(height + numberOfSeeds); - await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( randomSeed, ); }); @@ -327,7 +327,7 @@ describe('RandomModuleAPI', () => { // Create a buffer from height + numberOfSeeds const randomSeed = strippedHashOfIntegerBuffer(height + numberOfSeeds); - await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( randomSeed, ); }); @@ -342,7 +342,7 @@ describe('RandomModuleAPI', () => { const validators: ValidatorSeedReveal[] = []; for (const generator of input.blocks) { - const generatorAddress = cryptography.getAddressFromPublicKey( + const generatorAddress = cryptography.address.getAddressFromPublicKey( Buffer.from(generator.generatorPublicKey, 'hex'), ); const seedReveal = Buffer.from(generator.asset.seedReveal, 'hex'); @@ -380,7 +380,7 @@ describe('RandomModuleAPI', () => { const endOfLastRound = startOfRound - 1; const startOfLastRound = endOfLastRound - config.blocksPerRound + 1; // Act - const randomSeed1 = await randomAPI.getRandomBytes( + const randomSeed1 = await randomAPI.utils.getRandomBytes( context, heightForSeed1, round === 2 ? middleThreshold : middleThreshold * 2, @@ -389,7 +389,7 @@ describe('RandomModuleAPI', () => { const randomSeed2 = round === 2 ? strippedHashOfIntegerBuffer(endOfLastRound) - : await randomAPI.getRandomBytes(context, startOfLastRound, middleThreshold * 2); + : await randomAPI.utils.getRandomBytes(context, startOfLastRound, middleThreshold * 2); // Assert expect(randomSeed1.toString('hex')).toEqual(output.randomSeed1); expect(randomSeed2.toString('hex')).toEqual(output.randomSeed2); diff --git a/framework/test/unit/modules/random/random_module.spec.ts b/framework/test/unit/modules/random/random_module.spec.ts index 7c046fcc799..f49ee2d7565 100644 --- a/framework/test/unit/modules/random/random_module.spec.ts +++ b/framework/test/unit/modules/random/random_module.spec.ts @@ -97,12 +97,12 @@ describe('RandomModule', () => { { count: 5, height: 9, - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), }, { count: 6, height: 12, - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), }, ], }; @@ -110,17 +110,17 @@ describe('RandomModule', () => { const defaultUsedHashOnionUpdated: UsedHashOnionStoreObject = { usedHashOnions: [ { - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), count: 5, height: 9, }, { - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), count: 6, height: 12, }, { - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), count: 7, height: 15, }, @@ -214,15 +214,15 @@ describe('RandomModule', () => { { count: 5, height: 9, - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), }, { count: 6, height: 12, - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), }, { - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), count: 7, height: 15, }, @@ -327,7 +327,7 @@ describe('RandomModule', () => { { count: maxCount, height: 10, - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), }, ], }; @@ -335,12 +335,12 @@ describe('RandomModule', () => { const usedHashOnionOutput: UsedHashOnionStoreObject = { usedHashOnions: [ { - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), count: maxCount, height: 10, }, { - address: getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), + address: address.getAddressFromPublicKey(Buffer.from(targetDelegate.publicKey, 'hex')), count: 0, height: 15, }, @@ -467,7 +467,7 @@ describe('RandomModule', () => { it('should reject if seed reveal length is not 16 bytes', async () => { const asset = { moduleID: randomModule.id, - data: codec.encode(blockHeaderAssetRandomModule, { seedReveal: getRandomBytes(10) }), + data: codec.encode(blockHeaderAssetRandomModule, { seedReveal: utils.getRandomBytes(10) }), }; const context = createBlockContext({ assets: new BlockAssets([asset]), @@ -481,7 +481,7 @@ describe('RandomModule', () => { it('should resolve if seed reveal length is 16 bytes', async () => { const asset = { moduleID: randomModule.id, - data: codec.encode(blockHeaderAssetRandomModule, { seedReveal: getRandomBytes(16) }), + data: codec.encode(blockHeaderAssetRandomModule, { seedReveal: utils.getRandomBytes(16) }), }; const context = createBlockContext({ assets: new BlockAssets([asset]), @@ -493,16 +493,16 @@ describe('RandomModule', () => { describe('afterTransactionsExecute', () => { let stateStore: PrefixedStateReadWriter; - const generator1 = getRandomBytes(20); - const seed1 = getRandomBytes(16); - const generator2 = getRandomBytes(20); - const seed2 = getRandomBytes(16); - const generator3 = getRandomBytes(20); - const seed3 = getRandomBytes(16); + const generator1 = utils.getRandomBytes(20); + const seed1 = utils.getRandomBytes(16); + const generator2 = utils.getRandomBytes(20); + const seed2 = utils.getRandomBytes(16); + const generator3 = utils.getRandomBytes(20); + const seed3 = utils.getRandomBytes(16); const seedHash = (seed: Buffer, times: number) => { let res = seed; for (let i = 0; i < times; i += 1) { - res = hash(res).slice(0, 16); + res = utils.hash(res).slice(0, 16); } return res; }; @@ -676,7 +676,7 @@ describe('RandomModule', () => { }); it('should set seed reveal validity to be false if validator provides invalid seed reveal', async () => { - const seedReveal = seedHash(getRandomBytes(20), 1); + const seedReveal = seedHash(utils.getRandomBytes(20), 1); const asset = { moduleID: randomModule.id, data: codec.encode(blockHeaderAssetRandomModule, { seedReveal }), @@ -704,12 +704,12 @@ describe('RandomModule', () => { }); it('should set seed reveal validity to be false if there is no data for the past seed reveal', async () => { - const seedReveal = seedHash(getRandomBytes(20), 1); + const seedReveal = seedHash(utils.getRandomBytes(20), 1); const asset = { moduleID: randomModule.id, data: codec.encode(blockHeaderAssetRandomModule, { seedReveal }), }; - const generator = getRandomBytes(20); + const generator = utils.getRandomBytes(20); const context = createBlockContext({ assets: new BlockAssets([asset]), header: createBlockHeaderWithDefaults({ height: 6, generatorAddress: generator }), diff --git a/framework/test/unit/modules/reward/api.spec.ts b/framework/test/unit/modules/reward/api.spec.ts index b616dfb6588..f7d1c0a19c5 100644 --- a/framework/test/unit/modules/reward/api.spec.ts +++ b/framework/test/unit/modules/reward/api.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { RewardModule } from '../../../../src/modules/reward'; import { createBlockHeaderWithDefaults, createTransientAPIContext } from '../../../../src/testing'; @@ -28,7 +28,7 @@ describe('RewardModuleAPI', () => { '200000000', // Milestone 3 '100000000', // Milestone 4 ], - tokenIDReward: { chainID: intToBuffer(0, 4), localID: intToBuffer(0, 4) }, + tokenIDReward: { chainID: utils.intToBuffer(0, 4), localID: utils.intToBuffer(0, 4) }, }; const generatorConfig: any = {}; diff --git a/framework/test/unit/modules/reward/endpoint.spec.ts b/framework/test/unit/modules/reward/endpoint.spec.ts index 27e9e5a3a9f..4dd167077df 100644 --- a/framework/test/unit/modules/reward/endpoint.spec.ts +++ b/framework/test/unit/modules/reward/endpoint.spec.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Logger } from '../../../../src/logger'; import { RewardModule } from '../../../../src/modules/reward'; import { fakeLogger } from '../../../utils/mocks'; @@ -28,7 +28,7 @@ describe('RewardModuleEndpoint', () => { '200000000', // Milestone 3 '100000000', // Milestone 4 ], - tokenIDReward: { chainID: intToBuffer(0, 4), localID: intToBuffer(0, 4) }, + tokenIDReward: { chainID: utils.intToBuffer(0, 4), localID: utils.intToBuffer(0, 4) }, }; const generatorConfig: any = {}; const networkIdentifier = Buffer.alloc(0); diff --git a/framework/test/unit/modules/reward/reward_module.spec.ts b/framework/test/unit/modules/reward/reward_module.spec.ts index 076633fccf4..89aa6b26f43 100644 --- a/framework/test/unit/modules/reward/reward_module.spec.ts +++ b/framework/test/unit/modules/reward/reward_module.spec.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { RewardModule } from '../../../../src/modules/reward'; import { createBlockContext, createBlockHeaderWithDefaults } from '../../../../src/testing'; @@ -27,7 +27,7 @@ describe('RewardModule', () => { '200000000', // Milestone 3 '100000000', // Milestone 4 ], - tokenIDReward: { chainID: intToBuffer(0, 4), localID: intToBuffer(0, 4) }, + tokenIDReward: { chainID: utils.intToBuffer(0, 4), localID: utils.intToBuffer(0, 4) }, }; const generatorConfig: any = {}; diff --git a/framework/test/unit/modules/token/api.spec.ts b/framework/test/unit/modules/token/api.spec.ts index 5c4f7f925f0..277319667d5 100644 --- a/framework/test/unit/modules/token/api.spec.ts +++ b/framework/test/unit/modules/token/api.spec.ts @@ -44,7 +44,7 @@ import { InMemoryPrefixedStateDB } from '../../../../src/testing/in_memory_prefi import { DEFAULT_TOKEN_ID } from '../../../utils/mocks/transaction'; describe('token module', () => { - const defaultAddress = getRandomBytes(20); + const defaultAddress = utils.getRandomBytes(20); const defaultTokenIDAlias = Buffer.alloc(TOKEN_ID_LENGTH, 0); const defaultTokenID = Buffer.from([0, 0, 0, 1, 0, 0, 0, 0]); const defaultForeignTokenID = Buffer.from([1, 0, 0, 0, 0, 0, 0, 0]); @@ -52,7 +52,7 @@ describe('token module', () => { availableBalance: BigInt(10000000000), lockedBalances: [ { - moduleID: intToBuffer(12, 4), + moduleID: utils.intToBuffer(12, 4), amount: BigInt(100000000), }, ], @@ -128,7 +128,7 @@ describe('token module', () => { describe('getAvailableBalance', () => { it('should return zero if data does not exist', async () => { await expect( - api.getAvailableBalance(apiContext, getRandomBytes(20), defaultTokenID), + api.getAvailableBalance(apiContext, utils.getRandomBytes(20), defaultTokenID), ).resolves.toEqual(BigInt(0)); }); @@ -142,16 +142,21 @@ describe('token module', () => { describe('getLockedAmount', () => { it('should return zero if data does not exist', async () => { await expect( - api.getLockedAmount(apiContext, getRandomBytes(20), defaultTokenID, intToBuffer(3, 4)), + api.getLockedAmount( + apiContext, + utils.getRandomBytes(20), + defaultTokenID, + utils.intToBuffer(3, 4), + ), ).resolves.toEqual(BigInt(0)); await expect( - api.getLockedAmount(apiContext, defaultAddress, defaultTokenID, intToBuffer(3, 4)), + api.getLockedAmount(apiContext, defaultAddress, defaultTokenID, utils.intToBuffer(3, 4)), ).resolves.toEqual(BigInt(0)); }); it('should return balance if data exists', async () => { await expect( - api.getLockedAmount(apiContext, defaultAddress, defaultTokenID, intToBuffer(12, 4)), + api.getLockedAmount(apiContext, defaultAddress, defaultTokenID, utils.intToBuffer(12, 4)), ).resolves.toEqual(defaultAccount.lockedBalances[0].amount); }); }); @@ -194,7 +199,7 @@ describe('token module', () => { }); it('should return false if account does not exist', async () => { - await expect(api.accountExists(apiContext, getRandomBytes(20))).resolves.toBeFalse(); + await expect(api.accountExists(apiContext, utils.getRandomBytes(20))).resolves.toBeFalse(); }); }); @@ -320,7 +325,7 @@ describe('token module', () => { describe('lock', () => { it('should reject amount is less than zero', async () => { await expect( - api.lock(apiContext, defaultAddress, intToBuffer(12, 4), defaultTokenID, BigInt(-1)), + api.lock(apiContext, defaultAddress, utils.intToBuffer(12, 4), defaultTokenID, BigInt(-1)), ).rejects.toThrow('Amount must be a positive integer to lock'); }); @@ -373,13 +378,25 @@ describe('token module', () => { describe('unlock', () => { it('should reject amount is less than zero', async () => { await expect( - api.unlock(apiContext, defaultAddress, intToBuffer(12, 4), defaultTokenID, BigInt(-1)), + api.unlock( + apiContext, + defaultAddress, + utils.intToBuffer(12, 4), + defaultTokenID, + BigInt(-1), + ), ).rejects.toThrow('Amount must be a positive integer to unlock'); }); it('should reject if address does not have any corresponding locked balance for the specified module', async () => { await expect( - api.unlock(apiContext, defaultAddress, intToBuffer(15, 4), defaultTokenID, BigInt(100)), + api.unlock( + apiContext, + defaultAddress, + utils.intToBuffer(15, 4), + defaultTokenID, + BigInt(100), + ), ).rejects.toThrow('No balance is locked for module ID 15'); }); @@ -439,7 +456,7 @@ describe('token module', () => { apiContext, defaultAddress, defaultTokenID.slice(0, CHAIN_ID_LENGTH), - getRandomBytes(20), + utils.getRandomBytes(20), defaultTokenID, BigInt('-3'), BigInt('10000'), @@ -454,7 +471,7 @@ describe('token module', () => { apiContext, defaultAddress.slice(1), defaultTokenID.slice(0, CHAIN_ID_LENGTH), - getRandomBytes(20), + utils.getRandomBytes(20), defaultTokenID, BigInt('100'), BigInt('10000'), @@ -469,7 +486,7 @@ describe('token module', () => { apiContext, defaultAddress, defaultTokenID.slice(0, CHAIN_ID_LENGTH), - getRandomBytes(19), + utils.getRandomBytes(19), defaultTokenID, BigInt('100'), BigInt('10000'), @@ -484,7 +501,7 @@ describe('token module', () => { apiContext, defaultAddress, defaultTokenID.slice(0, CHAIN_ID_LENGTH), - getRandomBytes(20), + utils.getRandomBytes(20), defaultTokenID, defaultAccount.availableBalance + BigInt(100000), BigInt('10000'), @@ -499,7 +516,7 @@ describe('token module', () => { apiContext, defaultAddress, defaultTokenID.slice(0, CHAIN_ID_LENGTH), - getRandomBytes(20), + utils.getRandomBytes(20), defaultTokenID, defaultAccount.availableBalance, BigInt('10000'), @@ -528,7 +545,7 @@ describe('token module', () => { apiContext, defaultAddress, receivingChainID, - getRandomBytes(20), + utils.getRandomBytes(20), defaultTokenID, defaultAccount.availableBalance - messageFee, messageFee, @@ -546,7 +563,7 @@ describe('token module', () => { apiContext, defaultAddress, defaultTokenID.slice(0, CHAIN_ID_LENGTH), - getRandomBytes(20), + utils.getRandomBytes(20), defaultTokenID, defaultAccount.availableBalance, BigInt('10000'), @@ -599,7 +616,7 @@ describe('token module', () => { apiContext, defaultAddress, defaultForeignTokenID.slice(0, CHAIN_ID_LENGTH), - getRandomBytes(20), + utils.getRandomBytes(20), defaultForeignTokenID, defaultAccount.availableBalance, BigInt('10000'), @@ -660,7 +677,7 @@ describe('token module', () => { apiContext, defaultAddress, receivingChainID, - getRandomBytes(20), + utils.getRandomBytes(20), defaultTokenID, defaultAccount.availableBalance - messageFee, messageFee, @@ -674,7 +691,7 @@ describe('token module', () => { apiContext, defaultAddress, receivingChainID, - getRandomBytes(20), + utils.getRandomBytes(20), defaultTokenID, defaultAccount.availableBalance, BigInt('10000'), diff --git a/framework/test/unit/modules/token/cc_commands/cc_forward.spec.ts b/framework/test/unit/modules/token/cc_commands/cc_forward.spec.ts index 39fea9ab7a4..c4598f87f13 100644 --- a/framework/test/unit/modules/token/cc_commands/cc_forward.spec.ts +++ b/framework/test/unit/modules/token/cc_commands/cc_forward.spec.ts @@ -47,7 +47,7 @@ import { InMemoryPrefixedStateDB } from '../../../../../src/testing/in_memory_pr import { fakeLogger } from '../../../../utils/mocks'; describe('CrossChain Forward command', () => { - const defaultAddress = getRandomBytes(20); + const defaultAddress = utils.getRandomBytes(20); const defaultTokenIDAlias = Buffer.alloc(TOKEN_ID_LENGTH, 0); const defaultTokenID = Buffer.from([0, 0, 0, 1, 0, 0, 0, 0]); const defaultForeignTokenID = Buffer.from([1, 0, 0, 0, 0, 0, 0, 0]); @@ -55,7 +55,7 @@ describe('CrossChain Forward command', () => { availableBalance: BigInt(10000000000), lockedBalances: [ { - moduleID: intToBuffer(12, 4), + moduleID: utils.intToBuffer(12, 4), amount: BigInt(100000000), }, ], @@ -161,7 +161,7 @@ describe('CrossChain Forward command', () => { fee: BigInt(30000), status: CCM_STATUS_OK, params: codec.encode(crossChainForwardMessageParams, { - tokenID: getRandomBytes(9), + tokenID: utils.getRandomBytes(9), amount: BigInt(1000), senderAddress: defaultAddress, forwardToChainID: Buffer.from([4, 0, 0, 0]), @@ -176,7 +176,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -202,7 +202,7 @@ describe('CrossChain Forward command', () => { params: codec.encode(crossChainForwardMessageParams, { tokenID: defaultTokenID, amount: BigInt(1000), - senderAddress: getRandomBytes(21), + senderAddress: utils.getRandomBytes(21), forwardToChainID: Buffer.from([4, 0, 0, 0]), recipientAddress: defaultAddress, data: 'ddd', @@ -215,7 +215,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -243,7 +243,7 @@ describe('CrossChain Forward command', () => { amount: BigInt(1000), senderAddress: defaultAddress, forwardToChainID: Buffer.from([4, 0, 0, 0]), - recipientAddress: getRandomBytes(19), + recipientAddress: utils.getRandomBytes(19), data: 'ddd', forwardedMessageFee: BigInt(2000), }), @@ -254,7 +254,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -293,7 +293,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -332,7 +332,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect(interopAPI.terminateChain).toHaveBeenCalledWith( @@ -373,7 +373,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect(interopAPI.terminateChain).toHaveBeenCalledWith( @@ -409,7 +409,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); await expect( @@ -444,7 +444,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect(interopAPI.error).toHaveBeenCalledWith( @@ -485,7 +485,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect(interopAPI.error).toHaveBeenCalledWith( @@ -527,7 +527,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); await expect( @@ -562,7 +562,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect(command['_interopAPI'].send).toHaveBeenCalledWith( @@ -605,7 +605,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); await expect( @@ -641,7 +641,7 @@ describe('CrossChain Forward command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); await expect( diff --git a/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts b/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts index ac3afd2278d..972cf133cb2 100644 --- a/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts +++ b/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts @@ -46,7 +46,7 @@ import { InMemoryPrefixedStateDB } from '../../../../../src/testing/in_memory_pr import { fakeLogger } from '../../../../utils/mocks'; describe('CrossChain Transfer command', () => { - const defaultAddress = getRandomBytes(20); + const defaultAddress = utils.getRandomBytes(20); const defaultTokenIDAlias = Buffer.alloc(TOKEN_ID_LENGTH, 0); const defaultTokenID = Buffer.from([0, 0, 0, 1, 0, 0, 0, 0]); const defaultForeignTokenID = Buffer.from([1, 0, 0, 0, 0, 0, 0, 0]); @@ -54,7 +54,7 @@ describe('CrossChain Transfer command', () => { availableBalance: BigInt(10000000000), lockedBalances: [ { - moduleID: intToBuffer(12, 4), + moduleID: utils.intToBuffer(12, 4), amount: BigInt(100000000), }, ], @@ -172,7 +172,7 @@ describe('CrossChain Transfer command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -196,7 +196,7 @@ describe('CrossChain Transfer command', () => { fee: BigInt(30000), status: CCM_STATUS_OK, params: codec.encode(crossChainTransferMessageParams, { - tokenID: getRandomBytes(9), + tokenID: utils.getRandomBytes(9), amount: BigInt(1000), senderAddress: defaultAddress, recipientAddress: defaultAddress, @@ -209,7 +209,7 @@ describe('CrossChain Transfer command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -235,7 +235,7 @@ describe('CrossChain Transfer command', () => { params: codec.encode(crossChainTransferMessageParams, { tokenID: defaultForeignTokenID, amount: BigInt(1000), - senderAddress: getRandomBytes(21), + senderAddress: utils.getRandomBytes(21), recipientAddress: defaultAddress, data: 'ddd', }), @@ -246,7 +246,7 @@ describe('CrossChain Transfer command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -273,7 +273,7 @@ describe('CrossChain Transfer command', () => { tokenID: defaultForeignTokenID, amount: BigInt(1000), senderAddress: defaultAddress, - recipientAddress: getRandomBytes(19), + recipientAddress: utils.getRandomBytes(19), data: 'ddd', }), }, @@ -283,7 +283,7 @@ describe('CrossChain Transfer command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -320,7 +320,7 @@ describe('CrossChain Transfer command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -357,7 +357,7 @@ describe('CrossChain Transfer command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -394,7 +394,7 @@ describe('CrossChain Transfer command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect((fakeLogger.debug as jest.Mock).mock.calls[0][0].err.message).toInclude( @@ -437,7 +437,7 @@ describe('CrossChain Transfer command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); expect(interopAPI.error).toHaveBeenCalledWith( @@ -476,7 +476,7 @@ describe('CrossChain Transfer command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); await expect( @@ -485,7 +485,7 @@ describe('CrossChain Transfer command', () => { }); it('should add amount to recipient address', async () => { - const recipientAddress = getRandomBytes(20); + const recipientAddress = utils.getRandomBytes(20); await expect( command.execute({ ccm: { @@ -510,7 +510,7 @@ describe('CrossChain Transfer command', () => { ccmSize: BigInt(30), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); await expect( diff --git a/framework/test/unit/modules/token/commands/transfer.spec.ts b/framework/test/unit/modules/token/commands/transfer.spec.ts index eb75e4f1cdb..6ab4f7f8a5d 100644 --- a/framework/test/unit/modules/token/commands/transfer.spec.ts +++ b/framework/test/unit/modules/token/commands/transfer.spec.ts @@ -80,14 +80,14 @@ describe('Transfer command', () => { commandID: COMMAND_ID_TRANSFER_BUFFER, fee: BigInt(5000000), nonce: BigInt(0), - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), params: codec.encode(transferParamsSchema, { tokenID: Buffer.from('0000000100', 'hex'), amount: BigInt(100000000), - recipientAddress: getRandomBytes(20), + recipientAddress: utils.getRandomBytes(20), data: '', }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); const result = await command.verify(context.createCommandVerifyContext(transferParamsSchema)); @@ -103,14 +103,14 @@ describe('Transfer command', () => { commandID: COMMAND_ID_TRANSFER_BUFFER, fee: BigInt(5000000), nonce: BigInt(0), - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), params: codec.encode(transferParamsSchema, { tokenID: Buffer.from('000000010000', 'hex'), amount: BigInt(100000000), - recipientAddress: getRandomBytes(30), + recipientAddress: utils.getRandomBytes(30), data: '', }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); const result = await command.verify(context.createCommandVerifyContext(transferParamsSchema)); @@ -126,14 +126,14 @@ describe('Transfer command', () => { commandID: COMMAND_ID_TRANSFER_BUFFER, fee: BigInt(5000000), nonce: BigInt(0), - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), params: codec.encode(transferParamsSchema, { tokenID: Buffer.from('000000010000', 'hex'), amount: BigInt(100000000), - recipientAddress: getRandomBytes(20), + recipientAddress: utils.getRandomBytes(20), data: '1'.repeat(65), }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); const result = await command.verify(context.createCommandVerifyContext(transferParamsSchema)); @@ -149,14 +149,14 @@ describe('Transfer command', () => { commandID: COMMAND_ID_TRANSFER_BUFFER, fee: BigInt(5000000), nonce: BigInt(0), - senderPublicKey: getRandomBytes(32), + senderPublicKey: utils.getRandomBytes(32), params: codec.encode(transferParamsSchema, { tokenID: Buffer.from('0000000100000000', 'hex'), amount: BigInt(100000000), - recipientAddress: getRandomBytes(20), + recipientAddress: utils.getRandomBytes(20), data: '1'.repeat(64), }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); const result = await command.verify(context.createCommandVerifyContext(transferParamsSchema)); @@ -214,10 +214,10 @@ describe('Transfer command', () => { params: codec.encode(transferParamsSchema, { tokenID, amount: senderBalance + BigInt(1), - recipientAddress: getRandomBytes(20), + recipientAddress: utils.getRandomBytes(20), data: '1'.repeat(64), }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); await expect( @@ -240,7 +240,7 @@ describe('Transfer command', () => { recipientAddress: recipient.address, data: '1'.repeat(64), }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); await expect( @@ -257,7 +257,7 @@ describe('Transfer command', () => { }); it('should reject when recipient does not exist and the token does not have min balance set', async () => { - const recipientAddress = getRandomBytes(20); + const recipientAddress = utils.getRandomBytes(20); const amount = BigInt(100000000); const context = createTransactionContext({ stateStore, @@ -273,7 +273,7 @@ describe('Transfer command', () => { recipientAddress, data: '1'.repeat(64), }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); await expect( @@ -282,7 +282,7 @@ describe('Transfer command', () => { }); it('should reject when recipient does not exist and amount is less than minBalance', async () => { - const recipientAddress = getRandomBytes(20); + const recipientAddress = utils.getRandomBytes(20); const amount = BigInt(100); const context = createTransactionContext({ stateStore, @@ -298,7 +298,7 @@ describe('Transfer command', () => { recipientAddress, data: '1'.repeat(64), }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); await expect( @@ -307,7 +307,7 @@ describe('Transfer command', () => { }); it('should resolve when recipient does not exist but amount is greater than minBalance', async () => { - const recipientAddress = getRandomBytes(20); + const recipientAddress = utils.getRandomBytes(20); const amount = BigInt(100000000); const context = createTransactionContext({ stateStore, @@ -323,7 +323,7 @@ describe('Transfer command', () => { recipientAddress, data: '1'.repeat(64), }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); await expect( @@ -348,7 +348,7 @@ describe('Transfer command', () => { }); it('should resolve and not burn supply when tokenID is not native and recipient does not exist', async () => { - const recipientAddress = getRandomBytes(20); + const recipientAddress = utils.getRandomBytes(20); const amount = BigInt(100000000); const context = createTransactionContext({ stateStore, @@ -364,7 +364,7 @@ describe('Transfer command', () => { recipientAddress, data: '1'.repeat(64), }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); await expect( @@ -404,7 +404,7 @@ describe('Transfer command', () => { recipientAddress: recipient.address, data: '1'.repeat(64), }), - signatures: [getRandomBytes(64)], + signatures: [utils.getRandomBytes(64)], }), }); await expect( diff --git a/framework/test/unit/modules/token/endpoint.spec.ts b/framework/test/unit/modules/token/endpoint.spec.ts index cc553d74599..a8db5c5e719 100644 --- a/framework/test/unit/modules/token/endpoint.spec.ts +++ b/framework/test/unit/modules/token/endpoint.spec.ts @@ -37,7 +37,7 @@ import { InMemoryPrefixedStateDB } from '../../../../src/testing/in_memory_prefi import { DEFAULT_TOKEN_ID } from '../../../utils/mocks/transaction'; describe('token endpoint', () => { - const defaultAddress = getRandomBytes(20); + const defaultAddress = utils.getRandomBytes(20); const defaultTokenIDAlias = Buffer.alloc(TOKEN_ID_LENGTH, 0); const defaultTokenID = Buffer.from([0, 0, 0, 1, 0, 0, 0, 0]); const defaultForeignTokenID = Buffer.from([1, 0, 0, 0, 0, 0, 0, 0]); @@ -45,7 +45,7 @@ describe('token endpoint', () => { availableBalance: BigInt(10000000000), lockedBalances: [ { - moduleID: intToBuffer(12, 4), + moduleID: utils.intToBuffer(12, 4), amount: BigInt(100000000), }, ], @@ -131,7 +131,7 @@ describe('token endpoint', () => { it('should return empty balances if account does not exist', async () => { const moduleEndpointContext = createTransientModuleEndpointContext({ stateStore, - params: { address: getRandomBytes(20).toString('hex') }, + params: { address: utils.getRandomBytes(20).toString('hex') }, }); const resp = await endpoint.getBalances(moduleEndpointContext); expect(resp).toEqual({ balances: [] }); @@ -193,7 +193,7 @@ describe('token endpoint', () => { const moduleEndpointContext = createTransientModuleEndpointContext({ stateStore, params: { - address: getRandomBytes(20).toString('hex'), + address: utils.getRandomBytes(20).toString('hex'), tokenID: defaultTokenID.toString('hex'), }, }); diff --git a/framework/test/unit/modules/token/init_genesis_state_fixture.ts b/framework/test/unit/modules/token/init_genesis_state_fixture.ts index 3ebfc44a583..e43a490fdc6 100644 --- a/framework/test/unit/modules/token/init_genesis_state_fixture.ts +++ b/framework/test/unit/modules/token/init_genesis_state_fixture.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; // import { getRandomBytes } from '@liskhq/lisk-cryptography'; @@ -24,21 +24,21 @@ const validData = { address: Buffer.alloc(20, 0), tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: oneUnit, - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: oneUnit }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: oneUnit }], }, { address: Buffer.alloc(20, 0), tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 1, 0]), availableBalance: oneUnit, - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: oneUnit }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: oneUnit }], }, { address: Buffer.alloc(20, 1), tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: oneUnit, lockedBalances: [ - { moduleID: intToBuffer(3, 4), amount: oneUnit }, - { moduleID: intToBuffer(4, 4), amount: oneUnit }, + { moduleID: utils.intToBuffer(3, 4), amount: oneUnit }, + { moduleID: utils.intToBuffer(4, 4), amount: oneUnit }, ], }, ], @@ -71,7 +71,7 @@ export const invalidGenesisAssets = [ address: Buffer.alloc(10, 0), tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: oneUnit, - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: oneUnit }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: oneUnit }], }, ...validData.userSubstore.slice(1), ], @@ -87,7 +87,7 @@ export const invalidGenesisAssets = [ address: Buffer.alloc(20, 0), tokenID: Buffer.from([9, 0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: oneUnit, - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: oneUnit }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: oneUnit }], }, ...validData.userSubstore.slice(1), ], @@ -103,7 +103,7 @@ export const invalidGenesisAssets = [ address: Buffer.alloc(20, 0), tokenID: Buffer.from([9, 0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: BigInt('1000000000000000000000000000'), - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: oneUnit }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: oneUnit }], }, ...validData.userSubstore.slice(1), ], @@ -119,7 +119,7 @@ export const invalidGenesisAssets = [ address: Buffer.alloc(20, 9), tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: BigInt('1000'), - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: oneUnit }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: oneUnit }], }, ...validData.userSubstore.slice(1), ], @@ -137,8 +137,8 @@ export const invalidGenesisAssets = [ tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: BigInt('1000'), lockedBalances: [ - { moduleID: intToBuffer(3, 4), amount: oneUnit }, - { moduleID: intToBuffer(2, 4), amount: oneUnit }, + { moduleID: utils.intToBuffer(3, 4), amount: oneUnit }, + { moduleID: utils.intToBuffer(2, 4), amount: oneUnit }, ], }, ], @@ -156,8 +156,8 @@ export const invalidGenesisAssets = [ tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: BigInt('1000'), lockedBalances: [ - { moduleID: intToBuffer(2, 4), amount: oneUnit }, - { moduleID: intToBuffer(2, 4), amount: oneUnit }, + { moduleID: utils.intToBuffer(2, 4), amount: oneUnit }, + { moduleID: utils.intToBuffer(2, 4), amount: oneUnit }, ], }, ], @@ -174,7 +174,7 @@ export const invalidGenesisAssets = [ address: Buffer.alloc(20, 2), tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: BigInt('1000'), - lockedBalances: [{ moduleID: intToBuffer(2, 4), amount: BigInt(0) }], + lockedBalances: [{ moduleID: utils.intToBuffer(2, 4), amount: BigInt(0) }], }, ], }, @@ -273,21 +273,21 @@ export const invalidGenesisAssets = [ address: Buffer.alloc(20, 0), tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: BigInt(2) ** BigInt(64) - BigInt(10), - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: oneUnit }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: oneUnit }], }, { address: Buffer.alloc(20, 0), tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 1, 0]), availableBalance: oneUnit, - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: oneUnit }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: oneUnit }], }, { address: Buffer.alloc(20, 1), tokenID: Buffer.from([0, 0, 0, 0, 0, 0, 0, 0]), availableBalance: BigInt(2) ** BigInt(64) - BigInt(10), lockedBalances: [ - { moduleID: intToBuffer(3, 4), amount: oneUnit }, - { moduleID: intToBuffer(4, 4), amount: oneUnit }, + { moduleID: utils.intToBuffer(3, 4), amount: oneUnit }, + { moduleID: utils.intToBuffer(4, 4), amount: oneUnit }, ], }, ], diff --git a/framework/test/unit/modules/token/interoperable_api.spec.ts b/framework/test/unit/modules/token/interoperable_api.spec.ts index cba7a101033..93fab3d788a 100644 --- a/framework/test/unit/modules/token/interoperable_api.spec.ts +++ b/framework/test/unit/modules/token/interoperable_api.spec.ts @@ -42,7 +42,7 @@ import { InMemoryPrefixedStateDB } from '../../../../src/testing/in_memory_prefi import { fakeLogger } from '../../../utils/mocks'; describe('CrossChain Forward command', () => { - const defaultAddress = getRandomBytes(20); + const defaultAddress = utils.getRandomBytes(20); const defaultTokenIDAlias = Buffer.alloc(TOKEN_ID_LENGTH, 0); const defaultTokenID = Buffer.from([0, 0, 0, 1, 0, 0, 0, 0]); const defaultForeignTokenID = Buffer.from([1, 0, 0, 0, 0, 0, 0, 0]); @@ -50,7 +50,7 @@ describe('CrossChain Forward command', () => { availableBalance: BigInt(10000000000), lockedBalances: [ { - moduleID: intToBuffer(12, 4), + moduleID: utils.intToBuffer(12, 4), amount: BigInt(100000000), }, ], @@ -61,7 +61,7 @@ describe('CrossChain Forward command', () => { const sendingChainID = Buffer.from([3, 0, 0, 0]); const ccu = { activeValidatorsUpdate: [], - certificate: getRandomBytes(20), + certificate: utils.getRandomBytes(20), inboxUpdate: { crossChainMessages: [], messageWitness: { @@ -172,14 +172,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: BigInt(-3), status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), ccu, trsSender: defaultAddress, }), @@ -198,14 +198,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee, status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), ccu, trsSender: defaultAddress, }), @@ -226,14 +226,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: fee + defaultEscrowAmount, status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), ccu, trsSender: defaultAddress, }), @@ -252,14 +252,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee, status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), ccu, trsSender: defaultAddress, }), @@ -285,14 +285,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: BigInt(-3), status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), trsSender: defaultAddress, }), ).rejects.toThrow('Fee must be greater or equal to zero'); @@ -310,14 +310,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee, status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), trsSender: defaultAddress, }), ).resolves.toBeUndefined(); @@ -337,14 +337,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: fee + defaultEscrowAmount, status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), trsSender: defaultAddress, }), ).resolves.toBeUndefined(); @@ -362,14 +362,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee, status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), trsSender: defaultAddress, }), ).resolves.toBeUndefined(); @@ -394,14 +394,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: BigInt(-3), status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).rejects.toThrow('Fee must be greater or equal to zero'); }); @@ -417,14 +417,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee, status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); await expect( @@ -443,14 +443,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: fee + defaultAccount.availableBalance + BigInt(1), status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).rejects.toThrow('does not have sufficient balance for fee'); }); @@ -466,14 +466,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee, status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), }), ).resolves.toBeUndefined(); await expect( @@ -494,20 +494,20 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: BigInt(-3), status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), moduleID: MODULE_ID_TOKEN_BUFFER, storeKey: Buffer.concat([defaultAddress, defaultTokenID]), storePrefix: STORE_PREFIX_ESCROW, storeValue: codec.encode(userStoreSchema, { availableBalance: defaultAccount.availableBalance * BigInt(2), - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: BigInt(20) }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: BigInt(20) }], }), terminatedChainID: sendingChainID, }), @@ -525,20 +525,20 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: BigInt(-3), status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), moduleID: MODULE_ID_TOKEN_BUFFER, storeKey: Buffer.concat([defaultAddress, defaultTokenID, Buffer.alloc(20)]), storePrefix: STORE_PREFIX_USER, storeValue: codec.encode(userStoreSchema, { availableBalance: defaultAccount.availableBalance * BigInt(2), - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: BigInt(20) }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: BigInt(20) }], }), terminatedChainID: sendingChainID, }), @@ -556,20 +556,20 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: BigInt(-3), status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), moduleID: MODULE_ID_TOKEN_BUFFER, storeKey: Buffer.concat([defaultAddress, defaultForeignTokenID]), storePrefix: STORE_PREFIX_USER, storeValue: codec.encode(userStoreSchema, { availableBalance: defaultAccount.availableBalance * BigInt(2), - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: BigInt(20) }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: BigInt(20) }], }), terminatedChainID: sendingChainID, }), @@ -577,7 +577,7 @@ describe('CrossChain Forward command', () => { }); it('should reject if not enough balance is escrowed', async () => { - const recipient = getRandomBytes(20); + const recipient = utils.getRandomBytes(20); await expect( tokenInteropAPI.recover({ ccm: { @@ -588,20 +588,20 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: BigInt(-3), status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), moduleID: MODULE_ID_TOKEN_BUFFER, storeKey: Buffer.concat([recipient, defaultTokenID]), storePrefix: STORE_PREFIX_USER, storeValue: codec.encode(userStoreSchema, { availableBalance: defaultEscrowAmount, - lockedBalances: [{ moduleID: intToBuffer(3, 4), amount: BigInt(20) }], + lockedBalances: [{ moduleID: utils.intToBuffer(3, 4), amount: BigInt(20) }], }), terminatedChainID: sendingChainID, }), @@ -609,7 +609,7 @@ describe('CrossChain Forward command', () => { }); it('should deduct escrowed amount for the total recovered amount', async () => { - const recipient = getRandomBytes(20); + const recipient = utils.getRandomBytes(20); await expect( tokenInteropAPI.recover({ ccm: { @@ -620,14 +620,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: BigInt(-3), status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), moduleID: MODULE_ID_TOKEN_BUFFER, storeKey: Buffer.concat([recipient, defaultTokenID]), storePrefix: STORE_PREFIX_USER, @@ -645,7 +645,7 @@ describe('CrossChain Forward command', () => { }); it('should credit the address for the total recovered amount', async () => { - const recipient = getRandomBytes(20); + const recipient = utils.getRandomBytes(20); await expect( tokenInteropAPI.recover({ ccm: { @@ -656,14 +656,14 @@ describe('CrossChain Forward command', () => { receivingChainID: Buffer.from([0, 0, 0, 1]), fee: BigInt(-3), status: CCM_STATUS_OK, - params: getRandomBytes(30), + params: utils.getRandomBytes(30), }, feeAddress: defaultAddress, getAPIContext: () => apiContext, eventQueue: new EventQueue(), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), moduleID: MODULE_ID_TOKEN_BUFFER, storeKey: Buffer.concat([recipient, defaultTokenID]), storePrefix: STORE_PREFIX_USER, diff --git a/framework/test/unit/modules/validators/api.spec.ts b/framework/test/unit/modules/validators/api.spec.ts index dfdb76c0d0e..cf3064ad07d 100644 --- a/framework/test/unit/modules/validators/api.spec.ts +++ b/framework/test/unit/modules/validators/api.spec.ts @@ -46,10 +46,10 @@ describe('ValidatorsModuleAPI', () => { blockTime: 10, }; const generatorConfig: any = {}; - const blsKey = getRandomBytes(48); - const address = getRandomBytes(48); - const generatorKey = getRandomBytes(48); - const proofOfPossession = getRandomBytes(48); + const blsKey = utils.getRandomBytes(48); + const address = utils.getRandomBytes(48); + const generatorKey = utils.getRandomBytes(48); + const proofOfPossession = utils.getRandomBytes(48); const genesisTimestamp = 1610643809; beforeAll(async () => { @@ -58,7 +58,7 @@ describe('ValidatorsModuleAPI', () => { }); beforeEach(() => { - validatorsAPI = new ValidatorsAPI(intToBuffer(MODULE_ID_VALIDATORS, 4)); + validatorsAPI = new ValidatorsAPI(utils.intToBuffer(MODULE_ID_VALIDATORS, 4)); stateStore = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); validatorsSubStore = stateStore.getStore( validatorsAPI['moduleID'], @@ -224,7 +224,7 @@ describe('ValidatorsModuleAPI', () => { describe('setValidatorGeneratorKey', () => { it('should be able to correctly set generator key for validator if address exists', async () => { - const generatorKey1 = getRandomBytes(48); + const generatorKey1 = utils.getRandomBytes(48); const validatorAccount = { generatorKey, blsKey, @@ -481,14 +481,14 @@ describe('ValidatorsModuleAPI', () => { }); describe('getValidatorAccount', () => { - const validAddress = getRandomBytes(20); + const validAddress = utils.getRandomBytes(20); let validatorAccount: ValidatorKeys; beforeEach(async () => { apiContext = createNewAPIContext(new InMemoryPrefixedStateDB()); validatorAccount = { - generatorKey: getRandomBytes(48), - blsKey: getRandomBytes(32), + generatorKey: utils.getRandomBytes(48), + blsKey: utils.getRandomBytes(32), }; const validatorsStore = apiContext.getStore( @@ -507,7 +507,7 @@ describe('ValidatorsModuleAPI', () => { }); it('should throw when address length is not 20', async () => { - const invalidAddress = getRandomBytes(19); + const invalidAddress = utils.getRandomBytes(19); await expect(validatorsAPI.getValidatorAccount(apiContext, invalidAddress)).rejects.toThrow( 'Address is not valid', ); diff --git a/framework/test/unit/modules/validators/endpoint.spec.ts b/framework/test/unit/modules/validators/endpoint.spec.ts index e4ec499183f..732780b399c 100644 --- a/framework/test/unit/modules/validators/endpoint.spec.ts +++ b/framework/test/unit/modules/validators/endpoint.spec.ts @@ -21,9 +21,9 @@ import { fakeLogger } from '../../../utils/mocks'; describe('ValidatorsModuleEndpoint', () => { const logger: Logger = fakeLogger; let validatorsModule: ValidatorsModule; - const pk = getRandomBytes(48); - const address = getRandomBytes(48); - const proof = getRandomBytes(48); + const pk = utils.getRandomBytes(48); + const address = utils.getRandomBytes(48); + const proof = utils.getRandomBytes(48); const getStore1 = jest.fn(); const subStore = (new InMemoryDatabase() as unknown) as Database; const networkIdentifier = Buffer.alloc(0); diff --git a/framework/test/unit/state_machine/custom_modules.ts b/framework/test/unit/state_machine/custom_modules.ts index 65b2f1aed06..7fb6b235130 100644 --- a/framework/test/unit/state_machine/custom_modules.ts +++ b/framework/test/unit/state_machine/custom_modules.ts @@ -13,7 +13,7 @@ */ /* eslint-disable max-classes-per-file */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { BaseAPI, BaseCommand, BaseEndpoint, BaseModule } from '../../../src'; import { TransactionVerifyResult } from '../../../src/abi'; import { ModuleMetadata } from '../../../src/modules/base_module'; @@ -25,7 +25,7 @@ import { } from '../../../src/state_machine'; export class CustomCommand0 extends BaseCommand { - public id = intToBuffer(0, 4); + public id = utils.intToBuffer(0, 4); public name = 'customCommand0'; public schema = { $id: '/lisk/customCommand0', @@ -43,9 +43,9 @@ export class CustomCommand0 extends BaseCommand { } export class CustomModule0 extends BaseModule { - public id = intToBuffer(3, 4); + public id = utils.intToBuffer(3, 4); public name = 'customModule0'; - public commands = [new CustomCommand0(intToBuffer(3, 4))]; + public commands = [new CustomCommand0(utils.intToBuffer(3, 4))]; public api = ({ testing: jest.fn(), } as unknown) as BaseAPI; @@ -64,7 +64,7 @@ export class CustomModule0 extends BaseModule { } export class CustomModule1 extends BaseModule { - public id = intToBuffer(4, 4); + public id = utils.intToBuffer(4, 4); public name = 'customModule1'; public commands = []; public endpoint: BaseEndpoint = {} as BaseEndpoint; @@ -79,7 +79,7 @@ export class CustomModule1 extends BaseModule { } export class CustomCommand2 extends BaseCommand { - public id = intToBuffer(0, 4); + public id = utils.intToBuffer(0, 4); public name = 'customCommand2'; public schema = { $id: '/lisk/customCommand2', @@ -96,16 +96,16 @@ export class CustomCommand2 extends BaseCommand { // eslint-disable-next-line @typescript-eslint/require-await public async execute(ctx: TransactionExecuteContext): Promise { - ctx.eventQueue.add(intToBuffer(5, 4), Buffer.from([0, 0, 0, 1]), Buffer.from([0, 0, 2])); + ctx.eventQueue.add(utils.intToBuffer(5, 4), Buffer.from([0, 0, 0, 1]), Buffer.from([0, 0, 2])); } } export class CustomModule2 extends BaseModule { - public id = intToBuffer(5, 4); + public id = utils.intToBuffer(5, 4); public name = 'customModule2'; public endpoint: BaseEndpoint = {} as BaseEndpoint; public api: BaseAPI = {} as BaseAPI; - public commands = [new CustomCommand2(intToBuffer(5, 4))]; + public commands = [new CustomCommand2(utils.intToBuffer(5, 4))]; public verifyTransaction = jest .fn() diff --git a/framework/test/unit/state_machine/event_queue.spec.ts b/framework/test/unit/state_machine/event_queue.spec.ts index f352331c64d..60d8b11edc0 100644 --- a/framework/test/unit/state_machine/event_queue.spec.ts +++ b/framework/test/unit/state_machine/event_queue.spec.ts @@ -20,28 +20,33 @@ describe('EventQueue', () => { // Arrange const events = [ { - moduleID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(3, 4), typeID: Buffer.from([0, 0, 0, 0]), - data: getRandomBytes(20), - topics: [getRandomBytes(32), getRandomBytes(20)], + data: utils.getRandomBytes(20), + topics: [utils.getRandomBytes(32), utils.getRandomBytes(20)], }, { - moduleID: intToBuffer(4, 4), + moduleID: utils.intToBuffer(4, 4), typeID: Buffer.from([0, 0, 0, 0]), - data: getRandomBytes(20), - topics: [getRandomBytes(32), getRandomBytes(20)], + data: utils.getRandomBytes(20), + topics: [utils.getRandomBytes(32), utils.getRandomBytes(20)], }, { - moduleID: intToBuffer(2, 4), + moduleID: utils.intToBuffer(2, 4), typeID: Buffer.from([0, 0, 0, 0]), - data: getRandomBytes(20), - topics: [getRandomBytes(32)], + data: utils.getRandomBytes(20), + topics: [utils.getRandomBytes(32)], }, { - moduleID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(1, 4), typeID: Buffer.from([0, 0, 0, 0]), - data: getRandomBytes(20), - topics: [getRandomBytes(32), getRandomBytes(20), getRandomBytes(20), getRandomBytes(20)], + data: utils.getRandomBytes(20), + topics: [ + utils.getRandomBytes(32), + utils.getRandomBytes(20), + utils.getRandomBytes(20), + utils.getRandomBytes(20), + ], }, ]; let eventQueue: EventQueue; @@ -55,8 +60,8 @@ describe('EventQueue', () => { eventQueue.add( intToBuffer(2, 4), Buffer.from([0, 0, 0, 1]), - getRandomBytes(EVENT_MAX_EVENT_SIZE_BYTES + 1), - [getRandomBytes(32)], + utils.getRandomBytes(EVENT_MAX_EVENT_SIZE_BYTES + 1), + [utils.getRandomBytes(32)], ), ).toThrow('Max size of event data is'); }); @@ -66,7 +71,7 @@ describe('EventQueue', () => { eventQueue.add( intToBuffer(2, 4), Buffer.from([0, 0, 0, 1]), - getRandomBytes(EVENT_MAX_EVENT_SIZE_BYTES), + utils.getRandomBytes(EVENT_MAX_EVENT_SIZE_BYTES), [], ), ).toThrow('Topics must have at least one element'); @@ -77,8 +82,8 @@ describe('EventQueue', () => { eventQueue.add( intToBuffer(2, 4), Buffer.from([0, 0, 0, 1]), - getRandomBytes(EVENT_MAX_EVENT_SIZE_BYTES), - new Array(5).fill(0).map(() => getRandomBytes(32)), + utils.getRandomBytes(EVENT_MAX_EVENT_SIZE_BYTES), + new Array(5).fill(0).map(() => utils.getRandomBytes(32)), ), ).toThrow('Max topics per event is'); }); @@ -104,8 +109,8 @@ describe('EventQueue', () => { expect(eventQueue.getEvents()).toHaveLength(events.length); eventQueue.createSnapshot(); - eventQueue.add(intToBuffer(3, 4), Buffer.from([0, 0, 0, 1]), getRandomBytes(100), [ - getRandomBytes(32), + eventQueue.add(utils.intToBuffer(3, 4), Buffer.from([0, 0, 0, 1]), utils.getRandomBytes(100), [ + utils.getRandomBytes(32), ]); eventQueue.restoreSnapshot(); @@ -127,22 +132,22 @@ describe('EventQueue', () => { eventQueue.add( intToBuffer(3, 4), Buffer.from([0, 0, 0, 1]), - getRandomBytes(100), - [getRandomBytes(32)], + utils.getRandomBytes(100), + [utils.getRandomBytes(32)], false, ); eventQueue.add( intToBuffer(3, 4), Buffer.from([0, 0, 0, 1]), - getRandomBytes(100), - [getRandomBytes(32)], + utils.getRandomBytes(100), + [utils.getRandomBytes(32)], true, ); eventQueue.add( intToBuffer(3, 4), Buffer.from([0, 0, 0, 1]), - getRandomBytes(100), - [getRandomBytes(32)], + utils.getRandomBytes(100), + [utils.getRandomBytes(32)], false, ); eventQueue.restoreSnapshot(); diff --git a/framework/test/unit/state_machine/state_machine.spec.ts b/framework/test/unit/state_machine/state_machine.spec.ts index ce79f51c738..e2280e289b3 100644 --- a/framework/test/unit/state_machine/state_machine.spec.ts +++ b/framework/test/unit/state_machine/state_machine.spec.ts @@ -39,8 +39,8 @@ describe('state_machine', () => { let eventQueue: EventQueue; const networkIdentifier = Buffer.from('network identifier', 'utf8'); const transaction = { - moduleID: intToBuffer(3, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(3, 4), + commandID: utils.intToBuffer(0, 4), params: {}, } as Transaction; @@ -155,10 +155,10 @@ describe('state_machine', () => { transaction, currentValidators: [ { - address: getRandomBytes(20), + address: utils.getRandomBytes(20), bftWeight: BigInt(1), - blsKey: getRandomBytes(48), - generatorKey: getRandomBytes(32), + blsKey: utils.getRandomBytes(48), + generatorKey: utils.getRandomBytes(32), }, ], impliesMaxPrevote: true, diff --git a/framework/test/unit/testing/create_block.spec.ts b/framework/test/unit/testing/create_block.spec.ts index ae65c5ab04c..ea828fd93e7 100644 --- a/framework/test/unit/testing/create_block.spec.ts +++ b/framework/test/unit/testing/create_block.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { Block, BlockAssets } from '@liskhq/lisk-chain'; -import { getNetworkIdentifier } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { createBlock } from '../../../src/testing/create_block'; import * as devnetConfig from '../../fixtures/config/devnet/config.json'; diff --git a/framework/test/utils/configs/config_constants.ts b/framework/test/utils/configs/config_constants.ts index 3b3e3991291..f30225475e5 100644 --- a/framework/test/utils/configs/config_constants.ts +++ b/framework/test/utils/configs/config_constants.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; export const constantsConfig = (overriddenConfigProperties = {}) => ({ blockTime: 10, @@ -35,8 +35,8 @@ export const constantsConfig = (overriddenConfigProperties = {}) => ({ minFeePerByte: 1000, baseFees: [ { - moduleID: intToBuffer(5, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(5, 4), + commandID: utils.intToBuffer(0, 4), baseFee: '1000000000', }, ], diff --git a/framework/test/utils/mocks/endpoint.ts b/framework/test/utils/mocks/endpoint.ts index 7c782f97e87..7d17df09cd2 100644 --- a/framework/test/utils/mocks/endpoint.ts +++ b/framework/test/utils/mocks/endpoint.ts @@ -26,6 +26,6 @@ export const createContext = ( getImmutableAPIContext: () => createImmutableAPIContext(stateStore), getStore: (moduleID: Buffer, prefix: number) => stateStore.getStore(moduleID, prefix), logger: fakeLogger, - networkIdentifier: getRandomBytes(32), + networkIdentifier: utils.getRandomBytes(32), params, }); diff --git a/framework/test/utils/mocks/transaction.ts b/framework/test/utils/mocks/transaction.ts index 6ad4551fe64..a37af2a0fb5 100644 --- a/framework/test/utils/mocks/transaction.ts +++ b/framework/test/utils/mocks/transaction.ts @@ -53,8 +53,8 @@ export const createTransferTransaction = (input: { const { publicKey } = getAddressAndPublicKeyFromPassphrase(input.passphrase); const tx = new Transaction({ - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: input.nonce, senderPublicKey: publicKey, fee: input.fee ?? BigInt('200000'), @@ -86,8 +86,8 @@ export const createDelegateRegisterTransaction = (input: { }); const tx = new Transaction({ - moduleID: intToBuffer(13, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(13, 4), + commandID: utils.intToBuffer(0, 4), nonce: input.nonce, senderPublicKey: publicKey, fee: input.fee ?? BigInt('2500000000'), @@ -113,8 +113,8 @@ export const createDelegateVoteTransaction = (input: { const { publicKey } = getAddressAndPublicKeyFromPassphrase(input.passphrase); const tx = new Transaction({ - moduleID: intToBuffer(13, 4), - commandID: intToBuffer(1, 4), + moduleID: utils.intToBuffer(13, 4), + commandID: utils.intToBuffer(1, 4), nonce: input.nonce, senderPublicKey: publicKey, fee: input.fee ?? BigInt('100000000'), @@ -160,8 +160,8 @@ export const createMultiSignRegisterTransaction = (input: { ); }, { - moduleID: intToBuffer(12, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(12, 4), + commandID: utils.intToBuffer(0, 4), nonce: input.nonce, senderPublicKey: publicKey, fee: input.fee ?? BigInt('1100000000'), @@ -207,8 +207,8 @@ export const createMultisignatureTransferTransaction = (input: { ); }, { - moduleID: intToBuffer(2, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(2, 4), + commandID: utils.intToBuffer(0, 4), nonce: input.nonce, senderPublicKey: input.senderPublicKey, fee: input.fee ?? BigInt('1100000000'), @@ -236,8 +236,8 @@ export const createReportMisbehaviorTransaction = (input: { const { publicKey } = getAddressAndPublicKeyFromPassphrase(input.passphrase); const tx = new Transaction({ - moduleID: intToBuffer(13, 4), - commandID: intToBuffer(3, 4), + moduleID: utils.intToBuffer(13, 4), + commandID: utils.intToBuffer(3, 4), nonce: input.nonce, senderPublicKey: publicKey, fee: input.fee ?? BigInt('50000000'), diff --git a/protocol-specs/generators/address_generation/index.js b/protocol-specs/generators/address_generation/index.js index f9dc284cf87..70df472487d 100644 --- a/protocol-specs/generators/address_generation/index.js +++ b/protocol-specs/generators/address_generation/index.js @@ -35,7 +35,7 @@ const GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; const getBinaryAddress = publicKey => { const publicKeyBuffer = Buffer.from(publicKey, 'hex'); - return hash(publicKeyBuffer).slice(0, 20); + return utils.hash(publicKeyBuffer).slice(0, 20); }; const polymod = uint5Array => { diff --git a/protocol-specs/generators/dpos_delegate_shuffling/index.js b/protocol-specs/generators/dpos_delegate_shuffling/index.js index 80d1e83db42..f3215f5d2f8 100644 --- a/protocol-specs/generators/dpos_delegate_shuffling/index.js +++ b/protocol-specs/generators/dpos_delegate_shuffling/index.js @@ -25,7 +25,7 @@ const generateShuffledDelegateList = () => { })); for (const delegate of delegateList) { const seedSource = Buffer.concat([Buffer.from(previousRoundSeed1, 'hex'), delegate.address]); - delegate.roundHash = hash(seedSource); + delegate.roundHash = utils.hash(seedSource); } delegateList.sort((delegate1, delegate2) => { diff --git a/protocol-specs/generators/dpos_delegate_shuffling/sample_generator.js b/protocol-specs/generators/dpos_delegate_shuffling/sample_generator.js index 26b63a10a4c..66f2ce51339 100644 --- a/protocol-specs/generators/dpos_delegate_shuffling/sample_generator.js +++ b/protocol-specs/generators/dpos_delegate_shuffling/sample_generator.js @@ -25,7 +25,7 @@ const generateDelegates = num => { for (let i = 0; i < num; i += 1) { const passphrase = Mnemonic.generateMnemonic(); const { publicKey } = getKeys(passphrase); - const address = hash(Buffer.from(publicKey, 'hex')).slice(0, 20); + const address = utils.hash(Buffer.from(publicKey, 'hex')).slice(0, 20); delegateList.push({ address, diff --git a/protocol-specs/generators/dpos_forger_selection/sample_generator.js b/protocol-specs/generators/dpos_forger_selection/sample_generator.js index 25f8fb85b30..10c1faab4b5 100644 --- a/protocol-specs/generators/dpos_forger_selection/sample_generator.js +++ b/protocol-specs/generators/dpos_forger_selection/sample_generator.js @@ -26,7 +26,7 @@ const generateDelegates = (num, fixedNum) => { for (let i = 0; i < num; i += 1) { const passphrase = Mnemonic.generateMnemonic(); const { publicKey } = getKeys(passphrase); - const address = hash(Buffer.from(publicKey, 'hex')).slice(0, 20); + const address = utils.hash(Buffer.from(publicKey, 'hex')).slice(0, 20); const buf = crypto.randomBytes(8); const randomNumber = buf.readBigUInt64BE() / BigInt(10) ** BigInt(8); const voteWeight = fixedValue diff --git a/protocol-specs/generators/dpos_random_seed_generation/index.js b/protocol-specs/generators/dpos_random_seed_generation/index.js index 3562dd9b506..35665b4c4fa 100644 --- a/protocol-specs/generators/dpos_random_seed_generation/index.js +++ b/protocol-specs/generators/dpos_random_seed_generation/index.js @@ -35,7 +35,7 @@ const strippedHash = data => { throw new Error('Hash input is not a valid type'); } - return hash(data).slice(0, 16); + return utils.hash(data).slice(0, 16); }; const bitwiseXOR = bufferArray => { @@ -60,7 +60,7 @@ const bitwiseXOR = bufferArray => { const generateSeedOnion = (initialSeed, size) => { const seeds = new Array(size); - seeds[0] = hash(initialSeed, 'hex'); + seeds[0] = utils.hash(initialSeed, 'hex'); for (let i = 1; i < size; i += 1) { seeds[i] = strippedHash(seeds[i - 1], 'hex'); diff --git a/protocol-specs/generators/multisignature_registration/index.js b/protocol-specs/generators/multisignature_registration/index.js index 6068f2fad4c..f80d42e6fac 100644 --- a/protocol-specs/generators/multisignature_registration/index.js +++ b/protocol-specs/generators/multisignature_registration/index.js @@ -150,8 +150,8 @@ const createSignatureObject = (txBuffer, account) => ({ const generateValidMultisignatureRegistrationTransaction = () => { // basic transaction const unsignedTransaction = { - moduleID: intToBuffer(12, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(12, 4), + commandID: utils.intToBuffer(0, 4), senderPublicKey: Buffer.from( '0b211fce4b615083701cb8a8c99407e464b2f9aa4f367095322de1b77e5fcfbe', 'hex', @@ -219,8 +219,8 @@ const generateValidMultisignatureRegistrationSenderIsMemberTransaction = () => { ), nonce: BigInt('1'), fee: BigInt('1500000000'), - moduleID: intToBuffer(12, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(12, 4), + commandID: utils.intToBuffer(0, 4), params: { mandatoryKeys: [ Buffer.from('0b211fce4b615083701cb8a8c99407e464b2f9aa4f367095322de1b77e5fcfbe', 'hex'), @@ -288,8 +288,8 @@ const generateValidMultisignatureRegistrationOnlyOptionalMembersTransaction = () ), nonce: BigInt('1'), fee: BigInt('1500000000'), - moduleID: intToBuffer(12, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(12, 4), + commandID: utils.intToBuffer(0, 4), params: { mandatoryKeys: [], optionalKeys: [ @@ -345,8 +345,8 @@ const generateValidMultisignatureRegistrationOnlyMandatoryMembersTransaction = ( ), nonce: BigInt('1'), fee: BigInt('1500000000'), - moduleID: intToBuffer(12, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(12, 4), + commandID: utils.intToBuffer(0, 4), params: { mandatoryKeys: [ Buffer.from('4a67646a446313db964c39370359845c52fce9225a3929770ef41448c258fd39', 'hex'), @@ -416,8 +416,8 @@ const generateFormerSecondSignatureTransactioon = () => { ), nonce: BigInt('1'), fee: BigInt('1500000000'), - moduleID: intToBuffer(12, 4), - commandID: intToBuffer(0, 4), + moduleID: utils.intToBuffer(12, 4), + commandID: utils.intToBuffer(0, 4), params: { mandatoryKeys: [ Buffer.from('0b211fce4b615083701cb8a8c99407e464b2f9aa4f367095322de1b77e5fcfbe', 'hex'), diff --git a/protocol-specs/generators/proof_of_misbehavior_transaction/index.js b/protocol-specs/generators/proof_of_misbehavior_transaction/index.js index e11769a1fe3..7adc73be936 100644 --- a/protocol-specs/generators/proof_of_misbehavior_transaction/index.js +++ b/protocol-specs/generators/proof_of_misbehavior_transaction/index.js @@ -200,7 +200,7 @@ const scenario1Header1 = { ), height: 900000, reward: BigInt('10000000000'), - transactionRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), generatorPublicKey: Buffer.from( 'addb0e15a44b0fdc6ff291be28d8c98f5551d0cd9218d749e30ddb87c6e31ca9', 'hex', @@ -223,7 +223,7 @@ const scenario1Header2 = { ), height: 800000, reward: BigInt('10000000000'), - transactionRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), generatorPublicKey: Buffer.from( 'addb0e15a44b0fdc6ff291be28d8c98f5551d0cd9218d749e30ddb87c6e31ca9', 'hex', @@ -291,7 +291,7 @@ const scenario2Header1 = { ), height: 800000, reward: BigInt('10000000000'), - transactionRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), generatorPublicKey: Buffer.from( 'addb0e15a44b0fdc6ff291be28d8c98f5551d0cd9218d749e30ddb87c6e31ca9', 'hex', @@ -314,7 +314,7 @@ const scenario2Header2 = { ), height: 800000, reward: BigInt('10000000000'), - transactionRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), generatorPublicKey: Buffer.from( 'addb0e15a44b0fdc6ff291be28d8c98f5551d0cd9218d749e30ddb87c6e31ca9', 'hex', @@ -381,7 +381,7 @@ const scenario3Header1 = { ), height: 900000, reward: BigInt('10000000000'), - transactionRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), generatorPublicKey: Buffer.from( 'addb0e15a44b0fdc6ff291be28d8c98f5551d0cd9218d749e30ddb87c6e31ca9', 'hex', @@ -404,7 +404,7 @@ const scenario3Header2 = { ), height: 900000, reward: BigInt('10000000000'), - transactionRoot: hash(Buffer.alloc(0)), + transactionRoot: utils.hash(Buffer.alloc(0)), generatorPublicKey: Buffer.from( 'addb0e15a44b0fdc6ff291be28d8c98f5551d0cd9218d749e30ddb87c6e31ca9', 'hex', diff --git a/protocol-specs/generators/transaction_merkle_root_for_blocks/index.js b/protocol-specs/generators/transaction_merkle_root_for_blocks/index.js index 070e7201e81..43458d6c162 100644 --- a/protocol-specs/generators/transaction_merkle_root_for_blocks/index.js +++ b/protocol-specs/generators/transaction_merkle_root_for_blocks/index.js @@ -20,23 +20,23 @@ const BaseGenerator = require('../base_generator'); const getRandomTransactionIds = count => { const ids = []; for (let index = 0; index < count; index += 1) { - ids.push(getRandomBytes(32)); + ids.push(utils.getRandomBytes(32)); } return ids; }; -const LEAFPREFIX = intToBuffer(0); -const BRANCHPREFIX = intToBuffer(1); +const LEAFPREFIX = utils.intToBuffer(0); +const BRANCHPREFIX = utils.intToBuffer(1); const concat = (m1, m2) => Buffer.concat([m1, m2]); -const leafHash = m => hash(concat(LEAFPREFIX, m)); +const leafHash = m => utils.hash(concat(LEAFPREFIX, m)); -const branchHash = m => hash(concat(BRANCHPREFIX, m)); +const branchHash = m => utils.hash(concat(BRANCHPREFIX, m)); const merkleRoot = transactionIds => { const len = transactionIds.length; - if (len === 0) return hash(Buffer.from([])); + if (len === 0) return utils.hash(Buffer.from([])); if (len === 1) return leafHash(transactionIds[0]); const k = 2 ** Math.floor(Math.log2(len - 1)); From d955c0d10b6b2ba23b7f6c2f3482af25ecd4a2a6 Mon Sep 17 00:00:00 2001 From: shuse2 Date: Mon, 18 Jul 2022 13:34:14 +0200 Subject: [PATCH 3/6] :recycle: Fix cryptography tests --- elements/lisk-cryptography/src/encrypt.ts | 12 +- .../test/{keys.spec.ts => address.spec.ts} | 16 +- elements/lisk-cryptography/test/bls.spec.ts | 22 +- .../lisk-cryptography/test/buffer.spec.ts | 185 -------- .../lisk-cryptography/test/convert.spec.ts | 202 --------- .../test/{sign.spec.ts => ed.spec.ts} | 114 +++-- .../lisk-cryptography/test/encrypt.spec.ts | 208 +++++---- elements/lisk-cryptography/test/hash.spec.ts | 79 ---- .../lisk-cryptography/test/hash_onion.spec.ts | 54 --- .../test/legacy_address.spec.ts | 16 + .../test/message_tag.spec.ts | 72 ---- .../lisk-cryptography/test/nacl/index.spec.ts | 8 +- .../lisk-cryptography/test/nacl/nacl.spec.ts | 2 +- elements/lisk-cryptography/test/utils.spec.ts | 407 ++++++++++++++++-- 14 files changed, 622 insertions(+), 775 deletions(-) rename elements/lisk-cryptography/test/{keys.spec.ts => address.spec.ts} (95%) delete mode 100644 elements/lisk-cryptography/test/buffer.spec.ts delete mode 100644 elements/lisk-cryptography/test/convert.spec.ts rename elements/lisk-cryptography/test/{sign.spec.ts => ed.spec.ts} (71%) delete mode 100644 elements/lisk-cryptography/test/hash.spec.ts delete mode 100644 elements/lisk-cryptography/test/hash_onion.spec.ts delete mode 100644 elements/lisk-cryptography/test/message_tag.spec.ts diff --git a/elements/lisk-cryptography/src/encrypt.ts b/elements/lisk-cryptography/src/encrypt.ts index 962be470145..9010067242a 100644 --- a/elements/lisk-cryptography/src/encrypt.ts +++ b/elements/lisk-cryptography/src/encrypt.ts @@ -32,10 +32,6 @@ const ARGON2_ITERATIONS = 1; const ARGON2_PARALLELISM = 4; const ARGON2_MEMORY = 2024; -const convertPublicKeyEd2Curve = ed2curve.convertPublicKey; - -const convertPrivateKeyEd2Curve = ed2curve.convertSecretKey; - export interface EncryptedMessageWithNonce { readonly encryptedMessage: string; readonly nonce: string; @@ -47,11 +43,11 @@ export const encryptMessageWithPassphrase = ( recipientPublicKey: Buffer, ): EncryptedMessageWithNonce => { const { privateKey: senderPrivateKeyBytes } = getPrivateAndPublicKeyFromPassphrase(passphrase); - const convertedPrivateKey = Buffer.from(convertPrivateKeyEd2Curve(senderPrivateKeyBytes)); + const convertedPrivateKey = Buffer.from(ed2curve.convertSecretKey(senderPrivateKeyBytes)); const messageInBytes = Buffer.from(message, 'utf8'); const nonceSize = 24; const nonce = getRandomBytes(nonceSize); - const publicKeyUint8Array = convertPublicKeyEd2Curve(recipientPublicKey); + const publicKeyUint8Array = ed2curve.convertPublicKey(recipientPublicKey); // This cannot be reproduced, but external library have type union with null if (publicKeyUint8Array === null) { @@ -78,11 +74,11 @@ export const decryptMessageWithPassphrase = ( senderPublicKey: Buffer, ): string => { const { privateKey: recipientPrivateKeyBytes } = getPrivateAndPublicKeyFromPassphrase(passphrase); - const convertedPrivateKey = Buffer.from(convertPrivateKeyEd2Curve(recipientPrivateKeyBytes)); + const convertedPrivateKey = Buffer.from(ed2curve.convertSecretKey(recipientPrivateKeyBytes)); const cipherBytes = hexToBuffer(cipherHex); const nonceBytes = hexToBuffer(nonce); - const publicKeyUint8Array = convertPublicKeyEd2Curve(senderPublicKey); + const publicKeyUint8Array = ed2curve.convertPublicKey(senderPublicKey); // This cannot be reproduced, but external library have type union with null if (publicKeyUint8Array === null) { diff --git a/elements/lisk-cryptography/test/keys.spec.ts b/elements/lisk-cryptography/test/address.spec.ts similarity index 95% rename from elements/lisk-cryptography/test/keys.spec.ts rename to elements/lisk-cryptography/test/address.spec.ts index a2b2621fd36..bb4b70c61f3 100644 --- a/elements/lisk-cryptography/test/keys.spec.ts +++ b/elements/lisk-cryptography/test/address.spec.ts @@ -24,15 +24,11 @@ import { getAddressFromLisk32Address, getLisk32AddressFromAddress, getLisk32AddressFromPassphrase, -} from '../src/keys'; +} from '../src/address'; import { Keypair } from '../src/types'; -// Require is used for stubbing -// eslint-disable-next-line -const buffer = require('../src/buffer'); -// eslint-disable-next-line -const hashModule = require('../src/hash'); +import * as utils from '../src/utils'; -describe('keys', () => { +describe('address', () => { const defaultPassphrase = 'secret'; const defaultPassphraseHash = '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b'; const defaultPrivateKey = Buffer.from( @@ -51,9 +47,9 @@ describe('keys', () => { }; beforeEach(() => { - jest.spyOn(buffer, 'bufferToHex'); + jest.spyOn(utils, 'bufferToHex'); - jest.spyOn(hashModule, 'hash').mockReturnValue(Buffer.from(defaultPassphraseHash, 'hex')); + jest.spyOn(utils, 'hash').mockReturnValue(Buffer.from(defaultPassphraseHash, 'hex')); }); describe('#getPrivateAndPublicKeyFromPassphrase', () => { @@ -123,7 +119,7 @@ describe('keys', () => { const hash = 'c247a42e09e6aafd818821f75b2f5b0de47c8235'; const expectedLisk32Address = 'lsk24cd35u4jdq8szo3pnsqe5dsxwrnazyqqqg5eu'; beforeEach(() => { - return jest.spyOn(hashModule, 'hash').mockReturnValue(Buffer.from(hash, 'hex')); + return jest.spyOn(utils, 'hash').mockReturnValue(Buffer.from(hash, 'hex')); }); it('should generate lisk32 address from publicKey', () => { diff --git a/elements/lisk-cryptography/test/bls.spec.ts b/elements/lisk-cryptography/test/bls.spec.ts index dd696d09c69..9034bc04220 100644 --- a/elements/lisk-cryptography/test/bls.spec.ts +++ b/elements/lisk-cryptography/test/bls.spec.ts @@ -14,7 +14,14 @@ * */ -import { createAggSig, signBLS, verifyAggSig, verifyWeightedAggSig, verifyBLS } from '../src/bls'; +import { + createAggSig, + signBLS, + verifyAggSig, + verifyWeightedAggSig, + verifyBLS, + getPrivateKeyFromPhraseAndPath, +} from '../src/bls'; import { getAllFiles, hexToBuffer, loadSpecFile } from './helpers'; describe('bls_lib', () => { @@ -160,4 +167,17 @@ describe('bls_lib', () => { }); }); }); + + describe('getBLSPrivateKeyFromPhraseAndPath', () => { + const passphrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; + it('should get keypair from valid phrase and path', async () => { + const privateKey = await getPrivateKeyFromPhraseAndPath(passphrase, `m/12381`); + expect(privateKey.toString('hex')).toBe( + BigInt( + '27531519788986738912817629815232258573173656766051821145387425994698573826996', + ).toString(16), + ); + }); + }); }); diff --git a/elements/lisk-cryptography/test/buffer.spec.ts b/elements/lisk-cryptography/test/buffer.spec.ts deleted file mode 100644 index 83bd3faaa96..00000000000 --- a/elements/lisk-cryptography/test/buffer.spec.ts +++ /dev/null @@ -1,185 +0,0 @@ -/* - * 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 { bufferToHex, hexToBuffer, intToBuffer } from '../src/buffer'; - -describe('buffer', () => { - const defaultBuffer = Buffer.from('\xe5\xe4\xf6'); - const defaultHex = 'c3a5c3a4c3b6'; - - describe('#bufferToHex', () => { - it('should create a hex string from a Buffer', () => { - const hex = bufferToHex(defaultBuffer); - expect(hex).toBe(defaultHex); - }); - }); - - describe('#hexToBuffer', () => { - it('should create a Buffer from a hex string', () => { - const buffer = hexToBuffer(defaultHex); - expect(buffer).toEqual(defaultBuffer); - }); - - it('should throw TypeError with number', () => { - expect(hexToBuffer.bind(null, 123 as any)).toThrow(TypeError); - }); - - it('should throw TypeError with object', () => { - expect(hexToBuffer.bind(null, {} as any)).toThrow(TypeError); - }); - - it('should throw an error for a non-string input with custom argument name', () => { - expect(hexToBuffer.bind(null, {} as any, 'Custom')).toThrow('Custom must be a string.'); - }); - - it('should throw TypeError with non hex string', () => { - expect(hexToBuffer.bind(null, 'yKJj')).toThrow(TypeError); - }); - - it('should throw TypeError with partially correct hex string', () => { - expect(hexToBuffer.bind(null, 'Abxzzzz')).toThrow(TypeError); - }); - - it('should throw TypeError with odd number of string with partially correct hex string', () => { - expect(hexToBuffer.bind(null, 'Abxzzab')).toThrow(TypeError); - }); - - it('should throw TypeError with odd number hex string with invalid hex', () => { - expect(hexToBuffer.bind(null, '123xxxx')).toThrow(TypeError); - }); - - it('should throw an error for a non-hex string input with custom argument name', () => { - expect(hexToBuffer.bind(null, 'yKJj', 'Custom')).toThrow( - 'Custom must be a valid hex string.', - ); - }); - - it('should throw TypeError with odd-length hex string', () => { - expect(hexToBuffer.bind(null, 'c3a5c3a4c3b6a')).toThrow(TypeError); - }); - - it('should throw an error for an odd-length hex string input with custom argument name', () => { - expect(hexToBuffer.bind(null, 'c3a5c3a4c3b6a', 'Custom')).toThrow( - 'Custom must have a valid length of hex string.', - ); - }); - }); - - describe('#intToBuffer', () => { - it('should convert a integer to a 1 byte buffer when size=1, endian=big', () => { - const value = 127; - const size = 1; - const endian = 'big'; - - const expectedBuffer = Buffer.alloc(size); - expectedBuffer.writeInt8(value, 0); - - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); - }); - - it('should convert a integer to a 1 byte buffer when size=1, endian=little', () => { - const value = 127; - const size = 1; - const endian = 'little'; - - const expectedBuffer = Buffer.alloc(size); - expectedBuffer.writeInt8(value, 0); - - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); - }); - - it('should convert a integer to a 2 bytes big endian buffer when size=2, endian=big', () => { - const value = 32767; - const size = 2; - const endian = 'big'; - - const expectedBuffer = Buffer.alloc(size); - expectedBuffer.writeInt16BE(value, 0); - - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); - }); - - it('should convert a integer to a 2 bytes little endian buffer when size=2, endian=little', () => { - const value = 3276; - const size = 2; - const endian = 'little'; - - const expectedBuffer = Buffer.alloc(size); - expectedBuffer.writeInt16LE(value, 0); - - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); - }); - - it('should convert a integer to a 4 bytes big endian buffer when size=4, endian=big', () => { - const value = 2147483647; - const size = 4; - const endian = 'big'; - - const expectedBuffer = Buffer.alloc(size); - expectedBuffer.writeInt32BE(value, 0); - - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); - }); - - it('should convert a integer to a 4 bytes little endian buffer when size=4, endian=little', () => { - const value = 2147483647; - const size = 4; - const endian = 'little'; - - const expectedBuffer = Buffer.alloc(size); - expectedBuffer.writeInt32LE(value, 0); - - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); - }); - - it('should convert a integer to a 4 bytes big endian buffer when no size or endian is given', () => { - const value = 2147483647; - const size = 4; - - const expectedBuffer = Buffer.alloc(size); - expectedBuffer.writeInt32BE(value, 0); - - expect(utils.intToBuffer(value, size)).toEqual(expectedBuffer); - }); - - it('should convert a integer to a 8 bytes big endian buffer when size=8, endian=big', () => { - const value = '58191285901858109'; - const size = 8; - const endian = 'big'; - - const expectedBuffer = Buffer.from('00cebcaa8d34153d', 'hex'); - - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); - }); - - it('should convert a integer to a 8 bytes little endian buffer when size=8, endian=little', () => { - const value = '58191285901858109'; - const size = 8; - const endian = 'little'; - - const expectedBuffer = Buffer.from('3d15348daabcce00', 'hex'); - - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); - }); - - it('should convert a integer to a 8 bytes big endian buffer when size=8 and endian is not given', () => { - const value = '58191285901858109'; - const size = 8; - - const expectedBuffer = Buffer.from('00cebcaa8d34153d', 'hex'); - - expect(utils.intToBuffer(value, size)).toEqual(expectedBuffer); - }); - }); -}); diff --git a/elements/lisk-cryptography/test/convert.spec.ts b/elements/lisk-cryptography/test/convert.spec.ts deleted file mode 100644 index da431c0a7c3..00000000000 --- a/elements/lisk-cryptography/test/convert.spec.ts +++ /dev/null @@ -1,202 +0,0 @@ -/* - * 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 { EncryptedPassphraseObject } from '../src'; -import { - getFirstEightBytesReversed, - convertPublicKeyEd2Curve, - convertPrivateKeyEd2Curve, - stringifyEncryptedPassphrase, - parseEncryptedPassphrase, -} from '../src/convert'; -// Require is used for stubbing -// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-var-requires - -describe('convert', () => { - // keys for passphrase 'secret'; - const defaultPrivateKey = - '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b5d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09'; - const defaultPublicKey = Buffer.from( - '5d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09', - 'hex', - ); - const defaultPrivateKeyCurve = Buffer.from( - '68b211b2c01cc88690ba76a07895a5b4805e1c11fdd3af4c863e6d4efeb14378', - 'hex', - ); - const defaultPublicKeyCurve = Buffer.from( - '6f9d780305bda43dd47a291d897f2d8845a06160632d82fb1f209fdd46ed3c1e', - 'hex', - ); - const defaultStringWithMoreThanEightCharacters = '0123456789'; - const defaultFirstEightCharactersReversed = '76543210'; - - describe('#getFirstEightBytesReversed', () => { - it('should get the first eight bytes reversed from a Buffer', () => { - const bufferEntry = Buffer.from(defaultStringWithMoreThanEightCharacters); - const reversedAndCut = getFirstEightBytesReversed(bufferEntry); - expect(reversedAndCut).toEqual(Buffer.from(defaultFirstEightCharactersReversed)); - }); - - it('should get the first eight bytes reversed from a string', () => { - const reversedAndCut = getFirstEightBytesReversed(defaultStringWithMoreThanEightCharacters); - expect(reversedAndCut).toEqual(Buffer.from(defaultFirstEightCharactersReversed)); - }); - }); - - describe('#convertPublicKeyEd2Curve', () => { - it('should convert publicKey ED25519 to Curve25519 key', () => { - const result = convertPublicKeyEd2Curve(defaultPublicKey); - expect(result).not.toBeNull(); - const curveRepresentation = result as Buffer; - expect(defaultPublicKeyCurve.equals(Buffer.from(curveRepresentation))).toBe(true); - }); - }); - - describe('#convertPrivateKeyEd2Curve', () => { - it('should convert privateKey ED25519 to Curve25519 key', () => { - const curveRepresentation = convertPrivateKeyEd2Curve(Buffer.from(defaultPrivateKey, 'hex')); - expect(defaultPrivateKeyCurve.equals(Buffer.from(curveRepresentation))).toBe(true); - }); - }); - - describe('#stringifyEncryptedPassphrase', () => { - it('should throw an error if encrypted passphrase is not an object', () => { - const encryptedPassphrase = - 'salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; - expect(stringifyEncryptedPassphrase.bind(null, encryptedPassphrase as any)).toThrow( - 'Encrypted passphrase to stringify must be an object.', - ); - }); - - it('should format an encrypted passphrase as a string', () => { - const encryptedPassphrase = { - version: '1', - ciphertext: - 'c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', - mac: - 'ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', - kdf: 'PBKDF2', - kdfparams: { - salt: 'e8c7dae4c893e458e0ebb8bff9a36d84', - }, - cipher: 'aes-256-gcm', - cipherparams: { - iv: '1a2206e426c714091b7e48f6', - tag: '3a9d9f9f9a92c9a58296b8df64820c15', - }, - }; - const stringifiedEncryptedPassphrase = - 'kdf=PBKDF2&cipher=aes-256-gcm&version=1&ciphertext=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&mac=ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&salt=e8c7dae4c893e458e0ebb8bff9a36d84&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&iterations=¶llelism=&memorySize='; - expect(stringifyEncryptedPassphrase(encryptedPassphrase as EncryptedPassphraseObject)).toBe( - stringifiedEncryptedPassphrase, - ); - }); - - it('should format an encrypted passphrase with custom iterations as a string', () => { - const encryptedPassphrase = { - version: '1', - ciphertext: - 'c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', - mac: - 'ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', - kdf: 'PBKDF2', - kdfparams: { - salt: 'e8c7dae4c893e458e0ebb8bff9a36d84', - iterations: 12, - }, - cipher: 'aes-256-gcm', - cipherparams: { - iv: '1a2206e426c714091b7e48f6', - tag: '3a9d9f9f9a92c9a58296b8df64820c15', - }, - }; - const stringifiedEncryptedPassphrase = - 'kdf=PBKDF2&cipher=aes-256-gcm&version=1&ciphertext=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&mac=ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&salt=e8c7dae4c893e458e0ebb8bff9a36d84&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&iterations=12¶llelism=&memorySize='; - expect(stringifyEncryptedPassphrase(encryptedPassphrase as EncryptedPassphraseObject)).toBe( - stringifiedEncryptedPassphrase, - ); - }); - }); - - describe('#parseEncryptedPassphrase', () => { - it('should throw an error if encrypted passphrase is not a string', () => { - const stringifiedEncryptedPassphrase = { abc: 'def' }; - expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase as any)).toThrow( - 'Encrypted passphrase to parse must be a string.', - ); - }); - - it('should throw an error if iterations is present but not a valid number', () => { - const stringifiedEncryptedPassphrase = - 'iterations=null&salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; - expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase)).toThrow( - 'Encrypted passphrase to parse must have only one value per key.', - ); - }); - - it('should throw an error if multiple values are in a key', () => { - const stringifiedEncryptedPassphrase = - 'salt=xxx&salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; - expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase)).toThrow( - 'Encrypted passphrase to parse must have only one value per key.', - ); - }); - - it('should parse an encrypted passphrase string', () => { - const stringifiedEncryptedPassphrase = - 'kdf=PBKDF2&cipher=aes-256-gcm&version=1&ciphertext=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&mac=ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&salt=e8c7dae4c893e458e0ebb8bff9a36d84&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15'; - const encryptedPassphrase = { - version: '1', - ciphertext: - 'c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', - mac: - 'ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', - kdf: 'PBKDF2', - kdfparams: { - salt: 'e8c7dae4c893e458e0ebb8bff9a36d84', - }, - cipher: 'aes-256-gcm', - cipherparams: { - iv: '1a2206e426c714091b7e48f6', - tag: '3a9d9f9f9a92c9a58296b8df64820c15', - }, - }; - expect(parseEncryptedPassphrase(stringifiedEncryptedPassphrase)).toEqual(encryptedPassphrase); - }); - - it('should parse an encrypted passphrase string with custom iterations', () => { - const stringifiedEncryptedPassphrase = - 'kdf=PBKDF2&cipher=aes-256-gcm&version=1&ciphertext=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&mac=ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&salt=e8c7dae4c893e458e0ebb8bff9a36d84&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&iterations=12¶llelism=&memorySize='; - const encryptedPassphrase = { - version: '1', - ciphertext: - 'c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', - mac: - 'ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', - kdf: 'PBKDF2', - kdfparams: { - salt: 'e8c7dae4c893e458e0ebb8bff9a36d84', - iterations: 12, - }, - cipher: 'aes-256-gcm', - cipherparams: { - iv: '1a2206e426c714091b7e48f6', - tag: '3a9d9f9f9a92c9a58296b8df64820c15', - }, - }; - expect(parseEncryptedPassphrase(stringifiedEncryptedPassphrase)).toEqual(encryptedPassphrase); - }); - }); -}); diff --git a/elements/lisk-cryptography/test/sign.spec.ts b/elements/lisk-cryptography/test/ed.spec.ts similarity index 71% rename from elements/lisk-cryptography/test/sign.spec.ts rename to elements/lisk-cryptography/test/ed.spec.ts index 7975f650030..bc64e7e376e 100644 --- a/elements/lisk-cryptography/test/sign.spec.ts +++ b/elements/lisk-cryptography/test/ed.spec.ts @@ -23,12 +23,12 @@ import { signDataWithPassphrase, signDataWithPrivateKey, verifyData, - digestMessage, -} from '../src/sign'; -import { createMessageTag } from '../src/message_tag'; -// Require is used for stubbing -// eslint-disable-next-line -const keys = require('../src/keys'); + getKeyPairFromPhraseAndPath, + getPublicKeyFromPrivateKey, +} from '../src/ed'; +import { createMessageTag } from '../src/utils'; +import { MAX_UINT32 } from '../src/constants'; +import * as address from '../src/address'; const changeLength = (buffer: Buffer): Buffer => Buffer.concat([Buffer.from('00', 'hex'), buffer]); @@ -69,53 +69,15 @@ ${defaultSignature} signature: Buffer.from(defaultSignature, 'hex'), }; - jest.spyOn(keys, 'getAddressAndPublicKeyFromPassphrase').mockImplementation(() => { + jest.spyOn(address, 'getAddressAndPublicKeyFromPassphrase').mockImplementation(() => { return { + address: address.getAddressFromPublicKey(Buffer.from(defaultPublicKey, 'hex')), privateKey: Buffer.from(defaultPrivateKey, 'hex'), publicKey: Buffer.from(defaultPublicKey, 'hex'), }; }); }); - describe('#digestMessage', () => { - const strGenerator = (len: number, chr: string): string => chr.repeat(len); - - it('should create message digest for message with length = 0', () => { - const msgBytes = digestMessage(''); - const expectedMessageBytes = Buffer.from( - '3fdb82ac2a879b647f4f27f3fbd1c27e0d4e278f830b76295604035330163b79', - 'hex', - ); - expect(msgBytes).toEqual(expectedMessageBytes); - }); - it('should create message digest for message in length range 1 - 253', () => { - const msgBytes = digestMessage(strGenerator(250, 'a')); - const expectedMessageBytes = Buffer.from( - '12832c687d950513aa5db6198b84809eb8fd7ff1c8963dca48ea57278523ec67', - 'hex', - ); - expect(msgBytes).toEqual(expectedMessageBytes); - }); - it('should create message digest for message in length range 254 - 65536', () => { - const msgBytes = digestMessage(strGenerator(65535, 'a')); - const expectedMessageBytes = Buffer.from( - '73da94220312e71eb5c55c94fdddca3c06a6c18cb74a4a4a2cee1a82875c2450', - 'hex', - ); - expect(msgBytes).toEqual(expectedMessageBytes); - }); - it('should create message digest for message in length range 65537 - 4294967296', () => { - const msgBytes = digestMessage(strGenerator(6710886, 'a')); - const expectedMessageBytes = Buffer.from( - '7c51817b5c31c4d04e9ffcf2e78859d6522b124f218c789a8f721b5f3e6b295d', - 'hex', - ); - expect(msgBytes).toEqual(expectedMessageBytes); - }); - // highest range (length > 4294967296) is not practical to test - // but it is covered by `varuint-bitcoin` library - }); - describe('#signMessageWithPassphrase', () => { it('should create a signed message using a secret passphrase', () => { const signedMessage = signMessageWithPassphrase(defaultMessage, defaultPassphrase); @@ -244,4 +206,64 @@ ${defaultSignature} expect(verification).toBe(true); }); }); + + describe('getKeyPairFromPhraseAndPath', () => { + const passphrase = + 'target cancel solution recipe vague faint bomb convince pink vendor fresh patrol'; + it('should get keypair from valid phrase and path', async () => { + const privateKey = await getKeyPairFromPhraseAndPath(passphrase, `m/44'/134'/0'`); + const publicKey = getPublicKeyFromPrivateKey(privateKey); + expect(publicKey.toString('hex')).toBe( + 'c6bae83af23540096ac58d5121b00f33be6f02f05df785766725acdd5d48be9d', + ); + expect(privateKey.toString('hex')).toBe( + 'c465dfb15018d3aef0d94d411df048e240e87a3ec9cd6d422cea903bfc101f61c6bae83af23540096ac58d5121b00f33be6f02f05df785766725acdd5d48be9d', + ); + }); + + it('should fail for empty string path', async () => { + await expect(getKeyPairFromPhraseAndPath(passphrase, '')).rejects.toThrow( + 'Invalid path format', + ); + }); + + it('should fail if path does not start with "m"', async () => { + await expect(getKeyPairFromPhraseAndPath(passphrase, `/44'/134'/0'`)).rejects.toThrow( + 'Invalid path format', + ); + }); + + it('should fail if path does not include at least one "/"', async () => { + await expect(getKeyPairFromPhraseAndPath(passphrase, 'm441340')).rejects.toThrow( + 'Invalid path format', + ); + }); + + it('should fail for path with invalid segment', async () => { + await expect( + getKeyPairFromPhraseAndPath( + passphrase, + `m//134'/0'`, // should be number with or without ' between every back slash + ), + ).rejects.toThrow('Invalid path format'); + }); + + it('should fail for path with invalid characters', async () => { + await expect(getKeyPairFromPhraseAndPath(passphrase, `m/a'/134b'/0'`)).rejects.toThrow( + 'Invalid path format', + ); + }); + + it('should fail for path with non-sanctioned special characters', async () => { + await expect(getKeyPairFromPhraseAndPath(passphrase, `m/4a'/#134b'/0'`)).rejects.toThrow( + 'Invalid path format', + ); + }); + + it(`should fail for path with segment greater than ${MAX_UINT32} / 2`, async () => { + await expect( + getKeyPairFromPhraseAndPath(passphrase, `m/44'/134'/${MAX_UINT32}'`), + ).rejects.toThrow('Invalid path format'); + }); + }); }); diff --git a/elements/lisk-cryptography/test/encrypt.spec.ts b/elements/lisk-cryptography/test/encrypt.spec.ts index dd2d311c3d0..af7fe702723 100644 --- a/elements/lisk-cryptography/test/encrypt.spec.ts +++ b/elements/lisk-cryptography/test/encrypt.spec.ts @@ -11,7 +11,7 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { MAX_UINT32 } from '../src/constants'; +import * as ed2curve from 'ed2curve'; import { EncryptedPassphraseObject, EncryptedMessageWithNonce, @@ -19,18 +19,13 @@ import { decryptMessageWithPassphrase, encryptPassphraseWithPassword, decryptPassphraseWithPassword, - getKeyPairFromPhraseAndPath, KDF, Cipher, - getBLSPrivateKeyFromPhraseAndPath, + parseEncryptedPassphrase, + stringifyEncryptedPassphrase, } from '../src/encrypt'; -// Require is used for stubbing -// eslint-disable-next-line -const convert = require('../src/convert'); -// eslint-disable-next-line -const keys = require('../src/keys'); -// eslint-disable-next-line -const hashModule = require('../src/hash'); +import * as utils from '../src/utils'; +import * as address from '../src/address'; describe('encrypt', () => { const regHexadecimal = /[0-9A-Za-z]/g; @@ -59,25 +54,26 @@ describe('encrypt', () => { nonce: 'df4c8b09e270d2cb3f7b3d53dfa8a6f3441ad3b14a13fb66', }; jest - .spyOn(convert, 'convertPrivateKeyEd2Curve') + .spyOn(ed2curve, 'convertSecretKey') .mockReturnValue( Buffer.from('d8be8cacb03fb02f34e85030f902b635f364d6c23f090c7640e9dc9c568e7d5e', 'hex'), ); jest - .spyOn(convert, 'convertPublicKeyEd2Curve') + .spyOn(ed2curve, 'convertPublicKey') .mockReturnValue( Buffer.from('f245e78c83196d73452e55581ef924a1b792d352c142257aa3af13cded2e7905', 'hex'), ); - jest.spyOn(keys, 'getAddressAndPublicKeyFromPassphrase').mockImplementation(() => { + jest.spyOn(address, 'getAddressAndPublicKeyFromPassphrase').mockImplementation(() => { return { + address: address.getAddressFromPublicKey(defaultPublicKey), privateKey: defaultPrivateKey, publicKey: defaultPublicKey, }; }); hashStub = jest - .spyOn(hashModule, 'hash') + .spyOn(utils, 'hash') .mockReturnValue( Buffer.from('d43eed9049dd8f35106c720669a1148b2c6288d9ea517b936c33a1d84117a760', 'hex'), ); @@ -357,80 +353,134 @@ describe('encrypt', () => { expect(decryptedString).toBe(defaultPassphrase); }); }); + }); - describe('getKeyPairFromPhraseAndPath', () => { - const passphrase = - 'target cancel solution recipe vague faint bomb convince pink vendor fresh patrol'; - it('should get keypair from valid phrase and path', async () => { - const { publicKey, privateKey } = await getKeyPairFromPhraseAndPath( - passphrase, - `m/44'/134'/0'`, - ); - expect(publicKey.toString('hex')).toBe( - 'c6bae83af23540096ac58d5121b00f33be6f02f05df785766725acdd5d48be9d', - ); - expect(privateKey.toString('hex')).toBe( - 'c465dfb15018d3aef0d94d411df048e240e87a3ec9cd6d422cea903bfc101f61c6bae83af23540096ac58d5121b00f33be6f02f05df785766725acdd5d48be9d', - ); - }); - - it('should fail for empty string path', async () => { - await expect(getKeyPairFromPhraseAndPath(passphrase, '')).rejects.toThrow( - 'Invalid path format', - ); - }); + describe('#stringifyEncryptedPassphrase', () => { + it('should throw an error if encrypted passphrase is not an object', () => { + const encryptedPassphrase = + 'salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; + expect(stringifyEncryptedPassphrase.bind(null, encryptedPassphrase as any)).toThrow( + 'Encrypted passphrase to stringify must be an object.', + ); + }); - it('should fail if path does not start with "m"', async () => { - await expect(getKeyPairFromPhraseAndPath(passphrase, `/44'/134'/0'`)).rejects.toThrow( - 'Invalid path format', - ); - }); + it('should format an encrypted passphrase as a string', () => { + const encryptedPassphrase = { + version: '1', + ciphertext: + 'c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', + mac: + 'ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', + kdf: 'PBKDF2', + kdfparams: { + salt: 'e8c7dae4c893e458e0ebb8bff9a36d84', + }, + cipher: 'aes-256-gcm', + cipherparams: { + iv: '1a2206e426c714091b7e48f6', + tag: '3a9d9f9f9a92c9a58296b8df64820c15', + }, + }; + const stringifiedEncryptedPassphrase = + 'kdf=PBKDF2&cipher=aes-256-gcm&version=1&ciphertext=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&mac=ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&salt=e8c7dae4c893e458e0ebb8bff9a36d84&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&iterations=¶llelism=&memorySize='; + expect(stringifyEncryptedPassphrase(encryptedPassphrase as EncryptedPassphraseObject)).toBe( + stringifiedEncryptedPassphrase, + ); + }); - it('should fail if path does not include at least one "/"', async () => { - await expect(getKeyPairFromPhraseAndPath(passphrase, 'm441340')).rejects.toThrow( - 'Invalid path format', - ); - }); + it('should format an encrypted passphrase with custom iterations as a string', () => { + const encryptedPassphrase = { + version: '1', + ciphertext: + 'c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', + mac: + 'ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', + kdf: 'PBKDF2', + kdfparams: { + salt: 'e8c7dae4c893e458e0ebb8bff9a36d84', + iterations: 12, + }, + cipher: 'aes-256-gcm', + cipherparams: { + iv: '1a2206e426c714091b7e48f6', + tag: '3a9d9f9f9a92c9a58296b8df64820c15', + }, + }; + const stringifiedEncryptedPassphrase = + 'kdf=PBKDF2&cipher=aes-256-gcm&version=1&ciphertext=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&mac=ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&salt=e8c7dae4c893e458e0ebb8bff9a36d84&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&iterations=12¶llelism=&memorySize='; + expect(stringifyEncryptedPassphrase(encryptedPassphrase as EncryptedPassphraseObject)).toBe( + stringifiedEncryptedPassphrase, + ); + }); + }); - it('should fail for path with invalid segment', async () => { - await expect( - getKeyPairFromPhraseAndPath( - passphrase, - `m//134'/0'`, // should be number with or without ' between every back slash - ), - ).rejects.toThrow('Invalid path format'); - }); + describe('#parseEncryptedPassphrase', () => { + it('should throw an error if encrypted passphrase is not a string', () => { + const stringifiedEncryptedPassphrase = { abc: 'def' }; + expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase as any)).toThrow( + 'Encrypted passphrase to parse must be a string.', + ); + }); - it('should fail for path with invalid characters', async () => { - await expect(getKeyPairFromPhraseAndPath(passphrase, `m/a'/134b'/0'`)).rejects.toThrow( - 'Invalid path format', - ); - }); + it('should throw an error if iterations is present but not a valid number', () => { + const stringifiedEncryptedPassphrase = + 'iterations=null&salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; + expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase)).toThrow( + 'Encrypted passphrase to parse must have only one value per key.', + ); + }); - it('should fail for path with non-sanctioned special characters', async () => { - await expect(getKeyPairFromPhraseAndPath(passphrase, `m/4a'/#134b'/0'`)).rejects.toThrow( - 'Invalid path format', - ); - }); + it('should throw an error if multiple values are in a key', () => { + const stringifiedEncryptedPassphrase = + 'salt=xxx&salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; + expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase)).toThrow( + 'Encrypted passphrase to parse must have only one value per key.', + ); + }); - it(`should fail for path with segment greater than ${MAX_UINT32} / 2`, async () => { - await expect( - getKeyPairFromPhraseAndPath(passphrase, `m/44'/134'/${MAX_UINT32}'`), - ).rejects.toThrow('Invalid path format'); - }); + it('should parse an encrypted passphrase string', () => { + const stringifiedEncryptedPassphrase = + 'kdf=PBKDF2&cipher=aes-256-gcm&version=1&ciphertext=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&mac=ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&salt=e8c7dae4c893e458e0ebb8bff9a36d84&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15'; + const encryptedPassphrase = { + version: '1', + ciphertext: + 'c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', + mac: + 'ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', + kdf: 'PBKDF2', + kdfparams: { + salt: 'e8c7dae4c893e458e0ebb8bff9a36d84', + }, + cipher: 'aes-256-gcm', + cipherparams: { + iv: '1a2206e426c714091b7e48f6', + tag: '3a9d9f9f9a92c9a58296b8df64820c15', + }, + }; + expect(parseEncryptedPassphrase(stringifiedEncryptedPassphrase)).toEqual(encryptedPassphrase); }); - describe('getBLSPrivateKeyFromPhraseAndPath', () => { - const passphrase = - 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; - it('should get keypair from valid phrase and path', async () => { - const privateKey = await getBLSPrivateKeyFromPhraseAndPath(passphrase, `m/12381`); - expect(privateKey.toString('hex')).toBe( - BigInt( - '27531519788986738912817629815232258573173656766051821145387425994698573826996', - ).toString(16), - ); - }); + it('should parse an encrypted passphrase string with custom iterations', () => { + const stringifiedEncryptedPassphrase = + 'kdf=PBKDF2&cipher=aes-256-gcm&version=1&ciphertext=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&mac=ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&salt=e8c7dae4c893e458e0ebb8bff9a36d84&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&iterations=12¶llelism=&memorySize='; + const encryptedPassphrase = { + version: '1', + ciphertext: + 'c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', + mac: + 'ddfgb123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333', + kdf: 'PBKDF2', + kdfparams: { + salt: 'e8c7dae4c893e458e0ebb8bff9a36d84', + iterations: 12, + }, + cipher: 'aes-256-gcm', + cipherparams: { + iv: '1a2206e426c714091b7e48f6', + tag: '3a9d9f9f9a92c9a58296b8df64820c15', + }, + }; + expect(parseEncryptedPassphrase(stringifiedEncryptedPassphrase)).toEqual(encryptedPassphrase); }); }); }); diff --git a/elements/lisk-cryptography/test/hash.spec.ts b/elements/lisk-cryptography/test/hash.spec.ts deleted file mode 100644 index 931d1578259..00000000000 --- a/elements/lisk-cryptography/test/hash.spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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 as hashFunction, getNetworkIdentifier } from '../src/hash'; - -describe('hash', () => { - describe('#hash', () => { - const defaultText = 'text123*'; - let arrayToHash: ReadonlyArray; - let defaultHash: Buffer; - - beforeEach(async () => { - defaultHash = Buffer.from( - '7607d6792843d6003c12495b54e34517a508d2a8622526aff1884422c5478971', - 'hex', - ); - arrayToHash = [1, 2, 3]; - return Promise.resolve(); - }); - - it('should generate a sha256 hash from a Buffer', () => { - const testBuffer = Buffer.from(defaultText); - const hash = hashFunction(testBuffer); - expect(hash).toEqual(defaultHash); - }); - - it('should generate a sha256 hash from a utf8 string', () => { - const hash = hashFunction(defaultText, 'utf8'); - expect(hash).toEqual(defaultHash); - }); - - it('should generate a sha256 hash from a hex string', () => { - const testHex = Buffer.from(defaultText).toString('hex'); - const hash = hashFunction(testHex, 'hex'); - expect(hash).toEqual(defaultHash); - }); - - it('should throw on unknown format when trying a string with format "utf32"', () => { - expect(hashFunction.bind(null, defaultText, 'utf32')).toThrow( - 'Unsupported string format. Currently only `hex` and `utf8` are supported.', - ); - }); - - it('should throw on unknown format when using an array', () => { - expect(hashFunction.bind(null, arrayToHash as any)).toThrow( - 'Unsupported data:1,2,3 and format:undefined. Currently only Buffers or hex and utf8 strings are supported.', - ); - }); - }); - - describe('#getNetworkIdentifier', () => { - const genesisBlockID = Buffer.from( - 'ed14889723f24ecc54871d058d98ce91ff2f973192075c0155ba2b7b70ad2511', - 'hex', - ); - const communityIdentifier = 'LISK'; - const expectedHash = Buffer.from( - '6f201e72e20571b93ed42470caa94af1ace79dc9930ab5bb144ddd5df5753e73', - 'hex', - ); - - it('should generate a sha256 hash from genesis block transaction root and community identifier', () => { - const networkIdentifier = getNetworkIdentifier(genesisBlockID, communityIdentifier); - - expect(networkIdentifier).toEqual(expectedHash); - }); - }); -}); diff --git a/elements/lisk-cryptography/test/hash_onion.spec.ts b/elements/lisk-cryptography/test/hash_onion.spec.ts deleted file mode 100644 index 77ba43341b3..00000000000 --- a/elements/lisk-cryptography/test/hash_onion.spec.ts +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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 { hashOnion, generateHashOnionSeed } from '../src/hash_onion'; - -describe('hash onion', () => { - describe('#generateHashOnionSeed', () => { - it('should generate a random buffer', () => { - const seed1 = generateHashOnionSeed().toString('hex'); - const seed2 = generateHashOnionSeed().toString('hex'); - - expect(seed1).not.toEqual(seed2); - }); - - it('should generate a random buffer with 16 bytes', () => { - const seed = generateHashOnionSeed(); - expect(seed).toHaveLength(16); - }); - }); - - describe('#hashOnion', () => { - let seed: Buffer; - let hashOnionBuffers: ReadonlyArray; - beforeAll(() => { - seed = generateHashOnionSeed(); - hashOnionBuffers = hashOnion(seed); - }); - - it('should return 1001 hash onion hashes checkpoints by default', () => { - expect(hashOnionBuffers).toHaveLength(1001); - }); - - it('should return hash onion hashes which includes seed as the last element', () => { - expect(hashOnionBuffers[1000]).toEqual(seed); - }); - - it('should be able to calculate the checkpoint from another checkpoint', () => { - const firstDistanceHashes = hashOnion(hashOnionBuffers[1].slice(), 1000, 1); - expect(firstDistanceHashes[0]).toEqual(hashOnionBuffers[0]); - expect(firstDistanceHashes[1000]).toEqual(hashOnionBuffers[1]); - }); - }); -}); diff --git a/elements/lisk-cryptography/test/legacy_address.spec.ts b/elements/lisk-cryptography/test/legacy_address.spec.ts index d3c576a67c6..34b7759d2b2 100644 --- a/elements/lisk-cryptography/test/legacy_address.spec.ts +++ b/elements/lisk-cryptography/test/legacy_address.spec.ts @@ -13,6 +13,7 @@ * */ import { + getFirstEightBytesReversed, getLegacyAddressAndPublicKeyFromPassphrase, getLegacyAddressFromPassphrase, getLegacyAddressFromPrivateKey, @@ -31,6 +32,8 @@ describe('Legacy address', () => { 'hex', ); const defaultAddress = '7115442636316065252L'; + const defaultStringWithMoreThanEightCharacters = '0123456789'; + const defaultFirstEightCharactersReversed = '76543210'; describe('#getLegacyAddressAndPublicKeyFromPassphrase', () => { it('should return expected address', () => { @@ -58,4 +61,17 @@ describe('Legacy address', () => { expect(getLegacyAddressFromPublicKey(defaultPublicKey)).toEqual(defaultAddress); }); }); + + describe('#getFirstEightBytesReversed', () => { + it('should get the first eight bytes reversed from a Buffer', () => { + const bufferEntry = Buffer.from(defaultStringWithMoreThanEightCharacters); + const reversedAndCut = getFirstEightBytesReversed(bufferEntry); + expect(reversedAndCut).toEqual(Buffer.from(defaultFirstEightCharactersReversed)); + }); + + it('should get the first eight bytes reversed from a string', () => { + const reversedAndCut = getFirstEightBytesReversed(defaultStringWithMoreThanEightCharacters); + expect(reversedAndCut).toEqual(Buffer.from(defaultFirstEightCharactersReversed)); + }); + }); }); diff --git a/elements/lisk-cryptography/test/message_tag.spec.ts b/elements/lisk-cryptography/test/message_tag.spec.ts deleted file mode 100644 index 0410b07ef6e..00000000000 --- a/elements/lisk-cryptography/test/message_tag.spec.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright © 2020 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 { createMessageTag, tagMessage } from '../src/message_tag'; - -describe('Message Tag', () => { - describe('createMessageTag', () => { - it('should throw error if domain contains a space', () => { - expect(() => createMessageTag('MY TX')).toThrow( - 'Message tag domain must be alpha numeric without special characters. Got "MY TX".', - ); - }); - - it('should throw error if domain contains a underscore', () => { - expect(() => createMessageTag('MY_')).toThrow( - 'Message tag domain must be alpha numeric without special characters. Got "MY_".', - ); - }); - - it('should throw error if domain contains a special character', () => { - expect(() => createMessageTag('MY*')).toThrow( - 'Message tag domain must be alpha numeric without special characters. Got "MY*".', - ); - }); - - it('should return a valid tag', () => { - expect(createMessageTag('TX')).toEqual('LSK_TX_'); - }); - - it('should return a valid tag with version of number type', () => { - expect(createMessageTag('TX', 1)).toEqual('LSK_TX:1_'); - }); - - it('should return a valid tag with version of string type', () => { - expect(createMessageTag('TX', 'v2')).toEqual('LSK_TX:v2_'); - }); - }); - - describe('tagMessage', () => { - it('should concatenate the tag, network identifier and message when message is buffer', () => { - const tag = createMessageTag('TX'); - const tagBuffer = Buffer.from(tag, 'utf8'); - const networkId = Buffer.from('abc', 'utf8'); - const message = Buffer.from('message', 'utf8'); - const result = Buffer.concat([tagBuffer, networkId, message]); - - expect(tagMessage(tag, networkId, message)).toEqual(result); - }); - - it('should concatenate the tag, network identifier and message when message is string', () => { - const tag = createMessageTag('TX'); - const tagBuffer = Buffer.from(tag, 'utf8'); - const networkId = Buffer.from('abc', 'utf8'); - const message = Buffer.from('message', 'utf8'); - const result = Buffer.concat([tagBuffer, networkId, message]); - - expect(tagMessage(tag, networkId, 'message')).toEqual(result); - }); - }); -}); diff --git a/elements/lisk-cryptography/test/nacl/index.spec.ts b/elements/lisk-cryptography/test/nacl/index.spec.ts index 3820b4aacb7..3234866ada7 100644 --- a/elements/lisk-cryptography/test/nacl/index.spec.ts +++ b/elements/lisk-cryptography/test/nacl/index.spec.ts @@ -56,7 +56,7 @@ describe('nacl index.js', () => { // Act // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require const nacl = require('../../src/nacl'); - nacl.utils.getRandomBytes(8); + nacl.getRandomBytes(8); // Assert expect(sodiumMock).toHaveBeenCalledTimes(1); }); @@ -66,7 +66,7 @@ describe('nacl index.js', () => { process.env.NACL_FAST = 'disable'; // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require const nacl = require('../../src/nacl'); - nacl.utils.getRandomBytes(8); + nacl.getRandomBytes(8); // Assert expect(tweetMock).toHaveBeenCalledTimes(1); }); @@ -77,7 +77,7 @@ describe('nacl index.js', () => { // Act // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require const nacl = require('../../src/nacl'); - nacl.utils.getRandomBytes(8); + nacl.getRandomBytes(8); // Assert expect(sodiumMock).toHaveBeenCalledTimes(1); }); @@ -103,7 +103,7 @@ describe('nacl index.js', () => { // Act // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require const nacl = require('../../src/nacl'); - nacl.utils.getRandomBytes(8); + nacl.getRandomBytes(8); // Assert expect(tweetMock).toHaveBeenCalledTimes(1); }); diff --git a/elements/lisk-cryptography/test/nacl/nacl.spec.ts b/elements/lisk-cryptography/test/nacl/nacl.spec.ts index de6c6b3f180..d385ea62cf6 100644 --- a/elements/lisk-cryptography/test/nacl/nacl.spec.ts +++ b/elements/lisk-cryptography/test/nacl/nacl.spec.ts @@ -68,7 +68,7 @@ describe('nacl', () => { let randomBuffer: Buffer; beforeEach(async () => { - randomBuffer = utils.getRandomBytes(size); + randomBuffer = getRandomBytes(size); return Promise.resolve(); }); diff --git a/elements/lisk-cryptography/test/utils.spec.ts b/elements/lisk-cryptography/test/utils.spec.ts index 8302b68745a..83e995162c9 100644 --- a/elements/lisk-cryptography/test/utils.spec.ts +++ b/elements/lisk-cryptography/test/utils.spec.ts @@ -13,52 +13,391 @@ * */ -import { readBit, writeBit } from '../src/utils'; +import { + bufferToHex, + generateHashOnionSeed, + hashOnion, + hexToBuffer, + intToBuffer, + hash as hashFunction, + getNetworkIdentifier, + tagMessage, + createMessageTag, +} from '../src/utils'; describe('utils', () => { - describe('readBit', () => { - it('should read bits of one byte buffer', () => { - const binary = '10000101'; - const buffer = Buffer.alloc(1); - buffer.writeUIntLE(parseInt(binary, 2), 0, 1); - - for (const [index, bit] of binary.split('').entries()) { - expect(readBit(buffer, 7 - index)).toEqual(bit === '1'); - } + describe('buffer', () => { + const defaultBuffer = Buffer.from('\xe5\xe4\xf6'); + const defaultHex = 'c3a5c3a4c3b6'; + + describe('#bufferToHex', () => { + it('should create a hex string from a Buffer', () => { + const hex = bufferToHex(defaultBuffer); + expect(hex).toBe(defaultHex); + }); + }); + + describe('#hexToBuffer', () => { + it('should create a Buffer from a hex string', () => { + const buffer = hexToBuffer(defaultHex); + expect(buffer).toEqual(defaultBuffer); + }); + + it('should throw TypeError with number', () => { + expect(hexToBuffer.bind(null, 123 as any)).toThrow(TypeError); + }); + + it('should throw TypeError with object', () => { + expect(hexToBuffer.bind(null, {} as any)).toThrow(TypeError); + }); + + it('should throw an error for a non-string input with custom argument name', () => { + expect(hexToBuffer.bind(null, {} as any, 'Custom')).toThrow('Custom must be a string.'); + }); + + it('should throw TypeError with non hex string', () => { + expect(hexToBuffer.bind(null, 'yKJj')).toThrow(TypeError); + }); + + it('should throw TypeError with partially correct hex string', () => { + expect(hexToBuffer.bind(null, 'Abxzzzz')).toThrow(TypeError); + }); + + it('should throw TypeError with odd number of string with partially correct hex string', () => { + expect(hexToBuffer.bind(null, 'Abxzzab')).toThrow(TypeError); + }); + + it('should throw TypeError with odd number hex string with invalid hex', () => { + expect(hexToBuffer.bind(null, '123xxxx')).toThrow(TypeError); + }); + + it('should throw an error for a non-hex string input with custom argument name', () => { + expect(hexToBuffer.bind(null, 'yKJj', 'Custom')).toThrow( + 'Custom must be a valid hex string.', + ); + }); + + it('should throw TypeError with odd-length hex string', () => { + expect(hexToBuffer.bind(null, 'c3a5c3a4c3b6a')).toThrow(TypeError); + }); + + it('should throw an error for an odd-length hex string input with custom argument name', () => { + expect(hexToBuffer.bind(null, 'c3a5c3a4c3b6a', 'Custom')).toThrow( + 'Custom must have a valid length of hex string.', + ); + }); + }); + + describe('#intToBuffer', () => { + it('should convert a integer to a 1 byte buffer when size=1, endian=big', () => { + const value = 127; + const size = 1; + const endian = 'big'; + + const expectedBuffer = Buffer.alloc(size); + expectedBuffer.writeInt8(value, 0); + + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + }); + + it('should convert a integer to a 1 byte buffer when size=1, endian=little', () => { + const value = 127; + const size = 1; + const endian = 'little'; + + const expectedBuffer = Buffer.alloc(size); + expectedBuffer.writeInt8(value, 0); + + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + }); + + it('should convert a integer to a 2 bytes big endian buffer when size=2, endian=big', () => { + const value = 32767; + const size = 2; + const endian = 'big'; + + const expectedBuffer = Buffer.alloc(size); + expectedBuffer.writeInt16BE(value, 0); + + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + }); + + it('should convert a integer to a 2 bytes little endian buffer when size=2, endian=little', () => { + const value = 3276; + const size = 2; + const endian = 'little'; + + const expectedBuffer = Buffer.alloc(size); + expectedBuffer.writeInt16LE(value, 0); + + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + }); + + it('should convert a integer to a 4 bytes big endian buffer when size=4, endian=big', () => { + const value = 2147483647; + const size = 4; + const endian = 'big'; + + const expectedBuffer = Buffer.alloc(size); + expectedBuffer.writeInt32BE(value, 0); + + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + }); + + it('should convert a integer to a 4 bytes little endian buffer when size=4, endian=little', () => { + const value = 2147483647; + const size = 4; + const endian = 'little'; + + const expectedBuffer = Buffer.alloc(size); + expectedBuffer.writeInt32LE(value, 0); + + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + }); + + it('should convert a integer to a 4 bytes big endian buffer when no size or endian is given', () => { + const value = 2147483647; + const size = 4; + + const expectedBuffer = Buffer.alloc(size); + expectedBuffer.writeInt32BE(value, 0); + + expect(intToBuffer(value, size)).toEqual(expectedBuffer); + }); + + it('should convert a integer to a 8 bytes big endian buffer when size=8, endian=big', () => { + const value = '58191285901858109'; + const size = 8; + const endian = 'big'; + + const expectedBuffer = Buffer.from('00cebcaa8d34153d', 'hex'); + + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + }); + + it('should convert a integer to a 8 bytes little endian buffer when size=8, endian=little', () => { + const value = '58191285901858109'; + const size = 8; + const endian = 'little'; + + const expectedBuffer = Buffer.from('3d15348daabcce00', 'hex'); + + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); + }); + + it('should convert a integer to a 8 bytes big endian buffer when size=8 and endian is not given', () => { + const value = '58191285901858109'; + const size = 8; + + const expectedBuffer = Buffer.from('00cebcaa8d34153d', 'hex'); + + expect(intToBuffer(value, size)).toEqual(expectedBuffer); + }); + }); + }); + + describe('hash onion', () => { + describe('#generateHashOnionSeed', () => { + it('should generate a random buffer', () => { + const seed1 = generateHashOnionSeed().toString('hex'); + const seed2 = generateHashOnionSeed().toString('hex'); + + expect(seed1).not.toEqual(seed2); + }); + + it('should generate a random buffer with 16 bytes', () => { + const seed = generateHashOnionSeed(); + expect(seed).toHaveLength(16); + }); }); - it('should read bits of two byte buffer', () => { - const binary = '1010001010000101'; - const buffer = Buffer.alloc(2); - buffer.writeUIntLE(parseInt(binary, 2), 0, 2); + describe('#hashOnion', () => { + let seed: Buffer; + let hashOnionBuffers: ReadonlyArray; + beforeAll(() => { + seed = generateHashOnionSeed(); + hashOnionBuffers = hashOnion(seed); + }); - for (const [index, bit] of binary.split('').entries()) { - expect(readBit(buffer, 15 - index)).toEqual(bit === '1'); - } + it('should return 1001 hash onion hashes checkpoints by default', () => { + expect(hashOnionBuffers).toHaveLength(1001); + }); + + it('should return hash onion hashes which includes seed as the last element', () => { + expect(hashOnionBuffers[1000]).toEqual(seed); + }); + + it('should be able to calculate the checkpoint from another checkpoint', () => { + const firstDistanceHashes = hashOnion(hashOnionBuffers[1].slice(), 1000, 1); + expect(firstDistanceHashes[0]).toEqual(hashOnionBuffers[0]); + expect(firstDistanceHashes[1000]).toEqual(hashOnionBuffers[1]); + }); }); }); - describe('writeBit', () => { - it('should write bit of one byte buffer', () => { - const binary = '10000101'; - const buffer = Buffer.alloc(1); - for (const [index, bit] of binary.split('').entries()) { - writeBit(buffer, 7 - index, bit === '1'); - } - const result = buffer.readUIntLE(0, 1).toString(2).padStart(8, '0'); + describe('hash', () => { + describe('#hash', () => { + const defaultText = 'text123*'; + let arrayToHash: ReadonlyArray; + let defaultHash: Buffer; + + beforeEach(async () => { + defaultHash = Buffer.from( + '7607d6792843d6003c12495b54e34517a508d2a8622526aff1884422c5478971', + 'hex', + ); + arrayToHash = [1, 2, 3]; + return Promise.resolve(); + }); + + it('should generate a sha256 hash from a Buffer', () => { + const testBuffer = Buffer.from(defaultText); + const hash = hashFunction(testBuffer); + expect(hash).toEqual(defaultHash); + }); + + it('should generate a sha256 hash from a utf8 string', () => { + const hash = hashFunction(defaultText, 'utf8'); + expect(hash).toEqual(defaultHash); + }); - expect(result).toEqual(binary); + it('should generate a sha256 hash from a hex string', () => { + const testHex = Buffer.from(defaultText).toString('hex'); + const hash = hashFunction(testHex, 'hex'); + expect(hash).toEqual(defaultHash); + }); + + it('should throw on unknown format when trying a string with format "utf32"', () => { + expect(hashFunction.bind(null, defaultText, 'utf32')).toThrow( + 'Unsupported string format. Currently only `hex` and `utf8` are supported.', + ); + }); + + it('should throw on unknown format when using an array', () => { + expect(hashFunction.bind(null, arrayToHash as any)).toThrow( + 'Unsupported data:1,2,3 and format:undefined. Currently only Buffers or hex and utf8 strings are supported.', + ); + }); }); - it('should write bits of two byte buffer', () => { - const binary = '1010001010000101'; - const buffer = Buffer.alloc(2); - for (const [index, bit] of binary.split('').entries()) { - writeBit(buffer, 15 - index, bit === '1'); - } - const result = buffer.readUIntLE(0, 2).toString(2).padStart(16, '0'); + describe('#getNetworkIdentifier', () => { + const genesisBlockID = Buffer.from( + 'ed14889723f24ecc54871d058d98ce91ff2f973192075c0155ba2b7b70ad2511', + 'hex', + ); + const communityIdentifier = 'LISK'; + const expectedHash = Buffer.from( + '6f201e72e20571b93ed42470caa94af1ace79dc9930ab5bb144ddd5df5753e73', + 'hex', + ); + + it('should generate a sha256 hash from genesis block transaction root and community identifier', () => { + const networkIdentifier = getNetworkIdentifier(genesisBlockID, communityIdentifier); - expect(result).toEqual(binary); + expect(networkIdentifier).toEqual(expectedHash); + }); }); }); + + describe('Message Tag', () => { + describe('createMessageTag', () => { + it('should throw error if domain contains a space', () => { + expect(() => createMessageTag('MY TX')).toThrow( + 'Message tag domain must be alpha numeric without special characters. Got "MY TX".', + ); + }); + + it('should throw error if domain contains a underscore', () => { + expect(() => createMessageTag('MY_')).toThrow( + 'Message tag domain must be alpha numeric without special characters. Got "MY_".', + ); + }); + + it('should throw error if domain contains a special character', () => { + expect(() => createMessageTag('MY*')).toThrow( + 'Message tag domain must be alpha numeric without special characters. Got "MY*".', + ); + }); + + it('should return a valid tag', () => { + expect(createMessageTag('TX')).toEqual('LSK_TX_'); + }); + + it('should return a valid tag with version of number type', () => { + expect(createMessageTag('TX', 1)).toEqual('LSK_TX:1_'); + }); + + it('should return a valid tag with version of string type', () => { + expect(createMessageTag('TX', 'v2')).toEqual('LSK_TX:v2_'); + }); + }); + + describe('tagMessage', () => { + it('should concatenate the tag, network identifier and message when message is buffer', () => { + const tag = createMessageTag('TX'); + const tagBuffer = Buffer.from(tag, 'utf8'); + const networkId = Buffer.from('abc', 'utf8'); + const message = Buffer.from('message', 'utf8'); + const result = Buffer.concat([tagBuffer, networkId, message]); + + expect(tagMessage(tag, networkId, message)).toEqual(result); + }); + + it('should concatenate the tag, network identifier and message when message is string', () => { + const tag = createMessageTag('TX'); + const tagBuffer = Buffer.from(tag, 'utf8'); + const networkId = Buffer.from('abc', 'utf8'); + const message = Buffer.from('message', 'utf8'); + const result = Buffer.concat([tagBuffer, networkId, message]); + + expect(tagMessage(tag, networkId, 'message')).toEqual(result); + }); + }); + }); + + // describe('readBit', () => { + // it('should read bits of one byte buffer', () => { + // const binary = '10000101'; + // const buffer = Buffer.alloc(1); + // buffer.writeUIntLE(parseInt(binary, 2), 0, 1); + + // for (const [index, bit] of binary.split('').entries()) { + // expect(readBit(buffer, 7 - index)).toEqual(bit === '1'); + // } + // }); + + // it('should read bits of two byte buffer', () => { + // const binary = '1010001010000101'; + // const buffer = Buffer.alloc(2); + // buffer.writeUIntLE(parseInt(binary, 2), 0, 2); + + // for (const [index, bit] of binary.split('').entries()) { + // expect(readBit(buffer, 15 - index)).toEqual(bit === '1'); + // } + // }); + // }); + + // describe('writeBit', () => { + // it('should write bit of one byte buffer', () => { + // const binary = '10000101'; + // const buffer = Buffer.alloc(1); + // for (const [index, bit] of binary.split('').entries()) { + // writeBit(buffer, 7 - index, bit === '1'); + // } + // const result = buffer.readUIntLE(0, 1).toString(2).padStart(8, '0'); + + // expect(result).toEqual(binary); + // }); + + // it('should write bits of two byte buffer', () => { + // const binary = '1010001010000101'; + // const buffer = Buffer.alloc(2); + // for (const [index, bit] of binary.split('').entries()) { + // writeBit(buffer, 15 - index, bit === '1'); + // } + // const result = buffer.readUIntLE(0, 2).toString(2).padStart(16, '0'); + + // expect(result).toEqual(binary); + // }); + // }); }); From 9fabb11b877640a3a98a4b757fe0840194739acf Mon Sep 17 00:00:00 2001 From: shuse2 Date: Mon, 18 Jul 2022 14:49:13 +0200 Subject: [PATCH 4/6] :recycle: Fix elements test --- .../test/unit/transaction.spec.ts | 4 +- .../integration/data_access/blocks.spec.ts | 2 +- elements/lisk-chain/test/unit/block.spec.ts | 2 +- .../lisk-chain/test/unit/block_header.spec.ts | 2 +- elements/lisk-chain/test/unit/chain.spec.ts | 2 +- .../test/unit/data_access/data_access.spec.ts | 2 +- elements/lisk-chain/test/unit/event.spec.ts | 2 +- .../test/unit/state_store/state_store.spec.ts | 2 +- .../lisk-chain/test/unit/transactions.spec.ts | 2 +- elements/lisk-chain/test/utils/block.ts | 8 +- elements/lisk-chain/test/utils/transaction.ts | 4 +- .../{keys.spec.ts => address.spec.ts} | 24 +- .../test/lisk-cryptography/bls.spec.ts | 37 +++ .../test/lisk-cryptography/convert.spec.ts | 208 ------------ .../{sign.spec.ts => ed.spec.ts} | 128 +++++--- .../test/lisk-cryptography/encrypt.spec.ts | 302 ++++++++---------- .../test/lisk-cryptography/hash.spec.ts | 81 ----- .../test/lisk-cryptography/hash_onion.spec.ts | 58 ---- .../lisk-cryptography/legacy_address.spec.ts | 27 +- .../{buffer.spec.ts => utils.spec.ts} | 133 +++++++- .../test/unit/transaction_pool.spec.ts | 38 +-- .../test/utils/cryptography.ts | 4 +- elements/lisk-transactions/test/fee.spec.ts | 4 +- elements/lisk-transactions/test/sign.spec.ts | 33 +- .../test/sparse_merkle_tree/utils.spec.ts | 2 +- .../test/unit/abi_handler/abi_handler.spec.ts | 2 +- .../test/unit/engine/endpoint/txpool.spec.ts | 2 +- .../unit/engine/generator/broadcaster.spec.ts | 2 +- .../commands/delegate_registration.spec.ts | 2 +- .../modules/dpos_v2/commands/unlock.spec.ts | 2 +- .../test/unit/modules/dpos_v2/module.spec.ts | 2 +- .../dpos_v2/update_generator_key.spec.ts | 2 +- .../cc_commands/channel_terminated.spec.ts | 2 +- .../cc_commands/registration.spec.ts | 2 +- .../cc_commands/sidechain_terminated.spec.ts | 2 +- .../mainchain/commands/state_recovery.spec.ts | 2 +- .../commands/state_recovery_init.spec.ts | 2 +- .../interoperability/mainchain/store.spec.ts | 2 +- .../cc_commands/channel_terminated.spec.ts | 2 +- .../cc_commands/registration.spec.ts | 2 +- .../cc_commands/sidechain_terminated.spec.ts | 2 +- .../commands/message_recovery.spec.ts | 2 +- .../interoperability/sidechain/store.spec.ts | 2 +- .../modules/interoperability/store.spec.ts | 2 +- framework/test/unit/modules/token/api.spec.ts | 2 +- .../token/cc_commands/cc_forward.spec.ts | 2 +- .../token/cc_commands/cc_transfer.spec.ts | 2 +- .../test/unit/modules/token/endpoint.spec.ts | 2 +- .../modules/token/interoperable_api.spec.ts | 2 +- .../test/unit/modules/validators/api.spec.ts | 2 +- .../unit/state_machine/event_queue.spec.ts | 2 +- .../unit/state_machine/state_machine.spec.ts | 2 +- 52 files changed, 496 insertions(+), 669 deletions(-) rename elements/lisk-client/test/lisk-cryptography/{keys.spec.ts => address.spec.ts} (94%) create mode 100644 elements/lisk-client/test/lisk-cryptography/bls.spec.ts delete mode 100644 elements/lisk-client/test/lisk-cryptography/convert.spec.ts rename elements/lisk-client/test/lisk-cryptography/{sign.spec.ts => ed.spec.ts} (71%) delete mode 100644 elements/lisk-client/test/lisk-cryptography/hash.spec.ts delete mode 100644 elements/lisk-client/test/lisk-cryptography/hash_onion.spec.ts rename elements/lisk-client/test/lisk-cryptography/{buffer.spec.ts => utils.spec.ts} (55%) diff --git a/elements/lisk-api-client/test/unit/transaction.spec.ts b/elements/lisk-api-client/test/unit/transaction.spec.ts index d644b0f5922..a1fc42a6855 100644 --- a/elements/lisk-api-client/test/unit/transaction.spec.ts +++ b/elements/lisk-api-client/test/unit/transaction.spec.ts @@ -14,7 +14,7 @@ */ import { when } from 'jest-when'; -import { getAddressAndPublicKeyFromPassphrase, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils, address } from '@liskhq/lisk-cryptography'; import { Transaction } from '../../src/transaction'; import { metadata, nodeInfo, schema, tx } from '../utils/transaction'; @@ -26,7 +26,7 @@ describe('transaction', () => { 'faculty inspire crouch quit sorry vague hard ski scrap jaguar garment limb', ]; const passphrase1 = 'trim elegant oven term access apple obtain error grain excite lawn neck'; - const { publicKey: publicKey1 } = getAddressAndPublicKeyFromPassphrase(passphrase1); + const { publicKey: publicKey1 } = address.getAddressAndPublicKeyFromPassphrase(passphrase1); const publicKey2 = Buffer.from( 'fa406b6952d377f0278920e3eb8da919e4cf5c68b02eeba5d8b3334fdc0369b6', 'hex', diff --git a/elements/lisk-chain/test/integration/data_access/blocks.spec.ts b/elements/lisk-chain/test/integration/data_access/blocks.spec.ts index 940b405a7b8..01e0580c531 100644 --- a/elements/lisk-chain/test/integration/data_access/blocks.spec.ts +++ b/elements/lisk-chain/test/integration/data_access/blocks.spec.ts @@ -16,7 +16,7 @@ import * as path from 'path'; import * as fs from 'fs-extra'; import { Batch, Database, NotFoundError } from '@liskhq/lisk-db'; import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { encodeByteArray, Storage } from '../../../src/data_access/storage'; import { createValidDefaultBlock } from '../../utils/block'; import { getTransaction } from '../../utils/transaction'; diff --git a/elements/lisk-chain/test/unit/block.spec.ts b/elements/lisk-chain/test/unit/block.spec.ts index c81c80f2b7e..4e2558b84f0 100644 --- a/elements/lisk-chain/test/unit/block.spec.ts +++ b/elements/lisk-chain/test/unit/block.spec.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, hash, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Block, BlockAsset, BlockAssets, Transaction } from '../../src'; import { EMPTY_BUFFER, EMPTY_HASH } from '../../src/constants'; import { createValidDefaultBlock } from '../utils/block'; diff --git a/elements/lisk-chain/test/unit/block_header.spec.ts b/elements/lisk-chain/test/unit/block_header.spec.ts index 36f031cf225..44349571c72 100644 --- a/elements/lisk-chain/test/unit/block_header.spec.ts +++ b/elements/lisk-chain/test/unit/block_header.spec.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { hash, getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { BlockHeader } from '../../src/block_header'; import { EMPTY_BUFFER, EMPTY_HASH } from '../../src/constants'; import { diff --git a/elements/lisk-chain/test/unit/chain.spec.ts b/elements/lisk-chain/test/unit/chain.spec.ts index 4379bac239d..c87c98a5e71 100644 --- a/elements/lisk-chain/test/unit/chain.spec.ts +++ b/elements/lisk-chain/test/unit/chain.spec.ts @@ -15,7 +15,7 @@ import { NotFoundError, Batch, Database, InMemoryDatabase } from '@liskhq/lisk-db'; import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Chain } from '../../src/chain'; import { CurrentState, StateStore } from '../../src/state_store'; import { createValidDefaultBlock, defaultNetworkIdentifier } from '../utils/block'; diff --git a/elements/lisk-chain/test/unit/data_access/data_access.spec.ts b/elements/lisk-chain/test/unit/data_access/data_access.spec.ts index c5c8a32f44c..2e42bd3d46d 100644 --- a/elements/lisk-chain/test/unit/data_access/data_access.spec.ts +++ b/elements/lisk-chain/test/unit/data_access/data_access.spec.ts @@ -14,7 +14,7 @@ import { Readable } from 'stream'; import { when } from 'jest-when'; import { NotFoundError, InMemoryDatabase } from '@liskhq/lisk-db'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { DataAccess } from '../../../src/data_access'; import { createFakeBlockHeader, createValidDefaultBlock } from '../../utils/block'; import { Transaction } from '../../../src/transaction'; diff --git a/elements/lisk-chain/test/unit/event.spec.ts b/elements/lisk-chain/test/unit/event.spec.ts index 9b47d0ae328..648bcdae482 100644 --- a/elements/lisk-chain/test/unit/event.spec.ts +++ b/elements/lisk-chain/test/unit/event.spec.ts @@ -14,7 +14,7 @@ /* eslint-disable no-bitwise */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { eventSchema } from '../../src/schema'; import { Event } from '../../src/event'; import { EVENT_TOPIC_HASH_LENGTH_BYTES, EVENT_TOTAL_INDEX_LENGTH_BYTES } from '../../src/constants'; diff --git a/elements/lisk-chain/test/unit/state_store/state_store.spec.ts b/elements/lisk-chain/test/unit/state_store/state_store.spec.ts index 226d70b99db..42ffc5a6ee8 100644 --- a/elements/lisk-chain/test/unit/state_store/state_store.spec.ts +++ b/elements/lisk-chain/test/unit/state_store/state_store.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase } from '@liskhq/lisk-db'; import { DB_KEY_STATE_STORE } from '../../../src'; import { NotFoundError, StateStore } from '../../../src/state_store'; diff --git a/elements/lisk-chain/test/unit/transactions.spec.ts b/elements/lisk-chain/test/unit/transactions.spec.ts index 9d8e64c81f0..1376a5b0269 100644 --- a/elements/lisk-chain/test/unit/transactions.spec.ts +++ b/elements/lisk-chain/test/unit/transactions.spec.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Transaction } from '../../src/transaction'; describe('blocks/transactions', () => { diff --git a/elements/lisk-chain/test/utils/block.ts b/elements/lisk-chain/test/utils/block.ts index 247ae0c06b4..f549e7c576d 100644 --- a/elements/lisk-chain/test/utils/block.ts +++ b/elements/lisk-chain/test/utils/block.ts @@ -13,10 +13,8 @@ */ import { - getRandomBytes, - hash, - getPrivateAndPublicKeyFromPassphrase, - getAddressFromPublicKey, + utils, + address, } from '@liskhq/lisk-cryptography'; import { Mnemonic } from '@liskhq/lisk-passphrase'; import { MerkleTree } from '@liskhq/lisk-tree'; @@ -31,7 +29,7 @@ export const defaultNetworkIdentifier = Buffer.from( const getKeyPair = (): { publicKey: Buffer; privateKey: Buffer } => { const passphrase = Mnemonic.generateMnemonic(); - return getPrivateAndPublicKeyFromPassphrase(passphrase); + return address.getPrivateAndPublicKeyFromPassphrase(passphrase); }; export const createFakeBlockHeader = (header?: Partial): BlockHeader => diff --git a/elements/lisk-chain/test/utils/transaction.ts b/elements/lisk-chain/test/utils/transaction.ts index 1c759f4dad8..d674d73d4d6 100644 --- a/elements/lisk-chain/test/utils/transaction.ts +++ b/elements/lisk-chain/test/utils/transaction.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, intToBuffer, signData } from '@liskhq/lisk-cryptography'; +import { utils, ed } from '@liskhq/lisk-cryptography'; import { defaultNetworkIdentifier } from './block'; import { Transaction } from '../../src/transaction'; import { TAG_TRANSACTION } from '../../src'; @@ -37,7 +37,7 @@ export const getTransaction = (input?: { nonce?: bigint }): Transaction => { params: utils.getRandomBytes(128), signatures: [], }); - const signature = signData( + const signature = ed.signData( TAG_TRANSACTION, defaultNetworkIdentifier, tx.getSigningBytes(), diff --git a/elements/lisk-client/test/lisk-cryptography/keys.spec.ts b/elements/lisk-client/test/lisk-cryptography/address.spec.ts similarity index 94% rename from elements/lisk-client/test/lisk-cryptography/keys.spec.ts rename to elements/lisk-client/test/lisk-cryptography/address.spec.ts index 5be91867459..cda4e18b986 100644 --- a/elements/lisk-client/test/lisk-cryptography/keys.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/address.spec.ts @@ -16,16 +16,18 @@ import { cryptography } from '../../src'; const { - getAddressFromPublicKey, - getLisk32AddressFromPublicKey, - getPrivateAndPublicKeyFromPassphrase, - getKeys, - getAddressAndPublicKeyFromPassphrase, - getAddressFromPassphrase, - getAddressFromPrivateKey, - validateLisk32Address, - getAddressFromLisk32Address, - getLisk32AddressFromAddress, + address: { + getAddressFromPublicKey, + getLisk32AddressFromPublicKey, + getPrivateAndPublicKeyFromPassphrase, + getKeys, + getAddressAndPublicKeyFromPassphrase, + getAddressFromPassphrase, + getAddressFromPrivateKey, + validateLisk32Address, + getAddressFromLisk32Address, + getLisk32AddressFromAddress, + }, } = cryptography; describe('keys', () => { @@ -99,7 +101,7 @@ describe('keys', () => { describe('#address.getAddressFromPublicKey', () => { it('should generate address from publicKey', () => { - const address = address.getAddressFromPublicKey(defaultPublicKey); + const address = getAddressFromPublicKey(defaultPublicKey); expect(address).toEqual(defaultAddress); }); }); diff --git a/elements/lisk-client/test/lisk-cryptography/bls.spec.ts b/elements/lisk-client/test/lisk-cryptography/bls.spec.ts new file mode 100644 index 00000000000..699f1c3473b --- /dev/null +++ b/elements/lisk-client/test/lisk-cryptography/bls.spec.ts @@ -0,0 +1,37 @@ +/* eslint-disable camelcase */ +/* + * Copyright © 2022 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 { cryptography } from '../../src'; + +const { + bls: { + getPrivateKeyFromPhraseAndPath, + }, +} = cryptography; + +describe('bls', () => { + describe('getBLSPrivateKeyFromPhraseAndPath', () => { + const passphrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; + it('should get keypair from valid phrase and path', async () => { + const privateKey = await getPrivateKeyFromPhraseAndPath(passphrase, `m/12381`); + expect(privateKey.toString('hex')).toBe( + BigInt( + '27531519788986738912817629815232258573173656766051821145387425994698573826996', + ).toString(16), + ); + }); + }); +}); diff --git a/elements/lisk-client/test/lisk-cryptography/convert.spec.ts b/elements/lisk-client/test/lisk-cryptography/convert.spec.ts deleted file mode 100644 index cfdbc7933e9..00000000000 --- a/elements/lisk-client/test/lisk-cryptography/convert.spec.ts +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright © 2020 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 { cryptography } from '../../src'; - -const { - getFirstEightBytesReversed, - convertPublicKeyEd2Curve, - convertPrivateKeyEd2Curve, - stringifyEncryptedPassphrase, - parseEncryptedPassphrase, -} = cryptography; - -describe('convert', () => { - // keys for passphrase 'secret'; - const defaultPrivateKey = - '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b5d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09'; - const defaultPublicKey = Buffer.from( - '5d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09', - 'hex', - ); - const defaultPrivateKeyCurve = Buffer.from( - '68b211b2c01cc88690ba76a07895a5b4805e1c11fdd3af4c863e6d4efeb14378', - 'hex', - ); - const defaultPublicKeyCurve = Buffer.from( - '6f9d780305bda43dd47a291d897f2d8845a06160632d82fb1f209fdd46ed3c1e', - 'hex', - ); - const defaultStringWithMoreThanEightCharacters = '0123456789'; - const defaultFirstEightCharactersReversed = '76543210'; - - describe('#getFirstEightBytesReversed', () => { - it('should get the first eight bytes reversed from a Buffer', () => { - const bufferEntry = Buffer.from(defaultStringWithMoreThanEightCharacters); - const reversedAndCut = getFirstEightBytesReversed(bufferEntry); - expect(reversedAndCut).toEqual(Buffer.from(defaultFirstEightCharactersReversed)); - }); - - it('should get the first eight bytes reversed from a string', () => { - const reversedAndCut = getFirstEightBytesReversed(defaultStringWithMoreThanEightCharacters); - expect(reversedAndCut).toEqual(Buffer.from(defaultFirstEightCharactersReversed)); - }); - }); - - describe('#convertPublicKeyEd2Curve', () => { - it('should convert publicKey ED25519 to Curve25519 key', () => { - const result = convertPublicKeyEd2Curve(defaultPublicKey); - expect(result).not.toBeNull(); - const curveRepresentation = result as Buffer; - expect(defaultPublicKeyCurve.equals(Buffer.from(curveRepresentation))).toBe(true); - }); - }); - - describe('#convertPrivateKeyEd2Curve', () => { - it('should convert privateKey ED25519 to Curve25519 key', () => { - const curveRepresentation = convertPrivateKeyEd2Curve(Buffer.from(defaultPrivateKey, 'hex')); - expect(defaultPrivateKeyCurve.equals(Buffer.from(curveRepresentation))).toBe(true); - }); - }); - - describe('#stringifyEncryptedPassphrase', () => { - it('should throw an error if encrypted passphrase is not an object', () => { - const encryptedPassphrase = - 'salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; - expect(stringifyEncryptedPassphrase.bind(null, encryptedPassphrase as any)).toThrow( - 'Encrypted passphrase to stringify must be an object.', - ); - }); - - it('should format an encrypted passphrase as a string', () => { - const encryptedPassphrase = { - ciphertext: - 'fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4', - mac: '997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d', - kdf: 'argon2id', - kdfparams: { - parallelism: 4, - iterations: 1, - memorySize: 2024, - salt: 'd3228c53c27a44cbd9d88ea0919bdade', - }, - cipher: 'aes-256-gcm', - cipherparams: { - iv: 'b5c86483366f4698708e6985', - tag: '5d6c0f628ba12930111c33ef678b2319', - }, - version: '1', - }; - const stringifiedEncryptedPassphrase = - 'kdf=argon2id&cipher=aes-256-gcm&version=1&ciphertext=fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4&mac=997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d&salt=d3228c53c27a44cbd9d88ea0919bdade&iv=b5c86483366f4698708e6985&tag=5d6c0f628ba12930111c33ef678b2319&iterations=1¶llelism=4&memorySize=2024'; - expect(stringifyEncryptedPassphrase(encryptedPassphrase as any)).toBe( - stringifiedEncryptedPassphrase, - ); - }); - - it('should format an encrypted passphrase with custom iterations as a string', () => { - const encryptedPassphrase = { - ciphertext: - 'fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4', - mac: '997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d', - kdf: 'argon2id', - kdfparams: { - parallelism: 4, - iterations: 10000, - memorySize: 2024, - salt: 'd3228c53c27a44cbd9d88ea0919bdade', - }, - cipher: 'aes-256-gcm', - cipherparams: { - iv: 'b5c86483366f4698708e6985', - tag: '5d6c0f628ba12930111c33ef678b2319', - }, - version: '1', - }; - const stringifiedEncryptedPassphrase = - 'kdf=argon2id&cipher=aes-256-gcm&version=1&ciphertext=fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4&mac=997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d&salt=d3228c53c27a44cbd9d88ea0919bdade&iv=b5c86483366f4698708e6985&tag=5d6c0f628ba12930111c33ef678b2319&iterations=10000¶llelism=4&memorySize=2024'; - expect(stringifyEncryptedPassphrase(encryptedPassphrase as any)).toBe( - stringifiedEncryptedPassphrase, - ); - }); - }); - - describe('#parseEncryptedPassphrase', () => { - it('should throw an error if encrypted passphrase is not a string', () => { - const stringifiedEncryptedPassphrase = { abc: 'def' }; - expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase as any)).toThrow( - 'Encrypted passphrase to parse must be a string.', - ); - }); - - it('should throw an error if iterations is present but not a valid number', () => { - const stringifiedEncryptedPassphrase = - 'iterations=null&salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; - expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase)).toThrow( - 'Encrypted passphrase to parse must have only one value per key.', - ); - }); - - it('should throw an error if multiple values are in a key', () => { - const stringifiedEncryptedPassphrase = - 'salt=xxx&salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; - expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase)).toThrow( - 'Encrypted passphrase to parse must have only one value per key.', - ); - }); - - it('should parse an encrypted passphrase string', () => { - const stringifiedEncryptedPassphrase = - 'kdf=argon2id&cipher=aes-256-gcm&version=1&ciphertext=fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4&mac=997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d&salt=d3228c53c27a44cbd9d88ea0919bdade&iv=b5c86483366f4698708e6985&tag=5d6c0f628ba12930111c33ef678b2319&iterations=1¶llelism=4&memorySize=2024'; - const encryptedPassphrase = { - ciphertext: - 'fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4', - mac: '997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d', - kdf: 'argon2id', - kdfparams: { - parallelism: 4, - iterations: 1, - memorySize: 2024, - salt: 'd3228c53c27a44cbd9d88ea0919bdade', - }, - cipher: 'aes-256-gcm', - cipherparams: { - iv: 'b5c86483366f4698708e6985', - tag: '5d6c0f628ba12930111c33ef678b2319', - }, - version: '1', - }; - expect(parseEncryptedPassphrase(stringifiedEncryptedPassphrase)).toEqual(encryptedPassphrase); - }); - - it('should parse an encrypted passphrase string with custom iterations', () => { - const stringifiedEncryptedPassphrase = - 'kdf=argon2id&cipher=aes-256-gcm&version=1&ciphertext=fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4&mac=997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d&salt=d3228c53c27a44cbd9d88ea0919bdade&iv=b5c86483366f4698708e6985&tag=5d6c0f628ba12930111c33ef678b2319&iterations=10000¶llelism=4&memorySize=2024'; - const encryptedPassphrase = { - ciphertext: - 'fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4', - mac: '997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d', - kdf: 'argon2id', - kdfparams: { - parallelism: 4, - iterations: 10000, - memorySize: 2024, - salt: 'd3228c53c27a44cbd9d88ea0919bdade', - }, - cipher: 'aes-256-gcm', - cipherparams: { - iv: 'b5c86483366f4698708e6985', - tag: '5d6c0f628ba12930111c33ef678b2319', - }, - version: '1', - }; - expect(parseEncryptedPassphrase(stringifiedEncryptedPassphrase)).toEqual(encryptedPassphrase); - }); - }); -}); diff --git a/elements/lisk-client/test/lisk-cryptography/sign.spec.ts b/elements/lisk-client/test/lisk-cryptography/ed.spec.ts similarity index 71% rename from elements/lisk-client/test/lisk-cryptography/sign.spec.ts rename to elements/lisk-client/test/lisk-cryptography/ed.spec.ts index e24446a13b4..2cd55b774e4 100644 --- a/elements/lisk-client/test/lisk-cryptography/sign.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/ed.spec.ts @@ -16,16 +16,21 @@ import { cryptography } from '../../src'; const { - signMessageWithPassphrase, - verifyMessageWithPublicKey, - printSignedMessage, - signAndPrintMessage, - signData, - signDataWithPassphrase, - signDataWithPrivateKey, - verifyData, - digestMessage, - createMessageTag, + ed: { + signMessageWithPassphrase, + verifyMessageWithPublicKey, + printSignedMessage, + signAndPrintMessage, + signData, + signDataWithPassphrase, + signDataWithPrivateKey, + verifyData, + getKeyPairFromPhraseAndPath, + getPublicKeyFromPrivateKey, + }, + utils: { + createMessageTag, + }, } = cryptography; const makeInvalid = (buffer: Buffer): Buffer => { @@ -38,6 +43,7 @@ const makeInvalid = (buffer: Buffer): Buffer => { const changeLength = (buffer: Buffer): Buffer => Buffer.concat([Buffer.from('00', 'hex'), buffer]); describe('sign', () => { + const MAX_UINT32 = 4294967295; const tag = createMessageTag('TST'); const networkIdentifier = Buffer.from('a5df2ed79994178c10ac168d6d977ef45cd525e95b7a8624', 'hex'); const defaultPassphrase = 'minute omit local rare sword knee banner pair rib museum shadow juice'; @@ -72,45 +78,6 @@ ${defaultSignature} }; }); - describe('#digestMessage', () => { - const strGenerator = (len: number, chr: string): string => chr.repeat(len); - - it('should create message digest for message with length = 0', () => { - const msgBytes = digestMessage(''); - const expectedMessageBytes = Buffer.from( - '3fdb82ac2a879b647f4f27f3fbd1c27e0d4e278f830b76295604035330163b79', - 'hex', - ); - expect(msgBytes).toEqual(expectedMessageBytes); - }); - it('should create message digest for message in length range 1 - 253', () => { - const msgBytes = digestMessage(strGenerator(250, 'a')); - const expectedMessageBytes = Buffer.from( - '12832c687d950513aa5db6198b84809eb8fd7ff1c8963dca48ea57278523ec67', - 'hex', - ); - expect(msgBytes).toEqual(expectedMessageBytes); - }); - it('should create message digest for message in length range 254 - 65536', () => { - const msgBytes = digestMessage(strGenerator(65535, 'a')); - const expectedMessageBytes = Buffer.from( - '73da94220312e71eb5c55c94fdddca3c06a6c18cb74a4a4a2cee1a82875c2450', - 'hex', - ); - expect(msgBytes).toEqual(expectedMessageBytes); - }); - it('should create message digest for message in length range 65537 - 4294967296', () => { - const msgBytes = digestMessage(strGenerator(6710886, 'a')); - const expectedMessageBytes = Buffer.from( - '7c51817b5c31c4d04e9ffcf2e78859d6522b124f218c789a8f721b5f3e6b295d', - 'hex', - ); - expect(msgBytes).toEqual(expectedMessageBytes); - }); - // highest range (length > 4294967296) is not practical to test - // but it is covered by `varuint-bitcoin` library - }); - describe('#signMessageWithPassphrase', () => { it('should create a signed message using a secret passphrase', () => { const signedMessage = signMessageWithPassphrase(defaultMessage, defaultPassphrase); @@ -239,4 +206,67 @@ ${defaultSignature} expect(verification).toBe(true); }); }); + + describe('getKeyPairFromPhraseAndPath', () => { + const passphrase = + 'target cancel solution recipe vague faint bomb convince pink vendor fresh patrol'; + it('should get keypair from valid phrase and path', async () => { + const privateKey = await getKeyPairFromPhraseAndPath( + passphrase, + `m/44'/134'/0'`, + ); + const publicKey = getPublicKeyFromPrivateKey(privateKey); + expect(publicKey.toString('hex')).toBe( + 'c6bae83af23540096ac58d5121b00f33be6f02f05df785766725acdd5d48be9d', + ); + expect(privateKey.toString('hex')).toBe( + 'c465dfb15018d3aef0d94d411df048e240e87a3ec9cd6d422cea903bfc101f61c6bae83af23540096ac58d5121b00f33be6f02f05df785766725acdd5d48be9d', + ); + }); + + it('should fail for empty string path', async () => { + await expect(getKeyPairFromPhraseAndPath(passphrase, '')).rejects.toThrow( + 'Invalid path format', + ); + }); + + it('should fail if path does not start with "m"', async () => { + await expect(getKeyPairFromPhraseAndPath(passphrase, `/44'/134'/0'`)).rejects.toThrow( + 'Invalid path format', + ); + }); + + it('should fail if path does not include at least one "/"', async () => { + await expect(getKeyPairFromPhraseAndPath(passphrase, 'm441340')).rejects.toThrow( + 'Invalid path format', + ); + }); + + it('should fail for path with invalid segment', async () => { + await expect( + getKeyPairFromPhraseAndPath( + passphrase, + `m//134'/0'`, // should be number with or without ' between every back slash + ), + ).rejects.toThrow('Invalid path format'); + }); + + it('should fail for path with invalid characters', async () => { + await expect(getKeyPairFromPhraseAndPath(passphrase, `m/a'/134b'/0'`)).rejects.toThrow( + 'Invalid path format', + ); + }); + + it('should fail for path with non-sanctioned special characters', async () => { + await expect(getKeyPairFromPhraseAndPath(passphrase, `m/4a'/#134b'/0'`)).rejects.toThrow( + 'Invalid path format', + ); + }); + + it(`should fail for path with segment greater than ${MAX_UINT32} / 2`, async () => { + await expect( + getKeyPairFromPhraseAndPath(passphrase, `m/44'/134'/${MAX_UINT32}'`), + ).rejects.toThrow('Invalid path format'); + }); + }); }); diff --git a/elements/lisk-client/test/lisk-cryptography/encrypt.spec.ts b/elements/lisk-client/test/lisk-cryptography/encrypt.spec.ts index 3d496f17811..f8b5a147598 100644 --- a/elements/lisk-client/test/lisk-cryptography/encrypt.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/encrypt.spec.ts @@ -11,27 +11,24 @@ * Removal or modification of this copyright notice is prohibited. * */ - -import { - EncryptedPassphraseObject, - EncryptedMessageWithNonce, - encryptMessageWithPassphrase, - decryptMessageWithPassphrase, - encryptPassphraseWithPassword, - decryptPassphraseWithPassword, - getKeyPairFromPhraseAndPath, - KDF, - Cipher, - getBLSPrivateKeyFromPhraseAndPath, -} from '@liskhq/lisk-cryptography'; import * as cryptography from '@liskhq/lisk-cryptography'; jest.mock('@liskhq/lisk-cryptography', () => ({ ...jest.requireActual('@liskhq/lisk-cryptography'), })); +const { + encrypt: { + encryptPassphraseWithPassword, + decryptPassphraseWithPassword, + stringifyEncryptedPassphrase, + parseEncryptedPassphrase, + KDF, + Cipher, + }, +} = cryptography; + describe('encrypt', () => { - const MAX_UINT32 = 4294967295; const regHexadecimal = /[0-9A-Za-z]/g; const PBKDF2_ITERATIONS = 1e6; const ENCRYPTION_VERSION = '1'; @@ -44,31 +41,13 @@ describe('encrypt', () => { '7ef45cd525e95b7a86244bbd4eb4550914ad06301013958f4dd64d32ef7bc588', 'hex', ); - const defaultMessage = 'Some default text.'; const defaultPassword = 'myTotal53cr3t%&'; const customIterations = 12; - let defaultEncryptedMessageWithNonce: EncryptedMessageWithNonce; - let hashStub: any; beforeEach(async () => { - defaultEncryptedMessageWithNonce = { - encryptedMessage: '299390b9cbb92fe6a43daece2ceaecbacd01c7c03cfdba51d693b5c0e2b65c634115', - nonce: 'df4c8b09e270d2cb3f7b3d53dfa8a6f3441ad3b14a13fb66', - }; - jest - .spyOn(cryptography, 'convertPrivateKeyEd2Curve') - .mockReturnValue( - Buffer.from('d8be8cacb03fb02f34e85030f902b635f364d6c23f090c7640e9dc9c568e7d5e', 'hex'), - ); - jest - .spyOn(cryptography, 'convertPublicKeyEd2Curve') - .mockReturnValue( - Buffer.from('f245e78c83196d73452e55581ef924a1b792d352c142257aa3af13cded2e7905', 'hex'), - ); - - jest.spyOn(cryptography, 'getAddressAndPublicKeyFromPassphrase').mockImplementation(() => { + jest.spyOn(cryptography.address, 'getAddressAndPublicKeyFromPassphrase').mockImplementation(() => { return { address: defaultPrivateKey, publicKey: defaultPublicKey, @@ -76,74 +55,13 @@ describe('encrypt', () => { }); hashStub = jest - .spyOn(cryptography, 'hash') + .spyOn(cryptography.utils, 'hash') .mockReturnValue( Buffer.from('d43eed9049dd8f35106c720669a1148b2c6288d9ea517b936c33a1d84117a760', 'hex'), ); return Promise.resolve(); }); - describe('#encryptMessageWithPassphrase', () => { - let encryptedMessage: EncryptedMessageWithNonce; - - beforeEach(async () => { - encryptedMessage = encryptMessageWithPassphrase( - defaultMessage, - defaultPassphrase, - defaultPublicKey, - ); - return Promise.resolve(); - }); - - it('should encrypt a message', () => { - expect(encryptedMessage).toHaveProperty('encryptedMessage'); - expect(regHexadecimal.test(encryptedMessage.encryptedMessage)).toBe(true); - }); - - it('should output the nonce', () => { - expect(encryptedMessage).not.toBeUndefined(); - expect(encryptedMessage).toHaveProperty('nonce'); - expect(regHexadecimal.test(encryptedMessage.nonce)).toBe(true); - }); - }); - - describe('#decryptMessageWithPassphrase', () => { - it('should be able to decrypt the message correctly using the receiver’s secret passphrase', () => { - const decryptedMessage = decryptMessageWithPassphrase( - defaultEncryptedMessageWithNonce.encryptedMessage, - defaultEncryptedMessageWithNonce.nonce, - defaultPassphrase, - defaultPublicKey, - ); - - expect(decryptedMessage).toBe(defaultMessage); - }); - - it('should inform the user if the nonce is the wrong length', () => { - expect( - decryptMessageWithPassphrase.bind( - null, - defaultEncryptedMessageWithNonce.encryptedMessage, - defaultEncryptedMessageWithNonce.encryptedMessage.slice(0, 2), - defaultPassphrase, - defaultPublicKey, - ), - ).toThrow('Expected nonce to be 24 bytes.'); - }); - - it('should inform the user if something goes wrong during decryption', () => { - expect( - decryptMessageWithPassphrase.bind( - null, - defaultEncryptedMessageWithNonce.encryptedMessage.slice(0, 2), - defaultEncryptedMessageWithNonce.nonce, - defaultPassphrase, - defaultPublicKey, - ), - ).toThrow('Something went wrong during decryption. Is this the full encrypted message?'); - }); - }); - describe('encrypt and decrypt passphrase with password', () => { beforeEach(() => { hashStub.mockReturnValue( @@ -152,7 +70,7 @@ describe('encrypt', () => { }); describe('#encryptPassphraseWithPassword', () => { - let encryptedPassphrase: EncryptedPassphraseObject; + let encryptedPassphrase: cryptography.encrypt.EncryptedPassphraseObject; beforeEach(async () => { encryptedPassphrase = await encryptPassphraseWithPassword( @@ -204,7 +122,7 @@ describe('encrypt', () => { }); describe('#decryptPassphraseWithPassword', () => { - let encryptedPassphrase: EncryptedPassphraseObject; + let encryptedPassphrase: cryptography.encrypt.EncryptedPassphraseObject; beforeEach(() => { encryptedPassphrase = { @@ -368,80 +286,140 @@ describe('encrypt', () => { expect(decryptedString).toBe(defaultPassphrase); }); }); + }); - describe('getKeyPairFromPhraseAndPath', () => { - const passphrase = - 'target cancel solution recipe vague faint bomb convince pink vendor fresh patrol'; - it('should get keypair from valid phrase and path', async () => { - const { publicKey, privateKey } = await getKeyPairFromPhraseAndPath( - passphrase, - `m/44'/134'/0'`, - ); - expect(publicKey.toString('hex')).toBe( - 'c6bae83af23540096ac58d5121b00f33be6f02f05df785766725acdd5d48be9d', - ); - expect(privateKey.toString('hex')).toBe( - 'c465dfb15018d3aef0d94d411df048e240e87a3ec9cd6d422cea903bfc101f61c6bae83af23540096ac58d5121b00f33be6f02f05df785766725acdd5d48be9d', - ); - }); - - it('should fail for empty string path', async () => { - await expect(getKeyPairFromPhraseAndPath(passphrase, '')).rejects.toThrow( - 'Invalid path format', - ); - }); + describe('#stringifyEncryptedPassphrase', () => { + it('should throw an error if encrypted passphrase is not an object', () => { + const encryptedPassphrase = + 'salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; + expect(stringifyEncryptedPassphrase.bind(null, encryptedPassphrase as any)).toThrow( + 'Encrypted passphrase to stringify must be an object.', + ); + }); - it('should fail if path does not start with "m"', async () => { - await expect(getKeyPairFromPhraseAndPath(passphrase, `/44'/134'/0'`)).rejects.toThrow( - 'Invalid path format', - ); - }); + it('should format an encrypted passphrase as a string', () => { + const encryptedPassphrase = { + ciphertext: + 'fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4', + mac: '997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d', + kdf: 'argon2id', + kdfparams: { + parallelism: 4, + iterations: 1, + memorySize: 2024, + salt: 'd3228c53c27a44cbd9d88ea0919bdade', + }, + cipher: 'aes-256-gcm', + cipherparams: { + iv: 'b5c86483366f4698708e6985', + tag: '5d6c0f628ba12930111c33ef678b2319', + }, + version: '1', + }; + const stringifiedEncryptedPassphrase = + 'kdf=argon2id&cipher=aes-256-gcm&version=1&ciphertext=fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4&mac=997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d&salt=d3228c53c27a44cbd9d88ea0919bdade&iv=b5c86483366f4698708e6985&tag=5d6c0f628ba12930111c33ef678b2319&iterations=1¶llelism=4&memorySize=2024'; + expect(stringifyEncryptedPassphrase(encryptedPassphrase as any)).toBe( + stringifiedEncryptedPassphrase, + ); + }); - it('should fail if path does not include at least one "/"', async () => { - await expect(getKeyPairFromPhraseAndPath(passphrase, 'm441340')).rejects.toThrow( - 'Invalid path format', - ); - }); + it('should format an encrypted passphrase with custom iterations as a string', () => { + const encryptedPassphrase = { + ciphertext: + 'fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4', + mac: '997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d', + kdf: 'argon2id', + kdfparams: { + parallelism: 4, + iterations: 10000, + memorySize: 2024, + salt: 'd3228c53c27a44cbd9d88ea0919bdade', + }, + cipher: 'aes-256-gcm', + cipherparams: { + iv: 'b5c86483366f4698708e6985', + tag: '5d6c0f628ba12930111c33ef678b2319', + }, + version: '1', + }; + const stringifiedEncryptedPassphrase = + 'kdf=argon2id&cipher=aes-256-gcm&version=1&ciphertext=fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4&mac=997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d&salt=d3228c53c27a44cbd9d88ea0919bdade&iv=b5c86483366f4698708e6985&tag=5d6c0f628ba12930111c33ef678b2319&iterations=10000¶llelism=4&memorySize=2024'; + expect(stringifyEncryptedPassphrase(encryptedPassphrase as any)).toBe( + stringifiedEncryptedPassphrase, + ); + }); + }); - it('should fail for path with invalid segment', async () => { - await expect( - getKeyPairFromPhraseAndPath( - passphrase, - `m//134'/0'`, // should be number with or without ' between every back slash - ), - ).rejects.toThrow('Invalid path format'); - }); + describe('#parseEncryptedPassphrase', () => { + it('should throw an error if encrypted passphrase is not a string', () => { + const stringifiedEncryptedPassphrase = { abc: 'def' }; + expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase as any)).toThrow( + 'Encrypted passphrase to parse must be a string.', + ); + }); - it('should fail for path with invalid characters', async () => { - await expect(getKeyPairFromPhraseAndPath(passphrase, `m/a'/134b'/0'`)).rejects.toThrow( - 'Invalid path format', - ); - }); + it('should throw an error if iterations is present but not a valid number', () => { + const stringifiedEncryptedPassphrase = + 'iterations=null&salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; + expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase)).toThrow( + 'Encrypted passphrase to parse must have only one value per key.', + ); + }); - it('should fail for path with non-sanctioned special characters', async () => { - await expect(getKeyPairFromPhraseAndPath(passphrase, `m/4a'/#134b'/0'`)).rejects.toThrow( - 'Invalid path format', - ); - }); + it('should throw an error if multiple values are in a key', () => { + const stringifiedEncryptedPassphrase = + 'salt=xxx&salt=e8c7dae4c893e458e0ebb8bff9a36d84&cipherText=c0fab123d83c386ffacef9a171b6e0e0e9d913e58b7972df8e5ef358afbc65f99c9a2b6fe7716f708166ed72f59f007d2f96a91f48f0428dd51d7c9962e0c6a5fc27ca0722038f1f2cf16333&iv=1a2206e426c714091b7e48f6&tag=3a9d9f9f9a92c9a58296b8df64820c15&version=1'; + expect(parseEncryptedPassphrase.bind(null, stringifiedEncryptedPassphrase)).toThrow( + 'Encrypted passphrase to parse must have only one value per key.', + ); + }); - it(`should fail for path with segment greater than ${MAX_UINT32} / 2`, async () => { - await expect( - getKeyPairFromPhraseAndPath(passphrase, `m/44'/134'/${MAX_UINT32}'`), - ).rejects.toThrow('Invalid path format'); - }); + it('should parse an encrypted passphrase string', () => { + const stringifiedEncryptedPassphrase = + 'kdf=argon2id&cipher=aes-256-gcm&version=1&ciphertext=fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4&mac=997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d&salt=d3228c53c27a44cbd9d88ea0919bdade&iv=b5c86483366f4698708e6985&tag=5d6c0f628ba12930111c33ef678b2319&iterations=1¶llelism=4&memorySize=2024'; + const encryptedPassphrase = { + ciphertext: + 'fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4', + mac: '997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d', + kdf: 'argon2id', + kdfparams: { + parallelism: 4, + iterations: 1, + memorySize: 2024, + salt: 'd3228c53c27a44cbd9d88ea0919bdade', + }, + cipher: 'aes-256-gcm', + cipherparams: { + iv: 'b5c86483366f4698708e6985', + tag: '5d6c0f628ba12930111c33ef678b2319', + }, + version: '1', + }; + expect(parseEncryptedPassphrase(stringifiedEncryptedPassphrase)).toEqual(encryptedPassphrase); }); - describe('getBLSPrivateKeyFromPhraseAndPath', () => { - const passphrase = - 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'; - it('should get keypair from valid phrase and path', async () => { - const privateKey = await getBLSPrivateKeyFromPhraseAndPath(passphrase, `m/12381`); - expect(privateKey.toString('hex')).toBe( - BigInt( - '27531519788986738912817629815232258573173656766051821145387425994698573826996', - ).toString(16), - ); - }); + it('should parse an encrypted passphrase string with custom iterations', () => { + const stringifiedEncryptedPassphrase = + 'kdf=argon2id&cipher=aes-256-gcm&version=1&ciphertext=fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4&mac=997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d&salt=d3228c53c27a44cbd9d88ea0919bdade&iv=b5c86483366f4698708e6985&tag=5d6c0f628ba12930111c33ef678b2319&iterations=10000¶llelism=4&memorySize=2024'; + const encryptedPassphrase = { + ciphertext: + 'fc8cdb068314590fa7e3156c60bf4a6b1f908f91bb81c79319e858cead7fba581101167c12a4f63acf86908b5c2d7dad96246cd9cd25bc8adca61d7301925869e8bf5cf2a573ae9e5a84e4', + mac: '997afad0b38f2d47f347648994a65e8d7ec46feec92720ab629a77cc11875c4d', + kdf: 'argon2id', + kdfparams: { + parallelism: 4, + iterations: 10000, + memorySize: 2024, + salt: 'd3228c53c27a44cbd9d88ea0919bdade', + }, + cipher: 'aes-256-gcm', + cipherparams: { + iv: 'b5c86483366f4698708e6985', + tag: '5d6c0f628ba12930111c33ef678b2319', + }, + version: '1', + }; + expect(parseEncryptedPassphrase(stringifiedEncryptedPassphrase)).toEqual(encryptedPassphrase); }); }); }); diff --git a/elements/lisk-client/test/lisk-cryptography/hash.spec.ts b/elements/lisk-client/test/lisk-cryptography/hash.spec.ts deleted file mode 100644 index b5545676ecf..00000000000 --- a/elements/lisk-client/test/lisk-cryptography/hash.spec.ts +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright © 2020 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 { cryptography } from '../../src'; - -const { hash: hashFunction, getNetworkIdentifier } = cryptography; - -describe('hash', () => { - describe('#hash', () => { - const defaultText = 'text123*'; - let arrayToHash: ReadonlyArray; - let defaultHash: Buffer; - - beforeEach(() => { - defaultHash = Buffer.from( - '7607d6792843d6003c12495b54e34517a508d2a8622526aff1884422c5478971', - 'hex', - ); - arrayToHash = [1, 2, 3]; - }); - - it('should generate a sha256 hash from a Buffer', () => { - const testBuffer = Buffer.from(defaultText); - const hash = hashFunction(testBuffer); - expect(hash).toEqual(defaultHash); - }); - - it('should generate a sha256 hash from a utf8 string', () => { - const hash = hashFunction(defaultText, 'utf8'); - expect(hash).toEqual(defaultHash); - }); - - it('should generate a sha256 hash from a hex string', () => { - const testHex = Buffer.from(defaultText).toString('hex'); - const hash = hashFunction(testHex, 'hex'); - expect(hash).toEqual(defaultHash); - }); - - it('should throw on unknown format when trying a string with format "utf32"', () => { - expect(hashFunction.bind(null, defaultText, 'utf32')).toThrow( - 'Unsupported string format. Currently only `hex` and `utf8` are supported.', - ); - }); - - it('should throw on unknown format when using an array', () => { - expect(hashFunction.bind(null, arrayToHash as any)).toThrow( - 'Unsupported data:1,2,3 and format:undefined. Currently only Buffers or hex and utf8 strings are supported.', - ); - }); - }); - - describe('#getNetworkIdentifier', () => { - const genesisBlockID = Buffer.from( - 'ed14889723f24ecc54871d058d98ce91ff2f973192075c0155ba2b7b70ad2511', - 'hex', - ); - const communityIdentifier = 'LISK'; - const expectedHash = Buffer.from( - '6f201e72e20571b93ed42470caa94af1ace79dc9930ab5bb144ddd5df5753e73', - 'hex', - ); - - it('should generate a sha256 hash from genesis block transaction root and community identifier', () => { - const networkIdentifier = getNetworkIdentifier(genesisBlockID, communityIdentifier); - - expect(networkIdentifier).toEqual(expectedHash); - }); - }); -}); diff --git a/elements/lisk-client/test/lisk-cryptography/hash_onion.spec.ts b/elements/lisk-client/test/lisk-cryptography/hash_onion.spec.ts deleted file mode 100644 index 3ddb204e443..00000000000 --- a/elements/lisk-client/test/lisk-cryptography/hash_onion.spec.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright © 2020 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 { cryptography } from '../../src'; - -const { hashOnion, generateHashOnionSeed } = cryptography; - -describe('hash onion', () => { - describe('#generateHashOnionSeed', () => { - it('should generate a random buffer', () => { - const seed1 = generateHashOnionSeed().toString('hex'); - const seed2 = generateHashOnionSeed().toString('hex'); - - expect(seed1).not.toEqual(seed2); - }); - - it('should generate a random buffer with 16 bytes', () => { - const seed = generateHashOnionSeed(); - expect(seed).toHaveLength(16); - }); - }); - - describe('#hashOnion', () => { - let seed: Buffer; - let hashOnionBuffers: ReadonlyArray; - - beforeEach(() => { - seed = generateHashOnionSeed(); - hashOnionBuffers = hashOnion(seed); - }); - - it('should return 1001 hash onion hashes checkpoints by default', () => { - expect(hashOnionBuffers).toHaveLength(1001); - }); - - it('should return hash onion hashes which includes seed as the last element', () => { - expect(hashOnionBuffers[1000]).toEqual(seed); - }); - - it('should be able to calculate the checkpoint from another checkpoint', () => { - const firstDistanceHashes = hashOnion(hashOnionBuffers[1].slice(), 1000, 1); - expect(firstDistanceHashes[0]).toEqual(hashOnionBuffers[0]); - expect(firstDistanceHashes[1000]).toEqual(hashOnionBuffers[1]); - }); - }); -}); diff --git a/elements/lisk-client/test/lisk-cryptography/legacy_address.spec.ts b/elements/lisk-client/test/lisk-cryptography/legacy_address.spec.ts index 13048964bce..008098b1d7d 100644 --- a/elements/lisk-client/test/lisk-cryptography/legacy_address.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/legacy_address.spec.ts @@ -17,10 +17,13 @@ import { cryptography } from '../../src'; const { - getLegacyAddressAndPublicKeyFromPassphrase, - getLegacyAddressFromPassphrase, - getLegacyAddressFromPrivateKey, - getLegacyAddressFromPublicKey, + legacyAddress: { + getLegacyAddressAndPublicKeyFromPassphrase, + getLegacyAddressFromPassphrase, + getLegacyAddressFromPrivateKey, + getLegacyAddressFromPublicKey, + getFirstEightBytesReversed, + }, } = cryptography; describe('Legacy address', () => { @@ -36,6 +39,22 @@ describe('Legacy address', () => { ); const defaultAddress = '7115442636316065252L'; + describe('#getFirstEightBytesReversed', () => { + const defaultStringWithMoreThanEightCharacters = '0123456789'; + const defaultFirstEightCharactersReversed = '76543210'; + + it('should get the first eight bytes reversed from a Buffer', () => { + const bufferEntry = Buffer.from(defaultStringWithMoreThanEightCharacters); + const reversedAndCut = getFirstEightBytesReversed(bufferEntry); + expect(reversedAndCut).toEqual(Buffer.from(defaultFirstEightCharactersReversed)); + }); + + it('should get the first eight bytes reversed from a string', () => { + const reversedAndCut = getFirstEightBytesReversed(defaultStringWithMoreThanEightCharacters); + expect(reversedAndCut).toEqual(Buffer.from(defaultFirstEightCharactersReversed)); + }); + }); + describe('#getLegacyAddressAndPublicKeyFromPassphrase', () => { it('should return expected address', () => { expect(getLegacyAddressAndPublicKeyFromPassphrase(defaultPassphrase)).toEqual({ diff --git a/elements/lisk-client/test/lisk-cryptography/buffer.spec.ts b/elements/lisk-client/test/lisk-cryptography/utils.spec.ts similarity index 55% rename from elements/lisk-client/test/lisk-cryptography/buffer.spec.ts rename to elements/lisk-client/test/lisk-cryptography/utils.spec.ts index c708f37456a..70624fe3ce1 100644 --- a/elements/lisk-client/test/lisk-cryptography/buffer.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/utils.spec.ts @@ -15,7 +15,15 @@ import { cryptography } from '../../src'; -const { bufferToHex, hexToBuffer, intToBuffer } = cryptography; +const { utils: { + generateHashOnionSeed, + bufferToHex, + hexToBuffer, + intToBuffer, + getNetworkIdentifier, + hashOnion, + hash: hashFunction, +}, } = cryptography; describe('buffer', () => { const defaultBuffer = Buffer.from('\xe5\xe4\xf6'); @@ -88,7 +96,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt8(value, 0); - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 1 byte buffer when size=1, endian=little', () => { @@ -99,7 +107,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt8(value, 0); - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 2 bytes big endian buffer when size=2, endian=big', () => { @@ -110,7 +118,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt16BE(value, 0); - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 2 bytes little endian buffer when size=2, endian=little', () => { @@ -121,7 +129,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt16LE(value, 0); - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 4 bytes big endian buffer when size=4, endian=big', () => { @@ -132,7 +140,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt32BE(value, 0); - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 4 bytes little endian buffer when size=4, endian=little', () => { @@ -143,7 +151,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt32LE(value, 0); - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 4 bytes big endian buffer when no size or endian is given', () => { @@ -153,7 +161,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.alloc(size); expectedBuffer.writeInt32BE(value, 0); - expect(utils.intToBuffer(value, size)).toEqual(expectedBuffer); + expect(intToBuffer(value, size)).toEqual(expectedBuffer); }); it('should convert a integer to a 8 bytes big endian buffer when size=8, endian=big', () => { @@ -163,7 +171,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.from('00cebcaa8d34153d', 'hex'); - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 8 bytes little endian buffer when size=8, endian=little', () => { @@ -173,7 +181,7 @@ describe('buffer', () => { const expectedBuffer = Buffer.from('3d15348daabcce00', 'hex'); - expect(utils.intToBuffer(value, size, endian)).toEqual(expectedBuffer); + expect(intToBuffer(value, size, endian)).toEqual(expectedBuffer); }); it('should convert a integer to a 8 bytes big endian buffer when size=8 and endian is not given', () => { @@ -182,7 +190,110 @@ describe('buffer', () => { const expectedBuffer = Buffer.from('00cebcaa8d34153d', 'hex'); - expect(utils.intToBuffer(value, size)).toEqual(expectedBuffer); + expect(intToBuffer(value, size)).toEqual(expectedBuffer); + }); + }); + + describe('hash onion', () => { + describe('#generateHashOnionSeed', () => { + it('should generate a random buffer', () => { + const seed1 = generateHashOnionSeed().toString('hex'); + const seed2 = generateHashOnionSeed().toString('hex'); + + expect(seed1).not.toEqual(seed2); + }); + + it('should generate a random buffer with 16 bytes', () => { + const seed = generateHashOnionSeed(); + expect(seed).toHaveLength(16); + }); + }); + + describe('#hashOnion', () => { + let seed: Buffer; + let hashOnionBuffers: ReadonlyArray; + + beforeEach(() => { + seed = generateHashOnionSeed(); + hashOnionBuffers = hashOnion(seed); + }); + + it('should return 1001 hash onion hashes checkpoints by default', () => { + expect(hashOnionBuffers).toHaveLength(1001); + }); + + it('should return hash onion hashes which includes seed as the last element', () => { + expect(hashOnionBuffers[1000]).toEqual(seed); + }); + + it('should be able to calculate the checkpoint from another checkpoint', () => { + const firstDistanceHashes = hashOnion(hashOnionBuffers[1].slice(), 1000, 1); + expect(firstDistanceHashes[0]).toEqual(hashOnionBuffers[0]); + expect(firstDistanceHashes[1000]).toEqual(hashOnionBuffers[1]); + }); + }); + }); + + describe('hash', () => { + describe('#hash', () => { + const defaultText = 'text123*'; + let arrayToHash: ReadonlyArray; + let defaultHash: Buffer; + + beforeEach(() => { + defaultHash = Buffer.from( + '7607d6792843d6003c12495b54e34517a508d2a8622526aff1884422c5478971', + 'hex', + ); + arrayToHash = [1, 2, 3]; + }); + + it('should generate a sha256 hash from a Buffer', () => { + const testBuffer = Buffer.from(defaultText); + const hash = hashFunction(testBuffer); + expect(hash).toEqual(defaultHash); + }); + + it('should generate a sha256 hash from a utf8 string', () => { + const hash = hashFunction(defaultText, 'utf8'); + expect(hash).toEqual(defaultHash); + }); + + it('should generate a sha256 hash from a hex string', () => { + const testHex = Buffer.from(defaultText).toString('hex'); + const hash = hashFunction(testHex, 'hex'); + expect(hash).toEqual(defaultHash); + }); + + it('should throw on unknown format when trying a string with format "utf32"', () => { + expect(hashFunction.bind(null, defaultText, 'utf32')).toThrow( + 'Unsupported string format. Currently only `hex` and `utf8` are supported.', + ); + }); + + it('should throw on unknown format when using an array', () => { + expect(hashFunction.bind(null, arrayToHash as any)).toThrow( + 'Unsupported data:1,2,3 and format:undefined. Currently only Buffers or hex and utf8 strings are supported.', + ); + }); + }); + + describe('#getNetworkIdentifier', () => { + const genesisBlockID = Buffer.from( + 'ed14889723f24ecc54871d058d98ce91ff2f973192075c0155ba2b7b70ad2511', + 'hex', + ); + const communityIdentifier = 'LISK'; + const expectedHash = Buffer.from( + '6f201e72e20571b93ed42470caa94af1ace79dc9930ab5bb144ddd5df5753e73', + 'hex', + ); + + it('should generate a sha256 hash from genesis block transaction root and community identifier', () => { + const networkIdentifier = getNetworkIdentifier(genesisBlockID, communityIdentifier); + + expect(networkIdentifier).toEqual(expectedHash); + }); }); }); }); diff --git a/elements/lisk-transaction-pool/test/unit/transaction_pool.spec.ts b/elements/lisk-transaction-pool/test/unit/transaction_pool.spec.ts index a8b53f55ec1..d4b7b071f15 100644 --- a/elements/lisk-transaction-pool/test/unit/transaction_pool.spec.ts +++ b/elements/lisk-transaction-pool/test/unit/transaction_pool.spec.ts @@ -13,7 +13,7 @@ * */ import { when } from 'jest-when'; -import { getAddressFromPublicKey, getRandomBytes } from '@liskhq/lisk-cryptography'; +import { address as cryptoAddress, utils } from '@liskhq/lisk-cryptography'; import { TransactionList } from '../../src/transaction_list'; import { TransactionPool } from '../../src/transaction_pool'; import { Transaction, Status, TransactionStatus } from '../../src/types'; @@ -189,24 +189,24 @@ describe('TransactionPool class', () => { await transactionPool.add(tx); } (transactionPool as any)._transactionList - .get(address.getAddressFromPublicKey(senderPublicKeys[0])) + .get(cryptoAddress.getAddressFromPublicKey(senderPublicKeys[0])) .promote([txs[0]]); (transactionPool as any)._transactionList - .get(address.getAddressFromPublicKey(senderPublicKeys[1])) + .get(cryptoAddress.getAddressFromPublicKey(senderPublicKeys[1])) .promote([txs[3]]); // Force to make it unprocessable (transactionPool['_transactionList'].get( - address.getAddressFromPublicKey(senderPublicKeys[2]), + cryptoAddress.getAddressFromPublicKey(senderPublicKeys[2]), ) as TransactionList)['_demoteAfter'](BigInt(0)); }); it('should return copy of processable transactions list', () => { const processableTransactions = transactionPool.getProcessableTransactions(); const transactionFromSender0 = processableTransactions.get( - address.getAddressFromPublicKey(senderPublicKeys[0]), + cryptoAddress.getAddressFromPublicKey(senderPublicKeys[0]), ); const transactionFromSender1 = processableTransactions.get( - address.getAddressFromPublicKey(senderPublicKeys[1]), + cryptoAddress.getAddressFromPublicKey(senderPublicKeys[1]), ); expect(transactionFromSender0).toHaveLength(1); @@ -214,27 +214,27 @@ describe('TransactionPool class', () => { expect(transactionFromSender1).toHaveLength(1); expect((transactionFromSender1 as Transaction[])[0].nonce.toString()).toEqual('1'); // Check if it is a copy - processableTransactions.delete(address.getAddressFromPublicKey(senderPublicKeys[0])); + processableTransactions.delete(cryptoAddress.getAddressFromPublicKey(senderPublicKeys[0])); (processableTransactions as any).get( - address.getAddressFromPublicKey(senderPublicKeys[1]), + cryptoAddress.getAddressFromPublicKey(senderPublicKeys[1]), )[0] = 'random thing'; expect( (transactionPool as any)._transactionList.get( - address.getAddressFromPublicKey(senderPublicKeys[0]), + cryptoAddress.getAddressFromPublicKey(senderPublicKeys[0]), ), ).not.toBeUndefined(); expect( transactionPool .getProcessableTransactions() - .get(address.getAddressFromPublicKey(senderPublicKeys[1])), + .get(cryptoAddress.getAddressFromPublicKey(senderPublicKeys[1])), ).toHaveLength(1); }); it('should not include the sender key if processable transactions are empty', () => { const processableTransactions = transactionPool.getProcessableTransactions(); const transactionFromSender2 = processableTransactions.get( - address.getAddressFromPublicKey(senderPublicKeys[2]), + cryptoAddress.getAddressFromPublicKey(senderPublicKeys[2]), ); expect(transactionFromSender2).toBeUndefined(); }); @@ -277,12 +277,12 @@ describe('TransactionPool class', () => { const originalTrxObj = transactionPool['_transactionList'] - .get(address.getAddressFromPublicKey(tx.senderPublicKey)) + .get(cryptoAddress.getAddressFromPublicKey(tx.senderPublicKey)) ?.get(BigInt(1)) ?? {}; expect(originalTrxObj).toEqual(tx); const trxSenderAddressList = transactionPool['_transactionList'].get( - address.getAddressFromPublicKey(tx.senderPublicKey), + cryptoAddress.getAddressFromPublicKey(tx.senderPublicKey), ); expect(trxSenderAddressList?.getProcessable()).toContain(originalTrxObj); }); @@ -303,12 +303,12 @@ describe('TransactionPool class', () => { const originalTrxObj = transactionPool['_transactionList'] - .get(address.getAddressFromPublicKey(tx.senderPublicKey)) + .get(cryptoAddress.getAddressFromPublicKey(tx.senderPublicKey)) ?.get(BigInt(1)) ?? {}; expect(originalTrxObj).toEqual(tx); const trxSenderAddressList = transactionPool['_transactionList'].get( - address.getAddressFromPublicKey(tx.senderPublicKey), + cryptoAddress.getAddressFromPublicKey(tx.senderPublicKey), ); expect(trxSenderAddressList?.getUnprocessable()).toContain(originalTrxObj); }); @@ -712,7 +712,7 @@ describe('TransactionPool class', () => { it('should return false when a tx id does not exist', () => { expect( transactionPool['_transactionList'] - .get(address.getAddressFromPublicKey(tx.senderPublicKey)) + .get(cryptoAddress.getAddressFromPublicKey(tx.senderPublicKey)) ?.get(tx.nonce), ).toEqual(tx); expect(transactionPool['_feePriorityQueue'].values).toContain(tx.id); @@ -733,7 +733,7 @@ describe('TransactionPool class', () => { it('should remove the transaction from _allTransactions, _transactionList and _feePriorityQueue', () => { expect( transactionPool['_transactionList'] - .get(address.getAddressFromPublicKey(tx.senderPublicKey)) + .get(cryptoAddress.getAddressFromPublicKey(tx.senderPublicKey)) ?.get(tx.nonce), ).toEqual(tx); expect(transactionPool['_feePriorityQueue'].values).toContain(tx.id); @@ -744,7 +744,7 @@ describe('TransactionPool class', () => { expect(transactionPool.getAll()).toHaveLength(1); expect( transactionPool['_transactionList'] - .get(address.getAddressFromPublicKey(tx.senderPublicKey)) + .get(cryptoAddress.getAddressFromPublicKey(tx.senderPublicKey)) ?.get(tx.nonce), ).toBeUndefined(); expect(transactionPool['_feePriorityQueue'].values).not.toContain(tx.id); @@ -755,7 +755,7 @@ describe('TransactionPool class', () => { transactionPool.remove(additionalTx); expect( transactionPool['_transactionList'].get( - address.getAddressFromPublicKey(tx.senderPublicKey), + cryptoAddress.getAddressFromPublicKey(tx.senderPublicKey), ), ).toBeUndefined(); }); diff --git a/elements/lisk-transaction-pool/test/utils/cryptography.ts b/elements/lisk-transaction-pool/test/utils/cryptography.ts index 7b4cb4e8d02..0531093235b 100644 --- a/elements/lisk-transaction-pool/test/utils/cryptography.ts +++ b/elements/lisk-transaction-pool/test/utils/cryptography.ts @@ -12,11 +12,11 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { getAddressAndPublicKeyFromPassphrase, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils, address } from '@liskhq/lisk-cryptography'; export const generateRandomPublicKeys = (amount = 1): Array => new Array(amount).fill(0).map(_ => { - const { publicKey } = getAddressAndPublicKeyFromPassphrase(Math.random().toString(16)); + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(Math.random().toString(16)); return publicKey; }); diff --git a/elements/lisk-transactions/test/fee.spec.ts b/elements/lisk-transactions/test/fee.spec.ts index f4d7a7eb961..b0791c09eb0 100644 --- a/elements/lisk-transactions/test/fee.spec.ts +++ b/elements/lisk-transactions/test/fee.spec.ts @@ -13,7 +13,7 @@ * */ -import { getAddressAndPublicKeyFromPassphrase, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils, address } from '@liskhq/lisk-cryptography'; import { computeMinFee, getBytes } from '../src'; describe('fee', () => { @@ -42,7 +42,7 @@ describe('fee', () => { }, }; const passphrase1 = 'trim elegant oven term access apple obtain error grain excite lawn neck'; - const { publicKey: publicKey1 } = getAddressAndPublicKeyFromPassphrase(passphrase1); + const { publicKey: publicKey1 } = address.getAddressAndPublicKeyFromPassphrase(passphrase1); const validTransaction = { moduleID: utils.intToBuffer(2, 4), commandID: utils.intToBuffer(0, 4), diff --git a/elements/lisk-transactions/test/sign.spec.ts b/elements/lisk-transactions/test/sign.spec.ts index 2688f358aa6..b856256a516 100644 --- a/elements/lisk-transactions/test/sign.spec.ts +++ b/elements/lisk-transactions/test/sign.spec.ts @@ -15,10 +15,9 @@ import { codec } from '@liskhq/lisk-codec'; import { - getAddressAndPublicKeyFromPassphrase, - getPrivateAndPublicKeyFromPassphrase, - intToBuffer, - signDataWithPrivateKey, + ed, + utils, + address, } from '@liskhq/lisk-cryptography'; import { getSigningBytes, @@ -102,10 +101,10 @@ describe('sign', () => { '2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b5d036a858ce89f844491762eb89e2bfbd50a4a0a0da658e4b2628b25b117ae09', 'hex', ); - const { publicKey: publicKey1 } = getAddressAndPublicKeyFromPassphrase(passphrase1); - const { publicKey: publicKey2 } = getAddressAndPublicKeyFromPassphrase(passphrase2); - const { publicKey: publicKey3 } = getAddressAndPublicKeyFromPassphrase(passphrase3); - const { publicKey: publicKey4 } = getAddressAndPublicKeyFromPassphrase(passphrase4); + const { publicKey: publicKey1 } = address.getAddressAndPublicKeyFromPassphrase(passphrase1); + const { publicKey: publicKey2 } = address.getAddressAndPublicKeyFromPassphrase(passphrase2); + const { publicKey: publicKey3 } = address.getAddressAndPublicKeyFromPassphrase(passphrase3); + const { publicKey: publicKey4 } = address.getAddressAndPublicKeyFromPassphrase(passphrase4); const keys = { mandatoryKeys: [publicKey1, publicKey2], optionalKeys: [publicKey3, publicKey4], @@ -527,9 +526,9 @@ describe('sign', () => { }); it('should add sender and mandatory public key signatures in right order for multisignature registration trx', () => { - const account1 = getPrivateAndPublicKeyFromPassphrase(passphrase1); - const account2 = getPrivateAndPublicKeyFromPassphrase(passphrase2); - const account3 = getPrivateAndPublicKeyFromPassphrase(passphrase3); + const account1 = address.getPrivateAndPublicKeyFromPassphrase(passphrase1); + const account2 = address.getPrivateAndPublicKeyFromPassphrase(passphrase2); + const account3 = address.getPrivateAndPublicKeyFromPassphrase(passphrase3); const mandatoryKeys = [account1.publicKey, account2.publicKey]; const optionalKeys = [account3.publicKey]; @@ -575,13 +574,13 @@ describe('sign', () => { getSigningBytes(signedTransaction, multisigRegParams), ]); - const signature = signDataWithPrivateKey( + const signature = ed.signDataWithPrivateKey( TAG_TRANSACTION, networkIdentifier, transactionWithNetworkIdentifierBytes, account1.privateKey, ); - const signatureNonSender = signDataWithPrivateKey( + const signatureNonSender = ed.signDataWithPrivateKey( TAG_TRANSACTION, networkIdentifier, transactionWithNetworkIdentifierBytesNonSender, @@ -594,8 +593,8 @@ describe('sign', () => { }); it('should match the signatures of the mandatory keys in right order for transfer trx', () => { - const account1 = getPrivateAndPublicKeyFromPassphrase(passphrase1); - const account2 = getPrivateAndPublicKeyFromPassphrase(passphrase2); + const account1 = address.getPrivateAndPublicKeyFromPassphrase(passphrase1); + const account2 = address.getPrivateAndPublicKeyFromPassphrase(passphrase2); // Sender public key of account1 const transaction = { moduleID: utils.intToBuffer(2, 4), @@ -625,7 +624,7 @@ describe('sign', () => { getSigningBytes(transactionObject, validParamsSchema), ]); - const signature = signDataWithPrivateKey( + const signature = ed.signDataWithPrivateKey( TAG_TRANSACTION, networkIdentifier, transactionWithNetworkIdentifierBytes, @@ -646,7 +645,7 @@ describe('sign', () => { getSigningBytes(signedTransaction, validParamsSchema), ]); - const signatureMandatoryAccount = signDataWithPrivateKey( + const signatureMandatoryAccount = ed.signDataWithPrivateKey( TAG_TRANSACTION, networkIdentifier, transactionMandatoryKeyWithNetworkIdentifierBytes, diff --git a/elements/lisk-tree/test/sparse_merkle_tree/utils.spec.ts b/elements/lisk-tree/test/sparse_merkle_tree/utils.spec.ts index 9082afd4fc1..de8f9e1a2af 100644 --- a/elements/lisk-tree/test/sparse_merkle_tree/utils.spec.ts +++ b/elements/lisk-tree/test/sparse_merkle_tree/utils.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { sortByBitmapAndKey, binaryStringToBuffer, diff --git a/framework/test/unit/abi_handler/abi_handler.spec.ts b/framework/test/unit/abi_handler/abi_handler.spec.ts index 5e4e873dea2..bcfb0acd23e 100644 --- a/framework/test/unit/abi_handler/abi_handler.spec.ts +++ b/framework/test/unit/abi_handler/abi_handler.spec.ts @@ -15,7 +15,7 @@ import * as os from 'os'; import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase } from '@liskhq/lisk-db'; import { BaseModule, TokenModule } from '../../../src'; import { ABIHandler } from '../../../src/abi_handler/abi_handler'; diff --git a/framework/test/unit/engine/endpoint/txpool.spec.ts b/framework/test/unit/engine/endpoint/txpool.spec.ts index 5f068a9cba1..9f8f13c0c99 100644 --- a/framework/test/unit/engine/endpoint/txpool.spec.ts +++ b/framework/test/unit/engine/endpoint/txpool.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Chain, Transaction, Event } from '@liskhq/lisk-chain'; import { TransactionPool } from '@liskhq/lisk-transaction-pool'; import { LiskValidationError } from '@liskhq/lisk-validator'; diff --git a/framework/test/unit/engine/generator/broadcaster.spec.ts b/framework/test/unit/engine/generator/broadcaster.spec.ts index 4c1757d865f..79c3b3d2807 100644 --- a/framework/test/unit/engine/generator/broadcaster.spec.ts +++ b/framework/test/unit/engine/generator/broadcaster.spec.ts @@ -14,7 +14,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { TransactionPool } from '@liskhq/lisk-transaction-pool'; import { Broadcaster } from '../../../../src/engine/generator/broadcaster'; import { postTransactionsAnnouncementSchema } from '../../../../src/engine/generator/schemas'; diff --git a/framework/test/unit/modules/dpos_v2/commands/delegate_registration.spec.ts b/framework/test/unit/modules/dpos_v2/commands/delegate_registration.spec.ts index 53634929c92..3eb50b0824a 100644 --- a/framework/test/unit/modules/dpos_v2/commands/delegate_registration.spec.ts +++ b/framework/test/unit/modules/dpos_v2/commands/delegate_registration.spec.ts @@ -14,7 +14,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import * as testing from '../../../../../src/testing'; import { DelegateRegistrationCommand } from '../../../../../src/modules/dpos_v2/commands/delegate_registration'; import { diff --git a/framework/test/unit/modules/dpos_v2/commands/unlock.spec.ts b/framework/test/unit/modules/dpos_v2/commands/unlock.spec.ts index ce6523acff1..56d3eff653c 100644 --- a/framework/test/unit/modules/dpos_v2/commands/unlock.spec.ts +++ b/framework/test/unit/modules/dpos_v2/commands/unlock.spec.ts @@ -13,7 +13,7 @@ */ import { BlockHeader, Transaction } from '@liskhq/lisk-chain'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import * as testing from '../../../../../src/testing'; import { UnlockCommand } from '../../../../../src/modules/dpos_v2/commands/unlock'; import { diff --git a/framework/test/unit/modules/dpos_v2/module.spec.ts b/framework/test/unit/modules/dpos_v2/module.spec.ts index bb1099c084f..5e05d469cdc 100644 --- a/framework/test/unit/modules/dpos_v2/module.spec.ts +++ b/framework/test/unit/modules/dpos_v2/module.spec.ts @@ -13,7 +13,7 @@ */ import { BlockAssets } from '@liskhq/lisk-chain'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { when } from 'jest-when'; import { codec } from '@liskhq/lisk-codec'; import { GenesisConfig } from '../../../../src/types'; diff --git a/framework/test/unit/modules/dpos_v2/update_generator_key.spec.ts b/framework/test/unit/modules/dpos_v2/update_generator_key.spec.ts index 83fe2c197c0..2ec33d1a716 100644 --- a/framework/test/unit/modules/dpos_v2/update_generator_key.spec.ts +++ b/framework/test/unit/modules/dpos_v2/update_generator_key.spec.ts @@ -14,7 +14,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import * as testing from '../../../../src/testing'; import { UpdateGeneratorKeyCommand } from '../../../../src/modules/dpos_v2/commands/update_generator_key'; import { diff --git a/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts b/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts index c77c11f80d9..92562b72629 100644 --- a/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { MainchainCCChannelTerminatedCommand } from '../../../../../../src/modules/interoperability/mainchain/cc_commands/channel_terminated'; import { MainchainInteroperabilityStore } from '../../../../../../src/modules/interoperability/mainchain/store'; import { CCCommandExecuteContext } from '../../../../../../src/modules/interoperability/types'; diff --git a/framework/test/unit/modules/interoperability/mainchain/cc_commands/registration.spec.ts b/framework/test/unit/modules/interoperability/mainchain/cc_commands/registration.spec.ts index 932efa6f61e..218e7dda903 100644 --- a/framework/test/unit/modules/interoperability/mainchain/cc_commands/registration.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/cc_commands/registration.spec.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { MainchainCCRegistrationCommand } from '../../../../../../src/modules/interoperability/mainchain/cc_commands/registration'; import { MainchainInteroperabilityStore } from '../../../../../../src/modules/interoperability/mainchain/store'; import { registrationCCMParamsSchema } from '../../../../../../src/modules/interoperability/schemas'; diff --git a/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts b/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts index e9e6eae633a..a2467c2170b 100644 --- a/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { MAINCHAIN_ID_BUFFER } from '../../../../../../src/modules/interoperability/constants'; import { MainchainCCSidechainTerminatedCommand } from '../../../../../../src/modules/interoperability/mainchain/cc_commands/sidechain_terminated'; import { MainchainInteroperabilityStore } from '../../../../../../src/modules/interoperability/mainchain/store'; diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery.spec.ts index 66141a15232..a9678bac67e 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery.spec.ts @@ -14,7 +14,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { sparseMerkleTree } from '@liskhq/lisk-tree'; import { CommandExecuteContext, CommandVerifyContext } from '../../../../../../src'; import { BaseCCCommand } from '../../../../../../src/modules/interoperability/base_cc_command'; diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery_init.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery_init.spec.ts index b05d17c1dbf..59dd8b4b89c 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery_init.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/state_recovery_init.spec.ts @@ -1,6 +1,6 @@ import { when } from 'jest-when'; import { Transaction } from '@liskhq/lisk-chain'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { sparseMerkleTree } from '@liskhq/lisk-tree'; import { diff --git a/framework/test/unit/modules/interoperability/mainchain/store.spec.ts b/framework/test/unit/modules/interoperability/mainchain/store.spec.ts index 8c3e2d01fca..858c711028d 100644 --- a/framework/test/unit/modules/interoperability/mainchain/store.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/store.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { when } from 'jest-when'; import { testing } from '../../../../../src'; import { diff --git a/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts b/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts index 1ba07e22efb..f77843860bd 100644 --- a/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { SidechainCCChannelTerminatedCommand } from '../../../../../../src/modules/interoperability/sidechain/cc_commands/channel_terminated'; import { SidechainInteroperabilityStore } from '../../../../../../src/modules/interoperability/sidechain/store'; import { CCCommandExecuteContext } from '../../../../../../src/modules/interoperability/types'; diff --git a/framework/test/unit/modules/interoperability/sidechain/cc_commands/registration.spec.ts b/framework/test/unit/modules/interoperability/sidechain/cc_commands/registration.spec.ts index f4f33819e20..e89f71bf8cd 100644 --- a/framework/test/unit/modules/interoperability/sidechain/cc_commands/registration.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/cc_commands/registration.spec.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { SidechainCCRegistrationCommand } from '../../../../../../src/modules/interoperability/sidechain/cc_commands/registration'; import { registrationCCMParamsSchema } from '../../../../../../src/modules/interoperability/schemas'; import { SidechainInteroperabilityStore } from '../../../../../../src/modules/interoperability/sidechain/store'; diff --git a/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts b/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts index a36d51926d5..187f06c65a7 100644 --- a/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { MAINCHAIN_ID_BUFFER } from '../../../../../../src/modules/interoperability/constants'; import { SidechainCCSidechainTerminatedCommand } from '../../../../../../src/modules/interoperability/sidechain/cc_commands/sidechain_terminated'; import { SidechainInteroperabilityStore } from '../../../../../../src/modules/interoperability/sidechain/store'; diff --git a/framework/test/unit/modules/interoperability/sidechain/commands/message_recovery.spec.ts b/framework/test/unit/modules/interoperability/sidechain/commands/message_recovery.spec.ts index aad08d438a9..71cbe1327f8 100644 --- a/framework/test/unit/modules/interoperability/sidechain/commands/message_recovery.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/commands/message_recovery.spec.ts @@ -13,7 +13,7 @@ */ import { Transaction } from '@liskhq/lisk-chain'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { regularMerkleTree } from '@liskhq/lisk-tree'; import { when } from 'jest-when'; diff --git a/framework/test/unit/modules/interoperability/sidechain/store.spec.ts b/framework/test/unit/modules/interoperability/sidechain/store.spec.ts index 87a0a1d322c..8f24126ae94 100644 --- a/framework/test/unit/modules/interoperability/sidechain/store.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/store.spec.ts @@ -13,7 +13,7 @@ */ import { when } from 'jest-when'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { MAINCHAIN_ID, MAX_CCM_SIZE, diff --git a/framework/test/unit/modules/interoperability/store.spec.ts b/framework/test/unit/modules/interoperability/store.spec.ts index 0ebd5332f61..21f96845c4b 100644 --- a/framework/test/unit/modules/interoperability/store.spec.ts +++ b/framework/test/unit/modules/interoperability/store.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { regularMerkleTree } from '@liskhq/lisk-tree'; import { when } from 'jest-when'; import { diff --git a/framework/test/unit/modules/token/api.spec.ts b/framework/test/unit/modules/token/api.spec.ts index 277319667d5..e80dd5d03b1 100644 --- a/framework/test/unit/modules/token/api.spec.ts +++ b/framework/test/unit/modules/token/api.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { TokenAPI } from '../../../../src/modules/token'; import { CCM_STATUS_OK, diff --git a/framework/test/unit/modules/token/cc_commands/cc_forward.spec.ts b/framework/test/unit/modules/token/cc_commands/cc_forward.spec.ts index c4598f87f13..1398967f1cf 100644 --- a/framework/test/unit/modules/token/cc_commands/cc_forward.spec.ts +++ b/framework/test/unit/modules/token/cc_commands/cc_forward.spec.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { TokenAPI } from '../../../../../src/modules/token/api'; import { CCForwardCommand } from '../../../../../src/modules/token/cc_commands/cc_forward'; import { diff --git a/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts b/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts index 972cf133cb2..88debf36848 100644 --- a/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts +++ b/framework/test/unit/modules/token/cc_commands/cc_transfer.spec.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { TokenAPI } from '../../../../../src/modules/token/api'; import { CCTransferCommand } from '../../../../../src/modules/token/cc_commands/cc_transfer'; import { diff --git a/framework/test/unit/modules/token/endpoint.spec.ts b/framework/test/unit/modules/token/endpoint.spec.ts index a8db5c5e719..5a43e04f36c 100644 --- a/framework/test/unit/modules/token/endpoint.spec.ts +++ b/framework/test/unit/modules/token/endpoint.spec.ts @@ -11,7 +11,7 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { TokenAPI } from '../../../../src/modules/token'; import { CHAIN_ID_LENGTH, diff --git a/framework/test/unit/modules/token/interoperable_api.spec.ts b/framework/test/unit/modules/token/interoperable_api.spec.ts index 93fab3d788a..e2342e3b4d2 100644 --- a/framework/test/unit/modules/token/interoperable_api.spec.ts +++ b/framework/test/unit/modules/token/interoperable_api.spec.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { TokenAPI } from '../../../../src/modules/token'; import { CCM_STATUS_OK, diff --git a/framework/test/unit/modules/validators/api.spec.ts b/framework/test/unit/modules/validators/api.spec.ts index cf3064ad07d..dd8c61a2457 100644 --- a/framework/test/unit/modules/validators/api.spec.ts +++ b/framework/test/unit/modules/validators/api.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { ValidatorsAPI, ValidatorsModule } from '../../../../src/modules/validators'; import { MODULE_ID_VALIDATORS, diff --git a/framework/test/unit/state_machine/event_queue.spec.ts b/framework/test/unit/state_machine/event_queue.spec.ts index 60d8b11edc0..16aabe9e7c2 100644 --- a/framework/test/unit/state_machine/event_queue.spec.ts +++ b/framework/test/unit/state_machine/event_queue.spec.ts @@ -13,7 +13,7 @@ */ import { EVENT_MAX_EVENT_SIZE_BYTES } from '@liskhq/lisk-chain'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { EventQueue } from '../../../src/state_machine/event_queue'; describe('EventQueue', () => { diff --git a/framework/test/unit/state_machine/state_machine.spec.ts b/framework/test/unit/state_machine/state_machine.spec.ts index e2280e289b3..c0787b5b3b7 100644 --- a/framework/test/unit/state_machine/state_machine.spec.ts +++ b/framework/test/unit/state_machine/state_machine.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { Transaction, BlockAssets } from '@liskhq/lisk-chain'; -import { getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Logger } from '../../../src/logger'; import { BlockContext } from '../../../src/state_machine/block_context'; import { EventQueue } from '../../../src/state_machine/event_queue'; From 80156927a53bb03f5baf538b37beed63eca57bdb Mon Sep 17 00:00:00 2001 From: shuse2 Date: Mon, 18 Jul 2022 17:37:15 +0200 Subject: [PATCH 5/6] :recycle: Update reference --- .../bootstrapping/commands/account/create.ts | 2 +- commander/src/utils/commons.ts | 2 +- commander/src/utils/genesis_creation.ts | 6 +- .../commands/account/create.spec.ts | 30 +++--- .../commands/blskey/create.spec.ts | 20 ++-- .../commands/forging/config.spec.ts | 14 +-- .../bootstrapping/commands/hash-onion.spec.ts | 2 +- .../commands/passphrase/decrypt.spec.ts | 12 +-- .../commands/passphrase/encrypt.spec.ts | 22 ++--- .../test/commands/message/encrypt.spec.ts | 2 +- commander/test/helpers/account.ts | 2 +- commander/test/helpers/transactions.ts | 2 +- elements/lisk-chain/test/utils/block.ts | 7 +- .../test/lisk-cryptography/address.spec.ts | 34 ------- .../test/lisk-cryptography/bls.spec.ts | 4 +- .../test/lisk-cryptography/ed.spec.ts | 43 +++++++-- .../test/lisk-cryptography/encrypt.spec.ts | 14 +-- .../test/lisk-cryptography/utils.spec.ts | 20 ++-- elements/lisk-cryptography/benchmark/nacl.js | 4 +- elements/lisk-cryptography/src/address.ts | 11 +-- elements/lisk-cryptography/src/ed.ts | 2 + elements/lisk-cryptography/src/encrypt.ts | 2 +- .../lisk-cryptography/src/legacy_address.ts | 2 +- .../lisk-cryptography/test/address.spec.ts | 35 ------- elements/lisk-cryptography/test/ed.spec.ts | 35 +++++++ elements/lisk-transactions/test/sign.spec.ts | 16 ++-- .../test/utils/accounts.ts | 2 +- .../test/unit/blocks.spec.ts | 8 +- .../test/unit/forks.spec.ts | 8 +- framework/src/testing/block_processing_env.ts | 4 +- framework/src/testing/create_transaction.ts | 4 +- framework/test/fixtures/blocks.ts | 9 +- .../banning/invalid_block_property.spec.ts | 2 +- .../test/functional/network/blocks.spec.ts | 2 +- .../functional/network/transactions.spec.ts | 2 +- .../node/generator/transaction_pool.spec.ts | 4 +- .../block_process/process_block.spec.ts | 8 +- .../report_misbehavior_transaction.spec.ts | 10 +- .../testing/block_processing_env.spec.ts | 11 +-- .../commit_list.spec.ts | 2 +- .../commit_pool.spec.ts | 28 +++--- .../certificate_generation/utils.spec.ts | 28 +++--- .../unit/engine/consensus/consensus.spec.ts | 23 ++--- .../engine/consensus/network_endpoint.spec.ts | 2 +- .../block_synchronization_mechanism.spec.ts | 2 +- .../fast_chain_switching_mechanism.spec.ts | 2 +- .../test/unit/engine/endpoint/chain.spec.ts | 2 +- .../test/unit/engine/endpoint/system.spec.ts | 2 +- .../unit/engine/generator/endpoint.spec.ts | 2 +- .../unit/engine/generator/generator.spec.ts | 31 +++--- .../unit/engine/generator/strategies.spec.ts | 2 +- .../test/unit/engine/network/network.spec.ts | 2 +- framework/test/unit/modules/auth/api.spec.ts | 2 +- .../unit/modules/auth/auth_module.spec.ts | 95 +++++++++---------- .../test/unit/modules/auth/endpoint.spec.ts | 32 +++---- .../auth/register_multisignature.spec.ts | 2 +- framework/test/unit/modules/bft/api.spec.ts | 77 ++++----------- .../test/unit/modules/bft/bft_params.spec.ts | 18 ++-- .../unit/modules/bft/bft_processing.spec.ts | 9 +- .../test/unit/modules/bft/bft_votes.spec.ts | 12 +-- framework/test/unit/modules/bft/utils.spec.ts | 2 +- .../test/unit/modules/dpos_v2/api.spec.ts | 2 +- .../unit/modules/dpos_v2/commands/pom.spec.ts | 9 +- .../modules/dpos_v2/commands/vote.spec.ts | 2 +- .../unit/modules/dpos_v2/endpoint.spec.ts | 2 +- .../dpos_v2/genesis_block_test_data.ts | 18 ++-- .../test/unit/modules/dpos_v2/module.spec.ts | 24 ++--- .../test/unit/modules/fee/fee_module.spec.ts | 2 +- .../cc_commands/channel_terminated.spec.ts | 2 +- .../cc_commands/sidechain_terminated.spec.ts | 2 +- .../mainchain/commands/cc_update.spec.ts | 2 +- .../commands/message_recovery.spec.ts | 2 +- .../commands/sidechain_registration.spec.ts | 2 +- .../mainchain/endpoint.spec.ts | 6 +- .../cc_commands/channel_terminated.spec.ts | 2 +- .../cc_commands/sidechain_terminated.spec.ts | 2 +- .../sidechain/commands/cc_update.spec.ts | 2 +- .../commands/mainchain_registration.spec.ts | 5 +- .../sidechain/endpoint.spec.ts | 6 +- .../modules/interoperability/utils.spec.ts | 12 +-- .../test/unit/modules/random/api.spec.ts | 22 ++--- .../test/unit/modules/random/endpoint.spec.ts | 8 +- .../unit/modules/random/random_module.spec.ts | 31 ++++-- framework/test/unit/modules/token/api.spec.ts | 12 +-- .../modules/token/commands/transfer.spec.ts | 6 +- .../token/init_genesis_state_fixture.ts | 2 +- .../test/unit/modules/validators/api.spec.ts | 2 +- .../unit/modules/validators/endpoint.spec.ts | 2 +- .../unit/state_machine/event_queue.spec.ts | 12 +-- .../test/unit/testing/create_block.spec.ts | 10 +- framework/test/utils/mocks/account.ts | 18 ++-- framework/test/utils/mocks/endpoint.ts | 2 +- framework/test/utils/mocks/transaction.ts | 33 +++---- .../generators/address_generation/index.js | 2 +- .../dpos_delegate_shuffling/index.js | 2 +- .../sample_generator.js | 4 +- .../dpos_forger_selection/sample_generator.js | 4 +- .../dpos_random_seed_generation/index.js | 2 +- .../multisignature_registration/index.js | 4 +- .../proof_of_misbehavior_transaction/index.js | 13 +-- .../index.js | 4 +- 101 files changed, 489 insertions(+), 606 deletions(-) diff --git a/commander/src/bootstrapping/commands/account/create.ts b/commander/src/bootstrapping/commands/account/create.ts index ee640eae7b9..b6bc7021a62 100644 --- a/commander/src/bootstrapping/commands/account/create.ts +++ b/commander/src/bootstrapping/commands/account/create.ts @@ -30,7 +30,7 @@ interface AccountInfo { const createAccount = (prefix: string): AccountInfo => { const generatedPassphrase = passphrase.Mnemonic.generateMnemonic(); - const { privateKey, publicKey } = cryptography.address.getKeys(generatedPassphrase); + const { privateKey, publicKey } = cryptography.ed.getKeys(generatedPassphrase); const blsPrivateKey = cryptography.bls.generatePrivateKey( Buffer.from(generatedPassphrase, 'utf-8'), ); diff --git a/commander/src/utils/commons.ts b/commander/src/utils/commons.ts index 58a7ed0ac7f..1ef6ee24948 100644 --- a/commander/src/utils/commons.ts +++ b/commander/src/utils/commons.ts @@ -42,7 +42,7 @@ export const encryptPassphrase = async ( return outputPublicKey ? { encryptedPassphrase, - publicKey: cryptography.address.getKeys(passphrase).publicKey.toString('hex'), + publicKey: cryptography.ed.getKeys(passphrase).publicKey.toString('hex'), } : { encryptedPassphrase }; }; diff --git a/commander/src/utils/genesis_creation.ts b/commander/src/utils/genesis_creation.ts index cfe381f8240..6ad0236f504 100644 --- a/commander/src/utils/genesis_creation.ts +++ b/commander/src/utils/genesis_creation.ts @@ -15,7 +15,7 @@ */ import { Mnemonic } from '@liskhq/lisk-passphrase'; import { Schema } from '@liskhq/lisk-codec'; -import { bls, address, utils } from '@liskhq/lisk-cryptography'; +import { bls, address, utils, ed } from '@liskhq/lisk-cryptography'; import { dposGenesisStoreSchema, DPoSModule, @@ -65,7 +65,7 @@ export const generateGenesisBlockDefaultDPoSAssets = (input: GenesisBlockDefault const accountList = []; for (let i = 0; i < input.numberOfAccounts; i += 1) { const passphrase = Mnemonic.generateMnemonic(256); - const keys = address.getKeys(passphrase); + const keys = ed.getKeys(passphrase); accountList.push({ publicKey: keys.publicKey, privateKey: keys.privateKey, @@ -77,7 +77,7 @@ export const generateGenesisBlockDefaultDPoSAssets = (input: GenesisBlockDefault const validatorList = []; for (let i = 0; i < input.numberOfValidators; i += 1) { const passphrase = Mnemonic.generateMnemonic(256); - const keys = address.getKeys(passphrase); + const keys = ed.getKeys(passphrase); const blsPrivateKey = bls.generatePrivateKey(Buffer.from(passphrase, 'utf-8')); const blsPublicKey = bls.getPublicKeyFromPrivateKey(blsPrivateKey); const blsPoP = bls.popProve(blsPrivateKey); diff --git a/commander/test/bootstrapping/commands/account/create.spec.ts b/commander/test/bootstrapping/commands/account/create.spec.ts index a6ae951b818..43552110a15 100644 --- a/commander/test/bootstrapping/commands/account/create.spec.ts +++ b/commander/test/bootstrapping/commands/account/create.spec.ts @@ -25,8 +25,8 @@ describe('account:create', () => { 'lab mirror fetch tuna village sell sphere truly excite manual planet capable'; const secondDefaultMnemonic = 'alone cabin buffalo blast region upper jealous basket brush put answer twice'; - const blsPrivateKey = cryptography.generatePrivateKey(Buffer.from(defaultMnemonic, 'utf-8')); - const secondBlsPrivateKey = cryptography.generatePrivateKey( + const blsPrivateKey = cryptography.bls.generatePrivateKey(Buffer.from(defaultMnemonic, 'utf-8')); + const secondBlsPrivateKey = cryptography.bls.generatePrivateKey( Buffer.from(secondDefaultMnemonic, 'utf-8'), ); let results: any; @@ -47,12 +47,12 @@ describe('account:create', () => { await CreateCommand.run([], config); expect(JSON.parse(results[0])).toEqual([ { - publicKey: cryptography.utils.getKeys(defaultMnemonic).publicKey.toString('hex'), - privateKey: cryptography.utils.getKeys(defaultMnemonic).privateKey.toString('hex'), - blsPublicKey: cryptography.ed.getPublicKeyFromPrivateKey(blsPrivateKey).toString('hex'), + publicKey: cryptography.ed.getKeys(defaultMnemonic).publicKey.toString('hex'), + privateKey: cryptography.ed.getKeys(defaultMnemonic).privateKey.toString('hex'), + blsPublicKey: cryptography.bls.getPublicKeyFromPrivateKey(blsPrivateKey).toString('hex'), blsPrivateKey: blsPrivateKey.toString('hex'), address: cryptography.address.getLisk32AddressFromPublicKey( - cryptography.utils.getKeys(defaultMnemonic).publicKey, + cryptography.ed.getKeys(defaultMnemonic).publicKey, 'lsk', ), binaryAddress: cryptography.address @@ -70,12 +70,12 @@ describe('account:create', () => { await CreateCommand.run(['--count', defaultNumber.toString()], config); const result = [ { - publicKey: cryptography.utils.getKeys(defaultMnemonic).publicKey.toString('hex'), - privateKey: cryptography.utils.getKeys(defaultMnemonic).privateKey.toString('hex'), - blsPublicKey: cryptography.ed.getPublicKeyFromPrivateKey(blsPrivateKey).toString('hex'), + publicKey: cryptography.ed.getKeys(defaultMnemonic).publicKey.toString('hex'), + privateKey: cryptography.ed.getKeys(defaultMnemonic).privateKey.toString('hex'), + blsPublicKey: cryptography.bls.getPublicKeyFromPrivateKey(blsPrivateKey).toString('hex'), blsPrivateKey: blsPrivateKey.toString('hex'), address: cryptography.address.getLisk32AddressFromPublicKey( - cryptography.utils.getKeys(defaultMnemonic).publicKey, + cryptography.ed.getKeys(defaultMnemonic).publicKey, 'lsk', ), binaryAddress: cryptography.address @@ -84,17 +84,17 @@ describe('account:create', () => { passphrase: defaultMnemonic, }, { - publicKey: cryptography.utils.getKeys(secondDefaultMnemonic).publicKey.toString('hex'), - privateKey: cryptography.utils.getKeys(secondDefaultMnemonic).privateKey.toString('hex'), - blsPublicKey: cryptography + publicKey: cryptography.ed.getKeys(secondDefaultMnemonic).publicKey.toString('hex'), + privateKey: cryptography.ed.getKeys(secondDefaultMnemonic).privateKey.toString('hex'), + blsPublicKey: cryptography.bls .getPublicKeyFromPrivateKey(secondBlsPrivateKey) .toString('hex'), blsPrivateKey: secondBlsPrivateKey.toString('hex'), address: cryptography.address.getLisk32AddressFromPublicKey( - cryptography.utils.getKeys(secondDefaultMnemonic).publicKey, + cryptography.ed.getKeys(secondDefaultMnemonic).publicKey, 'lsk', ), - binaryAddress: cryptography + binaryAddress: cryptography.address .getAddressFromPassphrase(secondDefaultMnemonic) .toString('hex'), passphrase: secondDefaultMnemonic, diff --git a/commander/test/bootstrapping/commands/blskey/create.spec.ts b/commander/test/bootstrapping/commands/blskey/create.spec.ts index d82e2ea6ade..9c411050961 100644 --- a/commander/test/bootstrapping/commands/blskey/create.spec.ts +++ b/commander/test/bootstrapping/commands/blskey/create.spec.ts @@ -27,10 +27,10 @@ jest.mock('@liskhq/lisk-cryptography', () => ({ describe('passphrase:encrypt', () => { const defaultPassphrase = 'enemy pill squeeze gold spoil aisle awake thumb congress false box wagon'; - const defaultBlsPrivateKey = cryptography.generatePrivateKey( + const defaultBlsPrivateKey = cryptography.bls.generatePrivateKey( Buffer.from(defaultPassphrase, 'utf-8'), ); - const defaultBlsPublicKey = cryptography.ed.getPublicKeyFromPrivateKey(defaultBlsPrivateKey); + const defaultBlsPublicKey = cryptography.bls.getPublicKeyFromPrivateKey(defaultBlsPrivateKey); const consoleWarnSpy = jest.spyOn(console, 'warn'); let stdout: string[]; @@ -44,8 +44,8 @@ describe('passphrase:encrypt', () => { jest.spyOn(process.stdout, 'write').mockImplementation(val => stdout.push(val as string) > -1); jest.spyOn(process.stderr, 'write').mockImplementation(val => stderr.push(val as string) > -1); jest.spyOn(CreateCommand.prototype, 'printJSON').mockReturnValue(); - jest.spyOn(cryptography, 'generatePrivateKey'); - jest.spyOn(cryptography, 'getPublicKeyFromPrivateKey'); + jest.spyOn(cryptography.bls, 'generatePrivateKey'); + jest.spyOn(cryptography.bls, 'getPublicKeyFromPrivateKey'); jest.spyOn(readerUtils, 'getPassphraseFromPrompt').mockImplementation(async (name?: string) => { if (name === 'passphrase') { return defaultPassphrase; @@ -57,10 +57,12 @@ describe('passphrase:encrypt', () => { describe('blskey:create', () => { it('should create valid bls keys', async () => { await CreateCommand.run([], config); - expect(cryptography.generatePrivateKey).toHaveBeenCalledWith( + expect(cryptography.bls.generatePrivateKey).toHaveBeenCalledWith( Buffer.from(defaultPassphrase, 'utf-8'), ); - expect(cryptography.ed.getPublicKeyFromPrivateKey).toHaveBeenCalledWith(defaultBlsPrivateKey); + expect(cryptography.bls.getPublicKeyFromPrivateKey).toHaveBeenCalledWith( + defaultBlsPrivateKey, + ); expect(readerUtils.getPassphraseFromPrompt).toHaveBeenCalledWith('passphrase', true); expect(CreateCommand.prototype.printJSON).toHaveBeenCalledWith( @@ -80,10 +82,12 @@ describe('passphrase:encrypt', () => { ['--passphrase=enemy pill squeeze gold spoil aisle awake thumb congress false box wagon'], config, ); - expect(cryptography.generatePrivateKey).toHaveBeenCalledWith( + expect(cryptography.bls.generatePrivateKey).toHaveBeenCalledWith( Buffer.from(defaultPassphrase, 'utf-8'), ); - expect(cryptography.ed.getPublicKeyFromPrivateKey).toHaveBeenCalledWith(defaultBlsPrivateKey); + expect(cryptography.bls.getPublicKeyFromPrivateKey).toHaveBeenCalledWith( + defaultBlsPrivateKey, + ); expect(readerUtils.getPassphraseFromPrompt).not.toHaveBeenCalledWith('passphrase', true); expect(CreateCommand.prototype.printJSON).toHaveBeenCalledWith( diff --git a/commander/test/bootstrapping/commands/forging/config.spec.ts b/commander/test/bootstrapping/commands/forging/config.spec.ts index 4a7607246c0..2a6d3c7bad1 100644 --- a/commander/test/bootstrapping/commands/forging/config.spec.ts +++ b/commander/test/bootstrapping/commands/forging/config.spec.ts @@ -69,14 +69,14 @@ describe('forging:config command', () => { jest.spyOn(process.stdout, 'write').mockImplementation(val => stdout.push(val as string) > -1); jest.spyOn(process.stderr, 'write').mockImplementation(val => stderr.push(val as string) > -1); jest.spyOn(ConfigCommand.prototype, 'printJSON').mockReturnValue(); - jest.spyOn(cryptography, 'getKeys').mockReturnValue(defaultKeys as never); + jest.spyOn(cryptography.ed, 'getKeys').mockReturnValue(defaultKeys as never); jest.spyOn(fs, 'ensureDirSync').mockReturnValue(); jest.spyOn(fs, 'writeJSONSync').mockReturnValue(); jest - .spyOn(cryptography, 'encryptPassphraseWithPassword') + .spyOn(cryptography.encrypt, 'encryptPassphraseWithPassword') .mockReturnValue(encryptedPassphraseObject as any); jest - .spyOn(cryptography, 'stringifyEncryptedPassphrase') + .spyOn(cryptography.encrypt, 'stringifyEncryptedPassphrase') .mockReturnValue(encryptedPassphraseString); jest.spyOn(readerUtils, 'getPassphraseFromPrompt').mockImplementation(async (name?: string) => { if (name === 'passphrase') { @@ -96,11 +96,11 @@ describe('forging:config command', () => { describe('generate forging config and print', () => { it('should encrypt passphrase and with default hash-onions', async () => { await ConfigCommand.run(['--count=2', '--distance=1', '--pretty'], config); - expect(cryptography.encryptPassphraseWithPassword).toHaveBeenCalledWith( + expect(cryptography.encrypt.encryptPassphraseWithPassword).toHaveBeenCalledWith( defaultInputs.passphrase, defaultInputs.password, ); - expect(cryptography.stringifyEncryptedPassphrase).toHaveBeenCalledWith( + expect(cryptography.encrypt.stringifyEncryptedPassphrase).toHaveBeenCalledWith( encryptedPassphraseObject, ); expect(readerUtils.getPassphraseFromPrompt).toHaveBeenCalledWith('passphrase', true); @@ -132,11 +132,11 @@ describe('forging:config command', () => { ], config, ); - expect(cryptography.encryptPassphraseWithPassword).toHaveBeenCalledWith( + expect(cryptography.encrypt.encryptPassphraseWithPassword).toHaveBeenCalledWith( defaultInputs.passphrase, defaultInputs.password, ); - expect(cryptography.stringifyEncryptedPassphrase).toHaveBeenCalledWith( + expect(cryptography.encrypt.stringifyEncryptedPassphrase).toHaveBeenCalledWith( encryptedPassphraseObject, ); expect(readerUtils.getPassphraseFromPrompt).not.toHaveBeenCalledWith('passphrase', true); diff --git a/commander/test/bootstrapping/commands/hash-onion.spec.ts b/commander/test/bootstrapping/commands/hash-onion.spec.ts index 409ff722dd9..5574192b9f9 100644 --- a/commander/test/bootstrapping/commands/hash-onion.spec.ts +++ b/commander/test/bootstrapping/commands/hash-onion.spec.ts @@ -43,7 +43,7 @@ describe('hash-onion command', () => { for (let i = 0; i < result.hashes.length - 1; i += 1) { let nextHash = Buffer.from(result.hashes[i + 1], 'hex'); for (let j = 0; j < result.distance; j += 1) { - nextHash = cryptography.hash(nextHash).slice(0, 16); + nextHash = cryptography.utils.hash(nextHash).slice(0, 16); } expect(result.hashes[i]).toBe(nextHash.toString('hex')); } diff --git a/commander/test/bootstrapping/commands/passphrase/decrypt.spec.ts b/commander/test/bootstrapping/commands/passphrase/decrypt.spec.ts index 3196eb40351..7b1f8ebe054 100644 --- a/commander/test/bootstrapping/commands/passphrase/decrypt.spec.ts +++ b/commander/test/bootstrapping/commands/passphrase/decrypt.spec.ts @@ -48,10 +48,10 @@ describe('passphrase:decrypt', () => { jest.spyOn(process.stderr, 'write').mockImplementation(val => stderr.push(val as string) > -1); jest.spyOn(DecryptCommand.prototype, 'printJSON').mockReturnValue(); jest - .spyOn(cryptography, 'parseEncryptedPassphrase') + .spyOn(cryptography.encrypt, 'parseEncryptedPassphrase') .mockReturnValue(encryptedPassphraseObject as never); jest - .spyOn(cryptography, 'decryptPassphraseWithPassword') + .spyOn(cryptography.encrypt, 'decryptPassphraseWithPassword') .mockResolvedValue(passphrase as never); jest.spyOn(readerUtils, 'getPasswordFromPrompt').mockResolvedValue(defaultInputs); }); @@ -66,10 +66,10 @@ describe('passphrase:decrypt', () => { it('should decrypt passphrase with arg', async () => { await DecryptCommand.run([defaultEncryptedPassphrase], config); expect(readerUtils.getPasswordFromPrompt).toHaveBeenCalledWith('password', true); - expect(cryptography.parseEncryptedPassphrase).toHaveBeenCalledWith( + expect(cryptography.encrypt.parseEncryptedPassphrase).toHaveBeenCalledWith( defaultEncryptedPassphrase, ); - expect(cryptography.decryptPassphraseWithPassword).toHaveBeenCalledWith( + expect(cryptography.encrypt.decryptPassphraseWithPassword).toHaveBeenCalledWith( encryptedPassphraseObject, defaultInputs, ); @@ -81,10 +81,10 @@ describe('passphrase:decrypt', () => { it('should decrypt passphrase with passphrase flag and password flag', async () => { await DecryptCommand.run([defaultEncryptedPassphrase, '--password=LbYpLpV9Wpec6ux8'], config); expect(readerUtils.getPasswordFromPrompt).not.toHaveBeenCalled(); - expect(cryptography.parseEncryptedPassphrase).toHaveBeenCalledWith( + expect(cryptography.encrypt.parseEncryptedPassphrase).toHaveBeenCalledWith( defaultEncryptedPassphrase, ); - expect(cryptography.decryptPassphraseWithPassword).toHaveBeenCalledWith( + expect(cryptography.encrypt.decryptPassphraseWithPassword).toHaveBeenCalledWith( encryptedPassphraseObject, defaultInputs, ); diff --git a/commander/test/bootstrapping/commands/passphrase/encrypt.spec.ts b/commander/test/bootstrapping/commands/passphrase/encrypt.spec.ts index de168586718..8862a9b7ba6 100644 --- a/commander/test/bootstrapping/commands/passphrase/encrypt.spec.ts +++ b/commander/test/bootstrapping/commands/passphrase/encrypt.spec.ts @@ -56,12 +56,12 @@ describe('passphrase:encrypt', () => { jest.spyOn(process.stdout, 'write').mockImplementation(val => stdout.push(val as string) > -1); jest.spyOn(process.stderr, 'write').mockImplementation(val => stderr.push(val as string) > -1); jest.spyOn(EncryptCommand.prototype, 'printJSON').mockReturnValue(); - jest.spyOn(cryptography, 'getKeys').mockReturnValue(defaultKeys as never); + jest.spyOn(cryptography.ed, 'getKeys').mockReturnValue(defaultKeys as never); jest - .spyOn(cryptography, 'encryptPassphraseWithPassword') + .spyOn(cryptography.encrypt, 'encryptPassphraseWithPassword') .mockResolvedValue(encryptedPassphraseObject as never); jest - .spyOn(cryptography, 'stringifyEncryptedPassphrase') + .spyOn(cryptography.encrypt, 'stringifyEncryptedPassphrase') .mockReturnValue(encryptedPassphraseString); jest.spyOn(readerUtils, 'getPassphraseFromPrompt').mockImplementation(async (name?: string) => { if (name === 'passphrase') { @@ -80,11 +80,11 @@ describe('passphrase:encrypt', () => { describe('passphrase:encrypt', () => { it('should encrypt passphrase', async () => { await EncryptCommand.run([], config); - expect(cryptography.encryptPassphraseWithPassword).toHaveBeenCalledWith( + expect(cryptography.encrypt.encryptPassphraseWithPassword).toHaveBeenCalledWith( defaultInputs.passphrase, defaultInputs.password, ); - expect(cryptography.stringifyEncryptedPassphrase).toHaveBeenCalledWith( + expect(cryptography.encrypt.stringifyEncryptedPassphrase).toHaveBeenCalledWith( encryptedPassphraseObject, ); expect(readerUtils.getPassphraseFromPrompt).toHaveBeenCalledWith('passphrase', true); @@ -103,11 +103,11 @@ describe('passphrase:encrypt', () => { describe('passphrase:encrypt --output-public-key', () => { it('should encrypt passphrase and output public key', async () => { await EncryptCommand.run(['--output-public-key'], config); - expect(cryptography.encryptPassphraseWithPassword).toHaveBeenCalledWith( + expect(cryptography.encrypt.encryptPassphraseWithPassword).toHaveBeenCalledWith( defaultInputs.passphrase, defaultInputs.password, ); - expect(cryptography.stringifyEncryptedPassphrase).toHaveBeenCalledWith( + expect(cryptography.encrypt.stringifyEncryptedPassphrase).toHaveBeenCalledWith( encryptedPassphraseObject, ); expect(readerUtils.getPassphraseFromPrompt).toHaveBeenCalledWith('passphrase', true); @@ -128,11 +128,11 @@ describe('passphrase:encrypt', () => { ['--passphrase=enemy pill squeeze gold spoil aisle awake thumb congress false box wagon'], config, ); - expect(cryptography.encryptPassphraseWithPassword).toHaveBeenCalledWith( + expect(cryptography.encrypt.encryptPassphraseWithPassword).toHaveBeenCalledWith( defaultInputs.passphrase, defaultInputs.password, ); - expect(cryptography.stringifyEncryptedPassphrase).toHaveBeenCalledWith( + expect(cryptography.encrypt.stringifyEncryptedPassphrase).toHaveBeenCalledWith( encryptedPassphraseObject, ); expect(readerUtils.getPassphraseFromPrompt).not.toHaveBeenCalledWith('passphrase', true); @@ -155,11 +155,11 @@ describe('passphrase:encrypt', () => { ], config, ); - expect(cryptography.encryptPassphraseWithPassword).toHaveBeenCalledWith( + expect(cryptography.encrypt.encryptPassphraseWithPassword).toHaveBeenCalledWith( defaultInputs.passphrase, defaultInputs.password, ); - expect(cryptography.stringifyEncryptedPassphrase).toHaveBeenCalledWith( + expect(cryptography.encrypt.stringifyEncryptedPassphrase).toHaveBeenCalledWith( encryptedPassphraseObject, ); expect(readerUtils.getPassphraseFromPrompt).not.toHaveBeenCalledWith('passphrase', true); diff --git a/commander/test/commands/message/encrypt.spec.ts b/commander/test/commands/message/encrypt.spec.ts index f5503e45981..c57558c37f7 100644 --- a/commander/test/commands/message/encrypt.spec.ts +++ b/commander/test/commands/message/encrypt.spec.ts @@ -49,7 +49,7 @@ describe('message:encrypt', () => { jest.spyOn(process.stderr, 'write').mockImplementation(val => stderr.push(val as string) > -1); jest.spyOn(inquirer, 'prompt').mockResolvedValue({ passphrase: defaultInputs }); jest.spyOn(readerUtils, 'readFileSource').mockResolvedValue(message); - jest.spyOn(cryptography, 'encryptMessageWithPassphrase').mockReturnValue({ + jest.spyOn(cryptography.encrypt, 'encryptMessageWithPassphrase').mockReturnValue({ encryptedMessage: defaultEncryptedMessage.message, nonce: defaultEncryptedMessage.nonce, }); diff --git a/commander/test/helpers/account.ts b/commander/test/helpers/account.ts index e1a67c7f962..724d00ea139 100644 --- a/commander/test/helpers/account.ts +++ b/commander/test/helpers/account.ts @@ -21,7 +21,7 @@ const { Mnemonic } = liskPassphrase; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export const createAccount = () => { const passphrase = Mnemonic.generateMnemonic(); - const { privateKey, publicKey } = cryptography.utils.getKeys(passphrase); + const { privateKey, publicKey } = cryptography.ed.getKeys(passphrase); const address = cryptography.address.getAddressFromPublicKey(publicKey); return { diff --git a/commander/test/helpers/transactions.ts b/commander/test/helpers/transactions.ts index 9f8184a435e..9af51701b2a 100644 --- a/commander/test/helpers/transactions.ts +++ b/commander/test/helpers/transactions.ts @@ -125,7 +125,7 @@ export const genesisBlockID = Buffer.from( ); export const communityIdentifier = 'Lisk'; -export const networkIdentifier = cryptography.getNetworkIdentifier( +export const networkIdentifier = cryptography.utils.getNetworkIdentifier( genesisBlockID, communityIdentifier, ); diff --git a/elements/lisk-chain/test/utils/block.ts b/elements/lisk-chain/test/utils/block.ts index f549e7c576d..df4a420328b 100644 --- a/elements/lisk-chain/test/utils/block.ts +++ b/elements/lisk-chain/test/utils/block.ts @@ -12,10 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - utils, - address, -} from '@liskhq/lisk-cryptography'; +import { utils, address, ed } from '@liskhq/lisk-cryptography'; import { Mnemonic } from '@liskhq/lisk-passphrase'; import { MerkleTree } from '@liskhq/lisk-tree'; import * as genesis from '../fixtures/genesis_block.json'; @@ -29,7 +26,7 @@ export const defaultNetworkIdentifier = Buffer.from( const getKeyPair = (): { publicKey: Buffer; privateKey: Buffer } => { const passphrase = Mnemonic.generateMnemonic(); - return address.getPrivateAndPublicKeyFromPassphrase(passphrase); + return ed.getPrivateAndPublicKeyFromPassphrase(passphrase); }; export const createFakeBlockHeader = (header?: Partial): BlockHeader => diff --git a/elements/lisk-client/test/lisk-cryptography/address.spec.ts b/elements/lisk-client/test/lisk-cryptography/address.spec.ts index cda4e18b986..cd9817eb997 100644 --- a/elements/lisk-client/test/lisk-cryptography/address.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/address.spec.ts @@ -19,8 +19,6 @@ const { address: { getAddressFromPublicKey, getLisk32AddressFromPublicKey, - getPrivateAndPublicKeyFromPassphrase, - getKeys, getAddressAndPublicKeyFromPassphrase, getAddressFromPassphrase, getAddressFromPrivateKey, @@ -47,38 +45,6 @@ describe('keys', () => { address: defaultAddress, }; - describe('#getPrivateAndPublicKeyFromPassphrase', () => { - let keyPair: any; - - beforeEach(() => { - keyPair = getPrivateAndPublicKeyFromPassphrase(defaultPassphrase); - }); - - it('should generate the correct publicKey from a passphrase', () => { - expect(keyPair).toHaveProperty('publicKey', defaultPublicKey); - }); - - it('should generate the correct privateKey from a passphrase', () => { - expect(keyPair).toHaveProperty('privateKey', defaultPrivateKey); - }); - }); - - describe('#getKeys', () => { - let keyPair: any; - - beforeEach(() => { - keyPair = getKeys(defaultPassphrase); - }); - - it('should generate the correct publicKey from a passphrase', () => { - expect(keyPair).toHaveProperty('publicKey', defaultPublicKey); - }); - - it('should generate the correct privateKey from a passphrase', () => { - expect(keyPair).toHaveProperty('privateKey', defaultPrivateKey); - }); - }); - describe('#getAddressAndPublicKeyFromPassphrase', () => { it('should create correct address and publicKey', () => { expect(getAddressAndPublicKeyFromPassphrase(defaultPassphrase)).toEqual( diff --git a/elements/lisk-client/test/lisk-cryptography/bls.spec.ts b/elements/lisk-client/test/lisk-cryptography/bls.spec.ts index 699f1c3473b..afc7256e749 100644 --- a/elements/lisk-client/test/lisk-cryptography/bls.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/bls.spec.ts @@ -16,9 +16,7 @@ import { cryptography } from '../../src'; const { - bls: { - getPrivateKeyFromPhraseAndPath, - }, + bls: { getPrivateKeyFromPhraseAndPath }, } = cryptography; describe('bls', () => { diff --git a/elements/lisk-client/test/lisk-cryptography/ed.spec.ts b/elements/lisk-client/test/lisk-cryptography/ed.spec.ts index 2cd55b774e4..499464de979 100644 --- a/elements/lisk-client/test/lisk-cryptography/ed.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/ed.spec.ts @@ -27,10 +27,10 @@ const { verifyData, getKeyPairFromPhraseAndPath, getPublicKeyFromPrivateKey, + getKeys, + getPrivateAndPublicKeyFromPassphrase, }, - utils: { - createMessageTag, - }, + utils: { createMessageTag }, } = cryptography; const makeInvalid = (buffer: Buffer): Buffer => { @@ -121,6 +121,38 @@ ${defaultSignature} }); }); + describe('#getPrivateAndPublicKeyFromPassphrase', () => { + let keyPair: any; + + beforeEach(() => { + keyPair = getPrivateAndPublicKeyFromPassphrase(defaultPassphrase); + }); + + it('should generate the correct publicKey from a passphrase', () => { + expect(keyPair).toHaveProperty('publicKey', Buffer.from(defaultPublicKey, 'hex')); + }); + + it('should generate the correct privateKey from a passphrase', () => { + expect(keyPair).toHaveProperty('privateKey', Buffer.from(defaultPrivateKey, 'hex')); + }); + }); + + describe('#getKeys', () => { + let keyPair: any; + + beforeEach(() => { + keyPair = getKeys(defaultPassphrase); + }); + + it('should generate the correct publicKey from a passphrase', () => { + expect(keyPair).toHaveProperty('publicKey', Buffer.from(defaultPublicKey, 'hex')); + }); + + it('should generate the correct privateKey from a passphrase', () => { + expect(keyPair).toHaveProperty('privateKey', Buffer.from(defaultPrivateKey, 'hex')); + }); + }); + describe('#printSignedMessage', () => { it('should wrap a single signed message into a printed Lisk template', () => { const printedMessage = printSignedMessage({ @@ -211,10 +243,7 @@ ${defaultSignature} const passphrase = 'target cancel solution recipe vague faint bomb convince pink vendor fresh patrol'; it('should get keypair from valid phrase and path', async () => { - const privateKey = await getKeyPairFromPhraseAndPath( - passphrase, - `m/44'/134'/0'`, - ); + const privateKey = await getKeyPairFromPhraseAndPath(passphrase, `m/44'/134'/0'`); const publicKey = getPublicKeyFromPrivateKey(privateKey); expect(publicKey.toString('hex')).toBe( 'c6bae83af23540096ac58d5121b00f33be6f02f05df785766725acdd5d48be9d', diff --git a/elements/lisk-client/test/lisk-cryptography/encrypt.spec.ts b/elements/lisk-client/test/lisk-cryptography/encrypt.spec.ts index f8b5a147598..b53b43eb27d 100644 --- a/elements/lisk-client/test/lisk-cryptography/encrypt.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/encrypt.spec.ts @@ -47,12 +47,14 @@ describe('encrypt', () => { let hashStub: any; beforeEach(async () => { - jest.spyOn(cryptography.address, 'getAddressAndPublicKeyFromPassphrase').mockImplementation(() => { - return { - address: defaultPrivateKey, - publicKey: defaultPublicKey, - }; - }); + jest + .spyOn(cryptography.address, 'getAddressAndPublicKeyFromPassphrase') + .mockImplementation(() => { + return { + address: defaultPrivateKey, + publicKey: defaultPublicKey, + }; + }); hashStub = jest .spyOn(cryptography.utils, 'hash') diff --git a/elements/lisk-client/test/lisk-cryptography/utils.spec.ts b/elements/lisk-client/test/lisk-cryptography/utils.spec.ts index 70624fe3ce1..d36fd5f66bc 100644 --- a/elements/lisk-client/test/lisk-cryptography/utils.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/utils.spec.ts @@ -15,15 +15,17 @@ import { cryptography } from '../../src'; -const { utils: { - generateHashOnionSeed, - bufferToHex, - hexToBuffer, - intToBuffer, - getNetworkIdentifier, - hashOnion, - hash: hashFunction, -}, } = cryptography; +const { + utils: { + generateHashOnionSeed, + bufferToHex, + hexToBuffer, + intToBuffer, + getNetworkIdentifier, + hashOnion, + hash: hashFunction, + }, +} = cryptography; describe('buffer', () => { const defaultBuffer = Buffer.from('\xe5\xe4\xf6'); diff --git a/elements/lisk-cryptography/benchmark/nacl.js b/elements/lisk-cryptography/benchmark/nacl.js index 948702a1ad5..3968533e0c3 100644 --- a/elements/lisk-cryptography/benchmark/nacl.js +++ b/elements/lisk-cryptography/benchmark/nacl.js @@ -96,10 +96,10 @@ const verifyDetachedBenchmark = new Benchmark.Suite('verifyDetached') const getRandomBytesBenchmark = new Benchmark.Suite('getRandomBytes') .add('fast.getRandomBytes', () => { - fast.utils.getRandomBytes(24); + fast.getRandomBytes(24); }) .add('slow.getRandomBytes', () => { - slow.utils.getRandomBytes(24); + slow.getRandomBytes(24); }); const getKeyPairBenchmark = new Benchmark.Suite('getKeyPair') diff --git a/elements/lisk-cryptography/src/address.ts b/elements/lisk-cryptography/src/address.ts index cbb73443bb7..7680a2e5bb0 100644 --- a/elements/lisk-cryptography/src/address.ts +++ b/elements/lisk-cryptography/src/address.ts @@ -13,8 +13,8 @@ * */ import { BINARY_ADDRESS_LENGTH, DEFAULT_LISK32_ADDRESS_PREFIX } from './constants'; -import { getKeyPair, getPublicKey } from './nacl'; -import { Keypair } from './types'; +import { getKeys } from './ed'; +import { getPublicKey } from './nacl'; import { hash } from './utils'; const CHARSET = 'zxvcpmbn3465o978uyrtkqew2adsjhfg'; @@ -50,13 +50,6 @@ const convertUIntArray = (uintArray: number[], fromBits: number, toBits: number) const convertUInt5ToBase32 = (uint5Array: number[]): string => uint5Array.map((val: number) => CHARSET[val]).join(''); -export const getPrivateAndPublicKeyFromPassphrase = (passphrase: string): Keypair => { - const hashed = hash(passphrase, 'utf8'); - return getKeyPair(hashed); -}; - -export const getKeys = getPrivateAndPublicKeyFromPassphrase; - export const getAddressFromPublicKey = (publicKey: Buffer): Buffer => { const buffer = hash(publicKey); const truncatedBuffer = buffer.slice(0, BINARY_ADDRESS_LENGTH); diff --git a/elements/lisk-cryptography/src/ed.ts b/elements/lisk-cryptography/src/ed.ts index cacc1fd2d3e..06d0d1c3d30 100644 --- a/elements/lisk-cryptography/src/ed.ts +++ b/elements/lisk-cryptography/src/ed.ts @@ -56,6 +56,8 @@ export const getPrivateAndPublicKeyFromPassphrase = (passphrase: string) => { return getKeyPair(hashed); }; +export const getKeys = getPrivateAndPublicKeyFromPassphrase; + const getMasterKeyFromSeed = (seed: Buffer) => { const hmac = crypto.createHmac('sha512', ED25519_CURVE); const digest = hmac.update(seed).digest(); diff --git a/elements/lisk-cryptography/src/encrypt.ts b/elements/lisk-cryptography/src/encrypt.ts index 9010067242a..bce0f95e98b 100644 --- a/elements/lisk-cryptography/src/encrypt.ts +++ b/elements/lisk-cryptography/src/encrypt.ts @@ -18,7 +18,7 @@ import * as crypto from 'crypto'; import * as ed2curve from 'ed2curve'; // eslint-disable-next-line import/no-cycle -import { getPrivateAndPublicKeyFromPassphrase } from './address'; +import { getPrivateAndPublicKeyFromPassphrase } from './ed'; // eslint-disable-next-line import/no-cycle import { box, getRandomBytes, openBox } from './nacl'; import { bufferToHex, hexToBuffer } from './utils'; diff --git a/elements/lisk-cryptography/src/legacy_address.ts b/elements/lisk-cryptography/src/legacy_address.ts index 194405ad213..802391b17a2 100644 --- a/elements/lisk-cryptography/src/legacy_address.ts +++ b/elements/lisk-cryptography/src/legacy_address.ts @@ -13,7 +13,7 @@ * */ -import { getKeys } from './address'; +import { getKeys } from './ed'; import { getPublicKey } from './nacl'; import { hash } from './utils'; diff --git a/elements/lisk-cryptography/test/address.spec.ts b/elements/lisk-cryptography/test/address.spec.ts index bb4b70c61f3..b4e36dd6e4b 100644 --- a/elements/lisk-cryptography/test/address.spec.ts +++ b/elements/lisk-cryptography/test/address.spec.ts @@ -15,8 +15,6 @@ import { getAddressFromPublicKey, getLisk32AddressFromPublicKey, - getPrivateAndPublicKeyFromPassphrase, - getKeys, getAddressAndPublicKeyFromPassphrase, getAddressFromPassphrase, getAddressFromPrivateKey, @@ -25,7 +23,6 @@ import { getLisk32AddressFromAddress, getLisk32AddressFromPassphrase, } from '../src/address'; -import { Keypair } from '../src/types'; import * as utils from '../src/utils'; describe('address', () => { @@ -52,38 +49,6 @@ describe('address', () => { jest.spyOn(utils, 'hash').mockReturnValue(Buffer.from(defaultPassphraseHash, 'hex')); }); - describe('#getPrivateAndPublicKeyFromPassphrase', () => { - let keyPair: Keypair; - - beforeEach(() => { - keyPair = getPrivateAndPublicKeyFromPassphrase(defaultPassphrase); - }); - - it('should generate the correct publicKey from a passphrase', () => { - expect(keyPair).toHaveProperty('publicKey', defaultPublicKey); - }); - - it('should generate the correct privateKey from a passphrase', () => { - expect(keyPair).toHaveProperty('privateKey', defaultPrivateKey); - }); - }); - - describe('#getKeys', () => { - let keyPair: Keypair; - - beforeEach(() => { - keyPair = getKeys(defaultPassphrase); - }); - - it('should generate the correct publicKey from a passphrase', () => { - expect(keyPair).toHaveProperty('publicKey', defaultPublicKey); - }); - - it('should generate the correct privateKey from a passphrase', () => { - expect(keyPair).toHaveProperty('privateKey', defaultPrivateKey); - }); - }); - describe('#getAddressAndPublicKeyFromPassphrase', () => { it('should create correct address and publicKey', () => { expect(getAddressAndPublicKeyFromPassphrase(defaultPassphrase)).toEqual( diff --git a/elements/lisk-cryptography/test/ed.spec.ts b/elements/lisk-cryptography/test/ed.spec.ts index bc64e7e376e..9acd601d8fd 100644 --- a/elements/lisk-cryptography/test/ed.spec.ts +++ b/elements/lisk-cryptography/test/ed.spec.ts @@ -25,10 +25,13 @@ import { verifyData, getKeyPairFromPhraseAndPath, getPublicKeyFromPrivateKey, + getPrivateAndPublicKeyFromPassphrase, + getKeys, } from '../src/ed'; import { createMessageTag } from '../src/utils'; import { MAX_UINT32 } from '../src/constants'; import * as address from '../src/address'; +import { Keypair } from '../src/types'; const changeLength = (buffer: Buffer): Buffer => Buffer.concat([Buffer.from('00', 'hex'), buffer]); @@ -85,6 +88,38 @@ ${defaultSignature} }); }); + describe('#getPrivateAndPublicKeyFromPassphrase', () => { + let keyPair: Keypair; + + beforeEach(() => { + keyPair = getPrivateAndPublicKeyFromPassphrase(defaultPassphrase); + }); + + it('should generate the correct publicKey from a passphrase', () => { + expect(keyPair).toHaveProperty('publicKey', Buffer.from(defaultPublicKey, 'hex')); + }); + + it('should generate the correct privateKey from a passphrase', () => { + expect(keyPair).toHaveProperty('privateKey', Buffer.from(defaultPrivateKey, 'hex')); + }); + }); + + describe('#getKeys', () => { + let keyPair: Keypair; + + beforeEach(() => { + keyPair = getKeys(defaultPassphrase); + }); + + it('should generate the correct publicKey from a passphrase', () => { + expect(keyPair).toHaveProperty('publicKey', Buffer.from(defaultPublicKey, 'hex')); + }); + + it('should generate the correct privateKey from a passphrase', () => { + expect(keyPair).toHaveProperty('privateKey', Buffer.from(defaultPrivateKey, 'hex')); + }); + }); + describe('#verifyMessageWithPublicKey', () => { it('should detect invalid publicKeys', () => { expect( diff --git a/elements/lisk-transactions/test/sign.spec.ts b/elements/lisk-transactions/test/sign.spec.ts index b856256a516..159fb96e8e3 100644 --- a/elements/lisk-transactions/test/sign.spec.ts +++ b/elements/lisk-transactions/test/sign.spec.ts @@ -14,11 +14,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { - ed, - utils, - address, -} from '@liskhq/lisk-cryptography'; +import { ed, utils, address } from '@liskhq/lisk-cryptography'; import { getSigningBytes, signTransaction, @@ -526,9 +522,9 @@ describe('sign', () => { }); it('should add sender and mandatory public key signatures in right order for multisignature registration trx', () => { - const account1 = address.getPrivateAndPublicKeyFromPassphrase(passphrase1); - const account2 = address.getPrivateAndPublicKeyFromPassphrase(passphrase2); - const account3 = address.getPrivateAndPublicKeyFromPassphrase(passphrase3); + const account1 = ed.getPrivateAndPublicKeyFromPassphrase(passphrase1); + const account2 = ed.getPrivateAndPublicKeyFromPassphrase(passphrase2); + const account3 = ed.getPrivateAndPublicKeyFromPassphrase(passphrase3); const mandatoryKeys = [account1.publicKey, account2.publicKey]; const optionalKeys = [account3.publicKey]; @@ -593,8 +589,8 @@ describe('sign', () => { }); it('should match the signatures of the mandatory keys in right order for transfer trx', () => { - const account1 = address.getPrivateAndPublicKeyFromPassphrase(passphrase1); - const account2 = address.getPrivateAndPublicKeyFromPassphrase(passphrase2); + const account1 = ed.getPrivateAndPublicKeyFromPassphrase(passphrase1); + const account2 = ed.getPrivateAndPublicKeyFromPassphrase(passphrase2); // Sender public key of account1 const transaction = { moduleID: utils.intToBuffer(2, 4), diff --git a/framework-plugins/lisk-framework-forger-plugin/test/utils/accounts.ts b/framework-plugins/lisk-framework-forger-plugin/test/utils/accounts.ts index 0962c208a7f..739f56d611f 100644 --- a/framework-plugins/lisk-framework-forger-plugin/test/utils/accounts.ts +++ b/framework-plugins/lisk-framework-forger-plugin/test/utils/accounts.ts @@ -15,7 +15,7 @@ import { cryptography } from 'lisk-sdk'; export const getRandomAccount = () => { - const { publicKey, privateKey } = cryptography.utils.getKeys( + const { publicKey, privateKey } = cryptography.ed.getKeys( cryptography.utils.getRandomBytes(20).toString('hex'), ); const address = cryptography.address.getAddressFromPublicKey(publicKey); diff --git a/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts b/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts index a564eca7a06..aa67bb5cf32 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/test/unit/blocks.spec.ts @@ -66,18 +66,18 @@ describe('_handlePostBlock', () => { version: 0, previousBlockID: Buffer.alloc(0), timestamp: Math.floor(Date.now() / 1000 - 24 * 60 * 60), - stateRoot: cryptography.hash(Buffer.alloc(0)), - eventRoot: cryptography.hash(Buffer.alloc(0)), + stateRoot: cryptography.utils.hash(Buffer.alloc(0)), + eventRoot: cryptography.utils.hash(Buffer.alloc(0)), maxHeightGenerated: 0, maxHeightPrevoted: 0, - assetRoot: cryptography.hash(Buffer.alloc(0)), + assetRoot: cryptography.utils.hash(Buffer.alloc(0)), validatorsHash: cryptography.utils.getRandomBytes(32), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - transactionRoot: cryptography.hash(Buffer.alloc(0)), + transactionRoot: cryptography.utils.hash(Buffer.alloc(0)), signature: Buffer.alloc(0), }); diff --git a/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts b/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts index 627acb5eede..7ce00a819bc 100644 --- a/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts +++ b/framework-plugins/lisk-framework-monitor-plugin/test/unit/forks.spec.ts @@ -64,18 +64,18 @@ describe('_handleFork', () => { version: 0, previousBlockID: Buffer.alloc(0), timestamp: Math.floor(Date.now() / 1000 - 24 * 60 * 60), - stateRoot: cryptography.hash(Buffer.alloc(0)), - eventRoot: cryptography.hash(Buffer.alloc(0)), + stateRoot: cryptography.utils.hash(Buffer.alloc(0)), + eventRoot: cryptography.utils.hash(Buffer.alloc(0)), maxHeightGenerated: 0, maxHeightPrevoted: 0, - assetRoot: cryptography.hash(Buffer.alloc(0)), + assetRoot: cryptography.utils.hash(Buffer.alloc(0)), validatorsHash: cryptography.utils.getRandomBytes(32), aggregateCommit: { height: 0, aggregationBits: Buffer.alloc(0), certificateSignature: Buffer.alloc(0), }, - transactionRoot: cryptography.hash(Buffer.alloc(0)), + transactionRoot: cryptography.utils.hash(Buffer.alloc(0)), signature: Buffer.alloc(0), }); diff --git a/framework/src/testing/block_processing_env.ts b/framework/src/testing/block_processing_env.ts index 74e75a255da..559289e35e4 100644 --- a/framework/src/testing/block_processing_env.ts +++ b/framework/src/testing/block_processing_env.ts @@ -18,7 +18,7 @@ import * as fs from 'fs-extra'; import * as path from 'path'; import * as os from 'os'; import { Block, Chain, DataAccess, BlockHeader, Transaction, StateStore } from '@liskhq/lisk-chain'; -import { utils, address } from '@liskhq/lisk-cryptography'; +import { utils, ed } from '@liskhq/lisk-cryptography'; import { Database, StateDB } from '@liskhq/lisk-db'; import { objects } from '@liskhq/lisk-utils'; import { codec } from '@liskhq/lisk-codec'; @@ -116,7 +116,7 @@ const createProcessableBlock = async ( for (const tx of transactions) { await engine['_generator']['_pool'].add(tx); } - const { privateKey } = address.getKeys(passphrase); + const { privateKey } = ed.getKeys(passphrase); const block = await engine.generateBlock({ generatorAddress: validator, height: previousBlockHeader.height + 1, diff --git a/framework/src/testing/create_transaction.ts b/framework/src/testing/create_transaction.ts index e5ce46fe29e..dc271b1e16e 100644 --- a/framework/src/testing/create_transaction.ts +++ b/framework/src/testing/create_transaction.ts @@ -15,7 +15,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { address } from '@liskhq/lisk-cryptography'; +import { address, ed } from '@liskhq/lisk-cryptography'; import { validateTransaction } from '@liskhq/lisk-transactions'; import { CommandClass } from './types'; @@ -73,7 +73,7 @@ export const createTransaction = ({ throw new Error('Network identifier is required to sign a transaction'); } - const keys = address.getKeys(passphrase); + const keys = ed.getKeys(passphrase); result.sign(networkIdentifier, keys.privateKey); return result; diff --git a/framework/test/fixtures/blocks.ts b/framework/test/fixtures/blocks.ts index 2c1a9e37080..2d93860ac88 100644 --- a/framework/test/fixtures/blocks.ts +++ b/framework/test/fixtures/blocks.ts @@ -12,12 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - getRandomBytes, - hash, - getPrivateAndPublicKeyFromPassphrase, - getAddressFromPublicKey, -} from '@liskhq/lisk-cryptography'; +import { utils, address, ed } from '@liskhq/lisk-cryptography'; import { Mnemonic } from '@liskhq/lisk-passphrase'; import { MerkleTree } from '@liskhq/lisk-tree'; import { Block, BlockAssets, BlockHeader, BlockHeaderAttrs, Transaction } from '@liskhq/lisk-chain'; @@ -54,7 +49,7 @@ export const genesisBlock = (): Block => { const getKeyPair = (): { publicKey: Buffer; privateKey: Buffer } => { const passphrase = Mnemonic.generateMnemonic(); - return getPrivateAndPublicKeyFromPassphrase(passphrase); + return ed.getPrivateAndPublicKeyFromPassphrase(passphrase); }; export const createFakeBlockHeader = (header?: Partial): BlockHeader => diff --git a/framework/test/functional/network/banning/invalid_block_property.spec.ts b/framework/test/functional/network/banning/invalid_block_property.spec.ts index db2e8fd5056..298f4019a45 100644 --- a/framework/test/functional/network/banning/invalid_block_property.spec.ts +++ b/framework/test/functional/network/banning/invalid_block_property.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { P2P } from '@liskhq/lisk-p2p'; import { Application } from '../../../../src'; diff --git a/framework/test/functional/network/blocks.spec.ts b/framework/test/functional/network/blocks.spec.ts index 2ef0c2c7952..f0d3c82c2ba 100644 --- a/framework/test/functional/network/blocks.spec.ts +++ b/framework/test/functional/network/blocks.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { P2P } from '@liskhq/lisk-p2p'; import { Application } from '../../../src'; diff --git a/framework/test/functional/network/transactions.spec.ts b/framework/test/functional/network/transactions.spec.ts index 41762b1d087..7be5041a0ef 100644 --- a/framework/test/functional/network/transactions.spec.ts +++ b/framework/test/functional/network/transactions.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { P2P, events, p2pTypes } from '@liskhq/lisk-p2p'; import { Application } from '../../../src'; diff --git a/framework/test/integration/node/generator/transaction_pool.spec.ts b/framework/test/integration/node/generator/transaction_pool.spec.ts index 7879a4e3520..ea4f0eba1a3 100644 --- a/framework/test/integration/node/generator/transaction_pool.spec.ts +++ b/framework/test/integration/node/generator/transaction_pool.spec.ts @@ -30,8 +30,8 @@ describe('Transaction pool', () => { }); }); - afterAll(async () => { - await processEnv.cleanup({ databasePath }); + afterAll(() => { + processEnv.cleanup({ databasePath }); }); describe('given a valid transaction while generation is disabled', () => { diff --git a/framework/test/integration/node/processor/block_process/process_block.spec.ts b/framework/test/integration/node/processor/block_process/process_block.spec.ts index 35a314c5d03..0b3325af344 100644 --- a/framework/test/integration/node/processor/block_process/process_block.spec.ts +++ b/framework/test/integration/node/processor/block_process/process_block.spec.ts @@ -14,7 +14,7 @@ import { Block, Chain, DataAccess, Transaction } from '@liskhq/lisk-chain'; import { regularMerkleTree } from '@liskhq/lisk-tree'; -import { getKeys } from '@liskhq/lisk-cryptography'; +import { ed } from '@liskhq/lisk-cryptography'; import { nodeUtils } from '../../../../utils'; import * as testing from '../../../../../src/testing'; import { @@ -148,7 +148,7 @@ describe('Process block', () => { const passphrase = await getPassphraseFromDefaultConfig( invalidBlock.header.generatorAddress, ); - const { privateKey } = getKeys(passphrase); + const { privateKey } = ed.getKeys(passphrase); invalidBlock.header.sign(processEnv.getNetworkId(), privateKey); await expect(processEnv.process(invalidBlock)).rejects.toThrow( 'Failed to verify transaction', @@ -199,7 +199,7 @@ describe('Process block', () => { newBlock = await processEnv.createBlock(); (newBlock.header as any).height = 99; const passphrase = await getPassphraseFromDefaultConfig(newBlock.header.generatorAddress); - const { privateKey } = getKeys(passphrase); + const { privateKey } = ed.getKeys(passphrase); newBlock.header.sign(processEnv.getNetworkId(), privateKey); }); @@ -295,7 +295,7 @@ describe('Process block', () => { const passphrase = await getPassphraseFromDefaultConfig( invalidBlock.header.generatorAddress, ); - const { privateKey } = getKeys(passphrase); + const { privateKey } = ed.getKeys(passphrase); invalidBlock.header.sign(processEnv.getNetworkId(), privateKey); try { await processEnv.process(invalidBlock); diff --git a/framework/test/integration/node/processor/report_misbehavior_transaction.spec.ts b/framework/test/integration/node/processor/report_misbehavior_transaction.spec.ts index 9a904716340..dfee63ed337 100644 --- a/framework/test/integration/node/processor/report_misbehavior_transaction.spec.ts +++ b/framework/test/integration/node/processor/report_misbehavior_transaction.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ import { Block, BlockHeader } from '@liskhq/lisk-chain'; -import { getAddressFromPassphrase, getKeys } from '@liskhq/lisk-cryptography'; +import { address, ed } from '@liskhq/lisk-cryptography'; import { nodeUtils } from '../../../utils'; import { @@ -70,12 +70,12 @@ describe('Transaction order', () => { ...header.toObject(), height: 100, }); - const { privateKey } = getKeys(blockGenerator); + const { privateKey } = ed.getKeys(blockGenerator); conflictingHeader.sign(networkIdentifier, privateKey); const originalBalance = await processEnv.invoke<{ availableBalance: string }>( 'token_getBalance', { - address: getAddressFromPassphrase(blockGenerator).toString('hex'), + address: address.getAddressFromPassphrase(blockGenerator).toString('hex'), tokenID: DEFAULT_TOKEN_ID.toString('hex'), }, ); @@ -94,12 +94,12 @@ describe('Transaction order', () => { const updatedDelegate = await processEnv.invoke<{ pomHeights: number[] }>( 'dpos_getDelegate', { - address: getAddressFromPassphrase(blockGenerator).toString('hex'), + address: address.getAddressFromPassphrase(blockGenerator).toString('hex'), }, ); expect(updatedDelegate.pomHeights).toHaveLength(1); const balance = await processEnv.invoke<{ availableBalance: string }>('token_getBalance', { - address: getAddressFromPassphrase(blockGenerator).toString('hex'), + address: address.getAddressFromPassphrase(blockGenerator).toString('hex'), tokenID: DEFAULT_TOKEN_ID.toString('hex'), }); expect(balance.availableBalance).toEqual( diff --git a/framework/test/integration/testing/block_processing_env.spec.ts b/framework/test/integration/testing/block_processing_env.spec.ts index eae456905b9..bd404d10930 100644 --- a/framework/test/integration/testing/block_processing_env.spec.ts +++ b/framework/test/integration/testing/block_processing_env.spec.ts @@ -12,10 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - getAddressAndPublicKeyFromPassphrase, - getAddressFromPublicKey, -} from '@liskhq/lisk-cryptography'; +import { address } from '@liskhq/lisk-cryptography'; import * as testing from '../../../src/testing'; import { defaultConfig } from '../../../src/testing/fixtures/config'; @@ -32,8 +29,8 @@ describe('getBlockProcessingEnv', () => { }); }); - afterAll(async () => { - await processEnv.cleanup({ databasePath }); + afterAll(() => { + processEnv.cleanup({ databasePath }); }); it('should get genesis block as the last block', () => { @@ -82,7 +79,7 @@ describe('getBlockProcessingEnv', () => { // Arrange const lastBlockHeader = processEnv.getLastBlock().header; const passphrase = await processEnv.getNextValidatorPassphrase(lastBlockHeader); - const { publicKey } = getAddressAndPublicKeyFromPassphrase(passphrase); + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(passphrase); // Act & Assert const block = await processEnv.createBlock(); diff --git a/framework/test/unit/engine/consensus/certificate_generation/commit_list.spec.ts b/framework/test/unit/engine/consensus/certificate_generation/commit_list.spec.ts index d992a3d81e6..2be80a2e41c 100644 --- a/framework/test/unit/engine/consensus/certificate_generation/commit_list.spec.ts +++ b/framework/test/unit/engine/consensus/certificate_generation/commit_list.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { CommitList, COMMIT_SORT, diff --git a/framework/test/unit/engine/consensus/certificate_generation/commit_pool.spec.ts b/framework/test/unit/engine/consensus/certificate_generation/commit_pool.spec.ts index d8b6377e5d6..28c224d6bcd 100644 --- a/framework/test/unit/engine/consensus/certificate_generation/commit_pool.spec.ts +++ b/framework/test/unit/engine/consensus/certificate_generation/commit_pool.spec.ts @@ -15,13 +15,7 @@ import { InMemoryDatabase, NotFoundError } from '@liskhq/lisk-db'; import { BlockHeader, StateStore } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { - createAggSig, - generatePrivateKey, - getPublicKeyFromPrivateKey, - getRandomBytes, - signBLS, -} from '@liskhq/lisk-cryptography'; +import { bls, utils } from '@liskhq/lisk-cryptography'; import * as crypto from '@liskhq/lisk-cryptography'; import { when } from 'jest-when'; import { BFTParameterNotFoundError } from '../../../../../src/engine/bft/errors'; @@ -461,8 +455,8 @@ describe('CommitPool', () => { certificate = computeCertificateFromBlockHeader(blockHeader); - privateKey = generatePrivateKey(utils.getRandomBytes(32)); - publicKey = getPublicKeyFromPrivateKey(privateKey); + privateKey = bls.generatePrivateKey(utils.getRandomBytes(32)); + publicKey = bls.getPublicKeyFromPrivateKey(privateKey); signature = signCertificate(privateKey, networkIdentifier, certificate); commit = { @@ -793,8 +787,10 @@ describe('CommitPool', () => { stateStore = new StateStore(new InMemoryDatabase()); - privateKeys = Array.from({ length: 103 }, _ => generatePrivateKey(utils.getRandomBytes(32))); - publicKeys = privateKeys.map(priv => getPublicKeyFromPrivateKey(priv)); + privateKeys = Array.from({ length: 103 }, _ => + bls.generatePrivateKey(utils.getRandomBytes(32)), + ); + publicKeys = privateKeys.map(priv => bls.getPublicKeyFromPrivateKey(priv)); keysList = [...publicKeys]; weights = Array.from({ length: 103 }, _ => 1); @@ -811,7 +807,7 @@ describe('CommitPool', () => { const encodedCertificate = codec.encode(certificateSchema, certificate); signatures = privateKeys.map(privateKey => - signBLS(MESSAGE_TAG_CERTIFICATE, networkIdentifier, encodedCertificate, privateKey), + bls.signBLS(MESSAGE_TAG_CERTIFICATE, networkIdentifier, encodedCertificate, privateKey), ); pubKeySignaturePairs = Array.from({ length: 103 }, (_, i) => ({ @@ -819,7 +815,7 @@ describe('CommitPool', () => { signature: signatures[i], })); - ({ aggregationBits, signature: aggregateSignature } = createAggSig( + ({ aggregationBits, signature: aggregateSignature } = bls.createAggSig( publicKeys, pubKeySignaturePairs, )); @@ -1067,12 +1063,12 @@ describe('CommitPool', () => { }; const pubKeySignaturePairs = [pubKeySignaturePair1, pubKeySignaturePair2, pubKeySignaturePair3]; - const { aggregationBits: aggregationBits1, signature: aggregateSignature1 } = createAggSig( + const { aggregationBits: aggregationBits1, signature: aggregateSignature1 } = bls.createAggSig( [validatorInfo1.blsPublicKey], [pubKeySignaturePair1], ); - const { aggregationBits, signature: aggregateSignature } = createAggSig( + const { aggregationBits, signature: aggregateSignature } = bls.createAggSig( validatorKeys, pubKeySignaturePairs, ); @@ -1144,7 +1140,7 @@ describe('CommitPool', () => { }); it('should call validator keys in lexicographical order', async () => { - const spy = jest.spyOn(crypto, 'createAggSig'); + const spy = jest.spyOn(crypto.bls, 'createAggSig'); bftAPI.getBFTParameters.mockReturnValue({ validators: [ { address: validatorInfo1.address, blsKey: validatorInfo1.blsPublicKey }, diff --git a/framework/test/unit/engine/consensus/certificate_generation/utils.spec.ts b/framework/test/unit/engine/consensus/certificate_generation/utils.spec.ts index 61f720b8baa..ac090eac362 100644 --- a/framework/test/unit/engine/consensus/certificate_generation/utils.spec.ts +++ b/framework/test/unit/engine/consensus/certificate_generation/utils.spec.ts @@ -13,13 +13,7 @@ */ import { BlockHeader } from '@liskhq/lisk-chain'; -import { - signBLS, - generatePrivateKey, - getPublicKeyFromPrivateKey, - getRandomBytes, - createAggSig, -} from '@liskhq/lisk-cryptography'; +import { bls, utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { Certificate } from '../../../../../src/engine/consensus/certificate_generation/types'; import { MESSAGE_TAG_CERTIFICATE } from '../../../../../src/engine/consensus/certificate_generation/constants'; @@ -75,7 +69,7 @@ describe('utils', () => { let signature: Buffer; beforeEach(() => { - privateKey = generatePrivateKey(utils.getRandomBytes(32)); + privateKey = bls.generatePrivateKey(utils.getRandomBytes(32)); certificate = { blockID: Buffer.alloc(0), height: 1000, @@ -84,7 +78,7 @@ describe('utils', () => { validatorsHash: Buffer.alloc(0), }; const encodedCertificate = codec.encode(certificateSchema, certificate); - signature = signBLS( + signature = bls.signBLS( MESSAGE_TAG_CERTIFICATE, networkIdentifier, encodedCertificate, @@ -105,8 +99,8 @@ describe('utils', () => { let signature: Buffer; beforeEach(() => { - privateKey = generatePrivateKey(utils.getRandomBytes(32)); - publicKey = getPublicKeyFromPrivateKey(privateKey); + privateKey = bls.generatePrivateKey(utils.getRandomBytes(32)); + publicKey = bls.getPublicKeyFromPrivateKey(privateKey); certificate = { blockID: Buffer.alloc(0), height: 1030, @@ -117,7 +111,7 @@ describe('utils', () => { const encodedCertificate = codec.encode(certificateSchema, certificate); - signature = signBLS( + signature = bls.signBLS( MESSAGE_TAG_CERTIFICATE, networkIdentifier, encodedCertificate, @@ -178,8 +172,10 @@ describe('utils', () => { let aggregationBits: Buffer; beforeEach(() => { - privateKeys = Array.from({ length: 103 }, _ => generatePrivateKey(utils.getRandomBytes(32))); - publicKeys = privateKeys.map(priv => getPublicKeyFromPrivateKey(priv)); + privateKeys = Array.from({ length: 103 }, _ => + bls.generatePrivateKey(utils.getRandomBytes(32)), + ); + publicKeys = privateKeys.map(priv => bls.getPublicKeyFromPrivateKey(priv)); keysList = [...publicKeys]; weights = Array.from({ length: 103 }, _ => 1); @@ -196,7 +192,7 @@ describe('utils', () => { const encodedCertificate = codec.encode(certificateSchema, certificate); signatures = privateKeys.map(privateKey => - signBLS(MESSAGE_TAG_CERTIFICATE, networkIdentifier, encodedCertificate, privateKey), + bls.signBLS(MESSAGE_TAG_CERTIFICATE, networkIdentifier, encodedCertificate, privateKey), ); pubKeySignaturePairs = Array.from({ length: 103 }, (_, i) => ({ @@ -204,7 +200,7 @@ describe('utils', () => { signature: signatures[i], })); - ({ aggregationBits, signature: aggregateSignature } = createAggSig( + ({ aggregationBits, signature: aggregateSignature } = bls.createAggSig( publicKeys, pubKeySignaturePairs, )); diff --git a/framework/test/unit/engine/consensus/consensus.spec.ts b/framework/test/unit/engine/consensus/consensus.spec.ts index c334f63300c..f8fb8b6ec75 100644 --- a/framework/test/unit/engine/consensus/consensus.spec.ts +++ b/framework/test/unit/engine/consensus/consensus.spec.ts @@ -17,16 +17,7 @@ import { codec } from '@liskhq/lisk-codec'; import { when } from 'jest-when'; import { Mnemonic } from '@liskhq/lisk-passphrase'; import { InMemoryDatabase } from '@liskhq/lisk-db'; -import { - generatePrivateKey, - getAddressFromPassphrase, - getAddressFromPublicKey, - getPrivateAndPublicKeyFromPassphrase, - getPublicKeyFromPrivateKey, - getRandomBytes, - hash, - intToBuffer, -} from '@liskhq/lisk-cryptography'; +import { utils, address as cryptoAddress, bls, ed } from '@liskhq/lisk-cryptography'; import { ApplyPenaltyError } from '../../../../src/errors'; import { Consensus } from '../../../../src/engine/consensus/consensus'; import { NetworkEndpoint } from '../../../../src/engine/consensus/network_endpoint'; @@ -56,7 +47,7 @@ import { describe('consensus', () => { const genesis = (genesisBlock() as unknown) as Block; - const moduleIDs = [intToBuffer(2, 4)]; + const moduleIDs = [utils.intToBuffer(2, 4)]; let consensus: Consensus; let chain: Chain; let network: Network; @@ -245,9 +236,9 @@ describe('consensus', () => { describe('certifySingleCommit', () => { const passphrase = Mnemonic.generateMnemonic(256); - const address = getAddressFromPassphrase(passphrase); - const blsSK = generatePrivateKey(Buffer.from(passphrase, 'utf-8')); - const blsPK = getPublicKeyFromPrivateKey(blsSK); + const address = cryptoAddress.getAddressFromPassphrase(passphrase); + const blsSK = bls.generatePrivateKey(Buffer.from(passphrase, 'utf-8')); + const blsPK = bls.getPublicKeyFromPrivateKey(blsSK); const blockHeader = createFakeBlockHeader({ height: 303 }); beforeEach(async () => { @@ -875,10 +866,10 @@ describe('consensus', () => { it('should be success when valid signature', async () => { const passphrase = Mnemonic.generateMnemonic(); - const keyPair = getPrivateAndPublicKeyFromPassphrase(passphrase); + const keyPair = ed.getPrivateAndPublicKeyFromPassphrase(passphrase); const blockHeader = createFakeBlockHeader(); - (blockHeader as any).generatorAddress = address.getAddressFromPublicKey( + (blockHeader as any).generatorAddress = cryptoAddress.getAddressFromPublicKey( keyPair.publicKey, ); (consensus['_chain'] as any).networkIdentifier = defaultNetworkIdentifier; diff --git a/framework/test/unit/engine/consensus/network_endpoint.spec.ts b/framework/test/unit/engine/consensus/network_endpoint.spec.ts index d047b736867..7076eee9410 100644 --- a/framework/test/unit/engine/consensus/network_endpoint.spec.ts +++ b/framework/test/unit/engine/consensus/network_endpoint.spec.ts @@ -15,7 +15,7 @@ import { InMemoryDatabase, Database } from '@liskhq/lisk-db'; import { Block, Chain } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { NetworkEndpoint } from '../../../../src/engine/consensus/network_endpoint'; import { getBlocksFromIdRequestSchema, diff --git a/framework/test/unit/engine/consensus/synchronizer/block_synchronization_mechanism/block_synchronization_mechanism.spec.ts b/framework/test/unit/engine/consensus/synchronizer/block_synchronization_mechanism/block_synchronization_mechanism.spec.ts index 195df1395b5..fc6959c5b96 100644 --- a/framework/test/unit/engine/consensus/synchronizer/block_synchronization_mechanism/block_synchronization_mechanism.spec.ts +++ b/framework/test/unit/engine/consensus/synchronizer/block_synchronization_mechanism/block_synchronization_mechanism.spec.ts @@ -17,7 +17,7 @@ import { Block, Chain, BlockHeader } from '@liskhq/lisk-chain'; import { objects } from '@liskhq/lisk-utils'; import { InMemoryDatabase } from '@liskhq/lisk-db'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { BlockSynchronizationMechanism, Errors, diff --git a/framework/test/unit/engine/consensus/synchronizer/fast_chain_switching_mechanism/fast_chain_switching_mechanism.spec.ts b/framework/test/unit/engine/consensus/synchronizer/fast_chain_switching_mechanism/fast_chain_switching_mechanism.spec.ts index 58b510c863f..aa830bc36b5 100644 --- a/framework/test/unit/engine/consensus/synchronizer/fast_chain_switching_mechanism/fast_chain_switching_mechanism.spec.ts +++ b/framework/test/unit/engine/consensus/synchronizer/fast_chain_switching_mechanism/fast_chain_switching_mechanism.spec.ts @@ -15,7 +15,7 @@ import { when } from 'jest-when'; import { codec } from '@liskhq/lisk-codec'; import { Block, Chain } from '@liskhq/lisk-chain'; -import { getAddressFromPublicKey, getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils, address } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase } from '@liskhq/lisk-db'; import { FastChainSwitchingMechanism, diff --git a/framework/test/unit/engine/endpoint/chain.spec.ts b/framework/test/unit/engine/endpoint/chain.spec.ts index 5d016f2076a..d870e880807 100644 --- a/framework/test/unit/engine/endpoint/chain.spec.ts +++ b/framework/test/unit/engine/endpoint/chain.spec.ts @@ -13,7 +13,7 @@ */ import { Event, StateStore } from '@liskhq/lisk-chain'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase } from '@liskhq/lisk-db'; import { ChainEndpoint } from '../../../../src/engine/endpoint/chain'; import { createContext } from '../../../utils/mocks/endpoint'; diff --git a/framework/test/unit/engine/endpoint/system.spec.ts b/framework/test/unit/engine/endpoint/system.spec.ts index 81446021370..bf8a708a5fc 100644 --- a/framework/test/unit/engine/endpoint/system.spec.ts +++ b/framework/test/unit/engine/endpoint/system.spec.ts @@ -13,7 +13,7 @@ */ import { Block, BlockAssets } from '@liskhq/lisk-chain'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { TokenModule } from '../../../../src'; import { SystemEndpoint } from '../../../../src/engine/endpoint/system'; import { createFakeBlockHeader } from '../../../../src/testing'; diff --git a/framework/test/unit/engine/generator/endpoint.spec.ts b/framework/test/unit/engine/generator/endpoint.spec.ts index c643939bae9..74c2a8aa4a5 100644 --- a/framework/test/unit/engine/generator/endpoint.spec.ts +++ b/framework/test/unit/engine/generator/endpoint.spec.ts @@ -13,7 +13,7 @@ */ import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase, Database, Batch } from '@liskhq/lisk-db'; import { dataStructures } from '@liskhq/lisk-utils'; import { LiskValidationError } from '@liskhq/lisk-validator'; diff --git a/framework/test/unit/engine/generator/generator.spec.ts b/framework/test/unit/engine/generator/generator.spec.ts index 19e1edb728b..d1f81dfa4e4 100644 --- a/framework/test/unit/engine/generator/generator.spec.ts +++ b/framework/test/unit/engine/generator/generator.spec.ts @@ -13,16 +13,7 @@ */ import { EventEmitter } from 'events'; import { BlockAssets, Chain, Transaction } from '@liskhq/lisk-chain'; -import { - generatePrivateKey, - getAddressFromPassphrase, - getAddressFromPublicKey, - getPrivateAndPublicKeyFromPassphrase, - getPublicKeyFromPrivateKey, - getRandomBytes, - hash, - intToBuffer, -} from '@liskhq/lisk-cryptography'; +import { bls, utils, address as cryptoAddress, ed } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase, Database } from '@liskhq/lisk-db'; import { codec } from '@liskhq/lisk-codec'; import { when } from 'jest-when'; @@ -48,7 +39,7 @@ describe('generator', () => { 'c24ec443a9e0f18f67275dea31fa3083292e249db7347ac62958ff3ba9ab9b9b', 'hex', ), - address: address.getAddressFromPublicKey( + address: cryptoAddress.getAddressFromPublicKey( Buffer.from('c24ec443a9e0f18f67275dea31fa3083292e249db7347ac62958ff3ba9ab9b9b', 'hex'), ), encryptedPassphrase: @@ -59,7 +50,7 @@ describe('generator', () => { 'e2ab259cabe2b00f4f3760f3cdd989e09c2abb828150ddd2a30f004634c6d825', 'hex', ), - address: address.getAddressFromPublicKey( + address: cryptoAddress.getAddressFromPublicKey( Buffer.from('e2ab259cabe2b00f4f3760f3cdd989e09c2abb828150ddd2a30f004634c6d825', 'hex'), ), encryptedPassphrase: @@ -70,7 +61,7 @@ describe('generator', () => { 'fc1fa2e4f57f9e6d142328b12f17fd5739e44c07e4026bfb41dd877912511fa3', 'hex', ), - address: address.getAddressFromPublicKey( + address: cryptoAddress.getAddressFromPublicKey( Buffer.from('fc1fa2e4f57f9e6d142328b12f17fd5739e44c07e4026bfb41dd877912511fa3', 'hex'), ), encryptedPassphrase: @@ -205,7 +196,7 @@ describe('generator', () => { beforeEach(() => { accountDetails = { - address: address.getAddressFromPublicKey( + address: cryptoAddress.getAddressFromPublicKey( Buffer.from('75e99d6f2359ebaba661d0651c04f3d9cb8cd405d452e30af9f5d10e1cf732ed'), ), encryptedPassphrase: @@ -593,7 +584,7 @@ describe('generator', () => { height: 2, }); - expect(block.header.eventRoot).toEqual(hash(Buffer.alloc(0))); + expect(block.header.eventRoot).toEqual(utils.hash(Buffer.alloc(0))); }); it('should assign non empty eventRoot to the block when event exist', async () => { @@ -615,7 +606,7 @@ describe('generator', () => { height: 2, }); - expect(block.header.eventRoot).not.toEqual(hash(Buffer.alloc(0))); + expect(block.header.eventRoot).not.toEqual(utils.hash(Buffer.alloc(0))); }); it('should assign aggregateCommit to the block', async () => { @@ -632,12 +623,12 @@ describe('generator', () => { describe('events CONSENSUS_EVENT_FINALIZED_HEIGHT_CHANGED', () => { const passphrase = Mnemonic.generateMnemonic(256); - const address = getAddressFromPassphrase(passphrase); + const address = cryptoAddress.getAddressFromPassphrase(passphrase); const keypair = { - ...getPrivateAndPublicKeyFromPassphrase(passphrase), - blsSecretKey: generatePrivateKey(Buffer.from(passphrase, 'utf-8')), + ...ed.getPrivateAndPublicKeyFromPassphrase(passphrase), + blsSecretKey: bls.generatePrivateKey(Buffer.from(passphrase, 'utf-8')), }; - const blsPK = getPublicKeyFromPrivateKey(keypair.blsSecretKey); + const blsPK = bls.getPublicKeyFromPrivateKey(keypair.blsSecretKey); const blockHeader = createFakeBlockHeader(); beforeEach(async () => { diff --git a/framework/test/unit/engine/generator/strategies.spec.ts b/framework/test/unit/engine/generator/strategies.spec.ts index b972ac3fc15..fcd775e8a26 100644 --- a/framework/test/unit/engine/generator/strategies.spec.ts +++ b/framework/test/unit/engine/generator/strategies.spec.ts @@ -13,7 +13,7 @@ */ import { when } from 'jest-when'; -import { getAddressFromPublicKey, getRandomBytes, hash } from '@liskhq/lisk-cryptography'; +import { utils, address } from '@liskhq/lisk-cryptography'; import { dataStructures } from '@liskhq/lisk-utils'; import { BlockAssets, BlockHeader } from '@liskhq/lisk-chain'; import { HighFeeGenerationStrategy } from '../../../../src/engine/generator/strategies'; diff --git a/framework/test/unit/engine/network/network.spec.ts b/framework/test/unit/engine/network/network.spec.ts index c23580008fa..d74c86d71a6 100644 --- a/framework/test/unit/engine/network/network.spec.ts +++ b/framework/test/unit/engine/network/network.spec.ts @@ -14,7 +14,7 @@ import { InMemoryDatabase } from '@liskhq/lisk-db'; import { P2P } from '@liskhq/lisk-p2p'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Network } from '../../../../src/engine/network'; import { fakeLogger } from '../../../utils/mocks'; diff --git a/framework/test/unit/modules/auth/api.spec.ts b/framework/test/unit/modules/auth/api.spec.ts index aeb6f374035..2d90dbd30fe 100644 --- a/framework/test/unit/modules/auth/api.spec.ts +++ b/framework/test/unit/modules/auth/api.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { AuthAPI } from '../../../../src/modules/auth/api'; import { STORE_PREFIX_AUTH, MODULE_ID_AUTH_BUFFER } from '../../../../src/modules/auth/constants'; import { authAccountSchema } from '../../../../src/modules/auth/schemas'; diff --git a/framework/test/unit/modules/auth/auth_module.spec.ts b/framework/test/unit/modules/auth/auth_module.spec.ts index 904abbb655f..717c7933812 100644 --- a/framework/test/unit/modules/auth/auth_module.spec.ts +++ b/framework/test/unit/modules/auth/auth_module.spec.ts @@ -13,14 +13,7 @@ */ import { Mnemonic } from '@liskhq/lisk-passphrase'; import { codec } from '@liskhq/lisk-codec'; -import { - getRandomBytes, - getPrivateAndPublicKeyFromPassphrase, - hash, - getAddressFromPublicKey, - signDataWithPassphrase, - intToBuffer, -} from '@liskhq/lisk-cryptography'; +import { utils, ed, address as cryptoAddress } from '@liskhq/lisk-cryptography'; import { Transaction, transactionSchema, TAG_TRANSACTION, BlockAssets } from '@liskhq/lisk-chain'; import { objects as ObjectUtils } from '@liskhq/lisk-utils'; import { when } from 'jest-when'; @@ -84,8 +77,8 @@ describe('AuthModule', () => { }); passphrase = Mnemonic.generateMnemonic(); - passphraseDerivedKeys = getPrivateAndPublicKeyFromPassphrase(passphrase); - const address = address.getAddressFromPublicKey(passphraseDerivedKeys.publicKey); + passphraseDerivedKeys = ed.getPrivateAndPublicKeyFromPassphrase(passphrase); + const address = cryptoAddress.getAddressFromPublicKey(passphraseDerivedKeys.publicKey); when(subStoreMock) .calledWith(address, authAccountSchema) @@ -358,7 +351,7 @@ describe('AuthModule', () => { validTestTransaction = new Transaction(decodedMultiSignature); - const signature = signDataWithPassphrase( + const signature = ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getBytes(), @@ -413,7 +406,7 @@ describe('AuthModule', () => { signatures: [], }); - const signature = signDataWithPassphrase( + const signature = ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getBytes(), @@ -476,7 +469,7 @@ describe('AuthModule', () => { signatures: [], }); - const signature = signDataWithPassphrase( + const signature = ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getBytes(), @@ -539,8 +532,10 @@ describe('AuthModule', () => { }; for (const aMember of Object.values(members)) { - aMember.keys = { ...getPrivateAndPublicKeyFromPassphrase(aMember.passphrase) }; - aMember.address = address.getAddressFromPublicKey(aMember.keys.publicKey); + aMember.keys = { + ...ed.getPrivateAndPublicKeyFromPassphrase(aMember.passphrase), + }; + aMember.address = cryptoAddress.getAddressFromPublicKey(aMember.keys.publicKey); } const multisigAccount = { @@ -576,7 +571,7 @@ describe('AuthModule', () => { it('should not throw for valid transaction', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -585,7 +580,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -594,7 +589,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -634,7 +629,7 @@ describe('AuthModule', () => { }); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -661,7 +656,7 @@ describe('AuthModule', () => { it('should not throw for valid transaction when first optional is present', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -670,7 +665,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -679,7 +674,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -705,7 +700,7 @@ describe('AuthModule', () => { it('should not throw for valid transaction when second optional is present', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -714,7 +709,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -725,7 +720,7 @@ describe('AuthModule', () => { (transaction.signatures as any).push(Buffer.from('')); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -750,7 +745,7 @@ describe('AuthModule', () => { it('should throw for transaction where non optional absent signature is not empty buffer', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -759,7 +754,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -768,7 +763,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -796,7 +791,7 @@ describe('AuthModule', () => { it('should throw error if number of provided signatures is bigger than numberOfSignatures in account asset', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -805,7 +800,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -814,7 +809,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -823,7 +818,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -852,7 +847,7 @@ describe('AuthModule', () => { it('should throw error if number of provided signatures is smaller than numberOfSignatures in account asset', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -861,7 +856,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -892,7 +887,7 @@ describe('AuthModule', () => { it('should throw for transaction with valid numberOfSignatures but missing mandatory key signature', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -903,7 +898,7 @@ describe('AuthModule', () => { (transaction.signatures as any).push(Buffer.from('')); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -912,7 +907,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -937,7 +932,7 @@ describe('AuthModule', () => { it('should throw error if any of the mandatory signatures is not valid', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -946,7 +941,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -955,7 +950,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -982,7 +977,7 @@ describe('AuthModule', () => { it('should throw error if any of the optional signatures is not valid', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -991,7 +986,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -1002,7 +997,7 @@ describe('AuthModule', () => { (transaction.signatures as any).push(Buffer.from('')); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -1034,7 +1029,7 @@ describe('AuthModule', () => { it('should throw error if mandatory signatures are not in order', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -1043,7 +1038,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -1052,7 +1047,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -1083,7 +1078,7 @@ describe('AuthModule', () => { it('should throw error if optional signatures are not in order', async () => { // Arrange (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -1092,7 +1087,7 @@ describe('AuthModule', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -1103,7 +1098,7 @@ describe('AuthModule', () => { (transaction.signatures as any).push(Buffer.from('')); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -1135,7 +1130,7 @@ describe('AuthModule', () => { it('should correctly increment the nonce', async () => { const stateStore1 = new PrefixedStateReadWriter(new InMemoryPrefixedStateDB()); const authStore1 = stateStore1.getStore(authModule.id, STORE_PREFIX_AUTH); - const address = address.getAddressFromPublicKey(validTestTransaction.senderPublicKey); + const address = cryptoAddress.getAddressFromPublicKey(validTestTransaction.senderPublicKey); const authAccount1 = { nonce: validTestTransaction.nonce, numberOfSignatures: 5, diff --git a/framework/test/unit/modules/auth/endpoint.spec.ts b/framework/test/unit/modules/auth/endpoint.spec.ts index 2131dd09065..b1a2b5cc37e 100644 --- a/framework/test/unit/modules/auth/endpoint.spec.ts +++ b/framework/test/unit/modules/auth/endpoint.spec.ts @@ -1,12 +1,6 @@ import { NotFoundError, TAG_TRANSACTION, Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { - getAddressAndPublicKeyFromPassphrase, - getAddressFromPublicKey, - getRandomBytes, - intToBuffer, - signDataWithPassphrase, -} from '@liskhq/lisk-cryptography'; +import { ed, address as cryptoAddress, utils } from '@liskhq/lisk-cryptography'; import { when } from 'jest-when'; import { AuthModule } from '../../../../src/modules/auth'; import { AuthEndpoint } from '../../../../src/modules/auth/endpoint'; @@ -56,7 +50,9 @@ describe('AuthEndpoint', () => { }; for (const account of Object.values(accounts)) { - const { address, publicKey } = getAddressAndPublicKeyFromPassphrase(account.passphrase); + const { address, publicKey } = cryptoAddress.getAddressAndPublicKeyFromPassphrase( + account.passphrase, + ); account.address = address; account.publicKey = publicKey; } @@ -66,7 +62,7 @@ describe('AuthEndpoint', () => { const nonExistingSenderPublicKey = utils.getRandomBytes(32); const existingAddress = accounts.targetAccount.address as Buffer; - const nonExistingAddress = address.getAddressFromPublicKey(nonExistingSenderPublicKey); + const nonExistingAddress = cryptoAddress.getAddressFromPublicKey(nonExistingSenderPublicKey); const existingPassphrase = accounts.targetAccount.passphrase; @@ -160,7 +156,7 @@ describe('AuthEndpoint', () => { signatures: [], }); - const signature = signDataWithPassphrase( + const signature = ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getBytes(), @@ -207,7 +203,7 @@ describe('AuthEndpoint', () => { }); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -216,7 +212,7 @@ describe('AuthEndpoint', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -225,7 +221,7 @@ describe('AuthEndpoint', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -278,7 +274,7 @@ describe('AuthEndpoint', () => { }); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -287,7 +283,7 @@ describe('AuthEndpoint', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -296,7 +292,7 @@ describe('AuthEndpoint', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -305,7 +301,7 @@ describe('AuthEndpoint', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), @@ -314,7 +310,7 @@ describe('AuthEndpoint', () => { ); (transaction.signatures as any).push( - signDataWithPassphrase( + ed.signDataWithPassphrase( TAG_TRANSACTION, networkIdentifier, transaction.getSigningBytes(), diff --git a/framework/test/unit/modules/auth/register_multisignature.spec.ts b/framework/test/unit/modules/auth/register_multisignature.spec.ts index 15c4a9ccc5d..478f6da361a 100644 --- a/framework/test/unit/modules/auth/register_multisignature.spec.ts +++ b/framework/test/unit/modules/auth/register_multisignature.spec.ts @@ -14,7 +14,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import * as fixtures from './fixtures.json'; import * as testing from '../../../../src/testing'; import { RegisterMultisignatureCommand } from '../../../../src/modules/auth/commands/register_multisignature'; diff --git a/framework/test/unit/modules/bft/api.spec.ts b/framework/test/unit/modules/bft/api.spec.ts index 41bbb62ede4..22870deabec 100644 --- a/framework/test/unit/modules/bft/api.spec.ts +++ b/framework/test/unit/modules/bft/api.spec.ts @@ -14,7 +14,7 @@ import { NotFoundError, StateStore } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { BIG_ENDIAN, getRandomBytes, hash, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase } from '@liskhq/lisk-db'; import { BFTAPI } from '../../../../src/engine/bft/api'; import { @@ -178,7 +178,7 @@ describe('BFT API', () => { stateStore = new StateStore(new InMemoryDatabase()); const votesStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); await votesStore.setWithSchema( - intToBuffer(20, 4, BIG_ENDIAN), + utils.intToBuffer(20, 4), { prevoteThreshold: BigInt(68), precommitThreshold: BigInt(68), @@ -224,16 +224,8 @@ describe('BFT API', () => { beforeEach(async () => { stateStore = new StateStore(new InMemoryDatabase()); const votesStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); - await votesStore.setWithSchema( - utils.intToBuffer(20, 4, BIG_ENDIAN), - params20, - bftParametersSchema, - ); - await votesStore.setWithSchema( - utils.intToBuffer(30, 4, BIG_ENDIAN), - params30, - bftParametersSchema, - ); + await votesStore.setWithSchema(utils.intToBuffer(20, 4), params20, bftParametersSchema); + await votesStore.setWithSchema(utils.intToBuffer(30, 4), params30, bftParametersSchema); }); it('should return BFT parameters if it exists for the lower height', async () => { @@ -494,16 +486,8 @@ describe('BFT API', () => { beforeEach(async () => { stateStore = new StateStore(new InMemoryDatabase()); const votesStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); - await votesStore.setWithSchema( - utils.intToBuffer(20, 4, BIG_ENDIAN), - params20, - bftParametersSchema, - ); - await votesStore.setWithSchema( - utils.intToBuffer(30, 4, BIG_ENDIAN), - params30, - bftParametersSchema, - ); + await votesStore.setWithSchema(utils.intToBuffer(20, 4), params20, bftParametersSchema); + await votesStore.setWithSchema(utils.intToBuffer(30, 4), params30, bftParametersSchema); }); it('should return the next height strictly higher than the input where BFT parameter exists', async () => { @@ -542,16 +526,8 @@ describe('BFT API', () => { validatorsAPI.getValidatorAccount.mockResolvedValue({ blsKey: utils.getRandomBytes(32) }); stateStore = new StateStore(new InMemoryDatabase()); const paramsStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); - await paramsStore.setWithSchema( - intToBuffer(20, 4, BIG_ENDIAN), - params20, - bftParametersSchema, - ); - await paramsStore.setWithSchema( - intToBuffer(30, 4, BIG_ENDIAN), - params30, - bftParametersSchema, - ); + await paramsStore.setWithSchema(utils.intToBuffer(20, 4), params20, bftParametersSchema); + await paramsStore.setWithSchema(utils.intToBuffer(30, 4), params30, bftParametersSchema); const votesStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_VOTES); const addresses = [utils.getRandomBytes(20), utils.getRandomBytes(20)]; await votesStore.setWithSchema( @@ -755,17 +731,14 @@ describe('BFT API', () => { const paramsStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); await expect( - paramsStore.getWithSchema( - intToBuffer(105, 4, BIG_ENDIAN), - bftParametersSchema, - ), + paramsStore.getWithSchema(utils.intToBuffer(105, 4), bftParametersSchema), ).rejects.toThrow(NotFoundError); }); it('should store validators ordered lexicographically by address', async () => { const paramsStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); const params = await paramsStore.getWithSchema( - intToBuffer(104, 4, BIG_ENDIAN), + utils.intToBuffer(104, 4), bftParametersSchema, ); @@ -777,7 +750,7 @@ describe('BFT API', () => { it('should store validators in order of the input', async () => { const paramsStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); const params = await paramsStore.getWithSchema( - intToBuffer(104, 4, BIG_ENDIAN), + utils.intToBuffer(104, 4), bftParametersSchema, ); @@ -827,27 +800,21 @@ describe('BFT API', () => { const paramsStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); await expect( - paramsStore.getWithSchema( - intToBuffer(11, 4, BIG_ENDIAN), - bftParametersSchema, - ), + paramsStore.getWithSchema(utils.intToBuffer(11, 4), bftParametersSchema), ).toResolve(); }); it('should store BFT parameters with height latest blockBFTInfo + 1', async () => { const paramsStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); await expect( - paramsStore.getWithSchema( - intToBuffer(104, 4, BIG_ENDIAN), - bftParametersSchema, - ), + paramsStore.getWithSchema(utils.intToBuffer(104, 4), bftParametersSchema), ).toResolve(); }); it('should store new validators hash', async () => { const paramsStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_BFT_PARAMETERS); const params = await paramsStore.getWithSchema( - intToBuffer(104, 4, BIG_ENDIAN), + utils.intToBuffer(104, 4), bftParametersSchema, ); expect(params.validatorsHash).not.toEqual(params30.validatorsHash); @@ -903,7 +870,7 @@ describe('BFT API', () => { const sortedAccounts = [...accounts]; sortedAccounts.sort((a, b) => a.blsKey.compare(b.blsKey)); expect(validatorsHash).toEqual( - hash( + utils.hash( codec.encode(validatorsHashInputSchema, { activeValidators: [ { @@ -941,16 +908,8 @@ describe('BFT API', () => { beforeEach(async () => { stateStore = new StateStore(new InMemoryDatabase()); const keysStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_GENERATOR_KEYS); - await keysStore.setWithSchema( - utils.intToBuffer(20, 4, BIG_ENDIAN), - keys20, - generatorKeysSchema, - ); - await keysStore.setWithSchema( - utils.intToBuffer(30, 4, BIG_ENDIAN), - keys30, - generatorKeysSchema, - ); + await keysStore.setWithSchema(utils.intToBuffer(20, 4), keys20, generatorKeysSchema); + await keysStore.setWithSchema(utils.intToBuffer(30, 4), keys30, generatorKeysSchema); }); it('should current generators', async () => { @@ -1054,7 +1013,7 @@ describe('BFT API', () => { bftAPI.setGeneratorKeys(stateStore, createKeys().generators), ).resolves.toBeUndefined(); const keysStore = stateStore.getStore(bftAPI['moduleID'], STORE_PREFIX_GENERATOR_KEYS); - await expect(keysStore.has(utils.intToBuffer(36, 4, BIG_ENDIAN))).resolves.toBeTrue(); + await expect(keysStore.has(utils.intToBuffer(36, 4))).resolves.toBeTrue(); }); }); }); diff --git a/framework/test/unit/modules/bft/bft_params.spec.ts b/framework/test/unit/modules/bft/bft_params.spec.ts index d08f6575943..8c6a568813e 100644 --- a/framework/test/unit/modules/bft/bft_params.spec.ts +++ b/framework/test/unit/modules/bft/bft_params.spec.ts @@ -14,7 +14,7 @@ import { StateStore } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { BIG_ENDIAN, getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase, Database, Batch } from '@liskhq/lisk-db'; import { MODULE_ID_BFT_BUFFER, @@ -39,7 +39,7 @@ describe('BFT parameters', () => { db = new InMemoryDatabase() as never; const rootStore = new StateStore(db); const paramsStore = rootStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); - const height1Bytes = utils.intToBuffer(309, 4, BIG_ENDIAN); + const height1Bytes = utils.intToBuffer(309, 4); bftParams1 = { prevoteThreshold: BigInt(20), precommitThreshold: BigInt(30), @@ -54,7 +54,7 @@ describe('BFT parameters', () => { validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height1Bytes, codec.encode(bftParametersSchema, bftParams1)); - const height2Bytes = utils.intToBuffer(515, 4, BIG_ENDIAN); + const height2Bytes = utils.intToBuffer(515, 4); bftParams2 = { prevoteThreshold: BigInt(40), precommitThreshold: BigInt(50), @@ -105,7 +105,7 @@ describe('BFT parameters', () => { db = new InMemoryDatabase() as never; const rootStore = new StateStore(db); const paramsStore = rootStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); - const height1Bytes = utils.intToBuffer(309, 4, BIG_ENDIAN); + const height1Bytes = utils.intToBuffer(309, 4); bftParams1 = { prevoteThreshold: BigInt(20), precommitThreshold: BigInt(30), @@ -120,7 +120,7 @@ describe('BFT parameters', () => { validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height1Bytes, codec.encode(bftParametersSchema, bftParams1)); - const height2Bytes = utils.intToBuffer(515, 4, BIG_ENDIAN); + const height2Bytes = utils.intToBuffer(515, 4); bftParams2 = { prevoteThreshold: BigInt(40), precommitThreshold: BigInt(50), @@ -156,7 +156,7 @@ describe('BFT parameters', () => { await deleteBFTParameters(paramsStore, 515); expect(paramsStore.del).toHaveBeenCalledTimes(1); - expect(paramsStore.del).toHaveBeenCalledWith(utils.intToBuffer(309, 4, BIG_ENDIAN)); + expect(paramsStore.del).toHaveBeenCalledWith(utils.intToBuffer(309, 4)); }); }); @@ -168,7 +168,7 @@ describe('BFT parameters', () => { db = new InMemoryDatabase() as never; const rootStore = new StateStore(db); const paramsStore = rootStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); - const height1Bytes = utils.intToBuffer(104, 4, BIG_ENDIAN); + const height1Bytes = utils.intToBuffer(104, 4); const bftParams1 = { prevoteThreshold: BigInt(20), precommitThreshold: BigInt(30), @@ -183,7 +183,7 @@ describe('BFT parameters', () => { validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height1Bytes, codec.encode(bftParametersSchema, bftParams1)); - const height2Bytes = utils.intToBuffer(207, 4, BIG_ENDIAN); + const height2Bytes = utils.intToBuffer(207, 4); const bftParams2 = { prevoteThreshold: BigInt(40), precommitThreshold: BigInt(50), @@ -198,7 +198,7 @@ describe('BFT parameters', () => { validatorsHash: utils.getRandomBytes(32), }; await paramsStore.set(height2Bytes, codec.encode(bftParametersSchema, bftParams2)); - const height3Bytes = utils.intToBuffer(310, 4, BIG_ENDIAN); + const height3Bytes = utils.intToBuffer(310, 4); const bftParams3 = { prevoteThreshold: BigInt(40), precommitThreshold: BigInt(50), diff --git a/framework/test/unit/modules/bft/bft_processing.spec.ts b/framework/test/unit/modules/bft/bft_processing.spec.ts index 05d1ba6275e..120aecc942e 100644 --- a/framework/test/unit/modules/bft/bft_processing.spec.ts +++ b/framework/test/unit/modules/bft/bft_processing.spec.ts @@ -13,12 +13,7 @@ */ /* eslint-disable no-loop-func */ import { BlockHeader, StateStore } from '@liskhq/lisk-chain'; -import { - BIG_ENDIAN, - getAddressFromPublicKey, - getRandomBytes, - intToBuffer, -} from '@liskhq/lisk-cryptography'; +import { utils, address } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase } from '@liskhq/lisk-db'; import { BFTModule } from '../../../../src/engine/bft'; import { @@ -74,7 +69,7 @@ describe('BFT processing', () => { } } await paramsStore.setWithSchema( - intToBuffer(1, 4, BIG_ENDIAN), + utils.intToBuffer(1, 4), { prevoteThreshold: BigInt(threshold), precommitThreshold: BigInt(threshold), diff --git a/framework/test/unit/modules/bft/bft_votes.spec.ts b/framework/test/unit/modules/bft/bft_votes.spec.ts index 831125a9e6c..1f2db98b2a3 100644 --- a/framework/test/unit/modules/bft/bft_votes.spec.ts +++ b/framework/test/unit/modules/bft/bft_votes.spec.ts @@ -13,7 +13,7 @@ */ import { StateStore } from '@liskhq/lisk-chain'; -import { BIG_ENDIAN, getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase } from '@liskhq/lisk-db'; import { objects } from '@liskhq/lisk-utils'; import { BFTParametersCache } from '../../../../src/engine/bft/bft_params'; @@ -191,7 +191,7 @@ describe('BFT votes', () => { const stateStore = new StateStore(new InMemoryDatabase()); const paramsStore = stateStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); await paramsStore.setWithSchema( - intToBuffer(101, 4, BIG_ENDIAN), + utils.intToBuffer(101, 4), { prevoteThreshold: BigInt(68), precommitThreshold: BigInt(68), @@ -335,7 +335,7 @@ describe('BFT votes', () => { const stateStore = new StateStore(new InMemoryDatabase()); const paramsStore = stateStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); await paramsStore.setWithSchema( - intToBuffer(101, 4, BIG_ENDIAN), + utils.intToBuffer(101, 4), { prevoteThreshold: BigInt(68), precommitThreshold: BigInt(68), @@ -367,7 +367,7 @@ describe('BFT votes', () => { const stateStore = new StateStore(new InMemoryDatabase()); const paramsStore = stateStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); await paramsStore.setWithSchema( - intToBuffer(101, 4, BIG_ENDIAN), + utils.intToBuffer(101, 4), { prevoteThreshold: BigInt(103), precommitThreshold: BigInt(68), @@ -403,7 +403,7 @@ describe('BFT votes', () => { const stateStore = new StateStore(new InMemoryDatabase()); const paramsStore = stateStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); await paramsStore.setWithSchema( - intToBuffer(101, 4, BIG_ENDIAN), + utils.intToBuffer(101, 4), { prevoteThreshold: BigInt(68), precommitThreshold: BigInt(67), @@ -435,7 +435,7 @@ describe('BFT votes', () => { const stateStore = new StateStore(new InMemoryDatabase()); const paramsStore = stateStore.getStore(MODULE_ID_BFT_BUFFER, STORE_PREFIX_BFT_PARAMETERS); await paramsStore.setWithSchema( - intToBuffer(101, 4, BIG_ENDIAN), + utils.intToBuffer(101, 4), { prevoteThreshold: BigInt(68), precommitThreshold: BigInt(103), diff --git a/framework/test/unit/modules/bft/utils.spec.ts b/framework/test/unit/modules/bft/utils.spec.ts index c9522dd4b46..49880eb7d48 100644 --- a/framework/test/unit/modules/bft/utils.spec.ts +++ b/framework/test/unit/modules/bft/utils.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { createFakeBlockHeader } from '../../../../src/testing'; import { areDistinctHeadersContradicting, diff --git a/framework/test/unit/modules/dpos_v2/api.spec.ts b/framework/test/unit/modules/dpos_v2/api.spec.ts index fe3daa2b32e..fa5aaf19f5d 100644 --- a/framework/test/unit/modules/dpos_v2/api.spec.ts +++ b/framework/test/unit/modules/dpos_v2/api.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { DPoSAPI } from '../../../../src/modules/dpos_v2/api'; import { MODULE_ID_DPOS_BUFFER, diff --git a/framework/test/unit/modules/dpos_v2/commands/pom.spec.ts b/framework/test/unit/modules/dpos_v2/commands/pom.spec.ts index 18e904ac699..65da5487809 100644 --- a/framework/test/unit/modules/dpos_v2/commands/pom.spec.ts +++ b/framework/test/unit/modules/dpos_v2/commands/pom.spec.ts @@ -15,12 +15,7 @@ import { when } from 'jest-when'; import { BlockHeader, blockHeaderSchema, Transaction } from '@liskhq/lisk-chain'; import { objects } from '@liskhq/lisk-utils'; -import { - getAddressAndPublicKeyFromPassphrase, - getAddressFromPublicKey, - getRandomBytes, - intToBuffer, -} from '@liskhq/lisk-cryptography'; +import { address, utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { ReportDelegateMisbehaviorCommand } from '../../../../../src/modules/dpos_v2/commands/pom'; import * as testing from '../../../../../src/testing'; @@ -67,7 +62,7 @@ describe('ReportDelegateMisbehaviorCommand', () => { const { address: delegate1Address, publicKey: delegate1PublicKey, - } = getAddressAndPublicKeyFromPassphrase(utils.getRandomBytes(20).toString('utf8')); + } = address.getAddressAndPublicKeyFromPassphrase(utils.getRandomBytes(20).toString('utf8')); const defaultDelegateInfo = { totalVotesReceived: BigInt(100000000), selfVotes: BigInt(0), diff --git a/framework/test/unit/modules/dpos_v2/commands/vote.spec.ts b/framework/test/unit/modules/dpos_v2/commands/vote.spec.ts index c73ca37288c..0a0f16052e2 100644 --- a/framework/test/unit/modules/dpos_v2/commands/vote.spec.ts +++ b/framework/test/unit/modules/dpos_v2/commands/vote.spec.ts @@ -14,7 +14,7 @@ import { NotFoundError, StateStore, Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { getAddressFromPublicKey, getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { address, utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase } from '@liskhq/lisk-db'; import { validator } from '@liskhq/lisk-validator'; import { when } from 'jest-when'; diff --git a/framework/test/unit/modules/dpos_v2/endpoint.spec.ts b/framework/test/unit/modules/dpos_v2/endpoint.spec.ts index a98030b7a82..8a64dfa2c25 100644 --- a/framework/test/unit/modules/dpos_v2/endpoint.spec.ts +++ b/framework/test/unit/modules/dpos_v2/endpoint.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { Logger } from '../../../../src/logger'; import { diff --git a/framework/test/unit/modules/dpos_v2/genesis_block_test_data.ts b/framework/test/unit/modules/dpos_v2/genesis_block_test_data.ts index 84d4ee75d3e..6d1aaf42725 100644 --- a/framework/test/unit/modules/dpos_v2/genesis_block_test_data.ts +++ b/framework/test/unit/modules/dpos_v2/genesis_block_test_data.ts @@ -11,22 +11,16 @@ * * Removal or modification of this copyright notice is prohibited. */ -import { - getPublicKeyFromPrivateKey, - generatePrivateKey, - blsPopProve, - getKeys, - getAddressFromPublicKey, -} from '@liskhq/lisk-cryptography'; +import { bls, address as cryptoAddress, ed } from '@liskhq/lisk-cryptography'; import { Mnemonic } from '@liskhq/lisk-passphrase'; export const validators = new Array(120).fill(0).map((_, i) => { const passphrase = Mnemonic.generateMnemonic(); - const keys = getKeys(passphrase); - const address = address.getAddressFromPublicKey(keys.publicKey); - const blsPrivateKey = generatePrivateKey(Buffer.from(passphrase, 'utf-8')); - const blsPublicKey = getPublicKeyFromPrivateKey(blsPrivateKey); - const blsPoP = blsPopProve(blsPrivateKey); + const keys = ed.getKeys(passphrase); + const address = cryptoAddress.getAddressFromPublicKey(keys.publicKey); + const blsPrivateKey = bls.generatePrivateKey(Buffer.from(passphrase, 'utf-8')); + const blsPublicKey = bls.getPublicKeyFromPrivateKey(blsPrivateKey); + const blsPoP = bls.popProve(blsPrivateKey); return { address, name: `genesis_${i}`, diff --git a/framework/test/unit/modules/dpos_v2/module.spec.ts b/framework/test/unit/modules/dpos_v2/module.spec.ts index 5e05d469cdc..02e43641121 100644 --- a/framework/test/unit/modules/dpos_v2/module.spec.ts +++ b/framework/test/unit/modules/dpos_v2/module.spec.ts @@ -374,7 +374,7 @@ describe('DPoS module', () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(11 + 2, 4), + utils.intToBuffer(11 + 2, 4), snapshotStoreSchema, ); @@ -417,7 +417,7 @@ describe('DPoS module', () => { it('should create a snapshot which include top 101 delegates as active delegates', async () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(11 + 2, 4), + utils.intToBuffer(11 + 2, 4), snapshotStoreSchema, ); @@ -427,7 +427,7 @@ describe('DPoS module', () => { it('should create a snapshot which include all delegates in the snapshot', async () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(11 + 2, 4), + utils.intToBuffer(11 + 2, 4), snapshotStoreSchema, ); @@ -469,7 +469,7 @@ describe('DPoS module', () => { it('should create a snapshot which include top 101 delegates as active delegates', async () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(11 + 2, 4), + utils.intToBuffer(11 + 2, 4), snapshotStoreSchema, ); @@ -479,7 +479,7 @@ describe('DPoS module', () => { it('should create a snapshot which include all delegates in the snapshot', async () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(11 + 2, 4), + utils.intToBuffer(11 + 2, 4), snapshotStoreSchema, ); @@ -549,7 +549,7 @@ describe('DPoS module', () => { it('should create a snapshot which include top 101 delegates as active delegates', async () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(11 + 2, 4), + utils.intToBuffer(11 + 2, 4), snapshotStoreSchema, ); @@ -559,7 +559,7 @@ describe('DPoS module', () => { it('should cap the delegate weight', async () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(11 + 2, 4), + utils.intToBuffer(11 + 2, 4), snapshotStoreSchema, ); @@ -576,7 +576,7 @@ describe('DPoS module', () => { it('should set the delegate weight to zero when punished', async () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(11 + 2, 4), + utils.intToBuffer(11 + 2, 4), snapshotStoreSchema, ); @@ -669,7 +669,7 @@ describe('DPoS module', () => { it('should create a snapshot which include top 101 delegates as active delegates', async () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(11 + 2, 4), + utils.intToBuffer(11 + 2, 4), snapshotStoreSchema, ); @@ -679,7 +679,7 @@ describe('DPoS module', () => { it('should create a snapshot which include all delegates above standby threshold in the snapshot', async () => { const snapshotStore = stateStore.getStore(dpos.id, STORE_PREFIX_SNAPSHOT); const snapshot = await snapshotStore.getWithSchema( - intToBuffer(11 + 2, 4), + utils.intToBuffer(11 + 2, 4), snapshotStoreSchema, ); @@ -752,7 +752,7 @@ describe('DPoS module', () => { .slice(0, defaultConfigs.numberActiveDelegates) .map(d => d.delegateAddress); await snapshotStore.setWithSchema( - intToBuffer(defaultRound, 4), + utils.intToBuffer(defaultRound, 4), { activeDelegates, delegateWeightSnapshot: delegates.slice(defaultConfigs.numberActiveDelegates), @@ -833,7 +833,7 @@ describe('DPoS module', () => { .slice(0, defaultConfigs.numberActiveDelegates) .map(d => d.delegateAddress); await snapshotStore.setWithSchema( - intToBuffer(defaultRound, 4), + utils.intToBuffer(defaultRound, 4), { activeDelegates, delegateWeightSnapshot: delegates.slice(defaultConfigs.numberActiveDelegates), diff --git a/framework/test/unit/modules/fee/fee_module.spec.ts b/framework/test/unit/modules/fee/fee_module.spec.ts index 58a1d14338a..b3606a14cf9 100644 --- a/framework/test/unit/modules/fee/fee_module.spec.ts +++ b/framework/test/unit/modules/fee/fee_module.spec.ts @@ -13,7 +13,7 @@ */ import { Transaction } from '@liskhq/lisk-chain'; -import { getAddressFromPublicKey, getRandomBytes, intToBuffer } from '@liskhq/lisk-cryptography'; +import { address, utils } from '@liskhq/lisk-cryptography'; import { FeeModule } from '../../../../src/modules/fee'; import { VerifyStatus } from '../../../../src/state_machine'; import { createTransactionContext } from '../../../../src/testing'; diff --git a/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts b/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts index 92562b72629..fa00ddc3f07 100644 --- a/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/cc_commands/channel_terminated.spec.ts @@ -48,7 +48,7 @@ describe('MainchainCCChannelTerminatedCommand', () => { }); const ccChannelTerminatedCommand = new MainchainCCChannelTerminatedCommand( - intToBuffer(1, 4), + utils.intToBuffer(1, 4), ccAPIsMap, ); const mainchainInteroperabilityStore = new MainchainInteroperabilityStore( diff --git a/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts b/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts index a2467c2170b..43a0e3b9ea3 100644 --- a/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/cc_commands/sidechain_terminated.spec.ts @@ -89,7 +89,7 @@ describe('MainchainCCSidechainTerminatedCommand', () => { mainchainInteroperabilityStore.createTerminatedStateAccount = createTerminatedStateAccountMock; ccSidechainTerminatedCommand = new MainchainCCSidechainTerminatedCommand( - intToBuffer(1, 4), + utils.intToBuffer(1, 4), ccAPIsMap, ); (ccSidechainTerminatedCommand as any)['getInteroperabilityStore'] = jest diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/cc_update.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/cc_update.spec.ts index c1dc2d462f6..9eedc22bb96 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/cc_update.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/cc_update.spec.ts @@ -244,7 +244,7 @@ describe('CrossChainUpdateCommand', () => { jest.spyOn(MainchainInteroperabilityStore.prototype, 'isLive').mockResolvedValue(true); jest.spyOn(interopUtils, 'computeValidatorsHash').mockReturnValue(validatorsHash); - jest.spyOn(cryptography, 'verifyWeightedAggSig').mockReturnValue(true); + jest.spyOn(cryptography.bls, 'verifyWeightedAggSig').mockReturnValue(true); }); describe('verify', () => { diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/message_recovery.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/message_recovery.spec.ts index 075044257ca..cc4fef63f42 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/message_recovery.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/message_recovery.spec.ts @@ -15,7 +15,7 @@ import { when } from 'jest-when'; import { codec } from '@liskhq/lisk-codec'; import { Transaction } from '@liskhq/lisk-chain'; -import { getRandomBytes, hash, intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { MerkleTree, regularMerkleTree } from '@liskhq/lisk-tree'; import { CommandExecuteContext } from '../../../../../../src'; import { BaseCCCommand } from '../../../../../../src/modules/interoperability/base_cc_command'; diff --git a/framework/test/unit/modules/interoperability/mainchain/commands/sidechain_registration.spec.ts b/framework/test/unit/modules/interoperability/mainchain/commands/sidechain_registration.spec.ts index 9079f354bfa..ffb9579f333 100644 --- a/framework/test/unit/modules/interoperability/mainchain/commands/sidechain_registration.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/commands/sidechain_registration.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { hash, intToBuffer, getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; import { when } from 'jest-when'; diff --git a/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts b/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts index 1cb44c919eb..00388662cbe 100644 --- a/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts +++ b/framework/test/unit/modules/interoperability/mainchain/endpoint.spec.ts @@ -12,13 +12,13 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { MainchainInteroperabilityEndpoint } from '../../../../../src/modules/interoperability/mainchain/endpoint'; import { MainchainInteroperabilityStore } from '../../../../../src/modules/interoperability/mainchain/store'; describe('Mainchain endpoint', () => { - const moduleID = intToBuffer(1, 4); - const chainID = intToBuffer(1, 4); + const moduleID = utils.intToBuffer(1, 4); + const chainID = utils.intToBuffer(1, 4); const interoperableCCAPIs = new Map(); const getStore = jest.fn().mockReturnValue({ getWithSchema: jest.fn() }); diff --git a/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts b/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts index f77843860bd..b7769817ff8 100644 --- a/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/cc_commands/channel_terminated.spec.ts @@ -49,7 +49,7 @@ describe('SidechainCCChannelTerminatedCommand', () => { }); const ccChannelTerminatedCommand = new SidechainCCChannelTerminatedCommand( - intToBuffer(1, 4), + utils.intToBuffer(1, 4), ccAPIsMap, ); const mainchainInteroperabilityStore = new SidechainInteroperabilityStore( diff --git a/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts b/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts index 187f06c65a7..9ffdf366e18 100644 --- a/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/cc_commands/sidechain_terminated.spec.ts @@ -89,7 +89,7 @@ describe('SidechainCCSidechainTerminatedCommand', () => { mainchainInteroperabilityStore.createTerminatedStateAccount = createTerminatedStateAccountMock; ccSidechainTerminatedCommand = new SidechainCCSidechainTerminatedCommand( - intToBuffer(1, 4), + utils.intToBuffer(1, 4), ccAPIsMap, ); (ccSidechainTerminatedCommand as any)['getInteroperabilityStore'] = jest diff --git a/framework/test/unit/modules/interoperability/sidechain/commands/cc_update.spec.ts b/framework/test/unit/modules/interoperability/sidechain/commands/cc_update.spec.ts index 6f68912c05c..dbb83232100 100644 --- a/framework/test/unit/modules/interoperability/sidechain/commands/cc_update.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/commands/cc_update.spec.ts @@ -242,7 +242,7 @@ describe('CrossChainUpdateCommand', () => { jest.spyOn(SidechainInteroperabilityStore.prototype, 'isLive').mockResolvedValue(true); jest.spyOn(interopUtils, 'computeValidatorsHash').mockReturnValue(validatorsHash); - jest.spyOn(cryptography, 'verifyWeightedAggSig').mockReturnValue(true); + jest.spyOn(cryptography.bls, 'verifyWeightedAggSig').mockReturnValue(true); }); describe('verify', () => { diff --git a/framework/test/unit/modules/interoperability/sidechain/commands/mainchain_registration.spec.ts b/framework/test/unit/modules/interoperability/sidechain/commands/mainchain_registration.spec.ts index 9f7dcfb2c66..2575f65600a 100644 --- a/framework/test/unit/modules/interoperability/sidechain/commands/mainchain_registration.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/commands/mainchain_registration.spec.ts @@ -69,7 +69,6 @@ jest.mock('@liskhq/lisk-cryptography', () => ({ })); describe('Mainchain registration command', () => { - const { getRandomBytes } = crypto; const unsortedMainchainValidators: ActiveValidators[] = []; for (let i = 0; i < NUMBER_MAINCHAIN_VALIDATORS; i += 1) { unsortedMainchainValidators.push({ blsKey: utils.getRandomBytes(48), bftWeight: BigInt(1) }); @@ -313,13 +312,13 @@ describe('Mainchain registration command', () => { const keyList = [validatorAccounts[0].blsKey, validatorAccounts[1].blsKey]; const weights = [validatorAccounts[0].bftWeight, validatorAccounts[1].bftWeight]; - jest.spyOn(crypto, 'verifyWeightedAggSig'); + jest.spyOn(crypto.bls, 'verifyWeightedAggSig'); // Act await mainchainRegistrationCommand.execute(context); // Assert - expect(crypto.verifyWeightedAggSig).toHaveBeenCalledWith( + expect(crypto.bls.verifyWeightedAggSig).toHaveBeenCalledWith( keyList, params.aggregationBits, params.signature, diff --git a/framework/test/unit/modules/interoperability/sidechain/endpoint.spec.ts b/framework/test/unit/modules/interoperability/sidechain/endpoint.spec.ts index 7d3e5a509ee..041c569f54c 100644 --- a/framework/test/unit/modules/interoperability/sidechain/endpoint.spec.ts +++ b/framework/test/unit/modules/interoperability/sidechain/endpoint.spec.ts @@ -12,13 +12,13 @@ * Removal or modification of this copyright notice is prohibited. */ -import { intToBuffer } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { SidechainInteroperabilityEndpoint } from '../../../../../src/modules/interoperability/sidechain/endpoint'; import { SidechainInteroperabilityStore } from '../../../../../src/modules/interoperability/sidechain/store'; describe('Sidechain endpoint', () => { - const moduleID = intToBuffer(1, 4); - const chainID = intToBuffer(1, 4); + const moduleID = utils.intToBuffer(1, 4); + const chainID = utils.intToBuffer(1, 4); const interoperableCCAPIs = new Map(); const getStore = jest.fn().mockReturnValue({ getWithSchema: jest.fn() }); diff --git a/framework/test/unit/modules/interoperability/utils.spec.ts b/framework/test/unit/modules/interoperability/utils.spec.ts index 291b9abf7ad..3ce13dec7fc 100644 --- a/framework/test/unit/modules/interoperability/utils.spec.ts +++ b/framework/test/unit/modules/interoperability/utils.spec.ts @@ -360,7 +360,7 @@ describe('Utils', () => { const partnerChainAccount: any = { networkID: cryptography.utils.getRandomBytes(32) }; it('should return VerifyStatus.OK if certificate is empty', () => { - jest.spyOn(cryptography, 'verifyWeightedAggSig').mockReturnValue(true); + jest.spyOn(cryptography.bls, 'verifyWeightedAggSig').mockReturnValue(true); const { status, error } = verifyCertificateSignature( txParamsWithEmptyCertificate, partnerValidators, @@ -369,11 +369,11 @@ describe('Utils', () => { expect(status).toEqual(VerifyStatus.OK); expect(error?.message).toBeUndefined(); - expect(cryptography.verifyWeightedAggSig).not.toHaveBeenCalled(); + expect(cryptography.bls.verifyWeightedAggSig).not.toHaveBeenCalled(); }); it('should return VerifyStatus.FAIL when certificate signature verification fails', () => { - jest.spyOn(cryptography, 'verifyWeightedAggSig').mockReturnValue(false); + jest.spyOn(cryptography.bls, 'verifyWeightedAggSig').mockReturnValue(false); const { status, error } = verifyCertificateSignature( txParams, partnerValidators, @@ -382,11 +382,11 @@ describe('Utils', () => { expect(status).toEqual(VerifyStatus.FAIL); expect(error?.message).toEqual('Certificate is invalid due to invalid signature.'); - expect(cryptography.verifyWeightedAggSig).toHaveBeenCalledTimes(1); + expect(cryptography.bls.verifyWeightedAggSig).toHaveBeenCalledTimes(1); }); it('should return VerifyStatus.OK when certificate signature verification passes', () => { - jest.spyOn(cryptography, 'verifyWeightedAggSig').mockReturnValue(true); + jest.spyOn(cryptography.bls, 'verifyWeightedAggSig').mockReturnValue(true); const { status, error } = verifyCertificateSignature( txParams, @@ -396,7 +396,7 @@ describe('Utils', () => { expect(status).toEqual(VerifyStatus.OK); expect(error).toBeUndefined(); - expect(cryptography.verifyWeightedAggSig).toHaveBeenCalledTimes(1); + expect(cryptography.bls.verifyWeightedAggSig).toHaveBeenCalledTimes(1); }); }); diff --git a/framework/test/unit/modules/random/api.spec.ts b/framework/test/unit/modules/random/api.spec.ts index 873fa49cf0a..8cfe927b90f 100644 --- a/framework/test/unit/modules/random/api.spec.ts +++ b/framework/test/unit/modules/random/api.spec.ts @@ -36,7 +36,7 @@ import { testCases } from './dpos_random_seed_generation/dpos_random_seed_genera import * as randomSeedsMultipleRounds from '../../../fixtures/dpos_random_seed_generation/dpos_random_seed_generation_other_rounds.json'; const strippedHashOfIntegerBuffer = (num: number) => - cryptography.hash(utils.intToBuffer(num, 4)).slice(0, SEED_REVEAL_HASH_SIZE); + cryptography.utils.hash(utils.intToBuffer(num, 4)).slice(0, SEED_REVEAL_HASH_SIZE); describe('RandomModuleAPI', () => { let randomAPI: RandomAPI; @@ -213,7 +213,7 @@ describe('RandomModuleAPI', () => { const numberOfSeeds = 2; // Create a buffer from height + numberOfSeeds - await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).rejects.toThrow( + await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).rejects.toThrow( 'Height or number of seeds cannot be negative.', ); }); @@ -223,7 +223,7 @@ describe('RandomModuleAPI', () => { const numberOfSeeds = -2; // Create a buffer from height + numberOfSeeds - await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).rejects.toThrow( + await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).rejects.toThrow( 'Height or number of seeds cannot be negative.', ); }); @@ -244,7 +244,7 @@ describe('RandomModuleAPI', () => { hashesExpected[1], ]); - await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( xorExpected, ); }); @@ -266,7 +266,7 @@ describe('RandomModuleAPI', () => { hashesExpected[2], ]); - await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( xorExpected, ); }); @@ -288,7 +288,7 @@ describe('RandomModuleAPI', () => { hashesExpected[2], ]); - await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( xorExpected, ); }); @@ -305,7 +305,7 @@ describe('RandomModuleAPI', () => { // Do XOR of randomSeed with hashes of seed reveal with height >= randomStoreValidator.height >= height + numberOfSeeds const xorExpected = bitwiseXOR([randomSeed, hashesExpected[0]]); - await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( xorExpected, ); }); @@ -316,7 +316,7 @@ describe('RandomModuleAPI', () => { // Create a buffer from height + numberOfSeeds const randomSeed = strippedHashOfIntegerBuffer(height + numberOfSeeds); - await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( randomSeed, ); }); @@ -327,7 +327,7 @@ describe('RandomModuleAPI', () => { // Create a buffer from height + numberOfSeeds const randomSeed = strippedHashOfIntegerBuffer(height + numberOfSeeds); - await expect(randomAPI.utils.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( + await expect(randomAPI.getRandomBytes(context, height, numberOfSeeds)).resolves.toEqual( randomSeed, ); }); @@ -380,7 +380,7 @@ describe('RandomModuleAPI', () => { const endOfLastRound = startOfRound - 1; const startOfLastRound = endOfLastRound - config.blocksPerRound + 1; // Act - const randomSeed1 = await randomAPI.utils.getRandomBytes( + const randomSeed1 = await randomAPI.getRandomBytes( context, heightForSeed1, round === 2 ? middleThreshold : middleThreshold * 2, @@ -389,7 +389,7 @@ describe('RandomModuleAPI', () => { const randomSeed2 = round === 2 ? strippedHashOfIntegerBuffer(endOfLastRound) - : await randomAPI.utils.getRandomBytes(context, startOfLastRound, middleThreshold * 2); + : await randomAPI.getRandomBytes(context, startOfLastRound, middleThreshold * 2); // Assert expect(randomSeed1.toString('hex')).toEqual(output.randomSeed1); expect(randomSeed2.toString('hex')).toEqual(output.randomSeed2); diff --git a/framework/test/unit/modules/random/endpoint.spec.ts b/framework/test/unit/modules/random/endpoint.spec.ts index a9d98842813..54cb88e25a2 100644 --- a/framework/test/unit/modules/random/endpoint.spec.ts +++ b/framework/test/unit/modules/random/endpoint.spec.ts @@ -79,7 +79,7 @@ describe('RandomModuleEndpoint', () => { // Arrange const address = ['address']; const seed = genesisDelegates.delegates[0].hashOnion.hashes[1]; - const hashes = cryptography.hashOnion( + const hashes = cryptography.utils.hashOnion( Buffer.from(seed, 'hex'), genesisDelegates.delegates[0].hashOnion.distance, 1, @@ -107,7 +107,7 @@ describe('RandomModuleEndpoint', () => { // Arrange const { address } = genesisDelegates.delegates[0]; const seed = genesisDelegates.delegates[0].hashOnion.hashes[1]; - const hashes = cryptography.hashOnion( + const hashes = cryptography.utils.hashOnion( Buffer.from(seed, 'hex'), genesisDelegates.delegates[0].hashOnion.distance, 1, @@ -124,7 +124,7 @@ describe('RandomModuleEndpoint', () => { // Arrange const { address } = genesisDelegates.delegates[4]; const seed = genesisDelegates.delegates[4].hashOnion.hashes[0]; - const hashes = cryptography.hashOnion( + const hashes = cryptography.utils.hashOnion( Buffer.from(seed, 'hex'), genesisDelegates.delegates[0].hashOnion.distance, 1, @@ -141,7 +141,7 @@ describe('RandomModuleEndpoint', () => { // Arrange const { address } = genesisDelegates.delegates[1]; const seed = genesisDelegates.delegates[0].hashOnion.hashes[1]; - const hashes = cryptography.hashOnion( + const hashes = cryptography.utils.hashOnion( Buffer.from(seed, 'hex'), genesisDelegates.delegates[0].hashOnion.distance, 1, diff --git a/framework/test/unit/modules/random/random_module.spec.ts b/framework/test/unit/modules/random/random_module.spec.ts index f49ee2d7565..e6ad97a499d 100644 --- a/framework/test/unit/modules/random/random_module.spec.ts +++ b/framework/test/unit/modules/random/random_module.spec.ts @@ -12,12 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { - getAddressFromPublicKey, - getRandomBytes, - hash, - hashOnion, -} from '@liskhq/lisk-cryptography'; +import { utils, address } from '@liskhq/lisk-cryptography'; import { codec } from '@liskhq/lisk-codec'; import { BlockAssets } from '@liskhq/lisk-chain'; import * as genesisDelegates from '../../../fixtures/genesis_delegates.json'; @@ -146,7 +141,11 @@ describe('RandomModule', () => { ); const seed = targetDelegate.hashOnion.hashes[1]; - const hashes = hashOnion(Buffer.from(seed, 'hex'), targetDelegate.hashOnion.distance, 1); + const hashes = utils.hashOnion( + Buffer.from(seed, 'hex'), + targetDelegate.hashOnion.distance, + 1, + ); // Act await randomModule.init({ @@ -186,7 +185,11 @@ describe('RandomModule', () => { ); const seed = targetDelegate.hashOnion.hashes[1]; - const hashes = hashOnion(Buffer.from(seed, 'hex'), targetDelegate.hashOnion.distance, 1); + const hashes = utils.hashOnion( + Buffer.from(seed, 'hex'), + targetDelegate.hashOnion.distance, + 1, + ); // Act await randomModule.init({ @@ -245,7 +248,11 @@ describe('RandomModule', () => { ); const seed = targetDelegate.hashOnion.hashes[1]; - const hashes = hashOnion(Buffer.from(seed, 'hex'), targetDelegate.hashOnion.distance, 1); + const hashes = utils.hashOnion( + Buffer.from(seed, 'hex'), + targetDelegate.hashOnion.distance, + 1, + ); // Act await randomModule.init({ @@ -280,7 +287,11 @@ describe('RandomModule', () => { }); const seed = targetDelegate.hashOnion.hashes[1]; - const hashes = hashOnion(Buffer.from(seed, 'hex'), targetDelegate.hashOnion.distance, 1); + const hashes = utils.hashOnion( + Buffer.from(seed, 'hex'), + targetDelegate.hashOnion.distance, + 1, + ); await blockGenerateContext .getGeneratorStore(randomModule.id) diff --git a/framework/test/unit/modules/token/api.spec.ts b/framework/test/unit/modules/token/api.spec.ts index e80dd5d03b1..a0a2aae2ce6 100644 --- a/framework/test/unit/modules/token/api.spec.ts +++ b/framework/test/unit/modules/token/api.spec.ts @@ -334,7 +334,7 @@ describe('token module', () => { api.lock( apiContext, defaultAddress, - intToBuffer(12, 4), + utils.intToBuffer(12, 4), defaultTokenID, defaultAccount.availableBalance + BigInt(1), ), @@ -346,7 +346,7 @@ describe('token module', () => { api.lock( apiContext, defaultAddress, - intToBuffer(2, 4), + utils.intToBuffer(2, 4), defaultTokenID, defaultAccount.availableBalance, ), @@ -361,7 +361,7 @@ describe('token module', () => { api.lock( apiContext, defaultAddress, - intToBuffer(2, 4), + utils.intToBuffer(2, 4), defaultTokenID, defaultAccount.availableBalance, ), @@ -405,7 +405,7 @@ describe('token module', () => { api.unlock( apiContext, defaultAddress, - intToBuffer(12, 4), + utils.intToBuffer(12, 4), defaultTokenID, defaultAccount.lockedBalances[0].amount + BigInt(1), ), @@ -417,7 +417,7 @@ describe('token module', () => { api.unlock( apiContext, defaultAddress, - intToBuffer(12, 4), + utils.intToBuffer(12, 4), defaultTokenID, defaultAccount.lockedBalances[0].amount - BigInt(1), ), @@ -435,7 +435,7 @@ describe('token module', () => { api.unlock( apiContext, defaultAddress, - intToBuffer(12, 4), + utils.intToBuffer(12, 4), defaultTokenID, defaultAccount.lockedBalances[0].amount, ), diff --git a/framework/test/unit/modules/token/commands/transfer.spec.ts b/framework/test/unit/modules/token/commands/transfer.spec.ts index 6ab4f7f8a5d..70e90c239ff 100644 --- a/framework/test/unit/modules/token/commands/transfer.spec.ts +++ b/framework/test/unit/modules/token/commands/transfer.spec.ts @@ -14,7 +14,7 @@ import { Transaction } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { getAddressAndPublicKeyFromPassphrase, getRandomBytes } from '@liskhq/lisk-cryptography'; +import { address, utils } from '@liskhq/lisk-cryptography'; import { VerifyStatus } from '../../../../../src'; import { TokenAPI } from '../../../../../src/modules/token/api'; import { TransferCommand } from '../../../../../src/modules/token/commands/transfer'; @@ -167,8 +167,8 @@ describe('Transfer command', () => { describe('execute', () => { let stateStore: PrefixedStateReadWriter; - const sender = getAddressAndPublicKeyFromPassphrase('sender'); - const recipient = getAddressAndPublicKeyFromPassphrase('recipient'); + const sender = address.getAddressAndPublicKeyFromPassphrase('sender'); + const recipient = address.getAddressAndPublicKeyFromPassphrase('recipient'); const thirdTokenID = Buffer.from([1, 0, 0, 0, 4, 0, 0, 0]); const tokenID = Buffer.from([0, 0, 0, 1, 0, 0, 0, 0]); const senderBalance = BigInt(200000000); diff --git a/framework/test/unit/modules/token/init_genesis_state_fixture.ts b/framework/test/unit/modules/token/init_genesis_state_fixture.ts index e43a490fdc6..600a79d37ad 100644 --- a/framework/test/unit/modules/token/init_genesis_state_fixture.ts +++ b/framework/test/unit/modules/token/init_genesis_state_fixture.ts @@ -14,7 +14,7 @@ import { utils } from '@liskhq/lisk-cryptography'; -// import { getRandomBytes } from '@liskhq/lisk-cryptography'; +// import { utils } from '@liskhq/lisk-cryptography'; const oneUnit = BigInt('100000000'); diff --git a/framework/test/unit/modules/validators/api.spec.ts b/framework/test/unit/modules/validators/api.spec.ts index dd8c61a2457..4c225d465cb 100644 --- a/framework/test/unit/modules/validators/api.spec.ts +++ b/framework/test/unit/modules/validators/api.spec.ts @@ -492,7 +492,7 @@ describe('ValidatorsModuleAPI', () => { }; const validatorsStore = apiContext.getStore( - intToBuffer(MODULE_ID_VALIDATORS, 4), + utils.intToBuffer(MODULE_ID_VALIDATORS, 4), STORE_PREFIX_VALIDATORS_DATA, ); await validatorsStore.setWithSchema(validAddress, validatorAccount, validatorAccountSchema); diff --git a/framework/test/unit/modules/validators/endpoint.spec.ts b/framework/test/unit/modules/validators/endpoint.spec.ts index 732780b399c..749058146ef 100644 --- a/framework/test/unit/modules/validators/endpoint.spec.ts +++ b/framework/test/unit/modules/validators/endpoint.spec.ts @@ -12,7 +12,7 @@ * Removal or modification of this copyright notice is prohibited. */ -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { InMemoryDatabase, Database, Batch } from '@liskhq/lisk-db'; import { Logger } from '../../../../src/logger'; import { ValidatorsModule } from '../../../../src/modules/validators'; diff --git a/framework/test/unit/state_machine/event_queue.spec.ts b/framework/test/unit/state_machine/event_queue.spec.ts index 16aabe9e7c2..71fb11157aa 100644 --- a/framework/test/unit/state_machine/event_queue.spec.ts +++ b/framework/test/unit/state_machine/event_queue.spec.ts @@ -58,7 +58,7 @@ describe('EventQueue', () => { it('should throw error if data size exceeds maximum allowed', () => { expect(() => eventQueue.add( - intToBuffer(2, 4), + utils.intToBuffer(2, 4), Buffer.from([0, 0, 0, 1]), utils.getRandomBytes(EVENT_MAX_EVENT_SIZE_BYTES + 1), [utils.getRandomBytes(32)], @@ -69,7 +69,7 @@ describe('EventQueue', () => { it('should throw error if topics is empty', () => { expect(() => eventQueue.add( - intToBuffer(2, 4), + utils.intToBuffer(2, 4), Buffer.from([0, 0, 0, 1]), utils.getRandomBytes(EVENT_MAX_EVENT_SIZE_BYTES), [], @@ -80,7 +80,7 @@ describe('EventQueue', () => { it('should throw error if topics length exceeds maxumum allowed', () => { expect(() => eventQueue.add( - intToBuffer(2, 4), + utils.intToBuffer(2, 4), Buffer.from([0, 0, 0, 1]), utils.getRandomBytes(EVENT_MAX_EVENT_SIZE_BYTES), new Array(5).fill(0).map(() => utils.getRandomBytes(32)), @@ -130,21 +130,21 @@ describe('EventQueue', () => { eventQueue.createSnapshot(); eventQueue.add( - intToBuffer(3, 4), + utils.intToBuffer(3, 4), Buffer.from([0, 0, 0, 1]), utils.getRandomBytes(100), [utils.getRandomBytes(32)], false, ); eventQueue.add( - intToBuffer(3, 4), + utils.intToBuffer(3, 4), Buffer.from([0, 0, 0, 1]), utils.getRandomBytes(100), [utils.getRandomBytes(32)], true, ); eventQueue.add( - intToBuffer(3, 4), + utils.intToBuffer(3, 4), Buffer.from([0, 0, 0, 1]), utils.getRandomBytes(100), [utils.getRandomBytes(32)], diff --git a/framework/test/unit/testing/create_block.spec.ts b/framework/test/unit/testing/create_block.spec.ts index ea828fd93e7..ad8708bf0a0 100644 --- a/framework/test/unit/testing/create_block.spec.ts +++ b/framework/test/unit/testing/create_block.spec.ts @@ -21,10 +21,12 @@ import { defaultConfig } from '../../../src/testing/fixtures/config'; import { createFakeBlockHeader } from '../../fixtures'; describe('Create Block', () => { - const networkIdentifier = getNetworkIdentifier( - Buffer.from(devnetGenesisBlock.header.id, 'hex'), - devnetConfig.genesis.communityIdentifier, - ).toString('hex'); + const networkIdentifier = utils + .getNetworkIdentifier( + Buffer.from(devnetGenesisBlock.header.id, 'hex'), + devnetConfig.genesis.communityIdentifier, + ) + .toString('hex'); const genesis = { passphrase: 'cake cruise harvest senior glare resist acoustic maze stuff lizard autumn educate', privateKey: Buffer.from( diff --git a/framework/test/utils/mocks/account.ts b/framework/test/utils/mocks/account.ts index a1189b8c7c0..a80116062b0 100644 --- a/framework/test/utils/mocks/account.ts +++ b/framework/test/utils/mocks/account.ts @@ -12,24 +12,18 @@ * Removal or modification of this copyright notice is prohibited. * */ -import { - getAddressFromPassphrase, - generatePrivateKey, - getPublicKeyFromPrivateKey, - blsPopProve, - getKeys, -} from '@liskhq/lisk-cryptography'; +import { address, bls, ed } from '@liskhq/lisk-cryptography'; import { Mnemonic } from '@liskhq/lisk-passphrase'; export const createAccount = () => { const passphrase = Mnemonic.generateMnemonic(256); - const keys = getKeys(passphrase); - const blsPrivateKey = generatePrivateKey(Buffer.from(passphrase, 'utf-8')); - const blsPublicKey = getPublicKeyFromPrivateKey(blsPrivateKey); - const blsPoP = blsPopProve(blsPrivateKey); + const keys = ed.getKeys(passphrase); + const blsPrivateKey = bls.generatePrivateKey(Buffer.from(passphrase, 'utf-8')); + const blsPublicKey = bls.getPublicKeyFromPrivateKey(blsPrivateKey); + const blsPoP = bls.popProve(blsPrivateKey); return { passphrase, - address: getAddressFromPassphrase(passphrase), + address: address.getAddressFromPassphrase(passphrase), publicKey: keys.publicKey, privateKey: keys.privateKey, blsPrivateKey, diff --git a/framework/test/utils/mocks/endpoint.ts b/framework/test/utils/mocks/endpoint.ts index 7d17df09cd2..7df52e5d8ff 100644 --- a/framework/test/utils/mocks/endpoint.ts +++ b/framework/test/utils/mocks/endpoint.ts @@ -14,7 +14,7 @@ */ import { StateStore } from '@liskhq/lisk-chain'; -import { getRandomBytes } from '@liskhq/lisk-cryptography'; +import { utils } from '@liskhq/lisk-cryptography'; import { ModuleEndpointContext } from '../../../src'; import { createImmutableAPIContext } from '../../../src/state_machine'; import { fakeLogger } from './logger'; diff --git a/framework/test/utils/mocks/transaction.ts b/framework/test/utils/mocks/transaction.ts index a37af2a0fb5..cdf6829391c 100644 --- a/framework/test/utils/mocks/transaction.ts +++ b/framework/test/utils/mocks/transaction.ts @@ -15,14 +15,7 @@ import { Transaction, BlockHeader, TAG_TRANSACTION } from '@liskhq/lisk-chain'; import { codec } from '@liskhq/lisk-codec'; -import { - getAddressAndPublicKeyFromPassphrase, - signData, - generatePrivateKey, - getPublicKeyFromPrivateKey, - blsPopProve, - intToBuffer, -} from '@liskhq/lisk-cryptography'; +import { utils, bls, ed, address } from '@liskhq/lisk-cryptography'; import { signMultiSignatureTransaction } from '@liskhq/lisk-transactions'; import { registerMultisignatureParamsSchema } from '../../../src/modules/auth/schemas'; import { @@ -50,7 +43,7 @@ export const createTransferTransaction = (input: { amount: input.amount ?? BigInt('10000000000'), data: '', }); - const { publicKey } = getAddressAndPublicKeyFromPassphrase(input.passphrase); + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(input.passphrase); const tx = new Transaction({ moduleID: utils.intToBuffer(2, 4), @@ -62,7 +55,7 @@ export const createTransferTransaction = (input: { signatures: [], }); tx.signatures.push( - signData(TAG_TRANSACTION, input.networkIdentifier, tx.getSigningBytes(), input.passphrase), + ed.signData(TAG_TRANSACTION, input.networkIdentifier, tx.getSigningBytes(), input.passphrase), ); return tx; }; @@ -74,10 +67,10 @@ export const createDelegateRegisterTransaction = (input: { username: string; fee?: bigint; }): Transaction => { - const { publicKey } = getAddressAndPublicKeyFromPassphrase(input.passphrase); - const blsSK = generatePrivateKey(Buffer.from(input.passphrase, 'utf-8')); - const blsPK = getPublicKeyFromPrivateKey(blsSK); - const blsPop = blsPopProve(blsSK); + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(input.passphrase); + const blsSK = bls.generatePrivateKey(Buffer.from(input.passphrase, 'utf-8')); + const blsPK = bls.getPublicKeyFromPrivateKey(blsSK); + const blsPop = bls.popProve(blsSK); const encodedAsset = codec.encode(delegateRegistrationCommandParamsSchema, { name: input.username, generatorKey: publicKey, @@ -95,7 +88,7 @@ export const createDelegateRegisterTransaction = (input: { signatures: [], }); tx.signatures.push( - signData(TAG_TRANSACTION, input.networkIdentifier, tx.getSigningBytes(), input.passphrase), + ed.signData(TAG_TRANSACTION, input.networkIdentifier, tx.getSigningBytes(), input.passphrase), ); return tx; }; @@ -110,7 +103,7 @@ export const createDelegateVoteTransaction = (input: { const encodedAsset = codec.encode(voteCommandParamsSchema, { votes: input.votes, }); - const { publicKey } = getAddressAndPublicKeyFromPassphrase(input.passphrase); + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(input.passphrase); const tx = new Transaction({ moduleID: utils.intToBuffer(13, 4), @@ -122,7 +115,7 @@ export const createDelegateVoteTransaction = (input: { signatures: [], }); tx.signatures.push( - signData(TAG_TRANSACTION, input.networkIdentifier, tx.getSigningBytes(), input.passphrase), + ed.signData(TAG_TRANSACTION, input.networkIdentifier, tx.getSigningBytes(), input.passphrase), ); return tx; }; @@ -147,7 +140,7 @@ export const createMultiSignRegisterTransaction = (input: { optionalKeys: input.optionalKeys, numberOfSignatures: input.numberOfSignatures, }; - const { publicKey } = getAddressAndPublicKeyFromPassphrase(input.senderPassphrase); + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(input.senderPassphrase); const transaction = [...input.passphrases].reduce>( (prev, current) => { return signMultiSignatureTransaction( @@ -233,7 +226,7 @@ export const createReportMisbehaviorTransaction = (input: { header1: input.header1.getBytes(), header2: input.header2.getBytes(), }); - const { publicKey } = getAddressAndPublicKeyFromPassphrase(input.passphrase); + const { publicKey } = address.getAddressAndPublicKeyFromPassphrase(input.passphrase); const tx = new Transaction({ moduleID: utils.intToBuffer(13, 4), @@ -245,7 +238,7 @@ export const createReportMisbehaviorTransaction = (input: { signatures: [], }); tx.signatures.push( - signData(TAG_TRANSACTION, input.networkIdentifier, tx.getSigningBytes(), input.passphrase), + ed.signData(TAG_TRANSACTION, input.networkIdentifier, tx.getSigningBytes(), input.passphrase), ); return tx; }; diff --git a/protocol-specs/generators/address_generation/index.js b/protocol-specs/generators/address_generation/index.js index 70df472487d..e562c22a008 100644 --- a/protocol-specs/generators/address_generation/index.js +++ b/protocol-specs/generators/address_generation/index.js @@ -15,7 +15,7 @@ 'use strict'; -const { hash } = require('@liskhq/lisk-cryptography'); +const { utils } = require('@liskhq/lisk-cryptography'); const BaseGenerator = require('../base_generator'); const publicKeys = [ diff --git a/protocol-specs/generators/dpos_delegate_shuffling/index.js b/protocol-specs/generators/dpos_delegate_shuffling/index.js index f3215f5d2f8..0e0f7a63197 100644 --- a/protocol-specs/generators/dpos_delegate_shuffling/index.js +++ b/protocol-specs/generators/dpos_delegate_shuffling/index.js @@ -14,7 +14,7 @@ 'use strict'; -const { hash } = require('@liskhq/lisk-cryptography'); +const { utils } = require('@liskhq/lisk-cryptography'); const BaseGenerator = require('../base_generator'); const previousDelegateList = require('./delegate_address_list.json').delegateList; diff --git a/protocol-specs/generators/dpos_delegate_shuffling/sample_generator.js b/protocol-specs/generators/dpos_delegate_shuffling/sample_generator.js index 66f2ce51339..34c7868ad3b 100644 --- a/protocol-specs/generators/dpos_delegate_shuffling/sample_generator.js +++ b/protocol-specs/generators/dpos_delegate_shuffling/sample_generator.js @@ -14,7 +14,7 @@ 'use strict'; -const { getKeys, hash } = require('@liskhq/lisk-cryptography'); +const { utils, ed } = require('@liskhq/lisk-cryptography'); const { Mnemonic } = require('@liskhq/lisk-passphrase'); const fs = require('fs'); @@ -24,7 +24,7 @@ const generateDelegates = num => { const delegateList = []; for (let i = 0; i < num; i += 1) { const passphrase = Mnemonic.generateMnemonic(); - const { publicKey } = getKeys(passphrase); + const { publicKey } = ed.getKeys(passphrase); const address = utils.hash(Buffer.from(publicKey, 'hex')).slice(0, 20); delegateList.push({ diff --git a/protocol-specs/generators/dpos_forger_selection/sample_generator.js b/protocol-specs/generators/dpos_forger_selection/sample_generator.js index 10c1faab4b5..ce911ed3c4e 100644 --- a/protocol-specs/generators/dpos_forger_selection/sample_generator.js +++ b/protocol-specs/generators/dpos_forger_selection/sample_generator.js @@ -14,7 +14,7 @@ 'use strict'; -const { hash, getKeys } = require('@liskhq/lisk-cryptography'); +const { utils, ed } = require('@liskhq/lisk-cryptography'); const { Mnemonic } = require('@liskhq/lisk-passphrase'); const crypto = require('crypto'); const fs = require('fs'); @@ -25,7 +25,7 @@ const generateDelegates = (num, fixedNum) => { const delegateList = []; for (let i = 0; i < num; i += 1) { const passphrase = Mnemonic.generateMnemonic(); - const { publicKey } = getKeys(passphrase); + const { publicKey } = ed.getKeys(passphrase); const address = utils.hash(Buffer.from(publicKey, 'hex')).slice(0, 20); const buf = crypto.randomBytes(8); const randomNumber = buf.readBigUInt64BE() / BigInt(10) ** BigInt(8); diff --git a/protocol-specs/generators/dpos_random_seed_generation/index.js b/protocol-specs/generators/dpos_random_seed_generation/index.js index 35665b4c4fa..49035037eda 100644 --- a/protocol-specs/generators/dpos_random_seed_generation/index.js +++ b/protocol-specs/generators/dpos_random_seed_generation/index.js @@ -14,7 +14,7 @@ 'use strict'; -const { hash } = require('@liskhq/lisk-cryptography'); +const { utils } = require('@liskhq/lisk-cryptography'); const BaseGenerator = require('../base_generator'); const { list: sampleDelegateList } = require('./forger_list'); diff --git a/protocol-specs/generators/multisignature_registration/index.js b/protocol-specs/generators/multisignature_registration/index.js index f80d42e6fac..fcc42f09cbe 100644 --- a/protocol-specs/generators/multisignature_registration/index.js +++ b/protocol-specs/generators/multisignature_registration/index.js @@ -14,7 +14,7 @@ 'use strict'; -const { signData, intToBuffer } = require('@liskhq/lisk-cryptography'); +const { utils, ed } = require('@liskhq/lisk-cryptography'); const { Codec } = require('@liskhq/lisk-codec'); const BaseGenerator = require('../base_generator'); const { baseTransactionSchema } = require('../../utils/schema'); @@ -142,7 +142,7 @@ const sortKeysAscending = publicKeys => const createSignatureObject = (txBuffer, account) => ({ signature: Buffer.from( - signData(TAG_TRANSACTION, networkIdentifier, txBuffer, account.passphrase), + ed.signData(TAG_TRANSACTION, networkIdentifier, txBuffer, account.passphrase), 'hex', ), }); diff --git a/protocol-specs/generators/proof_of_misbehavior_transaction/index.js b/protocol-specs/generators/proof_of_misbehavior_transaction/index.js index 7adc73be936..eadafb29315 100644 --- a/protocol-specs/generators/proof_of_misbehavior_transaction/index.js +++ b/protocol-specs/generators/proof_of_misbehavior_transaction/index.js @@ -14,12 +14,7 @@ 'use strict'; -const { - hash, - getPrivateAndPublicKeyBytesFromPassphrase, - signData, - signDataWithPrivateKey, -} = require('@liskhq/lisk-cryptography'); +const { utils, ed } = require('@liskhq/lisk-cryptography'); const { Codec } = require('@liskhq/lisk-codec'); const { baseTransactionSchema } = require('../../utils/schema'); @@ -96,7 +91,7 @@ const sign = (header, privateKey) => { asset: assetBytes, }); return Buffer.from( - signDataWithPrivateKey( + ed.signDataWithPrivateKey( Buffer.concat([TAG_BLOCK_HEADER, networkIdentifier, blockBytes]), privateKey, ), @@ -145,7 +140,7 @@ const encode = tx => { const createSignatureObject = (txBuffer, account) => ({ signature: Buffer.from( - signData(Buffer.concat([TAG_TRANSACTION, networkIdentifier, txBuffer]), account.passphrase), + ed.signData(Buffer.concat([TAG_TRANSACTION, networkIdentifier, txBuffer]), account.passphrase), 'hex', ), }); @@ -183,7 +178,7 @@ const getHexAccount = account => ({ balance: account.balance, }); -const forgerKeyPair = getPrivateAndPublicKeyBytesFromPassphrase(accounts.forger.passphrase); +const forgerKeyPair = ed.getPrivateAndPublicKeyBytesFromPassphrase(accounts.forger.passphrase); /* Scenario 1: diff --git a/protocol-specs/generators/transaction_merkle_root_for_blocks/index.js b/protocol-specs/generators/transaction_merkle_root_for_blocks/index.js index 43458d6c162..bce16a4fb60 100644 --- a/protocol-specs/generators/transaction_merkle_root_for_blocks/index.js +++ b/protocol-specs/generators/transaction_merkle_root_for_blocks/index.js @@ -14,7 +14,7 @@ 'use strict'; -const { bufferToHex, hash, intToBuffer, getRandomBytes } = require('@liskhq/lisk-cryptography'); +const { utils } = require('@liskhq/lisk-cryptography'); const BaseGenerator = require('../base_generator'); const getRandomTransactionIds = count => { @@ -48,7 +48,7 @@ const merkleRoot = transactionIds => { const generateTransactionMerkleRoot = () => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 50, 150, 300, 1000].map(count => { const transactionIds = getRandomTransactionIds(count); - const ids = transactionIds.map(t => bufferToHex(t)); + const ids = transactionIds.map(t => utils.bufferToHex(t)); const transactionMerkleRoot = merkleRoot(transactionIds); return { From afb6a027c607b3d10f59015e2a7ef06080c9abe7 Mon Sep 17 00:00:00 2001 From: shuse2 Date: Tue, 19 Jul 2022 15:03:48 +0200 Subject: [PATCH 6/6] :recycle: Remove unnecessary eslint disable --- elements/lisk-client/test/lisk-cryptography/bls.spec.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/elements/lisk-client/test/lisk-cryptography/bls.spec.ts b/elements/lisk-client/test/lisk-cryptography/bls.spec.ts index afc7256e749..bd43c23d97a 100644 --- a/elements/lisk-client/test/lisk-cryptography/bls.spec.ts +++ b/elements/lisk-client/test/lisk-cryptography/bls.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable camelcase */ /* * Copyright © 2022 Lisk Foundation *