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        assert(!b.isZero(), "Division by zero");
 62        return a.mul(b.modInv(this.p)).mod(this.p);
 63    }
 64
 65    idiv(a, b) {
 66        assert(!b.isZero(), "Division by zero");
 67        return a.divide(b);
 68    }
 69
 70    mod(a, b) {
 71        return a.mod(b);
 72    }
 73
 74    pow(a, b) {
 75        return a.modPow(b, this.p);
 76    }
 77
 78    band(a, b) {
 79        return a.and(b).and(this.mask);
 80    }
 81
 82    bor(a, b) {
 83        return a.or(b).and(this.mask);
 84    }
 85
 86    bxor(a, b) {
 87        return a.xor(b).and(this.mask);
 88    }
 89
 90    bnot(a) {
 91        return a.xor(this.mask).and(this.mask);
 92    }
 93
 94    shl(a, b) {
 95        if (b.geq(this.bitLength)) return bigInt.zero;
 96        return a.shiftLeft(b).and(this.mask);
 97    }
 98
 99    shr(a, b) {
100        if (b.geq(this.bitLength)) return bigInt.zero;
101        return a.shiftRight(b).and(this.mask);
102    }
103
104    land(a, b) {
105        return (a.isZero() || b.isZero) ? bigInt.zero : bigInt.one;
106    }
107
108    lor(a, b) {
109        return (a.isZero() && b.isZero) ? bigInt.zero : bigInt.one;
110    }
111
112    lnot(a) {
113        return a.isZero() ? bigInt.one : bigInt.zero;
114    }
115};
116