├── scripts ├── eth_addr │ ├── input_eth_addr.json │ ├── eth_addr.circom │ └── build_eth_addr.sh ├── pubkeygen │ ├── input_pubkeygen.json │ ├── pubkeygen.circom │ └── build_pubkeygen.sh ├── groupsig │ ├── input_groupsig.json │ ├── groupsig.circom │ └── build_groupsig.sh ├── verify │ ├── verify.circom │ ├── input_verify.json │ └── build_verify.sh ├── compute_dummy_point.py ├── compute_offsets.py ├── get_params_long.py ├── compute_secp256k1_math.py ├── compute_p256_math.py ├── groupsign_cli.js └── groupsign_cli.ts ├── .vscode ├── extensions.json └── settings.json ├── .gitignore ├── .gitmodules ├── scratch ├── build_86_3 │ └── dummy_point │ │ ├── witness.wtns │ │ ├── dummy_point.r1cs │ │ ├── dummy_point.zkey │ │ ├── dummy_point_0.zkey │ │ ├── dummy_point_1.zkey │ │ ├── dummy_point_cpp │ │ ├── dummy_point.dat │ │ ├── Makefile │ │ ├── calcwit.hpp │ │ ├── circom.hpp │ │ ├── calcwit.cpp │ │ ├── fr.hpp │ │ ├── fr.cpp │ │ └── main.cpp │ │ ├── dummy_point_js │ │ ├── dummy_point.wasm │ │ ├── generate_witness.js │ │ └── witness_calculator.js │ │ ├── proof.json │ │ ├── public.json │ │ └── dummy_point.sym ├── dummy_point │ ├── input_86_3_dummy_point.json │ ├── input_dummy_point.json │ ├── dummy_point.circom │ └── build_dummy_point.sh ├── dummy_point.circom ├── text_scratch.txt ├── tracing_point_scratch.py └── scratch.py ├── test ├── circuits_p256 │ ├── test_p256_double.circom │ ├── test_ecdsa.circom │ ├── test_p256_add.circom │ ├── test_p256_scalarmult.circom │ ├── test_ecdsa_verify.circom │ ├── test_pairing_add.circom │ └── test_p256_poc.circom ├── ecdsa.test.ts └── p256.test.ts ├── tsconfig.json ├── .prettierrc ├── script_outputs ├── dummy_point_out.circom ├── p256_params_long.circom └── offsets_out.circom ├── circuits ├── eth_addr.circom ├── p256.circom ├── p256_func.circom ├── ecdsa.circom └── p256_utils.circom ├── package.json ├── README.md └── LICENSE /scripts/eth_addr/input_eth_addr.json: -------------------------------------------------------------------------------- 1 | {"privkey": ["7", "0", "0", "0"]} 2 | -------------------------------------------------------------------------------- /scripts/pubkeygen/input_pubkeygen.json: -------------------------------------------------------------------------------- 1 | {"privkey": ["0", "7", "6", "2", "1", "1"]} -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "iden3.circom" 4 | ] 5 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | node_modules/ 3 | pot*.ptau 4 | __pycache__ 5 | .DS_Store 6 | # scratch/ 7 | 8 | *.swp 9 | *~ 10 | INTERNAL.md -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "circuits/circom-pairing"] 2 | path = circuits/circom-pairing 3 | url = git@github.com:SleepingShell/circom-pairing.git -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/witness.wtns: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/privacy-scaling-explorations/circom-ecdsa-p256/HEAD/scratch/build_86_3/dummy_point/witness.wtns -------------------------------------------------------------------------------- /test/circuits_p256/test_p256_double.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../circuits/p256.circom"; 4 | 5 | component main {public [in]} = P256Double(43, 6); 6 | -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point.r1cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/privacy-scaling-explorations/circom-ecdsa-p256/HEAD/scratch/build_86_3/dummy_point/dummy_point.r1cs -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point.zkey: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/privacy-scaling-explorations/circom-ecdsa-p256/HEAD/scratch/build_86_3/dummy_point/dummy_point.zkey -------------------------------------------------------------------------------- /scripts/pubkeygen/pubkeygen.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../circuits/ecdsa.circom"; 4 | 5 | component main {public [privkey]} = ECDSAPrivToPub(43, 6); 6 | -------------------------------------------------------------------------------- /test/circuits_p256/test_ecdsa.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../circuits/ecdsa.circom"; 4 | 5 | component main {public [privkey]} = ECDSAPrivToPub(43, 6); 6 | -------------------------------------------------------------------------------- /test/circuits_p256/test_p256_add.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../circuits/p256.circom"; 4 | 5 | component main {public [a, b]} = P256AddUnequal(43, 6); 6 | -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_0.zkey: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/privacy-scaling-explorations/circom-ecdsa-p256/HEAD/scratch/build_86_3/dummy_point/dummy_point_0.zkey -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_1.zkey: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/privacy-scaling-explorations/circom-ecdsa-p256/HEAD/scratch/build_86_3/dummy_point/dummy_point_1.zkey -------------------------------------------------------------------------------- /scripts/groupsig/input_groupsig.json: -------------------------------------------------------------------------------- 1 | {"privkey": ["7", "0", "0", "0"], "addr1": "50", "addr2": "1210930943336347771396396330116102456817544228795", "addr3": "51", "msg": "42"} 2 | -------------------------------------------------------------------------------- /scripts/verify/verify.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../circuits/ecdsa.circom"; 4 | 5 | component main {public [r, s, msghash, pubkey]} = ECDSAVerifyNoPubkeyCheck(43, 6); 6 | -------------------------------------------------------------------------------- /test/circuits_p256/test_p256_scalarmult.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../circuits/p256.circom"; 4 | 5 | component main {public [scalar, point]} = P256ScalarMult(43, 6); 6 | -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_cpp/dummy_point.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/privacy-scaling-explorations/circom-ecdsa-p256/HEAD/scratch/build_86_3/dummy_point/dummy_point_cpp/dummy_point.dat -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_js/dummy_point.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/privacy-scaling-explorations/circom-ecdsa-p256/HEAD/scratch/build_86_3/dummy_point/dummy_point_js/dummy_point.wasm -------------------------------------------------------------------------------- /test/circuits_p256/test_ecdsa_verify.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../circuits/ecdsa.circom"; 4 | 5 | component main {public [r, s, msghash, pubkey]} = ECDSAVerifyNoPubkeyCheck(43, 6); 6 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "python.analysis.extraPaths": ["./scripts"], 3 | "[python]": { 4 | "editor.defaultFormatter": "ms-python.black-formatter" 5 | }, 6 | "python.formatting.provider": "none" 7 | } 8 | -------------------------------------------------------------------------------- /test/circuits_p256/test_pairing_add.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../circuits/circom-pairing/circuits/curve.circom"; 4 | 5 | component main = EllipticCurveAddUnequal(43,6,[8796093022207,8796093022207,1023,0,1048576,2199023255040]); 6 | -------------------------------------------------------------------------------- /scratch/dummy_point/input_86_3_dummy_point.json: -------------------------------------------------------------------------------- 1 | { 2 | "G": [ 3 | ["52227620040540588600771222", "33347259622618539004134583", "8091721874918813684698062"], 4 | ["59685082318776612195095029", "54599710628478995760242092", "6036146923926000695307902"] 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /scratch/dummy_point/input_dummy_point.json: -------------------------------------------------------------------------------- 1 | { 2 | "G": [ 3 | ["17627433388654248598", "8575836109218198432", "17923454489921339634", "7716867327612699207"], 4 | ["14678990851816772085", "3156516839386865358", "10297457778147434006", "5756518291402817435"] 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /scripts/eth_addr/eth_addr.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../node_modules/circomlib/circuits/mimcsponge.circom"; 4 | include "../../node_modules/circomlib/circuits/bitify.circom"; 5 | include "../../circuits/eth_addr.circom"; 6 | 7 | component main {public [privkey]} = PrivKeyToAddr(64, 4); 8 | -------------------------------------------------------------------------------- /scratch/dummy_point/dummy_point.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.0.2; 2 | 3 | include "../../node_modules/circomlib/circuits/mimcsponge.circom"; 4 | include "../../node_modules/circomlib/circuits/bitify.circom"; 5 | include "../../circuits/dummy_point.circom"; 6 | 7 | component main = dummy_point(86, 3); 8 | // component main = dummy_point(64, 4); 9 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | // Visit https://aka.ms/tsconfig.json for all config options 2 | { 3 | "compilerOptions": { 4 | "target": "ES2020", 5 | "module": "commonjs", 6 | "strict": true, 7 | "resolveJsonModule": true, 8 | "esModuleInterop": true, 9 | "skipLibCheck": true, 10 | "forceConsistentCasingInFileNames": true 11 | }, 12 | "include": ["./scripts", "./test"] 13 | } -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "jsxSingleQuote": true, 4 | "trailingComma": "es5", 5 | "tabWidth": 2, 6 | "semi": true, 7 | "bracketSpacing": true, 8 | "printWidth": 100, 9 | "overrides": [ 10 | { 11 | "files": "*.sol", 12 | "options": { 13 | "tabWidth": 4, 14 | "useTabs": false, 15 | "singleQuote": false, 16 | "bracketSpacing": false, 17 | "explicitTypes": "always" 18 | } 19 | } 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /script_outputs/dummy_point_out.circom: -------------------------------------------------------------------------------- 1 | (n,k) = (64, 4) 2 | 2^255 * Gx = [13055350994670398292, 5692045669299725136, 5793574232182301884, 8624967855033230099] 3 | 2^255 * Gy = [14602923977195939839, 16096495783772217585, 17848059978913647218, 11807357506748851191] 4 | 5 | (n,k) = (86, 3) 6 | 2^255 * Gx = [49732730225977125179960148, 43852565336912664664048527, 9043934293559324284618350] 7 | 2^255 * Gy = [20405083474242608521046015, 57969189420107975911442337, 12380911704996683387468560] 8 | 9 | 10 | -------------------------------------------------------------------------------- /test/circuits_p256/test_p256_poc.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../circuits/circom-pairing/circuits/curve.circom"; 4 | include "../../circuits/p256_func.circom"; 5 | 6 | template TestP256PointOnCurve(n,k) { 7 | signal input x[k]; 8 | signal input y[k]; 9 | 10 | var params[4][k] = get_p256_params(); 11 | 12 | component poc = PointOnCurve(n, k, params[0], params[1], params[2]); 13 | poc.in[0] <== x; 14 | poc.in[1] <== y; 15 | } 16 | component main {public [x, y]} = TestP256PointOnCurve(43, 6); 17 | -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_cpp/Makefile: -------------------------------------------------------------------------------- 1 | CC=g++ 2 | CFLAGS=-std=c++11 -O3 -I. 3 | DEPS_HPP = circom.hpp calcwit.hpp fr.hpp 4 | DEPS_O = main.o calcwit.o fr.o fr_asm.o 5 | 6 | ifeq ($(shell uname),Darwin) 7 | NASM=nasm -fmacho64 --prefix _ 8 | endif 9 | ifeq ($(shell uname),Linux) 10 | NASM=nasm -felf64 11 | endif 12 | 13 | all: dummy_point 14 | 15 | %.o: %.cpp $(DEPS_HPP) 16 | $(CC) -c $< $(CFLAGS) 17 | 18 | fr_asm.o: fr.asm 19 | $(NASM) fr.asm -o fr_asm.o 20 | 21 | dummy_point: $(DEPS_O) dummy_point.o 22 | $(CC) -o dummy_point *.o -lgmp 23 | -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_js/generate_witness.js: -------------------------------------------------------------------------------- 1 | const wc = require("./witness_calculator.js"); 2 | const { readFileSync, writeFile } = require("fs"); 3 | 4 | if (process.argv.length != 5) { 5 | console.log("Usage: node generate_witness.js "); 6 | } else { 7 | const input = JSON.parse(readFileSync(process.argv[3], "utf8")); 8 | 9 | const buffer = readFileSync(process.argv[2]); 10 | wc(buffer).then(async witnessCalculator => { 11 | // const w= await witnessCalculator.calculateWitness(input,0); 12 | // for (let i=0; i< w.length; i++){ 13 | // console.log(w[i]); 14 | // } 15 | const buff= await witnessCalculator.calculateWTNSBin(input,0); 16 | writeFile(process.argv[4], buff, function(err) { 17 | if (err) throw err; 18 | }); 19 | }); 20 | } 21 | -------------------------------------------------------------------------------- /scripts/compute_dummy_point.py: -------------------------------------------------------------------------------- 1 | import compute_p256_math 2 | import math 3 | import sys 4 | 5 | tmpGx = compute_p256_math.Gx 6 | tmpGy = compute_p256_math.Gy 7 | for i in range(255): 8 | tmpGx, tmpGy = compute_p256_math.double(tmpGx, tmpGy) 9 | 10 | Gx_255 = tmpGx 11 | Gy_255 = tmpGy 12 | 13 | return_str = "" 14 | for (n,k) in {(64,4), (86,3)}: 15 | return_str += "(n,k) = " + str((n,k)) + "\n" 16 | Gx_255_long = compute_p256_math.get_long(n, k, Gx_255) 17 | Gy_255_long = compute_p256_math.get_long(n, k, Gy_255) 18 | return_str += "2^255 * Gx = " + str(Gx_255_long) + "\n" 19 | return_str += "2^255 * Gy = " + str(Gy_255_long) + "\n" 20 | return_str += "\n" 21 | 22 | orig_stdout = sys.stdout 23 | f = open('../script_outputs/dummy_point_out.circom', 'w') 24 | sys.stdout = f 25 | 26 | print(return_str) 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /circuits/eth_addr.circom: -------------------------------------------------------------------------------- 1 | // DONE FILE 2 | 3 | pragma circom 2.1.5; 4 | 5 | include "./zk-identity/eth.circom"; 6 | include "./ecdsa.circom"; 7 | 8 | // n, k = 64, 4 9 | 10 | template PrivKeyToAddr(n, k) { 11 | signal input privkey[k]; 12 | signal output addr; 13 | 14 | component privToPub = ECDSAPrivToPub(n, k); 15 | for (var i = 0; i < k; i++) { 16 | privToPub.privkey[i] <== privkey[i]; 17 | } 18 | 19 | component flattenPub = FlattenPubkey(n, k); 20 | for (var i = 0; i < k; i++) { 21 | flattenPub.chunkedPubkey[0][i] <== privToPub.pubkey[0][i]; 22 | flattenPub.chunkedPubkey[1][i] <== privToPub.pubkey[1][i]; 23 | } 24 | 25 | component pubToAddr = PubkeyToAddress(); 26 | for (var i = 0; i < 512; i++) { 27 | pubToAddr.pubkeyBits[i] <== flattenPub.pubkeyBits[i]; 28 | } 29 | 30 | addr <== pubToAddr.address; 31 | } -------------------------------------------------------------------------------- /scripts/verify/input_verify.json: -------------------------------------------------------------------------------- 1 | { 2 | "r": [ 3 | "4356595461396", 4 | "7517478021216", 5 | "461130717732", 6 | "582422961751", 7 | "4827585151075", 8 | "1832639904957" 9 | ], 10 | "s": [ 11 | "491010621745", 12 | "1153769202424", 13 | "7481879050338", 14 | "2362326744248", 15 | "5715790716735", 16 | "1133501322735" 17 | ], 18 | "msghash": [ 19 | "1234", 20 | "0", 21 | "0", 22 | "0", 23 | "0", 24 | "0" 25 | ], 26 | "pubkey": [ 27 | [ 28 | "4705934152392", 29 | "8704141833119", 30 | "4827796658582", 31 | "5154602932886", 32 | "6957561507837", 33 | "974696539144" 34 | ], 35 | [ 36 | "8600645394507", 37 | "418369241838", 38 | "1959034348828", 39 | "6964301761725", 40 | "1750427296885", 41 | "1782063459524" 42 | ] 43 | ] 44 | } -------------------------------------------------------------------------------- /scripts/compute_offsets.py: -------------------------------------------------------------------------------- 1 | import compute_p256_math 2 | import math 3 | import sys 4 | 5 | return_str = "" 6 | 7 | 8 | def offsets(num_registers, n, k): 9 | return_str = "PrimeReduce" + str(num_registers) + "Registers: \n" 10 | matrix = [] 11 | for idx in range(num_registers): 12 | coeff = 2**(64*idx) % compute_p256_math.P 13 | long_coeff = compute_p256_math.get_long(n, k, coeff) 14 | matrix.append(long_coeff) 15 | return_str += "in[" + str(idx) + "], coeffs = " + \ 16 | str(long_coeff) + '\n' 17 | return_str += "\n" 18 | return_str += "matrix of coefficients = " + str(matrix) + "\n" + "\n" 19 | 20 | return return_str 21 | 22 | 23 | return_str += offsets(7, 64, 4) + offsets(10, 32, 8) 24 | 25 | orig_stdout = sys.stdout 26 | f = open('../script_outputs/offsets_out.circom', 'w') 27 | sys.stdout = f 28 | 29 | print(return_str) 30 | -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/proof.json: -------------------------------------------------------------------------------- 1 | { 2 | "pi_a": [ 3 | "14586010887018960833064990026432949506273468899225574397417781356048083681453", 4 | "1863592600439053200772808499996651017324950106112099403985206425736341791433", 5 | "1" 6 | ], 7 | "pi_b": [ 8 | [ 9 | "21109153537344805813330823056616519840399863268463258221474725737628766363947", 10 | "15065531990981394398788101388444726742812029134328633151390915350018211206077" 11 | ], 12 | [ 13 | "10884661685521563201861444377596047510115287403487019846417745887992827069248", 14 | "13596837068568294703481585949285139140984735055588649929598861970385910919830" 15 | ], 16 | [ 17 | "1", 18 | "0" 19 | ] 20 | ], 21 | "pi_c": [ 22 | "10960245403232778809310364027424633337040906511735032072610398409774169599492", 23 | "15329420804050057163216970453303145560115517354303062709508214056334506429915", 24 | "1" 25 | ], 26 | "protocol": "groth16", 27 | "curve": "bn128" 28 | } -------------------------------------------------------------------------------- /scratch/dummy_point.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.0.2; 2 | 3 | include "p256_func.circom"; 4 | include "bigint.circom"; 5 | include "bigint_func.circom"; 6 | 7 | template dummy_point(n, k) { 8 | signal input G[2][k]; 9 | signal dummy; 10 | signal output out[2][100]; 11 | 12 | var g1[k]; 13 | var g2[k]; 14 | dummy <== G[0][0] * G[0][0] + G[0][0]; 15 | 16 | for (var i=0; i", 16 | "license": "ISC", 17 | "dependencies": { 18 | "@noble/curves": "^0.9.1", 19 | "circomlib": "^2.0.5", 20 | "circom_tester": "^0.0.19", 21 | "ethers": "^5.5.2", 22 | "snarkjs": "^0.7.2" 23 | }, 24 | "devDependencies": { 25 | "@noble/secp256k1": "1.3.4", 26 | "@types/chai": "^4.3.0", 27 | "@types/expect": "^24.3.0", 28 | "@types/mocha": "^9.0.0", 29 | "chai": "^4.3.4", 30 | "mocha": "^9.1.3", 31 | "ts-node": "^10.4.0", 32 | "typescript": "^4.5.4" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /script_outputs/p256_params_long.circom: -------------------------------------------------------------------------------- 1 | (n, k) = (86, 3) 2 | P = [77371252455336267181195263, 1023, 19342813109330467168976896] 3 | N = [28553880287938765337601361, 77371252455335114450843292, 19342813109330467168976895] 4 | A = [77371252455336267181195260, 1023, 19342813109330467168976896] 5 | B = [23805269282153275520606283, 64478498050055519801623345, 6858709101169761702330043] 6 | Gx = [52227620040540588600771222, 33347259622618539004134583, 8091721874918813684698062] 7 | Gy = [59685082318776612195095029, 54599710628478995760242092, 6036146923926000695307902] 8 | 9 | (n, k) = (64, 4) 10 | P = [18446744073709551615, 4294967295, 0, 18446744069414584321] 11 | N = [17562291160714782033, 13611842547513532036, 18446744073709551615, 18446744069414584320] 12 | A = [18446744073709551612, 4294967295, 0, 18446744069414584321] 13 | B = [4309448131093880907, 7285987128567378166, 12964664127075681980, 6540974713487397863] 14 | Gx = [17627433388654248598, 8575836109218198432, 17923454489921339634, 7716867327612699207] 15 | Gy = [14678990851816772085, 3156516839386865358, 10297457778147434006, 5756518291402817435] 16 | 17 | (n, k) = (32, 8) 18 | P = [4294967295, 4294967295, 4294967295, 0, 0, 0, 1, 4294967295] 19 | N = [4234356049, 4089039554, 2803342980, 3169254061, 4294967295, 4294967295, 0, 4294967295] 20 | A = [4294967292, 4294967295, 4294967295, 0, 0, 0, 1, 4294967295] 21 | B = [668098635, 1003371582, 3428036854, 1696401072, 1989707452, 3018571093, 2855965671, 1522939352] 22 | Gx = [3633889942, 4104206661, 770388896, 1996717441, 1671708914, 4173129445, 3777774151, 1796723186] 23 | Gy = [935285237, 3417718888, 1798397646, 734933847, 2081398294, 2397563722, 4263149467, 1340293858] -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_cpp/calcwit.hpp: -------------------------------------------------------------------------------- 1 | #ifndef CIRCOM_CALCWIT_H 2 | #define CIRCOM_CALCWIT_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "circom.hpp" 11 | #include "fr.hpp" 12 | 13 | #define NMUTEXES 12 //512 14 | 15 | u64 fnv1a(std::string s); 16 | 17 | class Circom_CalcWit { 18 | 19 | bool *inputSignalAssigned; 20 | uint inputSignalAssignedCounter; 21 | 22 | Circom_Circuit *circuit; 23 | 24 | public: 25 | 26 | FrElement *signalValues; 27 | Circom_Component* componentMemory; 28 | FrElement* circuitConstants; 29 | std::map templateInsId2IOSignalInfo; 30 | std::string* listOfTemplateMessages; 31 | 32 | // parallelism 33 | std::mutex numThreadMutex; 34 | std::condition_variable ntcvs; 35 | uint numThread; 36 | 37 | uint maxThread; 38 | 39 | // Functions called by the circuit 40 | Circom_CalcWit(Circom_Circuit *aCircuit, uint numTh = NMUTEXES); 41 | ~Circom_CalcWit(); 42 | 43 | // Public functions 44 | void setInputSignal(u64 h, uint i, FrElement &val); 45 | void tryRunCircuit(); 46 | 47 | u64 getInputSignalSize(u64 h); 48 | 49 | inline uint getRemaingInputsToBeSet() { 50 | return inputSignalAssignedCounter; 51 | } 52 | 53 | inline void getWitness(uint idx, PFrElement val) { 54 | Fr_copy(val, &signalValues[circuit->witness2SignalList[idx]]); 55 | } 56 | 57 | std::string getTrace(u64 id_cmp); 58 | 59 | std::string generate_position_array(uint* dimensions, uint size_dimensions, uint index); 60 | 61 | private: 62 | 63 | uint getInputSignalHashPosition(u64 h); 64 | 65 | }; 66 | 67 | typedef void (*Circom_TemplateFunction)(uint __cIdx, Circom_CalcWit* __ctx); 68 | 69 | #endif // CIRCOM_CALCWIT_H 70 | -------------------------------------------------------------------------------- /script_outputs/offsets_out.circom: -------------------------------------------------------------------------------- 1 | PrimeReduce7Registers: 2 | in[0], coeffs = [1, 0, 0, 0] 3 | in[1], coeffs = [0, 1, 0, 0] 4 | in[2], coeffs = [0, 0, 1, 0] 5 | in[3], coeffs = [0, 0, 0, 1] 6 | in[4], coeffs = [1, 18446744069414584320, 18446744073709551615, 4294967294] 7 | in[5], coeffs = [4294967295, 4294967297, 18446744069414584319, 18446744065119617024] 8 | in[6], coeffs = [18446744069414584318, 12884901887, 2, 18446744065119617025] 9 | 10 | matrix of coefficients = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 18446744069414584320, 18446744073709551615, 4294967294], [4294967295, 4294967297, 18446744069414584319, 18446744065119617024], [18446744069414584318, 12884901887, 2, 18446744065119617025]] 11 | 12 | PrimeReduce10Registers: 13 | in[0], coeffs = [1, 0, 0, 0, 0, 0, 0, 0] 14 | in[1], coeffs = [0, 0, 1, 0, 0, 0, 0, 0] 15 | in[2], coeffs = [0, 0, 0, 0, 1, 0, 0, 0] 16 | in[3], coeffs = [0, 0, 0, 0, 0, 0, 1, 0] 17 | in[4], coeffs = [1, 0, 0, 4294967295, 4294967295, 4294967295, 4294967294, 0] 18 | in[5], coeffs = [4294967295, 0, 1, 1, 4294967295, 4294967294, 0, 4294967294] 19 | in[6], coeffs = [4294967294, 4294967294, 4294967295, 2, 2, 0, 1, 4294967294] 20 | in[7], coeffs = [4294967295, 4294967294, 4294967294, 4294967295, 0, 2, 3, 0] 21 | in[8], coeffs = [3, 0, 4294967295, 4294967291, 4294967294, 4294967295, 4294967293, 4] 22 | in[9], coeffs = [2, 5, 3, 4294967294, 4294967289, 4294967291, 4294967292, 4294967292] 23 | 24 | matrix of coefficients = [[1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 4294967295, 4294967295, 4294967295, 4294967294, 0], [4294967295, 0, 1, 1, 4294967295, 4294967294, 0, 4294967294], [4294967294, 4294967294, 4294967295, 2, 2, 0, 1, 4294967294], [4294967295, 4294967294, 4294967294, 4294967295, 0, 2, 3, 0], [3, 0, 4294967295, 4294967291, 4294967294, 4294967295, 4294967293, 4], [2, 5, 3, 4294967294, 4294967289, 4294967291, 4294967292, 4294967292]] 25 | 26 | 27 | -------------------------------------------------------------------------------- /scripts/groupsig/groupsig.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "../../node_modules/circomlib/circuits/mimcsponge.circom"; 4 | include "../../node_modules/circomlib/circuits/bitify.circom"; 5 | include "../../circuits/eth_addr.circom"; 6 | 7 | /* 8 | Inputs: 9 | - addr1 (pub) 10 | - addr2 (pub) 11 | - addr3 (pub) 12 | - msg (pub) 13 | - privkey 14 | 15 | Intermediate values: 16 | - myAddr (supposed to be addr of privkey) 17 | 18 | Output: 19 | - msgAttestation 20 | 21 | Prove: 22 | - PrivKeyToAddr(privkey) == myAddr 23 | - (x - addr1)(x - addr2)(x - addr3) == 0 24 | - msgAttestation == mimc(msg, privkey) 25 | */ 26 | 27 | template Main(n, k) { 28 | assert(n * k >= 256); 29 | assert(n * (k-1) < 256); 30 | 31 | signal input privkey[k]; 32 | signal input addr1; 33 | signal input addr2; 34 | signal input addr3; 35 | signal input msg; 36 | 37 | signal myAddr; 38 | 39 | signal output msgAttestation; 40 | 41 | // check that privkey properly represents a 256-bit number 42 | component n2bs[k]; 43 | for (var i = 0; i < k; i++) { 44 | n2bs[i] = Num2Bits(i == k-1 ? 256 - (k-1) * n : n); 45 | n2bs[i].in <== privkey[i]; 46 | } 47 | 48 | // compute addr 49 | component privToAddr = PrivKeyToAddr(n, k); 50 | for (var i = 0; i < k; i++) { 51 | privToAddr.privkey[i] <== privkey[i]; 52 | } 53 | myAddr <== privToAddr.addr; 54 | 55 | // verify address is one of the provided 56 | signal temp; 57 | temp <== (myAddr - addr1) * (myAddr - addr2); 58 | 0 === temp * (myAddr - addr3); 59 | 60 | // produce signature 61 | component mimcAttestation = MiMCSponge(k+1, 220, 1); 62 | mimcAttestation.ins[0] <== msg; 63 | for (var i = 0; i < k; i++) { 64 | mimcAttestation.ins[i+1] <== privkey[i]; 65 | } 66 | mimcAttestation.k <== 0; 67 | msgAttestation <== mimcAttestation.outs[0]; 68 | } 69 | 70 | component main {public [addr1, addr2, addr3, msg]} = Main(64, 4); -------------------------------------------------------------------------------- /scratch/text_scratch.txt: -------------------------------------------------------------------------------- 1 | ['f', 'f', 'f', 'f', 2 | 'f', 'f', 'f', 'f', 3 | 'f', 'f', 'f', 'f', 4 | 'f', 'f', 'f', 'f', 5 | 'f', 'f', 'f', 'f', 6 | 'f', 'f', 'f', 'f', 7 | '0', '0', '0', '0', 8 | '0', '0', '0', '0', 9 | '0', '0', '0', '0', 10 | '0', '0', '0', '0', 11 | '0', '0', '0', '0', 12 | '0', '0', '0', '0', 13 | '1', '0', '0', '0', 14 | '0', '0', '0', '0', 15 | 'f', 'f', 'f', 'f', 16 | 'f', 'f', 'f', 'f'] 17 | 18 | 19 | 2^0, 2^4, ... 20 | 21 | 2^(24*4)(2^(32*4)-1)/(2^4-1) - 2^(48*4) 22 | 23 | 56 * 4 24 | 25 | 26 | // proper: 27 | // 508515855n 28 | // 1925946678n 29 | // 1479546006n 30 | // 2941571439n 31 | // 1280170332n 32 | // 2209300002n 33 | // 3517425817n 34 | // 2119670560n 35 | // 4261680658n 36 | // 1368534515n 37 | // 1071415862n 38 | // 1796071564n 39 | // 155743491n 40 | // 1476551390n 41 | // 16382n 42 | // 0n 43 | 44 | 45 | // q: 46 | // 2201832346n 47 | // 807639114n 48 | // 1390919654n 49 | // 1951798673n 50 | // 1632294881n 51 | // 1476567772n 52 | // 16382n 53 | 54 | 55 | // qpProd: 56 | // 441656292767935329491896246588270814400332476686464817036616681810515471n 57 | // 441679301528718851428891688796402010190793895928107009059992484181093180n 58 | // 441683266643987450192448345829532974929482446205604695515865648302040741n 59 | // 4227243107222677573791778423994862229093782118277887003452210173565n 60 | // 21888242861036669527361730276088050524206108629278918168565866820731346360192n 61 | // 21888242861036669523500454806044391222172054395616764246739982361591775117866n 62 | // 12206257930146762475991211696461745414188797711653382355834798037071n 63 | // 441667114764550536796358231650274339850807612505725354989139408715976120n 64 | 65 | 66 | // reduced: 67 | // 9456797915143124070n 68 | // 12925581495935900700n 69 | // 18899535919838616630n 70 | // 17825649471654892095n 71 | // 21367519020553032360n 72 | // 21735374886241333170n 73 | // 13352533781637992671n 74 | // 15798678565696006614n 75 | // 3468853942337922974n 76 | // 5973954425854514603n 77 | // 8382911468591694416n 78 | // 7010653131167484667n 79 | // 6341810289591033122n 80 | // 70360154226690n -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_cpp/circom.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __CIRCOM_H 2 | #define __CIRCOM_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "fr.hpp" 11 | 12 | typedef unsigned long long u64; 13 | typedef uint32_t u32; 14 | typedef uint8_t u8; 15 | 16 | //only for the main inputs 17 | struct __attribute__((__packed__)) HashSignalInfo { 18 | u64 hash; 19 | u64 signalid; 20 | u64 signalsize; 21 | }; 22 | 23 | struct IODef { 24 | u32 offset; 25 | u32 len; 26 | u32 *lengths; 27 | }; 28 | 29 | struct IODefPair { 30 | u32 len; 31 | IODef* defs; 32 | }; 33 | 34 | struct Circom_Circuit { 35 | // const char *P; 36 | HashSignalInfo* InputHashMap; 37 | u64* witness2SignalList; 38 | FrElement* circuitConstants; 39 | std::map templateInsId2IOSignalInfo; 40 | }; 41 | 42 | 43 | struct Circom_Component { 44 | u32 templateId; 45 | u64 signalStart; 46 | u32 inputCounter; 47 | std::string templateName; 48 | std::string componentName; 49 | u64 idFather; 50 | u32* subcomponents; 51 | bool* subcomponentsParallel; 52 | bool *outputIsSet; //one for each output 53 | std::mutex *mutexes; //one for each output 54 | std::condition_variable *cvs; 55 | std::thread *sbct; //subcomponent threads 56 | }; 57 | 58 | /* 59 | For every template instantiation create two functions: 60 | - name_create 61 | - name_run 62 | 63 | //PFrElement: pointer to FrElement 64 | 65 | Every name_run or circom_function has: 66 | ===================================== 67 | 68 | //array of PFrElements for auxiliars in expression computation (known size); 69 | PFrElements expaux[]; 70 | 71 | //array of PFrElements for local vars (known size) 72 | PFrElements lvar[]; 73 | 74 | */ 75 | 76 | uint get_main_input_signal_start(); 77 | uint get_main_input_signal_no(); 78 | uint get_total_signal_no(); 79 | uint get_number_of_components(); 80 | uint get_size_of_input_hashmap(); 81 | uint get_size_of_witness(); 82 | uint get_size_of_constants(); 83 | uint get_size_of_io_map(); 84 | 85 | #endif // __CIRCOM_H 86 | -------------------------------------------------------------------------------- /scripts/eth_addr/build_eth_addr.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PHASE1=../../circuits/pot20_final.ptau 4 | BUILD_DIR=../../build/eth_addr 5 | CIRCUIT_NAME=eth_addr 6 | 7 | if [ -f "$PHASE1" ]; then 8 | echo "Found Phase 1 ptau file" 9 | else 10 | echo "No Phase 1 ptau file found. Exiting..." 11 | exit 1 12 | fi 13 | 14 | if [ ! -d "$BUILD_DIR" ]; then 15 | echo "No build directory found. Creating build directory..." 16 | mkdir -p "$BUILD_DIR" 17 | fi 18 | 19 | echo "****COMPILING CIRCUIT****" 20 | start=`date +%s` 21 | circom "$CIRCUIT_NAME".circom --r1cs --wasm --sym --c --wat --output "$BUILD_DIR" 22 | end=`date +%s` 23 | echo "DONE ($((end-start))s)" 24 | 25 | echo "****GENERATING WITNESS FOR SAMPLE INPUT****" 26 | start=`date +%s` 27 | node "$BUILD_DIR"/"$CIRCUIT_NAME"_js/generate_witness.js "$BUILD_DIR"/"$CIRCUIT_NAME"_js/"$CIRCUIT_NAME".wasm input_eth_addr.json "$BUILD_DIR"/witness.wtns 28 | end=`date +%s` 29 | echo "DONE ($((end-start))s)" 30 | 31 | echo "****GENERATING ZKEY 0****" 32 | start=`date +%s` 33 | npx snarkjs groth16 setup "$BUILD_DIR"/"$CIRCUIT_NAME".r1cs "$PHASE1" "$BUILD_DIR"/"$CIRCUIT_NAME"_0.zkey 34 | end=`date +%s` 35 | echo "DONE ($((end-start))s)" 36 | 37 | echo "****CONTRIBUTE TO THE PHASE 2 CEREMONY****" 38 | start=`date +%s` 39 | echo "test" | npx snarkjs zkey contribute "$BUILD_DIR"/"$CIRCUIT_NAME"_0.zkey "$BUILD_DIR"/"$CIRCUIT_NAME"_1.zkey --name="1st Contributor Name" 40 | end=`date +%s` 41 | echo "DONE ($((end-start))s)" 42 | 43 | echo "****GENERATING FINAL ZKEY****" 44 | start=`date +%s` 45 | npx snarkjs zkey beacon "$BUILD_DIR"/"$CIRCUIT_NAME"_1.zkey "$BUILD_DIR"/"$CIRCUIT_NAME".zkey 0102030405060708090a0b0c0d0e0f101112231415161718221a1b1c1d1e1f 10 -n="Final Beacon phase2" 46 | end=`date +%s` 47 | echo "DONE ($((end-start))s)" 48 | 49 | echo "****VERIFYING FINAL ZKEY****" 50 | start=`date +%s` 51 | npx snarkjs zkey verify "$BUILD_DIR"/"$CIRCUIT_NAME".r1cs "$PHASE1" "$BUILD_DIR"/"$CIRCUIT_NAME".zkey 52 | end=`date +%s` 53 | echo "DONE ($((end-start))s)" 54 | 55 | echo "****EXPORTING VKEY****" 56 | start=`date +%s` 57 | npx snarkjs zkey export verificationkey "$BUILD_DIR"/"$CIRCUIT_NAME".zkey "$BUILD_DIR"/vkey.json 58 | end=`date +%s` 59 | echo "DONE ($((end-start))s)" 60 | 61 | echo "****GENERATING PROOF FOR SAMPLE INPUT****" 62 | start=`date +%s` 63 | npx snarkjs groth16 prove "$BUILD_DIR"/"$CIRCUIT_NAME".zkey "$BUILD_DIR"/witness.wtns "$BUILD_DIR"/proof.json "$BUILD_DIR"/public.json 64 | end=`date +%s` 65 | echo "DONE ($((end-start))s)" 66 | 67 | echo "****VERIFYING PROOF FOR SAMPLE INPUT****" 68 | start=`date +%s` 69 | npx snarkjs groth16 verify "$BUILD_DIR"/vkey.json "$BUILD_DIR"/public.json "$BUILD_DIR"/proof.json 70 | end=`date +%s` 71 | echo "DONE ($((end-start))s)" 72 | -------------------------------------------------------------------------------- /scripts/groupsig/build_groupsig.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PHASE1=../../circuits/pot20_final.ptau 4 | BUILD_DIR=../../build/groupsig 5 | CIRCUIT_NAME=groupsig 6 | 7 | if [ -f "$PHASE1" ]; then 8 | echo "Found Phase 1 ptau file" 9 | else 10 | echo "No Phase 1 ptau file found. Exiting..." 11 | exit 1 12 | fi 13 | 14 | if [ ! -d "$BUILD_DIR" ]; then 15 | echo "No build directory found. Creating build directory..." 16 | mkdir -p "$BUILD_DIR" 17 | fi 18 | 19 | echo "****COMPILING CIRCUIT****" 20 | start=`date +%s` 21 | circom "$CIRCUIT_NAME".circom --r1cs --wasm --sym --c --wat --output "$BUILD_DIR" 22 | end=`date +%s` 23 | echo "DONE ($((end-start))s)" 24 | 25 | echo "****GENERATING WITNESS FOR SAMPLE INPUT****" 26 | start=`date +%s` 27 | node "$BUILD_DIR"/"$CIRCUIT_NAME"_js/generate_witness.js "$BUILD_DIR"/"$CIRCUIT_NAME"_js/"$CIRCUIT_NAME".wasm input_groupsig.json "$BUILD_DIR"/witness.wtns 28 | end=`date +%s` 29 | echo "DONE ($((end-start))s)" 30 | 31 | echo "****GENERATING ZKEY 0****" 32 | start=`date +%s` 33 | npx snarkjs groth16 setup "$BUILD_DIR"/"$CIRCUIT_NAME".r1cs "$PHASE1" "$BUILD_DIR"/"$CIRCUIT_NAME"_0.zkey 34 | end=`date +%s` 35 | echo "DONE ($((end-start))s)" 36 | 37 | echo "****CONTRIBUTE TO THE PHASE 2 CEREMONY****" 38 | start=`date +%s` 39 | echo "test" | npx snarkjs zkey contribute "$BUILD_DIR"/"$CIRCUIT_NAME"_0.zkey "$BUILD_DIR"/"$CIRCUIT_NAME"_1.zkey --name="1st Contributor Name" 40 | end=`date +%s` 41 | echo "DONE ($((end-start))s)" 42 | 43 | echo "****GENERATING FINAL ZKEY****" 44 | start=`date +%s` 45 | npx snarkjs zkey beacon "$BUILD_DIR"/"$CIRCUIT_NAME"_1.zkey "$BUILD_DIR"/"$CIRCUIT_NAME".zkey 0102030405060708090a0b0c0d0e0f101112231415161718221a1b1c1d1e1f 10 -n="Final Beacon phase2" 46 | end=`date +%s` 47 | echo "DONE ($((end-start))s)" 48 | 49 | echo "****VERIFYING FINAL ZKEY****" 50 | start=`date +%s` 51 | npx snarkjs zkey verify "$BUILD_DIR"/"$CIRCUIT_NAME".r1cs "$PHASE1" "$BUILD_DIR"/"$CIRCUIT_NAME".zkey 52 | end=`date +%s` 53 | echo "DONE ($((end-start))s)" 54 | 55 | echo "****EXPORTING VKEY****" 56 | start=`date +%s` 57 | npx snarkjs zkey export verificationkey "$BUILD_DIR"/"$CIRCUIT_NAME".zkey "$BUILD_DIR"/vkey.json 58 | end=`date +%s` 59 | echo "DONE ($((end-start))s)" 60 | 61 | echo "****GENERATING PROOF FOR SAMPLE INPUT****" 62 | start=`date +%s` 63 | npx snarkjs groth16 prove "$BUILD_DIR"/"$CIRCUIT_NAME".zkey "$BUILD_DIR"/witness.wtns "$BUILD_DIR"/proof.json "$BUILD_DIR"/public.json 64 | end=`date +%s` 65 | echo "DONE ($((end-start))s)" 66 | 67 | echo "****VERIFYING PROOF FOR SAMPLE INPUT****" 68 | start=`date +%s` 69 | npx snarkjs groth16 verify "$BUILD_DIR"/vkey.json "$BUILD_DIR"/public.json "$BUILD_DIR"/proof.json 70 | end=`date +%s` 71 | echo "DONE ($((end-start))s)" 72 | -------------------------------------------------------------------------------- /scripts/pubkeygen/build_pubkeygen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PHASE1=../../circuits/pot20_final.ptau 4 | BUILD_DIR=../../build/pubkeygen 5 | CIRCUIT_NAME=pubkeygen 6 | 7 | if [ -f "$PHASE1" ]; then 8 | echo "Found Phase 1 ptau file" 9 | else 10 | echo "No Phase 1 ptau file found. Exiting..." 11 | exit 1 12 | fi 13 | 14 | if [ ! -d "$BUILD_DIR" ]; then 15 | echo "No build directory found. Creating build directory..." 16 | mkdir -p "$BUILD_DIR" 17 | fi 18 | 19 | echo "****COMPILING CIRCUIT****" 20 | start=`date +%s` 21 | circom "$CIRCUIT_NAME".circom --r1cs --wasm --sym --c --wat --output "$BUILD_DIR" 22 | end=`date +%s` 23 | echo "DONE ($((end-start))s)" 24 | 25 | echo "****GENERATING WITNESS FOR SAMPLE INPUT****" 26 | start=`date +%s` 27 | node "$BUILD_DIR"/"$CIRCUIT_NAME"_js/generate_witness.js "$BUILD_DIR"/"$CIRCUIT_NAME"_js/"$CIRCUIT_NAME".wasm input_pubkeygen.json "$BUILD_DIR"/witness.wtns 28 | end=`date +%s` 29 | echo "DONE ($((end-start))s)" 30 | 31 | echo "****GENERATING ZKEY 0****" 32 | start=`date +%s` 33 | npx snarkjs groth16 setup "$BUILD_DIR"/"$CIRCUIT_NAME".r1cs "$PHASE1" "$BUILD_DIR"/"$CIRCUIT_NAME"_0.zkey 34 | end=`date +%s` 35 | echo "DONE ($((end-start))s)" 36 | 37 | echo "****CONTRIBUTE TO THE PHASE 2 CEREMONY****" 38 | start=`date +%s` 39 | echo "test" | npx snarkjs zkey contribute "$BUILD_DIR"/"$CIRCUIT_NAME"_0.zkey "$BUILD_DIR"/"$CIRCUIT_NAME"_1.zkey --name="1st Contributor Name" 40 | end=`date +%s` 41 | echo "DONE ($((end-start))s)" 42 | 43 | echo "****GENERATING FINAL ZKEY****" 44 | start=`date +%s` 45 | npx snarkjs zkey beacon "$BUILD_DIR"/"$CIRCUIT_NAME"_1.zkey "$BUILD_DIR"/"$CIRCUIT_NAME".zkey 0102030405060708090a0b0c0d0e0f101112231415161718221a1b1c1d1e1f 10 -n="Final Beacon phase2" 46 | end=`date +%s` 47 | echo "DONE ($((end-start))s)" 48 | 49 | echo "****VERIFYING FINAL ZKEY****" 50 | start=`date +%s` 51 | npx snarkjs zkey verify "$BUILD_DIR"/"$CIRCUIT_NAME".r1cs "$PHASE1" "$BUILD_DIR"/"$CIRCUIT_NAME".zkey 52 | end=`date +%s` 53 | echo "DONE ($((end-start))s)" 54 | 55 | echo "****EXPORTING VKEY****" 56 | start=`date +%s` 57 | npx snarkjs zkey export verificationkey "$BUILD_DIR"/"$CIRCUIT_NAME".zkey "$BUILD_DIR"/vkey.json 58 | end=`date +%s` 59 | echo "DONE ($((end-start))s)" 60 | 61 | echo "****GENERATING PROOF FOR SAMPLE INPUT****" 62 | start=`date +%s` 63 | npx snarkjs groth16 prove "$BUILD_DIR"/"$CIRCUIT_NAME".zkey "$BUILD_DIR"/witness.wtns "$BUILD_DIR"/proof.json "$BUILD_DIR"/public.json 64 | end=`date +%s` 65 | echo "DONE ($((end-start))s)" 66 | 67 | echo "****VERIFYING PROOF FOR SAMPLE INPUT****" 68 | start=`date +%s` 69 | npx snarkjs groth16 verify "$BUILD_DIR"/vkey.json "$BUILD_DIR"/public.json "$BUILD_DIR"/proof.json 70 | end=`date +%s` 71 | echo "DONE ($((end-start))s)" 72 | -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/public.json: -------------------------------------------------------------------------------- 1 | [ 2 | "49732730225977125179960148", 3 | "43852565336912664664048527", 4 | "9043934293559324284618350", 5 | "0", 6 | "0", 7 | "0", 8 | "0", 9 | "0", 10 | "0", 11 | "0", 12 | "0", 13 | "0", 14 | "0", 15 | "0", 16 | "0", 17 | "0", 18 | "0", 19 | "0", 20 | "0", 21 | "0", 22 | "0", 23 | "0", 24 | "0", 25 | "0", 26 | "0", 27 | "0", 28 | "0", 29 | "0", 30 | "0", 31 | "0", 32 | "0", 33 | "0", 34 | "0", 35 | "0", 36 | "0", 37 | "0", 38 | "0", 39 | "0", 40 | "0", 41 | "0", 42 | "0", 43 | "0", 44 | "0", 45 | "0", 46 | "0", 47 | "0", 48 | "0", 49 | "0", 50 | "0", 51 | "0", 52 | "0", 53 | "0", 54 | "0", 55 | "0", 56 | "0", 57 | "0", 58 | "0", 59 | "0", 60 | "0", 61 | "0", 62 | "0", 63 | "0", 64 | "0", 65 | "0", 66 | "0", 67 | "0", 68 | "0", 69 | "0", 70 | "0", 71 | "0", 72 | "0", 73 | "0", 74 | "0", 75 | "0", 76 | "0", 77 | "0", 78 | "0", 79 | "0", 80 | "0", 81 | "0", 82 | "0", 83 | "0", 84 | "0", 85 | "0", 86 | "0", 87 | "0", 88 | "0", 89 | "0", 90 | "0", 91 | "0", 92 | "0", 93 | "0", 94 | "0", 95 | "0", 96 | "0", 97 | "0", 98 | "0", 99 | "0", 100 | "0", 101 | "0", 102 | "20405083474242608521046015", 103 | "57969189420107975911442337", 104 | "12380911704996683387468560", 105 | "0", 106 | "0", 107 | "0", 108 | "0", 109 | "0", 110 | "0", 111 | "0", 112 | "0", 113 | "0", 114 | "0", 115 | "0", 116 | "0", 117 | "0", 118 | "0", 119 | "0", 120 | "0", 121 | "0", 122 | "0", 123 | "0", 124 | "0", 125 | "0", 126 | "0", 127 | "0", 128 | "0", 129 | "0", 130 | "0", 131 | "0", 132 | "0", 133 | "0", 134 | "0", 135 | "0", 136 | "0", 137 | "0", 138 | "0", 139 | "0", 140 | "0", 141 | "0", 142 | "0", 143 | "0", 144 | "0", 145 | "0", 146 | "0", 147 | "0", 148 | "0", 149 | "0", 150 | "0", 151 | "0", 152 | "0", 153 | "0", 154 | "0", 155 | "0", 156 | "0", 157 | "0", 158 | "0", 159 | "0", 160 | "0", 161 | "0", 162 | "0", 163 | "0", 164 | "0", 165 | "0", 166 | "0", 167 | "0", 168 | "0", 169 | "0", 170 | "0", 171 | "0", 172 | "0", 173 | "0", 174 | "0", 175 | "0", 176 | "0", 177 | "0", 178 | "0", 179 | "0", 180 | "0", 181 | "0", 182 | "0", 183 | "0", 184 | "0", 185 | "0", 186 | "0", 187 | "0", 188 | "0", 189 | "0", 190 | "0", 191 | "0", 192 | "0", 193 | "0", 194 | "0", 195 | "0", 196 | "0", 197 | "0", 198 | "0", 199 | "0", 200 | "0", 201 | "0" 202 | ] 203 | -------------------------------------------------------------------------------- /scratch/dummy_point/build_dummy_point.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PHASE1=../../circuits/pot20_final.ptau 4 | BUILD_DIR=../../build_86_3/dummy_point 5 | CIRCUIT_NAME=dummy_point 6 | 7 | if [ -f "$PHASE1" ]; then 8 | echo "Found Phase 1 ptau file" 9 | else 10 | echo "No Phase 1 ptau file found. Exiting..." 11 | exit 1 12 | fi 13 | 14 | if [ ! -d "$BUILD_DIR" ]; then 15 | echo "No build directory found. Creating build directory..." 16 | mkdir -p "$BUILD_DIR" 17 | fi 18 | 19 | echo "****COMPILING CIRCUIT****" 20 | start=`date +%s` 21 | circom "$CIRCUIT_NAME".circom --r1cs --wasm --sym --c --wat --output "$BUILD_DIR" 22 | end=`date +%s` 23 | echo "DONE ($((end-start))s)" 24 | 25 | echo "****GENERATING WITNESS FOR SAMPLE INPUT****" 26 | start=`date +%s` 27 | node "$BUILD_DIR"/"$CIRCUIT_NAME"_js/generate_witness.js "$BUILD_DIR"/"$CIRCUIT_NAME"_js/"$CIRCUIT_NAME".wasm input_86_3_dummy_point.json "$BUILD_DIR"/witness.wtns 28 | end=`date +%s` 29 | echo "DONE ($((end-start))s)" 30 | 31 | echo "****GENERATING ZKEY 0****" 32 | start=`date +%s` 33 | npx snarkjs groth16 setup "$BUILD_DIR"/"$CIRCUIT_NAME".r1cs "$PHASE1" "$BUILD_DIR"/"$CIRCUIT_NAME"_0.zkey 34 | end=`date +%s` 35 | echo "DONE ($((end-start))s)" 36 | 37 | echo "****CONTRIBUTE TO THE PHASE 2 CEREMONY****" 38 | start=`date +%s` 39 | echo "test" | npx snarkjs zkey contribute "$BUILD_DIR"/"$CIRCUIT_NAME"_0.zkey "$BUILD_DIR"/"$CIRCUIT_NAME"_1.zkey --name="1st Contributor Name" 40 | end=`date +%s` 41 | echo "DONE ($((end-start))s)" 42 | 43 | echo "****GENERATING FINAL ZKEY****" 44 | start=`date +%s` 45 | npx snarkjs zkey beacon "$BUILD_DIR"/"$CIRCUIT_NAME"_1.zkey "$BUILD_DIR"/"$CIRCUIT_NAME".zkey 0102030405060708090a0b0c0d0e0f101112231415161718221a1b1c1d1e1f 10 -n="Final Beacon phase2" 46 | end=`date +%s` 47 | echo "DONE ($((end-start))s)" 48 | 49 | echo "****VERIFYING FINAL ZKEY****" 50 | start=`date +%s` 51 | npx snarkjs zkey verify "$BUILD_DIR"/"$CIRCUIT_NAME".r1cs "$PHASE1" "$BUILD_DIR"/"$CIRCUIT_NAME".zkey 52 | end=`date +%s` 53 | echo "DONE ($((end-start))s)" 54 | 55 | echo "****EXPORTING VKEY****" 56 | start=`date +%s` 57 | npx snarkjs zkey export verificationkey "$BUILD_DIR"/"$CIRCUIT_NAME".zkey "$BUILD_DIR"/vkey.json 58 | end=`date +%s` 59 | echo "DONE ($((end-start))s)" 60 | 61 | echo "****GENERATING PROOF FOR SAMPLE INPUT****" 62 | start=`date +%s` 63 | npx snarkjs groth16 prove "$BUILD_DIR"/"$CIRCUIT_NAME".zkey "$BUILD_DIR"/witness.wtns "$BUILD_DIR"/proof.json "$BUILD_DIR"/public.json 64 | end=`date +%s` 65 | echo "DONE ($((end-start))s)" 66 | 67 | echo "****VERIFYING PROOF FOR SAMPLE INPUT****" 68 | start=`date +%s` 69 | npx snarkjs groth16 verify "$BUILD_DIR"/vkey.json "$BUILD_DIR"/public.json "$BUILD_DIR"/proof.json 70 | end=`date +%s` 71 | echo "DONE ($((end-start))s)" 72 | -------------------------------------------------------------------------------- /scripts/verify/build_verify.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PHASE1=../../circuits/pot21_final.ptau 4 | BUILD_DIR=../../build/verify 5 | CIRCUIT_NAME=verify 6 | 7 | export NODE_OPTIONS=--max_old_space_size=16384 8 | 9 | if [ -f "$PHASE1" ]; then 10 | echo "Found Phase 1 ptau file" 11 | else 12 | echo "No Phase 1 ptau file found. Exiting..." 13 | exit 1 14 | fi 15 | 16 | if [ ! -d "$BUILD_DIR" ]; then 17 | echo "No build directory found. Creating build directory..." 18 | mkdir -p "$BUILD_DIR" 19 | fi 20 | 21 | echo "****COMPILING CIRCUIT****" 22 | start=`date +%s` 23 | set -x 24 | circom "$CIRCUIT_NAME".circom --r1cs --wasm --sym --c --wat --output "$BUILD_DIR" 25 | { set +x; } 2>/dev/null 26 | end=`date +%s` 27 | echo "DONE ($((end-start))s)" 28 | 29 | echo "****GENERATING WITNESS FOR SAMPLE INPUT****" 30 | start=`date +%s` 31 | node "$BUILD_DIR"/"$CIRCUIT_NAME"_js/generate_witness.js "$BUILD_DIR"/"$CIRCUIT_NAME"_js/"$CIRCUIT_NAME".wasm input_verify.json "$BUILD_DIR"/witness.wtns 32 | end=`date +%s` 33 | echo "DONE ($((end-start))s)" 34 | 35 | echo "****GENERATING ZKEY 0****" 36 | start=`date +%s` 37 | npx snarkjs groth16 setup "$BUILD_DIR"/"$CIRCUIT_NAME".r1cs "$PHASE1" "$BUILD_DIR"/"$CIRCUIT_NAME"_0.zkey 38 | end=`date +%s` 39 | echo "DONE ($((end-start))s)" 40 | 41 | echo "****CONTRIBUTE TO THE PHASE 2 CEREMONY****" 42 | start=`date +%s` 43 | echo "test" | npx snarkjs zkey contribute "$BUILD_DIR"/"$CIRCUIT_NAME"_0.zkey "$BUILD_DIR"/"$CIRCUIT_NAME"_1.zkey --name="1st Contributor Name" 44 | end=`date +%s` 45 | echo "DONE ($((end-start))s)" 46 | 47 | echo "****GENERATING FINAL ZKEY****" 48 | start=`date +%s` 49 | npx snarkjs zkey beacon "$BUILD_DIR"/"$CIRCUIT_NAME"_1.zkey "$BUILD_DIR"/"$CIRCUIT_NAME".zkey 0102030405060708090a0b0c0d0e0f101112231415161718221a1b1c1d1e1f 10 -n="Final Beacon phase2" 50 | end=`date +%s` 51 | echo "DONE ($((end-start))s)" 52 | 53 | echo "****VERIFYING FINAL ZKEY****" 54 | start=`date +%s` 55 | npx snarkjs zkey verify "$BUILD_DIR"/"$CIRCUIT_NAME".r1cs "$PHASE1" "$BUILD_DIR"/"$CIRCUIT_NAME".zkey 56 | end=`date +%s` 57 | echo "DONE ($((end-start))s)" 58 | 59 | echo "** Exporting vkey" 60 | start=`date +%s` 61 | npx snarkjs zkey export verificationkey "$BUILD_DIR"/"$CIRCUIT_NAME".zkey "$BUILD_DIR"/vkey.json 62 | end=`date +%s` 63 | echo "DONE ($((end-start))s)" 64 | 65 | echo "****GENERATING PROOF FOR SAMPLE INPUT****" 66 | start=`date +%s` 67 | npx snarkjs groth16 prove "$BUILD_DIR"/"$CIRCUIT_NAME".zkey "$BUILD_DIR"/witness.wtns "$BUILD_DIR"/proof.json "$BUILD_DIR"/public.json 68 | end=`date +%s` 69 | echo "DONE ($((end-start))s)" 70 | 71 | echo "****VERIFYING PROOF FOR SAMPLE INPUT****" 72 | start=`date +%s` 73 | npx snarkjs groth16 verify "$BUILD_DIR"/vkey.json "$BUILD_DIR"/public.json "$BUILD_DIR"/proof.json 74 | end=`date +%s` 75 | echo "DONE ($((end-start))s)" 76 | -------------------------------------------------------------------------------- /scratch/tracing_point_scratch.py: -------------------------------------------------------------------------------- 1 | x = 5066263022277343669578718895168534326250603453777594175500187360389116729240 2 | y = 32670510020758816978083085130507043184471273380659243275938904335757337482424 3 | A = 115792089210356248762697446949407573530086143415290314195533631308867097853948 4 | B = 41058363725152142129326129780047268409114441015993725554835256314039467401291 5 | P = 115792089210356248762697446949407573530086143415290314195533631308867097853951 6 | 7 | print(((x**3 + A * x + B - y**2) % P) == 0) 8 | 9 | parameters = { 10 | "P": 115792089210356248762697446949407573530086143415290314195533631308867097853951, 11 | "N": 115792089210356248762697446949407573529996955224135760342422259061068512044369, 12 | "A": 115792089210356248762697446949407573530086143415290314195533631308867097853948, 13 | "B": 41058363725152142129326129780047268409114441015993725554835256314039467401291, 14 | "Gx": 48439561293906451759052585252797914202762949526041747995844080717082404635286, 15 | "Gy": 36134250956749795798585127919587881956611106672985015071877198253568414405109, 16 | } 17 | # supposed to be on the curve, let's trace witness computation thru the circuits 18 | # P256PointOnCurve 19 | 20 | # // DONE 21 | # // Implements: 22 | # // x^3 + Ax + B - y^2 == 0 mod p 23 | # // where A, B, p are params of P256 curve (p is field size) 24 | # template P256PointOnCurve() { 25 | # signal input x[4]; 26 | # signal input y[4]; 27 | 28 | # // first, we compute representations of x^3 and y^2. 29 | # // these representations have overflowed, nonnegative registers 30 | # signal x3[10]; // 197 bits 31 | # component x3Comp = A3NoCarry(); 32 | # for (var i = 0; i < 4; i++) x3Comp.a[i] <== x[i]; 33 | # for (var i = 0; i < 10; i++) x3[i] <== x3Comp.a3[i]; 34 | 35 | # signal y2[7]; // 130 bits 36 | # component y2Comp = A2NoCarry(); 37 | # for (var i = 0; i < 4; i++) y2Comp.a[i] <== y[i]; 38 | # for (var i = 0; i < 7; i++) y2[i] <== y2Comp.a2[i]; 39 | 40 | # // next, we compute representations of Ax and B. 41 | # signal A[4]; 42 | # var tmpA[100] = get_A(64, 4); 43 | # for (var i = 0; i < 4; i++) A[i] <== tmpA[i]; 44 | 45 | # signal B[4]; 46 | # var tmpB[100] = get_B(64, 4); 47 | # for (var i = 0; i < 4; i++) B[i] <== tmpB[i]; 48 | 49 | # signal Ax[7]; 50 | # component AxComp = BigMultNoCarry(64, 64, 64, 4, 4); 51 | # for (var i = 0; i < 4; i++) AxComp.a[i] <== x[i]; 52 | # for (var i = 0; i < 4; i++) AxComp.b[i] <== A[i]; 53 | # for (var i = 0; i < 7; i++) Ax[i] <== AxComp.out[i]; 54 | 55 | # component zeroCheck = CheckCubicModPIsZero(197); // 197 bits per register 56 | # for (var i = 0; i < 10; i++) { 57 | # if (i < 4) zeroCheck.in[i] <== x3[i] - y2[i] + Ax[i] + B[i]; 58 | # else if (i < 7) zeroCheck.in[i] <== x3[i] - y2[i] + Ax[i]; 59 | # else zeroCheck.in[i] <== x3[i]; 60 | # } 61 | # } 62 | -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_cpp/calcwit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "calcwit.hpp" 5 | 6 | extern void run(Circom_CalcWit* ctx); 7 | 8 | std::string int_to_hex( u64 i ) 9 | { 10 | std::stringstream stream; 11 | stream << "0x" 12 | << std::setfill ('0') << std::setw(16) 13 | << std::hex << i; 14 | return stream.str(); 15 | } 16 | 17 | u64 fnv1a(std::string s) { 18 | u64 hash = 0xCBF29CE484222325LL; 19 | for(char& c : s) { 20 | hash ^= u64(c); 21 | hash *= 0x100000001B3LL; 22 | } 23 | return hash; 24 | } 25 | 26 | Circom_CalcWit::Circom_CalcWit (Circom_Circuit *aCircuit, uint maxTh) { 27 | circuit = aCircuit; 28 | inputSignalAssignedCounter = get_main_input_signal_no(); 29 | inputSignalAssigned = new bool[inputSignalAssignedCounter]; 30 | for (int i = 0; i< inputSignalAssignedCounter; i++) { 31 | inputSignalAssigned[i] = false; 32 | } 33 | signalValues = new FrElement[get_total_signal_no()]; 34 | Fr_str2element(&signalValues[0], "1", 10); 35 | componentMemory = new Circom_Component[get_number_of_components()]; 36 | circuitConstants = circuit ->circuitConstants; 37 | templateInsId2IOSignalInfo = circuit -> templateInsId2IOSignalInfo; 38 | 39 | maxThread = maxTh; 40 | 41 | // parallelism 42 | numThread = 0; 43 | 44 | } 45 | 46 | Circom_CalcWit::~Circom_CalcWit() { 47 | // ... 48 | } 49 | 50 | uint Circom_CalcWit::getInputSignalHashPosition(u64 h) { 51 | uint n = get_size_of_input_hashmap(); 52 | uint pos = (uint)(h % (u64)n); 53 | if (circuit->InputHashMap[pos].hash!=h){ 54 | uint inipos = pos; 55 | pos++; 56 | while (pos != inipos) { 57 | if (circuit->InputHashMap[pos].hash==h) return pos; 58 | if (circuit->InputHashMap[pos].hash==0) { 59 | fprintf(stderr, "Signal not found\n"); 60 | assert(false); 61 | } 62 | pos = (pos+1)%n; 63 | } 64 | fprintf(stderr, "Signals not found\n"); 65 | assert(false); 66 | } 67 | return pos; 68 | } 69 | 70 | void Circom_CalcWit::tryRunCircuit(){ 71 | if (inputSignalAssignedCounter == 0) { 72 | run(this); 73 | } 74 | } 75 | 76 | void Circom_CalcWit::setInputSignal(u64 h, uint i, FrElement & val){ 77 | if (inputSignalAssignedCounter == 0) { 78 | fprintf(stderr, "No more signals to be assigned\n"); 79 | assert(false); 80 | } 81 | uint pos = getInputSignalHashPosition(h); 82 | if (i >= circuit->InputHashMap[pos].signalsize) { 83 | fprintf(stderr, "Input signal array access exceeds the size\n"); 84 | assert(false); 85 | } 86 | 87 | uint si = circuit->InputHashMap[pos].signalid+i; 88 | if (inputSignalAssigned[si-get_main_input_signal_start()]) { 89 | fprintf(stderr, "Signal assigned twice: %d\n", si); 90 | assert(false); 91 | } 92 | signalValues[si] = val; 93 | inputSignalAssigned[si-get_main_input_signal_start()] = true; 94 | inputSignalAssignedCounter--; 95 | tryRunCircuit(); 96 | } 97 | 98 | u64 Circom_CalcWit::getInputSignalSize(u64 h) { 99 | uint pos = getInputSignalHashPosition(h); 100 | return circuit->InputHashMap[pos].signalsize; 101 | } 102 | 103 | std::string Circom_CalcWit::getTrace(u64 id_cmp){ 104 | if (id_cmp == 0) return componentMemory[id_cmp].componentName; 105 | else{ 106 | u64 id_father = componentMemory[id_cmp].idFather; 107 | std::string my_name = componentMemory[id_cmp].componentName; 108 | 109 | return Circom_CalcWit::getTrace(id_father) + "." + my_name; 110 | } 111 | 112 | 113 | } 114 | 115 | std::string Circom_CalcWit::generate_position_array(uint* dimensions, uint size_dimensions, uint index){ 116 | std::string positions = ""; 117 | 118 | for (uint i = 0 ; i < size_dimensions; i++){ 119 | uint last_pos = index % dimensions[size_dimensions -1 - i]; 120 | index = index / dimensions[size_dimensions -1 - i]; 121 | std::string new_pos = "[" + std::to_string(last_pos) + "]"; 122 | positions = new_pos + positions; 123 | } 124 | return positions; 125 | } 126 | 127 | -------------------------------------------------------------------------------- /circuits/p256.circom: -------------------------------------------------------------------------------- 1 | pragma circom 2.1.5; 2 | 3 | include "circom-pairing/circuits/curve.circom"; 4 | include "p256_func.circom"; 5 | 6 | template P256AddUnequal(n, k) { 7 | assert(n == 43 && k == 6); 8 | 9 | signal input a[2][k]; 10 | signal input b[2][k]; 11 | 12 | var params[4][6] = get_p256_params(); 13 | component adder = EllipticCurveAddUnequal(n, k, params[2]); 14 | for (var i = 0; i < 6; i++) { 15 | adder.a[0][i] <== a[0][i]; 16 | adder.a[1][i] <== a[1][i]; 17 | adder.b[0][i] <== b[0][i]; 18 | adder.b[1][i] <== b[1][i]; 19 | } 20 | 21 | signal output out[2][k] <== adder.out; 22 | } 23 | 24 | template P256Double(n, k) { 25 | assert(n == 43 && k == 6); 26 | 27 | signal input in[2][k]; 28 | 29 | var params[4][6] = get_p256_params(); 30 | component doubler = EllipticCurveDouble(n, k, params[0], params[1], params[2]); 31 | for (var i = 0; i < 6; i++) { 32 | doubler.in[0][i] <== in[0][i]; 33 | doubler.in[1][i] <== in[1][i]; 34 | } 35 | 36 | signal output out[2][k] <== doubler.out; 37 | } 38 | 39 | template P256ScalarMult(n, k) { 40 | signal input scalar[k]; 41 | signal input point[2][k]; 42 | 43 | signal output out[2][k]; 44 | 45 | component n2b[k]; 46 | for (var i = 0; i < k; i++) { 47 | n2b[i] = Num2Bits(n); 48 | n2b[i].in <== scalar[i]; 49 | } 50 | 51 | // has_prev_non_zero[n * i + j] == 1 if there is a nonzero bit in location [i][j] or higher order bit 52 | component has_prev_non_zero[k * n]; 53 | for (var i = k - 1; i >= 0; i--) { 54 | for (var j = n - 1; j >= 0; j--) { 55 | has_prev_non_zero[n * i + j] = OR(); 56 | if (i == k - 1 && j == n - 1) { 57 | has_prev_non_zero[n * i + j].a <== 0; 58 | has_prev_non_zero[n * i + j].b <== n2b[i].out[j]; 59 | } else { 60 | has_prev_non_zero[n * i + j].a <== has_prev_non_zero[n * i + j + 1].out; 61 | has_prev_non_zero[n * i + j].b <== n2b[i].out[j]; 62 | } 63 | } 64 | } 65 | 66 | signal partial[n * k][2][k]; 67 | signal intermed[n * k - 1][2][k]; 68 | component adders[n * k - 1]; 69 | component doublers[n * k - 1]; 70 | for (var i = k - 1; i >= 0; i--) { 71 | for (var j = n - 1; j >= 0; j--) { 72 | if (i == k - 1 && j == n - 1) { 73 | for (var idx = 0; idx < k; idx++) { 74 | partial[n * i + j][0][idx] <== point[0][idx]; 75 | partial[n * i + j][1][idx] <== point[1][idx]; 76 | } 77 | } 78 | if (i < k - 1 || j < n - 1) { 79 | adders[n * i + j] = P256AddUnequal(n, k); 80 | doublers[n * i + j] = P256Double(n, k); 81 | for (var idx = 0; idx < k; idx++) { 82 | doublers[n * i + j].in[0][idx] <== partial[n * i + j + 1][0][idx]; 83 | doublers[n * i + j].in[1][idx] <== partial[n * i + j + 1][1][idx]; 84 | } 85 | for (var idx = 0; idx < k; idx++) { 86 | adders[n * i + j].a[0][idx] <== doublers[n * i + j].out[0][idx]; 87 | adders[n * i + j].a[1][idx] <== doublers[n * i + j].out[1][idx]; 88 | adders[n * i + j].b[0][idx] <== point[0][idx]; 89 | adders[n * i + j].b[1][idx] <== point[1][idx]; 90 | } 91 | // partial[n * i + j] 92 | // = has_prev_non_zero[n * i + j + 1] * ((1 - n2b[i].out[j]) * doublers[n * i + j] + n2b[i].out[j] * adders[n * i + j]) 93 | // + (1 - has_prev_non_zero[n * i + j + 1]) * point 94 | for (var idx = 0; idx < k; idx++) { 95 | intermed[n * i + j][0][idx] <== n2b[i].out[j] * (adders[n * i + j].out[0][idx] - doublers[n * i + j].out[0][idx]) + doublers[n * i + j].out[0][idx]; 96 | intermed[n * i + j][1][idx] <== n2b[i].out[j] * (adders[n * i + j].out[1][idx] - doublers[n * i + j].out[1][idx]) + doublers[n * i + j].out[1][idx]; 97 | partial[n * i + j][0][idx] <== has_prev_non_zero[n * i + j + 1].out * (intermed[n * i + j][0][idx] - point[0][idx]) + point[0][idx]; 98 | partial[n * i + j][1][idx] <== has_prev_non_zero[n * i + j + 1].out * (intermed[n * i + j][1][idx] - point[1][idx]) + point[1][idx]; 99 | } 100 | } 101 | } 102 | } 103 | 104 | for (var idx = 0; idx < k; idx++) { 105 | out[0][idx] <== partial[0][0][idx]; 106 | out[1][idx] <== partial[0][1][idx]; 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /scripts/compute_secp256k1_math.py: -------------------------------------------------------------------------------- 1 | import math 2 | import sys 3 | 4 | P = 2**256 - 2**32 - 977 5 | N = 115792089237316195423570985008687907852837564279074904382605163141518161494337 6 | A = 0 7 | B = 7 8 | Gx = 55066263022277343669578718895168534326250603453777594175500187360389116729240 9 | Gy = 32670510020758816978083085130507043184471273380659243275938904335757337482424 10 | 11 | 12 | def egcd(a, b): 13 | if a == 0: 14 | return (b, 0, 1) 15 | else: 16 | g, y, x = egcd(b % a, a) 17 | return (g, x - (b // a) * y, y) 18 | 19 | 20 | def modinv(a, m): 21 | g, x, y = egcd(a, m) 22 | if g != 1: 23 | raise Exception('modular inverse does not exist') 24 | else: 25 | return x % m 26 | 27 | 28 | def double(x, y): 29 | lamb = (3 * (x ** 2) * modinv(2 * y, P)) % P 30 | retx = (lamb ** 2 - 2 * x) % P 31 | rety = (lamb * (x - retx) - y) % P 32 | return retx, rety 33 | 34 | 35 | def add(x1, y1, x2, y2): 36 | lamb = ((y2 - y1) * modinv(P + x2 - x1, P)) % P 37 | retx = (P + lamb ** 2 - x1 - x2) % P 38 | rety = (P + lamb * (x1 - retx) - y1) % P 39 | return retx, rety 40 | 41 | # computes G^1, G^2, G^4, G^8, ..., G^2^exp 42 | 43 | 44 | def get_g_pows(exp): 45 | g_pows = [] 46 | curr_x, curr_y = Gx, Gy 47 | for idx in range(exp): 48 | g_pows.append((curr_x, curr_y)) 49 | curr_x, curr_y = double(curr_x, curr_y) 50 | return g_pows 51 | 52 | 53 | def get_long(n, k, x): 54 | ret = [] 55 | for idx in range(k): 56 | ret.append(x % (2 ** n)) 57 | x = x // (2 ** n) 58 | return ret 59 | 60 | 61 | def get_long_g_pows(exp, n, k): 62 | g_pows = get_g_pows(exp) 63 | long_g_pows = [] 64 | for x, y in g_pows: 65 | long_x, long_y = get_long(n, k, x), get_long(n, k, y) 66 | long_g_pows.append((long_x, long_y)) 67 | return long_g_pows 68 | 69 | 70 | def get_binary(x): 71 | ret = [] 72 | while x > 0: 73 | ret.append(x % 2) 74 | x = x // 2 75 | return ret 76 | 77 | # computes G^exp given precomputed G^1, G^2, G^4, G^8, etc. 78 | 79 | 80 | def get_g_pow_val(g_pows, exp): 81 | binary = get_binary(exp) 82 | is_nonzero = False 83 | curr_sum = None 84 | for idx, val in enumerate(binary): 85 | if val != 0: 86 | if not is_nonzero: 87 | is_nonzero = True 88 | curr_sum = g_pows[idx] 89 | else: 90 | curr_sum = add(curr_sum[0], curr_sum[1], 91 | g_pows[idx][0], g_pows[idx][1]) 92 | return curr_sum 93 | 94 | 95 | def get_cache_str(n, k, stride): 96 | num_strides = math.ceil(n * k / stride) 97 | stride_cache_size = 2 ** stride 98 | ret_str = ''' 99 | function get_g_pow_stride{}_table(n, k) '''.format(stride) 100 | ret_str = ret_str + '{' 101 | ret_str = ret_str + ''' 102 | assert(n == {} && k == {}); 103 | var powers[{}][{}][2][{}]; 104 | '''.format(n, k, num_strides, 2 ** stride, k) 105 | EXP = 256 + stride 106 | g_pows = get_g_pows(EXP) 107 | 108 | for stride_idx in range(num_strides): 109 | for idx in range(2 ** stride): 110 | exp = idx * (2 ** (stride_idx * stride)) 111 | ret_append = '\n' 112 | if exp > 0: 113 | g_pow = get_g_pow_val(g_pows, exp) 114 | long_g_pow = get_long(n, k, g_pow[0]), get_long(n, k, g_pow[1]) 115 | for reg_idx in range(k): 116 | ret_append += ' powers[{}][{}][0][{}] = {};\n'.format( 117 | stride_idx, idx, reg_idx, long_g_pow[0][reg_idx]) 118 | for reg_idx in range(k): 119 | ret_append += ' powers[{}][{}][1][{}] = {};\n'.format( 120 | stride_idx, idx, reg_idx, long_g_pow[1][reg_idx]) 121 | elif exp == 0: 122 | for reg_idx in range(k): 123 | ret_append += ' powers[{}][{}][0][{}] = 0;\n'.format( 124 | stride_idx, idx, reg_idx) 125 | for reg_idx in range(k): 126 | ret_append += ' powers[{}][{}][1][{}] = 0;\n'.format( 127 | stride_idx, idx, reg_idx) 128 | ret_str = ret_str + ret_append 129 | ret_str = ret_str + ''' 130 | return powers; 131 | } 132 | ''' 133 | return ret_str 134 | 135 | 136 | def get_ecdsa_func_str(n, k, stride_list): 137 | ret_str = '''pragma circom 2.1.5; 138 | ''' 139 | for stride in stride_list: 140 | cache_str = get_cache_str(n, k, stride) 141 | ret_str = ret_str + cache_str 142 | return ret_str 143 | 144 | 145 | stride_list = [8] 146 | ecdsa_func_str = get_ecdsa_func_str(64, 4, stride_list) 147 | 148 | orig_stdout = sys.stdout 149 | f = open('out.circom', 'w') 150 | sys.stdout = f 151 | 152 | print(ecdsa_func_str) 153 | -------------------------------------------------------------------------------- /scripts/compute_p256_math.py: -------------------------------------------------------------------------------- 1 | # DONE FILE 2 | 3 | import math 4 | import sys 5 | 6 | P = 115792089210356248762697446949407573530086143415290314195533631308867097853951 7 | N = 115792089210356248762697446949407573529996955224135760342422259061068512044369 8 | A = 115792089210356248762697446949407573530086143415290314195533631308867097853948 9 | B = 41058363725152142129326129780047268409114441015993725554835256314039467401291 10 | Gx = 48439561293906451759052585252797914202762949526041747995844080717082404635286 11 | Gy = 36134250956749795798585127919587881956611106672985015071877198253568414405109 12 | 13 | 14 | def egcd(a, b): 15 | if a == 0: 16 | return (b, 0, 1) 17 | else: 18 | g, y, x = egcd(b % a, a) 19 | return (g, x - (b // a) * y, y) 20 | 21 | 22 | def modinv(a, m): 23 | g, x, y = egcd(a, m) 24 | if g != 1: 25 | raise Exception('modular inverse does not exist') 26 | else: 27 | return x % m 28 | 29 | 30 | # added A to numerator: lambda = (3x^2+a)/2y 31 | def double(x, y): 32 | lamb = ((3 * (x ** 2) + A) * modinv(2 * y, P)) % P 33 | retx = (lamb ** 2 - 2 * x) % P 34 | rety = (lamb * (x - retx) - y) % P 35 | return retx, rety 36 | 37 | 38 | def add(x1, y1, x2, y2): 39 | lamb = ((y2 - y1) * modinv(P + x2 - x1, P)) % P 40 | retx = (P + lamb ** 2 - x1 - x2) % P 41 | rety = (P + lamb * (x1 - retx) - y1) % P 42 | return retx, rety 43 | 44 | # computes G^1, G^2, G^4, G^8, ..., G^2^exp 45 | 46 | 47 | def get_g_pows(exp): 48 | g_pows = [] 49 | curr_x, curr_y = Gx, Gy 50 | for idx in range(exp): 51 | g_pows.append((curr_x, curr_y)) 52 | curr_x, curr_y = double(curr_x, curr_y) 53 | return g_pows 54 | 55 | 56 | def get_long(n, k, x): 57 | ret = [] 58 | for idx in range(k): 59 | ret.append(x % (2 ** n)) 60 | x = x // (2 ** n) 61 | return ret 62 | 63 | 64 | def get_long_g_pows(exp, n, k): 65 | g_pows = get_g_pows(exp) 66 | long_g_pows = [] 67 | for x, y in g_pows: 68 | long_x, long_y = get_long(n, k, x), get_long(n, k, y) 69 | long_g_pows.append((long_x, long_y)) 70 | return long_g_pows 71 | 72 | 73 | def get_binary(x): 74 | ret = [] 75 | while x > 0: 76 | ret.append(x % 2) 77 | x = x // 2 78 | return ret 79 | 80 | # computes G^exp given precomputed G^1, G^2, G^4, G^8, etc. 81 | 82 | 83 | def get_g_pow_val(g_pows, exp): 84 | binary = get_binary(exp) 85 | is_nonzero = False 86 | curr_sum = None 87 | for idx, val in enumerate(binary): 88 | if val != 0: 89 | if not is_nonzero: 90 | is_nonzero = True 91 | curr_sum = g_pows[idx] 92 | else: 93 | curr_sum = add(curr_sum[0], curr_sum[1], 94 | g_pows[idx][0], g_pows[idx][1]) 95 | return curr_sum 96 | 97 | 98 | def get_cache_str(n, k, stride): 99 | num_strides = math.ceil(n * k / stride) 100 | stride_cache_size = 2 ** stride 101 | ret_str = ''' 102 | function get_g_pow_stride{}_table(n, k) '''.format(stride) 103 | ret_str = ret_str + '{' 104 | ret_str = ret_str + ''' 105 | assert(n == {} && k == {}); 106 | var powers[{}][{}][2][{}]; 107 | '''.format(n, k, num_strides, 2 ** stride, k) 108 | EXP = 256 + stride 109 | g_pows = get_g_pows(EXP) 110 | 111 | for stride_idx in range(num_strides): 112 | for idx in range(2 ** stride): 113 | exp = idx * (2 ** (stride_idx * stride)) 114 | ret_append = '\n' 115 | if exp > 0: 116 | g_pow = get_g_pow_val(g_pows, exp) 117 | long_g_pow = get_long(n, k, g_pow[0]), get_long(n, k, g_pow[1]) 118 | for reg_idx in range(k): 119 | ret_append += ' powers[{}][{}][0][{}] = {};\n'.format( 120 | stride_idx, idx, reg_idx, long_g_pow[0][reg_idx]) 121 | for reg_idx in range(k): 122 | ret_append += ' powers[{}][{}][1][{}] = {};\n'.format( 123 | stride_idx, idx, reg_idx, long_g_pow[1][reg_idx]) 124 | elif exp == 0: 125 | for reg_idx in range(k): 126 | ret_append += ' powers[{}][{}][0][{}] = 0;\n'.format( 127 | stride_idx, idx, reg_idx) 128 | for reg_idx in range(k): 129 | ret_append += ' powers[{}][{}][1][{}] = 0;\n'.format( 130 | stride_idx, idx, reg_idx) 131 | ret_str = ret_str + ret_append 132 | ret_str = ret_str + ''' 133 | return powers; 134 | } 135 | ''' 136 | return ret_str 137 | 138 | 139 | def get_ecdsa_func_str(n, k, stride_list): 140 | ret_str = '''pragma circom 2.1.5; 141 | ''' 142 | for stride in stride_list: 143 | cache_str = get_cache_str(n, k, stride) 144 | ret_str = ret_str + cache_str 145 | return ret_str 146 | 147 | 148 | stride_list = [8] 149 | ecdsa_func_str = get_ecdsa_func_str(43, 6, stride_list) 150 | 151 | orig_stdout = sys.stdout 152 | f = open('../script_outputs/p256_out.circom', 'w') 153 | sys.stdout = f 154 | 155 | print(ecdsa_func_str) 156 | -------------------------------------------------------------------------------- /scripts/groupsign_cli.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | const snarkjs = require('snarkjs'); 3 | const readline = require('readline'); 4 | const util = require('util'); 5 | const { BigNumber, Wallet } = require('ethers'); 6 | const fs = require('fs'); 7 | const wc = require('../build/groupsig/groupsig_js/witness_calculator.js'); 8 | const wasm = './build/groupsig/groupsig_js/groupsig.wasm'; 9 | const zkey = './build/groupsig/groupsig.zkey'; 10 | const vkey = './build/groupsig/vkey.json'; 11 | const wtnsFile = './build/groupsig/witness.wtns'; 12 | function isHex(str) { 13 | if (str.length % 2 !== 0) 14 | return false; 15 | if (str.slice(0, 2) !== '0x') 16 | return false; 17 | const allowedChars = '0123456789abcdefABCDEF'; 18 | for (let i = 2; i < str.length; i++) 19 | if (!allowedChars.includes(str[i])) 20 | return false; 21 | return true; 22 | } 23 | function isValidPrivateKey(privkey) { 24 | if (privkey.length !== 66) 25 | return false; 26 | if (!isHex(privkey)) 27 | return false; 28 | return true; 29 | } 30 | function isValidAddr(addr) { 31 | if (addr.length !== 42) 32 | return false; 33 | if (!isHex(addr)) 34 | return false; 35 | return true; 36 | } 37 | function toWordArray(x, nWords, bitsPerWord) { 38 | const res = []; 39 | let remaining = x; 40 | const base = 2n ** BigInt(bitsPerWord); 41 | for (let i = 0; i < nWords; i++) { 42 | res.push((remaining % base).toString()); 43 | remaining /= base; 44 | } 45 | if (remaining !== 0n) { 46 | throw new Error(`can't represent ${x} as ${nWords} ${bitsPerWord}-bit words`); 47 | } 48 | return res; 49 | } 50 | async function generateWitness(inputs) { 51 | const buffer = fs.readFileSync(wasm); 52 | const witnessCalculator = await wc(buffer); 53 | const buff = await witnessCalculator.calculateWTNSBin(inputs, 0); 54 | fs.writeFileSync(wtnsFile, buff); 55 | } 56 | async function run() { 57 | const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); 58 | const privKeyStr = await new Promise((res) => { 59 | rl.question("Enter an ETH private key:\n", (ans) => { 60 | res(ans); 61 | }); 62 | }); 63 | const wallet = new Wallet(privKeyStr); 64 | console.log(`Your address is: ${wallet.address}`); 65 | const groupAddr1 = await new Promise((res) => { 66 | rl.question("Enter address 1 for your group:\n", (ans) => { 67 | res(ans); 68 | }); 69 | }); 70 | if (!isValidAddr(groupAddr1)) 71 | throw new Error('not a valid ETH address'); 72 | const groupAddr2 = await new Promise((res) => { 73 | rl.question("Enter address 2 for your group:\n", (ans) => { 74 | res(ans); 75 | }); 76 | }); 77 | if (!isValidAddr(groupAddr2)) 78 | throw new Error('not a valid ETH address'); 79 | const idx1 = Math.floor(Math.random() * 3); 80 | let idx2 = Math.floor(Math.random() * 2); 81 | if (idx2 >= idx1) 82 | idx2++; 83 | const idx3 = 3 - idx1 - idx2; 84 | const groupAddresses = []; 85 | groupAddresses[idx1] = BigInt(wallet.address); 86 | groupAddresses[idx2] = BigInt(groupAddr1); 87 | groupAddresses[idx3] = BigInt(groupAddr2); 88 | const msg = await new Promise((res) => { 89 | rl.question("Enter a message to sign (number between 0 and babyjubjubprime - 1):\n", (ans) => { 90 | res(ans); 91 | }); 92 | }); 93 | const input = { 94 | privkey: toWordArray(BigInt(privKeyStr), 4, 64), 95 | addr1: groupAddresses[0], 96 | addr2: groupAddresses[1], 97 | addr3: groupAddresses[2], 98 | msg 99 | }; 100 | console.log(input); 101 | // for some reason fullprove is broken currently: https://github.com/iden3/snarkjs/issues/107 102 | console.log('generating witness...'); 103 | const wtnsStart = Date.now(); 104 | await generateWitness(input); 105 | console.log(`generated witness. took ${Date.now() - wtnsStart}ms`); 106 | const pfStart = Date.now(); 107 | console.log('generating proof...'); 108 | const { proof, publicSignals } = await snarkjs.groth16.prove(zkey, wtnsFile); 109 | console.log(proof); 110 | console.log(publicSignals); 111 | console.log(`generated proof. took ${Date.now() - pfStart}ms`); 112 | const verifyStart = Date.now(); 113 | console.log('verifying proof...'); 114 | const vkeyJson = JSON.parse(fs.readFileSync(vkey)); 115 | const res = await snarkjs.groth16.verify(vkeyJson, publicSignals, proof); 116 | if (res === true) { 117 | console.log("Verification OK"); 118 | console.log(`verified that one of these addresses signed ${publicSignals[4]}:`); 119 | console.log(BigNumber.from(publicSignals[1]).toHexString()); 120 | console.log(BigNumber.from(publicSignals[2]).toHexString()); 121 | console.log(BigNumber.from(publicSignals[3]).toHexString()); 122 | } 123 | else { 124 | console.log("Invalid proof"); 125 | } 126 | console.log(`verification took ${Date.now() - verifyStart}ms`); 127 | process.exit(0); 128 | } 129 | run(); 130 | -------------------------------------------------------------------------------- /scripts/groupsign_cli.ts: -------------------------------------------------------------------------------- 1 | const snarkjs = require('snarkjs'); 2 | const readline = require('readline'); 3 | const util = require('util'); 4 | const { BigNumber, Wallet } = require('ethers'); 5 | const fs = require('fs'); 6 | const wc = require('../build/groupsig/groupsig_js/witness_calculator.js'); 7 | 8 | const wasm = './build/groupsig/groupsig_js/groupsig.wasm'; 9 | const zkey = './build/groupsig/groupsig.zkey'; 10 | const vkey = './build/groupsig/vkey.json'; 11 | const wtnsFile = './build/groupsig/witness.wtns'; 12 | 13 | function isHex(str: string): boolean { 14 | if (str.length % 2 !== 0) return false; 15 | if (str.slice(0, 2) !== '0x') return false; 16 | const allowedChars = '0123456789abcdefABCDEF'; 17 | for (let i = 2; i < str.length; i++) 18 | if (!allowedChars.includes(str[i])) 19 | return false; 20 | return true; 21 | } 22 | 23 | function isValidPrivateKey(privkey: string): boolean { 24 | if (privkey.length !== 66) return false; 25 | if (!isHex(privkey)) return false; 26 | return true; 27 | } 28 | 29 | function isValidAddr(addr: string): boolean { 30 | if (addr.length !== 42) return false; 31 | if (!isHex(addr)) return false; 32 | return true; 33 | } 34 | 35 | function toWordArray(x: bigint, nWords: number, bitsPerWord: number): string[] { 36 | const res: string[] = []; 37 | let remaining = x; 38 | const base = 2n ** BigInt(bitsPerWord); 39 | for (let i = 0; i < nWords; i++) { 40 | res.push((remaining % base).toString()); 41 | remaining /= base; 42 | } 43 | if (remaining !== 0n) { 44 | throw new Error(`can't represent ${x} as ${nWords} ${bitsPerWord}-bit words`); 45 | } 46 | return res; 47 | } 48 | 49 | async function generateWitness(inputs: any) { 50 | const buffer = fs.readFileSync(wasm); 51 | const witnessCalculator = await wc(buffer); 52 | const buff = await witnessCalculator.calculateWTNSBin(inputs, 0); 53 | fs.writeFileSync(wtnsFile, buff); 54 | } 55 | 56 | async function run() { 57 | const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); 58 | 59 | const privKeyStr = await new Promise((res) => { 60 | rl.question("Enter an ETH private key:\n", (ans: string) => { 61 | res(ans); 62 | }) 63 | }) 64 | const wallet = new Wallet(privKeyStr); 65 | console.log(`Your address is: ${wallet.address}`); 66 | 67 | const groupAddr1 = await new Promise((res) => { 68 | rl.question("Enter address 1 for your group:\n", (ans: string) => { 69 | res(ans); 70 | }) 71 | }); 72 | if (!isValidAddr(groupAddr1)) throw new Error('not a valid ETH address'); 73 | const groupAddr2 = await new Promise((res) => { 74 | rl.question("Enter address 2 for your group:\n", (ans: string) => { 75 | res(ans); 76 | }) 77 | }); 78 | if (!isValidAddr(groupAddr2)) throw new Error('not a valid ETH address'); 79 | 80 | const idx1 = Math.floor(Math.random() * 3); 81 | let idx2 = Math.floor(Math.random() * 2); 82 | if (idx2 >= idx1) idx2++; 83 | const idx3 = 3 - idx1 - idx2; 84 | 85 | const groupAddresses = []; 86 | groupAddresses[idx1] = BigInt(wallet.address); 87 | groupAddresses[idx2] = BigInt(groupAddr1); 88 | groupAddresses[idx3] = BigInt(groupAddr2); 89 | 90 | const msg = await new Promise((res) => { 91 | rl.question("Enter a message to sign (number between 0 and babyjubjubprime - 1):\n", (ans: string) => { 92 | res(ans); 93 | }) 94 | }); 95 | 96 | const input = { 97 | privkey: toWordArray(BigInt(privKeyStr), 4, 64), 98 | addr1: groupAddresses[0], 99 | addr2: groupAddresses[1], 100 | addr3: groupAddresses[2], 101 | msg 102 | }; 103 | 104 | console.log(input); 105 | 106 | // for some reason fullprove is broken currently: https://github.com/iden3/snarkjs/issues/107 107 | console.log('generating witness...'); 108 | const wtnsStart = Date.now(); 109 | await generateWitness(input); 110 | console.log(`generated witness. took ${Date.now() - wtnsStart}ms`); 111 | 112 | const pfStart = Date.now(); 113 | console.log('generating proof...'); 114 | const { proof, publicSignals } = await snarkjs.groth16.prove(zkey, wtnsFile); 115 | console.log(proof); 116 | console.log(publicSignals); 117 | console.log(`generated proof. took ${Date.now() - pfStart}ms`); 118 | 119 | const verifyStart = Date.now(); 120 | console.log('verifying proof...'); 121 | 122 | const vkeyJson = JSON.parse(fs.readFileSync(vkey)); 123 | const res = await snarkjs.groth16.verify(vkeyJson, publicSignals, proof); 124 | if (res === true) { 125 | console.log("Verification OK"); 126 | console.log(`verified that one of these addresses signed ${publicSignals[4]}:`); 127 | console.log(BigNumber.from(publicSignals[1]).toHexString()); 128 | console.log(BigNumber.from(publicSignals[2]).toHexString()); 129 | console.log(BigNumber.from(publicSignals[3]).toHexString()); 130 | } else { 131 | console.log("Invalid proof"); 132 | } 133 | console.log(`verification took ${Date.now() - verifyStart}ms`); 134 | 135 | process.exit(0); 136 | } 137 | 138 | run(); 139 | -------------------------------------------------------------------------------- /circuits/p256_func.circom: -------------------------------------------------------------------------------- 1 | /// This file provides methods to grab curve parameter based on various representations 2 | 3 | pragma circom 2.1.5; 4 | 5 | function get_A(n, k) { 6 | assert((n == 86 && k == 3) || (n == 64 && k == 4) || (n == 43 && k ==6)); 7 | var ret[100]; 8 | if (n == 86 && k == 3) { 9 | ret[0] = 77371252455336267181195260; 10 | ret[1] = 1023; 11 | ret[2] = 19342813109330467168976896; 12 | } 13 | 14 | if (n == 64 && k == 4) { 15 | ret[0] = 18446744073709551615; 16 | ret[1] = 4294967295; 17 | ret[2] = 0; 18 | ret[3] = 18446744069414584321; 19 | } 20 | 21 | if (n == 43 && k == 6) { 22 | ret[0] = 8796093022204; 23 | ret[1] = 8796093022207; 24 | ret[2] = 1023; 25 | ret[3] = 0; 26 | ret[4] = 1048576; 27 | ret[5] = 2199023255040; 28 | } 29 | return ret; 30 | } 31 | 32 | //done 33 | function get_B(n,k) { 34 | assert((n == 86 && k == 3) || (n == 64 && k == 4) || (n == 43 && k ==6)); 35 | var ret[100]; 36 | if (n == 86 && k == 3) { 37 | ret[0] = 23805269282153275520606283; 38 | ret[1] = 64478498050055519801623345; 39 | ret[2] = 6858709101169761702330043; 40 | } 41 | 42 | if (n == 64 && k == 4) { 43 | ret[0] = 4309448131093880907; 44 | ret[1] = 7285987128567378166; 45 | ret[2] = 12964664127075681980; 46 | ret[3] = 6540974713487397863; 47 | } 48 | 49 | if (n == 43 && k == 6) { 50 | ret[0] = 4665002582091; 51 | ret[1] = 2706345785799; 52 | ret[2] = 1737114698545; 53 | ret[3] = 7330356544350; 54 | ret[4] = 4025432620731; 55 | ret[5] = 779744948564; 56 | } 57 | 58 | return ret; 59 | } 60 | 61 | //done 62 | function get_p256_prime(n, k) { 63 | assert((n == 86 && k == 3) || (n == 64 && k == 4) || (n == 32 && k == 8) || (n == 43 && k == 6)); 64 | 65 | // done 66 | var ret[100]; 67 | if (n == 86 && k == 3) { 68 | ret[0] = 77371252455336267181195263; 69 | ret[1] = 1023; 70 | ret[2] = 19342813109330467168976896; 71 | } 72 | 73 | // done 74 | if (n == 64 && k == 4) { 75 | ret[0] = 18446744073709551615; 76 | ret[1] = 4294967295; 77 | ret[2] = 0; 78 | ret[3] = 18446744069414584321; 79 | } 80 | 81 | if (n==32 && k==8) { 82 | ret[0] = 4294967295; 83 | ret[1] = 4294967295; 84 | ret[2] = 4294967295; 85 | ret[3] = 0; 86 | ret[4] = 0; 87 | ret[5] = 0; 88 | ret[6] = 1; 89 | ret[7] = 4294967295; 90 | } 91 | 92 | if (n == 43 && k == 6) { 93 | ret[0] = 8796093022207; 94 | ret[1] = 8796093022207; 95 | ret[2] = 1023; 96 | ret[3] = 0; 97 | ret[4] = 1048576; 98 | ret[5] = 2199023255040; 99 | } 100 | return ret; 101 | } 102 | 103 | //done 104 | function get_p256_order(n, k) { 105 | assert((n == 86 && k == 3) || (n == 64 && k == 4) || (n == 43 && k ==6)); 106 | var ret[100]; 107 | 108 | //done 109 | if (n == 86 && k == 3) { 110 | ret[0] = 28553880287938765337601361; 111 | ret[1] = 77371252455335114450843292; 112 | ret[2] = 19342813109330467168976895; 113 | } 114 | 115 | //done 116 | if (n == 64 && k == 4) { 117 | ret[0] = 17562291160714782033; 118 | ret[1] = 13611842547513532036; 119 | ret[2] = 18446744073709551615; 120 | ret[3] = 18446744069414584320; 121 | } 122 | 123 | if (n == 43 && k == 6) { 124 | ret[0] = 3036481267025; 125 | ret[1] = 3246200354617; 126 | ret[2] = 7643362670236; 127 | ret[3] = 8796093022207; 128 | ret[4] = 1048575; 129 | ret[5] = 2199023255040; 130 | } 131 | return ret; 132 | } 133 | 134 | // returns G * 2 ** 255 135 | // TODO check that this is correct... 136 | // DONE: change to P256 generator (double 255 times) 137 | function get_dummy_point(n, k) { 138 | assert(n == 86 && k == 3 || n == 64 && k == 4 || n == 43 && k == 6); 139 | var ret[2][100]; // should be [2][k] 140 | if (k == 3) { 141 | // done 142 | ret[0][0] = 49732730225977125179960148; 143 | ret[0][1] = 43852565336912664664048527; 144 | ret[0][2] = 9043934293559324284618350; 145 | ret[1][0] = 20405083474242608521046015; 146 | ret[1][1] = 57969189420107975911442337; 147 | ret[1][2] = 12380911704996683387468560; 148 | } else if (k == 4) { 149 | // done 150 | ret[0][0] = 4385603450014130423; 151 | ret[0][1] = 5129391198466743360; 152 | ret[0][2] = 5796222465970311708; 153 | ret[0][3] = 10225584345548510712; 154 | ret[1][0] = 8840623018579563820; 155 | ret[1][1] = 13067171496386086; 156 | ret[1][2] = 16363666747424765582; 157 | ret[1][3] = 9735895490635206920; 158 | } else if (k == 6) { 159 | ret[0][0] = 5013155818324; 160 | ret[0][1] = 5653956830653; 161 | ret[0][2] = 1357089440655; 162 | ret[0][3] = 4985459479134; 163 | ret[0][4] = 7362399503982; 164 | ret[0][5] = 1028176290396; 165 | ret[1][0] = 2185447106559; 166 | ret[1][1] = 2319789413632; 167 | ret[1][2] = 3837703653281; 168 | ret[1][3] = 6590333830457; 169 | ret[1][4] = 5404134177552; 170 | ret[1][5] = 1407546699851; 171 | } 172 | return ret; 173 | } 174 | 175 | function get_p256_params() { 176 | var a[100] = get_A(43, 6); 177 | var b[100] = get_B(43, 6); 178 | var p[100] = get_p256_prime(43, 6); 179 | var n[100] = get_p256_order(43, 6); 180 | 181 | var A[6]; 182 | var B[6]; 183 | var P[6]; 184 | var N[6]; 185 | for (var i = 0; i < 6; i++) { 186 | A[i] = a[i]; 187 | B[i] = b[i]; 188 | P[i] = p[i]; 189 | N[i] = n[i]; 190 | } 191 | 192 | return [A,B,P,N]; 193 | } -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point.sym: -------------------------------------------------------------------------------- 1 | 1,1,0,main.out[0][0] 2 | 2,2,0,main.out[0][1] 3 | 3,3,0,main.out[0][2] 4 | 4,4,0,main.out[0][3] 5 | 5,5,0,main.out[0][4] 6 | 6,6,0,main.out[0][5] 7 | 7,7,0,main.out[0][6] 8 | 8,8,0,main.out[0][7] 9 | 9,9,0,main.out[0][8] 10 | 10,10,0,main.out[0][9] 11 | 11,11,0,main.out[0][10] 12 | 12,12,0,main.out[0][11] 13 | 13,13,0,main.out[0][12] 14 | 14,14,0,main.out[0][13] 15 | 15,15,0,main.out[0][14] 16 | 16,16,0,main.out[0][15] 17 | 17,17,0,main.out[0][16] 18 | 18,18,0,main.out[0][17] 19 | 19,19,0,main.out[0][18] 20 | 20,20,0,main.out[0][19] 21 | 21,21,0,main.out[0][20] 22 | 22,22,0,main.out[0][21] 23 | 23,23,0,main.out[0][22] 24 | 24,24,0,main.out[0][23] 25 | 25,25,0,main.out[0][24] 26 | 26,26,0,main.out[0][25] 27 | 27,27,0,main.out[0][26] 28 | 28,28,0,main.out[0][27] 29 | 29,29,0,main.out[0][28] 30 | 30,30,0,main.out[0][29] 31 | 31,31,0,main.out[0][30] 32 | 32,32,0,main.out[0][31] 33 | 33,33,0,main.out[0][32] 34 | 34,34,0,main.out[0][33] 35 | 35,35,0,main.out[0][34] 36 | 36,36,0,main.out[0][35] 37 | 37,37,0,main.out[0][36] 38 | 38,38,0,main.out[0][37] 39 | 39,39,0,main.out[0][38] 40 | 40,40,0,main.out[0][39] 41 | 41,41,0,main.out[0][40] 42 | 42,42,0,main.out[0][41] 43 | 43,43,0,main.out[0][42] 44 | 44,44,0,main.out[0][43] 45 | 45,45,0,main.out[0][44] 46 | 46,46,0,main.out[0][45] 47 | 47,47,0,main.out[0][46] 48 | 48,48,0,main.out[0][47] 49 | 49,49,0,main.out[0][48] 50 | 50,50,0,main.out[0][49] 51 | 51,51,0,main.out[0][50] 52 | 52,52,0,main.out[0][51] 53 | 53,53,0,main.out[0][52] 54 | 54,54,0,main.out[0][53] 55 | 55,55,0,main.out[0][54] 56 | 56,56,0,main.out[0][55] 57 | 57,57,0,main.out[0][56] 58 | 58,58,0,main.out[0][57] 59 | 59,59,0,main.out[0][58] 60 | 60,60,0,main.out[0][59] 61 | 61,61,0,main.out[0][60] 62 | 62,62,0,main.out[0][61] 63 | 63,63,0,main.out[0][62] 64 | 64,64,0,main.out[0][63] 65 | 65,65,0,main.out[0][64] 66 | 66,66,0,main.out[0][65] 67 | 67,67,0,main.out[0][66] 68 | 68,68,0,main.out[0][67] 69 | 69,69,0,main.out[0][68] 70 | 70,70,0,main.out[0][69] 71 | 71,71,0,main.out[0][70] 72 | 72,72,0,main.out[0][71] 73 | 73,73,0,main.out[0][72] 74 | 74,74,0,main.out[0][73] 75 | 75,75,0,main.out[0][74] 76 | 76,76,0,main.out[0][75] 77 | 77,77,0,main.out[0][76] 78 | 78,78,0,main.out[0][77] 79 | 79,79,0,main.out[0][78] 80 | 80,80,0,main.out[0][79] 81 | 81,81,0,main.out[0][80] 82 | 82,82,0,main.out[0][81] 83 | 83,83,0,main.out[0][82] 84 | 84,84,0,main.out[0][83] 85 | 85,85,0,main.out[0][84] 86 | 86,86,0,main.out[0][85] 87 | 87,87,0,main.out[0][86] 88 | 88,88,0,main.out[0][87] 89 | 89,89,0,main.out[0][88] 90 | 90,90,0,main.out[0][89] 91 | 91,91,0,main.out[0][90] 92 | 92,92,0,main.out[0][91] 93 | 93,93,0,main.out[0][92] 94 | 94,94,0,main.out[0][93] 95 | 95,95,0,main.out[0][94] 96 | 96,96,0,main.out[0][95] 97 | 97,97,0,main.out[0][96] 98 | 98,98,0,main.out[0][97] 99 | 99,99,0,main.out[0][98] 100 | 100,100,0,main.out[0][99] 101 | 101,101,0,main.out[1][0] 102 | 102,102,0,main.out[1][1] 103 | 103,103,0,main.out[1][2] 104 | 104,104,0,main.out[1][3] 105 | 105,105,0,main.out[1][4] 106 | 106,106,0,main.out[1][5] 107 | 107,107,0,main.out[1][6] 108 | 108,108,0,main.out[1][7] 109 | 109,109,0,main.out[1][8] 110 | 110,110,0,main.out[1][9] 111 | 111,111,0,main.out[1][10] 112 | 112,112,0,main.out[1][11] 113 | 113,113,0,main.out[1][12] 114 | 114,114,0,main.out[1][13] 115 | 115,115,0,main.out[1][14] 116 | 116,116,0,main.out[1][15] 117 | 117,117,0,main.out[1][16] 118 | 118,118,0,main.out[1][17] 119 | 119,119,0,main.out[1][18] 120 | 120,120,0,main.out[1][19] 121 | 121,121,0,main.out[1][20] 122 | 122,122,0,main.out[1][21] 123 | 123,123,0,main.out[1][22] 124 | 124,124,0,main.out[1][23] 125 | 125,125,0,main.out[1][24] 126 | 126,126,0,main.out[1][25] 127 | 127,127,0,main.out[1][26] 128 | 128,128,0,main.out[1][27] 129 | 129,129,0,main.out[1][28] 130 | 130,130,0,main.out[1][29] 131 | 131,131,0,main.out[1][30] 132 | 132,132,0,main.out[1][31] 133 | 133,133,0,main.out[1][32] 134 | 134,134,0,main.out[1][33] 135 | 135,135,0,main.out[1][34] 136 | 136,136,0,main.out[1][35] 137 | 137,137,0,main.out[1][36] 138 | 138,138,0,main.out[1][37] 139 | 139,139,0,main.out[1][38] 140 | 140,140,0,main.out[1][39] 141 | 141,141,0,main.out[1][40] 142 | 142,142,0,main.out[1][41] 143 | 143,143,0,main.out[1][42] 144 | 144,144,0,main.out[1][43] 145 | 145,145,0,main.out[1][44] 146 | 146,146,0,main.out[1][45] 147 | 147,147,0,main.out[1][46] 148 | 148,148,0,main.out[1][47] 149 | 149,149,0,main.out[1][48] 150 | 150,150,0,main.out[1][49] 151 | 151,151,0,main.out[1][50] 152 | 152,152,0,main.out[1][51] 153 | 153,153,0,main.out[1][52] 154 | 154,154,0,main.out[1][53] 155 | 155,155,0,main.out[1][54] 156 | 156,156,0,main.out[1][55] 157 | 157,157,0,main.out[1][56] 158 | 158,158,0,main.out[1][57] 159 | 159,159,0,main.out[1][58] 160 | 160,160,0,main.out[1][59] 161 | 161,161,0,main.out[1][60] 162 | 162,162,0,main.out[1][61] 163 | 163,163,0,main.out[1][62] 164 | 164,164,0,main.out[1][63] 165 | 165,165,0,main.out[1][64] 166 | 166,166,0,main.out[1][65] 167 | 167,167,0,main.out[1][66] 168 | 168,168,0,main.out[1][67] 169 | 169,169,0,main.out[1][68] 170 | 170,170,0,main.out[1][69] 171 | 171,171,0,main.out[1][70] 172 | 172,172,0,main.out[1][71] 173 | 173,173,0,main.out[1][72] 174 | 174,174,0,main.out[1][73] 175 | 175,175,0,main.out[1][74] 176 | 176,176,0,main.out[1][75] 177 | 177,177,0,main.out[1][76] 178 | 178,178,0,main.out[1][77] 179 | 179,179,0,main.out[1][78] 180 | 180,180,0,main.out[1][79] 181 | 181,181,0,main.out[1][80] 182 | 182,182,0,main.out[1][81] 183 | 183,183,0,main.out[1][82] 184 | 184,184,0,main.out[1][83] 185 | 185,185,0,main.out[1][84] 186 | 186,186,0,main.out[1][85] 187 | 187,187,0,main.out[1][86] 188 | 188,188,0,main.out[1][87] 189 | 189,189,0,main.out[1][88] 190 | 190,190,0,main.out[1][89] 191 | 191,191,0,main.out[1][90] 192 | 192,192,0,main.out[1][91] 193 | 193,193,0,main.out[1][92] 194 | 194,194,0,main.out[1][93] 195 | 195,195,0,main.out[1][94] 196 | 196,196,0,main.out[1][95] 197 | 197,197,0,main.out[1][96] 198 | 198,198,0,main.out[1][97] 199 | 199,199,0,main.out[1][98] 200 | 200,200,0,main.out[1][99] 201 | 201,201,0,main.G[0][0] 202 | 202,-1,0,main.G[0][1] 203 | 203,-1,0,main.G[0][2] 204 | 204,-1,0,main.G[1][0] 205 | 205,-1,0,main.G[1][1] 206 | 206,-1,0,main.G[1][2] 207 | 207,202,0,main.dummy 208 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # circom-ecdsa-p256 2 | 3 | Implementation of ECDSA operations in circom for the P-256 curve. 4 | 5 | ## Project overview 6 | 7 | This repository provides proof-of-concept implementations of ECDSA operations on the P-256 curve in circom. **These implementations are for demonstration purposes only**. These circuits are not audited, and this is not intended to be used as a library for production-grade applications. 8 | 9 | Circuits can be found in `circuits`. `scripts` contains various utility scripts (most importantly, scripts for building a few example zkSNARKs using the ECDSA circuit primitives). `test` contains some unit tests for the circuits, mostly for witness generation. 10 | 11 | ## Information 12 | Due to the nature of the P-256 curved compared to the bn254 circom backend (and Ethereum precompiles), we must used Big Integer representation of the scalars. Please see [this blog post](https://0xparc.org/blog/zk-ecdsa-2) from 0xPARC describing BigInt arithmetic for the original circom-ecdsa implementation. 13 | 14 | Additionally, we utilize Yi-sun's more update BigInt and ECC arithmetic methods from the [circom-pairing library](https://github.com/yi-sun/circom-pairing). 15 | 16 | ## Install dependencies 17 | - Run `git submodule update --init --recursive` 18 | - Run `yarn` at the top level to install npm dependencies (`snarkjs` and `circomlib`). 19 | - You'll also need `circom` version `>= 2.1.5` on your system. Installation instructions [here](https://docs.circom.io/getting-started/installation/). 20 | - Run `yarn` inside of `circuits/circom-pairing` to install npm dependencies for the `circom-pairing` library. 21 | - If you want to build the `pubkeygen`, `eth_addr`, and `groupsig` circuits, you'll need to download a Powers of Tau file with `2^20` constraints and copy it into the `circuits` subdirectory of the project, with the name `pot20_final.ptau`. We do not provide such a file in this repo due to its large size. You can download and copy Powers of Tau files from the Hermez trusted setup from [this repository](https://github.com/iden3/snarkjs#7-prepare-phase-2). 22 | - If you want to build the `verify` circuits, you'll also need a Powers of Tau file that can support at least `2^21` constraints (place it in the same directory as above with the same naming convention). 23 | 24 | ## Building keys and witness generation files 25 | 26 | We provide examples of four circuits using the ECDSA primitives implemented here: 27 | 28 | - `pubkeygen`: Prove knowledge of a private key corresponding to a ECDSA public key. 29 | - `eth_addr`: Prove knowledge of a private key corresponding to an Ethereum address. 30 | - `groupsig`: Prove knowledge of a private key corresponding to one of three Ethereum addresses, and attest to a specific message. 31 | - `verify`: Prove that a ECDSA verification ran properly on a provided signature and message. Note that this circuit does not verify that the public key itself is valid. This must be done separately by the user. 32 | 33 | Run `yarn build:pubkeygen`, `yarn build:eth_addr`, `yarn build:groupsig`, `yarn build:verify` at the top level to compile each respective circuit and keys. 34 | 35 | Each of these will create a subdirectory inside a `build` directory at the top level (which will be created if it doesn't already exist). Inside this directory, the build process will create `r1cs` and `wasm` files for witness generation, as well as a `zkey` file (proving and verifying keys). Note that this process will take several minutes (see full benchmarks below). Building `verify` requires 56G of RAM. 36 | 37 | This process will also generate and verify a proof for a dummy input in the respective `scripts/[circuit_name]` subdirectory, as a smoke test. 38 | 39 | ## Circuits Description 40 | 41 | The following circuits are implemented and can be found in `circuits/ecdsa.circom`. 42 | 43 | - `ECDSAPrivToPub`: Given a secp256k1 private key, outputs the corresponding public key by computing `(private_key) * G` where `G` is the base point of secp256k1. 44 | - `ECDSAVerifyNoPubkeyCheck`: Given a signature `(r, s)`, a message hash, and a secp256k1 public key, it follows ecdsa verification algorithm to extract `r'` from `s`, message hash and public key, and then compares `r'` with `r` to see if the signaure is correct. The output result is `1` if `r'` and `r` are equal, `0` otherwise. 45 | 46 | The 256-bits input and output are chunked and represented as `k` `n`-bits values where `k` is `6` and `n` is `43`. Please see above examples for concrete usages. 47 | 48 | WARNING: Beware that the input to the above circuits should be properly checked and guarded (Lies on the curve, not equal to zero, etc). The purpose of the above circuits is to serve as building blocks but not as stand alone circuits to deploy. 49 | 50 | ## Benchmarks 51 | 52 | All benchmarks were run on an AMD 7700x, 32GB RAM machine 53 | 54 | | | pubkeygen | eth_addr | groupsig | verify | 55 | | ------------------------------------ | --------- | -------- | -------- | ------- | 56 | | Constraints | 114724 | 247380 | 250938 | 1972905 | 57 | | Circuit compilation | 15s | 47s | 48s | 44s | 58 | | Witness generation | 6s | 11s | 12s | 78s | 59 | | Trusted setup phase 2 key generation | 46s | 94s | 98s | 81s | 60 | | Trusted setup phase 2 contribution | 6s | 20s | 19s | 82s | 61 | | Proving key size | 102M | 132M | 134M | 1.2G | 62 | | Proving key verification | 48s | 81s | 80s | 45 | 63 | | Proving time | 3s | 7s | 6s | 26 | 64 | | Proof verification time | <1s | <1s | 1s | 1s | 65 | 66 | ## Testing 67 | 68 | Run `yarn test` at the top level to run tests. Note that these tests only test correctness of witness generation. They do not check that circuits are properly constrained, i.e. that only valid witnesses satisfy the constraints. This is a much harder problem that we're currently working on! 69 | 70 | Circuit unit tests are written in typescript, in the `test` directory using `chai`, `mocha`, and `circom_tester`. Running all tests takes about 1 hour on our 3.3GHz, 64G RAM test machine. To run a subset of the tests, use `yarn test --grep [test_str]` to run all tests whose description matches `[test_str]`. 71 | 72 | ## Groupsig CLI Demo 73 | 74 | You can run a CLI demo of a zkSNARK-enabled group signature generator once you've built the `groupsig` keys. Simply run `yarn groupsig-demo` at the top level and follow the instructions in your terminal. 75 | 76 | ## Acknowledgments 77 | 78 | This project was built during [0xPARC](http://0xparc.org/)'s [Applied ZK Learning Group #1](https://0xparc.org/blog/zk-learning-group). 79 | 80 | We use a [circom implementation of keccak](https://github.com/vocdoni/keccak256-circom) from Vocdoni. We also use some circom utilities for converting an ECDSA public key to an Ethereum address implemented by [lsankar4033](https://github.com/lsankar4033), [jefflau](https://github.com/jefflau), and [veronicaz41](https://github.com/veronicaz41) for another ZK Learning Group project in the same cohort. We use an optimization for big integer multiplication from [xJsnark](https://github.com/akosba/xjsnark). 81 | -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_cpp/fr.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __FR_H 2 | #define __FR_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #define Fr_N64 4 9 | #define Fr_SHORT 0x00000000 10 | #define Fr_LONG 0x80000000 11 | #define Fr_LONGMONTGOMERY 0xC0000000 12 | typedef uint64_t FrRawElement[Fr_N64]; 13 | typedef struct __attribute__((__packed__)) { 14 | int32_t shortVal; 15 | uint32_t type; 16 | FrRawElement longVal; 17 | } FrElement; 18 | typedef FrElement *PFrElement; 19 | extern FrElement Fr_q; 20 | extern FrElement Fr_R3; 21 | extern FrRawElement Fr_rawq; 22 | extern FrRawElement Fr_rawR3; 23 | 24 | extern "C" void Fr_copy(PFrElement r, PFrElement a); 25 | extern "C" void Fr_copyn(PFrElement r, PFrElement a, int n); 26 | extern "C" void Fr_add(PFrElement r, PFrElement a, PFrElement b); 27 | extern "C" void Fr_sub(PFrElement r, PFrElement a, PFrElement b); 28 | extern "C" void Fr_neg(PFrElement r, PFrElement a); 29 | extern "C" void Fr_mul(PFrElement r, PFrElement a, PFrElement b); 30 | extern "C" void Fr_square(PFrElement r, PFrElement a); 31 | extern "C" void Fr_band(PFrElement r, PFrElement a, PFrElement b); 32 | extern "C" void Fr_bor(PFrElement r, PFrElement a, PFrElement b); 33 | extern "C" void Fr_bxor(PFrElement r, PFrElement a, PFrElement b); 34 | extern "C" void Fr_bnot(PFrElement r, PFrElement a); 35 | extern "C" void Fr_shl(PFrElement r, PFrElement a, PFrElement b); 36 | extern "C" void Fr_shr(PFrElement r, PFrElement a, PFrElement b); 37 | extern "C" void Fr_eq(PFrElement r, PFrElement a, PFrElement b); 38 | extern "C" void Fr_neq(PFrElement r, PFrElement a, PFrElement b); 39 | extern "C" void Fr_lt(PFrElement r, PFrElement a, PFrElement b); 40 | extern "C" void Fr_gt(PFrElement r, PFrElement a, PFrElement b); 41 | extern "C" void Fr_leq(PFrElement r, PFrElement a, PFrElement b); 42 | extern "C" void Fr_geq(PFrElement r, PFrElement a, PFrElement b); 43 | extern "C" void Fr_land(PFrElement r, PFrElement a, PFrElement b); 44 | extern "C" void Fr_lor(PFrElement r, PFrElement a, PFrElement b); 45 | extern "C" void Fr_lnot(PFrElement r, PFrElement a); 46 | extern "C" void Fr_toNormal(PFrElement r, PFrElement a); 47 | extern "C" void Fr_toLongNormal(PFrElement r, PFrElement a); 48 | extern "C" void Fr_toMontgomery(PFrElement r, PFrElement a); 49 | 50 | extern "C" int Fr_isTrue(PFrElement pE); 51 | extern "C" int Fr_toInt(PFrElement pE); 52 | 53 | extern "C" void Fr_rawCopy(FrRawElement pRawResult, const FrRawElement pRawA); 54 | extern "C" void Fr_rawSwap(FrRawElement pRawResult, FrRawElement pRawA); 55 | extern "C" void Fr_rawAdd(FrRawElement pRawResult, const FrRawElement pRawA, const FrRawElement pRawB); 56 | extern "C" void Fr_rawSub(FrRawElement pRawResult, const FrRawElement pRawA, const FrRawElement pRawB); 57 | extern "C" void Fr_rawNeg(FrRawElement pRawResult, const FrRawElement pRawA); 58 | extern "C" void Fr_rawMMul(FrRawElement pRawResult, const FrRawElement pRawA, const FrRawElement pRawB); 59 | extern "C" void Fr_rawMSquare(FrRawElement pRawResult, const FrRawElement pRawA); 60 | extern "C" void Fr_rawMMul1(FrRawElement pRawResult, const FrRawElement pRawA, uint64_t pRawB); 61 | extern "C" void Fr_rawToMontgomery(FrRawElement pRawResult, const FrRawElement &pRawA); 62 | extern "C" void Fr_rawFromMontgomery(FrRawElement pRawResult, const FrRawElement &pRawA); 63 | extern "C" int Fr_rawIsEq(const FrRawElement pRawA, const FrRawElement pRawB); 64 | extern "C" int Fr_rawIsZero(const FrRawElement pRawB); 65 | 66 | extern "C" void Fr_fail(); 67 | 68 | 69 | // Pending functions to convert 70 | 71 | void Fr_str2element(PFrElement pE, char const*s, uint base); 72 | char *Fr_element2str(PFrElement pE); 73 | void Fr_idiv(PFrElement r, PFrElement a, PFrElement b); 74 | void Fr_mod(PFrElement r, PFrElement a, PFrElement b); 75 | void Fr_inv(PFrElement r, PFrElement a); 76 | void Fr_div(PFrElement r, PFrElement a, PFrElement b); 77 | void Fr_pow(PFrElement r, PFrElement a, PFrElement b); 78 | 79 | class RawFr { 80 | 81 | public: 82 | const static int N64 = Fr_N64; 83 | const static int MaxBits = 254; 84 | 85 | 86 | struct Element { 87 | FrRawElement v; 88 | }; 89 | 90 | private: 91 | Element fZero; 92 | Element fOne; 93 | Element fNegOne; 94 | 95 | public: 96 | 97 | RawFr(); 98 | ~RawFr(); 99 | 100 | const Element &zero() { return fZero; }; 101 | const Element &one() { return fOne; }; 102 | const Element &negOne() { return fNegOne; }; 103 | Element set(int value); 104 | void set(Element &r, int value); 105 | 106 | void fromString(Element &r, const std::string &n, uint32_t radix = 10); 107 | std::string toString(const Element &a, uint32_t radix = 10); 108 | 109 | void inline copy(Element &r, const Element &a) { Fr_rawCopy(r.v, a.v); }; 110 | void inline swap(Element &a, Element &b) { Fr_rawSwap(a.v, b.v); }; 111 | void inline add(Element &r, const Element &a, const Element &b) { Fr_rawAdd(r.v, a.v, b.v); }; 112 | void inline sub(Element &r, const Element &a, const Element &b) { Fr_rawSub(r.v, a.v, b.v); }; 113 | void inline mul(Element &r, const Element &a, const Element &b) { Fr_rawMMul(r.v, a.v, b.v); }; 114 | 115 | Element inline add(const Element &a, const Element &b) { Element r; Fr_rawAdd(r.v, a.v, b.v); return r;}; 116 | Element inline sub(const Element &a, const Element &b) { Element r; Fr_rawSub(r.v, a.v, b.v); return r;}; 117 | Element inline mul(const Element &a, const Element &b) { Element r; Fr_rawMMul(r.v, a.v, b.v); return r;}; 118 | 119 | Element inline neg(const Element &a) { Element r; Fr_rawNeg(r.v, a.v); return r; }; 120 | Element inline square(const Element &a) { Element r; Fr_rawMSquare(r.v, a.v); return r; }; 121 | 122 | Element inline add(int a, const Element &b) { return add(set(a), b);}; 123 | Element inline sub(int a, const Element &b) { return sub(set(a), b);}; 124 | Element inline mul(int a, const Element &b) { return mul(set(a), b);}; 125 | 126 | Element inline add(const Element &a, int b) { return add(a, set(b));}; 127 | Element inline sub(const Element &a, int b) { return sub(a, set(b));}; 128 | Element inline mul(const Element &a, int b) { return mul(a, set(b));}; 129 | 130 | void inline mul1(Element &r, const Element &a, uint64_t b) { Fr_rawMMul1(r.v, a.v, b); }; 131 | void inline neg(Element &r, const Element &a) { Fr_rawNeg(r.v, a.v); }; 132 | void inline square(Element &r, const Element &a) { Fr_rawMSquare(r.v, a.v); }; 133 | void inv(Element &r, const Element &a); 134 | void div(Element &r, const Element &a, const Element &b); 135 | void exp(Element &r, const Element &base, uint8_t* scalar, unsigned int scalarSize); 136 | 137 | void inline toMontgomery(Element &r, const Element &a) { Fr_rawToMontgomery(r.v, a.v); }; 138 | void inline fromMontgomery(Element &r, const Element &a) { Fr_rawFromMontgomery(r.v, a.v); }; 139 | int inline eq(const Element &a, const Element &b) { return Fr_rawIsEq(a.v, b.v); }; 140 | int inline isZero(const Element &a) { return Fr_rawIsZero(a.v); }; 141 | 142 | void toMpz(mpz_t r, const Element &a); 143 | void fromMpz(Element &a, const mpz_t r); 144 | 145 | int toRprBE(const Element &element, uint8_t *data, int bytes); 146 | int fromRprBE(Element &element, const uint8_t *data, int bytes); 147 | 148 | int bytes ( void ) { return Fr_N64 * 8; }; 149 | 150 | void fromUI(Element &r, unsigned long int v); 151 | 152 | static RawFr field; 153 | 154 | }; 155 | 156 | 157 | #endif // __FR_H 158 | 159 | 160 | 161 | -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_cpp/fr.cpp: -------------------------------------------------------------------------------- 1 | #include "fr.hpp" 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | 9 | static mpz_t q; 10 | static mpz_t zero; 11 | static mpz_t one; 12 | static mpz_t mask; 13 | static size_t nBits; 14 | static bool initialized = false; 15 | 16 | 17 | void Fr_toMpz(mpz_t r, PFrElement pE) { 18 | FrElement tmp; 19 | Fr_toNormal(&tmp, pE); 20 | if (!(tmp.type & Fr_LONG)) { 21 | mpz_set_si(r, tmp.shortVal); 22 | if (tmp.shortVal<0) { 23 | mpz_add(r, r, q); 24 | } 25 | } else { 26 | mpz_import(r, Fr_N64, -1, 8, -1, 0, (const void *)tmp.longVal); 27 | } 28 | } 29 | 30 | void Fr_fromMpz(PFrElement pE, mpz_t v) { 31 | if (mpz_fits_sint_p(v)) { 32 | pE->type = Fr_SHORT; 33 | pE->shortVal = mpz_get_si(v); 34 | } else { 35 | pE->type = Fr_LONG; 36 | for (int i=0; ilongVal[i] = 0; 37 | mpz_export((void *)(pE->longVal), NULL, -1, 8, -1, 0, v); 38 | } 39 | } 40 | 41 | 42 | bool Fr_init() { 43 | if (initialized) return false; 44 | initialized = true; 45 | mpz_init(q); 46 | mpz_import(q, Fr_N64, -1, 8, -1, 0, (const void *)Fr_q.longVal); 47 | mpz_init_set_ui(zero, 0); 48 | mpz_init_set_ui(one, 1); 49 | nBits = mpz_sizeinbase (q, 2); 50 | mpz_init(mask); 51 | mpz_mul_2exp(mask, one, nBits); 52 | mpz_sub(mask, mask, one); 53 | return true; 54 | } 55 | 56 | void Fr_str2element(PFrElement pE, char const *s, uint base) { 57 | mpz_t mr; 58 | mpz_init_set_str(mr, s, base); 59 | mpz_fdiv_r(mr, mr, q); 60 | Fr_fromMpz(pE, mr); 61 | mpz_clear(mr); 62 | } 63 | 64 | char *Fr_element2str(PFrElement pE) { 65 | FrElement tmp; 66 | mpz_t r; 67 | if (!(pE->type & Fr_LONG)) { 68 | if (pE->shortVal>=0) { 69 | char *r = new char[32]; 70 | sprintf(r, "%d", pE->shortVal); 71 | return r; 72 | } else { 73 | mpz_init_set_si(r, pE->shortVal); 74 | mpz_add(r, r, q); 75 | } 76 | } else { 77 | Fr_toNormal(&tmp, pE); 78 | mpz_init(r); 79 | mpz_import(r, Fr_N64, -1, 8, -1, 0, (const void *)tmp.longVal); 80 | } 81 | char *res = mpz_get_str (0, 10, r); 82 | mpz_clear(r); 83 | return res; 84 | } 85 | 86 | void Fr_idiv(PFrElement r, PFrElement a, PFrElement b) { 87 | mpz_t ma; 88 | mpz_t mb; 89 | mpz_t mr; 90 | mpz_init(ma); 91 | mpz_init(mb); 92 | mpz_init(mr); 93 | 94 | Fr_toMpz(ma, a); 95 | // char *s1 = mpz_get_str (0, 10, ma); 96 | // printf("s1 %s\n", s1); 97 | Fr_toMpz(mb, b); 98 | // char *s2 = mpz_get_str (0, 10, mb); 99 | // printf("s2 %s\n", s2); 100 | mpz_fdiv_q(mr, ma, mb); 101 | // char *sr = mpz_get_str (0, 10, mr); 102 | // printf("r %s\n", sr); 103 | Fr_fromMpz(r, mr); 104 | 105 | mpz_clear(ma); 106 | mpz_clear(mb); 107 | mpz_clear(mr); 108 | } 109 | 110 | void Fr_mod(PFrElement r, PFrElement a, PFrElement b) { 111 | mpz_t ma; 112 | mpz_t mb; 113 | mpz_t mr; 114 | mpz_init(ma); 115 | mpz_init(mb); 116 | mpz_init(mr); 117 | 118 | Fr_toMpz(ma, a); 119 | Fr_toMpz(mb, b); 120 | mpz_fdiv_r(mr, ma, mb); 121 | Fr_fromMpz(r, mr); 122 | 123 | mpz_clear(ma); 124 | mpz_clear(mb); 125 | mpz_clear(mr); 126 | } 127 | 128 | void Fr_pow(PFrElement r, PFrElement a, PFrElement b) { 129 | mpz_t ma; 130 | mpz_t mb; 131 | mpz_t mr; 132 | mpz_init(ma); 133 | mpz_init(mb); 134 | mpz_init(mr); 135 | 136 | Fr_toMpz(ma, a); 137 | Fr_toMpz(mb, b); 138 | mpz_powm(mr, ma, mb, q); 139 | Fr_fromMpz(r, mr); 140 | 141 | mpz_clear(ma); 142 | mpz_clear(mb); 143 | mpz_clear(mr); 144 | } 145 | 146 | void Fr_inv(PFrElement r, PFrElement a) { 147 | mpz_t ma; 148 | mpz_t mr; 149 | mpz_init(ma); 150 | mpz_init(mr); 151 | 152 | Fr_toMpz(ma, a); 153 | mpz_invert(mr, ma, q); 154 | Fr_fromMpz(r, mr); 155 | mpz_clear(ma); 156 | mpz_clear(mr); 157 | } 158 | 159 | void Fr_div(PFrElement r, PFrElement a, PFrElement b) { 160 | FrElement tmp; 161 | Fr_inv(&tmp, b); 162 | Fr_mul(r, a, &tmp); 163 | } 164 | 165 | void Fr_fail() { 166 | assert(false); 167 | } 168 | 169 | 170 | RawFr::RawFr() { 171 | Fr_init(); 172 | set(fZero, 0); 173 | set(fOne, 1); 174 | neg(fNegOne, fOne); 175 | } 176 | 177 | RawFr::~RawFr() { 178 | } 179 | 180 | void RawFr::fromString(Element &r, const std::string &s, uint32_t radix) { 181 | mpz_t mr; 182 | mpz_init_set_str(mr, s.c_str(), radix); 183 | mpz_fdiv_r(mr, mr, q); 184 | for (int i=0; i>3] & (1 << (p & 0x7))) 256 | void RawFr::exp(Element &r, const Element &base, uint8_t* scalar, unsigned int scalarSize) { 257 | bool oneFound = false; 258 | Element copyBase; 259 | copy(copyBase, base); 260 | for (int i=scalarSize*8-1; i>=0; i--) { 261 | if (!oneFound) { 262 | if ( !BIT_IS_SET(scalar, i) ) continue; 263 | copy(r, copyBase); 264 | oneFound = true; 265 | continue; 266 | } 267 | square(r, r); 268 | if ( BIT_IS_SET(scalar, i) ) { 269 | mul(r, r, copyBase); 270 | } 271 | } 272 | if (!oneFound) { 273 | copy(r, fOne); 274 | } 275 | } 276 | 277 | void RawFr::toMpz(mpz_t r, const Element &a) { 278 | Element tmp; 279 | Fr_rawFromMontgomery(tmp.v, a.v); 280 | mpz_import(r, Fr_N64, -1, 8, -1, 0, (const void *)tmp.v); 281 | } 282 | 283 | void RawFr::fromMpz(Element &r, const mpz_t a) { 284 | for (int i=0; i 0) { 49 | var mod: bigint = x % 2n ** small_stride; 50 | ret = ret + mod * 2n ** (stride * exp); 51 | x = x / 2n ** small_stride; 52 | exp = exp + 1n; 53 | } 54 | return ret; 55 | } 56 | 57 | describe('ECDSAPrivToPub', function () { 58 | this.timeout(1000 ** 10); 59 | 60 | // runs circom compilation 61 | let circuit: any; 62 | before(async function () { 63 | circuit = await wasm_tester(path.join(__dirname, 'circuits_p256', 'test_ecdsa.circom')); 64 | }); 65 | 66 | // privkey, pub0, pub1 67 | var test_cases: Array<[bigint, bigint, bigint]> = []; 68 | 69 | // 4 randomly generated privkeys 70 | var privkeys: Array = [ 71 | 88549154299169935420064281163296845505587953610183896504176354567359434168161n, 72 | 37706893564732085918706190942542566344879680306879183356840008504374628845468n, 73 | 90388020393783788847120091912026443124559466591761394939671630294477859800601n, 74 | 110977009687373213104962226057480551605828725303063265716157300460694423838923n, 75 | ]; 76 | 77 | // 16 more keys 78 | for (var cnt = 1n; cnt < 2n ** 4n; cnt++) { 79 | var privkey: bigint = get_strided_bigint(10n, 1n, cnt); 80 | privkeys.push(privkey); 81 | } 82 | 83 | for (var idx = 0; idx < privkeys.length; idx++) { 84 | var pubkey = P256.ProjectivePoint.fromPrivateKey(privkeys[idx]); 85 | test_cases.push([privkeys[idx], pubkey.x, pubkey.y]); 86 | } 87 | 88 | var test_ecdsa_instance = function (keys: [bigint, bigint, bigint]) { 89 | let privkey = keys[0]; 90 | let pub0 = keys[1]; 91 | let pub1 = keys[2]; 92 | 93 | var priv_tuple = bigint_to_tuple(privkey); 94 | var pub0_tuple = bigint_to_tuple(pub0); 95 | var pub1_tuple = bigint_to_tuple(pub1); 96 | 97 | it( 98 | 'Testing privkey: ' + privkey + ' pubkey.x: ' + pub0 + ' pubkey.y: ' + pub1, 99 | async function () { 100 | let witness = await circuit.calculateWitness({ privkey: priv_tuple }); 101 | expect(witness[1]).to.equal(pub0_tuple[0]); 102 | expect(witness[2]).to.equal(pub0_tuple[1]); 103 | expect(witness[3]).to.equal(pub0_tuple[2]); 104 | expect(witness[4]).to.equal(pub0_tuple[3]); 105 | expect(witness[5]).to.equal(pub0_tuple[4]); 106 | expect(witness[6]).to.equal(pub0_tuple[5]); 107 | expect(witness[7]).to.equal(pub1_tuple[0]); 108 | expect(witness[8]).to.equal(pub1_tuple[1]); 109 | expect(witness[9]).to.equal(pub1_tuple[2]); 110 | expect(witness[10]).to.equal(pub1_tuple[3]); 111 | expect(witness[11]).to.equal(pub1_tuple[4]); 112 | expect(witness[12]).to.equal(pub1_tuple[5]); 113 | //await circuit.checkConstraints(witness); 114 | } 115 | ); 116 | }; 117 | 118 | test_cases.forEach(test_ecdsa_instance); 119 | }); 120 | 121 | // bigendian 122 | function bigint_to_Uint8Array(x: bigint) { 123 | var ret: Uint8Array = new Uint8Array(32); 124 | for (var idx = 31; idx >= 0; idx--) { 125 | ret[idx] = Number(x % 256n); 126 | x = x / 256n; 127 | } 128 | return ret; 129 | } 130 | 131 | // bigendian 132 | function Uint8Array_to_bigint(x: Uint8Array) { 133 | var ret: bigint = 0n; 134 | for (var idx = 0; idx < x.length; idx++) { 135 | ret = ret * 256n; 136 | ret = ret + BigInt(x[idx]); 137 | } 138 | return ret; 139 | } 140 | 141 | describe('ECDSAVerifyNoPubkeyCheck', function () { 142 | this.timeout(1000 ** 10); 143 | 144 | // privkey, msghash, pub0, pub1 145 | var test_cases: Array<[bigint, bigint, bigint, bigint]> = []; 146 | var privkeys: Array = [ 147 | 88549154299169935420064281163296845505587953610183896504176354567359434168161n, 148 | 37706893564732085918706190942542566344879680306879183356840008504374628845468n, 149 | 90388020393783788847120091912026443124559466591761394939671630294477859800601n, 150 | 110977009687373213104962226057480551605828725303063265716157300460694423838923n, 151 | ]; 152 | for (var idx = 0; idx < privkeys.length; idx++) { 153 | var pubkey = P256.ProjectivePoint.fromPrivateKey(privkeys[idx]); 154 | var msghash_bigint: bigint = 1234n; 155 | test_cases.push([privkeys[idx], msghash_bigint, pubkey.x, pubkey.y]); 156 | } 157 | 158 | let circuit: any; 159 | before(async function () { 160 | circuit = await wasm_tester(path.join(__dirname, 'circuits_p256', 'test_ecdsa_verify.circom')); 161 | }); 162 | 163 | var test_ecdsa_verify = function (test_case: [bigint, bigint, bigint, bigint]) { 164 | let privkey = test_case[0]; 165 | let msghash_bigint = test_case[1]; 166 | let pub0 = test_case[2]; 167 | let pub1 = test_case[3]; 168 | 169 | var msghash: Uint8Array = bigint_to_Uint8Array(msghash_bigint); 170 | 171 | it( 172 | 'Testing correct sig: privkey: ' + 173 | privkey + 174 | ' msghash: ' + 175 | msghash_bigint + 176 | ' pub0: ' + 177 | pub0 + 178 | ' pub1: ' + 179 | pub1, 180 | async function () { 181 | // in compact format: r (big-endian), 32-bytes + s (big-endian), 32-bytes 182 | var sig: SignatureType = P256.sign(msghash, privkey); 183 | 184 | var r: bigint = sig.r; 185 | var s: bigint = sig.s; 186 | 187 | var priv_array: bigint[] = bigint_to_array(43, 6, privkey); 188 | var r_array: bigint[] = bigint_to_array(43, 6, r); 189 | var s_array: bigint[] = bigint_to_array(43, 6, s); 190 | var msghash_array: bigint[] = bigint_to_array(43, 6, msghash_bigint); 191 | var pub0_array: bigint[] = bigint_to_array(43, 6, pub0); 192 | var pub1_array: bigint[] = bigint_to_array(43, 6, pub1); 193 | var res = 1n; 194 | 195 | let witness = await circuit.calculateWitness({ 196 | r: r_array, 197 | s: s_array, 198 | msghash: msghash_array, 199 | pubkey: [pub0_array, pub1_array], 200 | }); 201 | expect(witness[1]).to.equal(res); 202 | await circuit.checkConstraints(witness); 203 | } 204 | ); 205 | 206 | it( 207 | 'Testing incorrect sig: privkey: ' + 208 | privkey + 209 | ' msghash: ' + 210 | msghash_bigint + 211 | ' pub0: ' + 212 | pub0 + 213 | ' pub1: ' + 214 | pub1, 215 | async function () { 216 | // in compact format: r (big-endian), 32-bytes + s (big-endian), 32-bytes 217 | var sig: SignatureType = P256.sign(msghash, privkey); 218 | var r = sig.r; 219 | var s = sig.s; 220 | 221 | var priv_array: bigint[] = bigint_to_array(43, 6, privkey); 222 | var r_array: bigint[] = bigint_to_array(43, 6, r + 1n); 223 | var s_array: bigint[] = bigint_to_array(43, 6, s); 224 | var msghash_array: bigint[] = bigint_to_array(43, 6, msghash_bigint); 225 | var pub0_array: bigint[] = bigint_to_array(43, 6, pub0); 226 | var pub1_array: bigint[] = bigint_to_array(43, 6, pub1); 227 | var res = 0n; 228 | 229 | let witness = await circuit.calculateWitness({ 230 | r: r_array, 231 | s: s_array, 232 | msghash: msghash_array, 233 | pubkey: [pub0_array, pub1_array], 234 | }); 235 | expect(witness[1]).to.equal(res); 236 | await circuit.checkConstraints(witness); 237 | } 238 | ); 239 | }; 240 | 241 | test_cases.forEach(test_ecdsa_verify); 242 | }); -------------------------------------------------------------------------------- /scratch/scratch.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | # import sys 4 | # sys.path.append('/Users/jbel/circom-ecdsa-p256/scripts') 5 | # from compute_p256_math import get_long 6 | # all signals in circom are taken mod this 254-bit prime 7 | babyjubjub_prime = ( 8 | 21888242871839275222246405745257275088548364400416034343698204186575808495617 9 | ) 10 | 11 | # size of the base field of p256 curve 12 | P = 115792089210356248762697446949407573530086143415290314195533631308867097853951 13 | 14 | # 32-bit register numbers (with overflow) 15 | 16 | 17 | def mod_p(n): 18 | return n % P 19 | 20 | 21 | def get_long(n, k, x): 22 | ret = [] 23 | for idx in range(k): 24 | ret.append(x % (2**n)) 25 | x = x // (2**n) 26 | return ret 27 | 28 | 29 | print(f"p in (32,8) representation = {get_long(32, 8, P)}") 30 | 31 | 32 | def get_short(num, n): 33 | result = 0 34 | for i in range(len(num)): 35 | result += num[i] * (2 ** (n * i)) 36 | return result 37 | 38 | 39 | prime_reduce_coeffs = [ 40 | [1, 0, 0, 0, 0, 0, 0, 0], 41 | [0, 0, 1, 0, 0, 0, 0, 0], 42 | [0, 0, 0, 0, 1, 0, 0, 0], 43 | [0, 0, 0, 0, 0, 0, 1, 0], 44 | [1, 0, 0, 4294967295, 4294967295, 4294967295, 4294967294, 0], 45 | [4294967295, 0, 1, 1, 4294967295, 4294967294, 0, 4294967294], 46 | [4294967294, 4294967294, 4294967295, 2, 2, 0, 1, 4294967294], 47 | [4294967295, 4294967294, 4294967294, 4294967295, 0, 2, 3, 0], 48 | [3, 0, 4294967295, 4294967291, 4294967294, 4294967295, 4294967293, 4], 49 | [2, 5, 3, 4294967294, 4294967289, 4294967291, 4294967292, 4294967292], 50 | ] 51 | 52 | 53 | def prime_reduce(input): 54 | out = [0] * 8 55 | for i in range(8): 56 | for j in range(10): 57 | out[i] += prime_reduce_coeffs[j][i] * input[j] 58 | return out 59 | 60 | 61 | # (n,k) = (64,10) 62 | circuit_input = [ 63 | 5477309056849665717288716933014530289923633976480703436866, 64 | 7994216246134738029693926913849331298100776613932837736787, 65 | 20597098804255160793536094346835435858891034312844008526976, 66 | 24081142476053152383489765775694493403995489760583505812692, 67 | 27942342172107885265743448700002544394917721576194116489877, 68 | 24596188685839422727699595064634599767343330143182270193146, 69 | 16023950495310598602403058560280021190668293464541717344875, 70 | 8969210184645150594009334345186397937285283576086984532980, 71 | 3202027368135246498762305357242428206209218255498458103798, 72 | 459539768467051557235386925911389314767911436845848222743, 73 | ] 74 | input_w_negs = circuit_input 75 | 76 | 77 | print( 78 | f"am i going crazy: {(babyjubjub_prime * (2**(64*5) + 2**(64*6) + 2**(64*7))) % P == 0}" 79 | ) 80 | 81 | # input_w_negs = [ 82 | # 4292955422453145964822479413621913075509602355677488716324, 83 | # 14138856352885911993756608258123408875015425226836977408445, 84 | # 19152084246042552967396910108811035673348399945778457592706, 85 | # 12217327447688951856114508225080847269707233820600705128337, 86 | # 1256809376368187748897015378026120801835577723245181144683, 87 | # -5357144585194727522208286995229502672918395199066236896292, 88 | # -5701009903066879220160354445995883352949269859399558567664, 89 | # -1857735208184233489713766934499120265226159210590079992716, 90 | # 923200339955551664594468325804491929844512499798227728984, 91 | # 661957230541661508833462765560680486656693245077732287604, 92 | # ] 93 | 94 | 95 | # def check_prime_reduce(negs): 96 | # if negs: 97 | # input_used = input_w_negs 98 | # else: 99 | # input_used = input 100 | # prime_reduce_out = prime_reduce(input_used) 101 | # prime_reduce_circuit_short = get_short(prime_reduce_out, 32) 102 | # print(f"prime reduce python output = {prime_reduce_out}") 103 | # in_short = get_short(input_used, 64) 104 | # # only true with negative inputs (yeah that's expected) 105 | # print(f"input is a multiple of P? {in_short % P == 0}") 106 | 107 | # print( 108 | # f"python prime reduce congruent to input mod P? {((prime_reduce_circuit_short - in_short) % P) == 0}" 109 | # ) 110 | 111 | 112 | # check_prime_reduce(True) 113 | 114 | 115 | # (n,k) = (32, 8) 116 | circuit_prime_reduce_out = [ 117 | 212984633734340117457950005240404110997764362411455218235427886251043, 118 | 107344807696394443008193267451432838599413561113649140947292848988085, 119 | 121097410567925527747491283184918165818408843075108549773998103103817, 120 | 174260221323464569417405159296157643949761220910431163705143072183371, 121 | 241377582909071380053420916522157321980790853004028240516166397985850, 122 | 241377582853889718847064786597367263348198777706772897412420808191222, 123 | 135737756906344003311852332811587327479264066512141530003054698440115, 124 | 176435877548514631810737913768421906383243055684255327039735124422322, 125 | ] 126 | 127 | expected_prime_reduce_out = prime_reduce(circuit_input) 128 | 129 | print( 130 | f"circuit computed prime reduce out correctly? {circuit_prime_reduce_out == expected_prime_reduce_out}" 131 | ) 132 | 133 | 134 | # after adding large multiple of p (i.e. should be positive) 135 | # (n,k) = (32, 8) 136 | circuit_reduced = [ 137 | 55426955395203346062864074699120910991877335319596923709273278994234403, 138 | 55321315569165400388414317961331939719478984518299117631985143956971445, 139 | 55335068172036931473153615977065425046697979800260577040811849211087177, 140 | 174260221323464569417405159296157643949761220910431163705143072183371, 141 | 241377582909071380053420916522157321980790853004028240516166397985850, 142 | 241377582853889718847064786597367263348198777706772897412420808191222, 143 | 135737769761848357383774537147284066208564886689765480265397380851123, 144 | 55390406639017520577216862607648928787262814012869723818077586232405682, 145 | ] 146 | 147 | circuit_prime_reduce_out_bigint = get_short(circuit_prime_reduce_out, 32) 148 | circuit_reduced_bigint = get_short(circuit_reduced, 32) 149 | print( 150 | f"circuit reduced is congruent to output of prime_reduce mod P? {(circuit_prime_reduce_out_bigint-circuit_reduced_bigint) % P == 0}" 151 | ) 152 | 153 | # (n,k) = (32, 16) 154 | circuit_proper = [ 155 | 1546435619, 156 | 2297931848, 157 | 4168434873, 158 | 3647777780, 159 | 2206504338, 160 | 14694086, 161 | 1298502331, 162 | 845341814, 163 | 167700765, 164 | 175910939, 165 | 1495087567, 166 | 1703443683, 167 | 2767007255, 168 | 2338051116, 169 | 2054, 170 | 0, 171 | ] 172 | 173 | expected_proper = get_long(32, 16, get_short(circuit_reduced, 32)) 174 | print( 175 | f"circuit computed proper of reduced correctly? {expected_proper == circuit_proper}" 176 | ) 177 | 178 | circuit_q = [2125042186, 860905375, 860478079, 175481588, 810091076, 2338053171, 2054] 179 | 180 | # expected_q_literal = [0, 0, 0, 0, 813694976, 2338053171, 2054] 181 | 182 | expected_q_short = int(get_short(circuit_proper, 32) / P) 183 | expected_q_long = get_long(32, 7, expected_q_short) 184 | print(f"expected q = {expected_q_long}") 185 | print(f"circuit computed q := proper/P correctly? {circuit_q == expected_q_long}") 186 | 187 | # (n,k) = (32, 14) 188 | # even with correct q and qpprod, entire circuit still failing? 189 | circuit_qpProd_with_correct_q = [ 190 | 0, 191 | 0, 192 | 0, 193 | 0, 194 | 3494793310025809920, 195 | 13536655213441852365, 196 | 13536664035304676295, 197 | 10041870725278866375, 198 | 8821862823930, 199 | 0, 200 | 813694976, 201 | 3494793312363863091, 202 | 10041861903416044499, 203 | 8821862823930, 204 | ] 205 | 206 | circuit_qpProd_with_incorrect_q = [ 207 | 9126986689365306870, 208 | 12824547119080017495, 209 | 16520272326449443800, 210 | 8146973318418801390, 211 | 7928727566095450185, 212 | 14274864262142066325, 213 | 13521185404795267981, 214 | 19168857415505078620, 215 | 3697569252438012634, 216 | 3695725207544907893, 217 | 753687682144755536, 218 | 3479314679729412591, 219 | 10041861903416044499, 220 | 8821862823930, 221 | ] 222 | 223 | circuit_qpProd_with_correct_q_bigint = get_short(circuit_qpProd_with_correct_q, 32) 224 | print( 225 | f"circuit qpprod = q*p? {circuit_qpProd_with_correct_q_bigint == expected_q_short*P}" 226 | ) 227 | # so product is correct, just computation of q is failing 228 | 21888187444883880018900342881182575967637372523080714746774494913296814261214 229 | 21888187550523706056846017330939313756608644921431516044580572201431851524172 230 | 21888187536771103185314932591641298023123317702436234083121163374726597408440 231 | 21888242697579053898781836327852115792390720450654813433267040481432736312246 232 | 21888242630461692313175025691836358566391042419625181339673458463719436319687 233 | 21888242630461692368356686898192488491181101052217256636938843429368442156760 234 | 21888242736101505460398048361482737941264298191851147653946260585213732320789 235 | 21888187481432636204725828528394667439619577137602021473984427979714854956310 236 | 8821862823930 237 | 0 238 | 813694976 239 | 3494793312363863091 240 | 10041861903416044499 241 | -------------------------------------------------------------------------------- /circuits/ecdsa.circom: -------------------------------------------------------------------------------- 1 | /// This file implements the ECDSA verification algorithm along with public key generation (xG) 2 | 3 | pragma circom 2.1.5; 4 | 5 | include "../node_modules/circomlib/circuits/multiplexer.circom"; 6 | 7 | include "p256.circom"; 8 | include "ecdsa_func.circom"; 9 | include "p256_func.circom"; 10 | 11 | // keys are encoded as (x, y) pairs with each coordinate being 12 | // encoded with k registers of n bits each 13 | template ECDSAPrivToPub(n, k) { 14 | var stride = 8; 15 | signal input privkey[k]; 16 | signal output pubkey[2][k]; 17 | 18 | component n2b[k]; 19 | for (var i = 0; i < k; i++) { 20 | n2b[i] = Num2Bits(n); 21 | n2b[i].in <== privkey[i]; 22 | } 23 | 24 | var num_strides = div_ceil(n * k, stride); 25 | // power[i][j] contains: [j * (1 << stride * i) * G] for 1 <= j < (1 << stride) 26 | var powers[num_strides][2 ** stride][2][k]; 27 | powers = get_g_pow_stride8_table(n, k); 28 | 29 | // contains a dummy point G * 2 ** 255 to stand in when we are adding 0 30 | // this point is sometimes an input into AddUnequal, so it must be guaranteed 31 | // to never equal any possible partial sum that we might get 32 | var dummyHolder[2][100] = get_dummy_point(n, k); 33 | var dummy[2][k]; 34 | for (var i = 0; i < k; i++) dummy[0][i] = dummyHolder[0][i]; 35 | for (var i = 0; i < k; i++) dummy[1][i] = dummyHolder[1][i]; 36 | 37 | // selector[i] contains a value in [0, ..., 2**i - 1] 38 | component selectors[num_strides]; 39 | for (var i = 0; i < num_strides; i++) { 40 | selectors[i] = Bits2Num(stride); 41 | for (var j = 0; j < stride; j++) { 42 | var bit_idx1 = (i * stride + j) \ n; 43 | var bit_idx2 = (i * stride + j) % n; 44 | if (bit_idx1 < k) { 45 | selectors[i].in[j] <== n2b[bit_idx1].out[bit_idx2]; 46 | } else { 47 | selectors[i].in[j] <== 0; 48 | } 49 | } 50 | } 51 | 52 | // multiplexers[i][l].out will be the coordinates of: 53 | // selectors[i].out * (2 ** (i * stride)) * G if selectors[i].out is non-zero 54 | // (2 ** 255) * G if selectors[i].out is zero 55 | component multiplexers[num_strides][2]; 56 | // select from k-register outputs using a 2 ** stride bit selector 57 | for (var i = 0; i < num_strides; i++) { 58 | for (var l = 0; l < 2; l++) { 59 | multiplexers[i][l] = Multiplexer(k, (1 << stride)); 60 | multiplexers[i][l].sel <== selectors[i].out; 61 | for (var idx = 0; idx < k; idx++) { 62 | multiplexers[i][l].inp[0][idx] <== dummy[l][idx]; 63 | for (var j = 1; j < (1 << stride); j++) { 64 | multiplexers[i][l].inp[j][idx] <== powers[i][j][l][idx]; 65 | } 66 | } 67 | } 68 | } 69 | 70 | component iszero[num_strides]; 71 | for (var i = 0; i < num_strides; i++) { 72 | iszero[i] = IsZero(); 73 | iszero[i].in <== selectors[i].out; 74 | } 75 | 76 | // has_prev_nonzero[i] = 1 if at least one of the selections in privkey up to stride i is non-zero 77 | component has_prev_nonzero[num_strides]; 78 | has_prev_nonzero[0] = OR(); 79 | has_prev_nonzero[0].a <== 0; 80 | has_prev_nonzero[0].b <== 1 - iszero[0].out; 81 | for (var i = 1; i < num_strides; i++) { 82 | has_prev_nonzero[i] = OR(); 83 | has_prev_nonzero[i].a <== has_prev_nonzero[i - 1].out; 84 | has_prev_nonzero[i].b <== 1 - iszero[i].out; 85 | } 86 | 87 | signal partial[num_strides][2][k]; 88 | for (var idx = 0; idx < k; idx++) { 89 | for (var l = 0; l < 2; l++) { 90 | partial[0][l][idx] <== multiplexers[0][l].out[idx]; 91 | } 92 | } 93 | 94 | component adders[num_strides - 1]; 95 | signal intermed1[num_strides - 1][2][k]; 96 | signal intermed2[num_strides - 1][2][k]; 97 | for (var i = 1; i < num_strides; i++) { 98 | adders[i - 1] = P256AddUnequal(n, k); 99 | for (var idx = 0; idx < k; idx++) { 100 | for (var l = 0; l < 2; l++) { 101 | adders[i - 1].a[l][idx] <== partial[i - 1][l][idx]; 102 | adders[i - 1].b[l][idx] <== multiplexers[i][l].out[idx]; 103 | } 104 | } 105 | 106 | // partial[i] = has_prev_nonzero[i - 1] * ((1 - iszero[i]) * adders[i - 1].out + iszero[i] * partial[i - 1][0][idx]) 107 | // + (1 - has_prev_nonzero[i - 1]) * (1 - iszero[i]) * multiplexers[i] 108 | for (var idx = 0; idx < k; idx++) { 109 | for (var l = 0; l < 2; l++) { 110 | intermed1[i - 1][l][idx] <== iszero[i].out * (partial[i - 1][l][idx] - adders[i - 1].out[l][idx]) + adders[i - 1].out[l][idx]; 111 | intermed2[i - 1][l][idx] <== multiplexers[i][l].out[idx] - iszero[i].out * multiplexers[i][l].out[idx]; 112 | partial[i][l][idx] <== has_prev_nonzero[i - 1].out * (intermed1[i - 1][l][idx] - intermed2[i - 1][l][idx]) + intermed2[i - 1][l][idx]; 113 | } 114 | } 115 | } 116 | 117 | for (var i = 0; i < k; i++) { 118 | for (var l = 0; l < 2; l++) { 119 | pubkey[l][i] <== partial[num_strides - 1][l][i]; 120 | } 121 | } 122 | } 123 | 124 | // r, s, msghash, and pubkey have coordinates 125 | // encoded with k registers of n bits each 126 | // signature is (r, s) 127 | // Does not check that pubkey is valid 128 | template ECDSAVerifyNoPubkeyCheck(n, k) { 129 | assert(k >= 2); 130 | assert(k <= 100); 131 | 132 | signal input r[k]; 133 | signal input s[k]; 134 | signal input msghash[k]; 135 | signal input pubkey[2][k]; 136 | 137 | signal output result; 138 | 139 | var p[100] = get_p256_prime(n, k); 140 | var order[100] = get_p256_order(n, k); 141 | 142 | // compute multiplicative inverse of s mod n 143 | var sinv_comp[100] = mod_inv(n, k, s, order); 144 | signal sinv[k]; 145 | component sinv_range_checks[k]; 146 | for (var idx = 0; idx < k; idx++) { 147 | sinv[idx] <-- sinv_comp[idx]; 148 | sinv_range_checks[idx] = Num2Bits(n); 149 | sinv_range_checks[idx].in <== sinv[idx]; 150 | } 151 | component sinv_check = BigMultModP(n, k); 152 | for (var idx = 0; idx < k; idx++) { 153 | sinv_check.a[idx] <== sinv[idx]; 154 | sinv_check.b[idx] <== s[idx]; 155 | sinv_check.p[idx] <== order[idx]; 156 | } 157 | for (var idx = 0; idx < k; idx++) { 158 | if (idx > 0) { 159 | sinv_check.out[idx] === 0; 160 | } 161 | if (idx == 0) { 162 | sinv_check.out[idx] === 1; 163 | } 164 | } 165 | 166 | // compute (h * sinv) mod n 167 | component g_coeff = BigMultModP(n, k); 168 | for (var idx = 0; idx < k; idx++) { 169 | g_coeff.a[idx] <== sinv[idx]; 170 | g_coeff.b[idx] <== msghash[idx]; 171 | g_coeff.p[idx] <== order[idx]; 172 | } 173 | 174 | // compute (h * sinv) * G 175 | component g_mult = ECDSAPrivToPub(n, k); 176 | for (var idx = 0; idx < k; idx++) { 177 | g_mult.privkey[idx] <== g_coeff.out[idx]; 178 | } 179 | 180 | // compute (r * sinv) mod n 181 | component pubkey_coeff = BigMultModP(n, k); 182 | for (var idx = 0; idx < k; idx++) { 183 | pubkey_coeff.a[idx] <== sinv[idx]; 184 | pubkey_coeff.b[idx] <== r[idx]; 185 | pubkey_coeff.p[idx] <== order[idx]; 186 | } 187 | 188 | // compute (r * sinv) * pubkey 189 | component pubkey_mult = P256ScalarMult(n, k); 190 | for (var idx = 0; idx < k; idx++) { 191 | pubkey_mult.scalar[idx] <== pubkey_coeff.out[idx]; 192 | pubkey_mult.point[0][idx] <== pubkey[0][idx]; 193 | pubkey_mult.point[1][idx] <== pubkey[1][idx]; 194 | } 195 | 196 | // compute (h * sinv) * G + (r * sinv) * pubkey 197 | component sum_res = P256AddUnequal(n, k); 198 | for (var idx = 0; idx < k; idx++) { 199 | sum_res.a[0][idx] <== g_mult.pubkey[0][idx]; 200 | sum_res.a[1][idx] <== g_mult.pubkey[1][idx]; 201 | sum_res.b[0][idx] <== pubkey_mult.out[0][idx]; 202 | sum_res.b[1][idx] <== pubkey_mult.out[1][idx]; 203 | } 204 | 205 | // compare sum_res.x with r 206 | component compare[k]; 207 | signal num_equal[k - 1]; 208 | for (var idx = 0; idx < k; idx++) { 209 | compare[idx] = IsEqual(); 210 | compare[idx].in[0] <== r[idx]; 211 | compare[idx].in[1] <== sum_res.out[0][idx]; 212 | 213 | if (idx > 0) { 214 | if (idx == 1) { 215 | num_equal[idx - 1] <== compare[0].out + compare[1].out; 216 | } else { 217 | num_equal[idx - 1] <== num_equal[idx - 2] + compare[idx].out; 218 | } 219 | } 220 | } 221 | component res_comp = IsEqual(); 222 | res_comp.in[0] <== k; 223 | res_comp.in[1] <== num_equal[k - 2]; 224 | result <== res_comp.out; 225 | } 226 | 227 | // TODO: implement ECDSA extended verify 228 | // r, s, and msghash have coordinates 229 | // encoded with k registers of n bits each 230 | // v is a single bit 231 | // extended signature is (r, s, v) 232 | template ECDSAExtendedVerify(n, k) { 233 | signal input r[k]; 234 | signal input s[k]; 235 | signal input v; 236 | signal input msghash[k]; 237 | 238 | signal output result; 239 | } 240 | 241 | function div_ceil(m, n) { 242 | var ret = 0; 243 | if (m % n == 0) { 244 | ret = m \ n; 245 | } else { 246 | ret = m \ n + 1; 247 | } 248 | return ret; 249 | } -------------------------------------------------------------------------------- /scratch/build_86_3/dummy_point/dummy_point_cpp/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | using json = nlohmann::json; 14 | 15 | #include "calcwit.hpp" 16 | #include "circom.hpp" 17 | 18 | 19 | #define handle_error(msg) \ 20 | do { perror(msg); exit(EXIT_FAILURE); } while (0) 21 | 22 | Circom_Circuit* loadCircuit(std::string const &datFileName) { 23 | Circom_Circuit *circuit = new Circom_Circuit; 24 | 25 | int fd; 26 | struct stat sb; 27 | 28 | fd = open(datFileName.c_str(), O_RDONLY); 29 | if (fd == -1) { 30 | std::cout << ".dat file not found: " << datFileName << "\n"; 31 | throw std::system_error(errno, std::generic_category(), "open"); 32 | } 33 | 34 | if (fstat(fd, &sb) == -1) { /* To obtain file size */ 35 | throw std::system_error(errno, std::generic_category(), "fstat"); 36 | } 37 | 38 | u8* bdata = (u8*)mmap(NULL, sb.st_size, PROT_READ , MAP_PRIVATE, fd, 0); 39 | close(fd); 40 | 41 | circuit->InputHashMap = new HashSignalInfo[get_size_of_input_hashmap()]; 42 | uint dsize = get_size_of_input_hashmap()*sizeof(HashSignalInfo); 43 | memcpy((void *)(circuit->InputHashMap), (void *)bdata, dsize); 44 | 45 | circuit->witness2SignalList = new u64[get_size_of_witness()]; 46 | uint inisize = dsize; 47 | dsize = get_size_of_witness()*sizeof(u64); 48 | memcpy((void *)(circuit->witness2SignalList), (void *)(bdata+inisize), dsize); 49 | 50 | circuit->circuitConstants = new FrElement[get_size_of_constants()]; 51 | if (get_size_of_constants()>0) { 52 | inisize += dsize; 53 | dsize = get_size_of_constants()*sizeof(FrElement); 54 | memcpy((void *)(circuit->circuitConstants), (void *)(bdata+inisize), dsize); 55 | } 56 | 57 | std::map templateInsId2IOSignalInfo1; 58 | if (get_size_of_io_map()>0) { 59 | u32 index[get_size_of_io_map()]; 60 | inisize += dsize; 61 | dsize = get_size_of_io_map()*sizeof(u32); 62 | memcpy((void *)index, (void *)(bdata+inisize), dsize); 63 | inisize += dsize; 64 | assert(inisize % sizeof(u32) == 0); 65 | assert(sb.st_size % sizeof(u32) == 0); 66 | u32 dataiomap[(sb.st_size-inisize)/sizeof(u32)]; 67 | memcpy((void *)dataiomap, (void *)(bdata+inisize), sb.st_size-inisize); 68 | u32* pu32 = dataiomap; 69 | 70 | for (int i = 0; i < get_size_of_io_map(); i++) { 71 | u32 n = *pu32; 72 | IODefPair p; 73 | p.len = n; 74 | IODef defs[n]; 75 | pu32 += 1; 76 | for (u32 j = 0; j templateInsId2IOSignalInfo = move(templateInsId2IOSignalInfo1); 92 | 93 | munmap(bdata, sb.st_size); 94 | 95 | return circuit; 96 | } 97 | 98 | bool check_valid_number(std::string & s, uint base){ 99 | bool is_valid = true; 100 | if (base == 16){ 101 | for (uint i = 0; i < s.size(); i++){ 102 | is_valid &= ( 103 | ('0' <= s[i] && s[i] <= '9') || 104 | ('a' <= s[i] && s[i] <= 'f') || 105 | ('A' <= s[i] && s[i] <= 'F') 106 | ); 107 | } 108 | } else{ 109 | for (uint i = 0; i < s.size(); i++){ 110 | is_valid &= ('0' <= s[i] && s[i] < char(int('0') + base)); 111 | } 112 | } 113 | return is_valid; 114 | } 115 | 116 | void json2FrElements (json val, std::vector & vval){ 117 | if (!val.is_array()) { 118 | FrElement v; 119 | std::string s_aux, s; 120 | uint base; 121 | if (val.is_string()) { 122 | s_aux = val.get(); 123 | std::string possible_prefix = s_aux.substr(0, 2); 124 | if (possible_prefix == "0b" || possible_prefix == "0B"){ 125 | s = s_aux.substr(2, s_aux.size() - 2); 126 | base = 2; 127 | } else if (possible_prefix == "0o" || possible_prefix == "0O"){ 128 | s = s_aux.substr(2, s_aux.size() - 2); 129 | base = 8; 130 | } else if (possible_prefix == "0x" || possible_prefix == "0X"){ 131 | s = s_aux.substr(2, s_aux.size() - 2); 132 | base = 16; 133 | } else{ 134 | s = s_aux; 135 | base = 10; 136 | } 137 | if (!check_valid_number(s, base)){ 138 | std::ostringstream errStrStream; 139 | errStrStream << "Invalid number in JSON input: " << s_aux << "\n"; 140 | throw std::runtime_error(errStrStream.str() ); 141 | } 142 | } else if (val.is_number()) { 143 | double vd = val.get(); 144 | std::stringstream stream; 145 | stream << std::fixed << std::setprecision(0) << vd; 146 | s = stream.str(); 147 | base = 10; 148 | } else { 149 | std::ostringstream errStrStream; 150 | errStrStream << "Invalid JSON type\n"; 151 | throw std::runtime_error(errStrStream.str() ); 152 | } 153 | Fr_str2element (&v, s.c_str(), base); 154 | vval.push_back(v); 155 | } else { 156 | for (uint i = 0; i < val.size(); i++) { 157 | json2FrElements (val[i], vval); 158 | } 159 | } 160 | } 161 | 162 | 163 | void loadJson(Circom_CalcWit *ctx, std::string filename) { 164 | std::ifstream inStream(filename); 165 | json j; 166 | inStream >> j; 167 | 168 | u64 nItems = j.size(); 169 | // printf("Items : %llu\n",nItems); 170 | if (nItems == 0){ 171 | ctx->tryRunCircuit(); 172 | } 173 | for (json::iterator it = j.begin(); it != j.end(); ++it) { 174 | // std::cout << it.key() << " => " << it.value() << '\n'; 175 | u64 h = fnv1a(it.key()); 176 | std::vector v; 177 | json2FrElements(it.value(),v); 178 | uint signalSize = ctx->getInputSignalSize(h); 179 | if (v.size() < signalSize) { 180 | std::ostringstream errStrStream; 181 | errStrStream << "Error loading signal " << it.key() << ": Not enough values\n"; 182 | throw std::runtime_error(errStrStream.str() ); 183 | } 184 | if (v.size() > signalSize) { 185 | std::ostringstream errStrStream; 186 | errStrStream << "Error loading signal " << it.key() << ": Too many values\n"; 187 | throw std::runtime_error(errStrStream.str() ); 188 | } 189 | for (uint i = 0; i " << Fr_element2str(&(v[i])) << '\n'; 192 | ctx->setInputSignal(h,i,v[i]); 193 | } catch (std::runtime_error e) { 194 | std::ostringstream errStrStream; 195 | errStrStream << "Error setting signal: " << it.key() << "\n" << e.what(); 196 | throw std::runtime_error(errStrStream.str() ); 197 | } 198 | } 199 | } 200 | } 201 | 202 | void writeBinWitness(Circom_CalcWit *ctx, std::string wtnsFileName) { 203 | FILE *write_ptr; 204 | 205 | write_ptr = fopen(wtnsFileName.c_str(),"wb"); 206 | 207 | fwrite("wtns", 4, 1, write_ptr); 208 | 209 | u32 version = 2; 210 | fwrite(&version, 4, 1, write_ptr); 211 | 212 | u32 nSections = 2; 213 | fwrite(&nSections, 4, 1, write_ptr); 214 | 215 | // Header 216 | u32 idSection1 = 1; 217 | fwrite(&idSection1, 4, 1, write_ptr); 218 | 219 | u32 n8 = Fr_N64*8; 220 | 221 | u64 idSection1length = 8 + n8; 222 | fwrite(&idSection1length, 8, 1, write_ptr); 223 | 224 | fwrite(&n8, 4, 1, write_ptr); 225 | 226 | fwrite(Fr_q.longVal, Fr_N64*8, 1, write_ptr); 227 | 228 | uint Nwtns = get_size_of_witness(); 229 | 230 | u32 nVars = (u32)Nwtns; 231 | fwrite(&nVars, 4, 1, write_ptr); 232 | 233 | // Data 234 | u32 idSection2 = 2; 235 | fwrite(&idSection2, 4, 1, write_ptr); 236 | 237 | u64 idSection2length = (u64)n8*(u64)Nwtns; 238 | fwrite(&idSection2length, 8, 1, write_ptr); 239 | 240 | FrElement v; 241 | 242 | for (int i=0;igetWitness(i, &v); 244 | Fr_toLongNormal(&v, &v); 245 | fwrite(v.longVal, Fr_N64*8, 1, write_ptr); 246 | } 247 | fclose(write_ptr); 248 | } 249 | 250 | int main (int argc, char *argv[]) { 251 | std::string cl(argv[0]); 252 | if (argc!=3) { 253 | std::cout << "Usage: " << cl << " \n"; 254 | } else { 255 | std::string datfile = cl + ".dat"; 256 | std::string jsonfile(argv[1]); 257 | std::string wtnsfile(argv[2]); 258 | 259 | // auto t_start = std::chrono::high_resolution_clock::now(); 260 | 261 | Circom_Circuit *circuit = loadCircuit(datfile); 262 | 263 | Circom_CalcWit *ctx = new Circom_CalcWit(circuit); 264 | 265 | loadJson(ctx, jsonfile); 266 | if (ctx->getRemaingInputsToBeSet()!=0) { 267 | std::cerr << "Not all inputs have been set. Only " << get_main_input_signal_no()-ctx->getRemaingInputsToBeSet() << " out of " << get_main_input_signal_no() << std::endl; 268 | assert(false); 269 | } 270 | /* 271 | for (uint i = 0; igetWitness(i, &x); 274 | std::cout << i << ": " << Fr_element2str(&x) << std::endl; 275 | } 276 | */ 277 | 278 | //auto t_mid = std::chrono::high_resolution_clock::now(); 279 | //std::cout << std::chrono::duration(t_mid-t_start).count()<(t_end-t_mid).count()< { 137 | const h = fnvHash(k); 138 | const hMSB = parseInt(h.slice(0,8), 16); 139 | const hLSB = parseInt(h.slice(8,16), 16); 140 | const fArr = flatArray(input[k]); 141 | let signalSize = this.instance.exports.getInputSignalSize(hMSB, hLSB); 142 | if (signalSize < 0){ 143 | throw new Error(`Signal ${k} not found\n`); 144 | } 145 | if (fArr.length < signalSize) { 146 | throw new Error(`Not enough values for input signal ${k}\n`); 147 | } 148 | if (fArr.length > signalSize) { 149 | throw new Error(`Too many values for input signal ${k}\n`); 150 | } 151 | for (let i=0; i0) { 287 | res.unshift(0); 288 | i--; 289 | } 290 | } 291 | return res; 292 | } 293 | 294 | function fromArray32(arr) { //returns a BigInt 295 | var res = BigInt(0); 296 | const radix = BigInt(0x100000000); 297 | for (let i = 0; i = []; 42 | 43 | // 4 randomly chosen private keys 44 | // DONE: change (sk, pk) = (d_a, g^d_a) for p256 curve 45 | var privkeys: Array = [ 46 | 88549154299169935420064281163296845505587953610183896504176354567359434168161n, 47 | 37706893564732085918706190942542566344879680306879183356840008504374628845468n, 48 | 90388020393783788847120091912026443124559466591761394939671630294477859800601n, 49 | 110977009687373213104962226057480551605828725303063265716157300460694423838923n, 50 | ]; 51 | var pubkeys: Array> = []; 52 | for (var idx = 0; idx < 4; idx++) { 53 | var pubkey = P256.ProjectivePoint.fromPrivateKey(privkeys[idx]); 54 | pubkeys.push(pubkey); 55 | } 56 | 57 | // summing all possible pairs of pubkeys 58 | for (var idx = 0; idx < 4; idx++) { 59 | for (var idx2 = idx + 1; idx2 < 4; idx2++) { 60 | var sum: ProjPointType = pubkeys[idx].add(pubkeys[idx2]); 61 | test_cases.push([ 62 | pubkeys[idx].x, 63 | pubkeys[idx].y, 64 | pubkeys[idx2].x, 65 | pubkeys[idx2].y, 66 | sum.x, 67 | sum.y, 68 | ]); 69 | } 70 | } 71 | 72 | var test_p256_add_instance = function ( 73 | test_case: [bigint, bigint, bigint, bigint, bigint, bigint] 74 | ) { 75 | let pub0x = test_case[0]; 76 | let pub0y = test_case[1]; 77 | let pub1x = test_case[2]; 78 | let pub1y = test_case[3]; 79 | let sumx = test_case[4]; 80 | let sumy = test_case[5]; 81 | 82 | var pub0x_array: bigint[] = bigint_to_array(43, 6, pub0x); 83 | var pub0y_array: bigint[] = bigint_to_array(43, 6, pub0y); 84 | var pub1x_array: bigint[] = bigint_to_array(43, 6, pub1x); 85 | var pub1y_array: bigint[] = bigint_to_array(43, 6, pub1y); 86 | var sumx_array: bigint[] = bigint_to_array(43, 6, sumx); 87 | var sumy_array: bigint[] = bigint_to_array(43, 6, sumy); 88 | 89 | it( 90 | 'Testing pub0x: ' + 91 | pub0x + 92 | ' pub0y: ' + 93 | pub0y + 94 | ' pub1x: ' + 95 | pub1x + 96 | ' pub1y: ' + 97 | pub1y + 98 | ' sumx: ' + 99 | sumx + 100 | ' sumy: ' + 101 | sumy, 102 | async function () { 103 | let witness = await circuit.calculateWitness({ 104 | a: [pub0x_array, pub0y_array], 105 | b: [pub1x_array, pub1y_array], 106 | }); 107 | 108 | expect(witness[1]).to.equal(sumx_array[0]); 109 | expect(witness[2]).to.equal(sumx_array[1]); 110 | expect(witness[3]).to.equal(sumx_array[2]); 111 | expect(witness[4]).to.equal(sumx_array[3]); 112 | expect(witness[5]).to.equal(sumx_array[4]); 113 | expect(witness[6]).to.equal(sumx_array[5]); 114 | expect(witness[7]).to.equal(sumy_array[0]); 115 | expect(witness[8]).to.equal(sumy_array[1]); 116 | expect(witness[9]).to.equal(sumy_array[2]); 117 | expect(witness[10]).to.equal(sumy_array[3]); 118 | expect(witness[11]).to.equal(sumy_array[4]); 119 | expect(witness[12]).to.equal(sumy_array[5]); 120 | await circuit.checkConstraints(witness); 121 | } 122 | ); 123 | }; 124 | 125 | test_cases.forEach(test_p256_add_instance); 126 | }); 127 | 128 | describe('P256Double', function () { 129 | this.timeout(1000 * 1000); 130 | 131 | // runs circom compilation 132 | let circuit: any; 133 | before(async function () { 134 | circuit = await wasm_tester(path.join(__dirname, 'circuits_p256', 'test_p256_double.circom')); 135 | }); 136 | 137 | // pubx, puby, doublex, doubley 138 | var test_cases: Array<[bigint, bigint, bigint, bigint]> = []; 139 | 140 | // 4 randomly chosen private keys 141 | var privkeys: Array = [ 142 | 88549154299169935420064281163296845505587953610183896504176354567359434168161n, 143 | 37706893564732085918706190942542566344879680306879183356840008504374628845468n, 144 | 90388020393783788847120091912026443124559466591761394939671630294477859800601n, 145 | 110977009687373213104962226057480551605828725303063265716157300460694423838923n, 146 | ]; 147 | var pubkeys: Array> = []; 148 | for (var idx = 0; idx < 4; idx++) { 149 | var pubkey: ProjPointType = P256.ProjectivePoint.fromPrivateKey(privkeys[idx]); 150 | pubkeys.push(pubkey); 151 | } 152 | 153 | for (var idx = 0; idx < 4; idx++) { 154 | var double: ProjPointType = pubkeys[idx].add(pubkeys[idx]); 155 | test_cases.push([pubkeys[idx].x, pubkeys[idx].y, double.x, double.y]); 156 | } 157 | 158 | var test_p256_double_instance = function (test_case: [bigint, bigint, bigint, bigint]) { 159 | let pubx = test_case[0]; 160 | let puby = test_case[1]; 161 | let doublex = test_case[2]; 162 | let doubley = test_case[3]; 163 | 164 | var pubx_array: bigint[] = bigint_to_array(43, 6, pubx); 165 | var puby_array: bigint[] = bigint_to_array(43, 6, puby); 166 | var doublex_array: bigint[] = bigint_to_array(43, 6, doublex); 167 | var doubley_array: bigint[] = bigint_to_array(43, 6, doubley); 168 | 169 | it( 170 | 'Testing pubx: ' + pubx + ' puby: ' + puby + ' doublex: ' + doublex + ' doubley: ' + doubley, 171 | async function () { 172 | let witness = await circuit.calculateWitness({ in: [pubx_array, puby_array] }); 173 | expect(witness[1]).to.equal(doublex_array[0]); 174 | expect(witness[2]).to.equal(doublex_array[1]); 175 | expect(witness[3]).to.equal(doublex_array[2]); 176 | expect(witness[4]).to.equal(doublex_array[3]); 177 | expect(witness[5]).to.equal(doublex_array[4]); 178 | expect(witness[6]).to.equal(doublex_array[5]); 179 | expect(witness[7]).to.equal(doubley_array[0]); 180 | expect(witness[8]).to.equal(doubley_array[1]); 181 | expect(witness[9]).to.equal(doubley_array[2]); 182 | expect(witness[10]).to.equal(doubley_array[3]); 183 | expect(witness[11]).to.equal(doubley_array[4]); 184 | expect(witness[12]).to.equal(doubley_array[5]); 185 | await circuit.checkConstraints(witness); 186 | } 187 | ); 188 | }; 189 | 190 | test_cases.forEach(test_p256_double_instance); 191 | }); 192 | 193 | describe('P256ScalarMult', function () { 194 | this.timeout(1000 * 1000); 195 | 196 | // runs circom compilation 197 | let circuit: any; 198 | before(async function () { 199 | circuit = await wasm_tester( 200 | path.join(__dirname, 'circuits_p256', 'test_p256_scalarmult.circom') 201 | ); 202 | }); 203 | 204 | // pubx, puby, scalarx, scalary 205 | var test_cases: Array<[bigint, bigint, bigint, bigint, bigint]> = []; 206 | 207 | // 4 randomly chosen private keys 208 | var privkeys: Array = [ 209 | 88549154299169935420064281163296845505587953610183896504176354567359434168161n, 210 | 37706893564732085918706190942542566344879680306879183356840008504374628845468n, 211 | 90388020393783788847120091912026443124559466591761394939671630294477859800601n, 212 | 110977009687373213104962226057480551605828725303063265716157300460694423838923n, 213 | ]; 214 | var scalars: Array = [ 215 | 49162213912846590284921918007854216316029616890568331838502149777137252900653n, 216 | 76140377069448461768020097386275705201902774674727812489842341759686817688095n, 217 | 110598305201199016801761605786356726057447763277828986929716844671829352701135n, 218 | 89529513800538853223820080909500512684436497357931942181483678921439822888771n, 219 | ]; 220 | var pubkeys: Array> = []; 221 | for (var idx = 0; idx < 4; idx++) { 222 | var pubkey: ProjPointType = P256.ProjectivePoint.fromPrivateKey(privkeys[idx]); 223 | pubkeys.push(pubkey); 224 | } 225 | 226 | for (var idx = 0; idx < 4; idx++) { 227 | var scalar: bigint = scalars[idx]; 228 | var scalar_point: ProjPointType = pubkeys[idx].multiply(scalar); 229 | test_cases.push([scalar, pubkeys[idx].x, pubkeys[idx].y, scalar_point.x, scalar_point.y]); 230 | } 231 | 232 | var test_p256_scalar_instance = function (test_case: [bigint, bigint, bigint, bigint, bigint]) { 233 | let scalar = test_case[0]; 234 | let pubx = test_case[1]; 235 | let puby = test_case[2]; 236 | let scalarx = test_case[3]; 237 | let scalary = test_case[4]; 238 | 239 | var scalar_array: bigint[] = bigint_to_array(43, 6, scalar); 240 | var pubx_array: bigint[] = bigint_to_array(43, 6, pubx); 241 | var puby_array: bigint[] = bigint_to_array(43, 6, puby); 242 | var scalarx_array: bigint[] = bigint_to_array(43, 6, scalarx); 243 | var scalary_array: bigint[] = bigint_to_array(43, 6, scalary); 244 | 245 | it( 246 | 'Testing scalar: ' + 247 | scalar + 248 | ' pubx: ' + 249 | pubx + 250 | ' puby: ' + 251 | puby + 252 | ' scalarx: ' + 253 | scalarx + 254 | ' scalary: ' + 255 | scalary, 256 | async function () { 257 | let witness = await circuit.calculateWitness({ 258 | scalar: scalar_array, 259 | point: [pubx_array, puby_array], 260 | }); 261 | expect(witness[1]).to.equal(scalarx_array[0]); 262 | expect(witness[2]).to.equal(scalarx_array[1]); 263 | expect(witness[3]).to.equal(scalarx_array[2]); 264 | expect(witness[4]).to.equal(scalarx_array[3]); 265 | expect(witness[5]).to.equal(scalarx_array[4]); 266 | expect(witness[6]).to.equal(scalarx_array[5]); 267 | expect(witness[7]).to.equal(scalary_array[0]); 268 | expect(witness[8]).to.equal(scalary_array[1]); 269 | expect(witness[9]).to.equal(scalary_array[2]); 270 | expect(witness[10]).to.equal(scalary_array[3]); 271 | expect(witness[11]).to.equal(scalary_array[4]); 272 | expect(witness[12]).to.equal(scalary_array[5]); 273 | await circuit.checkConstraints(witness); 274 | } 275 | ); 276 | }; 277 | 278 | test_cases.forEach(test_p256_scalar_instance); 279 | }); 280 | 281 | describe('P256PointOnCurve', function () { 282 | this.timeout(1000 * 1000); 283 | 284 | // runs circom compilation 285 | let circuit: any; 286 | before(async function () { 287 | circuit = await wasm_tester(path.join(__dirname, 'circuits_p256', 'test_p256_poc.circom')); 288 | }); 289 | 290 | // x, y, on/off 291 | var test_cases: Array<[bigint, bigint, boolean]> = []; 292 | 293 | // just using base point G on curve 294 | test_cases.push([ 295 | 48439561293906451759052585252797914202762949526041747995844080717082404635286n, 296 | 36134250956749795798585127919587881956611106672985015071877198253568414405109n, 297 | true, 298 | ]); 299 | 300 | // modified point not on curve (small perturbation on G) 301 | test_cases.push([ 302 | 48439561293906451759052585252797914202762949526041747995844080717082404635287n, 303 | 36134250956749795798585127919587881956611106672985015071877198253568414405109n, 304 | false, 305 | ]); 306 | 307 | var test_p256_poc_instance = function (test_case: [bigint, bigint, boolean]) { 308 | let x = test_case[0]; 309 | let y = test_case[1]; 310 | let on_curve = test_case[2]; 311 | 312 | var x_array: bigint[] = bigint_to_array(43, 6, x); 313 | var y_array: bigint[] = bigint_to_array(43, 6, y); 314 | 315 | it('Testing x: ' + x + ' y: ' + y + ' on_curve: ' + on_curve, async function () { 316 | if (on_curve) { 317 | let witness = await circuit.calculateWitness({ 318 | x: x_array, 319 | y: y_array, 320 | }); 321 | await circuit.checkConstraints(witness); 322 | } else { 323 | let witnessCalcSucceeded = true; 324 | try { 325 | // witness generation should fail 326 | await circuit.calculateWitness({ 327 | x: x_array, 328 | y: y_array, 329 | }); 330 | } catch (e) { 331 | witnessCalcSucceeded = false; 332 | console.log('point not on curve'); 333 | } 334 | expect(witnessCalcSucceeded).to.equal(false); 335 | } 336 | }); 337 | }; 338 | 339 | test_cases.forEach(test_p256_poc_instance); 340 | }); 341 | -------------------------------------------------------------------------------- /circuits/p256_utils.circom: -------------------------------------------------------------------------------- 1 | /// UNUSED FILE 2 | 3 | pragma circom 2.1.5; 4 | 5 | include "bigint_func.circom"; 6 | include "p256_func.circom"; 7 | 8 | // P = 2^256 - 2^224 + 2^192 + 2^96 - 1 9 | 10 | // input: 10 registers, 64 bits each. registers can be overful 11 | // returns: reduced number with 8 32-bit registers, preserving residue mod P 12 | // changing the curve... 13 | // offset is too big to use immediately (on the order of 2^224) 14 | // need overflow to be at most 53, since there are 200-bit inputs (see p256.circom circuit AddUnequalCubicConstraint) 15 | // use 8 32-bit registers instead, calculate reps of 2**(64*i) in (32,8) representation directly so can only add 32-bit overflow 16 | template P256PrimeReduce10Registers() { 17 | signal input in[10]; 18 | 19 | // raw number = in[0] + in[1]*(2^64)^1 + in[2]*(2^64)^2 +in[3]*(2^64)^3 ... + in[7]*(2^64)^7 + ... 20 | // in[i]*(2^64)^i --> represent each of (2^64)^i (mod p) as an 8 digit (register) number in base 2^32, so that offsets to multiply in[i] by for each register at most 32 bits = small 21 | 22 | // PrimeReduce10Registers: 23 | // TODO: remove hardcode 24 | var in_coeffs[10][8] = [[1, 0, 0, 0, 0, 0, 0, 0], 25 | [0, 0, 1, 0, 0, 0, 0, 0], 26 | [0, 0, 0, 0, 1, 0, 0, 0], 27 | [0, 0, 0, 0, 0, 0, 1, 0], 28 | [1, 0, 0, 4294967295, 4294967295, 4294967295, 4294967294, 0], 29 | [4294967295, 0, 1, 1, 4294967295, 4294967294, 0, 4294967294], 30 | [4294967294, 4294967294, 4294967295, 2, 2, 0, 1, 4294967294], 31 | [4294967295, 4294967294, 4294967294, 4294967295, 0, 2, 3, 0], 32 | [3, 0, 4294967295, 4294967291, 4294967294, 4294967295, 4294967293, 4], 33 | [2, 5, 3, 4294967294, 4294967289, 4294967291, 4294967292, 4294967292]]; 34 | 35 | 36 | 37 | var tmp[8] = [0,0,0,0,0,0,0,0]; 38 | for (var i=0; i<8; i++) { 39 | for (var j=0; j<10; j++) { 40 | tmp[i] += in_coeffs[j][i] * in[j]; 41 | } 42 | } 43 | 44 | signal output out[8]; // (32, 8) 45 | for (var i=0; i<8; i++) { 46 | out[i] <== tmp[i]; 47 | } 48 | 49 | } 50 | 51 | // DONE 52 | // input: 7 registers, 64 bits each. registers can be overful 53 | // returns: reduced number with 4 registers, preserving residue mod P 54 | // PrimeReduce7Registers only called in CheckQuadraticModPIsZero, which have inputs at most 132 bits 55 | // so can directly reduce 2^(64i)*in[i] directly in 4 registers of 64 bits -> 64 bit overflow for 4 <= i <= 6 56 | template P256PrimeReduce7Registers() { 57 | signal input in[7]; 58 | 59 | var in_coeffs[7][4] = [[1, 0, 0, 0], 60 | [0, 1, 0, 0], 61 | [0, 0, 1, 0], 62 | [0, 0, 0, 1], 63 | [1, 18446744069414584320, 18446744073709551615, 4294967294], 64 | [4294967295, 4294967297, 18446744069414584319, 18446744065119617024], 65 | [18446744069414584318, 12884901887, 2, 18446744065119617025]]; 66 | 67 | var tmp[4] = [0,0,0,0]; 68 | for (var i=0; i<4; i++) { 69 | for (var j=0; j<7; j++) { 70 | tmp[i] += in_coeffs[j][i] * in[j]; 71 | } 72 | } 73 | 74 | signal output out[4]; // (64, 4) 75 | for (var i=0; i<4; i++) { 76 | out[i] <== tmp[i]; 77 | } 78 | } 79 | 80 | // DONE 81 | // check that in is in range [0, P-1] 82 | // want to look at P base 2^64 - as long as number is less than that, good (check ranges from largest to smallest digit) 83 | // P = 18446744073709551615 * 2^0 + 4294967295 * 2^64 + 0 * 2^128 + 18446744069414584321 * 2^192 84 | // TODO: remove hardcode 85 | template CheckInRangeP256 () { 86 | signal input in[4]; 87 | 88 | component firstPlaceLessThan = LessThan(64); 89 | firstPlaceLessThan.in[0] <== in[3]; 90 | firstPlaceLessThan.in[1] <== 18446744069414584321; 91 | 92 | component firstPlaceEqual = IsEqual(); 93 | firstPlaceEqual.in[0] <== in[3]; 94 | firstPlaceEqual.in[1] <== 18446744069414584321; 95 | 96 | component secondPlaceLessThan = LessThan(64); 97 | secondPlaceLessThan.in[0] <== in[2]; 98 | secondPlaceLessThan.in[1] <== 0; 99 | 100 | component secondPlaceEqual = IsEqual(); 101 | secondPlaceEqual.in[0] <== in[2]; 102 | secondPlaceEqual.in[1] <== 0; 103 | 104 | component thirdPlaceLessThan = LessThan(64); 105 | thirdPlaceLessThan.in[0] <== in[1]; 106 | thirdPlaceLessThan.in[1] <== 4294967295; 107 | 108 | component thirdPlaceEqual = IsEqual(); 109 | thirdPlaceEqual.in[0] <== in[1]; 110 | thirdPlaceEqual.in[1] <== 4294967295; 111 | 112 | component fourthPlaceLessThan = LessThan(64); 113 | fourthPlaceLessThan.in[0] <== in[0]; 114 | fourthPlaceLessThan.in[1] <== 18446744073709551615; 115 | 116 | component fourthPlaceEqual = IsEqual(); 117 | fourthPlaceEqual.in[0] <== in[0]; 118 | fourthPlaceEqual.in[1] <== 18446744073709551615; 119 | 120 | signal l1; 121 | l1 <== 1 - firstPlaceLessThan.out; 122 | signal e1; 123 | e1 <== 1 - firstPlaceEqual.out; 124 | signal l2; 125 | l2 <== 1 - secondPlaceLessThan.out; 126 | signal e2; 127 | e2 <== 1 - secondPlaceEqual.out; 128 | signal l3; 129 | l3 <== 1 - thirdPlaceLessThan.out; 130 | signal e3; 131 | e3 <== 1 - thirdPlaceEqual.out; 132 | signal l4; 133 | l4 <== 1 - fourthPlaceLessThan.out; 134 | signal e4; 135 | e4 <== 1 - fourthPlaceEqual.out; 136 | 137 | // d1d2d3d4 < P <=> (d1 less) OR 138 | // (d1 equal and d2 less) OR 139 | // (d1 equal and d2 equal and d3 less) OR 140 | // (d1 equal and d2 equal and d3 equal and d4 less) 141 | 142 | signal tmp1; 143 | tmp1 <== 1 * (e1 + l2); 144 | signal tmp2; 145 | tmp2 <== (e1 + e2 + l3) * (e1 + e2 + e3 + l4); 146 | 147 | tmp1 * tmp2 === 0; 148 | 149 | } 150 | 151 | // DONE 152 | // 64 bit registers with m-bit overflow 153 | // registers (and overall number) are potentially negative 154 | template CheckCubicModPIsZero(m) { 155 | assert(m < 206); // since we deal with up to m+34 bit, potentially negative registers 156 | 157 | signal input in[10]; 158 | 159 | log("===CheckCubicMod==="); 160 | for (var i=0; i<10; i++) { // should be at most 200-bit registers 161 | log(in[i]); 162 | } 163 | 164 | log(111); 165 | 166 | // the p256 field size in (32,8)-rep 167 | signal p[8]; 168 | var p_32_8[100] = get_p256_prime(32, 8); 169 | for (var i=0; i<8; i++) { 170 | p[i] <== p_32_8[i]; 171 | log(p[i]); 172 | } 173 | 174 | 175 | // now, we compute a positive number congruent to `in` expressible in *8* overflowed registers. 176 | // for this representation, individual registers are allowed to be negative, but the final number 177 | // will be nonnegative overall. 178 | // first, we apply the p256 10-register reduction technique to reduce to *8* registers. this may result 179 | // in a negative number overall, but preserves congruence mod p. 180 | // our intermediate result is z = p256reduce(in) 181 | // second, we add a big multiple of p to z, to ensure that our final result is positive. 182 | // since the registers of z are m + 34 bits, its max abs value is 2^(m+34 + 224) + 2^(m+34 + 192) + 2^(m+34 + 160) + ... 183 | // < 2^(m+258) 184 | // so we add p * 2^(m+6) = (2^256-2^224 + eps) * 2^(m+6), which is a bit under 2^(m+262) and larger than |z| < 8 * 2^(m+34 + 224) = 2^(m+34 + 224 + 3) = 2^(m+261) 185 | 186 | // notes: 187 | // what if we just didn't reduce any registers? like why are we reducing the input at all if all we're doing is long division? then 188 | // in < 2^(m + 64*9) + ... < 2^(m + 64*9)*10... 189 | 190 | signal reduced[8]; 191 | 192 | component p256Reducer = P256PrimeReduce10Registers(); // (32, 8) 193 | for (var i = 0; i < 10; i++) { 194 | p256Reducer.in[i] <== in[i]; 195 | } 196 | 197 | log(0); 198 | 199 | for (var i = 0; i < 8; i++) { 200 | log(p256Reducer.out[i]); 201 | } 202 | 203 | log(222); 204 | 205 | // also compute P as (32, 8) rep to add - multiple should still be the same since value stays same 206 | signal multipleOfP[8]; 207 | for (var i = 0; i < 8; i++) { 208 | multipleOfP[i] <== p[i] * (1 << (m+6)); // m + 6 + 32 = m+38 bits 209 | } 210 | 211 | // reduced becomes (32, 8) 212 | for (var i = 0; i < 8; i++) { 213 | reduced[i] <== p256Reducer.out[i] + multipleOfP[i]; // max(m+34, m+38) + 1 = m+39 bits 214 | } 215 | 216 | for (var i = 0; i < 8; i++) { 217 | log(reduced[i]); 218 | } 219 | 220 | log(333); 221 | 222 | // now we compute the quotient q, which serves as a witness. we can do simple bounding to show 223 | // q := reduced / P < (p256Reducer + multipleofP) / 2^255 < (2^(m+262) + 2^(m+261)) / 2^255 < 2^(m+8) 224 | // so the expected quotient q is always expressive in *7* 32-bit registers (i.e. < 2^224) 225 | // as long as m < 216 (and we only ever call m < 200) 226 | signal q[7]; 227 | 228 | // getProperRepresentation(m, n, k, in) spec: 229 | // m bits per overflowed register (values are potentially negative) 230 | // n bits per properly-sized register 231 | // in has k registers 232 | // out has k + ceil(m/n) - 1 + 1 registers. highest-order potentially negative, 233 | // all others are positive 234 | // - 1 since the last register is included in the last ceil(m/n) array 235 | // + 1 since the carries from previous registers could push you over 236 | // TODO: need to check if largest register of proper is negative 237 | var temp[100] = getProperRepresentation(m + 39, 32, 8, reduced); // SOME ERROR HERE 238 | 239 | var proper[16]; 240 | for (var i = 0; i<16; i++) { 241 | proper[i] = temp[i]; 242 | log(proper[i]); 243 | } 244 | 245 | log(999999999); 246 | 247 | // long_div(n, k, m, a, b) spec: 248 | // n bits per register 249 | // a has k + m registers 250 | // b has k registers 251 | // out[0] has length m + 1 -- quotient 252 | // out[1] has length k -- remainder 253 | // implements algorithm of https://people.eecs.berkeley.edu/~fateman/282/F%20Wright%20notes/week4.pdf 254 | // b[k-1] must be nonzero! 255 | // var qVarTemp[2][100] = long_div(32, 8, 8, proper, p); // ERROR HERE 256 | // for (var i = 0; i < 7; i++) { 257 | // q[i] <-- qVarTemp[0][i]; 258 | // log(q[i]); 259 | // } 260 | 261 | var qVarTemp[7] = [0, 0, 0, 0, 813694976, 2338053171, 2054]; // try hardcoding expected q in? 262 | for (var i = 0; i < 7; i++) { 263 | q[i] <-- qVarTemp[i]; 264 | log(q[i]); 265 | } 266 | 267 | 268 | // we need to constrain that q is in proper (7x32) representation 269 | component qRangeChecks[7]; 270 | for (var i = 0; i < 7; i++) { 271 | qRangeChecks[i] = Num2Bits(32); 272 | qRangeChecks[i].in <== q[i]; 273 | } 274 | 275 | log(444); 276 | 277 | // now we compute a representation qpProd = q * p 278 | signal qpProd[14]; 279 | 280 | // template BigMultNoCarry(n, ma, mb, ka, kb) spec: 281 | // a and b have n-bit registers 282 | // a has ka registers, each with NONNEGATIVE ma-bit values (ma can be > n) 283 | // b has kb registers, each with NONNEGATIVE mb-bit values (mb can be > n) 284 | // out has ka + kb - 1 registers, each with (ma + mb + ceil(log(max(ka, kb))))-bit values 285 | component qpProdComp = BigMultNoCarry(32, 32, 32, 7, 8); // qpProd = q*p 286 | for (var i = 0; i < 7; i++) { 287 | qpProdComp.a[i] <== q[i]; 288 | } 289 | for (var i = 0; i < 8; i++) { 290 | qpProdComp.b[i] <== p[i]; 291 | } 292 | for (var i = 0; i < 14; i++) { 293 | qpProd[i] <== qpProdComp.out[i]; // 67 bits 294 | } 295 | 296 | for (var i = 0; i < 14; i++) { 297 | log(qpProd[i]); // 67 bits 298 | } 299 | 300 | // log(444); 301 | // for (var i = 0; i < 26; i++) { 302 | // log(qpProdComp.out[i]); // 67 bits 303 | // } 304 | 305 | 306 | log(555); 307 | 308 | // finally, check that qpProd == reduced 309 | // CheckCarryToZero(n, m, k) spec: 310 | // in[i] contains values in the range -2^(m-1) to 2^(m-1) 311 | // constrain that in[] as a big integer is zero 312 | // each limbs is n bits 313 | // FAILING HERE: 314 | component zeroCheck = CheckCarryToZero(32, m + 50, 14); 315 | for (var i = 0; i < 14; i++) { 316 | if (i < 8) { // reduced only has 8 registers 317 | zeroCheck.in[i] <== qpProd[i] - reduced[i]; // (m + 39) + 1 bits 318 | log(zeroCheck.in[i]); 319 | } else { 320 | zeroCheck.in[i] <== qpProd[i]; 321 | log(zeroCheck.in[i]); 322 | } 323 | } 324 | 325 | log(666); 326 | 327 | } 328 | 329 | // DONE 330 | // 64 bit registers with m-bit overflow 331 | // registers (and overall number) are potentially negative 332 | template CheckQuadraticModPIsZero(m) { 333 | assert(m < 147); // so that we can assume q has 2 registers 334 | 335 | signal input in[7]; 336 | 337 | // the p256 field size, hardcoded 338 | signal p[4]; 339 | p[0] <== 18446744073709551615; 340 | p[1] <== 4294967295; 341 | p[2] <== 0; 342 | p[3] <== 18446744069414584321; 343 | 344 | // now, we compute a positive number congruent to `in` expressible in 4 overflowed registers. 345 | // for this representation, individual registers are allowed to be negative, but the final number 346 | // will be nonnegative overall. 347 | // first, we apply the p256 7-register reduction technique to reduce to 4 registers. this may result 348 | // in a negative number overall, but preserves congruence mod p. 349 | // our intermediate result is z = p256Reduce(in) 350 | // second, we add a big multiple of p to z, to ensure that our final result is positive. 351 | // since the registers of z are m + 33 bits, its max abs value is 2^(m+33 + 192) + 2^(m+33 + 128) + ... 352 | // so we add p * 2^(m-30), which is a bit under 2^(m+226) and larger than |z| < 2^(m+33+192) + eps 353 | signal reduced[4]; 354 | component p256Reducer = P256PrimeReduce7Registers(); 355 | for (var i = 0; i < 7; i++) { 356 | p256Reducer.in[i] <== in[i]; 357 | } 358 | signal multipleOfP[4]; 359 | for (var i = 0; i < 4; i++) { 360 | multipleOfP[i] <== p[i] * (1 << (m-30)); // m - 30 + 64 = m + 34 bits 361 | } 362 | for (var i = 0; i < 4; i++) { 363 | reduced[i] <== p256Reducer.out[i] + multipleOfP[i]; // max(m+33, m+34) + 1 = m+35 bits 364 | } 365 | 366 | // now we compute the quotient q, which serves as a witness. we can do simple bounding to show 367 | // that the the expected quotient is always expressible in 2 registers (i.e. < 2^192) 368 | // so long as m < 147 369 | signal q[2]; 370 | 371 | var temp[100] = getProperRepresentation(m + 35, 64, 4, reduced); 372 | var proper[8]; 373 | for (var i = 0; i < 8; i++) { 374 | proper[i] = temp[i]; 375 | } 376 | 377 | var qVarTemp[2][100] = long_div(64, 4, 4, proper, p); 378 | for (var i = 0; i < 2; i++) { 379 | q[i] <-- qVarTemp[0][i]; 380 | } 381 | 382 | // we need to constrain that q is in proper (2x64) representation 383 | component qRangeChecks[2]; 384 | for (var i = 0; i < 2; i++) { 385 | qRangeChecks[i] = Num2Bits(64); 386 | qRangeChecks[i].in <== q[i]; 387 | } 388 | 389 | // now we compute a representation qpProd = q * p 390 | signal qpProd[5]; 391 | component qpProdComp = BigMultNoCarry(64, 64, 64, 2, 4); 392 | for (var i = 0; i < 2; i++) { 393 | qpProdComp.a[i] <== q[i]; 394 | } 395 | for (var i = 0; i < 4; i++) { 396 | qpProdComp.b[i] <== p[i]; 397 | } 398 | for (var i = 0; i < 5; i++) { 399 | qpProd[i] <== qpProdComp.out[i]; // 130 bits 400 | } 401 | 402 | // finally, check that qpProd == reduced 403 | component zeroCheck = CheckCarryToZero(64, m + 36, 5); 404 | for (var i = 0; i < 5; i++) { 405 | if (i < 4) { // reduced only has 4 registers 406 | zeroCheck.in[i] <== qpProd[i] - reduced[i]; // (m + 35) + 1 bits 407 | } else { 408 | zeroCheck.in[i] <== qpProd[i]; 409 | } 410 | } 411 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------