Ilia Sidorenko
Ilia Sidorenko

Reputation: 2715

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?

Upvotes: 1

Views: 722

Answers (2)

Pavel Fedotov
Pavel Fedotov

Reputation: 885

In circom arrays can only hold known amounts of elements at compilation time.

Arrays: they can hold a finite number of elements (known at compilation time) of the same type (signal, var, or the same type of components or arrays again). The elements are numbered from zero on and can be accessed using the corresponding index of their position. Array access is made using square brackets. Declaration of an array of a given type is made by adding [] aside of the variable identifier and including the size between the brackets (which should be defined using constant values and/or numeric parameters of templates).

An array of components must be instantiated with the same template with (optionally) different parameters.

pragma circom 2.0.0;

template fun(N){
  signal output out;
  out <== N;
}

template all(N){
  component c[N];
  for(var i = 0; i < N; i++){
     c[i] = fun(i);
  }
}

component main = all(5);

https://docs.circom.io/circom-language/data-types/

Upvotes: 1

Ilia Sidorenko
Ilia Sidorenko

Reputation: 2715

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

Upvotes: 3

Related Questions