arnaucube
arnaucube/snarkjsPublic Self-hosted repository
snarkjs/src/zqfield.js
src/zqfield.jsRaw
 1/*
 2    Copyright 2018 0kims association.
 3
 4    This file is part of snarkjs.
 5
 6    snarkjs is a free software: you can redistribute it and/or
 7    modify it under the terms of the GNU General Public License as published by the
 8    Free Software Foundation, either version 3 of the License, or (at your option)
 9    any later version.
10
11    snarkjs is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14    more details.
15
16    You should have received a copy of the GNU General Public License along with
17    snarkjs. If not, see <https://www.gnu.org/licenses/>.
18*/
19
20const crypto = require("crypto");
21
22const bigInt = require("./bigint");
23const fUtils = require("./futils.js");
24
25class ZqField {
26    constructor(q) {
27        this.q = q;
28        this.zero = bigInt.zero;
29        this.one = bigInt.one;
30        this.add = bigInt.genAdd();
31        this.double = bigInt.genDouble();
32        this.sub = bigInt.genSub();
33        this.neg = bigInt.genNeg();
34        this.mul = bigInt.genMul(q);
35        this.inverse = bigInt.genInverse(q);
36        this.square = bigInt.genSquare(q);
37        this.equals = bigInt.genEquals(q);
38        this.affine = bigInt.genAffine(q);
39        this.isZero = bigInt.genIsZero(q);
40        this.two = this.add(this.one, this.one);
41        this.twoinv = this.inverse(this.two);
42    }
43
44    copy(a) {
45        return bigInt(a);
46    }
47
48    div(a, b) {
49        return this.mul(a, this.inverse(b));
50    }
51
52    mulScalar(base, e) {
53        return this.mul(base, bigInt(e));
54    }
55
56    exp(base, e) {
57        return fUtils.exp(this, base, e);
58    }
59
60    toString(a) {
61        const ca = this.affine(a);
62        return `"0x${ca.toString(16)}"`;
63    }
64
65    random() {
66        let res = bigInt(0);
67        let n = bigInt(this.q);
68        while (!n.isZero()) {
69            res = res.shl(8).add(bigInt(crypto.randomBytes(1)[0]));
70            n = n.shr(8);
71        }
72        return res;
73    }
74}
75
76
77module.exports = ZqField;