Giter Site home page Giter Site logo

meilof / pysnark Goto Github PK

View Code? Open in Web Editor NEW
158.0 8.0 25.0 17.23 MB

Library for programming zk-SNARKs directly in Python

Home Page: https://meilof.github.io/pysnark/

License: Other

Python 97.86% Shell 0.04% Jupyter Notebook 0.47% Solidity 1.63%
zero-knowledge zk-snarks smart-contracts pinocchio python3

pysnark's Introduction

PySNARK

Recent news:

13.06.2021: updated setup instructions for zkinterface (bulletproofs, bellman)

17.05.2021: want to use if branches, while and for loops in PySNARK programs? Check out oblif!

28.03.2021: updated to latest zkinterface, now works with bellman and bulletproofs

03.11.2020: updated to latest snarkjs

(This is a re-write of the original version of PySNARK, still available here.)

PySNARK lets you program zk-SNARKs (aka verifiable computations) directly in Python 3. For example, the following code runs a SNARK program to compute a cube of a number, generates key material, generates a proof, and verifies it:

import sys

from pysnark.runtime import snark

@snark
def cube(x):
    return x*x*x

print("The cube of", sys.argv[1], "is", cube(int(sys.argv[1])))

For any computations performed using the PubVal datatype provided by pysnark (or using the @snark decorator), the library keeps track of the Rank-1 constraint system of the computation. When the computation finishes, key material for the computation is generated (or re-used) and a SNARK proof is generated.

Features:

PySNARK may be used for non-commercial, experimental and research purposes; see LICENSE.md for details. PySNARK is experimental and not fit for production environment.

Binder

Installation

pip3 install git+https://github.com/meilof/pysnark

To use the libsnark backend, do

pip3 install python-libsnark

To use the qaptools backend, download and install qaptools. If qaptoosl are not in the system path, set the QAPTOOLS_BIN environment variable to their location. On Windows, the qaptools executables can be placed in the current working directory.

To use the snarkjs backend, do:

npm install snarkjs

Using PySNARK (libsnark backend)

To try out PySNARK, do the following:

cd examples
python cube.py 3

If the libsnark backend is available, it will be imported and used by default. This will execute a SNARK computation to compute the cube of the input value, 3. As the comptation prorgresses, a constraint system of the computation is kept.

By default, if available, the libsnark backend will be used. In this case, the following files will be generated:

  • pysnark_ek: key material to generate proofs for this computation (if the same computation is performed later, this file will be re-used; if another computation is performed, it is rebuilt)
  • pysnark_vk: key material to verify proofs for this computation
  • pysnark_log: computation log that can be verified with the pysnark_vk key: number of inputs/outputs, followed by the inputs/outputs themselves, followed by a proof that the input/outputs were correctly computed

PySNARK with libsnark can use the more recent Groth16 proof system instead of traditional Pinocchio proofs by using the libsnarkgg backend:

cd examples
rm pysnark_*
PYSNARK_BACKEND=libsnarkgg python3 cube.py 3

Combining with snarkjs

PySNARK with the libsnarkgg backend can automatically produce snarkjs public.json, proof.json and verification_key.json files for the performed verifiable computation:

