Make Math.random() deterministic in provisions
Replace Math.random() in sandbox with a seedable implementation so that the script remains deterministic.
This commit is contained in:
1 parent
3e4f4b29ab
commit
7644d46f6b
2 files changed
+19
-1
No files matched your search
@@ -18,6 +18,8 @@
|
||||
|
||||
const vm = require("vm");
|
||||
|
||||
const seedrandom = require("seedrandom");
|
||||
|
||||
const common = require("./common");
|
||||
const device = require("./device");
|
||||
const extensions = require("./extensions");
|
||||
@@ -38,6 +40,8 @@ const sandbox = {
|
||||
declarations: null,
|
||||
extensionsCache: null,
|
||||
extensions: null,
|
||||
clear: null,
|
||||
rng: null,
|
||||
context: vm.createContext()
|
||||
}
|
||||
|
||||
@@ -54,6 +58,13 @@ class SandboxDate {
|
||||
}
|
||||
};
|
||||
|
||||
function random() {
|
||||
if (!sandbox.rng)
|
||||
sandbox.rng = seedrandom(sandbox.timestamp);
|
||||
|
||||
return sandbox.rng();
|
||||
}
|
||||
|
||||
|
||||
class ParameterWrapper {
|
||||
constructor(path, attributes, unpacked, unpackedRevision) {
|
||||
@@ -203,6 +214,11 @@ Object.defineProperty(sandbox.context, 'clear', {value: clear});
|
||||
Object.defineProperty(sandbox.context, 'commit', {value: commit});
|
||||
Object.defineProperty(sandbox.context, 'ext', {value: ext});
|
||||
|
||||
// Monkey-patch Math.random() to make it deterministic
|
||||
sandbox.context.random = random;
|
||||
vm.runInContext("Math.random = random;", sandbox.context);
|
||||
delete sandbox.random;
|
||||
|
||||
|
||||
function errorToFault(err) {
|
||||
if (!err)
|
||||
@@ -230,6 +246,7 @@ function run(script, globals, timestamp, deviceData, extensionsCache, startRevis
|
||||
sandbox.declarations = [];
|
||||
sandbox.extensions = {};
|
||||
sandbox.clear = null;
|
||||
sandbox.rng = null;
|
||||
|
||||
for (let n in sandbox.context)
|
||||
delete sandbox.context[n];
|
||||
|
||||
Reference in new issue
Block a user