utils.js 8.2 KB

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