2019-05-14 18:25:46 -04:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
import { arrayify } from "@ethersproject/bytes";
|
2019-08-01 18:04:06 -04:00
|
|
|
|
|
|
|
import { Logger } from "@ethersproject/logger";
|
|
|
|
import { version } from "./_version";
|
|
|
|
const logger = new Logger(version);
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2021-10-04 11:08:58 -04:00
|
|
|
// Debugging line for testing browser lib in node
|
|
|
|
//const window = { crypto: { getRandomValues: () => { } } };
|
|
|
|
|
2021-12-24 02:05:10 -05:00
|
|
|
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis
|
|
|
|
function getGlobal(): any {
|
|
|
|
if (typeof self !== 'undefined') { return self; }
|
|
|
|
if (typeof window !== 'undefined') { return window; }
|
|
|
|
if (typeof global !== 'undefined') { return global; }
|
|
|
|
throw new Error('unable to locate global object');
|
|
|
|
};
|
|
|
|
|
|
|
|
const anyGlobal = getGlobal();
|
2020-04-18 05:14:55 -04:00
|
|
|
|
|
|
|
let crypto: any = anyGlobal.crypto || anyGlobal.msCrypto;
|
2019-05-14 18:25:46 -04:00
|
|
|
if (!crypto || !crypto.getRandomValues) {
|
|
|
|
|
2019-08-01 18:04:06 -04:00
|
|
|
logger.warn("WARNING: Missing strong random number source");
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
crypto = {
|
|
|
|
getRandomValues: function(buffer: Uint8Array): Uint8Array {
|
2019-08-01 18:04:06 -04:00
|
|
|
return logger.throwError("no secure random source avaialble", Logger.errors.UNSUPPORTED_OPERATION, {
|
2019-05-14 18:25:46 -04:00
|
|
|
operation: "crypto.getRandomValues"
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export function randomBytes(length: number): Uint8Array {
|
2021-10-04 11:08:58 -04:00
|
|
|
if (length <= 0 || length > 1024 || (length % 1) || length != length) {
|
2019-08-01 18:04:06 -04:00
|
|
|
logger.throwArgumentError("invalid length", "length", length);
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
2019-11-01 23:33:51 +09:00
|
|
|
const result = new Uint8Array(length);
|
2019-05-14 18:25:46 -04:00
|
|
|
crypto.getRandomValues(result);
|
|
|
|
return arrayify(result);
|
|
|
|
};
|