UNPKG

@iden3/js-merkletree

Version:

javascript sparse merkle tree library

59 lines (58 loc) 2.52 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.str2Bytes = exports.newBigIntFromBytes = exports.bytes2Hex = exports.setBitBigEndian = exports.testBitBigEndian = exports.testBit = exports.bytes2BinaryString = exports.swapEndianness = exports.bytesEqual = void 0; const constants_1 = require("../../constants"); const crypto_1 = require("./crypto"); const bytesEqual = (b1, b2) => { return b1.every((ele, idx) => ele === b2[idx]); }; exports.bytesEqual = bytesEqual; // TODO: might be make this generic over typed arrays? const swapEndianness = (bytes) => { return bytes.slice().reverse(); }; exports.swapEndianness = swapEndianness; const bytes2BinaryString = (bytes) => { return '0b' + bytes.reduce((acc, i) => acc + i.toString(2).padStart(8, '0'), ''); }; exports.bytes2BinaryString = bytes2BinaryString; const testBit = (bitMap, n) => { return (bitMap[parseInt((n / 8).toString())] & (1 << n % 8)) !== 0; }; exports.testBit = testBit; const testBitBigEndian = (bitMap, n) => { return (bitMap[bitMap.length - parseInt(`${n / 8}`) - 1] & (1 << n % 8)) !== 0; }; exports.testBitBigEndian = testBitBigEndian; // SetBitBigEndian sets the bit n in the bitmap to 1, in Big Endian. const setBitBigEndian = (bitMap, n) => { bitMap[bitMap.length - parseInt(`${n / 8}`) - 1] |= 1 << n % 8; }; exports.setBitBigEndian = setBitBigEndian; const hextable = '0123456789abcdef'; const bytes2Hex = (u) => { const arr = new Array(u.length * 2); let j = 0; u.forEach((v) => { arr[j] = hextable[parseInt((v >> 4).toString(10))]; arr[j + 1] = hextable[parseInt((v & 15).toString(10))]; j += 2; }); return arr.join(''); }; exports.bytes2Hex = bytes2Hex; // NOTE: `bytes` should be big endian // bytes recieved from Hash.value getter are safe to use since their endianness is swapped, for the same reason the private Hash.bytes { stored in little endian } should never be used const newBigIntFromBytes = (bytes) => { if (bytes.length !== constants_1.HASH_BYTES_LENGTH) { throw `Expected 32 bytes, found ${bytes.length} bytes`; } const bigNum = BigInt((0, exports.bytes2BinaryString)(bytes)); if (!(0, crypto_1.checkBigIntInField)(bigNum)) { throw 'NewBigIntFromHashBytes: Value not inside the Finite Field'; } return bigNum; }; exports.newBigIntFromBytes = newBigIntFromBytes; const str2Bytes = (str) => new Uint8Array(str.length * 2).map((_, i) => str.charCodeAt(i)); exports.str2Bytes = str2Bytes;