fluidex / circom-plus

1 stars 1 forks source link

Circom could not generate correct code in some circuits which is obvious correct #4

Open noel2004 opened 2 years ago

noel2004 commented 2 years ago

For following circuit:

include "../circomlib/circuits/sha256/sha256.circom";

template Sha256Wrap(nBits) {

    signal input bits[nBits];

    var bitPadding = 8 - nBits % 8;
    if (bitPadding == 8){
        bitPadding = 0;
    }

    var hashBits = nBits + bitPadding;
    component hasher = Sha256(hashBits);

    for (var i = 0; i < nBits; i++){
        hasher.in[i] <== bits[i];
    }
    assert(nBits == 5);
    for (var i = nBits; i < hashBits; i++){
        hasher.in[i] <== 0;
    }    
}

component main = Sha256Wrap(5);

The code generated by circom would not run correctly: for native backend, it halt forever before load input successfully and for WASM backend it simply prompt "Constraint doesn't match"

For some similar circuit, the natvie backend may also complain that some signal has been assigned before being used.

However, code would run well if we simply change the last 'nBits' into the value (5) it should be in this circuit:

assert(nBits == 5); for (var i = 5; i < hashBits; i++){ hasher.in[i] <== 0; }

such issue keeps until at least 0.5.45, the latest version when this issue has been put.

noel2004 commented 2 years ago

Another workaround is replace the complied constant nBits into a variant which is obtained from a function:


include "../circomlib/circuits/sha256/sha256.circom";

function dummyCalc(n){
    var doubleN = n * 2;
    return doubleN >> 1;
}

template Sha256Wrap(nInputBits) {

    var nBits = dummyCalc(nInputBits);

    signal input bits[nBits];

    var bitPadding = 8 - nBits % 8;
    if (bitPadding == 8){
        bitPadding = 0;
    }

    var hashBits = nBits + bitPadding;
    component hasher = Sha256(hashBits);

    for (var i = 0; i < nBits; i++){
        hasher.in[i] <== bits[i];
    }
    for (var i = nBits; i < hashBits; i++){
        hasher.in[i] <== 0;
    }    
}

component main = Sha256Wrap(5);
noel2004 commented 2 years ago

issue.zip

We have put the demo code in the attachment above. With the problemic circuit (under 'fail' directory) and the working around ('good'), which can be test with snarkit