2019-08-25 02:39:20 -04:00
|
|
|
"use strict";
|
|
|
|
import { arrayify } from "@ethersproject/bytes";
|
|
|
|
import { Logger } from "@ethersproject/logger";
|
|
|
|
import { version } from "./_version";
|
|
|
|
const logger = new Logger(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
|
|
|
;
|
|
|
|
const anyGlobal = getGlobal();
|
2020-04-18 05:14:55 -04:00
|
|
|
let crypto = anyGlobal.crypto || anyGlobal.msCrypto;
|
2019-08-25 02:39:20 -04:00
|
|
|
if (!crypto || !crypto.getRandomValues) {
|
|
|
|
logger.warn("WARNING: Missing strong random number source");
|
|
|
|
crypto = {
|
|
|
|
getRandomValues: function (buffer) {
|
|
|
|
return logger.throwError("no secure random source avaialble", Logger.errors.UNSUPPORTED_OPERATION, {
|
|
|
|
operation: "crypto.getRandomValues"
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
export function randomBytes(length) {
|
2021-10-16 02:29:27 -04:00
|
|
|
if (length <= 0 || length > 1024 || (length % 1) || length != length) {
|
2019-08-25 02:39:20 -04:00
|
|
|
logger.throwArgumentError("invalid length", "length", length);
|
|
|
|
}
|
2019-11-20 18:57:38 +09:00
|
|
|
const result = new Uint8Array(length);
|
2019-08-25 02:39:20 -04:00
|
|
|
crypto.getRandomValues(result);
|
|
|
|
return arrayify(result);
|
|
|
|
}
|
|
|
|
;
|
2020-11-16 23:07:24 -05:00
|
|
|
//# sourceMappingURL=random.js.map
|