UNPKG

predict-v8-randomness

Version:
182 lines (181 loc) 11.4 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; }; var _Predictor_instances, _Predictor_MIN_SEQUENCE_LENGTH, _Predictor_MAX_PREDICT_NEXT_AMOUNT, _Predictor_isInitialized, _Predictor_seState0, _Predictor_seState1, _Predictor_solver, _Predictor_context, _Predictor_internalSequence, _Predictor_initialize, _Predictor_predict, _Predictor_xorShift128Plus, _Predictor_doubleToUInt64, _Predictor_toDouble; Object.defineProperty(exports, "__esModule", { value: true }); const z3 = __importStar(require("z3-solver")); class Predictor { constructor(sequence) { _Predictor_instances.add(this); // In my testing, I discovered we need at least 4 items in order to predict correctly. _Predictor_MIN_SEQUENCE_LENGTH.set(this, 4); // Due to the way V8 generates the pool of random numbers, we lose accuracy when the // 'initial sequence length' + the 'amount-of-numbers-to-predict-next' is >= 64. // Since we need 4 random numbers to start with, the absolute max amount of numbers // we can predict next is 60, but we do need to calculate the max if a user provided // the initial sequence. We need to subtract the initial sequence length from 64. _Predictor_MAX_PREDICT_NEXT_AMOUNT.set(this, 60); _Predictor_isInitialized.set(this, false); _Predictor_seState0.set(this, void 0); _Predictor_seState1.set(this, void 0); _Predictor_solver.set(this, void 0); _Predictor_context.set(this, void 0); _Predictor_internalSequence.set(this, []); this.sequence = []; if (sequence === undefined) { // Generate sequence ourselves sequence = Array.from({ length: __classPrivateFieldGet(this, _Predictor_MIN_SEQUENCE_LENGTH, "f") }, Math.random); } if (sequence.length !== __classPrivateFieldGet(this, _Predictor_MIN_SEQUENCE_LENGTH, "f")) { throw new Error(`[Predictor] We expect sequence to contain only ${__classPrivateFieldGet(this, _Predictor_MIN_SEQUENCE_LENGTH, "f")} numbers! Got ${sequence.length} numbers`); } __classPrivateFieldSet(this, _Predictor_internalSequence, [...sequence], "f"); this.sequence = [...__classPrivateFieldGet(this, _Predictor_internalSequence, "f")]; __classPrivateFieldGet(this, _Predictor_internalSequence, "f").reverse(); } predictNext() { return __awaiter(this, arguments, void 0, function* (n = 1) { // Due to the way V8 generates the pool of random numbers, we lose accuracy when the // 'initial sequence length' + the 'amount-of-numbers-to-predict-next' is >= 64. // Since we need 4 random numbers to start with, the absolute max amount of numbers // we can predict next is 60, but we do need to calculate the max if a user provided // the initial sequence. We need to subtract the initial sequence length from 64. if (n > __classPrivateFieldGet(this, _Predictor_MAX_PREDICT_NEXT_AMOUNT, "f")) { throw new Error(`[Predictor] Max amount we can predict next is ${__classPrivateFieldGet(this, _Predictor_MAX_PREDICT_NEXT_AMOUNT, "f")}\n[Predictor] Got ${n}`); } if (n === 0) { return []; } const predictions = new Array(n).fill(-1); for (let i = 0; i < n; i++) { const next = yield __classPrivateFieldGet(this, _Predictor_instances, "m", _Predictor_predict).call(this); predictions[i] = next; __classPrivateFieldGet(this, _Predictor_internalSequence, "f").unshift(next); // Only keep 4 numbers since that seems to be what we need to successfully predict. if (__classPrivateFieldGet(this, _Predictor_internalSequence, "f").length > 4) { __classPrivateFieldGet(this, _Predictor_internalSequence, "f").splice(4); } } return predictions; }); } } _Predictor_MIN_SEQUENCE_LENGTH = new WeakMap(), _Predictor_MAX_PREDICT_NEXT_AMOUNT = new WeakMap(), _Predictor_isInitialized = new WeakMap(), _Predictor_seState0 = new WeakMap(), _Predictor_seState1 = new WeakMap(), _Predictor_solver = new WeakMap(), _Predictor_context = new WeakMap(), _Predictor_internalSequence = new WeakMap(), _Predictor_instances = new WeakSet(), _Predictor_initialize = function _Predictor_initialize() { return __awaiter(this, void 0, void 0, function* () { if (__classPrivateFieldGet(this, _Predictor_isInitialized, "f")) { return true; } try { const { Context } = yield z3.init(); __classPrivateFieldSet(this, _Predictor_context, Context("main"), "f"); __classPrivateFieldSet(this, _Predictor_isInitialized, true, "f"); return true; } catch (e) { return false; } }); }, _Predictor_predict = function _Predictor_predict() { return __awaiter(this, void 0, void 0, function* () { if (!__classPrivateFieldGet(this, _Predictor_isInitialized, "f")) { if (!(yield __classPrivateFieldGet(this, _Predictor_instances, "m", _Predictor_initialize).call(this))) { return Promise.reject("[Predictor] Initialization failed!"); } } if (__classPrivateFieldGet(this, _Predictor_context, "f") === undefined) { return Promise.reject("[Predictor] Context not initialized!"); } __classPrivateFieldSet(this, _Predictor_solver, new (__classPrivateFieldGet(this, _Predictor_context, "f").Solver)(), "f"); __classPrivateFieldSet(this, _Predictor_seState0, __classPrivateFieldGet(this, _Predictor_context, "f").BitVec.const("se_state0", 64), "f"); __classPrivateFieldSet(this, _Predictor_seState1, __classPrivateFieldGet(this, _Predictor_context, "f").BitVec.const("se_state1", 64), "f"); for (let i = 0; i < __classPrivateFieldGet(this, _Predictor_internalSequence, "f").length; i++) { __classPrivateFieldGet(this, _Predictor_instances, "m", _Predictor_xorShift128Plus).call(this, __classPrivateFieldGet(this, _Predictor_seState0, "f"), __classPrivateFieldGet(this, _Predictor_seState1, "f")); const uint64 = __classPrivateFieldGet(this, _Predictor_instances, "m", _Predictor_doubleToUInt64).call(this, __classPrivateFieldGet(this, _Predictor_internalSequence, "f")[i] + 1); const mantissa = uint64 & ((BigInt(1) << BigInt(52)) - BigInt(1)); __classPrivateFieldGet(this, _Predictor_solver, "f").add(__classPrivateFieldGet(this, _Predictor_seState0, "f").lshr(12).eq(__classPrivateFieldGet(this, _Predictor_context, "f").BitVec.val(mantissa, 64))); } const check = yield __classPrivateFieldGet(this, _Predictor_solver, "f").check(); if (check !== "sat") { throw new Error(`Unsatisfiable: unable to reconstruct internal state. ${check}`); } const model = __classPrivateFieldGet(this, _Predictor_solver, "f").model(); const states = {}; for (const state of model.decls()) { // @ts-ignore states[state.name()] = model.get(state); } // @ts-ignore const state0 = states["se_state0"].value(); // BigInt return __classPrivateFieldGet(this, _Predictor_instances, "m", _Predictor_toDouble).call(this, state0); }); }, _Predictor_xorShift128Plus = function _Predictor_xorShift128Plus(state0, state1) { let s1 = state0; let s0 = state1; __classPrivateFieldSet(this, _Predictor_seState0, s0, "f"); s1 = s1.xor(s1.shl(23)); s1 = s1.xor(s1.lshr(17)); s1 = s1.xor(s0); s1 = s1.xor(s0.lshr(26)); __classPrivateFieldSet(this, _Predictor_seState1, s1, "f"); }, _Predictor_doubleToUInt64 = function _Predictor_doubleToUInt64(value) { const buffer = Buffer.alloc(8); buffer.writeDoubleLE(value, 0); return (BigInt(buffer.readUInt32LE(4)) << BigInt(32)) | BigInt(buffer.readUInt32LE(0)); }, _Predictor_toDouble = function _Predictor_toDouble(n) { const random = (n >> BigInt(12)) | BigInt(0x3ff0000000000000); const buffer = Buffer.allocUnsafe(8); buffer.writeBigUInt64LE(random, 0); return buffer.readDoubleLE(0) - 1; }; exports.default = Predictor;