UNPKG

@bsv/sdk

Version:

BSV Blockchain Software Development Kit

62 lines (55 loc) 1.49 kB
class Rand { _rand: (n: number) => number[] // ✅ Explicit function type constructor () { const noRand = (): never => { throw new Error( 'No secure random number generator is available in this environment.' ) } this._rand = noRand // Assign the function if (typeof self === 'object') { /* eslint-disable-next-line */ if (self.crypto?.getRandomValues) { this._rand = (n) => { const arr = new Uint8Array(n) /* eslint-disable-next-line */ self.crypto.getRandomValues(arr); return [...arr] } } /* if (typeof window === 'object') */ else { this._rand = noRand } } else { try { /* eslint-disable-next-line */ const crypto = require("crypto"); if (typeof crypto.randomBytes === 'function') { this._rand = (n: number) => [...crypto.randomBytes(n)] } } catch { this._rand = noRand } } } generate (len: number): number[] { return this._rand(len) } } let ayn: Rand | null = null /** * Generates a sequence of pseudo-random bytes with the given length. * * @param len - The number of bytes to generate * * @returns The generated bytes * * @example * import Random from '@bsv/sdk/primitives/Random' * const bytes = Random(32) // Produces 32 random bytes */ export default (len: number): number[] => { if (ayn == null) { ayn = new Rand() } return ayn.generate(len) }