GithubHelp home page GithubHelp logo

iden3 / snarkjs Goto Github PK

View Code? Open in Web Editor NEW
1.7K 32.0 418.0 140.82 MB

zkSNARK implementation in JavaScript & WASM

License: GNU General Public License v3.0

JavaScript 97.56% Solidity 1.27% EJS 1.11% Circom 0.02% HTML 0.03%

snarkjs's Introduction

testsCheck%20snarkjs%20tutorial

snarkjs

This is a JavaScript and Pure Web Assembly implementation of zkSNARK and PLONK schemes. It uses the Groth16 Protocol (3 point only and 3 pairings), PLONK and FFLONK.

This library includes all the tools required to perform trusted setup multi-party ceremonies: including the universal powers of tau ceremony, and the second phase circuit specific ceremonies.

Any zk-snark project can pick a round from the common phase 1 to start their circuit-specific phase 2 ceremony.

The formats used in this library for the multi-party computation are compatible with the ones used in Semaphore's Perpetual Powers of Tau and other implementations.

This library uses the compiled circuits generated by the circom compiler.

It works in node.js as well as directly in the browser.

It's an ES module, so it can be directly imported into bigger projects using Rollup or Webpack.

The low-level cryptography is performed directly in wasm, and uses worker threads to parallelize the computations. The result is a high performance library with benchmarks comparable to host implementations.

Preliminaries

Install node

First off, make sure you have a recent LTS version of Node.js installed. Non-LTS and versions prior to v18 are not guaranteed to work.

If you’re not sure which version of Node you have installed, you can run:

node -v

To download the latest version of Node, see here.

Install snarkjs

To install snarkjs run:

npm install -g snarkjs@latest

If you're seeing an error, try prefixing both commands with sudo and running them again.

Understand the help command

To see a list of all snarkjs commands, as well as descriptions about their inputs and outputs, run:

snarkjs --help

You can also use the --help option with specific commands:

snarkjs groth16 prove --help

Most of the commands have an alternative shorter alias (which you can discover using --help).

For example, the previous command can also be invoked with:

snarkjs g16p --help

Debugging tip

If you a feel a command is taking longer than it should, re-run it with a -v or --verbose option to see more details about how it's progressing and where it's getting blocked.

Install circom

To install circom, follow the instructions at installing circom.

Guide

0. Create and move into a new directory

mkdir snarkjs_example
cd snarkjs_example

1. Start a new powers of tau ceremony

snarkjs powersoftau new bn128 14 pot14_0000.ptau -v

The new command is used to start a powers of tau ceremony.

The first parameter after new refers to the type of curve you wish to use. At the moment, we support both bn128 and bls12-381.

The second parameter, in this case 14, is the power of two of the maximum number of constraints that the ceremony can accept: in this case, the number of constraints is 2 ^ 14 = 16,384. The maximum value supported here is 28, which means you can use snarkjs to securely generate zk-snark parameters for circuits with up to 2 ^ 28 (≈268 million) constraints.

2. Contribute to the ceremony

snarkjs powersoftau contribute pot14_0000.ptau pot14_0001.ptau --name="First contribution" -v

The contribute command creates a ptau file with a new contribution.

You'll be prompted to enter some random text to provide an extra source of entropy.

contribute takes as input the transcript of the protocol so far, in this case pot14_0000.ptau, and outputs a new transcript, in this case pot14_0001.ptau, which includes the computation carried out by the new contributor (ptau files contain a history of all the challenges and responses that have taken place so far).

