ethers.js/packages/random/src.ts/browser-random.ts

45 lines
1.4 KiB
TypeScript
Raw Normal View History

2019-05-15 01:25:46 +03:00
"use strict";
import { arrayify } from "@ethersproject/bytes";
2019-08-02 01:04:06 +03:00
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
2019-05-15 01:25:46 +03:00
// Debugging line for testing browser lib in node
//const window = { crypto: { getRandomValues: () => { } } };
// 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 12:14:55 +03:00
let crypto: any = anyGlobal.crypto || anyGlobal.msCrypto;
2019-05-15 01:25:46 +03:00
if (!crypto || !crypto.getRandomValues) {
2019-08-02 01:04:06 +03:00
logger.warn("WARNING: Missing strong random number source");
2019-05-15 01:25:46 +03:00
crypto = {
getRandomValues: function(buffer: Uint8Array): Uint8Array {
2019-08-02 01:04:06 +03:00
return logger.throwError("no secure random source avaialble", Logger.errors.UNSUPPORTED_OPERATION, {
2019-05-15 01:25:46 +03:00
operation: "crypto.getRandomValues"
});
}
};
}
export function randomBytes(length: number): Uint8Array {
if (length <= 0 || length > 1024 || (length % 1) || length != length) {
2019-08-02 01:04:06 +03:00
logger.throwArgumentError("invalid length", "length", length);
2019-05-15 01:25:46 +03:00
}
const result = new Uint8Array(length);
2019-05-15 01:25:46 +03:00
crypto.getRandomValues(result);
return arrayify(result);
};