/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ // The import here is via the package name. This is to ensure // that exports mapping/resolution does fall into place. import { crypto } from '@noble/hashes/crypto'; // Cast array to different type export const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); export const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); // Cast array to view export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); // The rotate right (circular right shift) operation for uint32 export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; // There is almost no big endian hardware, but js typed arrays uses platform specific endianness. // So, just to be sure not to corrupt anything. if (!isLE) throw new Error('Non little-endian hardware is not supported'); const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); /** * @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) */ export function bytesToHex(uint8a) { // pre-caching improves the speed 6x if (!(uint8a instanceof Uint8Array)) throw new Error('Uint8Array expected'); let hex = ''; for (let i = 0; i < uint8a.length; i++) { hex += hexes[uint8a[i]]; } return hex; } /** * @example hexToBytes('deadbeef') */ export function hexToBytes(hex) { if (typeof hex !== 'string') { throw new TypeError('hexToBytes: expected string, got ' + typeof hex); } if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex'); const array = new Uint8Array(hex.length / 2); for (let i = 0; i < array.length; i++) { const j = i * 2; const hexByte = hex.slice(j, j + 2); const byte = Number.parseInt(hexByte, 16); if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); array[i] = byte; } return array; } // There is no setImmediate in browser and setTimeout is slow. However, call to async function will return Promise // which will be fullfiled only on next scheduler queue processing step and this is exactly what we need. export const nextTick = async () => { }; // Returns control to thread each 'tick' ms to avoid blocking export async function asyncLoop(iters, tick, cb) { let ts = Date.now(); for (let i = 0; i < iters; i++) { cb(i); // Date.now() is not monotonic, so in case if clock goes backwards we return return control too const diff = Date.now() - ts; if (diff >= 0 && diff < tick) continue; await nextTick(); ts += diff; } } export function utf8ToBytes(str) { if (typeof str !== 'string') { throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`); } return new TextEncoder().encode(str); } export function toBytes(data) { if (typeof data === 'string') data = utf8ToBytes(data); if (!(data instanceof Uint8Array)) throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`); return data; } /** * Concats Uint8Array-s into one; like `Buffer.concat([buf1, buf2])` * @example concatBytes(buf1, buf2) */ export function concatBytes(...arrays) { if (!arrays.every((a) => a instanceof Uint8Array)) throw new Error('Uint8Array list expected'); if (arrays.length === 1) return arrays[0]; const length = arrays.reduce((a, arr) => a + arr.length, 0); const result = new Uint8Array(length); for (let i = 0, pad = 0; i < arrays.length; i++) { const arr = arrays[i]; result.set(arr, pad); pad += arr.length; } return result; } // For runtime check if class implements interface export class Hash { // Safe version that clones internal state clone() { return this._cloneInto(); } } // Check if object doens't have custom constructor (like Uint8Array/Array) const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; export function checkOpts(defaults, opts) { if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts))) throw new TypeError('Options should be object or undefined'); const merged = Object.assign(defaults, opts); return merged; } export function wrapConstructor(hashConstructor) { const hashC = (message) => hashConstructor().update(toBytes(message)).digest(); const tmp = hashConstructor(); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = () => hashConstructor(); return hashC; } export function wrapConstructorWithOpts(hashCons) { const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); const tmp = hashCons({}); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = (opts) => hashCons(opts); return hashC; } /** * Secure PRNG */ export function randomBytes(bytesLength = 32) { if (crypto.web) { return crypto.web.getRandomValues(new Uint8Array(bytesLength)); } else if (crypto.node) { return new Uint8Array(crypto.node.randomBytes(bytesLength).buffer); } else { throw new Error("The environment doesn't have randomBytes function"); } } //# sourceMappingURL=utils.js.map