@kevincharm/sparse-merkle-tree
Version:
Sparse Merkle Tree implementation in Solidity with accompanying JS library
47 lines (46 loc) • 1.42 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.serialise = exports.deserialise = exports.keccak = void 0;
const utils_1 = require("@noble/hashes/utils");
const sha3_1 = require("@noble/hashes/sha3");
function numToBytes(value) {
const hexRaw = value.toString(16);
const hexPadded = hexRaw.padStart(32 * 2, '0');
return (0, utils_1.hexToBytes)(hexPadded);
}
function bytesToNum(bytes) {
return BigInt('0x' + (0, utils_1.bytesToHex)(bytes));
}
function keccak(...bytes) {
if (bytes.every((v) => v === 0n)) {
return 0n;
}
const buffer = (0, utils_1.concatBytes)(...bytes.map((b) => numToBytes(b)));
return bytesToNum((0, sha3_1.keccak_256)(buffer));
}
exports.keccak = keccak;
/**
* Default deserialiser hexstring -> bigint
*
* @param input Hex string e.g. "0xcafebabe"
* @returns internal bigint representation
*/
function deserialise(input) {
const isHex = /^0x[0-9a-fA-F]+$/.test(input);
if (!isHex)
throw new Error(`Not valid hex: ${input}`);
return BigInt(input);
}
exports.deserialise = deserialise;
/**
* Default serialiser bigint -> 0-padded 32-byte hexstring
*
* @param input bigint
* @returns zero-padded 32-byte hexstring
*/
function serialise(input) {
const hexRaw = input.toString(16);
const hexPadded = hexRaw.padStart(32 * 2, '0');
return `0x${hexPadded}`;
}
exports.serialise = serialise;