utils.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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) {
  13. return (a instanceof Uint8Array ||
  14. (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array'));
  15. }
  16. // Cast array to different type
  17. export const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
  18. export const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
  19. // Cast array to view
  20. export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
  21. // The rotate right (circular right shift) operation for uint32
  22. export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
  23. // The rotate left (circular left shift) operation for uint32
  24. export const rotl = (word, shift) => (word << shift) | ((word >>> (32 - shift)) >>> 0);
  25. export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
  26. // The byte swap operation for uint32
  27. export const byteSwap = (word) => ((word << 24) & 0xff000000) |
  28. ((word << 8) & 0xff0000) |
  29. ((word >>> 8) & 0xff00) |
  30. ((word >>> 24) & 0xff);
  31. // Conditionally byte swap if on a big-endian platform
  32. export const byteSwapIfBE = isLE ? (n) => n : (n) => byteSwap(n);
  33. // In place byte swap for Uint32Array
  34. export function byteSwap32(arr) {
  35. for (let i = 0; i < arr.length; i++) {
  36. arr[i] = byteSwap(arr[i]);
  37. }
  38. }
  39. // Array where index 0xf0 (240) is mapped to string 'f0'
  40. const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
  41. /**
  42. * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
  43. */
  44. export function bytesToHex(bytes) {
  45. abytes(bytes);
  46. // pre-caching improves the speed 6x
  47. let hex = '';
  48. for (let i = 0; i < bytes.length; i++) {
  49. hex += hexes[bytes[i]];
  50. }
  51. return hex;
  52. }
  53. // We use optimized technique to convert hex string to byte array
  54. const asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 };
  55. function asciiToBase16(char) {
  56. if (char >= asciis._0 && char <= asciis._9)
  57. return char - asciis._0;
  58. if (char >= asciis._A && char <= asciis._F)
  59. return char - (asciis._A - 10);
  60. if (char >= asciis._a && char <= asciis._f)
  61. return char - (asciis._a - 10);
  62. return;
  63. }
  64. /**
  65. * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
  66. */
  67. export function hexToBytes(hex) {
  68. if (typeof hex !== 'string')
  69. throw new Error('hex string expected, got ' + typeof hex);
  70. const hl = hex.length;
  71. const al = hl / 2;
  72. if (hl % 2)
  73. throw new Error('padded hex string expected, got unpadded hex of length ' + hl);
  74. const array = new Uint8Array(al);
  75. for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
  76. const n1 = asciiToBase16(hex.charCodeAt(hi));
  77. const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
  78. if (n1 === undefined || n2 === undefined) {
  79. const char = hex[hi] + hex[hi + 1];
  80. throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
  81. }
  82. array[ai] = n1 * 16 + n2;
  83. }
  84. return array;
  85. }
  86. // There is no setImmediate in browser and setTimeout is slow.
  87. // call of async fn will return Promise, which will be fullfiled only on
  88. // next scheduler queue processing step and this is exactly what we need.
  89. export const nextTick = async () => { };
  90. // Returns control to thread each 'tick' ms to avoid blocking
  91. export async function asyncLoop(iters, tick, cb) {
  92. let ts = Date.now();
  93. for (let i = 0; i < iters; i++) {
  94. cb(i);
  95. // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
  96. const diff = Date.now() - ts;
  97. if (diff >= 0 && diff < tick)
  98. continue;
  99. await nextTick();
  100. ts += diff;
  101. }
  102. }
  103. /**
  104. * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
  105. */
  106. export function utf8ToBytes(str) {
  107. if (typeof str !== 'string')
  108. throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
  109. return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
  110. }
  111. /**
  112. * Normalizes (non-hex) string or Uint8Array to Uint8Array.
  113. * Warning: when Uint8Array is passed, it would NOT get copied.
  114. * Keep in mind for future mutable operations.
  115. */
  116. export function toBytes(data) {
  117. if (typeof data === 'string')
  118. data = utf8ToBytes(data);
  119. abytes(data);
  120. return data;
  121. }
  122. /**
  123. * Copies several Uint8Arrays into one.
  124. */
  125. export function concatBytes(...arrays) {
  126. let sum = 0;
  127. for (let i = 0; i < arrays.length; i++) {
  128. const a = arrays[i];
  129. abytes(a);
  130. sum += a.length;
  131. }
  132. const res = new Uint8Array(sum);
  133. for (let i = 0, pad = 0; i < arrays.length; i++) {
  134. const a = arrays[i];
  135. res.set(a, pad);
  136. pad += a.length;
  137. }
  138. return res;
  139. }
  140. // For runtime check if class implements interface
  141. export class Hash {
  142. // Safe version that clones internal state
  143. clone() {
  144. return this._cloneInto();
  145. }
  146. }
  147. const toStr = {}.toString;
  148. export function checkOpts(defaults, opts) {
  149. if (opts !== undefined && toStr.call(opts) !== '[object Object]')
  150. throw new Error('Options should be object or undefined');
  151. const merged = Object.assign(defaults, opts);
  152. return merged;
  153. }
  154. export function wrapConstructor(hashCons) {
  155. const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
  156. const tmp = hashCons();
  157. hashC.outputLen = tmp.outputLen;
  158. hashC.blockLen = tmp.blockLen;
  159. hashC.create = () => hashCons();
  160. return hashC;
  161. }
  162. export function wrapConstructorWithOpts(hashCons) {
  163. const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
  164. const tmp = hashCons({});
  165. hashC.outputLen = tmp.outputLen;
  166. hashC.blockLen = tmp.blockLen;
  167. hashC.create = (opts) => hashCons(opts);
  168. return hashC;
  169. }
  170. export function wrapXOFConstructorWithOpts(hashCons) {
  171. const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
  172. const tmp = hashCons({});
  173. hashC.outputLen = tmp.outputLen;
  174. hashC.blockLen = tmp.blockLen;
  175. hashC.create = (opts) => hashCons(opts);
  176. return hashC;
  177. }
  178. /**
  179. * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.
  180. */
  181. export function randomBytes(bytesLength = 32) {
  182. if (crypto && typeof crypto.getRandomValues === 'function') {
  183. return crypto.getRandomValues(new Uint8Array(bytesLength));
  184. }
  185. throw new Error('crypto.getRandomValues must be defined');
  186. }
  187. //# sourceMappingURL=utils.js.map