ethers.js/packages/random/lib/browser-random.js

46 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2019-05-14 18:48:48 -04:00
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
2021-03-07 18:24:04 -05:00
exports.randomBytes = void 0;
2019-05-14 18:48:48 -04:00
var bytes_1 = require("@ethersproject/bytes");
2019-08-02 02:10:58 -04:00
var logger_1 = require("@ethersproject/logger");
var _version_1 = require("./_version");
var logger = new logger_1.Logger(_version_1.version);
2021-10-16 02:29:27 -04:00
// Debugging line for testing browser lib in node
//const window = { crypto: { getRandomValues: () => { } } };
2021-12-24 03:09:45 -05:00
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
function getGlobal() {
if (typeof self !== 'undefined') {
return self;
2020-04-18 05:14:55 -04:00
}
2021-12-24 03:09:45 -05:00
if (typeof window !== 'undefined') {
return window;
2020-04-18 05:14:55 -04:00
}
2021-12-24 03:09:45 -05:00
if (typeof global !== 'undefined') {
return global;
2020-04-18 05:14:55 -04:00
}
2021-12-24 03:09:45 -05:00
throw new Error('unable to locate global object');
2020-04-18 05:14:55 -04:00
}
2021-12-24 03:09:45 -05:00
;
var anyGlobal = getGlobal();
2020-04-18 05:14:55 -04:00
var crypto = anyGlobal.crypto || anyGlobal.msCrypto;
2019-05-14 18:48:48 -04:00
if (!crypto || !crypto.getRandomValues) {
2019-08-02 02:10:58 -04:00
logger.warn("WARNING: Missing strong random number source");
2019-05-14 18:48:48 -04:00
crypto = {
getRandomValues: function (buffer) {
2019-08-02 02:10:58 -04:00
return logger.throwError("no secure random source avaialble", logger_1.Logger.errors.UNSUPPORTED_OPERATION, {
2019-05-14 18:48:48 -04:00
operation: "crypto.getRandomValues"
});
}
};
}
function randomBytes(length) {
2021-10-16 02:29:27 -04:00
if (length <= 0 || length > 1024 || (length % 1) || length != length) {
2019-08-02 02:10:58 -04:00
logger.throwArgumentError("invalid length", "length", length);
2019-05-14 18:48:48 -04:00
}
var result = new Uint8Array(length);
crypto.getRandomValues(result);
2021-10-16 02:29:27 -04:00
return (0, bytes_1.arrayify)(result);
2019-05-14 18:48:48 -04:00
}
exports.randomBytes = randomBytes;
;
2020-11-16 23:07:24 -05:00
//# sourceMappingURL=browser-random.js.map