meilofs-air:examples meilof$ PYSNARK_BACKEND=libsnarkgg python3 cube.py 33
The cube of 33 is 35937
*** Trying to read pysnark_ek
*** PySNARK: generating proof pysnark_log (sat=True, #io=2, #witness=2, #constraint=3)
*** Public inputs: 33 35937
*** Verification status: True
meilofs-air:examples meilof$ python3 -m pysnark.libsnark.tosnarkjsgg
meilofs-air:examples meilof$ snarkjs groth16 verify verification_key.json public.json proof.json
[INFO]  snarkJS: OK!

Using PySNARK (snarkjs backend)

PySNARK can be used in combination with snarkjs as a drop-in replacement of programming circuits using circom. PySNARK generates the circuit.r1cs file corresponding to the computation constraints and the witness.wtns file containing the values for the current computation:

$ PYSNARK_BACKEND=snarkjs python3 cube.py 33
The cube of 33 is 35937
snarkjs witness.wtns and circuit.r1cs written; see readme
$ snarkjs powersoftau new bn128 12 pot.ptau -v
...
$ snarkjs powersoftau prepare phase2 pot.ptau pott.ptau -v
...
$ snarkjs zkey new circuit.r1cs pott.ptau circuit.zkey
...
$ snarkjs zkey export verificationkey circuit.zkey verification_key.json
$ snarkjs groth16 prove circuit.zkey witness.wtns proof.json public.json
$ snarkjs groth16 verify verification_key.json public.json proof.json
[INFO]  snarkJS: OK!
$ snarkjs zkey export solidityverifier circuit.zkey verifier.sol
$ snarkjs zkey export soliditycalldata public.json proof.json

Using PySNARK (zkinterface backend: bellman, bulletproofs)

PySNARK with the zkinterface backend automatically produces zkinterface files for the computation. These files can be used for example with the bellman and bulletproofs backends of zkinterface, see here.

Specifically, a circuit.zkif file is generated that contains the circuit and constraints and can be used for key generation and verification. A computation.zkif file is generated that contains the circuit, constraints, and witness, and can be used by the prover.

To generate a zkif file that should work with the zkinterface libsnark backend (not tested):

examples meilof$ PYSNARK_BACKEND=zkinterface python3 cube.py 33
The cube of 33 is 35937
*** zkinterface: writing circuit
*** zkinterface: writing witness
*** zkinterface: writing constraints
*** zkinterface circuit, witness, constraints written to 'computation.zkif'
*** zkinterface: writing circuit
*** zkinterface: writing constraints
*** zkinterface circuit, constraints written to 'circuit.zkif'

To generate a zkif file for the zkinterface bellman backend and use it:

examples meilof$ PYSNARK_BACKEND=zkifbellman python3 cube.py 44
The cube of 44 is 85184
*** zkinterface: writing circuit
*** zkinterface: writing witness
*** zkinterface: writing constraints
*** zkinterface circuit, witness, constraints written to 'computation.zkif'
*** zkinterface: writing circuit
*** zkinterface: writing constraints
*** zkinterface circuit, constraints written to 'circuit.zkif'
examples meilof$ cat circuit.zkif | zkif_bellman setup
Written parameters into /Users/meilof/Subversion/pysnark/examples/bellman-pk
examples meilof$ cat computation.zkif | zkif_bellman prove
Reading parameters from /Users/meilof/Subversion/pysnark/examples/bellman-pk
Written proof into /Users/meilof/Subversion/pysnark/examples/bellman-proof
examples meilof$ cat circuit.zkif | zkif_bellman verify
Reading parameters from /Users/meilof/Subversion/pysnark/examples/bellman-pk
Reading proof from /Users/meilof/Subversion/pysnark/examples/bellman-proof
The proof is valid.
examples meilof$ PYSNARK_BACKEND=zkifbellman python3 cube.py 55
The cube of 55 is 166375
*** zkinterface: writing circuit
*** zkinterface: writing witness
*** zkinterface: writing constraints
*** zkinterface circuit, witness, constraints written to 'computation.zkif'
*** zkinterface: writing circuit
*** zkinterface: writing constraints
*** zkinterface circuit, constraints written to 'circuit.zkif'
examples meilof$ cat computation.zkif | zkif_bellman prove
Reading parameters from /Users/meilof/Subversion/pysnark/examples/bellman-pk
Written proof into /Users/meilof/Subversion/pysnark/examples/bellman-proof
examples meilof$ cat circuit.zkif | zkif_bellman verify
Reading parameters from /Users/meilof/Subversion/pysnark/examples/bellman-pk
Reading proof from /Users/meilof/Subversion/pysnark/examples/bellman-proof
The proof is valid.

Here, bellman-pk and circuit.zkif should be generated by a trusted third party. Provers should get bellman-pk and will generate the zkif files themselves; verifiers should get bellan-pk and circuit.zkif.

To generate a zkif file for the zkinterface bulletproofs backend and use it:

examples meilof$ PYSNARK_BACKEND=zkifbulletproofs python3 cube.py 33
The cube of 33 is 35937
*** zkinterface: writing circuit
*** zkinterface: writing witness
*** zkinterface: writing constraints
*** zkinterface circuit, witness, constraints written to 'computation.zkif'
*** zkinterface: writing circuit
*** zkinterface: writing constraints
*** zkinterface circuit, constraints written to 'circuit.zkif'
examples meilof$ cat computation.zkif | zkif_bulletproofs prove
Saved proof into bulletproofs-proof
examples meilof$ cat circuit.zkif | zkif_bulletproofs verify
Verifying proof in bulletproofs-proof

No trusted setup is needed. The proof bulletproofs.proof and the computation description circuit.zkif should be distributed to the verifier.

Using PySNARK (qaptools backend)

We discuss the usage of the PySNARK toolchain based on running one of the provided examples acting as each of the different types of parties in a verifiable computation: trusted party, prover, or verifier.

As trusted party

To try out running PySNARK as trusted party performing key generation, do the following:

cd examples
python cube.py 3

If PySNARK has been correctly installed, this will perform a verifiable computation that will compute the cube of the input value, 3. At the same time, it will generate all key material needed to verifiably perform the computation in the script. (Performing an example computation is the only way to generate this key material.) PySNARK produces the following files:

  • Files that should be kept secret by the trusted party generating the key material:
    • pysnark_mastersk: zk-SNARK master secret key
  • Files that the trusted party should distribute to provers along with the Python script (i.e., cube.py in this case):
    • pysnark_schedule: schedule of functions called in the computation
    • pysnark_masterek: master evaluation key
    • pysnark_ek_main: zk-SNARK evaluation key for the main function of the computation
    • pysnark_eqs_main: equations for the main function of the computation
    • pysnark_masterpk: master public key
  • Files that the trusted party should distribute to verifiers:
    • pysnark_schedule: schedule of functions called in the computation
    • pysnark_masterpk: master public key
    • pysnark_vk_main: verificaiton key for the main function
  • Files that the prover should distribute to verifiers:
    • pysnark_proof: proof that the particular computation was performed correctly
    • pysnark_values: input/output values of the computation
  • Files that are not needed anymore after the execution:
    • pysnark_eqs: equations for the zk-SNARK
    • pysnark_wires: wire values of the computation

As prover

To try out running PySNARK as a prover, put the files discussed above (i.e., pysnark_schedule, pysnark_masterek, pysnark_ek_main, and pysnark_eqs_main) together with cube.py in a directory and run the same command:

cd examples
python cube.py 3

This will perform a verifiable computation based on the previously generated key material.

As verifier

To try out running PySNARK as a verifier, put the files discussed above (i.e., pysnark_schedule, pysnark_masterpk and pysnark_vk_main received from the trusted party, and pysnark_proof and pysnark_values received from the prover) in a folder and run

python -m pysnark.qaptools.runqapver

This will verify the computation proof with respect to the input/output values from the pysnark_values file, e.g,:

# PySNARK i/o
main/o_in: 21
main/o_out: 9261

In this case, we have verifiably computed the fact that the cube of 21 is 9261. See the examples folder for additional examples.

Using commitments

PySNARK allows proofs to refer to committed data using Geppetri. This has three applications:

  • it allows proofs to refer to external private inputs from parties other than the trusted third party;
  • it allows different verifiable computations to share secret data with each other; and
  • it allows to divide a verifiable computation into multiple subcomputations, each with their own evaluation and verification keys (but all based on the same master secret key)

All computations sharing committe data should use the same master secret key.

See examples/testcomm.py for examples.

External secret inputs

To commit to data, use pysnark.qaptools.runqapinput, e.g., to commit to values 1, 2, and 3 using a commitment named test, use:

python -m pysnark.qaptools.runqapinput test 1 2 3

Alternatively, use pysnark.qaptools.runqapinput.gencomm from a Python script. Share pysnark_wires_test with any prover who wants to perform a computation with respect to this committed data, and pysnark_comm_test to any verifier.

Import this data into the verifiable computation with

[one,two,three] = pysnark.qaptools.backend.importcomm("test")

Sharing data between verifiable computations

In the first computation, do

pysnark.qaptools.backend.exportcomm([Var(1),Var(2),Var(3)], "test")

and share pysnark_wires_test and pysnark_comm_test with the other prover and the verifier, respectively.

In the second verifiable computation, do

[one,two,three] = pysnark.qaptools.backend.importcomm("test")

Sharing data between different parts of a verifiable computation

This is implicitly used whenever a function is called that is decorated with @pysnark.qaptools.backend.subqap. When a particular functon is used multiple times in a verifiable computation, using @pysnark.qaptools.backend.subqap prevents the circuit for the function to be replicated, resulting in smaller key material (but slower verification).

Using PySNARK for smart contracts

The qaptools backand of PySNARK supports the automatic generation of Solidity smart contracts that verify the correctness of the given zk-SNARK.

(Smart contracts can also be implemented using snarkjs with the snarkjs backend, see above.)

First, run a verifiable computation using the qaptools backend:

PYSNARK_BACKEND=qaptools python3 cube.py 33

(on Windows, simply run python3 cube.py 33 since qaptools is the only available backend).

Next, use the following command to generate smart contracts:

python -m pysnark.qaptools.contract

This generates smart contract contracts/Pysnark.sol to verify the previously performed verifiable computation (using library contracts/Pairing.sol that is also copied into the directory), and test script test/TestPysnark.sol that gives a test case for the contract based on the previous I/O and proof.

To test out the contracts using Truffle, first run truffle init from where you are running the above command. This functionality is based on ideas from ZoKrates. Then run truffle test to run the test script and check that the given proof can indeed be verified in Solidity.

Note that test/TestPysnark.sol indeed contains the I/O from the computation:

pragma solidity ^0.5.0;

import "truffle/Assert.sol";
import "../contracts/Pysnark.sol";

contract TestPysnark {
    function testVerifies() public {
        Pysnark ps = new Pysnark();
        uint[] memory proof = new uint[](22);
        uint[] memory io = new uint[](2);
        proof[0] = ...;
        ...
        proof[21] = ...;
        io[0] = 21; // main/o_in
        io[1] = 9261; // main/o_out
        Assert.equal(ps.verify(proof, io), true, "Proof should verify");
    }
}

Smart contracts can also refer to commitments, e.g., as imported with the pysnark.runtime.importcomm API call. In this case, the commitment becomes an argument to the verification function (a six-valued integer array), and the test case shows how the commitment used in the present computation should be used as value for that argument, e.g.:

pragma solidity ^0.5.0;

import "truffle/Assert.sol";
import "../contracts/Pysnark.sol";

contract TestPysnark {
    function testVerifies() public {
        Pysnark ps = new Pysnark(); 
        uint[] memory pysnark_comm_test = new uint[](6);
        pysnark_comm_test[0] = ...;
        ...
        Assert.equal(ps.verify(proof, io, pysnark_comm_test), true, "Proof should verify");
    }
}

To get more detailed information about the gas usage of the smart contract, run with Ganache: start ganache-cli; edit truffle.js to add a development network, e.g.:

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "*" // Match any network id
    }
  }
};

