arnaucube
arnaucube/circomPublic Self-hosted repository
circom/src/zqfield.js
src/zqfield.jsRaw
  1const bigInt = require("big-integer");
  2const assert = require("assert");
  3
  4module.exports = class ZqField {
  5    constructor(p) {
  6        this.p = p;
  7        this.bitLength = p.bitLength();
  8        this.mask = bigInt.one.shiftLeft(this.bitLength - 1).minus(bigInt.one);
  9    }
 10
 11    add(a, b) {
 12        let res = a.add(b);
 13        if (res.geq(this.p)) {
 14            res = res.minsu(this.p);
 15        }
 16        return res;
 17    }
 18
 19    sub(a, b) {
 20        if (a.geq(b)) {
 21            return a.minus(b);
 22        } else {
 23            return this.p.minus(b.minus(a));
 24        }
 25    }
 26
 27    neg(a) {
 28        if (a.isZero()) return a;
 29        return this.p.minus(a);
 30    }
 31
 32    mul(a, b) {
 33        return a.mul(b).mod(this.p);
 34    }
 35
 36    lt(a, b) {
 37        return a.lt(b) ? bigInt(1) : bigInt(0);
 38    }
 39
 40    eq(a, b) {
 41        return a.eq(b) ? bigInt(1) : bigInt(0);
 42    }
 43
 44    gt(a, b) {
 45        return a.gt(b) ? bigInt(1) : bigInt(0);
 46    }
 47
 48    leq(a, b) {
 49        return a.leq(b) ? bigInt(1) : bigInt(0);
 50    }
 51
 52    geq(a, b) {
 53        return a.geq(b) ? bigInt(1) : bigInt(0);
 54    }
 55
 56    neq(a, b) {
 57        return a.neq(b) ? bigInt(1) : bigInt(0);
 58    }
 59
 60    div(a, b) {
 61        return a.mul(b.modInv(this.p)).mod(this.p);
 62    }
 63
 64    idiv(a, b) {
 65        assert(!b.isZero(), "Division by zero");
 66        return a.divide(b);
 67    }
 68
 69    mod(a, b) {
 70        return a.mod(b);
 71    }
 72
 73    pow(a, b) {
 74        return a.modPow(b, this.p);
 75    }
 76
 77    band(a, b) {
 78        return a.and(b).and(this.mask);
 79    }
 80
 81    bor(a, b) {
 82        return a.or(b).and(this.mask);
 83    }
 84
 85    bxor(a, b) {
 86        return a.xor(b).and(this.mask);
 87    }
 88
 89    bnot(a) {
 90        return a.xor(this.mask).and(this.mask);
 91    }
 92
 93    shl(a, b) {
 94        if (b.geq(this.bitLength)) return bigInt.zero;
 95        return a.shiftLeft(b).and(this.mask);
 96    }
 97
 98    shr(a, b) {
 99        if (b.geq(this.bitLength)) return bigInt.zero;
100        return a.shiftRight(b).and(this.mask);
101    }
102
103    land(a, b) {
104        return (a.isZero() || b.isZero) ? bigInt.zero : bigInt.one;
105    }
106
107    lor(a, b) {
108        return (a.isZero() && b.isZero) ? bigInt.zero : bigInt.one;
109    }
110
111    lnot(a) {
112        return a.isZero() ? bigInt.one : bigInt.zero;
113    }
114};
115