random.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. "use strict";
  2. import { arrayify } from "@ethersproject/bytes";
  3. import { Logger } from "@ethersproject/logger";
  4. import { version } from "./_version";
  5. const logger = new Logger(version);
  6. // Debugging line for testing browser lib in node
  7. //const window = { crypto: { getRandomValues: () => { } } };
  8. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
  9. function getGlobal() {
  10. if (typeof self !== 'undefined') {
  11. return self;
  12. }
  13. if (typeof window !== 'undefined') {
  14. return window;
  15. }
  16. if (typeof global !== 'undefined') {
  17. return global;
  18. }
  19. throw new Error('unable to locate global object');
  20. }
  21. ;
  22. const anyGlobal = getGlobal();
  23. let crypto = anyGlobal.crypto || anyGlobal.msCrypto;
  24. if (!crypto || !crypto.getRandomValues) {
  25. logger.warn("WARNING: Missing strong random number source");
  26. crypto = {
  27. getRandomValues: function (buffer) {
  28. return logger.throwError("no secure random source avaialble", Logger.errors.UNSUPPORTED_OPERATION, {
  29. operation: "crypto.getRandomValues"
  30. });
  31. }
  32. };
  33. }
  34. export function randomBytes(length) {
  35. if (length <= 0 || length > 1024 || (length % 1) || length != length) {
  36. logger.throwArgumentError("invalid length", "length", length);
  37. }
  38. const result = new Uint8Array(length);
  39. crypto.getRandomValues(result);
  40. return arrayify(result);
  41. }
  42. ;
  43. //# sourceMappingURL=random.js.map