From ef9679552cc98b9f3961efe5a9af4fdfc9cb98df Mon Sep 17 00:00:00 2001 From: arnaucube Date: Thu, 9 May 2024 16:20:04 +0200 Subject: [PATCH] add full flow using keccak256-circom. The constraint generation fails, debugging circom & sonobe & arkworks/circom-compat --- Cargo.toml | 40 +++++++ circuit/keccak-chain.circom | 21 ++++ circuit/package.json | 18 +++ compile-circuit.sh | 12 ++ src/lib.rs | 225 ++++++++++++++++++++++++++++++++++++ 5 files changed, 316 insertions(+) create mode 100644 Cargo.toml create mode 100644 circuit/keccak-chain.circom create mode 100644 circuit/package.json create mode 100755 compile-circuit.sh create mode 100644 src/lib.rs diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..5e3fbdd --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "keccak-chain-sonobe" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] + +[dev-dependencies] +ark-groth16 = { version = "^0.4.0" } +ark-bn254 = { version = "0.4.0", features = ["r1cs"] } +ark-grumpkin = {version="0.4.0", features=["r1cs"]} +ark-ec = "0.4.1" +ark-ff = "0.4.1" +ark-r1cs-std = { version = "0.4.0", default-features = false } +ark-relations = { version = "0.4.0", default-features = false } +ark-poly-commit = "^0.4.0" +ark-crypto-primitives = { version = "^0.4.0", default-features = false, features = [ + "r1cs", + "sponge", + "crh", +] } +ark-std = "0.4.0" +color-eyre = "0.6.2" +num-bigint = "0.4.3" +# folding-schemes = { git = "https://github.com/privacy-scaling-explorations/sonobe", package = "folding-schemes"} +folding-schemes = { path = "../folding/sonobe_FIX-CIRCOM/folding-schemes", package = "folding-schemes"} +solidity-verifiers = { git = "https://github.com/privacy-scaling-explorations/sonobe", package = "solidity-verifiers"} +serde = "1.0.198" +serde_json = "1.0.116" + +rand = "0.8.5" + +[patch.crates-io] +# patch ark_curves to use a cherry-picked version which contains +# bn254::constraints & grumpkin for v0.4.0 (once arkworks v0.5.0 is released +# this will no longer be needed) +ark-bn254 = { git = "https://github.com/arnaucube/ark-curves-cherry-picked", branch="cherry-pick"} +ark-grumpkin = { git = "https://github.com/arnaucube/ark-curves-cherry-picked", branch="cherry-pick"} diff --git a/circuit/keccak-chain.circom b/circuit/keccak-chain.circom new file mode 100644 index 0000000..58d0d11 --- /dev/null +++ b/circuit/keccak-chain.circom @@ -0,0 +1,21 @@ +pragma circom 2.0.0; + +include "node_modules/keccak256-circom/circuits/keccak.circom"; + +template KeccakChain () { + signal input ivc_input[32*8]; + signal output ivc_output[32*8]; + + component keccak = Keccak(32*8, 32*8); + + for (var i=0; i<32*8; i++) { + keccak.in[i] <== ivc_input[i]; + } + for (var i=0; i<32*8; i++) { + ivc_output[i] <== keccak.out[i]; + } +} + +// for a input & output of 32 bytes: +component main { public [ivc_input] } = KeccakChain(); + diff --git a/circuit/package.json b/circuit/package.json new file mode 100644 index 0000000..2381217 --- /dev/null +++ b/circuit/package.json @@ -0,0 +1,18 @@ +{ + "name": "fakeid-demo", + "version": "0.0.1", + "description": "iden3 circuits", + "main": "index.js", + "scripts": { + "clean": "rm -fR dist", + "build": "npm run clean && ./node_modules/.bin/tsc --strictNullChecks", + "test": "./node_modules/.bin/mocha --timeout 5000 -p -r ts-node/register '*.test.ts'", + "postinstall":"cd node_modules/keccak256-circom && npm install" + }, + "license": "GPL-3.0", + "dependencies": { + "circomlib": "^2.0.5", + "keccak256-circom": "git://github.com/vocdoni/keccak256-circom.git" + + } +} diff --git a/compile-circuit.sh b/compile-circuit.sh new file mode 100755 index 0000000..35534de --- /dev/null +++ b/compile-circuit.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +# rm previous files +rm -r ./circuit/keccak-chain_js +rm circuit/keccak-chain.r1cs +rm circuit/keccak-chain.sym + +cd circuit +npm install +cd .. + +circom ./circuit/keccak-chain.circom --O0 --r1cs --sym --wasm --prime bn128 --output ./circuit/ diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..da12996 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,225 @@ +#![allow(non_snake_case)] +#![allow(non_camel_case_types)] +#![allow(clippy::upper_case_acronyms)] +/// +/// This example performs the full flow: +/// - define the circuit to be folded +/// - fold the circuit with Nova+CycleFold's IVC +/// - generate a DeciderEthCircuit final proof +/// - generate the Solidity contract that verifies the proof +/// - verify the proof in the EVM +/// + +#[cfg(test)] +mod tests { + use ark_bn254::{constraints::GVar, Bn254, Fr, G1Projective as G1}; + use ark_grumpkin::{constraints::GVar as GVar2, Projective as G2}; + + use ark_crypto_primitives::snark::SNARK; + use ark_groth16::{Groth16, ProvingKey, VerifyingKey as G16VerifierKey}; + use ark_poly_commit::kzg10::VerifierKey as KZGVerifierKey; + + use ark_std::Zero; + + use std::path::PathBuf; + use std::time::Instant; + + use folding_schemes::{ + commitment::{ + kzg::{ProverKey as KZGProverKey, KZG}, + pedersen::Pedersen, + CommitmentScheme, + }, + folding::nova::{ + decider_eth::{prepare_calldata, Decider as DeciderEth}, + decider_eth_circuit::DeciderEthCircuit, + get_r1cs, Nova, ProverParams, VerifierParams, + }, + frontend::{circom::CircomFCircuit, FCircuit}, + transcript::poseidon::poseidon_test_config, + Decider, FoldingScheme, + }; + use solidity_verifiers::{ + evm::{compile_solidity, Evm}, + utils::get_function_selector_for_nova_cyclefold_verifier, + verifiers::nova_cyclefold::get_decider_template_for_cyclefold_decider, + NovaCycleFoldVerifierKey, + }; + + // This method computes the Nova's Prover & Verifier parameters for the example. + // Warning: this method is only for testing purposes. For a real world use case those parameters + // should be generated carefully (both the PoseidonConfig and the PedersenParams). + #[allow(clippy::type_complexity)] + fn init_nova_ivc_params>( + F_circuit: FC, + ) -> ( + ProverParams, Pedersen>, + VerifierParams, + KZGVerifierKey, + ) { + let mut rng = ark_std::test_rng(); + let poseidon_config = poseidon_test_config::(); + + // get the CM & CF_CM len + let (r1cs, cf_r1cs) = + get_r1cs::(&poseidon_config, F_circuit).unwrap(); + let cs_len = r1cs.A.n_rows; + let cf_cs_len = cf_r1cs.A.n_rows; + + // let (pedersen_params, _) = Pedersen::::setup(&mut rng, cf_len).unwrap(); + let (kzg_pk, kzg_vk): (KZGProverKey, KZGVerifierKey) = + KZG::::setup(&mut rng, cs_len).unwrap(); + let (cf_pedersen_params, _) = Pedersen::::setup(&mut rng, cf_cs_len).unwrap(); + + let fs_prover_params = ProverParams::, Pedersen> { + poseidon_config: poseidon_config.clone(), + cs_params: kzg_pk.clone(), + cf_cs_params: cf_pedersen_params, + }; + let fs_verifier_params = VerifierParams:: { + poseidon_config: poseidon_config.clone(), + r1cs, + cf_r1cs, + }; + (fs_prover_params, fs_verifier_params, kzg_vk) + } + + /// Initializes Nova parameters and DeciderEth parameters. Only for test purposes. + #[allow(clippy::type_complexity)] + fn init_ivc_and_decider_params>( + f_circuit: FC, + ) -> ( + ProverParams, Pedersen>, + KZGVerifierKey, + ProvingKey, + G16VerifierKey, + ) { + let mut rng = rand::rngs::OsRng; + let start = Instant::now(); + let (fs_prover_params, _, kzg_vk) = init_nova_ivc_params::(f_circuit.clone()); + println!("generated Nova folding params: {:?}", start.elapsed()); + + pub type NOVA = Nova, Pedersen>; + let z_0 = vec![Fr::zero(); f_circuit.state_len()]; + let nova = NOVA::init(&fs_prover_params, f_circuit, z_0.clone()).unwrap(); + + let decider_circuit = + DeciderEthCircuit::, Pedersen>::from_nova::( + nova.clone(), + ) + .unwrap(); + let start = Instant::now(); + let (g16_pk, g16_vk) = + Groth16::::circuit_specific_setup(decider_circuit.clone(), &mut rng).unwrap(); + println!( + "generated G16 (Decider circuit) params: {:?}", + start.elapsed() + ); + (fs_prover_params, kzg_vk, g16_pk, g16_vk) + } + + #[test] + fn full_flow() { + // set the initial state + let z_0_aux: Vec = vec![0_u32; 32 * 8]; + let z_0: Vec = z_0_aux.iter().map(|v| Fr::from(*v)).collect::>(); + + // initialize the Circom circuit + let r1cs_path = PathBuf::from("./circuit/keccak-chain.r1cs"); + let wasm_path = PathBuf::from("./circuit/keccak-chain_js/keccak-chain.wasm"); + + let f_circuit_params = (r1cs_path, wasm_path, 32 * 8, 0); + let f_circuit = CircomFCircuit::::new(f_circuit_params).unwrap(); + + let (fs_prover_params, kzg_vk, g16_pk, g16_vk) = + init_ivc_and_decider_params::>(f_circuit.clone()); + + pub type NOVA = + Nova, KZG<'static, Bn254>, Pedersen>; + pub type DECIDERETH_FCircuit = DeciderEth< + G1, + GVar, + G2, + GVar2, + CircomFCircuit, + KZG<'static, Bn254>, + Pedersen, + Groth16, + NOVA, + >; + + // initialize the folding scheme engine, in our case we use Nova + let mut nova = NOVA::init(&fs_prover_params, f_circuit.clone(), z_0).unwrap(); + // run n steps of the folding iteration + for i in 0..10 { + let start = Instant::now(); + nova.prove_step(vec![]).unwrap(); + println!("Nova::prove_step {}: {:?}", i, start.elapsed()); + } + + let rng = rand::rngs::OsRng; + let start = Instant::now(); + let proof = DECIDERETH_FCircuit::prove( + (g16_pk, fs_prover_params.cs_params.clone()), + rng, + nova.clone(), + ) + .unwrap(); + println!("generated Decider proof: {:?}", start.elapsed()); + + let verified = DECIDERETH_FCircuit::verify( + (g16_vk.clone(), kzg_vk.clone()), + nova.i, + nova.z_0.clone(), + nova.z_i.clone(), + &nova.U_i, + &nova.u_i, + &proof, + ) + .unwrap(); + assert!(verified); + println!("Decider proof verification: {}", verified); + + // Now, let's generate the Solidity code that verifies this Decider final proof + let function_selector = + get_function_selector_for_nova_cyclefold_verifier(nova.z_0.len() * 2 + 1); + + let calldata: Vec = prepare_calldata( + function_selector, + nova.i, + nova.z_0, + nova.z_i, + &nova.U_i, + &nova.u_i, + proof, + ) + .unwrap(); + + // prepare the setup params for the solidity verifier + let nova_cyclefold_vk = + NovaCycleFoldVerifierKey::from((g16_vk, kzg_vk, f_circuit.state_len())); + + // generate the solidity code + let decider_solidity_code = get_decider_template_for_cyclefold_decider(nova_cyclefold_vk); + + // verify the proof against the solidity code in the EVM + let nova_cyclefold_verifier_bytecode = + compile_solidity(&decider_solidity_code, "NovaDecider"); + let mut evm = Evm::default(); + let verifier_address = evm.create(nova_cyclefold_verifier_bytecode); + let (_, output) = evm.call(verifier_address, calldata.clone()); + assert_eq!(*output.last().unwrap(), 1); + + // save smart contract and the calldata + println!("storing nova-verifier.sol and the calldata into files"); + use std::fs; + fs::write( + "./examples/nova-verifier.sol", + decider_solidity_code.clone(), + ) + .unwrap(); + fs::write("./examples/solidity-calldata.calldata", calldata.clone()).unwrap(); + let s = solidity_verifiers::utils::get_formatted_calldata(calldata.clone()); + fs::write("./examples/solidity-calldata.inputs", s.join(",\n")).expect(""); + } +}