arnaucube
arnaucube/snarkjsPublic Self-hosted repository
snarkjs/src/f1field.js
src/f1field.jsRaw
 1const bigInt = require("big-integer");
 2
 3class F1Field {
 4    constructor(q) {
 5        this.q = q;
 6        this.nq = bigInt.zero.minus(q);
 7        this.zero = bigInt.zero;
 8        this.one = bigInt.one;
 9    }
10
11    e(a) {
12        return bigInt(a);
13    }
14
15    copy(a) {
16        return bigInt(a);
17    }
18
19    add(a, b) {
20        return a.add(b);
21    }
22
23    sub(a, b) {
24        return a.minus(b);
25    }
26
27    neg(a) {
28        return bigInt.zero.minus(a);
29    }
30
31    mul(a, b) {
32        return a.times(b).mod(this.q);
33    }
34
35    inverse(a) {
36        return this.affine(a).modInv(this.q);
37    }
38
39    div(a, b) {
40        return this.mul(a, this.inverse(b));
41    }
42
43    square(a) {
44        return a.square().mod(this.q);
45    }
46
47    isZero(a) {
48        return a.isZero();
49    }
50
51    equals(a, b) {
52        return this.affine(a).equals(this.affine(b));
53    }
54
55    affine(a) {
56        let aux = a;
57        if (aux.isNegative()) {
58            if (aux.lesserOrEquals(this.nq)) {
59                aux = a.mod(this.q);
60            }
61            if (aux.isNegative()) {
62                aux = aux.add(this.q);
63            }
64        } else {
65            if (aux.greaterOrEquals(this.q)) {
66                aux = aux.mod(this.q);
67            }
68        }
69        return aux;
70    }
71
72    toString(a) {
73        const ca = this.affine(a);
74        return `"0x${ca.toString(16)}"`;
75    }
76}
77
78module.exports = F1Field;