Ensure JS compatibility on browser environments

This commit is contained in:
Jordi 2019-02-14 23:18:53 +01:00
parent b7f5cce74b
commit 9360dd121f
3 changed files with 31 additions and 9 deletions

@ -18,7 +18,6 @@
*/
const bigInt = require("./bigint.js");
const assert = require("assert");
const F1Field = require("./zqfield.js");
const F2Field = require("./f2field.js");
@ -160,9 +159,15 @@ class BN128 {
}
const Q1 = this.G2.affine(this._g2MulByQ(Qcopy));
assert(this.F2.equals(Q1[2], this.F2.one));
if (!this.F2.equals(Q1[2], this.F2.one))
{
throw new Error("Expected values are not equal");
}
const Q2 = this.G2.affine(this._g2MulByQ(Q1));
assert(this.F2.equals(Q2[2], this.F2.one));
if (!this.F2.equals(Q2[2], this.F2.one))
{
throw new Error("Expected values are not equal");
}
if (this.loopCountNef)
{

@ -25,7 +25,6 @@
*/
const bigInt = require("./bigint.js");
const assert = require("assert");
class PolField {
constructor (F) {
@ -446,8 +445,12 @@ class PolField {
let res = this.F.one;
let r = i;
assert(i<n);
assert(1<<nbits === n);
if(i>=n) {
throw new Error("Given 'i' should be lower than 'n'");
}
else if (1<<nbits !== n) {
throw new Error(`Internal errlr: ${n} should equal ${1<<nbits}`);
}
while (r>0) {
if (r & 1 == 1) {

@ -17,11 +17,25 @@
snarkjs. If not, see <https://www.gnu.org/licenses/>.
*/
const crypto = require("crypto");
const bigInt = require("./bigint");
const fUtils = require("./futils.js");
function getRandomByte() {
if (typeof window !== "undefined") { // Browser
if (typeof window.crypto !== "undefined") { // Supported
let array = new Uint8Array(1);
window.crypto.getRandomValues(array);
return array[0];
}
else { // fallback
return Math.floor(Math.random() * 256);
}
}
else { // NodeJS
return module.require("crypto").randomBytes(1)[0];
}
}
class ZqField {
constructor(q) {
this.q = bigInt(q);
@ -85,7 +99,7 @@ class ZqField {
let res = bigInt(0);
let n = bigInt(this.q);
while (!n.isZero()) {
res = res.shl(8).add(bigInt(crypto.randomBytes(1)[0]));
res = res.shl(8).add(bigInt(getRandomByte()));
n = n.shr(8);
}
return res;