utils.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import assert from "@noble/hashes/_assert";
  2. import { hexToBytes as _hexToBytes } from "@noble/hashes/utils";
  3. const assertBool = assert.bool;
  4. const assertBytes = assert.bytes;
  5. export { assertBool, assertBytes };
  6. export { bytesToHex, bytesToHex as toHex, concatBytes, createView, utf8ToBytes } from "@noble/hashes/utils";
  7. // buf.toString('utf8') -> bytesToUtf8(buf)
  8. export function bytesToUtf8(data) {
  9. if (!(data instanceof Uint8Array)) {
  10. throw new TypeError(`bytesToUtf8 expected Uint8Array, got ${typeof data}`);
  11. }
  12. return new TextDecoder().decode(data);
  13. }
  14. export function hexToBytes(data) {
  15. const sliced = data.startsWith("0x") ? data.substring(2) : data;
  16. return _hexToBytes(sliced);
  17. }
  18. // buf.equals(buf2) -> equalsBytes(buf, buf2)
  19. export function equalsBytes(a, b) {
  20. if (a.length !== b.length) {
  21. return false;
  22. }
  23. for (let i = 0; i < a.length; i++) {
  24. if (a[i] !== b[i]) {
  25. return false;
  26. }
  27. }
  28. return true;
  29. }
  30. // Internal utils
  31. export function wrapHash(hash) {
  32. return (msg) => {
  33. assert.bytes(msg);
  34. return hash(msg);
  35. };
  36. }
  37. // TODO(v3): switch away from node crypto, remove this unnecessary variable.
  38. export const crypto = (() => {
  39. const webCrypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : undefined;
  40. const nodeRequire = typeof module !== "undefined" &&
  41. typeof module.require === "function" &&
  42. module.require.bind(module);
  43. return {
  44. node: nodeRequire && !webCrypto ? nodeRequire("crypto") : undefined,
  45. web: webCrypto
  46. };
  47. })();