mirror of
https://github.com/arnaucube/sonobe.git
synced 2026-01-10 16:01:35 +01:00
Add solidity groth16, kzg10 and final decider verifiers in a dedicated workspace (#70)
* change: Refactor structure into workspace * chore: Add empty readme * change: Transform repo into workspace * add: Create folding-verifier-solidity crate * add: Include askama.toml for `sol` extension escaper * add: Jordi's old Groth16 verifier .sol template and adapt it * tmp: create simple template struct to test * Update FoldingSchemes trait, fit Nova+CycleFold - update lib.rs's `FoldingScheme` trait interface - fit Nova+CycleFold into the `FoldingScheme` trait - refactor `src/nova/*` * chore: add serialization assets for testing Now we include an `assets` folder with a serialized proof & vk for tests * Add `examples` dir, with Nova's `FoldingScheme` example * polishing * expose poseidon_test_config outside tests * change: Refactor structure into workspace * chore: Add empty readme * change: Transform repo into workspace * add: Create folding-verifier-solidity crate * add: Include askama.toml for `sol` extension escaper * add: Jordi's old Groth16 verifier .sol template and adapt it * tmp: create simple template struct to test * feat: templating kzg working * chore: add emv and revm * feat: start evm file * chore: add ark-poly-commit * chore: move `commitment` to `folding-schemes` * chore: update `.gitignore` to ignore generated contracts * chore: update template with bn254 lib on it (avoids import), update for loop to account for whitespaces * refactor: update template with no lib * feat: add evm deploy code, compile and create kzg verifier * chore: update `Cargo.toml` to have `folding-schemes` available with verifiers * feat: start kzg prove and verify with sol * chore: compute crs from kzg prover * feat: evm kzg verification passing * tmp * change: Swap order of G2 coordinates within the template * Update way to serialize proof with correct order * chore: update `Cargo.toml` * chore: add revm * chore: add `save_solidity` * refactor: verifiers in dedicated mod * refactor: have dedicated `utils` module * chore: expose modules * chore: update verifier for kzg * chore: rename templates * fix: look for binary using also name of contract * refactor: generate groth16 proof for sha256 pre-image, generate groth16 template with verifying key * chore: template renaming * fix: switch circuit for circuit that simply adds * feat: generates test data on the fly * feat: update to latest groth16 verifier * refactor: rename folder, update `.gitignore` * chore: update `Cargo.toml` * chore: update templates extension to indicate that they are templates * chore: rename templates, both files and structs * fix: template inheritance working * feat: template spdx and pragma statements * feat: decider verifier compiles, update test for kzg10 and groth16 templates * feat: parameterize which size of the crs should be stored on the contract * chore: add comment on how the groth16 and kzg10 proofs will be linked together * chore: cargo clippy run * chore: cargo clippy tests * chore: cargo fmt * refactor: remove unused lifetime parameter * chore: end merge * chore: move examples to `folding-schemes` workspace * get latest main changes * fix: temp fix clippy warnings, will remove lints once not used in tests only * fix: cargo clippy lint added on `code_size` * fix: update path to test circuit and add step for installing solc * chore: remove `save_solidity` steps * fix: the borrowed expression implements the required traits * chore: update `Cargo.toml` * chore: remove extra `[patch.crates-io]` * fix: update to patch at the workspace level and add comment explaining this * refactor: correct `staticcall` with valid input/output sizes and change return syntax for pairing * refactor: expose modules and remove `dead_code` calls * chore: update `README.md`, add additional comments on `kzg10` template and update `groth16` template comments * chore: be clearer on attributions on `kzg10` --------- Co-authored-by: CPerezz <c.perezbaro@gmail.com> Co-authored-by: arnaucube <root@arnaucube.com>
This commit is contained in:
181
folding-schemes-solidity/src/evm.rs
Normal file
181
folding-schemes-solidity/src/evm.rs
Normal file
@@ -0,0 +1,181 @@
|
||||
pub use revm;
|
||||
use revm::{
|
||||
primitives::{hex, Address, CreateScheme, ExecutionResult, Output, TransactTo, TxEnv},
|
||||
InMemoryDB, EVM,
|
||||
};
|
||||
use std::{
|
||||
fmt::{self, Debug, Formatter},
|
||||
fs::{create_dir_all, File},
|
||||
io::{self, Write},
|
||||
process::{Command, Stdio},
|
||||
str,
|
||||
};
|
||||
|
||||
// from: https://github.com/privacy-scaling-explorations/halo2-solidity-verifier/blob/85cb77b171ce3ee493628007c7a1cfae2ea878e6/examples/separately.rs#L56
|
||||
pub fn save_solidity(name: impl AsRef<str>, solidity: &str) {
|
||||
const DIR_GENERATED: &str = "./generated";
|
||||
create_dir_all(DIR_GENERATED).unwrap();
|
||||
File::create(format!("{DIR_GENERATED}/{}", name.as_ref()))
|
||||
.unwrap()
|
||||
.write_all(solidity.as_bytes())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Compile solidity with `--via-ir` flag, then return creation bytecode.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if executable `solc` can not be found, or compilation fails.
|
||||
pub fn compile_solidity(solidity: impl AsRef<[u8]>, contract_name: &str) -> Vec<u8> {
|
||||
let mut process = match Command::new("solc")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.arg("--bin")
|
||||
.arg("--optimize")
|
||||
.arg("-")
|
||||
.spawn()
|
||||
{
|
||||
Ok(process) => process,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {
|
||||
panic!("Command 'solc' not found");
|
||||
}
|
||||
Err(err) => {
|
||||
panic!("Failed to spawn process with command 'solc':\n{err}");
|
||||
}
|
||||
};
|
||||
process
|
||||
.stdin
|
||||
.take()
|
||||
.unwrap()
|
||||
.write_all(solidity.as_ref())
|
||||
.unwrap();
|
||||
let output = process.wait_with_output().unwrap();
|
||||
let stdout = str::from_utf8(&output.stdout).unwrap();
|
||||
if let Some(binary) = find_binary(stdout, contract_name) {
|
||||
binary
|
||||
} else {
|
||||
panic!(
|
||||
"Compilation fails:\n{}",
|
||||
str::from_utf8(&output.stderr).unwrap()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Find binary from `stdout` with given `contract_name`.
|
||||
/// `contract_name` is provided since `solc` may compile multiple contracts or libraries.
|
||||
/// hence, we need to find the correct binary.
|
||||
fn find_binary(stdout: &str, contract_name: &str) -> Option<Vec<u8>> {
|
||||
let start_contract = stdout.find(contract_name)?;
|
||||
let stdout_contract = &stdout[start_contract..];
|
||||
let start = stdout_contract.find("Binary:")? + 8;
|
||||
Some(hex::decode(&stdout_contract[start..stdout_contract.len() - 1]).unwrap())
|
||||
}
|
||||
|
||||
/// Evm runner.
|
||||
pub struct Evm {
|
||||
evm: EVM<InMemoryDB>,
|
||||
}
|
||||
|
||||
impl Debug for Evm {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
let mut debug_struct = f.debug_struct("Evm");
|
||||
debug_struct
|
||||
.field("env", &self.evm.env)
|
||||
.field("db", &self.evm.db.as_ref().unwrap())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Evm {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
evm: EVM {
|
||||
env: Default::default(),
|
||||
db: Some(Default::default()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Evm {
|
||||
/// Return code_size of given address.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if given address doesn't have bytecode.
|
||||
pub fn code_size(&mut self, address: Address) -> usize {
|
||||
self.evm.db.as_ref().unwrap().accounts[&address]
|
||||
.info
|
||||
.code
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.len()
|
||||
}
|
||||
|
||||
/// Apply create transaction with given `bytecode` as creation bytecode.
|
||||
/// Return created `address`.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if execution reverts or halts unexpectedly.
|
||||
pub fn create(&mut self, bytecode: Vec<u8>) -> Address {
|
||||
let (_, output) = self.transact_success_or_panic(TxEnv {
|
||||
gas_limit: u64::MAX,
|
||||
transact_to: TransactTo::Create(CreateScheme::Create),
|
||||
data: bytecode.into(),
|
||||
..Default::default()
|
||||
});
|
||||
match output {
|
||||
Output::Create(_, Some(address)) => address,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply call transaction to given `address` with `calldata`.
|
||||
/// Returns `gas_used` and `return_data`.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if execution reverts or halts unexpectedly.
|
||||
pub fn call(&mut self, address: Address, calldata: Vec<u8>) -> (u64, Vec<u8>) {
|
||||
let (gas_used, output) = self.transact_success_or_panic(TxEnv {
|
||||
gas_limit: u64::MAX,
|
||||
transact_to: TransactTo::Call(address),
|
||||
data: calldata.into(),
|
||||
..Default::default()
|
||||
});
|
||||
match output {
|
||||
Output::Call(output) => (gas_used, output.into()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn transact_success_or_panic(&mut self, tx: TxEnv) -> (u64, Output) {
|
||||
self.evm.env.tx = tx;
|
||||
let result = self.evm.transact_commit().unwrap();
|
||||
self.evm.env.tx = Default::default();
|
||||
match result {
|
||||
ExecutionResult::Success {
|
||||
gas_used,
|
||||
output,
|
||||
logs,
|
||||
..
|
||||
} => {
|
||||
if !logs.is_empty() {
|
||||
println!("--- logs from {} ---", logs[0].address);
|
||||
for (log_idx, log) in logs.iter().enumerate() {
|
||||
println!("log#{log_idx}");
|
||||
for (topic_idx, topic) in log.topics.iter().enumerate() {
|
||||
println!(" topic{topic_idx}: {topic:?}");
|
||||
}
|
||||
}
|
||||
println!("--- end ---");
|
||||
}
|
||||
(gas_used, output)
|
||||
}
|
||||
ExecutionResult::Revert { gas_used, output } => {
|
||||
panic!("Transaction reverts with gas_used {gas_used} and output {output:#x}")
|
||||
}
|
||||
ExecutionResult::Halt { reason, gas_used } => panic!(
|
||||
"Transaction halts unexpectedly with gas_used {gas_used} and reason {reason:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
5
folding-schemes-solidity/src/lib.rs
Normal file
5
folding-schemes-solidity/src/lib.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
pub use evm::*;
|
||||
pub use verifiers::templates::*;
|
||||
mod evm;
|
||||
mod utils;
|
||||
mod verifiers;
|
||||
43
folding-schemes-solidity/src/utils/encoding.rs
Normal file
43
folding-schemes-solidity/src/utils/encoding.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
/// Defines encodings of G1 and G2 elements for use in Solidity templates.
|
||||
use ark_bn254::{Fq, G1Affine, G2Affine};
|
||||
use std::fmt::{self, Display};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct FqWrapper(pub Fq);
|
||||
|
||||
impl Display for FqWrapper {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct G1Repr(pub [FqWrapper; 2]);
|
||||
|
||||
impl Display for G1Repr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{:#?}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a G1 element to a representation that can be used in Solidity templates.
|
||||
pub fn g1_to_fq_repr(g1: G1Affine) -> G1Repr {
|
||||
G1Repr([FqWrapper(g1.x), FqWrapper(g1.y)])
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct G2Repr(pub [[FqWrapper; 2]; 2]);
|
||||
|
||||
impl Display for G2Repr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{:#?}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a G2 element to a representation that can be used in Solidity templates.
|
||||
pub fn g2_to_fq_repr(g2: G2Affine) -> G2Repr {
|
||||
G2Repr([
|
||||
[FqWrapper(g2.x.c0), FqWrapper(g2.x.c1)],
|
||||
[FqWrapper(g2.y.c0), FqWrapper(g2.y.c1)],
|
||||
])
|
||||
}
|
||||
1
folding-schemes-solidity/src/utils/mod.rs
Normal file
1
folding-schemes-solidity/src/utils/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod encoding;
|
||||
287
folding-schemes-solidity/src/verifiers/mod.rs
Normal file
287
folding-schemes-solidity/src/verifiers/mod.rs
Normal file
@@ -0,0 +1,287 @@
|
||||
pub mod templates;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::evm::{compile_solidity, save_solidity, Evm};
|
||||
use crate::verifiers::templates::{Groth16Verifier, KZG10Verifier};
|
||||
use ark_bn254::{Bn254, Fr, G1Projective as G1};
|
||||
use ark_crypto_primitives::snark::{CircuitSpecificSetupSNARK, SNARK};
|
||||
use ark_ec::{AffineRepr, CurveGroup};
|
||||
use ark_ff::{BigInt, BigInteger, PrimeField};
|
||||
use ark_groth16::Groth16;
|
||||
use ark_poly_commit::kzg10::VerifierKey;
|
||||
use ark_r1cs_std::alloc::AllocVar;
|
||||
use ark_r1cs_std::eq::EqGadget;
|
||||
use ark_r1cs_std::fields::fp::FpVar;
|
||||
use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystemRef, SynthesisError};
|
||||
use ark_std::rand::{RngCore, SeedableRng};
|
||||
use ark_std::Zero;
|
||||
use ark_std::{test_rng, UniformRand};
|
||||
use askama::Template;
|
||||
use folding_schemes::{
|
||||
commitment::{
|
||||
kzg::{KZGProver, KZGSetup, ProverKey},
|
||||
CommitmentProver,
|
||||
},
|
||||
transcript::{
|
||||
poseidon::{poseidon_test_config, PoseidonTranscript},
|
||||
Transcript,
|
||||
},
|
||||
};
|
||||
use itertools::chain;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
// Function signatures for proof verification on kzg10 and groth16 contracts
|
||||
pub const FUNCTION_SIGNATURE_KZG10_CHECK: [u8; 4] = [0x9e, 0x78, 0xcc, 0xf7];
|
||||
pub const FUNCTION_SIGNATURE_GROTH16_VERIFY_PROOF: [u8; 4] = [0x43, 0x75, 0x3b, 0x4d];
|
||||
|
||||
// Pragma statements for verifiers
|
||||
pub const PRAGMA_GROTH16_VERIFIER: &str = "pragma solidity >=0.7.0 <0.9.0;"; // from snarkjs, avoid changing
|
||||
pub const PRAGMA_KZG10_VERIFIER: &str = "pragma solidity >=0.8.1 <=0.8.4;";
|
||||
|
||||
struct TestAddCircuit<F: PrimeField> {
|
||||
_f: PhantomData<F>,
|
||||
pub x: u8,
|
||||
pub y: u8,
|
||||
pub z: u8,
|
||||
}
|
||||
|
||||
impl<F: PrimeField> ConstraintSynthesizer<F> for TestAddCircuit<F> {
|
||||
fn generate_constraints(self, cs: ConstraintSystemRef<F>) -> Result<(), SynthesisError> {
|
||||
let x = FpVar::<F>::new_witness(cs.clone(), || Ok(F::from(self.x)))?;
|
||||
let y = FpVar::<F>::new_witness(cs.clone(), || Ok(F::from(self.y)))?;
|
||||
let z = FpVar::<F>::new_input(cs.clone(), || Ok(F::from(self.z)))?;
|
||||
let comp_z = x.clone() + y.clone();
|
||||
comp_z.enforce_equal(&z)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_groth16_kzg10_decider_template_renders() {
|
||||
let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(test_rng().next_u64());
|
||||
let (x, y, z) = (21, 21, 42);
|
||||
let (_, vk) = {
|
||||
let c = TestAddCircuit::<Fr> {
|
||||
_f: PhantomData,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
};
|
||||
Groth16::<Bn254>::setup(c, &mut rng).unwrap()
|
||||
};
|
||||
let groth16_template = Groth16Verifier::from(vk, None);
|
||||
let (pk, vk): (ProverKey<G1>, VerifierKey<Bn254>) = KZGSetup::<Bn254>::setup(&mut rng, 5);
|
||||
let kzg10_template = KZG10Verifier::from(&vk, &pk.powers_of_g[..5], None, None);
|
||||
let decider_template = super::templates::Groth16KZG10DeciderVerifier {
|
||||
groth16_verifier: groth16_template,
|
||||
kzg10_verifier: kzg10_template,
|
||||
};
|
||||
save_solidity("decider.sol", &decider_template.render().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_groth16_kzg10_decider_template_compiles() {
|
||||
let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(test_rng().next_u64());
|
||||
let (x, y, z) = (21, 21, 42);
|
||||
let (_, vk) = {
|
||||
let c = TestAddCircuit::<Fr> {
|
||||
_f: PhantomData,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
};
|
||||
Groth16::<Bn254>::setup(c, &mut rng).unwrap()
|
||||
};
|
||||
// we dont specify any pragma values for both verifiers, the pragma from the decider takes over
|
||||
let groth16_template = Groth16Verifier::from(vk, None);
|
||||
let (pk, vk): (ProverKey<G1>, VerifierKey<Bn254>) = KZGSetup::<Bn254>::setup(&mut rng, 5);
|
||||
let kzg10_template = KZG10Verifier::from(&vk, &pk.powers_of_g[..5], None, None);
|
||||
let decider_template = super::templates::Groth16KZG10DeciderVerifier {
|
||||
groth16_verifier: groth16_template,
|
||||
kzg10_verifier: kzg10_template,
|
||||
};
|
||||
let decider_verifier_bytecode =
|
||||
compile_solidity(decider_template.render().unwrap(), "NovaDecider");
|
||||
let mut evm = Evm::default();
|
||||
_ = evm.create(decider_verifier_bytecode);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_groth16_verifier_template_renders() {
|
||||
let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(test_rng().next_u64());
|
||||
let (x, y, z) = (21, 21, 42);
|
||||
let (_, vk) = {
|
||||
let c = TestAddCircuit::<Fr> {
|
||||
_f: PhantomData,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
};
|
||||
Groth16::<Bn254>::setup(c, &mut rng).unwrap()
|
||||
};
|
||||
let template = Groth16Verifier::from(vk, Some(PRAGMA_GROTH16_VERIFIER.to_string()));
|
||||
save_solidity("groth16_verifier.sol", &template.render().unwrap());
|
||||
_ = template.render().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_groth16_verifier_template_compiles() {
|
||||
let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(test_rng().next_u64());
|
||||
let (x, y, z) = (21, 21, 42);
|
||||
let (_, vk) = {
|
||||
let c = TestAddCircuit::<Fr> {
|
||||
_f: PhantomData,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
};
|
||||
Groth16::<Bn254>::setup(c, &mut rng).unwrap()
|
||||
};
|
||||
let res = Groth16Verifier::from(vk, Some(PRAGMA_GROTH16_VERIFIER.to_string()))
|
||||
.render()
|
||||
.unwrap();
|
||||
let groth16_verifier_bytecode = compile_solidity(res, "Verifier");
|
||||
let mut evm = Evm::default();
|
||||
_ = evm.create(groth16_verifier_bytecode);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_groth16_verifier_accepts_and_rejects_proofs() {
|
||||
let mut rng = ark_std::rand::rngs::StdRng::seed_from_u64(test_rng().next_u64());
|
||||
let (x, y, z) = (21, 21, 42);
|
||||
let (pk, vk) = {
|
||||
let c = TestAddCircuit::<Fr> {
|
||||
_f: PhantomData,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
};
|
||||
Groth16::<Bn254>::setup(c, &mut rng).unwrap()
|
||||
};
|
||||
let c = TestAddCircuit::<Fr> {
|
||||
_f: PhantomData,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
};
|
||||
let proof = Groth16::<Bn254>::prove(&pk, c, &mut rng).unwrap();
|
||||
let res = Groth16Verifier::from(vk, Some(PRAGMA_GROTH16_VERIFIER.to_string()))
|
||||
.render()
|
||||
.unwrap();
|
||||
save_solidity("groth16_verifier.sol", &res);
|
||||
let groth16_verifier_bytecode = compile_solidity(&res, "Verifier");
|
||||
let mut evm = Evm::default();
|
||||
let verifier_address = evm.create(groth16_verifier_bytecode);
|
||||
let (a_x, a_y) = proof.a.xy().unwrap();
|
||||
let (b_x, b_y) = proof.b.xy().unwrap();
|
||||
let (c_x, c_y) = proof.c.xy().unwrap();
|
||||
let mut calldata: Vec<u8> = chain![
|
||||
FUNCTION_SIGNATURE_GROTH16_VERIFY_PROOF,
|
||||
a_x.into_bigint().to_bytes_be(),
|
||||
a_y.into_bigint().to_bytes_be(),
|
||||
b_x.c1.into_bigint().to_bytes_be(),
|
||||
b_x.c0.into_bigint().to_bytes_be(),
|
||||
b_y.c1.into_bigint().to_bytes_be(),
|
||||
b_y.c0.into_bigint().to_bytes_be(),
|
||||
c_x.into_bigint().to_bytes_be(),
|
||||
c_y.into_bigint().to_bytes_be(),
|
||||
BigInt::from(Fr::from(z)).to_bytes_be(),
|
||||
]
|
||||
.collect();
|
||||
let (_, output) = evm.call(verifier_address, calldata.clone());
|
||||
assert_eq!(*output.last().unwrap(), 1);
|
||||
|
||||
// change calldata to make it invalid
|
||||
let last_calldata_element = calldata.last_mut().unwrap();
|
||||
*last_calldata_element = 0;
|
||||
let (_, output) = evm.call(verifier_address, calldata);
|
||||
assert_eq!(*output.last().unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_kzg_verifier_template_renders() {
|
||||
let rng = &mut test_rng();
|
||||
let n = 10;
|
||||
let (pk, vk): (ProverKey<G1>, VerifierKey<Bn254>) = KZGSetup::<Bn254>::setup(rng, n);
|
||||
let template = KZG10Verifier::from(
|
||||
&vk,
|
||||
&pk.powers_of_g[..5],
|
||||
Some(PRAGMA_KZG10_VERIFIER.to_string()),
|
||||
None,
|
||||
);
|
||||
let res = template.render().unwrap();
|
||||
assert!(res.contains(&vk.g.x.to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_kzg_verifier_compiles() {
|
||||
let rng = &mut test_rng();
|
||||
let n = 10;
|
||||
let (pk, vk): (ProverKey<G1>, VerifierKey<Bn254>) = KZGSetup::<Bn254>::setup(rng, n);
|
||||
let template = KZG10Verifier::from(
|
||||
&vk,
|
||||
&pk.powers_of_g[..5],
|
||||
Some(PRAGMA_KZG10_VERIFIER.to_string()),
|
||||
None,
|
||||
);
|
||||
let res = template.render().unwrap();
|
||||
let kzg_verifier_bytecode = compile_solidity(res, "KZG10");
|
||||
let mut evm = Evm::default();
|
||||
_ = evm.create(kzg_verifier_bytecode);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_kzg_verifier_accepts_and_rejects_proofs() {
|
||||
let rng = &mut test_rng();
|
||||
let poseidon_config = poseidon_test_config::<Fr>();
|
||||
let transcript_p = &mut PoseidonTranscript::<G1>::new(&poseidon_config);
|
||||
let transcript_v = &mut PoseidonTranscript::<G1>::new(&poseidon_config);
|
||||
|
||||
let n = 10;
|
||||
let (pk, vk): (ProverKey<G1>, VerifierKey<Bn254>) = KZGSetup::<Bn254>::setup(rng, n);
|
||||
let v: Vec<Fr> = std::iter::repeat_with(|| Fr::rand(rng)).take(n).collect();
|
||||
let cm = KZGProver::<G1>::commit(&pk, &v, &Fr::zero()).unwrap();
|
||||
let (eval, proof) =
|
||||
KZGProver::<G1>::prove(&pk, transcript_p, &cm, &v, &Fr::zero()).unwrap();
|
||||
let template = KZG10Verifier::from(
|
||||
&vk,
|
||||
&pk.powers_of_g[..5],
|
||||
Some(PRAGMA_KZG10_VERIFIER.to_string()),
|
||||
None,
|
||||
);
|
||||
let res = template.render().unwrap();
|
||||
let kzg_verifier_bytecode = compile_solidity(res, "KZG10");
|
||||
let mut evm = Evm::default();
|
||||
let verifier_address = evm.create(kzg_verifier_bytecode);
|
||||
|
||||
let (cm_affine, proof_affine) = (cm.into_affine(), proof.into_affine());
|
||||
let (x_comm, y_comm) = cm_affine.xy().unwrap();
|
||||
let (x_proof, y_proof) = proof_affine.xy().unwrap();
|
||||
let y = eval.into_bigint().to_bytes_be();
|
||||
|
||||
transcript_v.absorb_point(&cm).unwrap();
|
||||
let x = transcript_v.get_challenge();
|
||||
|
||||
let x = x.into_bigint().to_bytes_be();
|
||||
let mut calldata: Vec<u8> = chain![
|
||||
FUNCTION_SIGNATURE_KZG10_CHECK,
|
||||
x_comm.into_bigint().to_bytes_be(),
|
||||
y_comm.into_bigint().to_bytes_be(),
|
||||
x_proof.into_bigint().to_bytes_be(),
|
||||
y_proof.into_bigint().to_bytes_be(),
|
||||
x.clone(),
|
||||
y,
|
||||
]
|
||||
.collect();
|
||||
|
||||
let (_, output) = evm.call(verifier_address, calldata.clone());
|
||||
assert_eq!(*output.last().unwrap(), 1);
|
||||
|
||||
// change calldata to make it invalid
|
||||
let last_calldata_element = calldata.last_mut().unwrap();
|
||||
*last_calldata_element = 0;
|
||||
let (_, output) = evm.call(verifier_address, calldata);
|
||||
assert_eq!(*output.last().unwrap(), 0);
|
||||
}
|
||||
}
|
||||
113
folding-schemes-solidity/src/verifiers/templates.rs
Normal file
113
folding-schemes-solidity/src/verifiers/templates.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use std::ops::Deref;
|
||||
|
||||
use crate::utils::encoding::{g1_to_fq_repr, g2_to_fq_repr};
|
||||
/// Solidity templates for the verifier contracts.
|
||||
/// We use askama for templating and define which variables are required for each template.
|
||||
use crate::utils::encoding::{G1Repr, G2Repr};
|
||||
use ark_bn254::{Bn254, G1Affine};
|
||||
use ark_groth16::VerifyingKey;
|
||||
use ark_poly_commit::kzg10::VerifierKey;
|
||||
use askama::Template;
|
||||
|
||||
#[derive(Template, Default)]
|
||||
#[template(path = "groth16_verifier.askama.sol", ext = "sol")]
|
||||
pub struct Groth16Verifier {
|
||||
/// SPDX-License-Identifier
|
||||
pub sdpx: String,
|
||||
/// The `pragma` statement.
|
||||
pub pragma_version: String,
|
||||
/// The `alpha * G`, where `G` is the generator of `G1`.
|
||||
pub vkey_alpha_g1: G1Repr,
|
||||
/// The `alpha * H`, where `H` is the generator of `G2`.
|
||||
pub vkey_beta_g2: G2Repr,
|
||||
/// The `gamma * H`, where `H` is the generator of `G2`.
|
||||
pub vkey_gamma_g2: G2Repr,
|
||||
/// The `delta * H`, where `H` is the generator of `G2`.
|
||||
pub vkey_delta_g2: G2Repr,
|
||||
/// Length of the `gamma_abc_g1` vector.
|
||||
pub gamma_abc_len: usize,
|
||||
/// The `gamma^{-1} * (beta * a_i + alpha * b_i + c_i) * H`, where `H` is the generator of `E::G1`.
|
||||
pub gamma_abc_g1: Vec<G1Repr>,
|
||||
}
|
||||
|
||||
impl Groth16Verifier {
|
||||
pub fn from(value: VerifyingKey<Bn254>, pragma: Option<String>) -> Self {
|
||||
let pragma_version = pragma.unwrap_or_default();
|
||||
let sdpx = "// SPDX-License-Identifier: GPL-3.0".to_string();
|
||||
Self {
|
||||
pragma_version,
|
||||
sdpx,
|
||||
vkey_alpha_g1: g1_to_fq_repr(value.alpha_g1),
|
||||
vkey_beta_g2: g2_to_fq_repr(value.beta_g2),
|
||||
vkey_gamma_g2: g2_to_fq_repr(value.gamma_g2),
|
||||
vkey_delta_g2: g2_to_fq_repr(value.delta_g2),
|
||||
gamma_abc_len: value.gamma_abc_g1.len(),
|
||||
gamma_abc_g1: value
|
||||
.gamma_abc_g1
|
||||
.iter()
|
||||
.copied()
|
||||
.map(g1_to_fq_repr)
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template, Default)]
|
||||
#[template(path = "kzg10_verifier.askama.sol", ext = "sol")]
|
||||
pub struct KZG10Verifier {
|
||||
/// SPDX-License-Identifier
|
||||
pub sdpx: String,
|
||||
/// The `pragma` statement.
|
||||
pub pragma_version: String,
|
||||
/// The generator of `G1`.
|
||||
pub g1: G1Repr,
|
||||
/// The generator of `G2`.
|
||||
pub g2: G2Repr,
|
||||
/// The verification key
|
||||
pub vk: G2Repr,
|
||||
/// Length of the trusted setup vector.
|
||||
pub g1_crs_len: usize,
|
||||
/// The trusted setup vector.
|
||||
pub g1_crs: Vec<G1Repr>,
|
||||
}
|
||||
|
||||
impl KZG10Verifier {
|
||||
pub fn from(
|
||||
vk: &VerifierKey<Bn254>,
|
||||
crs: &[G1Affine],
|
||||
pragma: Option<String>,
|
||||
sdpx: Option<String>,
|
||||
) -> KZG10Verifier {
|
||||
let g1_string_repr = g1_to_fq_repr(vk.g);
|
||||
let g2_string_repr = g2_to_fq_repr(vk.h);
|
||||
let vk_string_repr = g2_to_fq_repr(vk.beta_h);
|
||||
let g1_crs_len = crs.len();
|
||||
let g1_crs = crs.iter().map(|g1| g1_to_fq_repr(*g1)).collect();
|
||||
let sdpx = sdpx.unwrap_or_default();
|
||||
let pragma_version = pragma.unwrap_or_default();
|
||||
KZG10Verifier {
|
||||
sdpx,
|
||||
pragma_version,
|
||||
g1: g1_string_repr,
|
||||
g2: g2_string_repr,
|
||||
vk: vk_string_repr,
|
||||
g1_crs,
|
||||
g1_crs_len,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "kzg10_groth16_decider_verifier.askama.sol", ext = "sol")]
|
||||
pub struct Groth16KZG10DeciderVerifier {
|
||||
pub groth16_verifier: Groth16Verifier,
|
||||
pub kzg10_verifier: KZG10Verifier,
|
||||
}
|
||||
|
||||
impl Deref for Groth16KZG10DeciderVerifier {
|
||||
type Target = Groth16Verifier;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.groth16_verifier
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user