Search code examples
circuitand-operatorcircomzkpzk-snark

How to use & (AND) operator in a signal in Circom


I'm trying to use & operator on a signal and get another signal in Circom circuit compiler language like so:

pragma circom 2.0.0;


template MAIN() {

    signal input a;
    signal output x;

    signal v;
    v <== 168;

    x <== v & 31;
}

component main = MAIN();

I'm getting this error:

error[T3001]: Non quadratic constraints are not allowed!
    ┌─ "/Users/ilia/compiling/main-circom/main.circom":146:5
    │
146 │     x <== v & 31; // 0b00011111
    │     ^^^^^^^^^^^^ found here
    │
    = call trace:
      ->MAIN

How can I generate a constraint for x signal so that it is quadratic?


Solution

  • I did it with Num2Bits:

    // the code bellow is a quadratic equivalent of:
    // x <== v & 31; // 0b00011111
    component num2Bits = Num2Bits(8);
    num2Bits.in <== v;
    signal vbits[8];
    for(k = 0; k < 8; k++) {
        vbits[k] <== num2Bits.out[k];
    }
    var lc1=0;
    var e2 = 1;
    for (var i = 0; i<5; i++) {
        lc1 += vbits[i] * e2;
        e2 = e2 + e2;
    }
    lc1 ==> x;