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