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

45 lines
1.2 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
2020-04-18 12:14:55 +03:00
let anyGlobal: any = null;
try {
anyGlobal = (window as any);
if (anyGlobal == null) { throw new Error("try next"); }
} catch (error) {
try {
anyGlobal = (global as any);
if (anyGlobal == null) { throw new Error("try next"); }
} catch (error) {
anyGlobal = { };
}
}
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 {
2020-04-18 12:14:55 +03:00
if (length <= 0 || length > 1024 || (length % 1)) {
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);
};