circuitcircomzk-snarkzkp

How to run a loop with unknown number of iterations in Circom?


I have the following circuit in Circom cicuit compiler:

pragma circom 2.0.0;

template MAIN() {

    signal len;
    len <== 32;

    for (k = 0; k < maplen; k++) { 
        // do something
    }

}

component main = MAIN();

I'm getting an error:

error[T2005]: Typing error found
    ┌─ "/Users/ilia/compiling/main-circom/circuits/main.circom":118:17
    │
118 │     for (k = 0; k < len; k++) {
    │                 ^^^^^^^ There are constraints depending on the value of the condition and it can be unknown during the constraint generation phase

How do I write this loop in a way which makes it possible to iterate len times where len is a signal?


Solution

  • You need to decide how many maximum iterations your loop can have (an iteration budget) and then discard all the iterations you don't need using LessThan component. You can also select the needed result of a iteration using QuinSelector