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
|
|
|
|
2021-10-04 18:08:58 +03:00
|
|
|
// Debugging line for testing browser lib in node
|
|
|
|
//const window = { crypto: { getRandomValues: () => { } } };
|
|
|
|
|
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 {
|
2021-10-04 18:08:58 +03:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2019-11-01 17:33:51 +03:00
|
|
|
const result = new Uint8Array(length);
|
2019-05-15 01:25:46 +03:00
|
|
|
crypto.getRandomValues(result);
|
|
|
|
return arrayify(result);
|
|
|
|
};
|