@apocentre/bc-ur
Version:
A JS implementation of the Uniform Resources (UR) specification from Blockchain Commons
59 lines • 2.43 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const big_integer_1 = __importDefault(require("big-integer"));
const MAX_UINT64 = 0xFFFFFFFFFFFFFFFF;
const rotl = (x, k) => asUintN(64, x.shiftLeft(k))
.or(asUintN(64, x.shiftRight((big_integer_1.default(64).minus(k)))));
const asUintN = (bits, bigint) => {
const p2bits = big_integer_1.default(1).shiftLeft(bits);
const mod = bigint.and(p2bits.subtract(1));
return mod;
};
class Xoshiro {
constructor(seed) {
this.next = () => {
return new bignumber_js_1.default(this.roll().toString());
};
this.nextDouble = () => {
return new bignumber_js_1.default(this.roll().toString()).div(MAX_UINT64 + 1);
};
this.nextInt = (low, high) => {
return Math.floor((this.nextDouble().toNumber() * (high - low + 1)) + low);
};
this.nextByte = () => this.nextInt(0, 255);
this.nextData = (count) => ([...new Array(count)].map(() => this.nextByte()));
const digest = utils_1.sha256Hash(seed);
this.s = [big_integer_1.default(0), big_integer_1.default(0), big_integer_1.default(0), big_integer_1.default(0)];
this.setS(digest);
}
setS(digest) {
for (let i = 0; i < 4; i++) {
let o = i * 8;
let v = big_integer_1.default(0);
for (let n = 0; n < 8; n++) {
v = asUintN(64, v.shiftLeft(8));
v = asUintN(64, v.or(digest[o + n]));
}
this.s[i] = asUintN(64, v);
}
}
roll() {
const result = asUintN(64, rotl(asUintN(64, this.s[1].multiply(5)), 7)
.multiply(9));
const t = asUintN(64, this.s[1].shiftLeft(17));
this.s[2] = asUintN(64, this.s[2].xor(this.s[0]));
this.s[3] = asUintN(64, this.s[3].xor(this.s[1]));
this.s[1] = asUintN(64, this.s[1].xor(this.s[2]));
this.s[0] = asUintN(64, this.s[0].xor(this.s[3]));
this.s[2] = asUintN(64, this.s[2].xor(t));
this.s[3] = asUintN(64, rotl(this.s[3], 45));
return result;
}
}
exports.default = Xoshiro;
//# sourceMappingURL=xoshiro.js.map