and finally, run truffle test --network development.

Acknowledgements

This software contains contributions by Koninklijke Philips N.V.. Part of this work on this software was carried out as part of the SODA project that has received funding from the European Union’s Horizon 2020 research and innovation programme under grant agreement No 731583.

This software contains contributions by Glenn Xavier. This work was supported by DARPA under Agreement No. HR00112020021.

This software also contains contributions by Meilof Veeningen.

See the license for more information.

pysnark's People

Contributors

gxavier38 avatar johannes-reinhart avatar meilof avatar rkshbrv avatar rosemanmeilof avatar xiaohan2909 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

pysnark's Issues

Key material too small and missing master secret key error for example cube.py using qaptools backend

Hello,
I recently installed your library and as a first step I tried the example that you suggest, cube.py, using qaptools backend.
I first ran the code as the trusted third party. It successfully generated all the files.
Then I created a prover folder in which I copy-pasted the cube.py source as well as all the required files listed in the README, namely:

  • pysnark_schedule
  • pysnark_masterek
  • pysnark_ek_main
  • pysnark_eqs_main
    The I executed the code in this folder, and ran into this error:
Traceback (most recent call last):
  File "/Users/denisverstraeten/Envs/anonymous-auction380/lib/python3.8/site-packages/pysnark/qaptools/backend.py", line 165, in prove
    cursz, curpubsz = runqapgen.ensure_mkey(sz, pubsz)
  File "/Users/denisverstraeten/Envs/anonymous-auction380/lib/python3.8/site-packages/pysnark/qaptools/runqapgen.py", line 115, in ensure_mkey
    raise IOError("Key material too small ("+str(curek)+","+str(curpk)+
OSError: Key material too small (8,-1)<(8,2) and missing master secret key

By following the traceback, it appeared that curpk is equal to -1. curpk is defined as curpk=get_mpkey_size() (line 105 of qaptools/runqapgen.py).
Looking at the function get_mpkey_size (line 74 of the same file), the value -1 is returned if there is an IOError, which, in this case in my opinion , comes from mpkf = open(options.get_mpkey_file()) (line 81).
Then, by inspecting the function get_mpkey_file (line 57 of qaptools/options.py), which returns 'pysnark_masterpk', I deduced that for the prover to be able to compute the proof, I needed to include the file pysnark_masterpk into the prover folder. And indeed, by doing so, the proof (as well as the verification) worked.
Is there something that I did wrong in the way that I followed the small example tutorial ? Moreover, in the previous discussion, nothing is linked especially to the cube example, I have the impression that any proof would lead to the same error. Should pysnark_masterpk be given to the prover in any case ?
Thank you very much for your answer,
Have a nice day,
Denis

The Future

The concept of ZKVM is very popular recently. It means to prove any program in the virtual environment of ZKP. I found the pysnark library to be very early and easy to use. Just need to add: @snark. Why is no one paying attention to your library? Who is the development team of pysnark, and is there a strong follow-up plan?

running example in README.md failed

Using the latest master source and [email protected]:

python3 cube.py 33                  
The cube of 33 is 35937
*** Trying to read pysnark_ek
*** No pysnark_ek or computation changed, generating keys...
*** PySNARK: generating proof pysnark_log (sat=True, #io=2, #witness=2, #constraint=3)
*** Public inputs: 33 35937
*** Verification status: True
⋊> ~/P/p/examples on master ◦                                     
⋊> ~/P/p/examples on master ◦                                     
⋊> ~/P/p/examples on master ◦                                     
⋊> ~/P/p/examples on master ◦ python3 -m pysnark.libsnark.tosnarkjs
*** Created proof.json, verification_key.json, public.json; test using "snarkjs verify"

⋊> ~/P/p/examples on master ◦ snarkjs verify                     
[ERROR] snarkJS: TypeError: Cannot read property 'toUpperCase' of undefined
    at normalizeName (/usr/local/lib/node_modules/snarkjs/build/cli.cjs:1703:18)
    at getCurveFromName (/usr/local/lib/node_modules/snarkjs/build/cli.cjs:1692:22)
    at groth16Verify (/usr/local/lib/node_modules/snarkjs/build/cli.cjs:6342:25)
    at Object.groth16Verify$1 [as action] (/usr/local/lib/node_modules/snarkjs/build/cli.cjs:6898:27)
    at clProcessor (/usr/local/lib/node_modules/snarkjs/build/cli.cjs:1264:31)
    at Object.<anonymous> (/usr/local/lib/node_modules/snarkjs/build/cli.cjs:6680:1)
    at Module._compile (internal/modules/cjs/loader.js:1251:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
    at Module.load (internal/modules/cjs/loader.js:1100:32)
    at Function.Module._load (internal/modules/cjs/loader.js:962:14)

Int Bit Size

Is it possible to use ints of size greater than 16?

Sudoku Example: Assertion failed

Running the sudoku example gives me an assertion failed. What is the problem here?

checking 1-9 in [{0}, {0}, {0}, 8, {0}, 2, 9, {0}, 1]
checking 1-9 in [{0}, {0}, 4, 9, 7, {0}, 2, {0}, {0}]
checking 1-9 in [{0}, 9, {0}, {0}, {0}, {0}, 3, {0}, {0}]
checking 1-9 in [{0}, {0}, {0}, {0}, 1, 3, 5, 7, 9]
checking 1-9 in [{0}, 4, 9, {0}, 5, {0}, 1, 2, {0}]
checking 1-9 in [1, 5, 7, 9, 2, {0}, {0}, {0}, {0}]
checking 1-9 in [{0}, {0}, 7, {0}, {0}, {0}, {0}, 2, {0}]
checking 1-9 in [{0}, {0}, 2, {0}, 3, 8, 5, {0}, {0}]
checking 1-9 in [6, {0}, 3, 2, {0}, 5, {0}, {0}, {0}]
checking 1-9 in [{0}, {0}, {0}, {0}, {0}, 4, {0}, 9, {0}]
checking 1-9 in [8, {0}, 2, 9, 7, {0}, {0}, {0}, {0}]
checking 1-9 in [9, {0}, 1, 2, {0}, {0}, 3, {0}, {0}]
checking 1-9 in [{0}, {0}, {0}, {0}, 4, 9, 1, 5, 7]
checking 1-9 in [{0}, 1, 3, {0}, 5, {0}, 9, 2, {0}]
checking 1-9 in [5, 7, 9, 1, 2, {0}, {0}, {0}, {0}]
checking 1-9 in [{0}, {0}, 7, {0}, {0}, 2, 6, {0}, 3]
checking 1-9 in [{0}, {0}, {0}, {0}, 3, 8, 2, {0}, 5]
checking 1-9 in [{0}, 2, {0}, 5, {0}, {0}, {0}, {0}, {0}]
checking 1-9 in [{0}, 8, 9, {0}, {0}, 5, {0}, {0}, {0}]
checking 1-9 in [{0}, {0}, {0}, {0}, 1, 7, {0}, {0}, 2]
checking 1-9 in [{0}, 2, 1, {0}, 3, 9, 7, {0}, {0}]
checking 1-9 in [{0}, 9, 2, {0}, {0}, 1, {0}, {0}, 5]
checking 1-9 in [{0}, 7, {0}, 4, 5, 2, {0}, 3, {0}]
checking 1-9 in [4, {0}, {0}, 9, {0}, {0}, 2, 8, {0}]
checking 1-9 in [{0}, {0}, 3, 1, 9, {0}, 6, 2, {0}]
checking 1-9 in [9, {0}, {0}, 5, 2, {0}, {0}, {0}, {0}]
checking 1-9 in [{0}, {0}, {0}, 7, {0}, {0}, 3, 5, {0}]
Solution hash: 5304291476511456775031793516212605969817732867735002414672557856863058671935
*** Trying to read pysnark_ek
*** PySNARK: generating proof pysnark_log (sat=False, #io=1, #witness=1229, #constraint=1473)
Assertion failed: cs.is_satisfied(primary_input, auxiliary_input), file c:/msys64/mingw64/include/libsnark/reductions/r1cs_to_qap/r1cs_to_qap.tcc, line 216```

Question : Verify commitment files generated by qaptools

Hello,
I am using using the qaptools backend, and I am generating commitments using gencomm.
Let's say I use it on a piece of data that I call test, so this will output the two files pysnark_wires_test and pysnark_comm_test, besides the key material.
Is there a built-in function in the library that allows to check whether pysnark_comm_test is a valid commitment to pysnark_wires_test ?
Thank you in advance for your answer !

What is cube.py proving?

Hi, I am new to ZKP, and I am just trying to understand what the examples are proving. I looked at public.json for cube.py, and the output contains both x and x^3, so what is this example proving?

Got error when run "PYSNARK_BACKEND=libsnarkgg python cube.py 3"

Hi,
I use git bash for Windows and want to run this example for Groth16 scheme. But I got the following error message when I run "rm pysnark_*" and then run "PYSNARK_BACKEND=libsnarkgg python cube.py 3":

The cube of 3 is 27
Assertion failed: !qap_wit.coefficients_for_H[qap_wit.degree()-2].is_zero(), file c:/msys64/mingw64/include/libsnark/zk_proof_systems/ppzksnark/r1cs_gg_ppzksnark/r1cs_gg_ppzksnark.tcc, line 418

I have no idea about how to fix this problem.
In addition, is there any tutorial to teach us use pysnark? I want to build a PyCharm project but have no idea how to integrate pysnark with my project.
Thanks a lot!

Trusted setup?

I'm wondering how trusted setup works in PySNARK.

When I output a proof, say in Bellman with zkinterface, it outputs both the constraints and the witness. Does that mean that the setup is done by the prover and there is no external trusted setup?

Add project to pypi?

Putting this on pypi would make installation more convenient, have you considered it?

Thanks for your time.

New zkInterface output violates spec

Hey Meilof,

Not sure if you saw the comment I made since it was buried, but since the zkInterface fix adding trusted setup the zkInterface outputs haven't been correct.

Here's what I'm getting when validating computation.zkif.

PYSNARK_BACKEND=zkinterface python3 cube.py 33
rm circuit.zkif
zkif validate

The statement is NOT COMPLIANT with the specification!
Violations:
- variable_0 was defined but not used.

Error: "Found 1 violations."

Validating only circuit.zkif I get 344 violations.
Validating both I get 4 violations.

Any ideas?

ggh_hash crashes if array starts with int and has LinCombs

The following works fine:

from pysnark.hash import ggh_hash
from pysnark.runtime import PrivVal
ggh_hash([PrivVal(2), 2])

But this crashes:

from pysnark.hash import ggh_hash
from pysnark.runtime import PrivVal
ggh_hash([2, PrivVal(2)])

Seems like if the array contains LinCombs it should be handled in ggh_hash_nonplain?

if_then_else evaluates all branches of the if statement

I'm having an issue with if_then_else where branches are evaluated even when the branch isn't entered.
Here's an example:

from pysnark.runtime import PrivVal
from pysnark.branching import if_then_else
if_then_else(PrivVal(0), PrivVal(1) / PrivVal(0), PrivVal(0))

The division shouldn't be entered but it's evaluated anyway, causing a ZeroDivisionError.

Am I using if_then_else incorrectly? If this is a bug, I suspect this is the cause https://github.com/meilof/pysnark/blob/master/pysnark/branching.py#L11

Mod operator

Any reason why the mod operator isn't implemented?

Floating point comparisons

When I try to compare fixed point values like in the following code:

from pysnark.fixedpoint import PrivValFxp
PrivValFxp(1.0) >= PrivValFxp(2.0)

whenever the comparison evaluates to False I get an error:

ValueError: constraint did not hold

This seems to happen for all comparison operators other than == and != and only when the result is False. The comparisons work fine for regular integer PrivVals.

Any ideas why this is happening?

Allow negative floats in division

Hi,
we used pysnark to test some of our algorithms. We made heavy use of negative floats, which resulted in an AssertionError.

We believe, there is a bug in runtime.py:

LinComb.__divmod__ currently reads:

    def __divmod__(self, divisor):
        """
        Divides a LinComb with an integer or another LinComb and returns the quotient and the remainder
        Costs 2 * bitlength + 4 constraints to divide
        """
        if isinstance(divisor, int):
            divisor = ConstVal(divisor)

        if isinstance(divisor, LinComb):
            if divisor.value == 0:
                raise ValueError("Division by zero")
            quo = PrivVal(self.value // divisor.value)
            res = quo * divisor
            rem = PrivVal(self.value - res.value)

            add_constraint(quo, divisor, self - rem)
            rem.assert_lt(divisor)
            quo.assert_positive()
            return (quo,rem)

        return NotImplemented

and it should read:

    def __divmod__(self, divisor):
        """
        Divides a LinComb with an integer or another LinComb and returns the quotient and the remainder
        Costs 2 * bitlength + 4 constraints to divide
        """
        if isinstance(divisor, int):
            divisor = ConstVal(divisor)

        if isinstance(divisor, LinComb):
            if divisor.value == 0:
                raise ValueError("Division by zero")
            quo = PrivVal(self.value // divisor.value)
            res = quo * divisor
            rem = PrivVal(self.value - res.value)

            add_constraint(quo, divisor, self - rem)
            rem.assert_lt(divisor)
            rem.assert_positive()
            return (quo,rem)

        return NotImplemented

(rem must be positive instead of quo)
Do you concur?

Integer division

Would it be possible for divisions like

PrivVal(2) / PrivVal(3)

to return a LinCombFxp rather than throwing a ValueError?

Problem in using zkinterface on Windows

After setting environment path " set PYSNARK_BACKEND=zkinterface" and then run "python cube.py 33 ", it always use the libsnark, rather than "zkinterface"
image

Qapver Error

I successfully compiled qaptools and python-libsnark and installed pysnark. However, i can't seem to verify the snark (And i'm not sure it's producing all the files it should)

atrask-macbookpro3:examples atrask$ python cube.py 3
The cube of 3 is 27
*** Trying to read pysnark_ek
*** PySNARK: generating proof pysnark_log (sat=True, #io=2, #witness=2, #constraint=3)
*** Public inputs: 3 27
*** Verification status: True
atrask-macbookpro3:examples atrask$ python -m pysnark.qaptools.runqapver
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pysnark/qaptools/runqapver.py", line 60, in <module>
    run()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pysnark/qaptools/runqapver.py", line 55, in run
    raise RuntimeError("qapver failed")
RuntimeError: qapver failed
atrask-macbookpro3:examples atrask$ ls
bench.py			cs2				kaplanmeier.py			snarkprofile.py
binarycircuit.py		cube-qaptools.py		manysquares.py			sudoku.py
binarycircuit_example.txt	cube.py				pysnark_ek			test.py
branch2.py			cube_json.py			pysnark_log			test2.py
compare.py			factorial.py			pysnark_vk			testarray.py
cs				index.html			secretsanta.py			testcomm.py
atrask-macbookpro3:examples atrask$ 

NameError 'gmpy' is not defined

I tried to run some examples with qaptools as backend, and it comes the error.
"NameError: name 'gmpy' is not defined"
Then I edited the function at backend.py.
"def fieldinverse(val):
#return int(gmpy.invert(val, vc_p))
return int(pysnark.gmpy.invert(val,vc_p))"
And it works fine.

Implementing Exponentiation

Is it possible to take powers of a hidden variable, e.g. PrivVal(2) ** PrivVal(3)?
To me it seems like this operation will always leak its exponent, since we could find its value by seeing how many multiplications were done.

TypeError: EndVector() takes 1 positional argument but 2 were given

hello , i use the "To generate a zkif file for the zkinterface bulletproofs backend and use it:" when i input the command "PYSNARK_BACKEND=zkifbulletproofs python3 cube.py 33",i encountered the following problem:

(newpysnark36) ➜  examples git:(master) PYSNARK_BACKEND=zkifbulletproofs python3 cube.py 33
The cube of 33 is 35937
*** zkinterface: writing circuit
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File "/Users/liuhuan/opt/anaconda3/envs/newpysnark36/lib/python3.6/site-packages/pysnark/atexitmaybe.py", line 57, in maybe_
    fn()
  File "/Users/liuhuan/opt/anaconda3/envs/newpysnark36/lib/python3.6/site-packages/pysnark/runtime.py", line 688, in final
    if autoprove: backend.prove()
  File "/Users/liuhuan/opt/anaconda3/envs/newpysnark36/lib/python3.6/site-packages/pysnark/zkinterface/backend.py", line 104, in prove
    vars = write_varlist(builder, pubvals, 1)
  File "/Users/liuhuan/opt/anaconda3/envs/newpysnark36/lib/python3.6/site-packages/pysnark/zkinterface/backend.py", line 78, in write_varlist
    ixs = builder.EndVector(len(vals))
TypeError: EndVector() takes 1 positional argument but 2 were given 

how do i solve it

Example For Hash String Fails To Work

Hello,

I am trying to use the hash_string.py example you gave. It raises the following error

AssertionError: 21888242871839275222246405745257275088548364400416034343698204186575808495616 is not a 16-bit positive integer

from the line:

hashed = ggh_hash(packer.pack(witness))

bench.py fails

Thanks for PySNARK !

Can't run bench.py out of the box:

➜  examples git:(master) git rev-parse HEAD
607094fa73c151a123a4c82eb92a8802d3ee38b7

➜  examples git:(master) python --version      
Python 3.9.1

➜  examples git:(master) pip show pysnark                                                 
Name: PySNARK
Version: 0.3.1
Summary: Python zk-SNARK execution environment
Home-page: https://github.com/meilof/pysnark
Location: /.local/lib/python3.9/site-packages

➜  examples git:(master) python cube.py 3
The cube of 3 is 27
*** Trying to read pysnark_ek
*** PySNARK: generating proof pysnark_log (sat=True, #io=2, #witness=2, #constraint=3)
*** Public inputs: 3 27
*** Verification status: True

➜  examples git:(master) python bench.py 
Traceback (most recent call last):
  File "/devenv/crypto/zk/meilof/pysnark/examples/bench.py", line 67, in <module>
    print("<, <=, >, >=              ", several([benchmark_lin_bl(lambda:LinComb.ZERO<LinComb.ZERO),
  File "/devenv/crypto/zk/meilof/pysnark/examples/bench.py", line 50, in benchmark_lin_bl
    op4 = count_ops(guarded(LinComb.ONE)(fn))
  File "/devenv/crypto/zk/meilof/pysnark/examples/bench.py", line 15, in count_ops
    benchmark(callback)(fn)()
  File "/.local/lib/python3.9/site-packages/pysnark/runtime.py", line 81, in __benchmark
    ret = fn(*args, **kwargs)
  File "/.local/lib/python3.9/site-packages/pysnark/runtime.py", line 128, in __guarded
    bak = enable_guard(cond)
NameError: name 'enable_guard' is not defined
*** Script returned with error, skipping proof generation

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.