name can be anything you want, and is just included for reference (it will be printed when you verify the file (step 5).

3. Provide a second contribution

snarkjs powersoftau contribute pot14_0001.ptau pot14_0002.ptau --name="Second contribution" -v -e="some random text"

By letting you write the random text as part of the command, the -e parameter allows contribute to be non-interactive.

4. Provide a third contribution using third party software

snarkjs powersoftau export challenge pot14_0002.ptau challenge_0003
snarkjs powersoftau challenge contribute bn128 challenge_0003 response_0003 -e="some random text"
snarkjs powersoftau import response pot14_0002.ptau response_0003 pot14_0003.ptau -n="Third contribution name"

The challenge and response files are compatible with this software.

This allows you to use different types of software in a single ceremony.

5. Verify the protocol so far

snarkjs powersoftau verify pot14_0003.ptau

The verify command verifies a ptau (powers of tau) file. Which means it checks all the contributions to the multi-party computation (MPC) up to that point. It also prints the hashes of all the intermediate results to the console.

If everything checks out, you should see the following at the top of the output:

[INFO]  snarkJS: Powers Of tau file OK!

In sum, whenever a new zk-snark project needs to perform a trusted setup, you can just pick the latest ptau file, and run the verify command to verify the entire chain of challenges and responses so far.

6. Apply a random beacon

snarkjs powersoftau beacon pot14_0003.ptau pot14_beacon.ptau 0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f 10 -n="Final Beacon"

The beacon command creates a ptau file with a contribution applied in the form of a random beacon.

We need to apply a random beacon in order to finalise phase 1 of the trusted setup.

To paraphrase Sean Bowe and Ariel Gabizon, a random beacon is a source of public randomness that is not available before a fixed time. The beacon itself can be a delayed hash function (e.g. 2^40 iterations of SHA256) evaluated on some high entropy and publicly available data. Possible sources of data include: the closing value of the stock market on a certain date in the future, the output of a selected set of national lotteries, or the value of a block at a particular height in one or more blockchains. E.g. the hash of the 11 millionth Ethereum block (which as of this writing is some 3 months in the future). See here for more on the importance of a random beacon.

For the purposes of this tutorial, the beacon is essentially a delayed hash function evaluated on 0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f (in practice this value will be some form of high entropy and publicly available data of your choice). The next input -- in our case 10 -- just tells snarkjs to perform 2 ^ 10 iterations of this hash function.

Note that security holds even if an adversary has limited influence on the beacon.

7. Prepare phase 2

snarkjs powersoftau prepare phase2 pot14_beacon.ptau pot14_final.ptau -v

We're now ready to prepare phase 2 of the setup (the circuit-specific phase).

Under the hood, the prepare phase2 command calculates the encrypted evaluation of the Lagrange polynomials at tau for tau, alpha*tau and beta*tau. It takes the beacon ptau file we generated in the previous step, and outputs a final ptau file which will be used to generate the circuit proving and verification keys.


NOTE

Ptau files for bn128 with the peraperPhase2 54 contributions and a beacon, can be found here:

power maxConstraints file hash
8 256 powersOfTau28_hez_final_08.ptau d6a8fb3a04feb600096c3b791f936a578c4e664d262e4aa24beed1b7a9a96aa5eb72864d628db247e9293384b74b36ffb52ca8d148d6e1b8b51e279fdf57b583
9 512 powersOfTau28_hez_final_09.ptau 94f108a80e81b5d932d8e8c9e8fd7f46cf32457e31462deeeef37af1b71c2c1b3c71fb0d9b59c654ec266b042735f50311f9fd1d4cadce47ab234ad163157cb5
10 1k powersOfTau28_hez_final_10.ptau 6cfeb8cda92453099d20120bdd0e8a5c4e7706c2da9a8f09ccc157ed2464d921fd0437fb70db42104769efd7d6f3c1f964bcf448c455eab6f6c7d863e88a5849
11 2k powersOfTau28_hez_final_11.ptau 47c282116b892e5ac92ca238578006e31a47e7c7e70f0baa8b687f0a5203e28ea07bbbec765a98dcd654bad618475d4661bfaec3bd9ad2ed12e7abc251d94d33
12 4k powersOfTau28_hez_final_12.ptau ded2694169b7b08e898f736d5de95af87c3f1a64594013351b1a796dbee393bd825f88f9468c84505ddd11eb0b1465ac9b43b9064aa8ec97f2b73e04758b8a4a
13 8k powersOfTau28_hez_final_13.ptau 58efc8bf2834d04768a3d7ffcd8e1e23d461561729beaac4e3e7a47829a1c9066d5320241e124a1a8e8aa6c75be0ba66f65bc8239a0542ed38e11276f6fdb4d9
14 16k powersOfTau28_hez_final_14.ptau eeefbcf7c3803b523c94112023c7ff89558f9b8e0cf5d6cdcba3ade60f168af4a181c9c21774b94fbae6c90411995f7d854d02ebd93fb66043dbb06f17a831c1
15 32k powersOfTau28_hez_final_15.ptau 982372c867d229c236091f767e703253249a9b432c1710b4f326306bfa2428a17b06240359606cfe4d580b10a5a1f63fbed499527069c18ae17060472969ae6e
16 64k powersOfTau28_hez_final_16.ptau 6a6277a2f74e1073601b4f9fed6e1e55226917efb0f0db8a07d98ab01df1ccf43eb0e8c3159432acd4960e2f29fe84a4198501fa54c8dad9e43297453efec125
17 128k powersOfTau28_hez_final_17.ptau 6247a3433948b35fbfae414fa5a9355bfb45f56efa7ab4929e669264a0258976741dfbe3288bfb49828e5df02c2e633df38d2245e30162ae7e3bcca5b8b49345
18 256k powersOfTau28_hez_final_18.ptau 7e6a9c2e5f05179ddfc923f38f917c9e6831d16922a902b0b4758b8e79c2ab8a81bb5f29952e16ee6c5067ed044d7857b5de120a90704c1d3b637fd94b95b13e
19 512k powersOfTau28_hez_final_19.ptau bca9d8b04242f175189872c42ceaa21e2951e0f0f272a0cc54fc37193ff6648600eaf1c555c70cdedfaf9fb74927de7aa1d33dc1e2a7f1a50619484989da0887
20 1M powersOfTau28_hez_final_20.ptau 89a66eb5590a1c94e3f1ee0e72acf49b1669e050bb5f93c73b066b564dca4e0c7556a52b323178269d64af325d8fdddb33da3a27c34409b821de82aa2bf1a27b
21 2M powersOfTau28_hez_final_21.ptau 9aef0573cef4ded9c4a75f148709056bf989f80dad96876aadeb6f1c6d062391f07a394a9e756d16f7eb233198d5b69407cca44594c763ab4a5b67ae73254678
22 4M powersOfTau28_hez_final_22.ptau 0d64f63dba1a6f11139df765cb690da69d9b2f469a1ddd0de5e4aa628abb28f787f04c6a5fb84a235ec5ea7f41d0548746653ecab0559add658a83502d1cb21b
23 8M powersOfTau28_hez_final_23.ptau 3063a0bd81d68711197c8820a92466d51aeac93e915f5136d74f63c394ee6d88c5e8016231ea6580bec02e25d491f319d92e77f5c7f46a9caa8f3b53c0ea544f
24 16M powersOfTau28_hez_final_24.ptau fa404d140d5819d39984833ca5ec3632cd4995f81e82db402371a4de7c2eae8687c62bc632a95b0c6aadba3fb02680a94e09174b7233ccd26d78baca2647c733
25 32M powersOfTau28_hez_final_25.ptau 0377d860cdb09a8a31ea1b0b8c04335614c8206357181573bf294c25d5ca7dff72387224fbd868897e6769f7805b3dab02854aec6d69d7492883b5e4e5f35eeb
26 64M powersOfTau28_hez_final_26.ptau 418dee4a74b9592198bd8fd02ad1aea76f9cf3085f206dfd7d594c9e264ae919611b1459a1cc920c2f143417744ba9edd7b8d51e44be9452344a225ff7eead19
27 128M powersOfTau28_hez_final_27.ptau 10ffd99837c512ef99752436a54b9810d1ac8878d368fb4b806267bdd664b4abf276c9cd3c4b9039a1fa4315a0c326c0e8e9e8fe0eb588ffd4f9021bf7eae1a1
28 256M powersOfTau28_hez_final.ptau 55c77ce8562366c91e7cda394cf7b7c15a06c12d8c905e8b36ba9cf5e13eb37d1a429c589e8eaba4c591bc4b88a0e2828745a53e170eac300236f5c1a326f41a

There is a file truncated for each power of two.

The complete file is powersOfTau28_hez_final.ptau which includes 2**28 powers.

And it's blake2b hash is:

55c77ce8562366c91e7cda394cf7b7c15a06c12d8c905e8b36ba9cf5e13eb37d1a429c589e8eaba4c591bc4b88a0e2828745a53e170eac300236f5c1a326f41a

You can find more information about the ceremony here

The last ptau file was generated using this procedure:

https://www.reddit.com/r/ethereum/comments/iftos6/powers_of_tau_selection_for_hermez_rollup/


8. Verify the final ptau

snarkjs powersoftau verify pot14_final.ptau

The verify command verifies a powers of tau file.

Before we go ahead and create the circuit, we perform a final check and verify the final protocol transcript.

Notice there is no longer a warning informing you that the file does not contain phase 2 precalculated values.

9. Create the circuit

cat <<EOT > circuit.circom
pragma circom 2.0.0;

template Multiplier(n) {
    signal input a;
    signal input b;
    signal output c;

    signal int[n];

    int[0] <== a*a + b;
    for (var i=1; i<n; i++) {
    int[i] <== int[i-1]*int[i-1] + b;
    }

    c <== int[n-1];
}

component main = Multiplier(1000);
EOT

We create a circom file that allows us to easily test the system with a different number of constraints.

In this case, we've chosen 1000, but we can change this to anything we want (as long as the value we choose is below the number we defined in step 1).

10. Compile the circuit

circom circuit.circom --r1cs --wasm --sym

The circom command takes one input (the circuit to compile, in our case circuit.circom) and three options:

  • r1cs: generates circuit.r1cs (the r1cs constraint system of the circuit in binary format).

  • wasm: generates circuit.wasm (the wasm code to generate the witness – more on that later).

  • sym: generates circuit.sym (a symbols file required for debugging and printing the constraint system in an annotated mode).

11. View information about the circuit

snarkjs r1cs info circuit.r1cs

The info command is used to print circuit stats.

You should see the following output:

[INFO]  snarkJS: Curve: bn-128
[INFO]  snarkJS: # of Wires: 1003
[INFO]  snarkJS: # of Constraints: 1000
[INFO]  snarkJS: # of Private Inputs: 2
[INFO]  snarkJS: # of Public Inputs: 0
[INFO]  snarkJS: # of Outputs: 1

This information fits with our mental map of the circuit we created: we had two private inputs a and b, one output c, and a thousand constraints of the form a * b = c.

12. Print the constraints

snarkjs r1cs print circuit.r1cs circuit.sym

To double check, we print the constraints of the circuit.

You should see a thousand constraints of the form:

[ -main.int[i] ] * [ main.int[i] ] - [ main.b -main.int[i+1] ] = 0

13. Export r1cs to json

snarkjs r1cs export json circuit.r1cs circuit.r1cs.json
cat circuit.r1cs.json

We export r1cs to json format to make it human readable.

14. Calculate the witness

First, we create a file with the inputs for our circuit:

cat <<EOT > input.json
{"a": 3, "b": 11}
EOT

Now, we use the Javascript/WASM program created by circom in the directory circuit_js to create the witness (values of all the wires) for our inputs:

circuit_js$ node generate_witness.js circuit.wasm ../input.json ../witness.wtns

We can check if the generated witness complies with the r1cs file with the following command:

snarkjs wtns check circuit.r1cs witness.wtns

15. Setup

Currently, snarkjs supports 3 proving systems: Groth16, PLONK and FFLONK (Beta version).

Groth16 requires a trusted ceremony for each circuit. PLONK and FFLONK do not require it, it's enough with the powers of tau ceremony which is universal.

Plonk

snarkjs plonk setup circuit.r1cs pot14_final.ptau circuit_final.zkey

Fflonk

snarkjs fflonk setup circuit.r1cs pot14_final.ptau circuit.zkey

You can jump directly to Section 21 as PLONK or FFLONK does not require a specific trusted ceremony.

Groth16

snarkjs groth16 setup circuit.r1cs pot14_final.ptau circuit_0000.zkey

This generates the reference zkey without phase 2 contributions

IMPORTANT: Do not use this zkey in production, as it's not safe. It requires at least a contribution,

The zkey new command creates an initial zkey file with zero contributions.

The zkey is a zero-knowledge key that includes both the proving and verification keys as well as phase 2 contributions.

Importantly, one can verify whether a zkey belongs to a specific circuit or not.

Note that circuit_0000.zkey (the output of the zkey command above) does not include any contributions yet, so it cannot be used in a final circuit.

The following steps (15-20) are similar to the equivalent phase 1 steps, except we use zkey instead of powersoftau as the main command, and we generate zkey rather that ptau files.

16. Contribute to the phase 2 ceremony

snarkjs zkey contribute circuit_0000.zkey circuit_0001.zkey --name="1st Contributor Name" -v

The zkey contribute command creates a zkey file with a new contribution.

As in phase 1, you'll be prompted to enter some random text to provide an extra source of entropy.

17. Provide a second contribution

snarkjs zkey contribute circuit_0001.zkey circuit_0002.zkey --name="Second contribution Name" -v -e="Another random entropy"

We provide a second contribution.

18. Provide a third contribution using third party software

snarkjs zkey export bellman circuit_0002.zkey  challenge_phase2_0003
snarkjs zkey bellman contribute bn128 challenge_phase2_0003 response_phase2_0003 -e="some random text"
snarkjs zkey import bellman circuit_0002.zkey response_phase2_0003 circuit_0003.zkey -n="Third contribution name"

And a third using third-party software.

19. Verify the latest zkey

snarkjs zkey verify circuit.r1cs pot14_final.ptau circuit_0003.zkey

The zkey verify command verifies a zkey file. It also prints the hashes of all the intermediary results to the console.

We verify the zkey file we created in the previous step. Which means we check all the contributions to the second phase of the multi-party computation (MPC) up to that point.

This command also checks that the zkey file matches the circuit.

If everything checks out, you should see the following:

[INFO]  snarkJS: ZKey Ok!

20. Apply a random beacon

snarkjs zkey beacon circuit_0003.zkey circuit_final.zkey 0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f 10 -n="Final Beacon phase2"

The zkey beacon command creates a zkey file with a contribution applied in the form of a random beacon.

We use it to apply a random beacon to the latest zkey after the final contribution has been made (this is necessary in order to generate a final zkey file and finalise phase 2 of the trusted setup).

21. Verify the final zkey

snarkjs zkey verify circuit.r1cs pot14_final.ptau circuit_final.zkey

Before we go ahead and export the verification key as a json, we perform a final check and verify the final protocol transcript (zkey).

22. Export the verification key

snarkjs zkey export verificationkey circuit_final.zkey verification_key.json

We export the verification key from circuit_final.zkey into verification_key.json.

23. Create the proof

PLONK

snarkjs plonk prove circuit_final.zkey witness.wtns proof.json public.json

FFLONK

snarkjs fflonk prove circuit.zkey witness.wtns proof.json public.json

Groth16

snarkjs groth16 prove circuit_final.zkey witness.wtns proof.json public.json

We create the proof. this command generates the files proof.json and public.json: proof.json contains the actual proof, whereas public.json contains the values of the public inputs and output.

Note that it's also possible to create the proof and calculate the witness in the same command by running:

snarkjs groth16 fullprove input.json circuit.wasm circuit_final.zkey proof.json public.json
or
snarkjs plonk fullprove witness.json circuit.wasm circuit_final.zkey proof.json public.json
or
snarkjs fflonk fullprove witness.json circuit.wasm circuit_final.zkey proof.json public.json
> ```

24. Verify the proof

PLONK

snarkjs plonk verify verification_key.json public.json proof.json

FFLONK

snarkjs fflonk verify verification_key.json public.json proof.json

Groth16

snarkjs groth16 verify verification_key.json public.json proof.json

We use the this command to verify the proof, passing in the verification_key we exported earlier.

If all is well, you should see that OK has been outputted to your console. This signifies the proof is valid.

25. Turn the verifier into a smart contract

snarkjs zkey export solidityverifier circuit_final.zkey verifier.sol

Finally, we export the verifier as a Solidity smart-contract so that we can publish it on-chain -- using remix for example. For the details on how to do this, refer to section 4 of this tutorial.

26. Simulate a verification call

snarkjs zkey export soliditycalldata public.json proof.json

We use soliditycalldata to simulate a verification call, and cut and paste the result directly in the verifyProof field in the deployed smart contract in the remix environment.

And voila! That's all there is to it :)

Using Node

npm init
npm install snarkjs
const snarkjs = require("snarkjs");
const fs = require("fs");

async function run() {
    const { proof, publicSignals } = await snarkjs.groth16.fullProve({a: 10, b: 21}, "circuit.wasm", "circuit_final.zkey");

    console.log("Proof: ");
    console.log(JSON.stringify(proof, null, 1));

    const vKey = JSON.parse(fs.readFileSync("verification_key.json"));

    const res = await snarkjs.groth16.verify(vKey, publicSignals, proof);

    if (res === true) {
        console.log("Verification OK");
    } else {
        console.log("Invalid proof");
    }

}

run().then(() => {
    process.exit(0);
});

In the browser

Load snarkjs.min.js and start using it as usual.

cp node_modules/snarkjs/build/snarkjs.min.js .
<!doctype html>
<html>
<head>
  <title>Snarkjs client example</title>
</head>
<body>

  <h1>Snarkjs client example</h1>
  <button id="bGenProof"> Create proof </button>

  <!-- JS-generated output will be added here. -->
  <pre class="proof"> Proof: <code id="proof"></code></pre>

  <pre class="proof"> Result: <code id="result"></code></pre>


  <script src="snarkjs.min.js">   </script>


  <!-- This is the bundle generated by rollup.js -->
  <script>

const proofComponent = document.getElementById('proof');
const resultComponent = document.getElementById('result');
const bGenProof = document.getElementById("bGenProof");

bGenProof.addEventListener("click", calculateProof);

async function calculateProof() {

    const { proof, publicSignals } =
      await snarkjs.groth16.fullProve( { a: 3, b: 11}, "circuit.wasm", "circuit_final.zkey");

    proofComponent.innerHTML = JSON.stringify(proof, null, 1);


    const vkey = await fetch("verification_key.json").then( function(res) {
        return res.json();
    });

    const res = await snarkjs.groth16.verify(vkey, publicSignals, proof);

    resultComponent.innerHTML = res;
}

  </script>

</body>
</html>

Security

Avoid using versions before v0.4.16. They contain bugs that may affect the security.

Further resources

Final note

We hope you enjoyed this quick walk-through. Please address any questions you may have to our telegram group (it’s also a great way to join the community and stay up-to-date with the latest circom and snarkjs developments) 💙

License

snarkjs is part of the iden3 project copyright 2018 0KIMS association and published with GPL-3 license. Please check the COPYING file for more details.

snarkjs's People

Contributors

arnaucube avatar bajpai244 avatar bellesmarta avatar dependabot[bot] avatar eduadiez avatar glamperd avatar invocamanman avatar io4 avatar jbaylina avatar judiciouscoder avatar kirrya95 avatar kobigurk avatar kolezhniuk avatar krlosmata avatar lispc avatar nalinbhardwaj avatar obrezhniev avatar phated avatar prabal-banerjee avatar sragss avatar standaa avatar stumble avatar uaoleg avatar unixpi avatar vplasencia avatar weijiekoh avatar wp-lai avatar xavi-pinsach avatar yelhousni avatar zkronos73 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

snarkjs's Issues

snarkjs ReferenceError in Fabric

Hi, I am trying to use this module in Fabric. I call the module in API project, and call it using require ("snarkjs"); the dependency is added in package.json in the project. it gives the following error

ReferenceError: snarkjs is not defined

Any help regarding this?

Can this library work on node v10 LTS? Error: Cannot find module 'worker_threads'

internal/modules/cjs/loader.js:638
throw err;
^

Error: Cannot find module 'worker_threads'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object. (/usr/local/lib/node_modules/snarkjs/node_modules/ffjavascript/build/main.cjs:9:38)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)

Using node v: 10.21.0

Safari Issues

When calling fullProve on Safari and Chrome on IOs

TypeError: wA.cpus is not a function. (In 'wA.cpus()', 'wA.cpus' is undefined)

zkSnark.Circuit is not a constructor

The setup instructions in the README don't seem to work with the latest version of snarkjs on npm (they were working as of 0.1.20 but I'm not sure when it started to fail)

Efficient snarkjs bit signature scheme?

Hi,
I'm looking for an efficient snarkjs based signature scheme implementation. I have tried EDDSA which is excruciatingly slow, and wanted to know if there is anything better I can look at.

Using bigInt utilities on the browser

how can I use the bigInt utilities on the browser?

And what is the recommended way for webpack import usage, I tried #77 but no luck as there isn't a dist folder tried with build/snarkjs.min.js window.snarkjs === {}, I Had to copy the snark.min.js

Please update README to use stringifyBigInts

The code in the readme includes these lines:

fs.writeFileSync("myCircuit.vk_proof", JSON.stringify(setup.vk_proof), "utf8");
fs.writeFileSync("myCircuit.vk_verifier", JSON.stringify(setup.vk_verifier), "utf8");

However, they won't work in Node 10 as bigints can't be serialised. The solution is to use JSON.stringify(stringifyBigInts(setup.vk_proof), as cli.js demonstrates.

EIP-170 issue: Contract Size Limit 24kb

Is there any easier way of resolving this problem other than manually dividing the contract parts & calling them separately?

My contract size is more than 100kb due to including sha256

Unable to verify when in WSL2

  Full process
    ✓ powersoftau new (76ms)
    ✓ powersoftau contribute  (1717ms)
    ✓ powersoftau export challenge
    ✓ powersoftau challenge contribute (1688ms)
    ✓ powersoftau import response (367ms)
    ✓ powersoftau beacon (1706ms)
    ✓ powersoftau prepare phase2 (29497ms)
    1) powersoftau verify
    ✓ zkey new (341ms)
    ✓ zkey contribute  (124ms)
    ✓ zkey export bellman (1550ms)
    ✓ zkey bellman contribute (133ms)
    ✓ zkey import bellman (1803ms)
    ✓ zkey beacon (121ms)
    2) zkey verify
    ✓ zkey export verificationkey
    ✓ witness calculate
    ✓ groth16 proof (111ms)
    3) groth16 verify

WSL2 Ubuntu 18.04.4 LTS
Windows 10 Pro 19042.450
node v14.8.0
[email protected]
[email protected]

I have considered possible environmental issues
I ran the test in docker, the same
https://github.com/eduadiez/snarkjs_tester

[INFO]  snarkJS: GET main.b --> 11
[INFO]  snarkJS: SET main.int[999] <-- 7713112592372404476342535432037683616424591277138491596200192981572885523208
[INFO]  snarkJS: GET main.int[999] --> 7713112592372404476342535432037683616424591277138491596200192981572885523208
[INFO]  snarkJS: SET main.c <-- 7713112592372404476342535432037683616424591277138491596200192981572885523208
[INFO]  snarkJS: FINISH: main
[ERROR] snarkJS: Invalid proof
["0x16729f318153579b15da0c352920e8d090edf4591e666713f8394dbbb65bfa3a", "0x0c060e04096d33f36ef7c8c1c1415f704977835822427040cdf87893e5b2b47a"],[["0x1c39ae20ec1dc6894cf64120a5f5d1558cddc3e163780591373c4f86e5398032", "0x2459bede3aceb13a4599206b9c98e494c7541ba5b389732279de8a63b6390110"],["0x1b556bc700d9f555199325835b91edeb29f354567e43660883ee7d3e0ce189bb", "0x27562869095ea22b0806e183f0150cedabdc8e47f51abf6e4006736a35ef52f4"]],["0x2a37638cff971e2305bde2a909d8452a49999b004400e21e31055224419cd5ba", "0x17cf966aae627a38f670846ded3fa0dce9cfd35f15f7072322ec752699ed4853"],["0x110d778eaf8b8ef7ac10f8ac239a14df0eb292a8d1b71340d527b26301a9ab08"]

[ERROR] snarkJS: H section does not match

Currently running on
Ubuntu 20.04.1 LTS
AMD Ryzen 7 3800X(8/16 Cores)
MSI GTX 970

When I try to run the setup as described in the tutorial I run into the problem that verification step 18 does not verify.
In order to reproduce, I provided the script I run and the output by running(circom and snarkjs are installed globally)
sudo ./make > result

make

rm circuit* pot12*
sudo npm i circomlib
snarkjs powersoftau new bn128 12 pot12_0000.ptau -v
snarkjs powersoftau contribute pot12_0000.ptau pot12_0001.ptau --name="Second contribution" -v -e="some random text"
snarkjs powersoftau verify pot12_0001.ptau
snarkjs powersoftau beacon pot12_0001.ptau pot12_beacon.ptau 0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f 10 -n="Final Beacon"
snarkjs powersoftau prepare phase2 pot12_beacon.ptau pot12_final.ptau -v
snarkjs powersoftau verify pot12_final.ptau
cat <<EOT > circuit.circom
include "./node_modules/circomlib/circuits/mimcsponge.circom";
include "./node_modules/circomlib/circuits/mimc.circom";
include "./node_modules/circomlib/circuits/bitify.circom";

template Hasher1() {
    signal input in;
    signal output hash;
    component hasher = MiMC7(91);
    hasher.x_in <== in;
    hasher.k <== 0;
    hash <== hasher.out;
}

template Hasher2() {
    signal input in[2];
    signal input direction;
    signal output hash;
    signal par[2];
    if (direction == 0) {
        par[0] <-- in[0];
        par[1] <-- in[1];
    } else {
        par[1] <-- in[0];
        par[0] <-- in[1];
    }
    component hasher = MiMCSponge(2, 220, 1);
    hasher.ins[0] <== par[0];
    hasher.ins[1] <== par[1];
    hasher.k <== 0;
    hash <== hasher.outs[0];
}

template Test(levels) {
    signal input anonymous; // unused
    signal input root; // set by smart contract Vote v to v.root
    signal input index;
    signal input nullifier;
    signal private input secret;
    signal private input merkle[levels];
    signal private input direction[levels];
    signal hash[levels+1];
    signal indexbits[256];
    signal indexext;

    component n2b = Num2Bits(256);
    n2b.in <== index;
    for (var i = 0; i < 128; i++) {
        indexbits[i] <== n2b.out[i];
    }
    for (var i = 0; i < levels; i++) {
        if (direction[i] == 0)
            indexbits[128 + i] <-- 0;
        else
            indexbits[128 + i] <-- 1;
    }
    for (var i = 128 + levels; i < 256; i++) {
            indexbits[i] <-- 0;
    }
    component b2n = Bits2Num(256);
    for (var i = 0; i < 256; i++) {
        b2n.in[i] <== indexbits[i];
    }
    indexext <== b2n.out;

    component nullifierHasher = Hasher2();
    nullifierHasher.in[0] <== secret;
    nullifierHasher.in[1] <== indexext;
    nullifierHasher.direction <== 0;
    nullifier === nullifierHasher.hash;

    component secretHasher = Hasher1();
    secretHasher.in <== secret;
    hash[0] <== secretHasher.hash;

    component hasher[levels];
    for (var i = 0; i < levels; i++) {
        hasher[i] = Hasher2();
        hasher[i].in[0] <== hash[i];
        hasher[i].in[1] <== merkle[i];
        hasher[i].direction <== direction[i];
        hash[i+1] <== hasher[i].hash;
    }

    hash[levels] === root;
}

component main = Test(1);
EOT

circom circuit.circom --r1cs --wasm --sym -v
snarkjs r1cs info circuit.r1cs
snarkjs r1cs export json circuit.r1cs circuit.r1cs.json
snarkjs zkey new circuit.r1cs pot12_final.ptau circuit_0000.zkey
snarkjs zkey contribute circuit_0000.zkey circuit_0001.zkey --name="Second contribution Name" -v -e="Another random entropy"
snarkjs zkey verify circuit.r1cs pot12_final.ptau circuit_0001.zkey

result


+ [email protected]
updated 1 package and audited 148 packages in 1.239s

3 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

[DEBUG] snarkJS: Calculating First Challenge Hash
[DEBUG] snarkJS: Calculate Initial Hash: tauG1
[DEBUG] snarkJS: Calculate Initial Hash: tauG2
[DEBUG] snarkJS: Calculate Initial Hash: alphaTauG1
[DEBUG] snarkJS: Calculate Initial Hash: betaTauG1
[DEBUG] snarkJS: Blank Contribution Hash:
		786a02f7 42015903 c6c6fd85 2552d272
		912f4740 e1584761 8a86e217 f71f5419
		d25e1031 afee5853 13896444 934eb04b
		903a685b 1448b755 d56f701a fe9be2ce
[INFO]  snarkJS: First Contribution Hash:
		9e63a5f6 2b96538d aaed2372 481920d1
		a40b9195 9ea38ef9 f5f6a303 3b886516
		0710d067 c09d0961 5f928ea5 17bcdf49
		ad75abd2 c8340b40 0e3b18e9 68b4ffef
[DEBUG] snarkJS: Calculating First Challenge Hash
[DEBUG] snarkJS: Calculate Initial Hash: tauG1
[DEBUG] snarkJS: Calculate Initial Hash: tauG2
[DEBUG] snarkJS: Calculate Initial Hash: alphaTauG1
[DEBUG] snarkJS: Calculate Initial Hash: betaTauG1
[DEBUG] snarkJS: processing: tauG1: 0/8191
[DEBUG] snarkJS: processing: tauG2: 0/4096
[DEBUG] snarkJS: processing: alphaTauG1: 0/4096
[DEBUG] snarkJS: processing: betaTauG1: 0/4096
[DEBUG] snarkJS: processing: betaTauG2: 0/1
[INFO]  snarkJS: Contribution Response Hash imported: 
		7f9d40a6 950c9618 77ca1b1c 09051111
		77c1ec07 0426461d 9f4f0d81 aeec63b2
		54edc382 2db8db70 05f0968a 187e9d47
		80ab5d40 ece32e0b 35ad1d35 6ccfde13
[INFO]  snarkJS: Next Challenge Hash: 
		d4bc228f f82e99ec edb382e6 45200d24
		99277f4f a58c3072 1caeed2a 109d8e41
		c863ef84 ad73c5a8 7f4aff22 f99c73a7
		a5487e5d a377a55a 36f390a5 c461fe53
[INFO]  snarkJS: Powers Of tau file OK!
[INFO]  snarkJS: Next challenge hash: 
		d4bc228f f82e99ec edb382e6 45200d24
		99277f4f a58c3072 1caeed2a 109d8e41
		c863ef84 ad73c5a8 7f4aff22 f99c73a7
		a5487e5d a377a55a 36f390a5 c461fe53
[INFO]  snarkJS: -----------------------------------------------------
[INFO]  snarkJS: Contribution #1: Second contribution
[INFO]  snarkJS: Next Challenge: 
		d4bc228f f82e99ec edb382e6 45200d24
		99277f4f a58c3072 1caeed2a 109d8e41
		c863ef84 ad73c5a8 7f4aff22 f99c73a7
		a5487e5d a377a55a 36f390a5 c461fe53
[INFO]  snarkJS: Response Hash:
		7f9d40a6 950c9618 77ca1b1c 09051111
		77c1ec07 0426461d 9f4f0d81 aeec63b2
		54edc382 2db8db70 05f0968a 187e9d47
		80ab5d40 ece32e0b 35ad1d35 6ccfde13
[INFO]  snarkJS: Response Hash:
		9e63a5f6 2b96538d aaed2372 481920d1
		a40b9195 9ea38ef9 f5f6a303 3b886516
		0710d067 c09d0961 5f928ea5 17bcdf49
		ad75abd2 c8340b40 0e3b18e9 68b4ffef
[INFO]  snarkJS: -----------------------------------------------------
[WARN]  snarkJS: this file does not contain phase2 precalculated values. Please run: 
   snarkjs "powersoftau preparephase2" to prepare this file to be used in the phase2 ceremony.
[INFO]  snarkJS: Contribution Response Hash imported: 
		f1a525dd ac208f67 3d69a241 857568c3
		6aa0a7f7 16785240 b521e56d 0c94262e
		c4499ab4 3abce15b 1de06071 c33672a2
		3288e0a8 255373d8 0eb6d824 c3e209df
[INFO]  snarkJS: Next Challenge Hash: 
		5a0ddea4 a9916bab 804a58ca c4aec0f4
		3ed071e3 ae3e8af2 44884d9c 0d4e4f9e
		e4857788 b4519fc8 6741a99e 996086af
		28cee82e eeb63e5e 3ed752b3 a86dc8ef
[DEBUG] snarkJS: Starting section: tauG1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 0 FFTMix 1/1
[DEBUG] snarkJS: tauG1 0 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 1 FFTMix 1/1
[DEBUG] snarkJS: tauG1 1 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 2 FFTMix 1/1
[DEBUG] snarkJS: tauG1 2 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 3 FFTMix 1/1
[DEBUG] snarkJS: tauG1 3 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 4 FFTMix 1/1
[DEBUG] snarkJS: tauG1 4 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 5 FFTMix 1/1
[DEBUG] snarkJS: tauG1 5 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 6 FFTMix 1/1
[DEBUG] snarkJS: tauG1 6 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 7 FFTMix 1/1
[DEBUG] snarkJS: tauG1 7 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 8 FFTMix 1/1
[DEBUG] snarkJS: tauG1 8 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 9 FFTMix 1/1
[DEBUG] snarkJS: tauG1 9 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 10 FFTMix 1/1
[DEBUG] snarkJS: tauG1 10 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 11 FFTMix 1/1
[DEBUG] snarkJS: tauG1 11 FFTFinal 1/1
[DEBUG] snarkJS: tauG1 Prepare 1/1
[DEBUG] snarkJS: tauG1 12 FFTMix 1/1
[DEBUG] snarkJS: tauG1 12 FFTFinal 1/1
[DEBUG] snarkJS: Starting section: tauG2
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 0 FFTMix 1/1
[DEBUG] snarkJS: tauG2 0 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 1 FFTMix 1/1
[DEBUG] snarkJS: tauG2 1 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 2 FFTMix 1/1
[DEBUG] snarkJS: tauG2 2 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 3 FFTMix 1/1
[DEBUG] snarkJS: tauG2 3 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 4 FFTMix 1/1
[DEBUG] snarkJS: tauG2 4 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 5 FFTMix 1/1
[DEBUG] snarkJS: tauG2 5 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 6 FFTMix 1/1
[DEBUG] snarkJS: tauG2 6 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 7 FFTMix 1/1
[DEBUG] snarkJS: tauG2 7 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 8 FFTMix 1/1
[DEBUG] snarkJS: tauG2 8 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 9 FFTMix 1/1
[DEBUG] snarkJS: tauG2 9 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 10 FFTMix 1/1
[DEBUG] snarkJS: tauG2 10 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 11 FFTMix 1/1
[DEBUG] snarkJS: tauG2 11 FFTFinal 1/1
[DEBUG] snarkJS: tauG2 Prepare 1/1
[DEBUG] snarkJS: tauG2 12 FFTMix 1/1
[DEBUG] snarkJS: tauG2 12 FFTFinal 1/1
[DEBUG] snarkJS: Starting section: alphaTauG1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 0 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 0 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 1 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 1 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 2 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 2 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 3 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 3 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 4 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 4 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 5 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 5 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 6 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 6 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 7 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 7 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 8 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 8 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 9 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 9 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 10 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 10 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 11 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 11 FFTFinal 1/1
[DEBUG] snarkJS: alphaTauG1 Prepare 1/1
[DEBUG] snarkJS: alphaTauG1 12 FFTMix 1/1
[DEBUG] snarkJS: alphaTauG1 12 FFTFinal 1/1
[DEBUG] snarkJS: Starting section: betaTauG1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 0 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 0 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 1 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 1 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 2 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 2 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 3 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 3 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 4 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 4 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 5 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 5 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 6 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 6 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 7 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 7 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 8 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 8 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 9 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 9 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 10 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 10 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 11 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 11 FFTFinal 1/1
[DEBUG] snarkJS: betaTauG1 Prepare 1/1
[DEBUG] snarkJS: betaTauG1 12 FFTMix 1/1
[DEBUG] snarkJS: betaTauG1 12 FFTFinal 1/1
[INFO]  snarkJS: Powers Of tau file OK!
[INFO]  snarkJS: Next challenge hash: 
		5a0ddea4 a9916bab 804a58ca c4aec0f4
		3ed071e3 ae3e8af2 44884d9c 0d4e4f9e
		e4857788 b4519fc8 6741a99e 996086af
		28cee82e eeb63e5e 3ed752b3 a86dc8ef
[INFO]  snarkJS: -----------------------------------------------------
[INFO]  snarkJS: Contribution #2: Final Beacon
[INFO]  snarkJS: Next Challenge: 
		5a0ddea4 a9916bab 804a58ca c4aec0f4
		3ed071e3 ae3e8af2 44884d9c 0d4e4f9e
		e4857788 b4519fc8 6741a99e 996086af
		28cee82e eeb63e5e 3ed752b3 a86dc8ef
[INFO]  snarkJS: Response Hash:
		f1a525dd ac208f67 3d69a241 857568c3
		6aa0a7f7 16785240 b521e56d 0c94262e
		c4499ab4 3abce15b 1de06071 c33672a2
		3288e0a8 255373d8 0eb6d824 c3e209df
[INFO]  snarkJS: Response Hash:
		d4bc228f f82e99ec edb382e6 45200d24
		99277f4f a58c3072 1caeed2a 109d8e41
		c863ef84 ad73c5a8 7f4aff22 f99c73a7
		a5487e5d a377a55a 36f390a5 c461fe53
[INFO]  snarkJS: Beacon generator: 0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
[INFO]  snarkJS: Beacon iterations Exp: 10
[INFO]  snarkJS: Powers Of tau file OK!
[INFO]  snarkJS: -----------------------------------------------------
[INFO]  snarkJS: Contribution #1: Second contribution
[INFO]  snarkJS: Next Challenge: 
		d4bc228f f82e99ec edb382e6 45200d24
		99277f4f a58c3072 1caeed2a 109d8e41
		c863ef84 ad73c5a8 7f4aff22 f99c73a7
		a5487e5d a377a55a 36f390a5 c461fe53
[INFO]  snarkJS: Response Hash:
		7f9d40a6 950c9618 77ca1b1c 09051111
		77c1ec07 0426461d 9f4f0d81 aeec63b2
		54edc382 2db8db70 05f0968a 187e9d47
		80ab5d40 ece32e0b 35ad1d35 6ccfde13
[INFO]  snarkJS: Response Hash:
		9e63a5f6 2b96538d aaed2372 481920d1
		a40b9195 9ea38ef9 f5f6a303 3b886516
		0710d067 c09d0961 5f928ea5 17bcdf49
		ad75abd2 c8340b40 0e3b18e9 68b4ffef
[INFO]  snarkJS: -----------------------------------------------------
NConstraints Before: 3272
NSignals Before: 4701
Classify Signals
classify signals: 0/4701
Reduce Constants
reducing constants:  0
Reduce Constraints
indexing constraints: 0/3266
reducing constraints: 0/3266   reduced: 0
substituting constraints: 0/13
reducing constraints: 0/13   reduced: 0
reordering constraints: 0/3266
NConstraints After: 3260
generate witness (counting):  0
seting id:  0
writing constraint:  0
writing wire2label map: 0/3403
Generating wasm...
buildHeader...
buildEntryTables...
buildEntryTables component: 0/13
buildCode...
buildCode component: 0/13
buildComponentsArray...
buildComponentsArray component: 0/13
buildMapIsInput...
buildMapIsInput signal: 0/4701
buildWit2Sig...
buildWit2Sig signal: 0/4701
constructionPhase: .327
classifySignals: .003
reduceConstants: .068
reduceConstraints: .178
generateWitnessNames: .005
generateR1cs: .076
generateWasm: .375
generateSyms: .001
[INFO]  snarkJS: Curve: bn-128
[INFO]  snarkJS: # of Wires: 3403
[INFO]  snarkJS: # of Constraints: 3260
[INFO]  snarkJS: # of Private Inputs: 3
[INFO]  snarkJS: # of Public Inputs: 4
[INFO]  snarkJS: # of Outputs: 0
[INFO]  snarkJS: Circuit hash: 
		b520d631 96f2c316 be1f068d e9f40815
		02d35773 4da75552 43449b21 078fc3e9
		d40fd1b3 9427c58f 2ab6fb9d 5f354e77
		636adc3c 605e07a8 33da7919 a5e238bc
[DEBUG] snarkJS: Applying key: L Section: 0/3398
[DEBUG] snarkJS: Applying key: H Section: 0/4096
[INFO]  snarkJS: Contribution Hash: 
		52ff9e72 b92431b0 9bcbc922 06b2f2ca
		a458fa59 e1bcf218 182f9d78 3e2aa81c
		88ff8338 a3ad2d75 c915bfd4 de71a548
		4f814923 b71b5add ac6ce14f 1902a537
[ERROR] snarkJS: H section does not match

How to generate "witness.wtns" files using snarkjs?

I can't use the following command to generate "witness.wtns" file.

>snarkjs wtns calculate circuit.wasm input.json witness.wtns

Error: Invalid Command

This command is written on this page and README Guide 22.

My version of snarkjs is 0.3.60.

How should I generate "witness.wtns" files using snarkjs?

Dead loop or taking too long to setup such circuit

include "../../node_modules/circom/circuits/comparators.circom";
include "../../node_modules/circom/circuits/sha256/sha256_2.circom";
 
template Sha256() {
    signal input value
    signal output out;
 
    component sha256_2 = Sha256_2();
    sha256_2.a <-- 0;
    sha256_2.b <-- value;
 
    out <== sha256_2.out;
}
 
template BankBalancesProover(nBanks) {
    signal private input balances[nBanks];
    signal input expectedBalanceHashes[nBanks];
    signal input minimalBalanceRequirement;
    signal output out;
 
    var i;
 
    component sha256[nBanks];
    for (i = 0; i < nBanks; ++i) {
        sha256[i] = Sha256();
    }
 
    component lessthan = LessThan(32);
    var totalBalance = 0;
    for (i = 0; i < nBanks; ++i) {
        sha256[i].value <-- balances[i];
        //expectedBalanceHashes[i] === sha256[i].out;
        totalBalance += balances[i];
    }
    lessthan.in[0] <-- totalBalance;
    lessthan.in[1] <-- minimalBalanceRequirement;
 
    out <== lessthan.out;
}
 
component main = BankBalancesProover(2);

Circom complication passed, but setup using snarkjs took hours and I suspect it was a deadloop...

PLONK prove doesn't work for Getting Started circuit. Error: Polinomial does not divide

I followed the instruction as in README.md file with plonk.
But, at step 24, it fails with the following error. witness should be correct value.

Anyone knows how to resolve it?

[ERROR] snarkJS: Error: Polinomial does not divide
    at divPol1 (/home/username/.nvm/versions/node/v14.17.0/lib/node_modules/snarkjs/build/cli.cjs:7188:19)
    at round5 (/home/username/.nvm/versions/node/v14.17.0/lib/node_modules/snarkjs/build/cli.cjs:7131:18)
    at plonk16Prove (/home/username/.nvm/versions/node/v14.17.0/lib/node_modules/snarkjs/build/cli.cjs:6484:11)
    at async Object.plonkProve [as action] (/home/username/.nvm/versions/node/v14.17.0/lib/node_modules/snarkjs/build/cli.cjs:8825:36)
    at async clProcessor (/home/username/.nvm/versions/node/v14.17.0/lib/node_modules/snarkjs/build/cli.cjs:280:21)

Use ECMA-262-standard BigInt

Hi, fan of the work here, just wondering whether it's possible to use BigInt now that it is at Stage 3 (the last one before the "ready to implement", and BigInts are already in V8, JavaScriptCore, and SpiderMonkey per https://github.com/tc39/proposal-bigint at bottom). And if so, what if any speedup does native BigInt gain? Thanks.

snarkjs setup failing in nodejs 14.11

I am trying a simple factor multiplication circuit as give in the circom tutorial. I am able to compile the circuit as per the command >> circom circuit.circom --r1cs --wasm --sym

However the following snarkjs commands and steps are failing >>

snarkjs printconstraints -r circuit.r1cs -s circuit.sym
snarkjs setup

Readme update

Hello,
In readme file, it is specified that the methods 'setup', 'genProof' and 'isValid' are accesible like that:

zkSnark.setup
zkSnark.genProof
zkSnark.isValid

but actually they are behind 'original' or 'groth' property, depends on what kind of protocol is used:

zkSnark.original.setup
zkSnark.original.genProof
zkSnark.original.isValid

zkSnark.groth.setup
zkSnark.groth.genProof
zkSnark.groth.isValid

Thank you.

No snarkjs setup option

Hello, I am trying to generate a proof from a r1cs file; I have attempted several different snarkjs tutorials, each of which mention a

snarkjs setup

command that can be used for key generation. I find no snarkjs setup capability is available, the only way I was able to generate a proof from my r1cs file was to first run through the full Powers of Tau ceremony to perform key generation.

In my opinion an ideal flow would not require running the full Powers of Tau ceremony when your project is in the development phase, I'd really just like to "kick the tires" and see that the end-to-end process of proof verification works using some dummy keys.

Can't install snarkjs

Hello, I can't install snarkjs

I'm running sudo npm install -g snarkjs to install it, with node version v14.17.1, and I get the following error:

npm ERR! code 128
npm ERR! command failed
npm ERR! command git --no-replace-objects ls-remote ssh://[email protected]/jbaylina/blake2b-wasm.git
npm ERR! [email protected]: Permission denied (publickey).
npm ERR! fatal: Could not read from remote repository.
npm ERR! 
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.

I have an ssh key that is working fine, idk what I am missing, any help with this?

Inputs over 16 digits are modified

I am experimenting with the circuit.circom circuit from the circom Tutorial:

template Multiplier() {
    signal private input a;
    signal private input b;
    signal output c;

    c <== a*b;
}

component main = Multiplier();

If I provide inputs which are longer than 16 digits such as:

{"a": 13905001134553859943, "b": 2}

the witness.json output is:

[
 "1",
 "27810002269107720192",
 "13905001134553860096",
 "2"
]

Notice that the second to last number is the signal a which is 13905001134553860096 instead of 13905001134553859943 and the output signal is 27810002269107720192 instead of 27810002269107719886.

I am using "circom": "^0.5.11", "snarkjs": "^0.1.31"

Can't use snarkjs in browser with webpack in Angular

Environment:

  • os: macOS BigSur 11.4 (m1 processor)
  • node: v15.4.0
  • npm 7.0.15
  • Angular: 12.0.5
  • snarkjs: 0.4.6

When i try to import and use the library in angular 12 i get the following error:

data:application/javascript;base64,KGZ1bmN0aW9uIHRocmVhZChzZWxmKSB7CiAgY29uc3QgTUFYTUVNID0gMzI3Njc7CiAgbGV0IGluc3RhbmNlOwogIGxldCBtZW1vcnk7CgogIGlmIChzZWxmKSB7CiAgICBzZWxmLm9ubWVzc2FnZSA9IGZ1bmN0aW9uIChlKSB7CiAgICAgIGxldCBkYXRhOwoKICAgICAgaWYgKGUuZGF0YSkgewogICAgICAgIGRhdGEgPSBlLmRhdGE7CiAgICAgIH0gZWxzZSB7CiAgICAgICAgZGF0YSA9IGU7CiAgICAgIH0KCiAgICAgIGlmIChkYXRhWzBdLmNtZCA9PSAiSU5JVCIpIHsKICAgICAgICBpbml0KGRhdGFbMF0pLnRoZW4oZnVuY3Rpb24gKCkgewogICAgICAgICAgc2VsZi5wb3N0TWVzc2FnZShkYXRhLnJlc3VsdCk7CiAgICAgICAgfSk7CiAgICAgIH0gZWxzZSBpZiAoZGF0YVswXS5jbWQgPT0gIlRFUk1JTkFURSIpIHsKICAgICAgICBwcm9jZXNzLmV4aXQoKTsKICAgICAgfSBlbHNlIHsKICAgICAgICBjb25zdCByZXMgPSBydW5UYXNrKGRhdGEpOwogICAgICAgIHNlbGYucG9zdE1lc3NhZ2UocmVzKTsKICAgICAgfQogICAgfTsKICB9CgogIGZ1bmN0aW9uIGluaXQoX3gpIHsKICAgIHJldHVybiBfaW5pdC5hcHBseSh0aGlzLCBhcmd1bWVudHMpOwogIH0KCiAgZnVuY3Rpb24gX2luaXQoKSB7CiAgICBfaW5pdCA9ICgwLF9Vc2Vyc19zaWFuZHJldl9Eb2N1bWVudHNfd3d3X3J1YmljX2Nhc2hfcnViaWNfY2FzaF91aV9ub2RlX21vZHVsZXNfYmFiZWxfcnVudGltZV9oZWxwZXJzX2VzbV9hc3luY1RvR2VuZXJhdG9yX19XRUJQQUNLX0lNUE9SVEVEX01PRFVMRV8wX18uZGVmYXVsdCkoZnVuY3Rpb24qIChkYXRhKSB7CiAgICAgIGNvbnN0IGNvZGUgPSBuZXcgVWludDhBcnJheShkYXRhLmNvZGUpOwogICAgICBjb25zdCB3YXNtTW9kdWxlID0geWllbGQgV2ViQXNzZW1ibHkuY29tcGlsZShjb2RlKTsKICAgICAgbWVtb3J5ID0gbmV3IFdlYkFzc2VtYmx5Lk1lbW9yeSh7CiAgICAgICAgaW5pdGlhbDogZGF0YS5pbml0LAogICAgICAgIG1heGltdW06IE1BWE1FTQogICAgICB9KTsKICAgICAgaW5zdGFuY2UgPSB5aWVsZCBXZWJBc3NlbWJseS5pbnN0YW50aWF0ZSh3YXNtTW9kdWxlLCB7CiAgICAgICAgZW52OiB7CiAgICAgICAgICAibWVtb3J5IjogbWVtb3J5CiAgICAgICAgfQogICAgICB9KTsKICAgIH0pOwogICAgcmV0dXJuIF9pbml0LmFwcGx5KHRoaXMsIGFyZ3VtZW50cyk7CiAgfQoKICBmdW5jdGlvbiBhbGxvYyhsZW5ndGgpIHsKICAgIGNvbnN0IHUzMiA9IG5ldyBVaW50MzJBcnJheShtZW1vcnkuYnVmZmVyLCAwLCAxKTsKCiAgICB3aGlsZSAodTMyWzBdICYgMykgdTMyWzBdKys7IC8vIFJldHVybiBhbHdheXMgYWxpZ25lZCBwb2ludGVycwoKCiAgICBjb25zdCByZXMgPSB1MzJbMF07CiAgICB1MzJbMF0gKz0gbGVuZ3RoOwoKICAgIGlmICh1MzJbMF0gKyBsZW5ndGggPiBtZW1vcnkuYnVmZmVyLmJ5dGVMZW5ndGgpIHsKICAgICAgY29uc3QgY3VycmVudFBhZ2VzID0gbWVtb3J5LmJ1ZmZlci5ieXRlTGVuZ3RoIC8gMHgxMDAwMDsKICAgICAgbGV0IHJlcXVpcmVkUGFnZXMgPSBNYXRoLmZsb29yKCh1MzJbMF0gKyBsZW5ndGgpIC8gMHgxMDAwMCkgKyAxOwogICAgICBpZiAocmVxdWlyZWRQYWdlcyA+IE1BWE1FTSkgcmVxdWlyZWRQYWdlcyA9IE1BWE1FTTsKICAgICAgbWVtb3J5Lmdyb3cocmVxdWlyZWRQYWdlcyAtIGN1cnJlbnRQYWdlcyk7CiAgICB9CgogICAgcmV0dXJuIHJlczsKICB9CgogIGZ1bmN0aW9uIGFsbG9jQnVmZmVyKGJ1ZmZlcikgewogICAgY29uc3QgcCA9IGFsbG9jKGJ1ZmZlci5ieXRlTGVuZ3RoKTsKICAgIHNldEJ1ZmZlcihwLCBidWZmZXIpOwogICAgcmV0dXJuIHA7CiAgfQoKICBmdW5jdGlvbiBnZXRCdWZmZXIocG9pbnRlciwgbGVuZ3RoKSB7CiAgICBjb25zdCB1OCA9IG5ldyBVaW50OEFycmF5KG1lbW9yeS5idWZmZXIpOwogICAgcmV0dXJuIG5ldyBVaW50OEFycmF5KHU4LmJ1ZmZlciwgdTguYnl0ZU9mZnNldCArIHBvaW50ZXIsIGxlbmd0aCk7CiAgfQoKICBmdW5jdGlvbiBzZXRCdWZmZXIocG9pbnRlciwgYnVmZmVyKSB7CiAgICBjb25zdCB1OCA9IG5ldyBVaW50OEFycmF5KG1lbW9yeS5idWZmZXIpOwogICAgdTguc2V0KG5ldyBVaW50OEFycmF5KGJ1ZmZlciksIHBvaW50ZXIpOwogIH0KCiAgZnVuY3Rpb24gcnVuVGFzayh0YXNrKSB7CiAgICBpZiAodGFza1swXS5jbWQgPT0gIklOSVQiKSB7CiAgICAgIHJldHVybiBpbml0KHRhc2tbMF0pOwogICAgfQoKICAgIGNvbnN0IGN0eCA9IHsKICAgICAgdmFyczogW10sCiAgICAgIG91dDogW10KICAgIH07CiAgICBjb25zdCB1MzJhID0gbmV3IFVpbnQzMkFycmF5KG1lbW9yeS5idWZmZXIsIDAsIDEpOwogICAgY29uc3Qgb2xkQWxsb2MgPSB1MzJhWzBdOwoKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgdGFzay5sZW5ndGg7IGkrKykgewogICAgICBzd2l0Y2ggKHRhc2tbaV0uY21kKSB7CiAgICAgICAgY2FzZSAiQUxMT0NTRVQiOgogICAgICAgICAgY3R4LnZhcnNbdGFza1tpXS52YXJdID0gYWxsb2NCdWZmZXIodGFza1tpXS5idWZmKTsKICAgICAgICAgIGJyZWFrOwoKICAgICAgICBjYXNlICJBTExPQyI6CiAgICAgICAgICBjdHgudmFyc1t0YXNrW2ldLnZhcl0gPSBhbGxvYyh0YXNrW2ldLmxlbik7CiAgICAgICAgICBicmVhazsKCiAgICAgICAgY2FzZSAiU0VUIjoKICAgICAgICAgIHNldEJ1ZmZlcihjdHgudmFyc1t0YXNrW2ldLnZhcl0sIHRhc2tbaV0uYnVmZik7CiAgICAgICAgICBicmVhazsKCiAgICAgICAgY2FzZSAiQ0FMTCI6CiAgICAgICAgICB7CiAgICAgICAgICAgIGNvbnN0IHBhcmFtcyA9IFtdOwoKICAgICAgICAgICAgZm9yIChsZXQgaiA9IDA7IGogPCB0YXNrW2ldLnBhcmFtcy5sZW5ndGg7IGorKykgewogICAgICAgICAgICAgIGNvbnN0IHAgPSB0YXNrW2ldLnBhcmFtc1tqXTsKCiAgICAgICAgICAgICAgaWYgKHR5cGVvZiBwLnZhciAhPT0gInVuZGVmaW5lZCIpIHsKICAgICAgICAgICAgICAgIHBhcmFtcy5wdXNoKGN0eC52YXJzW3AudmFyXSArIChwLm9mZnNldCB8fCAwKSk7CiAgICAgICAgICAgICAgfSBlbHNlIGlmICh0eXBlb2YgcC52YWwgIT0gInVuZGVmaW5lZCIpIHsKICAgICAgICAgICAgICAgIHBhcmFtcy5wdXNoKHAudmFsKTsKICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KCiAgICAgICAgICAgIGluc3RhbmNlLmV4cG9ydHNbdGFza1tpXS5mbk5hbWVdKC4uLnBhcmFtcyk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgICAgfQoKICAgICAgICBjYXNlICJHRVQiOgogICAgICAgICAgY3R4Lm91dFt0YXNrW2ldLm91dF0gPSBnZXRCdWZmZXIoY3R4LnZhcnNbdGFza1tpXS52YXJdLCB0YXNrW2ldLmxlbikuc2xpY2UoKTsKICAgICAgICAgIGJyZWFrOwoKICAgICAgICBkZWZhdWx0OgogICAgICAgICAgdGhyb3cgbmV3IEVycm9yKCJJbnZhbGlkIGNtZCIpOwogICAgICB9CiAgICB9CgogICAgY29uc3QgdTMyYiA9IG5ldyBVaW50MzJBcnJheShtZW1vcnkuYnVmZmVyLCAwLCAxKTsKICAgIHUzMmJbMF0gPSBvbGRBbGxvYzsKICAgIHJldHVybiBjdHgub3V0OwogIH0KCiAgcmV0dXJuIHJ1blRhc2s7Cn0pKHNlbGYp:34 Uncaught ReferenceError: <PATH-TO-PROJECT>_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__ is not defined
    at _init 

shortly

Uncaught ReferenceError: <PATH-TO-PROJECT>_node_modules_babel_runtime_helpers_esm_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__ is not defined

The same thing happens when importing a minified snarkjs.min.js file.

If i add it as <script> all working correctly

can't convert .circom file into json

I want to convert my circuit.circom into a json file, so that i can parse it into circuitDef variable.
const circuitDef = JSON.parse(fs.readFileSync("myCircuit.cir", "utf8"));
I tried to use circom circuit.circom -o circuit.json to generate the json, nothing is generated after i run the command.

the comment said "myCircuit.cir" is the output of the jaz compiler, what does the jaz compiler mean?

no such file or directory: "circuit.wasm"

When I run the example in nodejs as readme.md, here is something wrong, how can i fix it?

errorImage:
image

sourcecode:

const snarkjs = require("snarkjs");
const fs = require("fs");

async function run() {
    const { proof, publicSignals } = await snarkjs.groth16.fullProve({a: 10, b: 21}, "circuit.wasm", "circuit_final.zkey");

    console.log("Proof: ");
    console.log(JSON.stringify(proof, null, 1));

    const vKey = JSON.parse(fs.readFileSync("verification_key.json"));

    const res = await snarkjs.groth16.verify(vKey, publicSignals, proof);

    if (res === true) {
        console.log("Verification OK");
    } else {
        console.log("Invalid proof");
    }

}

run().then(() => {
    process.exit(0);
});

Documentation request - When published onchain (in Groth but probably in Original too), proof.B coordinates [0] and [1] need to be inverted

Example of current output of snarkjs proof:

{
 "pi_a": [
  "8672724157132394715227818352194233917722827782658190072425728153459290955312",
  "7375086425622569736819116160743186769012649834254836145031174930518838963488",
  "1"
 ],
 "pi_b": [["6881925918148905105441347662954817864186305337036815078560618994321663172222",
   "3049015615790940851316755450706164346858085868225728346367249985466115202138"
  ],
  ["13771197875345021380185234591840276140969529068670354576635291846742746862832",
   "14561090412457165546517536381334271644464928208309915762919468486930221707975"
  ]],
  [
   "1",
   "0"
  ]
 ],
 "pi_c": ["19360681555332980378414239993347024849778805526350853773452435961609577282662",
  "3544921845580311861522375623286122893850008281531259544658505155859628522276"],
  "1"
 ],
 "protocol": "groth"
}

Rightful version for usage in Smart Contract:

{
 "pi_a": [
  "8672724157132394715227818352194233917722827782658190072425728153459290955312",
  "7375086425622569736819116160743186769012649834254836145031174930518838963488",
  "1"
 ],
 "pi_b": [[
   "3049015615790940851316755450706164346858085868225728346367249985466115202138",
"6881925918148905105441347662954817864186305337036815078560618994321663172222"
  ],
  ["14561090412457165546517536381334271644464928208309915762919468486930221707975",
"13771197875345021380185234591840276140969529068670354576635291846742746862832"
  ]],
  [
   "1",
   "0"
  ]
 ],
 "pi_c": ["19360681555332980378414239993347024849778805526350853773452435961609577282662",
  "3544921845580311861522375623286122893850008281531259544658505155859628522276"],
  "1"
 ],
 "protocol": "groth"
}

You also need to get rid of the 1 and [1,0]

Feature Request: Remove dependency on wasm for generating witness

For compiling large circuits, wasm is problematic, using a native backend as with snarkit is the only way to compile large circuits. Would it be possible to update snarkjs to generate a witness without having to use wasm in order to support large circuits? Wold that involve a large amount of work?

Can't find package.json in directory

Whenever I put any snarkjs command it shows the following but the package.json file is present in that directory.

 internal/fs/utils.js:269
    throw err;
    ^

Error: ENOENT: no such file or directory, open '\C:\Users\fattah\AppData\Roaming\npm\node_modules\snarkjs\package.json'
    at Object.openSync (fs.js:462:3)
    at Object.readFileSync (fs.js:364:35)
    at Object.<anonymous> (C:\Users\fattah\AppData\Roaming\npm\node_modules\snarkjs\build\cli.cjs:1232:15)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47 {
  errno: -4058,
  syscall: 'open',
  code: 'ENOENT',
  path: '\\C:\\Users\\fattah\\AppData\\Roaming\\npm\\node_modules\\snarkjs\\package.json'
}

Invalid Unicode escape sequence on Windows

I wrote some samples to practice. It seems some format error in my json file. It shows

C:\Users\user\code\test\circom\hellow>snarkjs info -c main.json
SyntaxError: Invalid Unicode escape sequence
    at new Circuit (C:\Users\user\AppData\Roaming\npm\node_modules\snarkjs\src\circuit.js:46:78)
    at Object.<anonymous> (C:\Users\user\AppData\Roaming\npm\node_modules\snarkjs\cli.js:279:21)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
ERROR: SyntaxError: Invalid Unicode escape sequence

Here is my circom code, (not sure it's correct or not, still learning...)

include "../circomlib/circuits/sha256/sha256.circom"
include "../circomlib/circuits/binsum.circom"
include "../circomlib/circuits/bitify.circom"

template Sha256_verifier() {
    signal private input in;
    signal output out;

    var numBits = nbits(in);
    component inBits = Num2Bits(numBits);
    inBits.in <-- in;

    component sha256 = Sha256(numBits);
    for (var i=0; i<numBits; i++) {
        sha256.in[i] <-- inBits.out[i];
    }

    component outNum = Bits2Num(256);
    for (var i=0; i<256; i++) {
        outNum.in[i] <== sha256.out[i];
    }
    out <== outNum.out;
    // sha256.out === out;
}

component main = Sha256_verifier();

It works on my Mac, but it's too slow to setup. So, I run it on my Windows, but it has the above errors.

it works on Windows with the following code.(generating proofs, setup, and verification are fine)

template Multiplier() {
    signal private input a;
    signal private input b;
    signal output c;

    c <== a*b;
}
component main = Multiplier();

[Bug] Can't run examples from getting started, snarkjs fails

Description

I've been trying to go through getting started chapter, and steps that require snarkjs are errory. Full log below.

Other commands are also failing, if needed, I can provide logs for them as well.

Env

  • Mac OS Big Sur (Arm)
  • snarkjs@latest
  • circom@latest

Log

$ .../circom/factor $ snarkjs info -c circuit.r1cs && snarkjs print -r circuit.r1cs -s circuit.sym

#
# Fatal error in , line 0
# Check failed: allocator->SetPermissions(reinterpret_cast<void*>(region.begin()), region.size(), PageAllocator::kNoAccess).
#
#
#
#FailureMessage Object: 0x16cf45ee8
 1: 0x102fb12a4 node::NodePlatform::GetStackTracePrinter()::$_3::__invoke() [/opt/local/bin/node]
 2: 0x1037d84a8 V8_Fatal(char const*, ...) [/opt/local/bin/node]
 3: 0x103525494 v8::internal::wasm::WasmCodeAllocator::GetNumCodeSpaces() const [/opt/local/bin/node]
 4: 0x103525334 v8::internal::wasm::WasmCodeAllocator::FreeCode(v8::internal::Vector<v8::internal::wasm::WasmCode* const>) [/opt/local/bin/node]
 5: 0x103528198 v8::internal::wasm::NativeModule::FreeCode(v8::internal::Vector<v8::internal::wasm::WasmCode* const>) [/opt/local/bin/node]
 6: 0x103535d1c v8::internal::wasm::WasmEngine::FreeDeadCodeLocked(std::__1::unordered_map<v8::internal::wasm::NativeModule*, std::__1::vector<v8::internal::wasm::WasmCode*, std::__1::allocator<v8::internal::wasm::WasmCode*> >, std::__1::hash<v8::internal::wasm::NativeModule*>, std::__1::equal_to<v8::internal::wasm::NativeModule*>, std::__1::allocator<std::__1::pair<v8::internal::wasm::NativeModule* const, std::__1::vector<v8::internal::wasm::WasmCode*, std::__1::allocator<v8::internal::wasm::WasmCode*> > > > > const&) [/opt/local/bin/node]
 7: 0x103533d3c v8::internal::wasm::WasmEngine::PotentiallyFinishCurrentGC() [/opt/local/bin/node]
 8: 0x103534f78 v8::internal::wasm::WasmEngine::ReportLiveCodeForGC(v8::internal::Isolate*, v8::internal::Vector<v8::internal::wasm::WasmCode*>) [/opt/local/bin/node]
 9: 0x103535268 v8::internal::wasm::WasmEngine::ReportLiveCodeFromStackForGC(v8::internal::Isolate*) [/opt/local/bin/node]
10: 0x103198fe0 v8::internal::StackGuard::HandleInterrupts() [/opt/local/bin/node]
11: 0x103428a74 v8::internal::Runtime_StackGuard(int, unsigned long*, v8::internal::Isolate*) [/opt/local/bin/node]
12: 0x1036aa8cc Builtins_CEntry_Return1_DontSaveFPRegs_ArgvOnStack_NoBuiltinExit [/opt/local/bin/node]
13: 0x10366f9fc Builtins_AsyncFunctionAwaitResolveClosure [/opt/local/bin/node]
14: 0x1036f6b5c Builtins_PromiseFulfillReactionJob [/opt/local/bin/node]
15: 0x103662748 Builtins_RunMicrotasks [/opt/local/bin/node]
16: 0x103640d68 Builtins_JSRunMicrotasksEntry [/opt/local/bin/node]
17: 0x150008000 
[1]    57544 trace trap  snarkjs info -c circuit.r1cs

Getting error on setup

I followed the test in zksnark_groth.js, but got error like this,

C:\Users\user\code\node_modules\snarkjs\src\gcurve.js:32
        return this.F.isZero(p[2]);
                              ^

TypeError: Cannot read property '2' of undefined
    at GCurve.isZero (C:\Users\user\code\node_modules\snarkjs\src\gcurve.js:32:31)
    at GCurve.double (C:\Users\user\code\node_modules\snarkjs\src\gcurve.js:105:18)
    at Object.exports.mulScalar (C:\Users\user\code\node_modules\snarkjs\src\futils.js:31:17)
    at GCurve.mulScalar (C:\Users\user\code\node_modules\snarkjs\src\gcurve.js:140:23)
    at Object.genProof (C:\Users\user\code\node_modules\snarkjs\src\prover_groth.js:70:42)
    at Object.generateProof (C:\Users\user\code\00_Projects\zk\zkVerifier\circom\nodejs-client\proof_generation.js:33:50)
    at Object.<anonymous> (C:\Users\user\code\00_Projects\zk\zkVerifier\circom\nodejs-client\index.js:13:7)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)

I print out setup.vk_proof, there is no vk_delta_1. In prover_groth.js:70:42 ,

proof.pi_a  = G1.add( proof.pi_a, G1.mulScalar( vk_delta_1, r ));

Not sure the error is relative to vk_delta_1 missing.

Getting TypeError: a.affine is not a function when using snarksjs

I am experimenting with Snarks.js, I tried using it https://github.com/iden3/circom
I use the code as so

const zkSnark = require("snarkjs");
const fs=require("fs")
const circuitDef = JSON.parse(fs.readFileSync("mycircuit.json", "utf8"));
const circuit = new zkSnark.Circuit(circuitDef);
const setup = zkSnark.original.setup(circuit);
fs.writeFileSync("myCircuit.vk_proof", JSON.stringify(setup.vk_proof), "utf8");
fs.writeFileSync("myCircuit.vk_verifier", JSON.stringify(setup.vk_verifier), "utf8");
setup.toxic // Must be discarded.

const input = {
"in": 30,
}
const witness = circuit.calculateWitness(input);

const vk_proof = JSON.parse(fs.readFileSync("myCircuit.vk_proof", "utf8"));
console.log(vk_proof)
const {proof, publicSignals} = zkSnark.original.genProof(vk_proof, witness)
console.log(proof, publicSignals)

bn128 pairing not computed correctly?

For a project of mine (https://github.com/meilof/pysnark) I am trying to convert Groth proofs generated by libsnark into a format that can be verified by snarkjs and by websnark (conversion script: https://github.com/meilof/pysnark/blob/master/pysnark/libsnark/tosnarkjsgg.py) .

The proofs are verified succesfully using websnark.

Unfortunately, the proofs fail to be verified by snarkjs. However, if in verifier_groth.js I use "bn128.pairing(vk_verifier.vk_alfa_1 , vk_verifier.vk_beta_2)" instead of vk_verifier.vk_alfabeta_12, the proofs check out. So apparently there is an inconsistency in how libsnark and snarkjs compute pairings (or represent the result).

I noticed that websnark does:

        const valid = this.instance.exports.bn128_pairingEq4(pA, pB, pIC, pGamma2, pC, pDelta2, pAlfa1, pBeta2, this.pOneT);
//        const valid = this.instance.exports.bn128_pairingEq3(pA, pB, pIC, pGamma2, pC, pDelta2, pAlfaBeta);

I also noticed that the proof generated using libsnark and converted using my conversion script work with both alternatives for the above verification, whereas proofs generated using snarkjs only work with the first one, i.e., they only work if the pairing pAlfaBeta computed by snarkjs is not used.

This seems to suggest to me that there is something wrong with the way pairings are computed in snarkjs. Maybe good to test its output against a reference output?

Hope this helps! Please let me know if you want to discuss this in more detail.

genProof fails with `TypeError: a.affine is not a function`

At the proof generation line:
const {proof, publicSignals} = zkSnark.original.genProof(vk_proof, witness);

I get the error:
TypeError: a.affine is not a function
The source of the error is line 152 in bigint.js:
return (a) => (a.affine(q) == wBigInt.zero);

snarkjs calculatewitness raises 3 Hash not found 0 0 0 0 Error for a no-constraint circuit

Problem?
Snarkjs raises 3 Hash not found 0 0 0 0 error for an empty circuit

How to reproduce?
Here's the used circuit & input.json
https://gist.github.com/wanseob/d4d31e204d25cf31416a0af4ee98e2e6

circom circuit.circom --r1cs --wasm --sym
snarkjs calculatewitness --wasm circuit.wasm --input input.json --witness witness.json
ERROR:  3 Hash not found 0 0 0 0
Error: Hash not found 0 0 0 0
    at error (/home/wanseob/.nvm/versions/node/v12.16.2/lib/node_modules/snarkjs/node_modules/circom_runtime/js/witness_calculator.js:47:23)
    at wasm-function[87]:0x61f1
    at wasm-function[94]:0x6382
    at wasm-function[95]:0x63bb
    at WitnessCalculator._doCalculateWitness (/home/wanseob/.nvm/versions/node/v12.16.2/lib/node_modules/snarkjs/node_modules/circom_runtime/js/witness_calculator.js:133:35)
    at WitnessCalculator.calculateWitness (/home/wanseob/.nvm/versions/node/v12.16.2/lib/node_modules/snarkjs/node_modules/circom_runtime/js/witness_calculator.js:150:20)
    at run (/home/wanseob/.nvm/versions/node/v12.16.2/lib/node_modules/snarkjs/cli.js:367:32)
ERROR: Error: Hash not found 0 0 0 0

versions:

  • circom: 0.5.11
  • snarkjs: 0.1.31
  • nodejs: 12.16.2

The zkey new command is very slow after version 0.3.23

I used version 0.3.23 to generate a zkey file and it took a few minutes.

Next, I upgraded to 0.3.24, and the same command takes a very long time - it has not finished even after more than an hour.

The log shows that the Writing points IC and Writing points C steps take a very long time.

The r1cs file I used is here: https://www.dropbox.com/s/kg1fv7fgbqffv7e/batchUstCircuit.r1cs?dl=0
The ptau file is here: https://www.dropbox.com/s/kg4rnjdosnluuhq/pot19_final.ptau?dl=0

NODE_OPTIONS="max-old-space-size=4096" node build/cli.cjs zkey new -v batchUstCircuit.r1cs pot19_final.ptau circuit.zkey

kimleeoh protocol bug

The proof generation using Kim-Lee-Oh protocol fails because when running snarkjs setup --protocol kimleeoh it generates proving_key.json and verification_key.json with "protocol": "groth" field causing an error when generating the proof. Changing it to "protocol": "kimleeoh" fixes the problem.

Errors in the browser version.

There is no global when connected via script.

fix:

 <script>var global = window</script>
 <script src="snarkjs.min.js"></script>

Doesn't work via import (create-react-app + ts).

fix:

edit snarkjs.js

(window || global) .snarkjs = ...

and

import "snarkjs/dist/snarkjs.js"

can't use snarkjs.powersOfTau.contribute in the browser

Hi, I'm calling
var t = await snarkjs.powersOfTau.contribute(new Uint8Array(await (await (await fetch(chrome.extension.getURL("1.ptau"))).blob()).arrayBuffer()), {type:"mem"}, 'aaaa', 'dddd')
in the browset
t is returned as a Uint8Array of 64 bytes
But how can I get the resulting ptau in the browser?
In nodejs you can pass in a filename as a second parameter. But we don't have filenames in the browser.

Is there anything that can be done?
Maybe there can be added an option to pass in an Array which will be filled with the result?

TypeError: Cannot convert undefined to a BigInt

Hello,

I am getting the following error when I'm trying to use the snarkjs calculatewitness function :
TypeError: Cannot convert undefined to a BigInt
at BigInt ()
at Object.__f [as Quest] (eval at Circuit (C:\Users\AXlHT\AppData\Roaming\npm\node_modules\snarkjs\src\circuit.js:46:33), :16:29)
at RTCtx.triggerComponent (C:\Users\AXlHT\AppData\Roaming\npm\node_modules\snarkjs\src\calculateWitness.js:126:41)
at C:\Users\AXlHT\AppData\Roaming\npm\node_modules\snarkjs\src\calculateWitness.js:167:51
at Array.map ()
at RTCtx.setSignalFullName (C:\Users\AXlHT\AppData\Roaming\npm\node_modules\snarkjs\src\calculateWitness.js:166:24)
at RTCtx.setSignal (C:\Users\AXlHT\AppData\Roaming\npm\node_modules\snarkjs\src\calculateWitness.js:104:14)
at C:\Users\AXlHT\AppData\Roaming\npm\node_modules\snarkjs\src\calculateWitness.js:50:17
at iterateSelector (C:\Users\AXlHT\AppData\Roaming\npm\node_modules\snarkjs\src\calculateWitness.js:31:20)
at iterateSelector (C:\Users\AXlHT\AppData\Roaming\npm\node_modules\snarkjs\src\calculateWitness.js:35:13)
ERROR: TypeError: Cannot convert undefined to a BigInt

Here is the circuit I have been able to compile and setup :

template Quest(n) {
signal private input moves[n];
signal victory;
signal alive;

var paragraphsMapping = [[1,2,3],[4,7],[4,5], [5,6],[7,8],[0],[8,9],[0],[9,10],[99],[0]];
var paragraphsMappingLength = 11;
var maxOutcomeArrayLength = 3;
var currentParagraph = 0;
var outcomeExists = 0;

alive <-- 1;
victory <-- 0;


for (var i = 0; i < n ; i++) {

    outcomeExists = 0;

    if (victory == 0 && alive == 1) {

        for (var j = 0; j < maxOutcomeArrayLength ; j++)    {
         if(paragraphsMapping[currentParagraph][j] == moves[i]) {
    outcomeExists = 1;
            }
        }
    }

    if(outcomeExists == 1) {

  if (paragraphsMapping[moves[i]][0] == 0) {
    alive <-- 0;
  }

  if (paragraphsMapping[moves[i]][0] == 99) {
    victory <-- 1;
  }

  currentParagraph = moves[i];
    }

}

alive === 1;
victory === 1;

}

component main = Quest(4);

Typo in log output

> snarkjs calculatewitness --lt
Component Treiggered: main
End Component Treiggered: main

Treiggered should be Triggered.

> snarkjs --version
0.1.18

Angular error during compilation - Can't resolve 'crypto'

Hello,
I am running Angular and requiring 'snarkjs' library.
I have the following error during compilation:

ERROR in ../node_modules/snarkjs/src/zqfield.js
Module not found: Error: Can't resolve 'crypto' in '/Users/ognyanchikov/angular-zk/node_modules/snarkjs/src'

The problem comes from line 35 of that file (zqfield.js). It tries to require 'crypto' library, because 'window' is still undefined (during compilation of Angular project), but in Angular, the 'crypto' module is not included. The 'webpack' configuration is turning it off, as well as other modules, e.g 'fs'.

These are my packages versions:

Angular CLI: 7.1.4
Node: 8.10.0
OS: darwin x64
Angular: 7.1.4

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.11.4
@angular-devkit/build-angular     0.11.4
@angular-devkit/build-optimizer   0.11.4
@angular-devkit/build-webpack     0.11.4
@angular-devkit/core              7.1.4
@angular-devkit/schematics        7.1.4
@ngtools/webpack                  7.1.4
@schematics/angular               7.1.4
@schematics/update                0.11.4
rxjs                              6.3.3
typescript                        3.1.6
webpack                           4.23.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.