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:
Zaid Abdulla committed 2017-01-01 05:50:43 -08:00
1 parent 3e4f4b29ab
commit 7644d46f6b
2 files changed
+19 -1

No files matched your search

+17
View File
@@ -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];
+2 -1
View File
@@ -24,7 +24,8 @@
"libxmljs": "^0.18.0",
"redis": "^2.6.2",
"hiredis": "^0.5.0",
"mongodb": "^2.2.4"
"mongodb": "^2.2.4",
"seedrandom": "^2.4.2"
},
"devDependencies": {
"coffee-script": "^1.10.0"