utils.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  2. // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
  3. // node.js versions earlier than v19 don't declare it in global scope.
  4. // For node.js, package.json#exports field mapping rewrites import
  5. // from `crypto` to `cryptoNode`, which imports native module.
  6. // Makes the utils un-importable in browsers without a bundler.
  7. // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
  8. import { crypto } from '@noble/hashes/crypto';
  9. import { bytes as abytes } from './_assert.js';
  10. // export { isBytes } from './_assert.js';
  11. // We can't reuse isBytes from _assert, because somehow this causes huge perf issues
  12. export function isBytes(a: unknown): a is Uint8Array {
  13. return (
  14. a instanceof Uint8Array ||
  15. (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')
  16. );
  17. }
  18. // prettier-ignore
  19. export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |
  20. Uint16Array | Int16Array | Uint32Array | Int32Array;
  21. // Cast array to different type
  22. export const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
  23. export const u32 = (arr: TypedArray) =>
  24. new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
  25. // Cast array to view
  26. export const createView = (arr: TypedArray) =>
  27. new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
  28. // The rotate right (circular right shift) operation for uint32
  29. export const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);
  30. // The rotate left (circular left shift) operation for uint32
  31. export const rotl = (word: number, shift: number) =>
  32. (word << shift) | ((word >>> (32 - shift)) >>> 0);
  33. export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
  34. // The byte swap operation for uint32
  35. export const byteSwap = (word: number) =>
  36. ((word << 24) & 0xff000000) |
  37. ((word << 8) & 0xff0000) |
  38. ((word >>> 8) & 0xff00) |
  39. ((word >>> 24) & 0xff);
  40. // Conditionally byte swap if on a big-endian platform
  41. export const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);
  42. // In place byte swap for Uint32Array
  43. export function byteSwap32(arr: Uint32Array) {
  44. for (let i = 0; i < arr.length; i++) {
  45. arr[i] = byteSwap(arr[i]);
  46. }
  47. }
  48. // Array where index 0xf0 (240) is mapped to string 'f0'
  49. const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>
  50. i.toString(16).padStart(2, '0')
  51. );
  52. /**
  53. * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
  54. */
  55. export function bytesToHex(bytes: Uint8Array): string {
  56. abytes(bytes);
  57. // pre-caching improves the speed 6x
  58. let hex = '';
  59. for (let i = 0; i < bytes.length; i++) {
  60. hex += hexes[bytes[i]];
  61. }
  62. return hex;
  63. }
  64. // We use optimized technique to convert hex string to byte array
  65. const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;
  66. function asciiToBase16(char: number): number | undefined {
  67. if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;
  68. if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);
  69. if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);
  70. return;
  71. }
  72. /**
  73. * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
  74. */
  75. export function hexToBytes(hex: string): Uint8Array {
  76. if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);
  77. const hl = hex.length;
  78. const al = hl / 2;
  79. if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
  80. const array = new Uint8Array(al);
  81. for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
  82. const n1 = asciiToBase16(hex.charCodeAt(hi));
  83. const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
  84. if (n1 === undefined || n2 === undefined) {
  85. const char = hex[hi] + hex[hi + 1];
  86. throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
  87. }
  88. array[ai] = n1 * 16 + n2;
  89. }
  90. return array;
  91. }
  92. // There is no setImmediate in browser and setTimeout is slow.
  93. // call of async fn will return Promise, which will be fullfiled only on
  94. // next scheduler queue processing step and this is exactly what we need.
  95. export const nextTick = async () => {};
  96. // Returns control to thread each 'tick' ms to avoid blocking
  97. export async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {
  98. let ts = Date.now();
  99. for (let i = 0; i < iters; i++) {
  100. cb(i);
  101. // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
  102. const diff = Date.now() - ts;
  103. if (diff >= 0 && diff < tick) continue;
  104. await nextTick();
  105. ts += diff;
  106. }
  107. }
  108. // Global symbols in both browsers and Node.js since v11
  109. // See https://github.com/microsoft/TypeScript/issues/31535
  110. declare const TextEncoder: any;
  111. /**
  112. * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
  113. */
  114. export function utf8ToBytes(str: string): Uint8Array {
  115. if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
  116. return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
  117. }
  118. export type Input = Uint8Array | string;
  119. /**
  120. * Normalizes (non-hex) string or Uint8Array to Uint8Array.
  121. * Warning: when Uint8Array is passed, it would NOT get copied.
  122. * Keep in mind for future mutable operations.
  123. */
  124. export function toBytes(data: Input): Uint8Array {
  125. if (typeof data === 'string') data = utf8ToBytes(data);
  126. abytes(data);
  127. return data;
  128. }
  129. /**
  130. * Copies several Uint8Arrays into one.
  131. */
  132. export function concatBytes(...arrays: Uint8Array[]): Uint8Array {
  133. let sum = 0;
  134. for (let i = 0; i < arrays.length; i++) {
  135. const a = arrays[i];
  136. abytes(a);
  137. sum += a.length;
  138. }
  139. const res = new Uint8Array(sum);
  140. for (let i = 0, pad = 0; i < arrays.length; i++) {
  141. const a = arrays[i];
  142. res.set(a, pad);
  143. pad += a.length;
  144. }
  145. return res;
  146. }
  147. // For runtime check if class implements interface
  148. export abstract class Hash<T extends Hash<T>> {
  149. abstract blockLen: number; // Bytes per block
  150. abstract outputLen: number; // Bytes in output
  151. abstract update(buf: Input): this;
  152. // Writes digest into buf
  153. abstract digestInto(buf: Uint8Array): void;
  154. abstract digest(): Uint8Array;
  155. /**
  156. * Resets internal state. Makes Hash instance unusable.
  157. * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed
  158. * by user, they will need to manually call `destroy()` when zeroing is necessary.
  159. */
  160. abstract destroy(): void;
  161. /**
  162. * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`
  163. * when no options are passed.
  164. * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal
  165. * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.
  166. * There are no guarantees for clean-up because it's impossible in JS.
  167. */
  168. abstract _cloneInto(to?: T): T;
  169. // Safe version that clones internal state
  170. clone(): T {
  171. return this._cloneInto();
  172. }
  173. }
  174. /**
  175. * XOF: streaming API to read digest in chunks.
  176. * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.
  177. * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot
  178. * destroy state, next call can require more bytes.
  179. */
  180. export type HashXOF<T extends Hash<T>> = Hash<T> & {
  181. xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream
  182. xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf
  183. };
  184. const toStr = {}.toString;
  185. type EmptyObj = {};
  186. export function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(
  187. defaults: T1,
  188. opts?: T2
  189. ): T1 & T2 {
  190. if (opts !== undefined && toStr.call(opts) !== '[object Object]')
  191. throw new Error('Options should be object or undefined');
  192. const merged = Object.assign(defaults, opts);
  193. return merged as T1 & T2;
  194. }
  195. export type CHash = ReturnType<typeof wrapConstructor>;
  196. export function wrapConstructor<T extends Hash<T>>(hashCons: () => Hash<T>) {
  197. const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();
  198. const tmp = hashCons();
  199. hashC.outputLen = tmp.outputLen;
  200. hashC.blockLen = tmp.blockLen;
  201. hashC.create = () => hashCons();
  202. return hashC;
  203. }
  204. export function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(
  205. hashCons: (opts?: T) => Hash<H>
  206. ) {
  207. const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();
  208. const tmp = hashCons({} as T);
  209. hashC.outputLen = tmp.outputLen;
  210. hashC.blockLen = tmp.blockLen;
  211. hashC.create = (opts: T) => hashCons(opts);
  212. return hashC;
  213. }
  214. export function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(
  215. hashCons: (opts?: T) => HashXOF<H>
  216. ) {
  217. const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();
  218. const tmp = hashCons({} as T);
  219. hashC.outputLen = tmp.outputLen;
  220. hashC.blockLen = tmp.blockLen;
  221. hashC.create = (opts: T) => hashCons(opts);
  222. return hashC;
  223. }
  224. /**
  225. * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
  226. */
  227. export function randomBytes(bytesLength = 32): Uint8Array {
  228. if (crypto && typeof crypto.getRandomValues === 'function') {
  229. return crypto.getRandomValues(new Uint8Array(bytesLength));
  230. }
  231. throw new Error('crypto.getRandomValues must be defined');
  232. }