From e44ef085a53fd82a603c3e7f606fddf0818bb6bf Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sun, 22 Oct 2023 20:00:11 +0900 Subject: [PATCH 01/28] Clarify what the CLI commands do --- packages/halo2-circuits/src/bin/cli.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 4ae51e7..b255875 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -23,7 +23,7 @@ struct Cli { #[derive(Debug, Subcommand, Clone)] enum Commands { - /// Generate a setup paramter + /// Generate a trusted setup paramter GenParams { /// k parameter for circuit. #[arg(long)] @@ -31,19 +31,21 @@ enum Commands { #[arg(short, long, default_value = "./params")] params_path: String, }, - /// Generate proving keys for RSA circuit + /// Generate the proving key and the verification key for RSA circuit GenRsaKeys { /// k parameter for circuit. #[arg(long, default_value = "17")] k: u32, - /// setup parameters path + /// trusted setup parameters path #[arg(short, long, default_value = "./params")] params_path: String, /// proving key path #[arg(long, default_value = "./build/rsa.pk")] pk_path: String, + // citizen's certificate #[arg(long, default_value = "./certs/myna_cert.pem")] verify_cert_path: String, + // nation's certificate #[arg(long, default_value = "./certs/ca_cert.pem")] issuer_cert_path: String, }, @@ -51,14 +53,16 @@ enum Commands { /// k parameter for circuit. #[arg(long, default_value = "17")] k: u32, - /// setup parameters path + /// trusted setup parameters path #[arg(short, long, default_value = "./params")] params_path: String, /// proving key path #[arg(long, default_value = "./build/rsa.pk")] pk_path: String, + // citizen's certificate #[arg(long, default_value = "./certs/myna_cert.pem")] verify_cert_path: String, + // nation's certificate #[arg(long, default_value = "./certs/ca_cert.pem")] issuer_cert_path: String, /// output proof file @@ -69,14 +73,16 @@ enum Commands { /// k parameter for circuit. #[arg(long, default_value = "17")] k: u32, - /// setup parameters path + /// trusted setup parameters path #[arg(short, long, default_value = "./params")] params_path: String, /// proving key path #[arg(long, default_value = "./build/rsa.pk")] pk_path: String, + // citizen's certificate #[arg(long, default_value = "./certs/myna_cert.pem")] verify_cert_path: String, + // nation's certificate #[arg(long, default_value = "./certs/ca_cert.pem")] issuer_cert_path: String, /// output proof file From 4629079846d4e6107c121a4d137bcb695b372831 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Thu, 2 Nov 2023 18:14:03 +0900 Subject: [PATCH 02/28] Add rustfmt.toml --- packages/halo2-circuits/rustfmt.toml | 14 ++++++ packages/halo2-circuits/src/bin/cli.rs | 66 ++++++------------------ packages/halo2-circuits/src/helpers.rs | 69 ++++++++------------------ 3 files changed, 50 insertions(+), 99 deletions(-) create mode 100644 packages/halo2-circuits/rustfmt.toml diff --git a/packages/halo2-circuits/rustfmt.toml b/packages/halo2-circuits/rustfmt.toml new file mode 100644 index 0000000..8e98b09 --- /dev/null +++ b/packages/halo2-circuits/rustfmt.toml @@ -0,0 +1,14 @@ +edition = "2021" +version = "Two" +tab_spaces = 4 +use_small_heuristics = "Max" +max_width = 120 +wrap_comments = true +comment_width = 120 +format_code_in_doc_comments = true +doc_comment_code_block_width = 120 +normalize_doc_attributes = true +imports_granularity = "Crate" +hex_literal_case = "Upper" +condense_wildcard_suffixes = true +use_try_shorthand = true diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index b255875..ab38ca9 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -1,7 +1,8 @@ use clap::{Parser, Subcommand}; use halo2_base::{ - gates::circuit::builder::BaseCircuitBuilder, halo2_proofs::halo2curves::bn256::Fr, - halo2_proofs::plonk::Circuit, utils::fs::gen_srs, + gates::circuit::builder::BaseCircuitBuilder, + halo2_proofs::{halo2curves::bn256::Fr, plonk::Circuit}, + utils::fs::gen_srs, }; use halo2_circuits::helpers::*; use snark_verifier_sdk::{ @@ -10,9 +11,7 @@ use snark_verifier_sdk::{ halo2::gen_snark_shplonk, read_pk, CircuitExt, }; -use std::env; -use std::fs::remove_file; -use std::path::Path; +use std::{env, fs::remove_file, path::Path}; #[derive(Parser, Debug, Clone)] #[command(author, version, about, long_about = None)] @@ -99,25 +98,15 @@ async fn main() { env::set_var("PARAMS_DIR", params_path); gen_srs(k); } - Commands::GenRsaKeys { - k, - params_path, - pk_path, - verify_cert_path, - issuer_cert_path, - } => { + Commands::GenRsaKeys { k, params_path, pk_path, verify_cert_path, issuer_cert_path } => { env::set_var("PARAMS_DIR", params_path); let params = gen_srs(k); let (tbs, signature_bigint) = extract_tbs_and_sig(&verify_cert_path); let public_key_modulus = extract_public_key(&issuer_cert_path); - let builder = create_default_rsa_circuit_with_instances( - k as usize, - tbs, - public_key_modulus, - signature_bigint, - ); + let builder = + create_default_rsa_circuit_with_instances(k as usize, tbs, public_key_modulus, signature_bigint); if Path::new(&pk_path).exists() { match remove_file(&pk_path) { @@ -127,28 +116,16 @@ async fn main() { } gen_pk(¶ms, &builder, Some(Path::new(&pk_path))); } - Commands::ProveRsa { - k, - params_path, - pk_path, - verify_cert_path, - issuer_cert_path, - proof_path, - } => { + Commands::ProveRsa { k, params_path, pk_path, verify_cert_path, issuer_cert_path, proof_path } => { env::set_var("PARAMS_DIR", params_path); let params = gen_srs(k); let (tbs, signature_bigint) = extract_tbs_and_sig(&verify_cert_path); let public_key_modulus = extract_public_key(&issuer_cert_path); - let builder = create_default_rsa_circuit_with_instances( - k as usize, - tbs, - public_key_modulus, - signature_bigint, - ); - let pk = - read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); + let builder = + create_default_rsa_circuit_with_instances(k as usize, tbs, public_key_modulus, signature_bigint); + let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); if Path::new(&proof_path).exists() { match remove_file(&proof_path) { @@ -158,28 +135,16 @@ async fn main() { } gen_snark_shplonk(¶ms, &pk, builder.clone(), Some(Path::new(&proof_path))); } - Commands::GenRsaVerifyEVMProof { - k, - params_path, - pk_path, - verify_cert_path, - issuer_cert_path, - proof_path, - } => { + Commands::GenRsaVerifyEVMProof { k, params_path, pk_path, verify_cert_path, issuer_cert_path, proof_path } => { env::set_var("PARAMS_DIR", params_path); let params = gen_srs(k); let (tbs, signature_bigint) = extract_tbs_and_sig(&verify_cert_path); let public_key_modulus = extract_public_key(&issuer_cert_path); - let builder = create_default_rsa_circuit_with_instances( - k as usize, - tbs, - public_key_modulus, - signature_bigint, - ); - let pk = - read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); + let builder = + create_default_rsa_circuit_with_instances(k as usize, tbs, public_key_modulus, signature_bigint); + let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); if Path::new(&proof_path).exists() { match remove_file(&proof_path) { @@ -207,7 +172,6 @@ async fn main() { write_calldata(&builder.instances(), &proof, Path::new("./build/calldata.txt")).unwrap(); println!("Succesfully generate calldata!"); - } } } diff --git a/packages/halo2-circuits/src/helpers.rs b/packages/halo2-circuits/src/helpers.rs index 8f05158..b0b33ee 100644 --- a/packages/halo2-circuits/src/helpers.rs +++ b/packages/halo2-circuits/src/helpers.rs @@ -5,10 +5,7 @@ use halo2_base::{ AssignedValue, QuantumCell::{Constant, Existing}, }; -use halo2_rsa::{ - BigUintConfig, BigUintInstructions, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, - RSASignature, -}; +use halo2_rsa::{BigUintConfig, BigUintInstructions, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, RSASignature}; use halo2_sha256_unoptimized::Sha256Chip; use snark_verifier_sdk::{gen_pk, halo2::gen_snark_shplonk, Snark}; @@ -16,28 +13,22 @@ use itertools::Itertools; use num_bigint::BigUint; use openssl::ssl::{SslConnector, SslMethod}; use sha2::{Digest, Sha256}; -use std::fs::File; -use std::io::Read; -use std::io::Write; -use std::net::TcpStream; -use std::vec; -use x509_parser::pem::parse_x509_pem; -use x509_parser::public_key::PublicKey; +use std::{ + fs::File, + io::{Read, Write}, + net::TcpStream, + vec, +}; +use x509_parser::{pem::parse_x509_pem, public_key::PublicKey}; pub fn extract_public_key(cert_path: &str) -> BigUint { println!("{:?}", cert_path); let mut cert_file = File::open(cert_path).expect("Failed to open cert pem file"); let mut cert_pem_buffer = Vec::new(); - cert_file - .read_to_end(&mut cert_pem_buffer) - .expect("Failed to read cert PEM file"); + cert_file.read_to_end(&mut cert_pem_buffer).expect("Failed to read cert PEM file"); - let cert_pem = parse_x509_pem(&cert_pem_buffer) - .expect("Failed to parse cert") - .1; - let cert = cert_pem - .parse_x509() - .expect("Failed to parse PEM certificate"); + let cert_pem = parse_x509_pem(&cert_pem_buffer).expect("Failed to parse cert").1; + let cert = cert_pem.parse_x509().expect("Failed to parse PEM certificate"); match cert.public_key().parsed().unwrap() { PublicKey::RSA(public_key) => BigUint::from_bytes_be(public_key.modulus), @@ -49,17 +40,12 @@ pub fn extract_tbs_and_sig(cert_path: &str) -> (Vec, BigUint) { // Read the PEM certificate from a file let mut cert_file = File::open(cert_path).expect("Failed to open PEM file"); let mut cert_pem_buffer = Vec::new(); - cert_file - .read_to_end(&mut cert_pem_buffer) - .expect("Failed to read PEM file"); + cert_file.read_to_end(&mut cert_pem_buffer).expect("Failed to read PEM file"); // Parse the PEM certificate using x509-parser - let cert_pem = parse_x509_pem(&cert_pem_buffer) - .unwrap_or_else(|e| panic!("Failed to parse PEM ${:?} {:?}", &cert_path, e)) - .1; - let cert = cert_pem - .parse_x509() - .expect("Failed to parse PEM certificate"); + let cert_pem = + parse_x509_pem(&cert_pem_buffer).unwrap_or_else(|e| panic!("Failed to parse PEM ${:?} {:?}", &cert_path, e)).1; + let cert = cert_pem.parse_x509().expect("Failed to parse PEM certificate"); // Extract the TBS (To-Be-Signed) data from the certificate let tbs = cert.tbs_certificate.as_ref(); @@ -100,24 +86,16 @@ pub fn create_default_rsa_circuit_with_instances( // Hash in pure Rust vs in-circuit let hashed_tbs = Sha256::digest(tbs); println!("Hashed TBS: {:?}", hashed_tbs); - let mut hashed_bytes: Vec> = hashed_tbs - .iter() - .map(|limb| ctx.load_witness(Fr::from(*limb as u64))) - .collect_vec(); + let mut hashed_bytes: Vec> = + hashed_tbs.iter().map(|limb| ctx.load_witness(Fr::from(*limb as u64))).collect_vec(); hashed_bytes.reverse(); let bytes_bits = hashed_bytes.len() * 8; let limb_bits = bigint_chip.limb_bits(); let limb_bytes = limb_bits / 8; let mut hashed_u64s = vec![]; - let bases = (0..limb_bytes) - .map(|i| Fr::from(1u64 << (8 * i))) - .map(Constant) - .collect_vec(); + let bases = (0..limb_bytes).map(|i| Fr::from(1u64 << (8 * i))).map(Constant).collect_vec(); for i in 0..(bytes_bits / limb_bits) { - let left = hashed_bytes[limb_bytes * i..limb_bytes * (i + 1)] - .iter() - .map(|x| Existing(*x)) - .collect_vec(); + let left = hashed_bytes[limb_bytes * i..limb_bytes * (i + 1)].iter().map(|x| Existing(*x)).collect_vec(); let sum = bigint_chip.gate().inner_product(ctx, left, bases.clone()); hashed_u64s.push(sum); } @@ -131,13 +109,8 @@ pub fn create_default_rsa_circuit_with_instances( let signature = RSASignature::new(signature_bigint.clone()); // cloning might be slow let signature = rsa_chip.assign_signature(ctx, signature).unwrap(); - let is_valid = rsa_chip - .verify_pkcs1v15_signature(ctx, &public_key, &hashed_u64s, &signature) - .unwrap(); - rsa_chip - .biguint_config() - .gate() - .assert_is_const(ctx, &is_valid, &Fr::one()); + let is_valid = rsa_chip.verify_pkcs1v15_signature(ctx, &public_key, &hashed_u64s, &signature).unwrap(); + rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_valid, &Fr::one()); // Insert input hash as public instance for circuit hashed_bytes.reverse(); From 2a0b8468c9eeed44b5fc805930124f821cff7097 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sun, 5 Nov 2023 02:01:33 +0900 Subject: [PATCH 03/28] Calculate the identity commitment --- Cargo.lock | 1 + packages/halo2-circuits/Cargo.toml | 4 + packages/halo2-circuits/src/bin/cli.rs | 177 +++++++++------------- packages/halo2-circuits/src/circuit.rs | 198 +++++++++++++++++++++++++ packages/halo2-circuits/src/helpers.rs | 23 ++- packages/halo2-circuits/src/lib.rs | 18 +-- 6 files changed, 290 insertions(+), 131 deletions(-) create mode 100644 packages/halo2-circuits/src/circuit.rs diff --git a/Cargo.lock b/Cargo.lock index 7367eee..8944103 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2154,6 +2154,7 @@ dependencies = [ "getrandom", "getset", "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", "halo2-rsa", "halo2-sha256-unoptimized", "itertools 0.11.0", diff --git a/packages/halo2-circuits/Cargo.toml b/packages/halo2-circuits/Cargo.toml index 48feebd..84ba7d0 100644 --- a/packages/halo2-circuits/Cargo.toml +++ b/packages/halo2-circuits/Cargo.toml @@ -20,6 +20,10 @@ halo2-base = { branch = "community-edition", default-features = false, features "display", "test-utils", ], git = "https://github.com/axiom-crypto/halo2-lib.git" } +halo2-ecc = { branch = "community-edition", default-features = false, features = [ + "halo2-axiom", + "display", +], git = "https://github.com/axiom-crypto/halo2-lib.git" } zkevm-hashes = { branch = "feat/zkevm-sha256", default-features = false, features = [ "halo2-axiom", "display", diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index ab38ca9..41bfa06 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -2,9 +2,9 @@ use clap::{Parser, Subcommand}; use halo2_base::{ gates::circuit::builder::BaseCircuitBuilder, halo2_proofs::{halo2curves::bn256::Fr, plonk::Circuit}, - utils::fs::gen_srs, + utils::{fs::gen_srs, BigPrimeField}, }; -use halo2_circuits::helpers::*; +use halo2_circuits::{circuit, helpers::*}; use snark_verifier_sdk::{ evm::{evm_verify, gen_evm_proof_shplonk, gen_evm_verifier_shplonk, write_calldata}, gen_pk, @@ -23,7 +23,7 @@ struct Cli { #[derive(Debug, Subcommand, Clone)] enum Commands { /// Generate a trusted setup paramter - GenParams { + TrustedSetup { /// k parameter for circuit. #[arg(long)] k: u32, @@ -31,82 +31,43 @@ enum Commands { params_path: String, }, /// Generate the proving key and the verification key for RSA circuit - GenRsaKeys { + Prove { /// k parameter for circuit. #[arg(long, default_value = "17")] k: u32, - /// trusted setup parameters path + /// trusted setup parameters path. input #[arg(short, long, default_value = "./params")] params_path: String, - /// proving key path + /// proving key path. output #[arg(long, default_value = "./build/rsa.pk")] pk_path: String, - // citizen's certificate - #[arg(long, default_value = "./certs/myna_cert.pem")] - verify_cert_path: String, - // nation's certificate - #[arg(long, default_value = "./certs/ca_cert.pem")] - issuer_cert_path: String, - }, - ProveRsa { - /// k parameter for circuit. - #[arg(long, default_value = "17")] - k: u32, - /// trusted setup parameters path - #[arg(short, long, default_value = "./params")] - params_path: String, - /// proving key path - #[arg(long, default_value = "./build/rsa.pk")] - pk_path: String, - // citizen's certificate - #[arg(long, default_value = "./certs/myna_cert.pem")] - verify_cert_path: String, - // nation's certificate - #[arg(long, default_value = "./certs/ca_cert.pem")] - issuer_cert_path: String, - /// output proof file + /// proof path. output #[arg(long, default_value = "./build/myna_verify_rsa.proof")] proof_path: String, - }, - GenRsaVerifyEVMProof { - /// k parameter for circuit. - #[arg(long, default_value = "17")] - k: u32, - /// trusted setup parameters path - #[arg(short, long, default_value = "./params")] - params_path: String, - /// proving key path - #[arg(long, default_value = "./build/rsa.pk")] - pk_path: String, // citizen's certificate #[arg(long, default_value = "./certs/myna_cert.pem")] verify_cert_path: String, // nation's certificate #[arg(long, default_value = "./certs/ca_cert.pem")] issuer_cert_path: String, - /// output proof file - #[arg(long, default_value = "./build/myna_verify_rsa.proof")] - proof_path: String, + password: u64, }, } -#[tokio::main] -async fn main() { +fn main() { let cli = Cli::parse(); match cli.command { - Commands::GenParams { k, params_path } => { + Commands::TrustedSetup { k, params_path } => { env::set_var("PARAMS_DIR", params_path); gen_srs(k); } - Commands::GenRsaKeys { k, params_path, pk_path, verify_cert_path, issuer_cert_path } => { - env::set_var("PARAMS_DIR", params_path); - let params = gen_srs(k); + Commands::Prove { k, params_path, pk_path, proof_path, verify_cert_path, issuer_cert_path, password } => { + let nation_pubkey = read_nation_cert(&issuer_cert_path); + let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); - let (tbs, signature_bigint) = extract_tbs_and_sig(&verify_cert_path); - let public_key_modulus = extract_public_key(&issuer_cert_path); - - let builder = - create_default_rsa_circuit_with_instances(k as usize, tbs, public_key_modulus, signature_bigint); + let public = circuit::PublicInput { nation_pubkey }; + let private = circuit::PrivateInput { tbs_cert, nation_sig, password: Fr::from(password) }; + let builder = circuit::proof_of_japanese_residence(public, private); if Path::new(&pk_path).exists() { match remove_file(&pk_path) { @@ -114,18 +75,6 @@ async fn main() { Err(e) => println!("An error occurred: {}", e), } } - gen_pk(¶ms, &builder, Some(Path::new(&pk_path))); - } - Commands::ProveRsa { k, params_path, pk_path, verify_cert_path, issuer_cert_path, proof_path } => { - env::set_var("PARAMS_DIR", params_path); - let params = gen_srs(k); - - let (tbs, signature_bigint) = extract_tbs_and_sig(&verify_cert_path); - let public_key_modulus = extract_public_key(&issuer_cert_path); - - let builder = - create_default_rsa_circuit_with_instances(k as usize, tbs, public_key_modulus, signature_bigint); - let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); if Path::new(&proof_path).exists() { match remove_file(&proof_path) { @@ -133,45 +82,61 @@ async fn main() { Err(e) => println!("An error occurred: {}", e), } } - gen_snark_shplonk(¶ms, &pk, builder.clone(), Some(Path::new(&proof_path))); - } - Commands::GenRsaVerifyEVMProof { k, params_path, pk_path, verify_cert_path, issuer_cert_path, proof_path } => { - env::set_var("PARAMS_DIR", params_path); - let params = gen_srs(k); - let (tbs, signature_bigint) = extract_tbs_and_sig(&verify_cert_path); - let public_key_modulus = extract_public_key(&issuer_cert_path); - - let builder = - create_default_rsa_circuit_with_instances(k as usize, tbs, public_key_modulus, signature_bigint); - let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); - - if Path::new(&proof_path).exists() { - match remove_file(&proof_path) { - Ok(_) => println!("File found, overwriting..."), - Err(e) => println!("An error occurred: {}", e), - } - } - gen_snark_shplonk(¶ms, &pk, builder.clone(), Some(Path::new(&proof_path))); - - let deployment_code = gen_evm_verifier_shplonk::>( - ¶ms, - pk.get_vk(), - builder.num_instance(), - Some(Path::new("./build/VerifyRsa.sol")), - ); - - let proof = gen_evm_proof_shplonk(¶ms, &pk, builder.clone(), builder.instances()); - - println!("Size of the contract: {} bytes", deployment_code.len()); - println!("Deploying contract..."); - - evm_verify(deployment_code, builder.instances(), proof.clone()); - - println!("Verification success!"); - - write_calldata(&builder.instances(), &proof, Path::new("./build/calldata.txt")).unwrap(); - println!("Succesfully generate calldata!"); - } + env::set_var("PARAMS_DIR", params_path); + let trusted_setup = gen_srs(k); + let pk = gen_pk(&trusted_setup, &builder, Some(Path::new(&pk_path))); + gen_snark_shplonk(&trusted_setup, &pk, builder, Some(Path::new(&proof_path))); + } /* Commands::GenRsaVerifyEVMProof { + * k, + * params_path, + * pk_path, + * verify_cert_path, + * issuer_cert_path, + * proof_path, + * } => { + * env::set_var("PARAMS_DIR", params_path); + * let params = gen_srs(k); */ + + /* let (tbs, signature_bigint) = extract_tbs_and_sig(&verify_cert_path); + * let public_key_modulus = extract_public_key(&issuer_cert_path); */ + + /* let builder = create_default_rsa_circuit_with_instances( + * k as usize, + * tbs, + * public_key_modulus, + * signature_bigint, + * ); + * let pk = + * read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); */ + + /* if Path::new(&proof_path).exists() { + * match remove_file(&proof_path) { + * Ok(_) => println!("File found, overwriting..."), + * Err(e) => println!("An error occurred: {}", e), + * } + * } + * gen_snark_shplonk(¶ms, &pk, builder.clone(), Some(Path::new(&proof_path))); */ + + /* let deployment_code = gen_evm_verifier_shplonk::>( + * ¶ms, + * pk.get_vk(), + * builder.num_instance(), + * Some(Path::new("./build/VerifyRsa.sol")), + * ); */ + + /* let proof = gen_evm_proof_shplonk(¶ms, &pk, builder.clone(), builder.instances()); */ + + /* println!("Size of the contract: {} bytes", deployment_code.len()); + * println!("Deploying contract..."); */ + + /* evm_verify(deployment_code, builder.instances(), proof.clone()); */ + + /* println!("Verification success!"); */ + + /* write_calldata(&builder.instances(), &proof, Path::new("./build/calldata.txt")).unwrap(); + * println!("Succesfully generate calldata!"); */ + + /* } */ } } diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs new file mode 100644 index 0000000..a62092f --- /dev/null +++ b/packages/halo2-circuits/src/circuit.rs @@ -0,0 +1,198 @@ +use halo2_base::{ + gates::{circuit::builder::BaseCircuitBuilder, GateInstructions, RangeChip, RangeInstructions}, + halo2_proofs::{arithmetic::Field, halo2curves::bn256::Fr}, + poseidon::hasher::{spec::OptimizedPoseidonSpec, PoseidonHasher}, + AssignedValue, Context, +}; +use halo2_ecc::bigint::OverflowInteger; +use halo2_rsa::{ + AssignedBigUint, AssignedRSAPubE, AssignedRSAPublicKey, AssignedRSASignature, BigUintConfig, BigUintInstructions, + Fresh, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, RSASignature, +}; +use num_bigint::BigUint; +use num_traits::{identities::One, ToPrimitive}; + +#[derive(Debug, Clone)] +pub struct PublicInput { + // 2048 bits + pub nation_pubkey: BigUint, +} + +#[derive(Debug, Clone)] +pub struct PrivateInput { + pub tbs_cert: BigUint, + // 2048 bits + pub nation_sig: BigUint, + pub password: Fr, +} + +// LOOKUP_BITS must be divisible by 64. because halo2-rsa uses limbs that are 64 bits wide each. +const LOOKUP_BITS: usize = 16; +const RSA_KEY_SIZE: usize = 2048; +const PUBKEY_BEGINS: usize = 2216; +const E: usize = 65537; +// The reason we chose 64 here is because +// a) 2048, the width of RSA keys, must be able to divide limb_bits https://github.com/zkemail/halo2-rsa/blob/main/src/big_uint/chip.rs#L49C49-L49C49 +// b) limb_bits * 2 must be smaller than 253 the order of the field https://github.com/axiom-crypto/halo2-lib/blob/dd21d6c2ddb1c6cb5ef78f20d68a6c9682353698/halo2-ecc/src/bigint/mul_no_carry.rs#L8 +// the maximum value that satisfies the both is 64 +const LIMB_BITS: usize = 64; + +// halo2_rsa's mul_mod constraints are too heavy for just taking a bit slice. +// here I write optimized constraints that constraints the same thing. +fn slice_biguint( + ctx: &mut Context, + biguint_chip: &BigUintConfig, + src: AssignedBigUint, + since: usize, + until: usize, +) -> AssignedBigUint { + assert!(0 < src.num_limbs()); + assert!(since < until); + + // I want an auditor to look at this function carefully + // since: | + // until: | + // src: |----|----|----|----|----|----| + // dest: |----|----|----|-| + // beginning_part: |-| |-| |-| |-| + // ending_part: |--| |--| |--| |-| + // final_part: || + // + + let beginning_part_width = since % biguint_chip.limb_bits(); + let ending_part_base = ctx.load_constant(Fr::from(2).pow_vartime([beginning_part_width as u64])); + let ending_part_width = biguint_chip.limb_bits() - beginning_part_width; + let beginning_part_base = ctx.load_constant(Fr::from(2).pow_vartime([ending_part_width as u64])); + let final_part_offset = until % biguint_chip.limb_bits(); + let final_part_base = ctx.load_constant(Fr::from(2).pow_vartime([final_part_offset as u64])); + let mut parts: Vec> = Vec::new(); + + // assign witnesses + for (i, src_limb) in src.value().iter_u64_digits().enumerate() { + let do_src_and_dest_overlap = + since < (i + 1) * biguint_chip.limb_bits() && until > i * biguint_chip.limb_bits(); + if !do_src_and_dest_overlap { + continue; + } + + let beginning_part_max_width = until - i * biguint_chip.limb_bits(); + let beginning_part_width = beginning_part_width.min(beginning_part_max_width); + let beginning_part = BigUint::from(src_limb) % (BigUint::one() << beginning_part_width); + parts.push(ctx.load_witness(Fr::from(beginning_part.to_u64().unwrap()))); + + let ending_part_max_width = until - i * biguint_chip.limb_bits() - beginning_part_width; + let ending_part_width = ending_part_width.min(ending_part_max_width); + let ending_part = (BigUint::from(src_limb) >> beginning_part_width) % (BigUint::one() << ending_part_width); + parts.push(ctx.load_witness(Fr::from(ending_part.to_u64().unwrap()))); + + if until < (i + 1) * biguint_chip.limb_bits() { + let final_part = src_limb >> final_part_offset; + parts.push(ctx.load_witness(Fr::from(final_part))); + } + } + + // range check the first beginning part + // it does not overlap with dest + // thus the range check for dest does not imply a range check for the first beginning part + let width: usize = (until - since) as usize; + biguint_chip.range().range_check(ctx, parts[0], beginning_part_width.min(width)); + + let chunks = parts.chunks_exact(2); + let final_part = if let &[final_part] = chunks.remainder() { final_part } else { ctx.load_zero() }; + + // constrain against src + for (i, pair) in chunks.enumerate() { + let is_last = i + 1 == parts.len() / 2; + let final_part = if is_last { final_part } else { ctx.load_zero() }; + + if let &[beginning_part, ending_part] = pair { + let src_limb = biguint_chip.gate().mul_add(ctx, ending_part_base, ending_part, beginning_part); + let src_limb = biguint_chip.gate().mul_add(ctx, final_part_base, final_part, src_limb); + + ctx.constrain_equal(&src.limbs()[since / biguint_chip.limb_bits() + i], &src_limb); + } else { + unreachable!(); + } + } + + // constrain against dest + let dest_limbs: Vec> = parts[1..parts.len() - 1] + .chunks_exact(2) + .map(|pair| { + if let &[ending_part, beginning_part] = pair { + let dest_limb = biguint_chip.gate().mul_add(ctx, beginning_part_base, beginning_part, ending_part); + biguint_chip.range().range_check(ctx, dest_limb, biguint_chip.limb_bits()); + dest_limb + } else { + unreachable!(); + } + }) + .collect(); + let dest_in_rust = (src.value() >> since) % (BigUint::one() << width); + let dest_in_circuit = + AssignedBigUint::new(OverflowInteger::new(dest_limbs, biguint_chip.limb_bits()), dest_in_rust); + + dest_in_circuit +} + +pub fn proof_of_japanese_residence(public: PublicInput, private: PrivateInput) -> BaseCircuitBuilder { + // TODO: Choose this k + let k = 17; + let exp_bits = 5; // UNUSED + + let mut builder = BaseCircuitBuilder::new(false); + builder.set_k(k); + builder.set_lookup_bits(LOOKUP_BITS); + builder.set_instance_columns(1); + + let range_chip = builder.range_chip(); + let ctx = builder.main(0); + let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip, LIMB_BITS); + let rsa_chip = RSAConfig::construct(biguint_chip, RSA_KEY_SIZE, exp_bits); + let mut poseidon = PoseidonHasher::new(OptimizedPoseidonSpec::::new::<8, 57, 0>()); + poseidon.initialize_consts(ctx, rsa_chip.gate()); + + // load public inputs + let nation_pubkey = + rsa_chip.assign_public_key(ctx, RSAPublicKey::new(public.nation_pubkey, RSAPubE::Fix(E.into()))).unwrap(); + + // load private inputs + let tbs_cert = rsa_chip.biguint_config().assign_integer(ctx, &private.tbs_cert, 1 << 15).unwrap(); + let nation_sig = rsa_chip.assign_signature(ctx, RSASignature::new(private.nation_sig)).unwrap(); + let password = ctx.load_witness(private.password); + + // extract citizen's public key from the tbs certificate + let n = slice_biguint(ctx, &rsa_chip.biguint_config(), tbs_cert, PUBKEY_BEGINS, PUBKEY_BEGINS + RSA_KEY_SIZE); + let citizen_pubkey = AssignedRSAPublicKey::new(n.clone(), AssignedRSAPubE::Fix(E.into())); + + let identity_commitment_preimage: Vec> = + n.limbs().into_iter().copied().chain(std::iter::once(password)).collect(); + let identity_commitment = poseidon.hash_fix_len_array(ctx, rsa_chip.gate(), &identity_commitment_preimage); + + builder.assigned_instances[0].push(identity_commitment); + let circuit_params = builder.calculate_params(None); + builder.use_params(circuit_params) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::helpers::read_citizen_cert; + use halo2_base::utils::testing::base_test; + + // TODO: Write tests for failure cases + #[test] + fn extract_citizen_pubkey() { + let (_, tbs_cert, expected_citizen_pubkey) = read_citizen_cert("certs/myna_cert.pem"); + base_test().k(LOOKUP_BITS as u32).bench_builder((), (), |pool, range_chip, _| { + let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); + let tbs_cert = biguint_chip.assign_integer(pool.main(), &tbs_cert, 1 << 15).unwrap(); + let expected = biguint_chip.assign_constant(pool.main(), expected_citizen_pubkey.clone()).unwrap(); + let result = + slice_biguint(pool.main(), &biguint_chip, tbs_cert, PUBKEY_BEGINS, PUBKEY_BEGINS + RSA_KEY_SIZE); + let is_ok = biguint_chip.is_equal_fresh(pool.main(), &result, &expected).unwrap(); + let one = pool.main().load_constant(Fr::one()); + pool.main().constrain_equal(&is_ok, &one); + }); + } +} diff --git a/packages/halo2-circuits/src/helpers.rs b/packages/halo2-circuits/src/helpers.rs index b0b33ee..52b4606 100644 --- a/packages/halo2-circuits/src/helpers.rs +++ b/packages/halo2-circuits/src/helpers.rs @@ -21,7 +21,7 @@ use std::{ }; use x509_parser::{pem::parse_x509_pem, public_key::PublicKey}; -pub fn extract_public_key(cert_path: &str) -> BigUint { +pub fn read_nation_cert(cert_path: &str) -> BigUint { println!("{:?}", cert_path); let mut cert_file = File::open(cert_path).expect("Failed to open cert pem file"); let mut cert_pem_buffer = Vec::new(); @@ -36,7 +36,11 @@ pub fn extract_public_key(cert_path: &str) -> BigUint { } } -pub fn extract_tbs_and_sig(cert_path: &str) -> (Vec, BigUint) { +// returns +// - nation's signature +// - citizen's tbs certificate +// - citizen's public key +pub fn read_citizen_cert(cert_path: &str) -> (BigUint, BigUint, BigUint) { // Read the PEM certificate from a file let mut cert_file = File::open(cert_path).expect("Failed to open PEM file"); let mut cert_pem_buffer = Vec::new(); @@ -48,15 +52,18 @@ pub fn extract_tbs_and_sig(cert_path: &str) -> (Vec, BigUint) { let cert = cert_pem.parse_x509().expect("Failed to parse PEM certificate"); // Extract the TBS (To-Be-Signed) data from the certificate - let tbs = cert.tbs_certificate.as_ref(); + let tbs_bytes = cert.tbs_certificate.as_ref(); + let tbs_biguint = BigUint::from_bytes_le(tbs_bytes); // println!("TBS (To-Be-Signed): {:x?}", tbs); // Extract the signature from cert 3 - let signature_bytes = &cert.signature_value; - let signature_bigint = BigUint::from_bytes_be(&signature_bytes.data); - // println!("Signature: {:?}", signature_bigint); + let nation_sig_bytes = &cert.signature_value; + let nation_sig_biguint = BigUint::from_bytes_le(&nation_sig_bytes.data); - (tbs.to_vec(), signature_bigint) + let citizen_pubkey_bytes = cert.tbs_certificate.subject_pki.subject_public_key.as_ref(); + let citizen_pubkey_biguint = BigUint::from_bytes_le(&citizen_pubkey_bytes[9..256 + 9]); + + (nation_sig_biguint, tbs_biguint, citizen_pubkey_biguint) } pub fn create_default_rsa_circuit_with_instances( @@ -116,7 +123,7 @@ pub fn create_default_rsa_circuit_with_instances( hashed_bytes.reverse(); builder.assigned_instances[0].extend(hashed_bytes); - let circuit_params = builder.calculate_params(Some(10)); + let circuit_params = builder.calculate_params(None); println!("Circuit params: {:?}", circuit_params); builder.use_params(circuit_params) } diff --git a/packages/halo2-circuits/src/lib.rs b/packages/halo2-circuits/src/lib.rs index da63098..2c13e3f 100644 --- a/packages/halo2-circuits/src/lib.rs +++ b/packages/halo2-circuits/src/lib.rs @@ -1,18 +1,2 @@ -use halo2_base::{ - gates::{ - circuit::{builder::BaseCircuitBuilder, BaseConfig, CircuitBuilderStage}, - flex_gate::MultiPhaseThreadBreakPoints, - }, - halo2_proofs::{ - circuit::{Layouter, SimpleFloorPlanner}, - halo2curves::bn256::{Bn256, Fr}, - plonk::{self, Circuit, ConstraintSystem, Selector}, - poly::kzg::commitment::ParamsKZG, - }, -}; -use itertools::Itertools; -use snark_verifier_sdk::{ - halo2::aggregation::{AggregationCircuit, AggregationConfigParams, VerifierUniversality}, - CircuitExt, Snark, SHPLONK, -}; +pub mod circuit; pub mod helpers; From a88b3545dcbbfc4baece39530ff90bbcb59e00ea Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sun, 5 Nov 2023 19:54:25 +0900 Subject: [PATCH 04/28] Make the test pass with LIMB_BITS=32 --- packages/halo2-circuits/src/circuit.rs | 34 ++++++++++++-------------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index a62092f..fcfad49 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -1,13 +1,13 @@ use halo2_base::{ - gates::{circuit::builder::BaseCircuitBuilder, GateInstructions, RangeChip, RangeInstructions}, + gates::{circuit::builder::BaseCircuitBuilder, GateInstructions, RangeInstructions}, halo2_proofs::{arithmetic::Field, halo2curves::bn256::Fr}, poseidon::hasher::{spec::OptimizedPoseidonSpec, PoseidonHasher}, AssignedValue, Context, }; use halo2_ecc::bigint::OverflowInteger; use halo2_rsa::{ - AssignedBigUint, AssignedRSAPubE, AssignedRSAPublicKey, AssignedRSASignature, BigUintConfig, BigUintInstructions, - Fresh, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, RSASignature, + AssignedBigUint, AssignedRSAPubE, AssignedRSAPublicKey, BigUintConfig, BigUintInstructions, Fresh, RSAConfig, + RSAInstructions, RSAPubE, RSAPublicKey, RSASignature, }; use num_bigint::BigUint; use num_traits::{identities::One, ToPrimitive}; @@ -35,7 +35,7 @@ const E: usize = 65537; // a) 2048, the width of RSA keys, must be able to divide limb_bits https://github.com/zkemail/halo2-rsa/blob/main/src/big_uint/chip.rs#L49C49-L49C49 // b) limb_bits * 2 must be smaller than 253 the order of the field https://github.com/axiom-crypto/halo2-lib/blob/dd21d6c2ddb1c6cb5ef78f20d68a6c9682353698/halo2-ecc/src/bigint/mul_no_carry.rs#L8 // the maximum value that satisfies the both is 64 -const LIMB_BITS: usize = 64; +const LIMB_BITS: usize = 32; // halo2_rsa's mul_mod constraints are too heavy for just taking a bit slice. // here I write optimized constraints that constraints the same thing. @@ -57,7 +57,6 @@ fn slice_biguint( // beginning_part: |-| |-| |-| |-| // ending_part: |--| |--| |--| |-| // final_part: || - // let beginning_part_width = since % biguint_chip.limb_bits(); let ending_part_base = ctx.load_constant(Fr::from(2).pow_vartime([beginning_part_width as u64])); @@ -68,27 +67,26 @@ fn slice_biguint( let mut parts: Vec> = Vec::new(); // assign witnesses - for (i, src_limb) in src.value().iter_u64_digits().enumerate() { - let do_src_and_dest_overlap = - since < (i + 1) * biguint_chip.limb_bits() && until > i * biguint_chip.limb_bits(); - if !do_src_and_dest_overlap { - continue; - } + let mut read_bits = since / biguint_chip.limb_bits() * biguint_chip.limb_bits(); + while read_bits < until { + let src_limb = (src.value() >> read_bits) % (BigUint::one() << biguint_chip.limb_bits()); - let beginning_part_max_width = until - i * biguint_chip.limb_bits(); + let beginning_part_max_width = until - read_bits; let beginning_part_width = beginning_part_width.min(beginning_part_max_width); - let beginning_part = BigUint::from(src_limb) % (BigUint::one() << beginning_part_width); + let beginning_part = src_limb.clone() % (BigUint::one() << beginning_part_width); parts.push(ctx.load_witness(Fr::from(beginning_part.to_u64().unwrap()))); - let ending_part_max_width = until - i * biguint_chip.limb_bits() - beginning_part_width; + let ending_part_max_width = until - read_bits - beginning_part_width; let ending_part_width = ending_part_width.min(ending_part_max_width); - let ending_part = (BigUint::from(src_limb) >> beginning_part_width) % (BigUint::one() << ending_part_width); + let ending_part = (src_limb.clone() >> beginning_part_width) % (BigUint::one() << ending_part_width); parts.push(ctx.load_witness(Fr::from(ending_part.to_u64().unwrap()))); - if until < (i + 1) * biguint_chip.limb_bits() { - let final_part = src_limb >> final_part_offset; - parts.push(ctx.load_witness(Fr::from(final_part))); + if until < read_bits + biguint_chip.limb_bits() { + let final_part = src_limb.clone() >> final_part_offset; + parts.push(ctx.load_witness(Fr::from(final_part.to_u64().unwrap()))); } + + read_bits += biguint_chip.limb_bits(); } // range check the first beginning part From b97e074a1d4f0c832052eba170303fa341123fa4 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Tue, 7 Nov 2023 19:50:35 +0900 Subject: [PATCH 05/28] aaaa --- Cargo.lock | 125 ++------------- packages/halo2-circuits/Cargo.toml | 6 +- packages/halo2-circuits/src/bin/cli.rs | 3 +- packages/halo2-circuits/src/circuit.rs | 214 ++++++++++--------------- 4 files changed, 95 insertions(+), 253 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8944103..4a47a07 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -197,12 +197,6 @@ dependencies = [ "rand", ] -[[package]] -name = "array-init" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc" - [[package]] name = "arrayref" version = "0.3.7" @@ -2101,48 +2095,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "halo2-base" -version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop#ff0cadf7b38d2fd5e9a57781641789ac71516227" -dependencies = [ - "getset", - "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", - "itertools 0.11.0", - "log", - "num-bigint", - "num-integer", - "num-traits", - "poseidon-rs", - "rand_chacha", - "rayon", - "rustc-hash", - "serde", - "serde_json", -] - -[[package]] -name = "halo2-base" -version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=feat/zkevm-sha256#fd90273b5f948bc9e1d5ea7ff08a49126221041e" -dependencies = [ - "ark-std", - "getset", - "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", - "itertools 0.11.0", - "log", - "num-bigint", - "num-integer", - "num-traits", - "poseidon-rs", - "rand", - "rand_chacha", - "rayon", - "rustc-hash", - "serde", - "serde_json", -] - [[package]] name = "halo2-circuits" version = "0.1.0" @@ -2153,8 +2105,8 @@ dependencies = [ "env_logger", "getrandom", "getset", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-base", + "halo2-ecc", "halo2-rsa", "halo2-sha256-unoptimized", "itertools 0.11.0", @@ -2170,7 +2122,6 @@ dependencies = [ "snark-verifier-sdk", "tokio", "x509-parser", - "zkevm-hashes", ] [[package]] @@ -2178,26 +2129,7 @@ name = "halo2-ecc" version = "0.4.0" source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition#980b39bcca5b3327aaef6c8d73577d9381bfa899" dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", - "itertools 0.10.5", - "num-bigint", - "num-integer", - "num-traits", - "rand", - "rand_chacha", - "rand_core", - "rayon", - "serde", - "serde_json", - "test-case", -] - -[[package]] -name = "halo2-ecc" -version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop#ff0cadf7b38d2fd5e9a57781641789ac71516227" -dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", + "halo2-base", "itertools 0.10.5", "num-bigint", "num-integer", @@ -2217,8 +2149,8 @@ version = "0.1.0" source = "git+https://github.com/MynaWallet/halo2-rsa.git?branch=main#231d5421011276dfb7d6a6f84144a2dea9c9e3fe" dependencies = [ "env_logger", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-base", + "halo2-ecc", "num-bigint", "num-traits", "rand", @@ -2235,7 +2167,7 @@ dependencies = [ "env_logger", "generic-array", "getrandom", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-base", "hex", "itertools 0.10.5", "num-bigint", @@ -4442,8 +4374,8 @@ name = "snark-verifier" version = "0.1.6" source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=community-edition#7011e8ce0c2f7e79ab9629aa528cfb6837cdeafe" dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-base", + "halo2-ecc", "hex", "itertools 0.11.0", "lazy_static", @@ -4457,24 +4389,6 @@ dependencies = [ "sha3 0.10.8", ] -[[package]] -name = "snark-verifier" -version = "0.1.7" -source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=develop#624b003c656e44b14202d4b8a16a2f7bc4e71eeb" -dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", - "hex", - "itertools 0.11.0", - "lazy_static", - "num-bigint", - "num-integer", - "num-traits", - "pairing", - "rand", - "serde", -] - [[package]] name = "snark-verifier-sdk" version = "0.1.6" @@ -4484,7 +4398,7 @@ dependencies = [ "bincode", "ethereum-types", "getset", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-base", "hex", "itertools 0.10.5", "lazy_static", @@ -4495,7 +4409,7 @@ dependencies = [ "rand_chacha", "serde", "serde_json", - "snark-verifier 0.1.6", + "snark-verifier", ] [[package]] @@ -5762,25 +5676,6 @@ dependencies = [ "zstd 0.11.2+zstd.1.5.2", ] -[[package]] -name = "zkevm-hashes" -version = "0.2.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=feat/zkevm-sha256#fd90273b5f948bc9e1d5ea7ff08a49126221041e" -dependencies = [ - "array-init", - "ethers-core", - "getset", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=feat/zkevm-sha256)", - "itertools 0.11.0", - "lazy_static", - "log", - "num-bigint", - "rand", - "rayon", - "sha3 0.10.8", - "snark-verifier 0.1.7", -] - [[package]] name = "zstd" version = "0.11.2+zstd.1.5.2" diff --git a/packages/halo2-circuits/Cargo.toml b/packages/halo2-circuits/Cargo.toml index 84ba7d0..e26dbc1 100644 --- a/packages/halo2-circuits/Cargo.toml +++ b/packages/halo2-circuits/Cargo.toml @@ -2,7 +2,7 @@ name = "halo2-circuits" version = "0.1.0" edition = "2021" -authors = ["hiroism007"] +authors = ["hiroism007", "chokermaxx"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -24,10 +24,6 @@ halo2-ecc = { branch = "community-edition", default-features = false, features = "halo2-axiom", "display", ], git = "https://github.com/axiom-crypto/halo2-lib.git" } -zkevm-hashes = { branch = "feat/zkevm-sha256", default-features = false, features = [ - "halo2-axiom", - "display", -], git = "https://github.com/axiom-crypto/halo2-lib.git" } halo2-sha256-unoptimized = { branch = "main", default-features = false, features = [ "halo2-axiom", "display", diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 41bfa06..0ed48f2 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -66,7 +66,8 @@ fn main() { let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); let public = circuit::PublicInput { nation_pubkey }; - let private = circuit::PrivateInput { tbs_cert, nation_sig, password: Fr::from(password) }; + let private = + circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; let builder = circuit::proof_of_japanese_residence(public, private); if Path::new(&pk_path).exists() { diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index fcfad49..4f70def 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -1,16 +1,16 @@ use halo2_base::{ - gates::{circuit::builder::BaseCircuitBuilder, GateInstructions, RangeInstructions}, + gates::{circuit::builder::BaseCircuitBuilder, GateInstructions, RangeChip, RangeInstructions}, halo2_proofs::{arithmetic::Field, halo2curves::bn256::Fr}, poseidon::hasher::{spec::OptimizedPoseidonSpec, PoseidonHasher}, - AssignedValue, Context, + AssignedValue, Context, QuantumCell, }; use halo2_ecc::bigint::OverflowInteger; use halo2_rsa::{ - AssignedBigUint, AssignedRSAPubE, AssignedRSAPublicKey, BigUintConfig, BigUintInstructions, Fresh, RSAConfig, - RSAInstructions, RSAPubE, RSAPublicKey, RSASignature, + AssignedBigUint, BigUintConfig, BigUintInstructions, Fresh, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, + RSASignature, }; +use halo2_sha256_unoptimized::Sha256Chip; use num_bigint::BigUint; -use num_traits::{identities::One, ToPrimitive}; #[derive(Debug, Clone)] pub struct PublicInput { @@ -20,117 +20,51 @@ pub struct PublicInput { #[derive(Debug, Clone)] pub struct PrivateInput { - pub tbs_cert: BigUint, + pub tbs_cert: Vec, // 2048 bits pub nation_sig: BigUint, pub password: Fr, } -// LOOKUP_BITS must be divisible by 64. because halo2-rsa uses limbs that are 64 bits wide each. -const LOOKUP_BITS: usize = 16; +// halo2-sha256-unoptimized takes inputs byte by byte so I guess 8 is optimimal +const LOOKUP_BITS: usize = 8; const RSA_KEY_SIZE: usize = 2048; const PUBKEY_BEGINS: usize = 2216; const E: usize = 65537; -// The reason we chose 64 here is because -// a) 2048, the width of RSA keys, must be able to divide limb_bits https://github.com/zkemail/halo2-rsa/blob/main/src/big_uint/chip.rs#L49C49-L49C49 -// b) limb_bits * 2 must be smaller than 253 the order of the field https://github.com/axiom-crypto/halo2-lib/blob/dd21d6c2ddb1c6cb5ef78f20d68a6c9682353698/halo2-ecc/src/bigint/mul_no_carry.rs#L8 -// the maximum value that satisfies the both is 64 -const LIMB_BITS: usize = 32; - -// halo2_rsa's mul_mod constraints are too heavy for just taking a bit slice. -// here I write optimized constraints that constraints the same thing. -fn slice_biguint( +const LIMB_BITS: usize = 64; +const SHA256_BLOCK_BITS: usize = 512; +const MAX_TBS_CERT_BITS: usize = 1 << 15; +const SHA256_INPUT_BLOCKS: usize = MAX_TBS_CERT_BITS / SHA256_BLOCK_BITS; // the remainder must be 0 + +pub fn bytes_to_biguint( ctx: &mut Context, - biguint_chip: &BigUintConfig, - src: AssignedBigUint, - since: usize, - until: usize, + biguint_chip: BigUintConfig, + src: &[AssignedValue], ) -> AssignedBigUint { - assert!(0 < src.num_limbs()); - assert!(since < until); - - // I want an auditor to look at this function carefully - // since: | - // until: | - // src: |----|----|----|----|----|----| - // dest: |----|----|----|-| - // beginning_part: |-| |-| |-| |-| - // ending_part: |--| |--| |--| |-| - // final_part: || - - let beginning_part_width = since % biguint_chip.limb_bits(); - let ending_part_base = ctx.load_constant(Fr::from(2).pow_vartime([beginning_part_width as u64])); - let ending_part_width = biguint_chip.limb_bits() - beginning_part_width; - let beginning_part_base = ctx.load_constant(Fr::from(2).pow_vartime([ending_part_width as u64])); - let final_part_offset = until % biguint_chip.limb_bits(); - let final_part_base = ctx.load_constant(Fr::from(2).pow_vartime([final_part_offset as u64])); - let mut parts: Vec> = Vec::new(); - - // assign witnesses - let mut read_bits = since / biguint_chip.limb_bits() * biguint_chip.limb_bits(); - while read_bits < until { - let src_limb = (src.value() >> read_bits) % (BigUint::one() << biguint_chip.limb_bits()); - - let beginning_part_max_width = until - read_bits; - let beginning_part_width = beginning_part_width.min(beginning_part_max_width); - let beginning_part = src_limb.clone() % (BigUint::one() << beginning_part_width); - parts.push(ctx.load_witness(Fr::from(beginning_part.to_u64().unwrap()))); - - let ending_part_max_width = until - read_bits - beginning_part_width; - let ending_part_width = ending_part_width.min(ending_part_max_width); - let ending_part = (src_limb.clone() >> beginning_part_width) % (BigUint::one() << ending_part_width); - parts.push(ctx.load_witness(Fr::from(ending_part.to_u64().unwrap()))); - - if until < read_bits + biguint_chip.limb_bits() { - let final_part = src_limb.clone() >> final_part_offset; - parts.push(ctx.load_witness(Fr::from(final_part.to_u64().unwrap()))); - } - - read_bits += biguint_chip.limb_bits(); - } - - // range check the first beginning part - // it does not overlap with dest - // thus the range check for dest does not imply a range check for the first beginning part - let width: usize = (until - since) as usize; - biguint_chip.range().range_check(ctx, parts[0], beginning_part_width.min(width)); - - let chunks = parts.chunks_exact(2); - let final_part = if let &[final_part] = chunks.remainder() { final_part } else { ctx.load_zero() }; - - // constrain against src - for (i, pair) in chunks.enumerate() { - let is_last = i + 1 == parts.len() / 2; - let final_part = if is_last { final_part } else { ctx.load_zero() }; - - if let &[beginning_part, ending_part] = pair { - let src_limb = biguint_chip.gate().mul_add(ctx, ending_part_base, ending_part, beginning_part); - let src_limb = biguint_chip.gate().mul_add(ctx, final_part_base, final_part, src_limb); - - ctx.constrain_equal(&src.limbs()[since / biguint_chip.limb_bits() + i], &src_limb); - } else { - unreachable!(); - } - } - - // constrain against dest - let dest_limbs: Vec> = parts[1..parts.len() - 1] - .chunks_exact(2) - .map(|pair| { - if let &[ending_part, beginning_part] = pair { - let dest_limb = biguint_chip.gate().mul_add(ctx, beginning_part_base, beginning_part, ending_part); - biguint_chip.range().range_check(ctx, dest_limb, biguint_chip.limb_bits()); - dest_limb - } else { - unreachable!(); - } + let num_bases = (biguint_chip.limb_bits() / 8) as u64; + let bases: Vec> = + (0..num_bases).map(|i| QuantumCell::Constant(Fr::from(2).pow_vartime([i * 8]))).collect(); + let dest_limbs = src + .chunks(biguint_chip.limb_bits() / 8) + .map(|bytes_in_limb| { + let dest_limb = biguint_chip.gate().inner_product(ctx, bytes_in_limb.to_vec(), bases.clone()); + biguint_chip.range().range_check(ctx, dest_limb, biguint_chip.limb_bits()); + dest_limb }) .collect(); - let dest_in_rust = (src.value() >> since) % (BigUint::one() << width); - let dest_in_circuit = - AssignedBigUint::new(OverflowInteger::new(dest_limbs, biguint_chip.limb_bits()), dest_in_rust); - dest_in_circuit + let bytes_in_rust: Vec = src.iter().map(|byte| byte.value().to_bytes()[0].clone()).collect(); + let dest_in_rust = BigUint::from_bytes_le(&bytes_in_rust); + AssignedBigUint::new(OverflowInteger::new(dest_limbs, biguint_chip.limb_bits()), dest_in_rust) +} + +pub fn bytes_to_64s( + ctx: &mut Context, + range_chip: RangeChip, + src: &[AssignedValue], +) -> Vec> { + let biguint_chip = BigUintConfig::construct(range_chip, 64); + bytes_to_biguint(ctx, biguint_chip, src).limbs().to_vec() } pub fn proof_of_japanese_residence(public: PublicInput, private: PrivateInput) -> BaseCircuitBuilder { @@ -145,7 +79,9 @@ pub fn proof_of_japanese_residence(public: PublicInput, private: PrivateInput) - let range_chip = builder.range_chip(); let ctx = builder.main(0); - let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip, LIMB_BITS); + let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); + let mut sha256_chip = + Sha256Chip::construct(vec![SHA256_INPUT_BLOCKS * SHA256_BLOCK_BITS / 8], range_chip.clone(), true); let rsa_chip = RSAConfig::construct(biguint_chip, RSA_KEY_SIZE, exp_bits); let mut poseidon = PoseidonHasher::new(OptimizedPoseidonSpec::::new::<8, 57, 0>()); poseidon.initialize_consts(ctx, rsa_chip.gate()); @@ -155,42 +91,56 @@ pub fn proof_of_japanese_residence(public: PublicInput, private: PrivateInput) - rsa_chip.assign_public_key(ctx, RSAPublicKey::new(public.nation_pubkey, RSAPubE::Fix(E.into()))).unwrap(); // load private inputs - let tbs_cert = rsa_chip.biguint_config().assign_integer(ctx, &private.tbs_cert, 1 << 15).unwrap(); let nation_sig = rsa_chip.assign_signature(ctx, RSASignature::new(private.nation_sig)).unwrap(); let password = ctx.load_witness(private.password); // extract citizen's public key from the tbs certificate - let n = slice_biguint(ctx, &rsa_chip.biguint_config(), tbs_cert, PUBKEY_BEGINS, PUBKEY_BEGINS + RSA_KEY_SIZE); - let citizen_pubkey = AssignedRSAPublicKey::new(n.clone(), AssignedRSAPubE::Fix(E.into())); - - let identity_commitment_preimage: Vec> = - n.limbs().into_iter().copied().chain(std::iter::once(password)).collect(); + let sha256ed = sha256_chip.digest(ctx, &private.tbs_cert, None).unwrap(); + // let n = bytes_to_biguint( + // ctx, + // rsa_chip.biguint_config().clone(), + // &sha256ed.input_bytes[PUBKEY_BEGINS / 8..PUBKEY_BEGINS / 8 + RSA_KEY_SIZE / 8], + // ); + // let citizen_pubkey = AssignedRSAPublicKey::new(n.clone(), AssignedRSAPubE::Fix(E.into())); + + let identity_commitment_preimage: Vec> = sha256ed.input_bytes + [PUBKEY_BEGINS / 8..PUBKEY_BEGINS / 8 + RSA_KEY_SIZE / 8] + .iter() + .copied() + .chain(std::iter::once(password)) + .collect(); let identity_commitment = poseidon.hash_fix_len_array(ctx, rsa_chip.gate(), &identity_commitment_preimage); + let sha256ed_64s = bytes_to_64s(ctx, range_chip.clone(), &sha256ed.output_bytes); + let is_nation_sig_valid = + rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); + rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); + builder.assigned_instances[0].push(identity_commitment); + builder.assigned_instances[0].extend(nation_pubkey.n.limbs()); let circuit_params = builder.calculate_params(None); builder.use_params(circuit_params) } -#[cfg(test)] -mod tests { - use super::*; - use crate::helpers::read_citizen_cert; - use halo2_base::utils::testing::base_test; - - // TODO: Write tests for failure cases - #[test] - fn extract_citizen_pubkey() { - let (_, tbs_cert, expected_citizen_pubkey) = read_citizen_cert("certs/myna_cert.pem"); - base_test().k(LOOKUP_BITS as u32).bench_builder((), (), |pool, range_chip, _| { - let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); - let tbs_cert = biguint_chip.assign_integer(pool.main(), &tbs_cert, 1 << 15).unwrap(); - let expected = biguint_chip.assign_constant(pool.main(), expected_citizen_pubkey.clone()).unwrap(); - let result = - slice_biguint(pool.main(), &biguint_chip, tbs_cert, PUBKEY_BEGINS, PUBKEY_BEGINS + RSA_KEY_SIZE); - let is_ok = biguint_chip.is_equal_fresh(pool.main(), &result, &expected).unwrap(); - let one = pool.main().load_constant(Fr::one()); - pool.main().constrain_equal(&is_ok, &one); - }); - } -} +// #[cfg(test)] +// mod tests { +// use super::*; +// use crate::helpers::read_citizen_cert; +// use halo2_base::utils::testing::base_test; + +// // TODO: Write tests for failure cases +// #[test] +// fn extract_citizen_pubkey() { +// let (_, tbs_cert, expected_citizen_pubkey) = read_citizen_cert("certs/myna_cert.pem"); +// base_test().k(LOOKUP_BITS as u32).bench_builder((), (), |pool, range_chip, _| { +// let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); +// let tbs_cert = biguint_chip.assign_integer(pool.main(), &tbs_cert, 1 << 15).unwrap(); +// let expected = biguint_chip.assign_constant(pool.main(), expected_citizen_pubkey.clone()).unwrap(); +// let result = +// slice_biguint(pool.main(), &biguint_chip, tbs_cert, PUBKEY_BEGINS, PUBKEY_BEGINS + RSA_KEY_SIZE); +// let is_ok = biguint_chip.is_equal_fresh(pool.main(), &result, &expected).unwrap(); +// let one = pool.main().load_constant(Fr::one()); +// pool.main().constrain_equal(&is_ok, &one); +// }); +// } +// } From f723877588ac71681779d826b1cbdd9419353ad9 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Tue, 7 Nov 2023 21:58:14 +0900 Subject: [PATCH 06/28] Split the commands --- packages/halo2-circuits/src/bin/cli.rs | 47 ++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 0ed48f2..12dd840 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -31,6 +31,28 @@ enum Commands { params_path: String, }, /// Generate the proving key and the verification key for RSA circuit + GenerateKeys { + /// k parameter for circuit. + #[arg(long, default_value = "17")] + k: u32, + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./params")] + params_path: String, + /// proving key path. output + #[arg(long, default_value = "./build/rsa.pk")] + pk_path: String, + /// proof path. output + #[arg(long, default_value = "./build/myna_verify_rsa.proof")] + proof_path: String, + // citizen's certificate + #[arg(long, default_value = "./certs/myna_cert.pem")] + verify_cert_path: String, + // nation's certificate + #[arg(long, default_value = "./certs/ca_cert.pem")] + issuer_cert_path: String, + password: u64, + }, + /// Generate the proving key and the verification key for RSA circuit Prove { /// k parameter for circuit. #[arg(long, default_value = "17")] @@ -61,7 +83,15 @@ fn main() { env::set_var("PARAMS_DIR", params_path); gen_srs(k); } - Commands::Prove { k, params_path, pk_path, proof_path, verify_cert_path, issuer_cert_path, password } => { + Commands::GenerateKeys { + k, + params_path, + pk_path, + proof_path, + verify_cert_path, + issuer_cert_path, + password, + } => { let nation_pubkey = read_nation_cert(&issuer_cert_path); let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); @@ -77,6 +107,19 @@ fn main() { } } + env::set_var("PARAMS_DIR", params_path); + let trusted_setup = gen_srs(k); + gen_pk(&trusted_setup, &builder, Some(Path::new(&pk_path))); + } + Commands::Prove { k, params_path, pk_path, proof_path, verify_cert_path, issuer_cert_path, password } => { + let nation_pubkey = read_nation_cert(&issuer_cert_path); + let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); + + let public = circuit::PublicInput { nation_pubkey }; + let private = + circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; + let builder = circuit::proof_of_japanese_residence(public, private); + if Path::new(&proof_path).exists() { match remove_file(&proof_path) { Ok(_) => println!("File found, overwriting..."), @@ -86,7 +129,7 @@ fn main() { env::set_var("PARAMS_DIR", params_path); let trusted_setup = gen_srs(k); - let pk = gen_pk(&trusted_setup, &builder, Some(Path::new(&pk_path))); + let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); gen_snark_shplonk(&trusted_setup, &pk, builder, Some(Path::new(&proof_path))); } /* Commands::GenRsaVerifyEVMProof { * k, From a381d797b5f4caec6ed9282dfe60c1b7a5df7bc9 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Tue, 7 Nov 2023 21:58:18 +0900 Subject: [PATCH 07/28] ahahaha --- packages/halo2-circuits/src/circuit.rs | 108 ++++++++++++++----------- 1 file changed, 63 insertions(+), 45 deletions(-) diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index 4f70def..5f8b43f 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -80,22 +80,21 @@ pub fn proof_of_japanese_residence(public: PublicInput, private: PrivateInput) - let range_chip = builder.range_chip(); let ctx = builder.main(0); let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); + let rsa_chip = RSAConfig::construct(biguint_chip, RSA_KEY_SIZE, exp_bits); let mut sha256_chip = Sha256Chip::construct(vec![SHA256_INPUT_BLOCKS * SHA256_BLOCK_BITS / 8], range_chip.clone(), true); - let rsa_chip = RSAConfig::construct(biguint_chip, RSA_KEY_SIZE, exp_bits); - let mut poseidon = PoseidonHasher::new(OptimizedPoseidonSpec::::new::<8, 57, 0>()); - poseidon.initialize_consts(ctx, rsa_chip.gate()); + // let mut poseidon = PoseidonHasher::new(OptimizedPoseidonSpec::::new::<8, 57, 0>()); + // poseidon.initialize_consts(ctx, rsa_chip.gate()); // load public inputs - let nation_pubkey = - rsa_chip.assign_public_key(ctx, RSAPublicKey::new(public.nation_pubkey, RSAPubE::Fix(E.into()))).unwrap(); + // let nation_pubkey = + // rsa_chip.assign_public_key(ctx, RSAPublicKey::new(public.nation_pubkey, RSAPubE::Fix(E.into()))).unwrap(); // load private inputs - let nation_sig = rsa_chip.assign_signature(ctx, RSASignature::new(private.nation_sig)).unwrap(); - let password = ctx.load_witness(private.password); + // let nation_sig = rsa_chip.assign_signature(ctx, RSASignature::new(private.nation_sig)).unwrap(); + // let password = ctx.load_witness(private.password); // extract citizen's public key from the tbs certificate - let sha256ed = sha256_chip.digest(ctx, &private.tbs_cert, None).unwrap(); // let n = bytes_to_biguint( // ctx, // rsa_chip.biguint_config().clone(), @@ -103,44 +102,63 @@ pub fn proof_of_japanese_residence(public: PublicInput, private: PrivateInput) - // ); // let citizen_pubkey = AssignedRSAPublicKey::new(n.clone(), AssignedRSAPubE::Fix(E.into())); - let identity_commitment_preimage: Vec> = sha256ed.input_bytes - [PUBKEY_BEGINS / 8..PUBKEY_BEGINS / 8 + RSA_KEY_SIZE / 8] - .iter() - .copied() - .chain(std::iter::once(password)) - .collect(); - let identity_commitment = poseidon.hash_fix_len_array(ctx, rsa_chip.gate(), &identity_commitment_preimage); - - let sha256ed_64s = bytes_to_64s(ctx, range_chip.clone(), &sha256ed.output_bytes); - let is_nation_sig_valid = - rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); - rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); - - builder.assigned_instances[0].push(identity_commitment); - builder.assigned_instances[0].extend(nation_pubkey.n.limbs()); + let sha256ed = sha256_chip.digest(ctx, &private.tbs_cert, None).unwrap(); + // let identity_commitment_preimage: Vec> = sha256ed.input_bytes + // [PUBKEY_BEGINS / 8..(PUBKEY_BEGINS + RSA_KEY_SIZE) / 8] + // .iter() + // .copied() + // .chain(std::iter::once(password)) + // .collect(); + // let identity_commitment = poseidon.hash_fix_len_array(ctx, rsa_chip.gate(), &identity_commitment_preimage); + + // let sha256ed_64s = bytes_to_64s(ctx, range_chip.clone(), &sha256ed.output_bytes); + // let is_nation_sig_valid = + // rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); + // rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); + + // builder.assigned_instances[0].push(identity_commitment); + // builder.assigned_instances[0].extend(nation_pubkey.n.limbs()); + builder.assigned_instances[0].extend(sha256ed.output_bytes); let circuit_params = builder.calculate_params(None); builder.use_params(circuit_params) } -// #[cfg(test)] -// mod tests { -// use super::*; -// use crate::helpers::read_citizen_cert; -// use halo2_base::utils::testing::base_test; - -// // TODO: Write tests for failure cases -// #[test] -// fn extract_citizen_pubkey() { -// let (_, tbs_cert, expected_citizen_pubkey) = read_citizen_cert("certs/myna_cert.pem"); -// base_test().k(LOOKUP_BITS as u32).bench_builder((), (), |pool, range_chip, _| { -// let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); -// let tbs_cert = biguint_chip.assign_integer(pool.main(), &tbs_cert, 1 << 15).unwrap(); -// let expected = biguint_chip.assign_constant(pool.main(), expected_citizen_pubkey.clone()).unwrap(); -// let result = -// slice_biguint(pool.main(), &biguint_chip, tbs_cert, PUBKEY_BEGINS, PUBKEY_BEGINS + RSA_KEY_SIZE); -// let is_ok = biguint_chip.is_equal_fresh(pool.main(), &result, &expected).unwrap(); -// let one = pool.main().load_constant(Fr::one()); -// pool.main().constrain_equal(&is_ok, &one); -// }); -// } -// } +#[cfg(test)] +mod tests { + use super::*; + use crate::helpers::read_citizen_cert; + use halo2_base::{halo2_proofs::halo2curves::ff::PrimeField, utils::testing::base_test}; + use num_traits::cast::ToPrimitive; + + // TODO: Write tests for failure cases + // #[test] + // fn extract_citizen_pubkey() { + // let (_, tbs_cert, expected_citizen_pubkey) = read_citizen_cert("certs/myna_cert.pem"); + // base_test().k(LOOKUP_BITS as u32).bench_builder((), (), |pool, range_chip, _| { + // let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); + // let tbs_cert = biguint_chip.assign_integer(pool.main(), &tbs_cert, 1 << 15).unwrap(); + // let expected = biguint_chip.assign_constant(pool.main(), expected_citizen_pubkey.clone()).unwrap(); + // let result = + // slice_biguint(pool.main(), &biguint_chip, tbs_cert, PUBKEY_BEGINS, PUBKEY_BEGINS + RSA_KEY_SIZE); + // let is_ok = biguint_chip.is_equal_fresh(pool.main(), &result, &expected).unwrap(); + // let one = pool.main().load_constant(Fr::one()); + // pool.main().constrain_equal(&is_ok, &one); + // }); + // } + + #[test] + fn aaa() { + let two_pow_16 = Fr::from_raw([1 << 16, 0, 0, 0]); + let mut test_subject = Fr::from_raw([0, 0, 0, 1 << 46]); + while test_subject != Fr::zero() { + for j in 1..16 { + let k = test_subject * Fr::from_raw([1 << j, 0, 0, 0]); + if two_pow_16 >= k { + unreachable!("i:{:?},j:{:?},k:{:?}", test_subject.to_repr(), j, k.to_repr()); + } + } + + test_subject += Fr::one(); + } + } +} From c1472f9d516bc3d33795db607be6819ab4d28336 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Wed, 8 Nov 2023 20:28:25 +0900 Subject: [PATCH 08/28] WIP: 20231108 --- Cargo.lock | 29 +- packages/halo2-circuits/Cargo.lock | 357 +------------------------ packages/halo2-circuits/Cargo.toml | 3 + packages/halo2-circuits/src/bin/cli.rs | 27 +- packages/halo2-circuits/src/circuit.rs | 176 ++++++++---- packages/halo2-circuits/src/helpers.rs | 3 +- 6 files changed, 184 insertions(+), 411 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4a47a07..e5611f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -40,13 +40,14 @@ dependencies = [ [[package]] name = "ahash" -version = "0.8.3" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" +checksum = "91429305e9f0a25f6205c5b8e0d2db09e0708a7a6df0f42212bb56c32c8ac97a" dependencies = [ "cfg-if", "once_cell", "version_check", + "zerocopy", ] [[package]] @@ -2075,7 +2076,7 @@ checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" [[package]] name = "halo2-base" version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition#980b39bcca5b3327aaef6c8d73577d9381bfa899" +source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition#262f5c5e074fbbb88c9decf5516568c12413ab94" dependencies = [ "ark-std", "getset", @@ -2127,7 +2128,7 @@ dependencies = [ [[package]] name = "halo2-ecc" version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition#980b39bcca5b3327aaef6c8d73577d9381bfa899" +source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition#262f5c5e074fbbb88c9decf5516568c12413ab94" dependencies = [ "halo2-base", "itertools 0.10.5", @@ -5636,6 +5637,26 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" +[[package]] +name = "zerocopy" +version = "0.7.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cd369a67c0edfef15010f980c3cbe45d7f651deac2cd67ce097cd801de16557" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2f140bda219a26ccc0cdb03dba58af72590c53b22642577d88a927bc5c87d6b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.38", +] + [[package]] name = "zeroize" version = "1.6.0" diff --git a/packages/halo2-circuits/Cargo.lock b/packages/halo2-circuits/Cargo.lock index edb6a88..a55e8e2 100644 --- a/packages/halo2-circuits/Cargo.lock +++ b/packages/halo2-circuits/Cargo.lock @@ -140,12 +140,6 @@ dependencies = [ "rand", ] -[[package]] -name = "array-init" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc" - [[package]] name = "arrayref" version = "0.3.7" @@ -380,9 +374,6 @@ name = "bytes" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" -dependencies = [ - "serde", -] [[package]] name = "c-kzg" @@ -429,15 +420,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" -[[package]] -name = "chrono" -version = "0.4.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" -dependencies = [ - "num-traits", -] - [[package]] name = "ciborium" version = "0.2.1" @@ -944,23 +926,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "ethabi" -version = "18.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7413c5f74cc903ea37386a8965a936cbeb334bd270862fdece542c1b2dcbc898" -dependencies = [ - "ethereum-types", - "hex", - "once_cell", - "regex", - "serde", - "serde_json", - "sha3 0.10.8", - "thiserror", - "uint", -] - [[package]] name = "ethbloom" version = "0.13.0" @@ -969,10 +934,6 @@ checksum = "c22d4b5885b6aa2fe5e8b9329fb8d232bf739e434e6b87347c63bdd00c120f60" dependencies = [ "crunchy", "fixed-hash", - "impl-codec", - "impl-rlp", - "impl-serde", - "scale-info", "tiny-keccak", ] @@ -984,47 +945,10 @@ checksum = "02d215cbf040552efcbe99a38372fe80ab9d00268e20012b79fcd0f073edd8ee" dependencies = [ "ethbloom", "fixed-hash", - "impl-codec", - "impl-rlp", - "impl-serde", "primitive-types", - "scale-info", "uint", ] -[[package]] -name = "ethers-core" -version = "2.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0a17f0708692024db9956b31d7a20163607d2745953f5ae8125ab368ba280ad" -dependencies = [ - "arrayvec", - "bytes", - "chrono", - "const-hex", - "elliptic-curve", - "ethabi", - "generic-array", - "k256", - "num_enum", - "open-fastrlp", - "rand", - "rlp", - "serde", - "serde_json", - "strum", - "tempfile", - "thiserror", - "tiny-keccak", - "unicode-xid", -] - -[[package]] -name = "fastrand" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" - [[package]] name = "ff" version = "0.13.0" @@ -1157,48 +1081,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "halo2-base" -version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop#bf71f0e30ff1da8b9ef67dfbb0824e298a89d5a9" -dependencies = [ - "getset", - "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", - "itertools 0.11.0", - "log", - "num-bigint", - "num-integer", - "num-traits", - "poseidon-rs", - "rand_chacha", - "rayon", - "rustc-hash", - "serde", - "serde_json", -] - -[[package]] -name = "halo2-base" -version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=feat/zkevm-sha256#adf331ecdd8ae492bced80d3157ae9c3b66fde04" -dependencies = [ - "ark-std", - "getset", - "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", - "itertools 0.11.0", - "log", - "num-bigint", - "num-integer", - "num-traits", - "poseidon-rs", - "rand", - "rand_chacha", - "rayon", - "rustc-hash", - "serde", - "serde_json", -] - [[package]] name = "halo2-circuits" version = "0.1.0" @@ -1209,7 +1091,8 @@ dependencies = [ "env_logger", "getrandom", "getset", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-base", + "halo2-ecc", "halo2-rsa", "halo2-sha256-unoptimized", "itertools 0.11.0", @@ -1225,7 +1108,6 @@ dependencies = [ "snark-verifier-sdk", "tokio", "x509-parser", - "zkevm-hashes", ] [[package]] @@ -1233,26 +1115,7 @@ name = "halo2-ecc" version = "0.4.0" source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition#980b39bcca5b3327aaef6c8d73577d9381bfa899" dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", - "itertools 0.10.5", - "num-bigint", - "num-integer", - "num-traits", - "rand", - "rand_chacha", - "rand_core", - "rayon", - "serde", - "serde_json", - "test-case", -] - -[[package]] -name = "halo2-ecc" -version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop#bf71f0e30ff1da8b9ef67dfbb0824e298a89d5a9" -dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", + "halo2-base", "itertools 0.10.5", "num-bigint", "num-integer", @@ -1272,8 +1135,8 @@ version = "0.1.0" source = "git+https://github.com/MynaWallet/halo2-rsa.git?branch=main#231d5421011276dfb7d6a6f84144a2dea9c9e3fe" dependencies = [ "env_logger", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-base", + "halo2-ecc", "num-bigint", "num-traits", "rand", @@ -1290,7 +1153,7 @@ dependencies = [ "env_logger", "generic-array", "getrandom", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-base", "hex", "itertools 0.10.5", "num-bigint", @@ -1466,24 +1329,6 @@ dependencies = [ "parity-scale-codec", ] -[[package]] -name = "impl-rlp" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28220f89297a075ddc7245cd538076ee98b01f2a9c23a53a4f1105d5a322808" -dependencies = [ - "rlp", -] - -[[package]] -name = "impl-serde" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc88fc67028ae3db0c853baa36269d398d5f45b6982f95549ff5def78c935cd" -dependencies = [ - "serde", -] - [[package]] name = "impl-trait-for-tuples" version = "0.2.2" @@ -1797,27 +1642,6 @@ dependencies = [ "libc", ] -[[package]] -name = "num_enum" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70bf6736f74634d299d00086f02986875b3c2d924781a6a2cb6c201e73da0ceb" -dependencies = [ - "num_enum_derive", -] - -[[package]] -name = "num_enum_derive" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56ea360eafe1022f7cc56cd7b869ed57330fb2453d0c7831d99b74c65d2f5597" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 2.0.33", -] - [[package]] name = "object" version = "0.32.1" @@ -1854,31 +1678,6 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" -[[package]] -name = "open-fastrlp" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "786393f80485445794f6043fd3138854dd109cc6c4bd1a6383db304c9ce9b9ce" -dependencies = [ - "arrayvec", - "auto_impl", - "bytes", - "ethereum-types", - "open-fastrlp-derive", -] - -[[package]] -name = "open-fastrlp-derive" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "003b2be5c6c53c1cfeb0a238b8a1c3915cd410feb684457a36c10038f764bb1c" -dependencies = [ - "bytes", - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "openssl" version = "0.10.57" @@ -2110,9 +1909,6 @@ checksum = "0b34d9fd68ae0b74a41b21c03c2f62847aa0ffea044eee893b4c140b37e244e2" dependencies = [ "fixed-hash", "impl-codec", - "impl-rlp", - "impl-serde", - "scale-info", "uint", ] @@ -2249,15 +2045,6 @@ dependencies = [ "num_cpus", ] -[[package]] -name = "redox_syscall" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" -dependencies = [ - "bitflags 1.3.2", -] - [[package]] name = "regex" version = "1.10.1" @@ -2376,28 +2163,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "rlp" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb919243f34364b6bd2fc10ef797edbfa75f33c252e7998527479c6d6b47e1ec" -dependencies = [ - "bytes", - "rlp-derive", - "rustc-hex", -] - -[[package]] -name = "rlp-derive" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e33d7b2abe0c340d8797fe2907d3f20d3b5ea5908683618bfe80df7f621f672a" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "rsa" version = "0.6.1" @@ -2489,12 +2254,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "rustversion" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" - [[package]] name = "ryu" version = "1.0.15" @@ -2510,30 +2269,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "scale-info" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35c0a159d0c45c12b20c5a844feb1fe4bea86e28f17b92a5f0c42193634d3782" -dependencies = [ - "cfg-if", - "derive_more", - "parity-scale-codec", - "scale-info-derive", -] - -[[package]] -name = "scale-info-derive" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "912e55f6d20e0e80d63733872b40e1227c0bce1e1ab81ba67d696339bfd7fd29" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "scopeguard" version = "1.2.0" @@ -2687,8 +2422,8 @@ name = "snark-verifier" version = "0.1.6" source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=community-edition#7011e8ce0c2f7e79ab9629aa528cfb6837cdeafe" dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-base", + "halo2-ecc", "hex", "itertools 0.11.0", "lazy_static", @@ -2702,24 +2437,6 @@ dependencies = [ "sha3 0.10.8", ] -[[package]] -name = "snark-verifier" -version = "0.1.7" -source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=develop#624b003c656e44b14202d4b8a16a2f7bc4e71eeb" -dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", - "hex", - "itertools 0.11.0", - "lazy_static", - "num-bigint", - "num-integer", - "num-traits", - "pairing", - "rand", - "serde", -] - [[package]] name = "snark-verifier-sdk" version = "0.1.6" @@ -2729,7 +2446,7 @@ dependencies = [ "bincode", "ethereum-types", "getset", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition)", + "halo2-base", "hex", "itertools 0.10.5", "lazy_static", @@ -2740,7 +2457,7 @@ dependencies = [ "rand_chacha", "serde", "serde_json", - "snark-verifier 0.1.6", + "snark-verifier", ] [[package]] @@ -2791,28 +2508,6 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" -[[package]] -name = "strum" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" -dependencies = [ - "strum_macros", -] - -[[package]] -name = "strum_macros" -version = "0.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8d03b598d3d0fff69bf533ee3ef19b8eeb342729596df84bcc7e1f96ec4059" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "rustversion", - "syn 2.0.33", -] - [[package]] name = "substrate-bn" version = "0.6.0" @@ -2872,19 +2567,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" -[[package]] -name = "tempfile" -version = "3.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef" -dependencies = [ - "cfg-if", - "fastrand", - "redox_syscall", - "rustix", - "windows-sys 0.48.0", -] - [[package]] name = "termcolor" version = "1.3.0" @@ -3465,22 +3147,3 @@ dependencies = [ "quote", "syn 2.0.33", ] - -[[package]] -name = "zkevm-hashes" -version = "0.2.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=feat/zkevm-sha256#adf331ecdd8ae492bced80d3157ae9c3b66fde04" -dependencies = [ - "array-init", - "ethers-core", - "getset", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=feat/zkevm-sha256)", - "itertools 0.11.0", - "lazy_static", - "log", - "num-bigint", - "rand", - "rayon", - "sha3 0.10.8", - "snark-verifier 0.1.7", -] diff --git a/packages/halo2-circuits/Cargo.toml b/packages/halo2-circuits/Cargo.toml index e26dbc1..cf3b144 100644 --- a/packages/halo2-circuits/Cargo.toml +++ b/packages/halo2-circuits/Cargo.toml @@ -66,3 +66,6 @@ default = ["halo2-axiom", "display"] display = ["halo2-base/display"] halo2-pse = ["halo2-base/halo2-pse"] halo2-axiom = ["halo2-base/halo2-axiom"] + +[workspace] +resolver = "2" \ No newline at end of file diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 12dd840..d24635b 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -95,10 +95,22 @@ fn main() { let nation_pubkey = read_nation_cert(&issuer_cert_path); let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); + let mut builder = BaseCircuitBuilder::new(false); + builder.set_k(k as usize); + builder.set_lookup_bits(circuit::LOOKUP_BITS); + builder.set_instance_columns(1); + let range_chip = builder.range_chip(); + let ctx = builder.main(0); + let public = circuit::PublicInput { nation_pubkey }; let private = circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; - let builder = circuit::proof_of_japanese_residence(public, private); + dbg!(tbs_cert.to_bytes_le().len()); + let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); + + builder.assigned_instances[0].extend(outputs); + let circuit_params = builder.calculate_params(None); + builder = builder.use_params(circuit_params); if Path::new(&pk_path).exists() { match remove_file(&pk_path) { @@ -115,10 +127,21 @@ fn main() { let nation_pubkey = read_nation_cert(&issuer_cert_path); let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); + let mut builder = BaseCircuitBuilder::new(false); + builder.set_k(k as usize); + builder.set_lookup_bits(circuit::LOOKUP_BITS); + builder.set_instance_columns(1); + let range_chip = builder.range_chip(); + let ctx = builder.main(0); + let public = circuit::PublicInput { nation_pubkey }; let private = circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; - let builder = circuit::proof_of_japanese_residence(public, private); + let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); + + builder.assigned_instances[0].extend(outputs); + let circuit_params = builder.calculate_params(None); + builder = builder.use_params(circuit_params); if Path::new(&proof_path).exists() { match remove_file(&proof_path) { diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index 5f8b43f..cd26114 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -1,6 +1,12 @@ use halo2_base::{ gates::{circuit::builder::BaseCircuitBuilder, GateInstructions, RangeChip, RangeInstructions}, - halo2_proofs::{arithmetic::Field, halo2curves::bn256::Fr}, + halo2_proofs::{ + arithmetic::Field, + halo2curves::{ + bn256::Fr, + ff::{PrimeField, PrimeFieldBits}, + }, + }, poseidon::hasher::{spec::OptimizedPoseidonSpec, PoseidonHasher}, AssignedValue, Context, QuantumCell, }; @@ -9,8 +15,10 @@ use halo2_rsa::{ AssignedBigUint, BigUintConfig, BigUintInstructions, Fresh, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, RSASignature, }; -use halo2_sha256_unoptimized::Sha256Chip; use num_bigint::BigUint; +use sha2::{Digest, Sha256}; +// use zkevm_hashes::Sha256Chip; +use halo2_sha256_unoptimized::Sha256Chip; #[derive(Debug, Clone)] pub struct PublicInput { @@ -27,7 +35,7 @@ pub struct PrivateInput { } // halo2-sha256-unoptimized takes inputs byte by byte so I guess 8 is optimimal -const LOOKUP_BITS: usize = 8; +pub const LOOKUP_BITS: usize = 8; const RSA_KEY_SIZE: usize = 2048; const PUBKEY_BEGINS: usize = 2216; const E: usize = 65537; @@ -39,12 +47,12 @@ const SHA256_INPUT_BLOCKS: usize = MAX_TBS_CERT_BITS / SHA256_BLOCK_BITS; // the pub fn bytes_to_biguint( ctx: &mut Context, biguint_chip: BigUintConfig, - src: &[AssignedValue], + bytes: &[AssignedValue], ) -> AssignedBigUint { let num_bases = (biguint_chip.limb_bits() / 8) as u64; let bases: Vec> = (0..num_bases).map(|i| QuantumCell::Constant(Fr::from(2).pow_vartime([i * 8]))).collect(); - let dest_limbs = src + let dest_limbs = bytes .chunks(biguint_chip.limb_bits() / 8) .map(|bytes_in_limb| { let dest_limb = biguint_chip.gate().inner_product(ctx, bytes_in_limb.to_vec(), bases.clone()); @@ -53,7 +61,7 @@ pub fn bytes_to_biguint( }) .collect(); - let bytes_in_rust: Vec = src.iter().map(|byte| byte.value().to_bytes()[0].clone()).collect(); + let bytes_in_rust: Vec = bytes.iter().map(|byte| byte.value().to_bytes()[0].clone()).collect(); let dest_in_rust = BigUint::from_bytes_le(&bytes_in_rust); AssignedBigUint::new(OverflowInteger::new(dest_limbs, biguint_chip.limb_bits()), dest_in_rust) } @@ -63,36 +71,31 @@ pub fn bytes_to_64s( range_chip: RangeChip, src: &[AssignedValue], ) -> Vec> { + // bug let biguint_chip = BigUintConfig::construct(range_chip, 64); bytes_to_biguint(ctx, biguint_chip, src).limbs().to_vec() } -pub fn proof_of_japanese_residence(public: PublicInput, private: PrivateInput) -> BaseCircuitBuilder { - // TODO: Choose this k - let k = 17; - let exp_bits = 5; // UNUSED - - let mut builder = BaseCircuitBuilder::new(false); - builder.set_k(k); - builder.set_lookup_bits(LOOKUP_BITS); - builder.set_instance_columns(1); - - let range_chip = builder.range_chip(); - let ctx = builder.main(0); +pub fn proof_of_japanese_residence( + ctx: &mut Context, + range_chip: RangeChip, + public: PublicInput, + private: PrivateInput, +) -> Vec> { let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); - let rsa_chip = RSAConfig::construct(biguint_chip, RSA_KEY_SIZE, exp_bits); + let rsa_chip = RSAConfig::construct(biguint_chip, RSA_KEY_SIZE, 5); let mut sha256_chip = Sha256Chip::construct(vec![SHA256_INPUT_BLOCKS * SHA256_BLOCK_BITS / 8], range_chip.clone(), true); - // let mut poseidon = PoseidonHasher::new(OptimizedPoseidonSpec::::new::<8, 57, 0>()); - // poseidon.initialize_consts(ctx, rsa_chip.gate()); + let mut poseidon = PoseidonHasher::new(OptimizedPoseidonSpec::::new::<8, 57, 0>()); + poseidon.initialize_consts(ctx, rsa_chip.gate()); // load public inputs - // let nation_pubkey = - // rsa_chip.assign_public_key(ctx, RSAPublicKey::new(public.nation_pubkey, RSAPubE::Fix(E.into()))).unwrap(); + let nation_pubkey = + rsa_chip.assign_public_key(ctx, RSAPublicKey::new(public.nation_pubkey, RSAPubE::Fix(E.into()))).unwrap(); // load private inputs - // let nation_sig = rsa_chip.assign_signature(ctx, RSASignature::new(private.nation_sig)).unwrap(); - // let password = ctx.load_witness(private.password); + let nation_sig = rsa_chip.assign_signature(ctx, RSASignature::new(private.nation_sig)).unwrap(); + let password = ctx.load_witness(private.password); // extract citizen's public key from the tbs certificate // let n = bytes_to_biguint( @@ -103,30 +106,72 @@ pub fn proof_of_japanese_residence(public: PublicInput, private: PrivateInput) - // let citizen_pubkey = AssignedRSAPublicKey::new(n.clone(), AssignedRSAPubE::Fix(E.into())); let sha256ed = sha256_chip.digest(ctx, &private.tbs_cert, None).unwrap(); - // let identity_commitment_preimage: Vec> = sha256ed.input_bytes - // [PUBKEY_BEGINS / 8..(PUBKEY_BEGINS + RSA_KEY_SIZE) / 8] - // .iter() - // .copied() - // .chain(std::iter::once(password)) - // .collect(); - // let identity_commitment = poseidon.hash_fix_len_array(ctx, rsa_chip.gate(), &identity_commitment_preimage); - - // let sha256ed_64s = bytes_to_64s(ctx, range_chip.clone(), &sha256ed.output_bytes); - // let is_nation_sig_valid = - // rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); - // rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); - - // builder.assigned_instances[0].push(identity_commitment); - // builder.assigned_instances[0].extend(nation_pubkey.n.limbs()); - builder.assigned_instances[0].extend(sha256ed.output_bytes); - let circuit_params = builder.calculate_params(None); - builder.use_params(circuit_params) + let identity_commitment_preimage: Vec> = sha256ed.input_bytes + [PUBKEY_BEGINS / 8..(PUBKEY_BEGINS + RSA_KEY_SIZE) / 8] + .iter() + .copied() + .chain(std::iter::once(password)) + .collect(); + + // println!("sha256ed"); + // for byte in &sha256ed.input_bytes[PUBKEY_BEGINS / 8..(PUBKEY_BEGINS + RSA_KEY_SIZE) / 8] { + // let byte = byte.value().to_repr()[0]; + // print!("{:0b}", byte); + // } + + let identity_commitment = poseidon.hash_fix_len_array(ctx, rsa_chip.gate(), &identity_commitment_preimage); + + let sha256ed_64s = + bytes_to_64s(ctx, range_chip.clone(), &sha256ed.output_bytes.iter().rev().copied().collect::>()); + + // assert_eq!( + // sha256ed_64s.iter().flat_map(|a| a.value().to_bytes()[0..8].to_vec()).collect::>(), + // Sha256::digest(private.tbs_cert).to_vec() + // ); + // println!("sha256ed_64s.len(): {}", sha256ed_64s.len()); + // for bytes in sha256ed_64s.iter() { + // let limbs = bytes.value().to_bytes(); + // for limb in limbs { + // print!("{:0b}", limb); + // } + // } + // println!("aa"); + + let hashed_tbs = Sha256::digest(private.tbs_cert); + println!("Hashed TBS: {:?}", hashed_tbs); + let mut hashed_bytes: Vec> = + hashed_tbs.iter().map(|limb| ctx.load_witness(Fr::from(*limb as u64))).collect(); + hashed_bytes.reverse(); + let bytes_bits = hashed_bytes.len() * 8; + let limb_bits = 64; + let limb_bytes = limb_bits / 8; + let mut hashed_u64s = vec![]; + let bases: Vec<_> = (0..limb_bytes).map(|i| Fr::from(1u64 << (8 * i))).map(QuantumCell::Constant).collect(); + for i in 0..(bytes_bits / limb_bits) { + let left: Vec<_> = + hashed_bytes[limb_bytes * i..limb_bytes * (i + 1)].iter().map(|x| QuantumCell::Existing(*x)).collect(); + let sum = rsa_chip.gate().inner_product(ctx, left, bases.clone()); + hashed_u64s.push(sum); + } + + assert_eq!( + sha256ed_64s.iter().map(|a| a.value()).collect::>(), + hashed_u64s.iter().map(|a| a.value()).collect::>() + ); + + let is_nation_sig_valid = + rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); + rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); + + let mut outputs = nation_pubkey.n.limbs().to_vec(); + outputs.push(identity_commitment); + outputs } #[cfg(test)] mod tests { use super::*; - use crate::helpers::read_citizen_cert; + use crate::helpers::{read_citizen_cert, read_nation_cert}; use halo2_base::{halo2_proofs::halo2curves::ff::PrimeField, utils::testing::base_test}; use num_traits::cast::ToPrimitive; @@ -146,19 +191,36 @@ mod tests { // }); // } + // #[test] + // fn aaa() { + // let two_pow_16 = Fr::from_raw([1 << 16, 0, 0, 0]); + // let mut test_subject = Fr::from_raw([0, 0, 0, 1 << 46]); + // while test_subject != Fr::zero() { + // for j in 1..16 { + // let k = test_subject * Fr::from_raw([1 << j, 0, 0, 0]); + // if two_pow_16 >= k { + // unreachable!("i:{:?},j:{:?},k:{:?}", test_subject.to_repr(), j, k.to_repr()); + // } + // } + + // test_subject += Fr::one(); + // } + // } + #[test] - fn aaa() { - let two_pow_16 = Fr::from_raw([1 << 16, 0, 0, 0]); - let mut test_subject = Fr::from_raw([0, 0, 0, 1 << 46]); - while test_subject != Fr::zero() { - for j in 1..16 { - let k = test_subject * Fr::from_raw([1 << j, 0, 0, 0]); - if two_pow_16 >= k { - unreachable!("i:{:?},j:{:?},k:{:?}", test_subject.to_repr(), j, k.to_repr()); - } - } - - test_subject += Fr::one(); - } + fn mock() { + let nation_pubkey = read_nation_cert("./certs/ca_cert.pem"); + let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert("./certs/myna_cert.pem"); + + base_test().k(22).run(|ctx, range_chip| { + let public = PublicInput { nation_pubkey: nation_pubkey.clone() }; + let private = PrivateInput { + tbs_cert: tbs_cert.to_bytes_le(), + nation_sig: nation_sig.clone(), + password: Fr::from(123), + }; + + let outputs = proof_of_japanese_residence(ctx, range_chip.clone(), public, private); + }); } } diff --git a/packages/halo2-circuits/src/helpers.rs b/packages/halo2-circuits/src/helpers.rs index 52b4606..a29470e 100644 --- a/packages/halo2-circuits/src/helpers.rs +++ b/packages/halo2-circuits/src/helpers.rs @@ -53,12 +53,13 @@ pub fn read_citizen_cert(cert_path: &str) -> (BigUint, BigUint, BigUint) { // Extract the TBS (To-Be-Signed) data from the certificate let tbs_bytes = cert.tbs_certificate.as_ref(); + dbg!(tbs_bytes.len()); let tbs_biguint = BigUint::from_bytes_le(tbs_bytes); // println!("TBS (To-Be-Signed): {:x?}", tbs); // Extract the signature from cert 3 let nation_sig_bytes = &cert.signature_value; - let nation_sig_biguint = BigUint::from_bytes_le(&nation_sig_bytes.data); + let nation_sig_biguint = BigUint::from_bytes_be(&nation_sig_bytes.data); let citizen_pubkey_bytes = cert.tbs_certificate.subject_pki.subject_public_key.as_ref(); let citizen_pubkey_biguint = BigUint::from_bytes_le(&citizen_pubkey_bytes[9..256 + 9]); From 44f8aeb16f91a3209a9dbcd4f35d0d244613167b Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Thu, 9 Nov 2023 15:33:33 +0900 Subject: [PATCH 09/28] Measure the gas cost --- packages/halo2-circuits/src/bin/cli.rs | 127 +++++++++++++++---------- 1 file changed, 75 insertions(+), 52 deletions(-) diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index d24635b..c8ea5a2 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -74,6 +74,28 @@ enum Commands { issuer_cert_path: String, password: u64, }, + /// Generate the proving key and the verification key for RSA circuit + GenerateSolidity { + /// k parameter for circuit. + #[arg(long, default_value = "17")] + k: u32, + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./params")] + params_path: String, + /// proving key path. output + #[arg(long, default_value = "./build/rsa.pk")] + pk_path: String, + /// proof path. output + #[arg(long, default_value = "./build/myna_verify_rsa.proof")] + proof_path: String, + // citizen's certificate + #[arg(long, default_value = "./certs/myna_cert.pem")] + verify_cert_path: String, + // nation's certificate + #[arg(long, default_value = "./certs/ca_cert.pem")] + issuer_cert_path: String, + password: u64, + }, } fn main() { @@ -93,7 +115,7 @@ fn main() { password, } => { let nation_pubkey = read_nation_cert(&issuer_cert_path); - let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); + let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(&verify_cert_path); let mut builder = BaseCircuitBuilder::new(false); builder.set_k(k as usize); @@ -154,56 +176,57 @@ fn main() { let trusted_setup = gen_srs(k); let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); gen_snark_shplonk(&trusted_setup, &pk, builder, Some(Path::new(&proof_path))); - } /* Commands::GenRsaVerifyEVMProof { - * k, - * params_path, - * pk_path, - * verify_cert_path, - * issuer_cert_path, - * proof_path, - * } => { - * env::set_var("PARAMS_DIR", params_path); - * let params = gen_srs(k); */ - - /* let (tbs, signature_bigint) = extract_tbs_and_sig(&verify_cert_path); - * let public_key_modulus = extract_public_key(&issuer_cert_path); */ - - /* let builder = create_default_rsa_circuit_with_instances( - * k as usize, - * tbs, - * public_key_modulus, - * signature_bigint, - * ); - * let pk = - * read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); */ - - /* if Path::new(&proof_path).exists() { - * match remove_file(&proof_path) { - * Ok(_) => println!("File found, overwriting..."), - * Err(e) => println!("An error occurred: {}", e), - * } - * } - * gen_snark_shplonk(¶ms, &pk, builder.clone(), Some(Path::new(&proof_path))); */ - - /* let deployment_code = gen_evm_verifier_shplonk::>( - * ¶ms, - * pk.get_vk(), - * builder.num_instance(), - * Some(Path::new("./build/VerifyRsa.sol")), - * ); */ - - /* let proof = gen_evm_proof_shplonk(¶ms, &pk, builder.clone(), builder.instances()); */ - - /* println!("Size of the contract: {} bytes", deployment_code.len()); - * println!("Deploying contract..."); */ - - /* evm_verify(deployment_code, builder.instances(), proof.clone()); */ - - /* println!("Verification success!"); */ - - /* write_calldata(&builder.instances(), &proof, Path::new("./build/calldata.txt")).unwrap(); - * println!("Succesfully generate calldata!"); */ - - /* } */ + } + Commands::GenerateSolidity { + k, + params_path, + pk_path, + proof_path, + verify_cert_path, + issuer_cert_path, + password, + } => { + let nation_pubkey = read_nation_cert(&issuer_cert_path); + let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); + + let mut builder = BaseCircuitBuilder::new(false); + builder.set_k(k as usize); + builder.set_lookup_bits(circuit::LOOKUP_BITS); + builder.set_instance_columns(1); + let range_chip = builder.range_chip(); + let ctx = builder.main(0); + + let public = circuit::PublicInput { nation_pubkey }; + let private = + circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; + let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); + + builder.assigned_instances[0].extend(outputs); + let circuit_params = builder.calculate_params(None); + builder = builder.use_params(circuit_params); + + env::set_var("PARAMS_DIR", params_path); + let trusted_setup = gen_srs(k); + let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); + + let deployment_code = gen_evm_verifier_shplonk::>( + &trusted_setup, + pk.get_vk(), + builder.num_instance(), + Some(Path::new("./build/VerifyRsa.sol")), + ); + + let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, builder.clone(), builder.instances()); + + println!("Size of the contract: {} bytes", deployment_code.len()); + println!("Deploying contract..."); + + evm_verify(deployment_code, builder.instances(), proof.clone()); + + println!("Verification success!"); + + write_calldata(&builder.instances(), &proof, Path::new("./build/calldata.txt")).unwrap(); + println!("Succesfully generate calldata!"); + } } } From 4d568ab8c93482d83cac8d9c2c7c45b721e1d636 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Thu, 9 Nov 2023 20:56:17 +0900 Subject: [PATCH 10/28] Test the circuit with just Halo2, without halo2-base --- packages/halo2-circuits/src/circuit.rs | 96 ++++++++++++++++++++++---- 1 file changed, 82 insertions(+), 14 deletions(-) diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index cd26114..d300dde 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -1,11 +1,14 @@ use halo2_base::{ - gates::{circuit::builder::BaseCircuitBuilder, GateInstructions, RangeChip, RangeInstructions}, + gates::{ + circuit::{builder::BaseCircuitBuilder, BaseCircuitParams, BaseConfig}, + GateInstructions, RangeChip, RangeInstructions, + }, halo2_proofs::{ arithmetic::Field, - halo2curves::{ - bn256::Fr, - ff::{PrimeField, PrimeFieldBits}, - }, + circuit::{Layouter, SimpleFloorPlanner}, + dev::MockProver, + halo2curves::bn256::Fr, + plonk::{Circuit, ConstraintSystem, Error}, }, poseidon::hasher::{spec::OptimizedPoseidonSpec, PoseidonHasher}, AssignedValue, Context, QuantumCell, @@ -39,6 +42,7 @@ pub const LOOKUP_BITS: usize = 8; const RSA_KEY_SIZE: usize = 2048; const PUBKEY_BEGINS: usize = 2216; const E: usize = 65537; +const K: usize = 22; const LIMB_BITS: usize = 64; const SHA256_BLOCK_BITS: usize = 512; const MAX_TBS_CERT_BITS: usize = 1 << 15; @@ -76,6 +80,50 @@ pub fn bytes_to_64s( bytes_to_biguint(ctx, biguint_chip, src).limbs().to_vec() } +#[derive(Debug, Clone)] +struct Config { + halo2base: BaseConfig, +} + +#[derive(Debug, Clone, Default)] +struct ProofOfJapaneseResidence { + halo2base: BaseCircuitBuilder, +} + +impl Circuit for ProofOfJapaneseResidence { + type Config = Config; + type Params = BaseCircuitParams; + type FloorPlanner = SimpleFloorPlanner; + + fn without_witnesses(&self) -> Self { + Self::default() + } + + fn params(&self) -> Self::Params { + self.halo2base.config_params.clone() + } + + fn configure_with_params(meta: &mut ConstraintSystem, params: BaseCircuitParams) -> Self::Config { + Self::Config { halo2base: BaseConfig::configure(meta, params) } + } + + fn configure(_: &mut ConstraintSystem) -> Self::Config { + unreachable!("halo2-base says I must not call configure"); + } + + fn synthesize(&self, config: Self::Config, mut layouter: impl Layouter) -> Result<(), Error> { + self.halo2base.synthesize(config.halo2base, layouter)?; + + // TODO: SHA256 + + Ok(()) + } +} + +impl ProofOfJapaneseResidence { + fn assign_halo2base() {} +} + pub fn proof_of_japanese_residence( ctx: &mut Context, range_chip: RangeChip, @@ -209,18 +257,38 @@ mod tests { #[test] fn mock() { + let mut builder = BaseCircuitBuilder::default(); + builder.set_k(K); + builder.set_lookup_bits(LOOKUP_BITS); + builder.set_instance_columns(1); + let range_chip = builder.range_chip().clone(); + let nation_pubkey = read_nation_cert("./certs/ca_cert.pem"); let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert("./certs/myna_cert.pem"); + let public_input = PublicInput { nation_pubkey: nation_pubkey.clone() }; + let private_input = + PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig: nation_sig.clone(), password: Fr::from(123) }; + let public_outputs = + proof_of_japanese_residence(builder.pool(0).main(), range_chip, public_input, private_input); + + builder.assigned_instances[0].extend(public_outputs); + // AUDIT: Is K enough to achieve zero knowledge? + builder.calculate_params(Some(9)); - base_test().k(22).run(|ctx, range_chip| { - let public = PublicInput { nation_pubkey: nation_pubkey.clone() }; - let private = PrivateInput { - tbs_cert: tbs_cert.to_bytes_le(), - nation_sig: nation_sig.clone(), - password: Fr::from(123), - }; + let circuit = ProofOfJapaneseResidence { halo2base: builder }; + dbg!(circuit.params()); - let outputs = proof_of_japanese_residence(ctx, range_chip.clone(), public, private); - }); + MockProver::run( + K as u32, + &circuit, + circuit + .halo2base + .assigned_instances + .iter() + .map(|public_column| public_column.into_iter().map(|public_cell| public_cell.value().clone()).collect()) + .collect(), + ) + .expect("The circuit generation failed") + .assert_satisfied(); } } From 6fc2206d6231232062f5e4ebad6b5961b36380be Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Thu, 9 Nov 2023 21:36:33 +0900 Subject: [PATCH 11/28] Feed TBSCertificate into the circuit by splitting it by 32bits each --- packages/halo2-circuits/Cargo.lock | 1146 ++++++++++++++---------- packages/halo2-circuits/Cargo.toml | 14 +- packages/halo2-circuits/src/bin/cli.rs | 184 ++-- packages/halo2-circuits/src/circuit.rs | 95 +- packages/halo2-circuits/src/helpers.rs | 63 -- 5 files changed, 810 insertions(+), 692 deletions(-) diff --git a/packages/halo2-circuits/Cargo.lock b/packages/halo2-circuits/Cargo.lock index a55e8e2..8998c3b 100644 --- a/packages/halo2-circuits/Cargo.lock +++ b/packages/halo2-circuits/Cargo.lock @@ -17,17 +17,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" -[[package]] -name = "ahash" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c99f64d1e06488f620f932677e24bc6e2897582980441ae90a671415bd7ec2f" -dependencies = [ - "cfg-if", - "once_cell", - "version_check", -] - [[package]] name = "aho-corasick" version = "1.1.2" @@ -37,52 +26,17 @@ dependencies = [ "memchr", ] -[[package]] -name = "allocator-api2" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" - -[[package]] -name = "alloy-primitives" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0628ec0ba5b98b3370bb6be17b12f23bfce8ee4ad83823325a20546d9b03b78" -dependencies = [ - "alloy-rlp", - "bytes", - "cfg-if", - "const-hex", - "derive_more", - "hex-literal", - "itoa", - "ruint", - "tiny-keccak", -] - [[package]] name = "alloy-rlp" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc0fac0fc16baf1f63f78b47c3d24718f3619b0714076f6a02957d808d52cbef" dependencies = [ - "alloy-rlp-derive", "arrayvec", "bytes", "smol_str", ] -[[package]] -name = "alloy-rlp-derive" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0391754c09fab4eae3404d19d0d297aa1c670c1775ab51d8a5312afeca23157" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.33", -] - [[package]] name = "anes" version = "0.1.6" @@ -129,6 +83,110 @@ dependencies = [ "windows-sys 0.45.0", ] +[[package]] +name = "ark-ff" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b3235cc41ee7a12aaaf2c575a2ad7b46713a8a50bda2fc3b003a04845c05dd6" +dependencies = [ + "ark-ff-asm 0.3.0", + "ark-ff-macros 0.3.0", + "ark-serialize 0.3.0", + "ark-std 0.3.0", + "derivative", + "num-bigint", + "num-traits", + "paste", + "rustc_version 0.3.3", + "zeroize", +] + +[[package]] +name = "ark-ff" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec847af850f44ad29048935519032c33da8aa03340876d351dfab5660d2966ba" +dependencies = [ + "ark-ff-asm 0.4.2", + "ark-ff-macros 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "derivative", + "digest 0.10.7", + "itertools 0.10.5", + "num-bigint", + "num-traits", + "paste", + "rustc_version 0.4.0", + "zeroize", +] + +[[package]] +name = "ark-ff-asm" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db02d390bf6643fb404d3d22d31aee1c4bc4459600aef9113833d17e786c6e44" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-asm" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed4aa4fe255d0bc6d79373f7e31d2ea147bcf486cba1be5ba7ea85abdb92348" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" +dependencies = [ + "num-bigint", + "num-traits", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-macros" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-serialize" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d6c2b318ee6e10f8c2853e73a83adc0ccb88995aa978d8a3408d492ab2ee671" +dependencies = [ + "ark-std 0.3.0", + "digest 0.9.0", +] + +[[package]] +name = "ark-serialize" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" +dependencies = [ + "ark-std 0.4.0", + "digest 0.10.7", + "num-bigint", +] + [[package]] name = "ark-std" version = "0.3.0" @@ -140,6 +198,22 @@ dependencies = [ "rand", ] +[[package]] +name = "ark-std" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" +dependencies = [ + "num-traits", + "rand", +] + +[[package]] +name = "array-init" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc" + [[package]] name = "arrayref" version = "0.3.7" @@ -256,29 +330,6 @@ dependencies = [ "serde", ] -[[package]] -name = "bindgen" -version = "0.66.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b84e06fc203107bfbad243f4aba2af864eb7db3b1cf46ea0a023b0b433d2a7" -dependencies = [ - "bitflags 2.4.0", - "cexpr", - "clang-sys", - "lazy_static", - "lazycell", - "log", - "peeking_take_while", - "prettyplease", - "proc-macro2", - "quote", - "regex", - "rustc-hash", - "shlex", - "syn 2.0.33", - "which", -] - [[package]] name = "bitflags" version = "1.3.2" @@ -287,9 +338,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" +checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" [[package]] name = "bitvec" @@ -339,18 +390,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d696c370c750c948ada61c69a0ee2cbbb9c50b1019ddb86d9317157a99c2cae" -[[package]] -name = "blst" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c94087b935a822949d3291a9989ad2b2051ea141eda0fd4e478a75f6aa3e604b" -dependencies = [ - "cc", - "glob", - "threadpool", - "zeroize", -] - [[package]] name = "bumpalo" version = "3.14.0" @@ -365,28 +404,16 @@ checksum = "c3ac9f8b63eca6fd385229b3675f6cc0dc5c8a5c8a54a59d4f52ffd670d87b0c" [[package]] name = "byteorder" -version = "1.4.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" - -[[package]] -name = "c-kzg" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac926d808fb72fe09ebf471a091d6d72918876ccf0b4989766093d2d0d24a0ef" dependencies = [ - "bindgen", - "blst", - "cc", - "glob", - "hex", - "libc", "serde", ] @@ -405,21 +432,21 @@ dependencies = [ "libc", ] -[[package]] -name = "cexpr" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" -dependencies = [ - "nom", -] - [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "chrono" +version = "0.4.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" +dependencies = [ + "num-traits", +] + [[package]] name = "ciborium" version = "0.2.1" @@ -447,17 +474,6 @@ dependencies = [ "half", ] -[[package]] -name = "clang-sys" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c688fc74432808e3eb684cae8830a86be1d66a2bd58e1f248ed0960a590baf6f" -dependencies = [ - "glob", - "libc", - "libloading", -] - [[package]] name = "clap" version = "3.2.25" @@ -503,7 +519,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -568,13 +584,14 @@ dependencies = [ [[package]] name = "const-hex" -version = "1.9.1" +version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c37be52ef5e3b394db27a2341010685ad5103c72ac15ce2e9420a7e8f93f342c" +checksum = "a5104de16b218eddf8e34ffe2f86f74bfa4e61e95a1b89732fccf6325efd0557" dependencies = [ "cfg-if", "cpufeatures", "hex", + "proptest", "serde", ] @@ -596,17 +613,11 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7144d30dcf0fafbce74250a3963025d8d52177934239851c917d29f1df280c2" -[[package]] -name = "convert_case" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" - [[package]] name = "cpufeatures" -version = "0.2.9" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" +checksum = "ce420fe07aecd3e67c5f910618fe65e94158f6dcc0adf44e00d69ce2bdfe0fd0" dependencies = [ "libc", ] @@ -802,16 +813,25 @@ dependencies = [ "powerfmt", ] +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "derive_more" version = "0.99.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" dependencies = [ - "convert_case", "proc-macro2", "quote", - "rustc_version", "syn 1.0.109", ] @@ -844,7 +864,7 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -886,17 +906,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "enumn" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2ad8cef1d801a4686bfd8919f0b30eac4c8e48968c437a6405ded4fb5272d2b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.33", -] - [[package]] name = "env_logger" version = "0.10.0" @@ -918,14 +927,31 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.5" +version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3e13f66a2f95e32a39eaa81f6b95d42878ca0e1db0c7543723dfe12557e860" +checksum = "7c18ee0ed65a5f1f81cac6b1d213b69c35fa47d4252ad41f1486dbd8226fe36e" dependencies = [ "libc", "windows-sys 0.48.0", ] +[[package]] +name = "ethabi" +version = "18.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7413c5f74cc903ea37386a8965a936cbeb334bd270862fdece542c1b2dcbc898" +dependencies = [ + "ethereum-types", + "hex", + "once_cell", + "regex", + "serde", + "serde_json", + "sha3 0.10.8", + "thiserror", + "uint", +] + [[package]] name = "ethbloom" version = "0.13.0" @@ -934,6 +960,10 @@ checksum = "c22d4b5885b6aa2fe5e8b9329fb8d232bf739e434e6b87347c63bdd00c120f60" dependencies = [ "crunchy", "fixed-hash", + "impl-codec", + "impl-rlp", + "impl-serde", + "scale-info", "tiny-keccak", ] @@ -945,10 +975,58 @@ checksum = "02d215cbf040552efcbe99a38372fe80ab9d00268e20012b79fcd0f073edd8ee" dependencies = [ "ethbloom", "fixed-hash", + "impl-codec", + "impl-rlp", + "impl-serde", "primitive-types", + "scale-info", "uint", ] +[[package]] +name = "ethers-core" +version = "2.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0a17f0708692024db9956b31d7a20163607d2745953f5ae8125ab368ba280ad" +dependencies = [ + "arrayvec", + "bytes", + "chrono", + "const-hex", + "elliptic-curve", + "ethabi", + "generic-array", + "k256", + "num_enum", + "open-fastrlp", + "rand", + "rlp", + "serde", + "serde_json", + "strum", + "tempfile", + "thiserror", + "tiny-keccak", + "unicode-xid", +] + +[[package]] +name = "fastrand" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" + +[[package]] +name = "fastrlp" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139834ddba373bbdd213dffe02c8d110508dcf1726c2be27e8d1f7d7e1856418" +dependencies = [ + "arrayvec", + "auto_impl", + "bytes", +] + [[package]] name = "ff" version = "0.13.0" @@ -1006,9 +1084,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.10" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427" +checksum = "fe9006bed769170c11f845cf00c7c1e9092aeb3f268e007c3e760ac68008070f" dependencies = [ "cfg-if", "js-sys", @@ -1035,12 +1113,6 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" -[[package]] -name = "glob" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" - [[package]] name = "group" version = "0.13.0" @@ -1061,9 +1133,29 @@ checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" [[package]] name = "halo2-base" version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition#980b39bcca5b3327aaef6c8d73577d9381bfa899" +source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop#ee12efa86fdd89ae7b37c8f11005888180a1d316" +dependencies = [ + "getset", + "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", + "itertools 0.11.0", + "log", + "num-bigint", + "num-integer", + "num-traits", + "poseidon-rs", + "rand_chacha", + "rayon", + "rustc-hash", + "serde", + "serde_json", +] + +[[package]] +name = "halo2-base" +version = "0.4.0" +source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc#a30e3b18d285c8b0d7145c1c34297edd9433df60" dependencies = [ - "ark-std", + "ark-std 0.3.0", "getset", "halo2_proofs 0.2.0 (git+https://github.com/privacy-scaling-explorations/halo2.git?rev=7a21656)", "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", @@ -1081,6 +1173,28 @@ dependencies = [ "serde_json", ] +[[package]] +name = "halo2-base" +version = "0.4.0" +source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#10960fc9b6613ac93049916680da3a7f40f75d31" +dependencies = [ + "ark-std 0.3.0", + "getset", + "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", + "itertools 0.11.0", + "log", + "num-bigint", + "num-integer", + "num-traits", + "poseidon-rs", + "rand", + "rand_chacha", + "rayon", + "rustc-hash", + "serde", + "serde_json", +] + [[package]] name = "halo2-circuits" version = "0.1.0" @@ -1091,10 +1205,9 @@ dependencies = [ "env_logger", "getrandom", "getset", - "halo2-base", - "halo2-ecc", + "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", + "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", "halo2-rsa", - "halo2-sha256-unoptimized", "itertools 0.11.0", "num-bigint", "num-traits", @@ -1108,14 +1221,15 @@ dependencies = [ "snark-verifier-sdk", "tokio", "x509-parser", + "zkevm-hashes", ] [[package]] name = "halo2-ecc" version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition#980b39bcca5b3327aaef6c8d73577d9381bfa899" +source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop#ee12efa86fdd89ae7b37c8f11005888180a1d316" dependencies = [ - "halo2-base", + "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", "itertools 0.10.5", "num-bigint", "num-integer", @@ -1130,38 +1244,35 @@ dependencies = [ ] [[package]] -name = "halo2-rsa" -version = "0.1.0" -source = "git+https://github.com/MynaWallet/halo2-rsa.git?branch=main#231d5421011276dfb7d6a6f84144a2dea9c9e3fe" +name = "halo2-ecc" +version = "0.4.0" +source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc#a30e3b18d285c8b0d7145c1c34297edd9433df60" dependencies = [ - "env_logger", - "halo2-base", - "halo2-ecc", + "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", + "itertools 0.10.5", "num-bigint", + "num-integer", "num-traits", "rand", - "rsa", - "sha2", + "rand_chacha", + "rand_core", + "rayon", + "serde", + "serde_json", + "test-case", ] [[package]] -name = "halo2-sha256-unoptimized" +name = "halo2-rsa" version = "0.1.0" -source = "git+https://github.com/zkpdf/halo2-sha256-unoptimized.git?branch=main#ec2d2b28cdb7dd38cb9896b09720d09923fcc2f2" dependencies = [ - "console_error_panic_hook", "env_logger", - "generic-array", - "getrandom", - "halo2-base", - "hex", - "itertools 0.10.5", + "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", + "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", "num-bigint", "num-traits", "rand", - "rayon", "rsa", - "serde", "sha2", ] @@ -1184,7 +1295,7 @@ dependencies = [ [[package]] name = "halo2_proofs" version = "0.2.0" -source = "git+https://github.com/axiom-crypto/halo2.git#4b42325623c9cfea02441ce0cffa17ebf962b3bb" +source = "git+https://github.com/axiom-crypto/halo2.git#2e98a5ce91791c5fc77541e8afb6abc29a9b1dac" dependencies = [ "blake2b_simd", "crossbeam", @@ -1252,13 +1363,9 @@ checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" [[package]] name = "hashbrown" -version = "0.14.1" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dfda62a12f55daeae5015f81b0baea145391cb4520f86c248fc615d72640d12" -dependencies = [ - "ahash", - "allocator-api2", -] +checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156" [[package]] name = "heck" @@ -1277,9 +1384,9 @@ dependencies = [ [[package]] name = "hermit-abi" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" +checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" [[package]] name = "hex" @@ -1290,12 +1397,6 @@ dependencies = [ "serde", ] -[[package]] -name = "hex-literal" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" - [[package]] name = "hmac" version = "0.12.1" @@ -1305,15 +1406,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "home" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" -dependencies = [ - "windows-sys 0.48.0", -] - [[package]] name = "humantime" version = "2.1.0" @@ -1329,6 +1421,24 @@ dependencies = [ "parity-scale-codec", ] +[[package]] +name = "impl-rlp" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28220f89297a075ddc7245cd538076ee98b01f2a9c23a53a4f1105d5a322808" +dependencies = [ + "rlp", +] + +[[package]] +name = "impl-serde" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc88fc67028ae3db0c853baa36269d398d5f45b6982f95549ff5def78c935cd" +dependencies = [ + "serde", +] + [[package]] name = "impl-trait-for-tuples" version = "0.2.2" @@ -1352,12 +1462,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.0.2" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8adf3ddd720272c6ea8bf59463c04e0f93d0bbf7c5439b691bca2987e0270897" +checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" dependencies = [ "equivalent", - "hashbrown 0.14.1", + "hashbrown 0.14.2", ] [[package]] @@ -1366,7 +1476,7 @@ version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" dependencies = [ - "hermit-abi 0.3.2", + "hermit-abi 0.3.3", "rustix", "windows-sys 0.48.0", ] @@ -1397,9 +1507,9 @@ checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" [[package]] name = "js-sys" -version = "0.3.64" +version = "0.3.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" +checksum = "54c0c35952f67de54bb584e9fd912b3023117cbafc0a77d8f3dee1fb5f572fe8" dependencies = [ "wasm-bindgen", ] @@ -1435,39 +1545,23 @@ dependencies = [ "spin", ] -[[package]] -name = "lazycell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" - [[package]] name = "libc" -version = "0.2.148" +version = "0.2.150" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cdc71e17332e86d2e1d38c1f99edcb6288ee11b815fb1a4b049eaa2114d369b" - -[[package]] -name = "libloading" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" -dependencies = [ - "cfg-if", - "winapi", -] +checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c" [[package]] name = "libm" -version = "0.2.7" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7012b1bbb0719e1097c47611d3898568c546d597c2e74d66f6087edd5233ff4" +checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" [[package]] name = "linux-raw-sys" -version = "0.4.10" +version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da2479e8c062e40bf0066ffa0bc823de0a9368974af99c9f6df941d2c231e03f" +checksum = "969488b55f8ac402214f3f5fd243ebb7206cf82de60d3172994707a4bcc2b829" [[package]] name = "log" @@ -1517,9 +1611,9 @@ dependencies = [ [[package]] name = "mio" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" +checksum = "3dce281c5e46beae905d4de1870d8b1509a9142b62eedf18b443b011ca8343d0" dependencies = [ "libc", "wasi", @@ -1536,20 +1630,6 @@ dependencies = [ "minimal-lexical", ] -[[package]] -name = "num" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b05180d69e3da0e530ba2a1dae5110317e49e3b7f3d41be227dc5f92e49ee7af" -dependencies = [ - "num-bigint", - "num-complex", - "num-integer", - "num-iter", - "num-rational", - "num-traits", -] - [[package]] name = "num-bigint" version = "0.4.4" @@ -1580,15 +1660,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "num-complex" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ba157ca0885411de85d6ca030ba7e2a83a28636056c7c699b07c8b6f7383214" -dependencies = [ - "num-traits", -] - [[package]] name = "num-integer" version = "0.1.45" @@ -1611,35 +1682,44 @@ dependencies = [ ] [[package]] -name = "num-rational" -version = "0.4.1" +name = "num-traits" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" +checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" dependencies = [ "autocfg", - "num-bigint", - "num-integer", - "num-traits", + "libm", +] + +[[package]] +name = "num_cpus" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +dependencies = [ + "hermit-abi 0.3.3", + "libc", ] [[package]] -name = "num-traits" -version = "0.2.16" +name = "num_enum" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" +checksum = "683751d591e6d81200c39fb0d1032608b77724f34114db54f571ff1317b337c0" dependencies = [ - "autocfg", - "libm", + "num_enum_derive", ] [[package]] -name = "num_cpus" -version = "1.16.0" +name = "num_enum_derive" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +checksum = "6c11e44798ad209ccdd91fc192f0526a369a01234f7373e1b141c96d7cee4f0e" dependencies = [ - "hermit-abi 0.3.2", - "libc", + "proc-macro-crate 2.0.0", + "proc-macro2", + "quote", + "syn 2.0.39", ] [[package]] @@ -1678,13 +1758,38 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" +[[package]] +name = "open-fastrlp" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "786393f80485445794f6043fd3138854dd109cc6c4bd1a6383db304c9ce9b9ce" +dependencies = [ + "arrayvec", + "auto_impl", + "bytes", + "ethereum-types", + "open-fastrlp-derive", +] + +[[package]] +name = "open-fastrlp-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "003b2be5c6c53c1cfeb0a238b8a1c3915cd410feb684457a36c10038f764bb1c" +dependencies = [ + "bytes", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "openssl" -version = "0.10.57" +version = "0.10.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bac25ee399abb46215765b1cb35bc0212377e58a061560d8b29b024fd0430e7c" +checksum = "7a257ad03cd8fb16ad4172fedf8094451e1af1c4b70097636ef2eac9a5f0cc33" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.4.1", "cfg-if", "foreign-types", "libc", @@ -1701,14 +1806,14 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] name = "openssl-sys" -version = "0.9.93" +version = "0.9.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db4d56a4c0478783083cfafcc42493dd4a981d41669da64b4572a2a089b51b1d" +checksum = "40a4130519a360279579c2053038317e40eff64d13fd3f004f9e1b72b8a6aaf9" dependencies = [ "cc", "libc", @@ -1751,7 +1856,7 @@ version = "3.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "312270ee71e1cd70289dacf597cab7b207aa107d2f28191c2ae45b2ece18a260" dependencies = [ - "proc-macro-crate", + "proc-macro-crate 1.3.1", "proc-macro2", "quote", "syn 1.0.109", @@ -1778,12 +1883,6 @@ version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" -[[package]] -name = "peeking_take_while" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" - [[package]] name = "pem-rfc7468" version = "0.3.1" @@ -1793,6 +1892,17 @@ dependencies = [ "base64ct", ] +[[package]] +name = "pest" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae9cee2a55a544be8b89dc6848072af97a20f2422603c10865be2a42b580fff5" +dependencies = [ + "memchr", + "thiserror", + "ucd-trie", +] + [[package]] name = "pin-project-lite" version = "0.2.13" @@ -1891,16 +2001,6 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" -[[package]] -name = "prettyplease" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae005bd773ab59b4725093fd7df83fd7892f7d8eafb48dbd7de6e024e4215f9d" -dependencies = [ - "proc-macro2", - "syn 2.0.33", -] - [[package]] name = "primitive-types" version = "0.12.2" @@ -1909,6 +2009,9 @@ checksum = "0b34d9fd68ae0b74a41b21c03c2f62847aa0ffea044eee893b4c140b37e244e2" dependencies = [ "fixed-hash", "impl-codec", + "impl-rlp", + "impl-serde", + "scale-info", "uint", ] @@ -1919,7 +2022,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" dependencies = [ "once_cell", - "toml_edit", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e8366a6159044a37876a2b9817124296703c586a5c92e2c53751fa06d8d43e8" +dependencies = [ + "toml_edit 0.20.7", ] [[package]] @@ -1948,9 +2060,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.67" +version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d433d9f1a3e8c1263d9456598b16fec66f4acc9a74dacffd35c7bb09b3a1328" +checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" dependencies = [ "unicode-ident", ] @@ -1961,11 +2073,13 @@ version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c003ac8c77cb07bb74f5f198bce836a689bcd5a42574612bf14d17bfd08c20e" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.4.1", + "lazy_static", "num-traits", "rand", "rand_chacha", "rand_xorshift", + "regex-syntax 0.7.5", "unarray", ] @@ -2025,9 +2139,9 @@ dependencies = [ [[package]] name = "rayon" -version = "1.7.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b" +checksum = "9c27db03db7734835b3f53954b534c91069375ce6ccaa2e065441e07d9b6cdb1" dependencies = [ "either", "rayon-core", @@ -2035,99 +2149,57 @@ dependencies = [ [[package]] name = "rayon-core" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d" +checksum = "5ce3fb6ad83f861aac485e76e1985cd109d9a3713802152be56c3b1f0e0658ed" dependencies = [ - "crossbeam-channel", "crossbeam-deque", "crossbeam-utils", - "num_cpus", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", ] [[package]] name = "regex" -version = "1.10.1" +version = "1.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaac441002f822bc9705a681810a4dd2963094b9ca0ddc41cb963a4c189189ea" +checksum = "380b951a9c5e80ddfd6136919eef32310721aa4aacd4889a8d39124b026ab343" dependencies = [ "aho-corasick", "memchr", "regex-automata", - "regex-syntax", + "regex-syntax 0.8.2", ] [[package]] name = "regex-automata" -version = "0.4.2" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5011c7e263a695dc8ca064cddb722af1be54e517a280b12a5356f98366899e5d" +checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" dependencies = [ "aho-corasick", "memchr", - "regex-syntax", + "regex-syntax 0.8.2", ] [[package]] name = "regex-syntax" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" - -[[package]] -name = "revm" -version = "3.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68f4ca8ae0345104523b4af1a8a7ea97cfa1865cdb7a7c25d23c1a18d9b48598" -dependencies = [ - "auto_impl", - "revm-interpreter", - "revm-precompile", -] - -[[package]] -name = "revm-interpreter" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f959cafdf64a7f89b014fa73dc2325001cf654b3d9400260b212d19a2ebe3da0" -dependencies = [ - "revm-primitives", -] - -[[package]] -name = "revm-precompile" -version = "2.2.0" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d360a88223d85709d2e95d4609eb1e19c649c47e28954bfabae5e92bb37e83e" -dependencies = [ - "c-kzg", - "k256", - "num", - "once_cell", - "revm-primitives", - "ripemd", - "secp256k1", - "sha2", - "substrate-bn", -] +checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" [[package]] -name = "revm-primitives" -version = "1.3.0" +name = "regex-syntax" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51187b852d9e458816a2e19c81f1dd6c924077e1a8fccd16e4f044f865f299d7" -dependencies = [ - "alloy-primitives", - "alloy-rlp", - "auto_impl", - "bitflags 2.4.0", - "bitvec", - "c-kzg", - "enumn", - "hashbrown 0.14.1", - "hex", - "once_cell", -] +checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" [[package]] name = "rfc6979" @@ -2155,12 +2227,25 @@ dependencies = [ ] [[package]] -name = "ripemd" -version = "0.1.3" +name = "rlp" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" +checksum = "bb919243f34364b6bd2fc10ef797edbfa75f33c252e7998527479c6d6b47e1ec" dependencies = [ - "digest 0.10.7", + "bytes", + "rlp-derive", + "rustc-hex", +] + +[[package]] +name = "rlp-derive" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e33d7b2abe0c340d8797fe2907d3f20d3b5ea5908683618bfe80df7f621f672a" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", ] [[package]] @@ -2191,8 +2276,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95294d6e3a6192f3aabf91c38f56505a625aa495533442744185a36d75a790c4" dependencies = [ "alloy-rlp", + "ark-ff 0.3.0", + "ark-ff 0.4.2", + "bytes", + "fastrlp", + "num-bigint", + "parity-scale-codec", + "primitive-types", "proptest", "rand", + "rlp", "ruint-macro", "serde", "valuable", @@ -2223,13 +2316,22 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" +[[package]] +name = "rustc_version" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +dependencies = [ + "semver 0.11.0", +] + [[package]] name = "rustc_version" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ - "semver", + "semver 1.0.20", ] [[package]] @@ -2243,17 +2345,23 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.19" +version = "0.38.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "745ecfa778e66b2b63c88a61cb36e0eea109e803b0b86bf9879fbc77c70e86ed" +checksum = "2b426b0506e5d50a7d8dafcf2e81471400deb602392c7dd110815afb4eaf02a3" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.4.1", "errno", "libc", "linux-raw-sys", "windows-sys 0.48.0", ] +[[package]] +name = "rustversion" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" + [[package]] name = "ryu" version = "1.0.15" @@ -2269,6 +2377,30 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "scale-info" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f7d66a1128282b7ef025a8ead62a4a9fcf017382ec53b8ffbf4d7bf77bd3c60" +dependencies = [ + "cfg-if", + "derive_more", + "parity-scale-codec", + "scale-info-derive", +] + +[[package]] +name = "scale-info-derive" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abf2c68b89cafb3b8d918dd07b42be0da66ff202cf1155c5739a4e0c1ea0dc19" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -2290,21 +2422,12 @@ dependencies = [ ] [[package]] -name = "secp256k1" -version = "0.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25996b82292a7a57ed3508f052cfff8640d38d32018784acd714758b43da9c8f" -dependencies = [ - "secp256k1-sys", -] - -[[package]] -name = "secp256k1-sys" -version = "0.8.1" +name = "semver" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70a129b9e9efbfb223753b9163c4ab3b13cff7fd9c7f010fbac25ab4099fa07e" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" dependencies = [ - "cc", + "semver-parser", ] [[package]] @@ -2313,11 +2436,20 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" +[[package]] +name = "semver-parser" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" +dependencies = [ + "pest", +] + [[package]] name = "serde" -version = "1.0.188" +version = "1.0.192" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" +checksum = "bca2a08484b285dcb282d0f67b26cadc0df8b19f8c12502c13d966bf9482f001" dependencies = [ "serde_derive", ] @@ -2333,20 +2465,20 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.188" +version = "1.0.192" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" +checksum = "d6c7207fbec9faa48073f3e3074cbe553af6ea512d7c21ba46e434e70ea9fbc1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] name = "serde_json" -version = "1.0.107" +version = "1.0.108" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b420ce6e3d8bd882e9b243c6eed35dbc9a6110c9769e74b584e0d68d1f20c65" +checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" dependencies = [ "itoa", "ryu", @@ -2355,9 +2487,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.7" +version = "0.10.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" +checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" dependencies = [ "cfg-if", "cpufeatures", @@ -2386,12 +2518,6 @@ dependencies = [ "keccak", ] -[[package]] -name = "shlex" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380" - [[package]] name = "signature" version = "2.1.0" @@ -2404,9 +2530,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.11.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9" +checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" [[package]] name = "smol_str" @@ -2419,11 +2545,29 @@ dependencies = [ [[package]] name = "snark-verifier" -version = "0.1.6" -source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=community-edition#7011e8ce0c2f7e79ab9629aa528cfb6837cdeafe" +version = "0.1.7" +source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=develop#0c306577e58d4725fc3921d6c827168108373816" +dependencies = [ + "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", + "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", + "hex", + "itertools 0.11.0", + "lazy_static", + "num-bigint", + "num-integer", + "num-traits", + "pairing", + "rand", + "serde", +] + +[[package]] +name = "snark-verifier" +version = "0.1.7" +source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=release-0.1.7-rc#ee667e940a78b50c50a18449010e2f5f6287ebac" dependencies = [ - "halo2-base", - "halo2-ecc", + "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", + "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", "hex", "itertools 0.11.0", "lazy_static", @@ -2432,23 +2576,23 @@ dependencies = [ "num-traits", "pairing", "rand", - "revm", + "ruint", "serde", "sha3 0.10.8", ] [[package]] name = "snark-verifier-sdk" -version = "0.1.6" -source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=community-edition#7011e8ce0c2f7e79ab9629aa528cfb6837cdeafe" +version = "0.1.7" +source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=release-0.1.7-rc#ee667e940a78b50c50a18449010e2f5f6287ebac" dependencies = [ - "ark-std", + "ark-std 0.3.0", "bincode", "ethereum-types", "getset", - "halo2-base", + "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", "hex", - "itertools 0.10.5", + "itertools 0.11.0", "lazy_static", "num-bigint", "num-integer", @@ -2457,14 +2601,14 @@ dependencies = [ "rand_chacha", "serde", "serde_json", - "snark-verifier", + "snark-verifier 0.1.7 (git+https://github.com/axiom-crypto/snark-verifier.git?branch=release-0.1.7-rc)", ] [[package]] name = "socket2" -version = "0.5.4" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4031e820eb552adee9295814c0ced9e5cf38ddf1e8b7d566d6de8e2538ea989e" +checksum = "7b5fac59a5cb5dd637972e5fca70daf0523c9067fcdc4842f053dae04a18f8e9" dependencies = [ "libc", "windows-sys 0.48.0", @@ -2509,16 +2653,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" [[package]] -name = "substrate-bn" -version = "0.6.0" +name = "strum" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b5bbfa79abbae15dd642ea8176a21a635ff3c00059961d1ea27ad04e5b441c" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" dependencies = [ - "byteorder", - "crunchy", - "lazy_static", - "rand", - "rustc-hex", + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.25.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.39", ] [[package]] @@ -2540,9 +2693,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.33" +version = "2.0.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9caece70c63bfba29ec2fed841a09851b14a235c60010fa4de58089b6c025668" +checksum = "23e78b90f2fcf45d3e842032ce32e3f2d1545ba6636271dcbf24fa306d87be7a" dependencies = [ "proc-macro2", "quote", @@ -2567,6 +2720,19 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" +[[package]] +name = "tempfile" +version = "3.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" +dependencies = [ + "cfg-if", + "fastrand", + "redox_syscall", + "rustix", + "windows-sys 0.48.0", +] + [[package]] name = "termcolor" version = "1.3.0" @@ -2595,7 +2761,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] @@ -2607,7 +2773,7 @@ dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", "test-case-core", ] @@ -2619,31 +2785,22 @@ checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d" [[package]] name = "thiserror" -version = "1.0.49" +version = "1.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1177e8c6d7ede7afde3585fd2513e611227efd6481bd78d2e82ba1ce16557ed4" +checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.49" +version = "1.0.50" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10712f02019e9288794769fba95cd6847df9874d49d871d062172f9dd41bc4cc" +checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", -] - -[[package]] -name = "threadpool" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" -dependencies = [ - "num_cpus", + "syn 2.0.39", ] [[package]] @@ -2719,14 +2876,14 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] name = "toml_datetime" -version = "0.6.3" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" [[package]] name = "toml_edit" @@ -2734,18 +2891,28 @@ version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.0.2", + "indexmap 2.1.0", + "toml_datetime", + "winnow", +] + +[[package]] +name = "toml_edit" +version = "0.20.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70f427fce4d84c72b5b732388bf4a9f4531b53f74e2887e3ecb2481f68f66d81" +dependencies = [ + "indexmap 2.1.0", "toml_datetime", "winnow", ] [[package]] name = "tracing" -version = "0.1.37" +version = "0.1.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ - "cfg-if", "pin-project-lite", "tracing-attributes", "tracing-core", @@ -2753,29 +2920,35 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.26" +version = "0.1.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", ] [[package]] name = "tracing-core" -version = "0.1.31" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" dependencies = [ "once_cell", ] [[package]] name = "typenum" -version = "1.16.0" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" + +[[package]] +name = "ucd-trie" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" +checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" [[package]] name = "uint" @@ -2855,9 +3028,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.87" +version = "0.2.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" +checksum = "7daec296f25a1bae309c0cd5c29c4b260e510e6d813c286b19eaadf409d40fce" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -2865,24 +3038,24 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.87" +version = "0.2.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" +checksum = "e397f4664c0e4e428e8313a469aaa58310d302159845980fd23b0f22a847f217" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.87" +version = "0.2.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" +checksum = "5961017b3b08ad5f3fe39f1e79877f8ee7c23c5e5fd5eb80de95abc41f1f16b2" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2890,45 +3063,33 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.87" +version = "0.2.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" +checksum = "c5353b8dab669f5e10f5bd76df26a9360c748f054f862ff5f3f8aae0c7fb3907" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.87" +version = "0.2.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" +checksum = "0d046c5d029ba91a1ed14da14dca44b68bf2f124cfbaf741c54151fdb3e0750b" [[package]] name = "web-sys" -version = "0.3.64" +version = "0.3.65" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" +checksum = "5db499c5f66323272151db0e666cd34f78617522fb0c1604d31a27c50c206a85" dependencies = [ "js-sys", "wasm-bindgen", ] -[[package]] -name = "which" -version = "4.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" -dependencies = [ - "either", - "home", - "once_cell", - "rustix", -] - [[package]] name = "winapi" version = "0.3.9" @@ -3094,9 +3255,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "winnow" -version = "0.5.17" +version = "0.5.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3b801d0e0a6726477cc207f60162da452f3a95adb368399bef20a946e06f65c" +checksum = "829846f3e3db426d4cee4510841b71a8e58aa2a76b1132579487ae430ccd9c7b" dependencies = [ "memchr", ] @@ -3145,5 +3306,24 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.33", + "syn 2.0.39", +] + +[[package]] +name = "zkevm-hashes" +version = "0.2.0" +source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#10960fc9b6613ac93049916680da3a7f40f75d31" +dependencies = [ + "array-init", + "ethers-core", + "getset", + "halo2-base 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", + "itertools 0.11.0", + "lazy_static", + "log", + "num-bigint", + "rand", + "rayon", + "sha3 0.10.8", + "snark-verifier 0.1.7 (git+https://github.com/axiom-crypto/snark-verifier.git?branch=develop)", ] diff --git a/packages/halo2-circuits/Cargo.toml b/packages/halo2-circuits/Cargo.toml index cf3b144..2b913be 100644 --- a/packages/halo2-circuits/Cargo.toml +++ b/packages/halo2-circuits/Cargo.toml @@ -11,24 +11,24 @@ num-bigint = { version = "0.4", features = ["rand"] } sha2 = "0.10.6" rand = "0.8.5" rsa = { version = "0.6.1", features = ["serde"] } -halo2-rsa = { branch = "main", default-features = false, features = [ +halo2-rsa = { default-features = false, features = [ "halo2-axiom", "display", -], git = "https://github.com/MynaWallet/halo2-rsa.git" } -halo2-base = { branch = "community-edition", default-features = false, features = [ +], path = "../../../halo2-rsa" } +halo2-base = { branch = "release-0.4.1-rc", default-features = false, features = [ "halo2-axiom", "display", "test-utils", ], git = "https://github.com/axiom-crypto/halo2-lib.git" } -halo2-ecc = { branch = "community-edition", default-features = false, features = [ +halo2-ecc = { branch = "release-0.4.1-rc", default-features = false, features = [ "halo2-axiom", "display", ], git = "https://github.com/axiom-crypto/halo2-lib.git" } -halo2-sha256-unoptimized = { branch = "main", default-features = false, features = [ +zkevm-hashes = { branch = "sha256", default-features = false, features = [ "halo2-axiom", "display", -], git = "https://github.com/zkpdf/halo2-sha256-unoptimized.git" } -snark-verifier-sdk = { branch = "community-edition", default-features = false, features = [ +], git = "https://github.com/MynaWallet/halo2-lib.git" } +snark-verifier-sdk = { branch = "release-0.1.7-rc", default-features = false, features = [ "halo2-axiom", "display", "loader_evm", diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index c8ea5a2..2c2a634 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -6,7 +6,7 @@ use halo2_base::{ }; use halo2_circuits::{circuit, helpers::*}; use snark_verifier_sdk::{ - evm::{evm_verify, gen_evm_proof_shplonk, gen_evm_verifier_shplonk, write_calldata}, + evm::{gen_evm_proof_shplonk, gen_evm_verifier_shplonk, write_calldata}, gen_pk, halo2::gen_snark_shplonk, read_pk, CircuitExt, @@ -114,68 +114,68 @@ fn main() { issuer_cert_path, password, } => { - let nation_pubkey = read_nation_cert(&issuer_cert_path); - let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(&verify_cert_path); - - let mut builder = BaseCircuitBuilder::new(false); - builder.set_k(k as usize); - builder.set_lookup_bits(circuit::LOOKUP_BITS); - builder.set_instance_columns(1); - let range_chip = builder.range_chip(); - let ctx = builder.main(0); - - let public = circuit::PublicInput { nation_pubkey }; - let private = - circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; - dbg!(tbs_cert.to_bytes_le().len()); - let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); - - builder.assigned_instances[0].extend(outputs); - let circuit_params = builder.calculate_params(None); - builder = builder.use_params(circuit_params); - - if Path::new(&pk_path).exists() { - match remove_file(&pk_path) { - Ok(_) => println!("File found, overwriting..."), - Err(e) => println!("An error occurred: {}", e), - } - } - - env::set_var("PARAMS_DIR", params_path); - let trusted_setup = gen_srs(k); - gen_pk(&trusted_setup, &builder, Some(Path::new(&pk_path))); + // let nation_pubkey = read_nation_cert(&issuer_cert_path); + // let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(&verify_cert_path); + + // let mut builder = BaseCircuitBuilder::new(false); + // builder.set_k(k as usize); + // builder.set_lookup_bits(circuit::LOOKUP_BITS); + // builder.set_instance_columns(1); + // let range_chip = builder.range_chip(); + // let ctx = builder.main(0); + + // let public = circuit::PublicInput { nation_pubkey }; + // let private = + // circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; + // dbg!(tbs_cert.to_bytes_le().len()); + // let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); + + // builder.assigned_instances[0].extend(outputs); + // let circuit_params = builder.calculate_params(None); + // builder = builder.use_params(circuit_params); + + // if Path::new(&pk_path).exists() { + // match remove_file(&pk_path) { + // Ok(_) => println!("File found, overwriting..."), + // Err(e) => println!("An error occurred: {}", e), + // } + // } + + // env::set_var("PARAMS_DIR", params_path); + // let trusted_setup = gen_srs(k); + // gen_pk(&trusted_setup, &builder, Some(Path::new(&pk_path))); } Commands::Prove { k, params_path, pk_path, proof_path, verify_cert_path, issuer_cert_path, password } => { - let nation_pubkey = read_nation_cert(&issuer_cert_path); - let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); - - let mut builder = BaseCircuitBuilder::new(false); - builder.set_k(k as usize); - builder.set_lookup_bits(circuit::LOOKUP_BITS); - builder.set_instance_columns(1); - let range_chip = builder.range_chip(); - let ctx = builder.main(0); - - let public = circuit::PublicInput { nation_pubkey }; - let private = - circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; - let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); - - builder.assigned_instances[0].extend(outputs); - let circuit_params = builder.calculate_params(None); - builder = builder.use_params(circuit_params); - - if Path::new(&proof_path).exists() { - match remove_file(&proof_path) { - Ok(_) => println!("File found, overwriting..."), - Err(e) => println!("An error occurred: {}", e), - } - } - - env::set_var("PARAMS_DIR", params_path); - let trusted_setup = gen_srs(k); - let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); - gen_snark_shplonk(&trusted_setup, &pk, builder, Some(Path::new(&proof_path))); + // let nation_pubkey = read_nation_cert(&issuer_cert_path); + // let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); + + // let mut builder = BaseCircuitBuilder::new(false); + // builder.set_k(k as usize); + // builder.set_lookup_bits(circuit::LOOKUP_BITS); + // builder.set_instance_columns(1); + // let range_chip = builder.range_chip(); + // let ctx = builder.main(0); + + // let public = circuit::PublicInput { nation_pubkey }; + // let private = + // circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; + // let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); + + // builder.assigned_instances[0].extend(outputs); + // let circuit_params = builder.calculate_params(None); + // builder = builder.use_params(circuit_params); + + // if Path::new(&proof_path).exists() { + // match remove_file(&proof_path) { + // Ok(_) => println!("File found, overwriting..."), + // Err(e) => println!("An error occurred: {}", e), + // } + // } + + // env::set_var("PARAMS_DIR", params_path); + // let trusted_setup = gen_srs(k); + // let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); + // gen_snark_shplonk(&trusted_setup, &pk, builder, Some(Path::new(&proof_path))); } Commands::GenerateSolidity { k, @@ -186,47 +186,47 @@ fn main() { issuer_cert_path, password, } => { - let nation_pubkey = read_nation_cert(&issuer_cert_path); - let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); + // let nation_pubkey = read_nation_cert(&issuer_cert_path); + // let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); - let mut builder = BaseCircuitBuilder::new(false); - builder.set_k(k as usize); - builder.set_lookup_bits(circuit::LOOKUP_BITS); - builder.set_instance_columns(1); - let range_chip = builder.range_chip(); - let ctx = builder.main(0); + // let mut builder = BaseCircuitBuilder::new(false); + // builder.set_k(k as usize); + // builder.set_lookup_bits(circuit::LOOKUP_BITS); + // builder.set_instance_columns(1); + // let range_chip = builder.range_chip(); + // let ctx = builder.main(0); - let public = circuit::PublicInput { nation_pubkey }; - let private = - circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; - let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); + // let public = circuit::PublicInput { nation_pubkey }; + // let private = + // circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; + // let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); - builder.assigned_instances[0].extend(outputs); - let circuit_params = builder.calculate_params(None); - builder = builder.use_params(circuit_params); + // builder.assigned_instances[0].extend(outputs); + // let circuit_params = builder.calculate_params(None); + // builder = builder.use_params(circuit_params); - env::set_var("PARAMS_DIR", params_path); - let trusted_setup = gen_srs(k); - let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); + // env::set_var("PARAMS_DIR", params_path); + // let trusted_setup = gen_srs(k); + // let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); - let deployment_code = gen_evm_verifier_shplonk::>( - &trusted_setup, - pk.get_vk(), - builder.num_instance(), - Some(Path::new("./build/VerifyRsa.sol")), - ); + // let deployment_code = gen_evm_verifier_shplonk::>( + // &trusted_setup, + // pk.get_vk(), + // builder.num_instance(), + // Some(Path::new("./build/VerifyRsa.sol")), + // ); - let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, builder.clone(), builder.instances()); + // let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, builder.clone(), builder.instances()); - println!("Size of the contract: {} bytes", deployment_code.len()); - println!("Deploying contract..."); + // println!("Size of the contract: {} bytes", deployment_code.len()); + // println!("Deploying contract..."); - evm_verify(deployment_code, builder.instances(), proof.clone()); + // evm_verify(deployment_code, builder.instances(), proof.clone()); - println!("Verification success!"); + // println!("Verification success!"); - write_calldata(&builder.instances(), &proof, Path::new("./build/calldata.txt")).unwrap(); - println!("Succesfully generate calldata!"); + // write_calldata(&builder.instances(), &proof, Path::new("./build/calldata.txt")).unwrap(); + // println!("Succesfully generate calldata!"); } } } diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index d300dde..e668956 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -6,7 +6,6 @@ use halo2_base::{ halo2_proofs::{ arithmetic::Field, circuit::{Layouter, SimpleFloorPlanner}, - dev::MockProver, halo2curves::bn256::Fr, plonk::{Circuit, ConstraintSystem, Error}, }, @@ -21,7 +20,6 @@ use halo2_rsa::{ use num_bigint::BigUint; use sha2::{Digest, Sha256}; // use zkevm_hashes::Sha256Chip; -use halo2_sha256_unoptimized::Sha256Chip; #[derive(Debug, Clone)] pub struct PublicInput { @@ -31,7 +29,7 @@ pub struct PublicInput { #[derive(Debug, Clone)] pub struct PrivateInput { - pub tbs_cert: Vec, + pub tbs_cert: [u32; MAX_TBS_CERT_BITS / 32], // 2048 bits pub nation_sig: BigUint, pub password: Fr, @@ -120,10 +118,6 @@ impl Circuit for ProofOfJapaneseResidence { } } -impl ProofOfJapaneseResidence { - fn assign_halo2base() {} -} - pub fn proof_of_japanese_residence( ctx: &mut Context, range_chip: RangeChip, @@ -132,8 +126,8 @@ pub fn proof_of_japanese_residence( ) -> Vec> { let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); let rsa_chip = RSAConfig::construct(biguint_chip, RSA_KEY_SIZE, 5); - let mut sha256_chip = - Sha256Chip::construct(vec![SHA256_INPUT_BLOCKS * SHA256_BLOCK_BITS / 8], range_chip.clone(), true); + // let mut sha256_chip = + // Sha256Chip::construct(vec![SHA256_INPUT_BLOCKS * SHA256_BLOCK_BITS / 8], range_chip.clone(), true); let mut poseidon = PoseidonHasher::new(OptimizedPoseidonSpec::::new::<8, 57, 0>()); poseidon.initialize_consts(ctx, rsa_chip.gate()); @@ -153,13 +147,13 @@ pub fn proof_of_japanese_residence( // ); // let citizen_pubkey = AssignedRSAPublicKey::new(n.clone(), AssignedRSAPubE::Fix(E.into())); - let sha256ed = sha256_chip.digest(ctx, &private.tbs_cert, None).unwrap(); - let identity_commitment_preimage: Vec> = sha256ed.input_bytes - [PUBKEY_BEGINS / 8..(PUBKEY_BEGINS + RSA_KEY_SIZE) / 8] - .iter() - .copied() - .chain(std::iter::once(password)) - .collect(); + // let sha256ed = sha256_chip.digest(ctx, &private.tbs_cert, None).unwrap(); + // let identity_commitment_preimage: Vec> = sha256ed.input_bytes + // [PUBKEY_BEGINS / 8..(PUBKEY_BEGINS + RSA_KEY_SIZE) / 8] + // .iter() + // .copied() + // .chain(std::iter::once(password)) + // .collect(); // println!("sha256ed"); // for byte in &sha256ed.input_bytes[PUBKEY_BEGINS / 8..(PUBKEY_BEGINS + RSA_KEY_SIZE) / 8] { @@ -167,10 +161,10 @@ pub fn proof_of_japanese_residence( // print!("{:0b}", byte); // } - let identity_commitment = poseidon.hash_fix_len_array(ctx, rsa_chip.gate(), &identity_commitment_preimage); + // let identity_commitment = poseidon.hash_fix_len_array(ctx, rsa_chip.gate(), &identity_commitment_preimage); - let sha256ed_64s = - bytes_to_64s(ctx, range_chip.clone(), &sha256ed.output_bytes.iter().rev().copied().collect::>()); + // let sha256ed_64s = + // bytes_to_64s(ctx, range_chip.clone(), &sha256ed.output_bytes.iter().rev().copied().collect::>()); // assert_eq!( // sha256ed_64s.iter().flat_map(|a| a.value().to_bytes()[0..8].to_vec()).collect::>(), @@ -185,34 +179,34 @@ pub fn proof_of_japanese_residence( // } // println!("aa"); - let hashed_tbs = Sha256::digest(private.tbs_cert); - println!("Hashed TBS: {:?}", hashed_tbs); - let mut hashed_bytes: Vec> = - hashed_tbs.iter().map(|limb| ctx.load_witness(Fr::from(*limb as u64))).collect(); - hashed_bytes.reverse(); - let bytes_bits = hashed_bytes.len() * 8; - let limb_bits = 64; - let limb_bytes = limb_bits / 8; - let mut hashed_u64s = vec![]; - let bases: Vec<_> = (0..limb_bytes).map(|i| Fr::from(1u64 << (8 * i))).map(QuantumCell::Constant).collect(); - for i in 0..(bytes_bits / limb_bits) { - let left: Vec<_> = - hashed_bytes[limb_bytes * i..limb_bytes * (i + 1)].iter().map(|x| QuantumCell::Existing(*x)).collect(); - let sum = rsa_chip.gate().inner_product(ctx, left, bases.clone()); - hashed_u64s.push(sum); - } + // let hashed_tbs = Sha256::digest(private.tbs_cert); + // println!("Hashed TBS: {:?}", hashed_tbs); + // let mut hashed_bytes: Vec> = + // hashed_tbs.iter().map(|limb| ctx.load_witness(Fr::from(*limb as u64))).collect(); + // hashed_bytes.reverse(); + // let bytes_bits = hashed_bytes.len() * 8; + // let limb_bits = 64; + // let limb_bytes = limb_bits / 8; + // let mut hashed_u64s = vec![]; + // let bases: Vec<_> = (0..limb_bytes).map(|i| Fr::from(1u64 << (8 * i))).map(QuantumCell::Constant).collect(); + // for i in 0..(bytes_bits / limb_bits) { + // let left: Vec<_> = + // hashed_bytes[limb_bytes * i..limb_bytes * (i + 1)].iter().map(|x| QuantumCell::Existing(*x)).collect(); + // let sum = rsa_chip.gate().inner_product(ctx, left, bases.clone()); + // hashed_u64s.push(sum); + // } - assert_eq!( - sha256ed_64s.iter().map(|a| a.value()).collect::>(), - hashed_u64s.iter().map(|a| a.value()).collect::>() - ); + // assert_eq!( + // sha256ed_64s.iter().map(|a| a.value()).collect::>(), + // hashed_u64s.iter().map(|a| a.value()).collect::>() + // ); - let is_nation_sig_valid = - rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); - rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); + // let is_nation_sig_valid = + // rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); + // rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); let mut outputs = nation_pubkey.n.limbs().to_vec(); - outputs.push(identity_commitment); + // outputs.push(identity_commitment); outputs } @@ -220,7 +214,10 @@ pub fn proof_of_japanese_residence( mod tests { use super::*; use crate::helpers::{read_citizen_cert, read_nation_cert}; - use halo2_base::{halo2_proofs::halo2curves::ff::PrimeField, utils::testing::base_test}; + use halo2_base::{ + halo2_proofs::{dev::MockProver, halo2curves::ff::PrimeField}, + utils::testing::base_test, + }; use num_traits::cast::ToPrimitive; // TODO: Write tests for failure cases @@ -265,13 +262,17 @@ mod tests { let nation_pubkey = read_nation_cert("./certs/ca_cert.pem"); let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert("./certs/myna_cert.pem"); + + let mut tbs_cert_32 = [0u32; MAX_TBS_CERT_BITS / 32]; + tbs_cert_32[0..tbs_cert.to_u32_digits().len()].copy_from_slice(&tbs_cert.to_u32_digits()); + let public_input = PublicInput { nation_pubkey: nation_pubkey.clone() }; let private_input = - PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig: nation_sig.clone(), password: Fr::from(123) }; - let public_outputs = + PrivateInput { tbs_cert: tbs_cert_32, nation_sig: nation_sig.clone(), password: Fr::from(0xA42) }; + let public_output = proof_of_japanese_residence(builder.pool(0).main(), range_chip, public_input, private_input); - builder.assigned_instances[0].extend(public_outputs); + builder.assigned_instances[0].extend(public_output); // AUDIT: Is K enough to achieve zero knowledge? builder.calculate_params(Some(9)); diff --git a/packages/halo2-circuits/src/helpers.rs b/packages/halo2-circuits/src/helpers.rs index a29470e..ccac964 100644 --- a/packages/halo2-circuits/src/helpers.rs +++ b/packages/halo2-circuits/src/helpers.rs @@ -6,7 +6,6 @@ use halo2_base::{ QuantumCell::{Constant, Existing}, }; use halo2_rsa::{BigUintConfig, BigUintInstructions, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, RSASignature}; -use halo2_sha256_unoptimized::Sha256Chip; use snark_verifier_sdk::{gen_pk, halo2::gen_snark_shplonk, Snark}; use itertools::Itertools; @@ -66,65 +65,3 @@ pub fn read_citizen_cert(cert_path: &str) -> (BigUint, BigUint, BigUint) { (nation_sig_biguint, tbs_biguint, citizen_pubkey_biguint) } - -pub fn create_default_rsa_circuit_with_instances( - k: usize, - tbs: Vec, - public_key_modulus: BigUint, - signature_bigint: BigUint, -) -> BaseCircuitBuilder { - // Circuit inputs - let limb_bits = 64; - let default_bits = 2048; - let exp_bits = 5; // UNUSED - let default_e = 65537_u32; - - let mut builder = BaseCircuitBuilder::new(false); - // Set rows - builder.set_k(k); - builder.set_lookup_bits(k - 1); - builder.set_instance_columns(1); - - let range = builder.range_chip(); - let ctx = builder.main(0); - - let bigint_chip = BigUintConfig::construct(range.clone(), limb_bits); - let rsa_chip = RSAConfig::construct(bigint_chip.clone(), default_bits, exp_bits); - - // Hash in pure Rust vs in-circuit - let hashed_tbs = Sha256::digest(tbs); - println!("Hashed TBS: {:?}", hashed_tbs); - let mut hashed_bytes: Vec> = - hashed_tbs.iter().map(|limb| ctx.load_witness(Fr::from(*limb as u64))).collect_vec(); - hashed_bytes.reverse(); - let bytes_bits = hashed_bytes.len() * 8; - let limb_bits = bigint_chip.limb_bits(); - let limb_bytes = limb_bits / 8; - let mut hashed_u64s = vec![]; - let bases = (0..limb_bytes).map(|i| Fr::from(1u64 << (8 * i))).map(Constant).collect_vec(); - for i in 0..(bytes_bits / limb_bits) { - let left = hashed_bytes[limb_bytes * i..limb_bytes * (i + 1)].iter().map(|x| Existing(*x)).collect_vec(); - let sum = bigint_chip.gate().inner_product(ctx, left, bases.clone()); - hashed_u64s.push(sum); - } - - // Generate values to be fed into the circuit (Pure Rust) - // Verify Cert - let e_fix = RSAPubE::Fix(BigUint::from(default_e)); - let public_key = RSAPublicKey::new(public_key_modulus.clone(), e_fix); // cloning might be slow - let public_key = rsa_chip.assign_public_key(ctx, public_key).unwrap(); - - let signature = RSASignature::new(signature_bigint.clone()); // cloning might be slow - let signature = rsa_chip.assign_signature(ctx, signature).unwrap(); - - let is_valid = rsa_chip.verify_pkcs1v15_signature(ctx, &public_key, &hashed_u64s, &signature).unwrap(); - rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_valid, &Fr::one()); - - // Insert input hash as public instance for circuit - hashed_bytes.reverse(); - builder.assigned_instances[0].extend(hashed_bytes); - - let circuit_params = builder.calculate_params(None); - println!("Circuit params: {:?}", circuit_params); - builder.use_params(circuit_params) -} From 1a0b75760a0fdc79178da2ca3c0a8152a3a284ea Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Fri, 17 Nov 2023 11:52:41 +0900 Subject: [PATCH 12/28] Take a SHA256 hash on halo2 -> Sign it with RSA on halo2-base --- packages/halo2-circuits/Cargo.lock | 421 +++---------------------- packages/halo2-circuits/Cargo.toml | 20 +- packages/halo2-circuits/src/bin/cli.rs | 12 +- packages/halo2-circuits/src/circuit.rs | 134 ++++++-- packages/halo2-circuits/src/helpers.rs | 2 +- 5 files changed, 167 insertions(+), 422 deletions(-) diff --git a/packages/halo2-circuits/Cargo.lock b/packages/halo2-circuits/Cargo.lock index 8998c3b..a7e8b8a 100644 --- a/packages/halo2-circuits/Cargo.lock +++ b/packages/halo2-circuits/Cargo.lock @@ -26,17 +26,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "alloy-rlp" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc0fac0fc16baf1f63f78b47c3d24718f3619b0714076f6a02957d808d52cbef" -dependencies = [ - "arrayvec", - "bytes", - "smol_str", -] - [[package]] name = "anes" version = "0.1.6" @@ -83,110 +72,6 @@ dependencies = [ "windows-sys 0.45.0", ] -[[package]] -name = "ark-ff" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b3235cc41ee7a12aaaf2c575a2ad7b46713a8a50bda2fc3b003a04845c05dd6" -dependencies = [ - "ark-ff-asm 0.3.0", - "ark-ff-macros 0.3.0", - "ark-serialize 0.3.0", - "ark-std 0.3.0", - "derivative", - "num-bigint", - "num-traits", - "paste", - "rustc_version 0.3.3", - "zeroize", -] - -[[package]] -name = "ark-ff" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec847af850f44ad29048935519032c33da8aa03340876d351dfab5660d2966ba" -dependencies = [ - "ark-ff-asm 0.4.2", - "ark-ff-macros 0.4.2", - "ark-serialize 0.4.2", - "ark-std 0.4.0", - "derivative", - "digest 0.10.7", - "itertools 0.10.5", - "num-bigint", - "num-traits", - "paste", - "rustc_version 0.4.0", - "zeroize", -] - -[[package]] -name = "ark-ff-asm" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db02d390bf6643fb404d3d22d31aee1c4bc4459600aef9113833d17e786c6e44" -dependencies = [ - "quote", - "syn 1.0.109", -] - -[[package]] -name = "ark-ff-asm" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed4aa4fe255d0bc6d79373f7e31d2ea147bcf486cba1be5ba7ea85abdb92348" -dependencies = [ - "quote", - "syn 1.0.109", -] - -[[package]] -name = "ark-ff-macros" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" -dependencies = [ - "num-bigint", - "num-traits", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "ark-ff-macros" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" -dependencies = [ - "num-bigint", - "num-traits", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "ark-serialize" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6c2b318ee6e10f8c2853e73a83adc0ccb88995aa978d8a3408d492ab2ee671" -dependencies = [ - "ark-std 0.3.0", - "digest 0.9.0", -] - -[[package]] -name = "ark-serialize" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" -dependencies = [ - "ark-std 0.4.0", - "digest 0.10.7", - "num-bigint", -] - [[package]] name = "ark-std" version = "0.3.0" @@ -198,16 +83,6 @@ dependencies = [ "rand", ] -[[package]] -name = "ark-std" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" -dependencies = [ - "num-traits", - "rand", -] - [[package]] name = "array-init" version = "2.1.0" @@ -321,15 +196,6 @@ version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" -[[package]] -name = "bincode" -version = "1.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" -dependencies = [ - "serde", -] - [[package]] name = "bitflags" version = "1.3.2" @@ -743,9 +609,9 @@ dependencies = [ [[package]] name = "crypto-bigint" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "740fe28e594155f10cfc383984cbefd529d7396050557148f79cb0f621204124" +checksum = "28f85c3514d2a6e64160359b45a3918c3b4178bcbf4ae5d03ab2d02e521c479a" dependencies = [ "generic-array", "rand_core", @@ -813,17 +679,6 @@ dependencies = [ "powerfmt", ] -[[package]] -name = "derivative" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "derive_more" version = "0.99.17" @@ -894,7 +749,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d97ca172ae9dc9f9b779a6e3a65d308f2af74e5b8c921299075bdb4a0370e914" dependencies = [ "base16ct", - "crypto-bigint 0.5.3", + "crypto-bigint 0.5.4", "digest 0.10.7", "ff", "generic-array", @@ -908,9 +763,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.10.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" +checksum = "95b3f3e67048839cb0d0781f445682a35113da7121f7c949db0e2be96a4fbece" dependencies = [ "humantime", "is-terminal", @@ -1016,17 +871,6 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" -[[package]] -name = "fastrlp" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139834ddba373bbdd213dffe02c8d110508dcf1726c2be27e8d1f7d7e1856418" -dependencies = [ - "arrayvec", - "auto_impl", - "bytes", -] - [[package]] name = "ff" version = "0.13.0" @@ -1136,36 +980,13 @@ version = "0.4.0" source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop#ee12efa86fdd89ae7b37c8f11005888180a1d316" dependencies = [ "getset", - "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", - "itertools 0.11.0", - "log", - "num-bigint", - "num-integer", - "num-traits", - "poseidon-rs", - "rand_chacha", - "rayon", - "rustc-hash", - "serde", - "serde_json", -] - -[[package]] -name = "halo2-base" -version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc#a30e3b18d285c8b0d7145c1c34297edd9433df60" -dependencies = [ - "ark-std 0.3.0", - "getset", - "halo2_proofs 0.2.0 (git+https://github.com/privacy-scaling-explorations/halo2.git?rev=7a21656)", - "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", + "halo2_proofs 0.3.1", "itertools 0.11.0", "log", "num-bigint", "num-integer", "num-traits", "poseidon-rs", - "rand", "rand_chacha", "rayon", "rustc-hash", @@ -1176,11 +997,12 @@ dependencies = [ [[package]] name = "halo2-base" version = "0.4.0" -source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#10960fc9b6613ac93049916680da3a7f40f75d31" +source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#2963e2a3b7ad704505ba6a7c5a8b6b938c7efde8" dependencies = [ - "ark-std 0.3.0", + "ark-std", "getset", - "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", + "halo2_proofs 0.2.0", + "halo2_proofs 0.3.1", "itertools 0.11.0", "log", "num-bigint", @@ -1205,8 +1027,8 @@ dependencies = [ "env_logger", "getrandom", "getset", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", + "halo2-base 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", + "halo2-ecc 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", "halo2-rsa", "itertools 0.11.0", "num-bigint", @@ -1218,7 +1040,6 @@ dependencies = [ "serde", "serde_json", "sha2", - "snark-verifier-sdk", "tokio", "x509-parser", "zkevm-hashes", @@ -1246,9 +1067,9 @@ dependencies = [ [[package]] name = "halo2-ecc" version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc#a30e3b18d285c8b0d7145c1c34297edd9433df60" +source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#2963e2a3b7ad704505ba6a7c5a8b6b938c7efde8" dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", + "halo2-base 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", "itertools 0.10.5", "num-bigint", "num-integer", @@ -1267,8 +1088,8 @@ name = "halo2-rsa" version = "0.1.0" dependencies = [ "env_logger", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", + "halo2-base 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", + "halo2-ecc 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", "num-bigint", "num-traits", "rand", @@ -1294,14 +1115,14 @@ dependencies = [ [[package]] name = "halo2_proofs" -version = "0.2.0" -source = "git+https://github.com/axiom-crypto/halo2.git#2e98a5ce91791c5fc77541e8afb6abc29a9b1dac" +version = "0.3.1" +source = "git+https://github.com/axiom-crypto/halo2.git#58f50f7fa9dfaf0b4864bc431c17a96fef7b177e" dependencies = [ "blake2b_simd", "crossbeam", "ff", "group", - "halo2curves 0.4.0", + "halo2curves 0.4.1", "maybe-rayon", "pairing", "rand", @@ -1333,8 +1154,8 @@ dependencies = [ [[package]] name = "halo2curves" -version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2curves.git?branch=main#e185711b6ba8f3e22f2af8bf24a5fc84b781ca46" +version = "0.4.1" +source = "git+https://github.com/axiom-crypto/halo2curves.git?branch=main#f11edd061714dea13aeaccda58cc4b271700b367" dependencies = [ "blake2b_simd", "ff", @@ -1892,17 +1713,6 @@ dependencies = [ "base64ct", ] -[[package]] -name = "pest" -version = "2.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae9cee2a55a544be8b89dc6848072af97a20f2422603c10865be2a42b580fff5" -dependencies = [ - "memchr", - "thiserror", - "ucd-trie", -] - [[package]] name = "pin-project-lite" version = "0.2.13" @@ -2069,9 +1879,9 @@ dependencies = [ [[package]] name = "proptest" -version = "1.3.1" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c003ac8c77cb07bb74f5f198bce836a689bcd5a42574612bf14d17bfd08c20e" +checksum = "31b476131c3c86cb68032fdc5cb6d5a1045e3e42d96b69fa599fd77701e1f5bf" dependencies = [ "bitflags 2.4.1", "lazy_static", @@ -2079,7 +1889,7 @@ dependencies = [ "rand", "rand_chacha", "rand_xorshift", - "regex-syntax 0.7.5", + "regex-syntax", "unarray", ] @@ -2175,7 +1985,7 @@ dependencies = [ "aho-corasick", "memchr", "regex-automata", - "regex-syntax 0.8.2", + "regex-syntax", ] [[package]] @@ -2186,15 +1996,9 @@ checksum = "5f804c7828047e88b2d32e2d7fe5a105da8ee3264f01902f796c8e067dc2483f" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.8.2", + "regex-syntax", ] -[[package]] -name = "regex-syntax" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" - [[package]] name = "regex-syntax" version = "0.8.2" @@ -2269,35 +2073,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "ruint" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95294d6e3a6192f3aabf91c38f56505a625aa495533442744185a36d75a790c4" -dependencies = [ - "alloy-rlp", - "ark-ff 0.3.0", - "ark-ff 0.4.2", - "bytes", - "fastrlp", - "num-bigint", - "parity-scale-codec", - "primitive-types", - "proptest", - "rand", - "rlp", - "ruint-macro", - "serde", - "valuable", - "zeroize", -] - -[[package]] -name = "ruint-macro" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e666a5496a0b2186dbcd0ff6106e29e093c15591bde62c20d3842007c6978a09" - [[package]] name = "rustc-demangle" version = "0.1.23" @@ -2316,24 +2091,6 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" -[[package]] -name = "rustc_version" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" -dependencies = [ - "semver 0.11.0", -] - -[[package]] -name = "rustc_version" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" -dependencies = [ - "semver 1.0.20", -] - [[package]] name = "rusticata-macros" version = "4.1.0" @@ -2345,9 +2102,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.21" +version = "0.38.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b426b0506e5d50a7d8dafcf2e81471400deb602392c7dd110815afb4eaf02a3" +checksum = "9ad981d6c340a49cdc40a1028d9c6084ec7e9fa33fcb839cab656a267071e234" dependencies = [ "bitflags 2.4.1", "errno", @@ -2421,30 +2178,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "semver" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" -dependencies = [ - "semver-parser", -] - -[[package]] -name = "semver" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" - -[[package]] -name = "semver-parser" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" -dependencies = [ - "pest", -] - [[package]] name = "serde" version = "1.0.192" @@ -2530,18 +2263,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" - -[[package]] -name = "smol_str" -version = "0.2.0" +version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74212e6bbe9a4352329b2f68ba3130c15a3f26fe88ff22dbdc6cdd58fa85e99c" -dependencies = [ - "serde", -] +checksum = "4dccd0940a2dcdf68d092b8cbab7dc0ad8fa938bf95787e1b916b0e3d0e8e970" [[package]] name = "snark-verifier" @@ -2561,49 +2285,6 @@ dependencies = [ "serde", ] -[[package]] -name = "snark-verifier" -version = "0.1.7" -source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=release-0.1.7-rc#ee667e940a78b50c50a18449010e2f5f6287ebac" -dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", - "hex", - "itertools 0.11.0", - "lazy_static", - "num-bigint", - "num-integer", - "num-traits", - "pairing", - "rand", - "ruint", - "serde", - "sha3 0.10.8", -] - -[[package]] -name = "snark-verifier-sdk" -version = "0.1.7" -source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=release-0.1.7-rc#ee667e940a78b50c50a18449010e2f5f6287ebac" -dependencies = [ - "ark-std 0.3.0", - "bincode", - "ethereum-types", - "getset", - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=release-0.4.1-rc)", - "hex", - "itertools 0.11.0", - "lazy_static", - "num-bigint", - "num-integer", - "num-traits", - "rand", - "rand_chacha", - "serde", - "serde_json", - "snark-verifier 0.1.7 (git+https://github.com/axiom-crypto/snark-verifier.git?branch=release-0.1.7-rc)", -] - [[package]] name = "socket2" version = "0.5.5" @@ -2735,9 +2416,9 @@ dependencies = [ [[package]] name = "termcolor" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6093bad37da69aab9d123a8091e4be0aa4a03e4d601ec641c327398315f62b64" +checksum = "ff1bc3d3f05aff0403e8ac0d92ced918ec05b666a43f83297ccef5bea8a3d449" dependencies = [ "winapi-util", ] @@ -2853,9 +2534,9 @@ dependencies = [ [[package]] name = "tokio" -version = "1.33.0" +version = "1.34.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f38200e3ef7995e5ef13baec2f432a6da0aa9ac495b2c0e8f3b7eec2c92d653" +checksum = "d0c014766411e834f7af5b8f4cf46257aab4036ca95e9d2c144a10f59ad6f5b9" dependencies = [ "backtrace", "bytes", @@ -2870,9 +2551,9 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" +checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", @@ -2944,12 +2625,6 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" -[[package]] -name = "ucd-trie" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" - [[package]] name = "uint" version = "0.9.5" @@ -2992,12 +2667,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" -[[package]] -name = "valuable" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" - [[package]] name = "vcpkg" version = "0.2.15" @@ -3294,25 +2963,11 @@ name = "zeroize" version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.39", -] [[package]] name = "zkevm-hashes" version = "0.2.0" -source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#10960fc9b6613ac93049916680da3a7f40f75d31" +source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#2963e2a3b7ad704505ba6a7c5a8b6b938c7efde8" dependencies = [ "array-init", "ethers-core", @@ -3325,5 +2980,5 @@ dependencies = [ "rand", "rayon", "sha3 0.10.8", - "snark-verifier 0.1.7 (git+https://github.com/axiom-crypto/snark-verifier.git?branch=develop)", + "snark-verifier", ] diff --git a/packages/halo2-circuits/Cargo.toml b/packages/halo2-circuits/Cargo.toml index 2b913be..eadf46c 100644 --- a/packages/halo2-circuits/Cargo.toml +++ b/packages/halo2-circuits/Cargo.toml @@ -15,25 +15,25 @@ halo2-rsa = { default-features = false, features = [ "halo2-axiom", "display", ], path = "../../../halo2-rsa" } -halo2-base = { branch = "release-0.4.1-rc", default-features = false, features = [ +halo2-base = { branch = "sha256", default-features = false, features = [ "halo2-axiom", "display", "test-utils", -], git = "https://github.com/axiom-crypto/halo2-lib.git" } -halo2-ecc = { branch = "release-0.4.1-rc", default-features = false, features = [ +], git = "https://github.com/MynaWallet/halo2-lib.git" } +halo2-ecc = { branch = "sha256", default-features = false, features = [ "halo2-axiom", "display", -], git = "https://github.com/axiom-crypto/halo2-lib.git" } +], git = "https://github.com/MynaWallet/halo2-lib.git" } zkevm-hashes = { branch = "sha256", default-features = false, features = [ "halo2-axiom", "display", ], git = "https://github.com/MynaWallet/halo2-lib.git" } -snark-verifier-sdk = { branch = "release-0.1.7-rc", default-features = false, features = [ - "halo2-axiom", - "display", - "loader_evm", - "loader_halo2", -], git = "https://github.com/axiom-crypto/snark-verifier.git" } +# snark-verifier-sdk = { branch = "release-0.1.7-rc", default-features = false, features = [ +# "halo2-axiom", +# "display", +# "loader_evm", +# "loader_halo2", +# ], git = "https://github.com/axiom-crypto/snark-verifier.git" } x509-parser = { version = "0.15", features = ["verify"] } openssl = "0.10" num-traits = "0.2.15" diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 2c2a634..7c005c8 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -5,12 +5,12 @@ use halo2_base::{ utils::{fs::gen_srs, BigPrimeField}, }; use halo2_circuits::{circuit, helpers::*}; -use snark_verifier_sdk::{ - evm::{gen_evm_proof_shplonk, gen_evm_verifier_shplonk, write_calldata}, - gen_pk, - halo2::gen_snark_shplonk, - read_pk, CircuitExt, -}; +// use snark_verifier_sdk::{ +// evm::{gen_evm_proof_shplonk, gen_evm_verifier_shplonk, write_calldata}, +// gen_pk, +// halo2::gen_snark_shplonk, +// read_pk, CircuitExt, +// }; use std::{env, fs::remove_file, path::Path}; #[derive(Parser, Debug, Clone)] diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index e668956..88a0a09 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -7,7 +7,7 @@ use halo2_base::{ arithmetic::Field, circuit::{Layouter, SimpleFloorPlanner}, halo2curves::bn256::Fr, - plonk::{Circuit, ConstraintSystem, Error}, + plonk::{Assignment, Circuit, ConstraintSystem, Error}, }, poseidon::hasher::{spec::OptimizedPoseidonSpec, PoseidonHasher}, AssignedValue, Context, QuantumCell, @@ -18,18 +18,21 @@ use halo2_rsa::{ RSASignature, }; use num_bigint::BigUint; -use sha2::{Digest, Sha256}; +use num_traits::One; +use sha2::Digest; +use zkevm_hashes::sha256::vanilla::columns::Sha256CircuitConfig; // use zkevm_hashes::Sha256Chip; #[derive(Debug, Clone)] pub struct PublicInput { // 2048 bits pub nation_pubkey: BigUint, + // little endian + pub sha256: [Fr; 2], } #[derive(Debug, Clone)] pub struct PrivateInput { - pub tbs_cert: [u32; MAX_TBS_CERT_BITS / 32], // 2048 bits pub nation_sig: BigUint, pub password: Fr, @@ -43,8 +46,7 @@ const E: usize = 65537; const K: usize = 22; const LIMB_BITS: usize = 64; const SHA256_BLOCK_BITS: usize = 512; -const MAX_TBS_CERT_BITS: usize = 1 << 15; -const SHA256_INPUT_BLOCKS: usize = MAX_TBS_CERT_BITS / SHA256_BLOCK_BITS; // the remainder must be 0 +const TBS_CERT_MAX_BITS: usize = 1 << 12; pub fn bytes_to_biguint( ctx: &mut Context, @@ -78,14 +80,60 @@ pub fn bytes_to_64s( bytes_to_biguint(ctx, biguint_chip, src).limbs().to_vec() } +pub fn biguint_to_fr(src: BigUint) -> Fr { + let mut buf = [0; 32]; + buf[0..src.to_bytes_le().len()].copy_from_slice(&src.to_bytes_le()); + Fr::from_bytes(&buf).expect("a BigUint was too big to fit in a Fr") +} + +pub fn split_each_limb( + ctx: &mut Context, + range_chip: &RangeChip, + big_limbs: &[AssignedValue], + big_limb_bits: usize, + small_limb_bits: usize, +) -> Vec> { + assert_eq!(0, big_limb_bits % small_limb_bits); + assert!(small_limb_bits < big_limb_bits); + + let limb_bases = (0..).map(|x| QuantumCell::Constant(biguint_to_fr(BigUint::one() << (x * small_limb_bits)))); + let mut small_limbs: Vec> = Vec::new(); + for big_limb in big_limbs { + let mut offset = 0; + while offset < big_limb_bits { + let small_limb = + (BigUint::from_bytes_le(&big_limb.value().to_bytes()) >> offset) % (BigUint::one() << small_limb_bits); + let small_limb = ctx.load_witness(biguint_to_fr(small_limb)); + range_chip.range_check(ctx, small_limb, small_limb_bits); + small_limbs.push(small_limb); + offset += small_limb_bits; + } + + let small_to_big = range_chip.gate().inner_product( + ctx, + small_limbs + .iter() + .skip(small_limbs.len() - big_limb_bits / small_limb_bits) + .copied() + .map(QuantumCell::Existing), + limb_bases.clone(), + ); + ctx.constrain_equal(big_limb, &small_to_big); + } + + small_limbs +} + #[derive(Debug, Clone)] struct Config { halo2base: BaseConfig, + sha256: Sha256CircuitConfig, } -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] struct ProofOfJapaneseResidence { halo2base: BaseCircuitBuilder, + tbs_cert: Vec, } impl Circuit for ProofOfJapaneseResidence { @@ -94,7 +142,7 @@ impl Circuit for ProofOfJapaneseResidence { type FloorPlanner = SimpleFloorPlanner; fn without_witnesses(&self) -> Self { - Self::default() + unreachable!() } fn params(&self) -> Self::Params { @@ -102,7 +150,7 @@ impl Circuit for ProofOfJapaneseResidence { } fn configure_with_params(meta: &mut ConstraintSystem, params: BaseCircuitParams) -> Self::Config { - Self::Config { halo2base: BaseConfig::configure(meta, params) } + Self::Config { halo2base: BaseConfig::configure(meta, params), sha256: Sha256CircuitConfig::new(meta) } } fn configure(_: &mut ConstraintSystem) -> Self::Config { @@ -110,9 +158,41 @@ impl Circuit for ProofOfJapaneseResidence { } fn synthesize(&self, config: Self::Config, mut layouter: impl Layouter) -> Result<(), Error> { - self.halo2base.synthesize(config.halo2base, layouter)?; - - // TODO: SHA256 + let mut assigned_blocks = Vec::new(); + layouter.assign_region( + || "SHA256", + |mut region| { + assigned_blocks = config.sha256.multi_sha256( + &mut region, + vec![self.tbs_cert.clone()], + None, + // TODO: We should specify here the number of SHA256 blocks thats necessary to fit the input in + // but when I do so zkevm-hashes panics. Why?? Some(TBS_CERT_MAX_BITS / SHA256_BLOCK_BITS) + ); + Ok(()) + }, + )?; + + let mut final_block = None; + for block in assigned_blocks.iter() { + block.is_final().value().map(|is_final| { + if Fr::zero() < is_final.evaluate() { + final_block = Some(block); + } + }); + + if let Some(_) = final_block { + break; + } + } + let final_block = final_block.expect("unreachable"); + dbg!(final_block.output()); + + // TODO: Hide these + layouter.constrain_instance(final_block.output().lo().cell(), config.halo2base.instance[0], 0); + layouter.constrain_instance(final_block.output().hi().cell(), config.halo2base.instance[0], 1); + + self.halo2base.synthesize(config.halo2base, layouter).unwrap(); Ok(()) } @@ -131,6 +211,9 @@ pub fn proof_of_japanese_residence( let mut poseidon = PoseidonHasher::new(OptimizedPoseidonSpec::::new::<8, 57, 0>()); poseidon.initialize_consts(ctx, rsa_chip.gate()); + let sha256lo = ctx.load_witness(public.sha256[0]); + let sha256hi = ctx.load_witness(public.sha256[1]); + // load public inputs let nation_pubkey = rsa_chip.assign_public_key(ctx, RSAPublicKey::new(public.nation_pubkey, RSAPubE::Fix(E.into()))).unwrap(); @@ -201,12 +284,14 @@ pub fn proof_of_japanese_residence( // hashed_u64s.iter().map(|a| a.value()).collect::>() // ); - // let is_nation_sig_valid = - // rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); - // rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); + let sha256ed_64s = split_each_limb(ctx, rsa_chip.range(), &[sha256lo, sha256hi], 128, 64); + let is_nation_sig_valid = + rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); + rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); - let mut outputs = nation_pubkey.n.limbs().to_vec(); + let mut outputs = vec![sha256lo, sha256hi]; // outputs.push(identity_commitment); + outputs.extend(nation_pubkey.n.limbs().to_vec()); outputs } @@ -219,6 +304,7 @@ mod tests { utils::testing::base_test, }; use num_traits::cast::ToPrimitive; + use sha2::Sha256; // TODO: Write tests for failure cases // #[test] @@ -263,21 +349,25 @@ mod tests { let nation_pubkey = read_nation_cert("./certs/ca_cert.pem"); let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert("./certs/myna_cert.pem"); - let mut tbs_cert_32 = [0u32; MAX_TBS_CERT_BITS / 32]; - tbs_cert_32[0..tbs_cert.to_u32_digits().len()].copy_from_slice(&tbs_cert.to_u32_digits()); + let mut sha256ed = Sha256::digest(tbs_cert.to_bytes_le()); + sha256ed.reverse(); + let mut buf = [0; 32]; + buf[0..16].copy_from_slice(&sha256ed[0..16]); + let sha256lo = Fr::from_bytes(&buf).unwrap(); + buf[0..16].copy_from_slice(&sha256ed[16..32]); + let sha256hi = Fr::from_bytes(&buf).unwrap(); - let public_input = PublicInput { nation_pubkey: nation_pubkey.clone() }; - let private_input = - PrivateInput { tbs_cert: tbs_cert_32, nation_sig: nation_sig.clone(), password: Fr::from(0xA42) }; + let public_input = PublicInput { sha256: [sha256lo, sha256hi], nation_pubkey: nation_pubkey.clone() }; + let private_input = PrivateInput { nation_sig: nation_sig.clone(), password: Fr::from(0xA42) }; let public_output = proof_of_japanese_residence(builder.pool(0).main(), range_chip, public_input, private_input); + dbg!(&public_output); builder.assigned_instances[0].extend(public_output); // AUDIT: Is K enough to achieve zero knowledge? builder.calculate_params(Some(9)); - let circuit = ProofOfJapaneseResidence { halo2base: builder }; - dbg!(circuit.params()); + let circuit = ProofOfJapaneseResidence { halo2base: builder, tbs_cert: tbs_cert.to_bytes_le() }; MockProver::run( K as u32, diff --git a/packages/halo2-circuits/src/helpers.rs b/packages/halo2-circuits/src/helpers.rs index ccac964..30cea63 100644 --- a/packages/halo2-circuits/src/helpers.rs +++ b/packages/halo2-circuits/src/helpers.rs @@ -6,7 +6,7 @@ use halo2_base::{ QuantumCell::{Constant, Existing}, }; use halo2_rsa::{BigUintConfig, BigUintInstructions, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, RSASignature}; -use snark_verifier_sdk::{gen_pk, halo2::gen_snark_shplonk, Snark}; +// use snark_verifir_sdk::{gen_pk, halo2::gen_snark_shplonk, Snark}; use itertools::Itertools; use num_bigint::BigUint; From 962da7453282fc4683b4f5ea22cccfe9f1569445 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sun, 19 Nov 2023 13:42:57 +0900 Subject: [PATCH 13/28] Implement CLI commands to prove/verify a proof --- packages/halo2-circuits/src/bin/cli.rs | 326 ++++++++++++++++++------- packages/halo2-circuits/src/circuit.rs | 43 ++-- 2 files changed, 258 insertions(+), 111 deletions(-) diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 7c005c8..a277069 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -1,10 +1,31 @@ use clap::{Parser, Subcommand}; use halo2_base::{ gates::circuit::builder::BaseCircuitBuilder, - halo2_proofs::{halo2curves::bn256::Fr, plonk::Circuit}, + halo2_proofs::{ + halo2curves::bn256::{Bn256, Fr, G1Affine}, + plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, Circuit, ProvingKey, VerifyingKey}, + poly::{ + commitment::Params, + kzg::{ + commitment::{KZGCommitmentScheme, ParamsKZG}, + multiopen::{ProverGWC, VerifierGWC}, + strategy::SingleStrategy, + }, + }, + transcript::{Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer}, + SerdeFormat, + }, utils::{fs::gen_srs, BigPrimeField}, }; use halo2_circuits::{circuit, helpers::*}; +use rand::rngs::OsRng; +use sha2::{Digest, Sha256}; +use std::{ + fmt::Binary, + fs::File, + io::{Read, Write}, +}; +// use snark_verifier_sdk:: // use snark_verifier_sdk::{ // evm::{gen_evm_proof_shplonk, gen_evm_verifier_shplonk, write_calldata}, // gen_pk, @@ -24,47 +45,58 @@ struct Cli { enum Commands { /// Generate a trusted setup paramter TrustedSetup { - /// k parameter for circuit. - #[arg(long)] - k: u32, - #[arg(short, long, default_value = "./params")] - params_path: String, + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./build/trusted_setup")] + trusted_setup_path: String, }, /// Generate the proving key and the verification key for RSA circuit GenerateKeys { - /// k parameter for circuit. - #[arg(long, default_value = "17")] - k: u32, /// trusted setup parameters path. input - #[arg(short, long, default_value = "./params")] - params_path: String, + #[arg(short, long, default_value = "./build/trusted_setup")] + trusted_setup_path: String, /// proving key path. output - #[arg(long, default_value = "./build/rsa.pk")] + #[arg(long, default_value = "./build/vk")] + vk_path: String, + /// proving key path. output + #[arg(long, default_value = "./build/pk")] pk_path: String, - /// proof path. output - #[arg(long, default_value = "./build/myna_verify_rsa.proof")] - proof_path: String, // citizen's certificate #[arg(long, default_value = "./certs/myna_cert.pem")] verify_cert_path: String, // nation's certificate #[arg(long, default_value = "./certs/ca_cert.pem")] issuer_cert_path: String, + #[arg(default_value = "42")] password: u64, }, - /// Generate the proving key and the verification key for RSA circuit Prove { - /// k parameter for circuit. - #[arg(long, default_value = "17")] - k: u32, /// trusted setup parameters path. input - #[arg(short, long, default_value = "./params")] - params_path: String, + #[arg(short, long, default_value = "./build/trusted_setup")] + trusted_setup_path: String, /// proving key path. output - #[arg(long, default_value = "./build/rsa.pk")] + #[arg(long, default_value = "./build/pk")] pk_path: String, /// proof path. output - #[arg(long, default_value = "./build/myna_verify_rsa.proof")] + #[arg(long, default_value = "./build/proof")] + proof_path: String, + // citizen's certificate + #[arg(long, default_value = "./certs/myna_cert.pem")] + verify_cert_path: String, + // nation's certificate + #[arg(long, default_value = "./certs/ca_cert.pem")] + issuer_cert_path: String, + #[arg(default_value = "42")] + password: u64, + }, + Verify { + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./build/trusted_setup")] + trusted_setup_path: String, + /// proving key path. output + #[arg(long, default_value = "./build/vk")] + vk_path: String, + /// proof path. output + #[arg(long, default_value = "./build/proof")] proof_path: String, // citizen's certificate #[arg(long, default_value = "./certs/myna_cert.pem")] @@ -72,19 +104,17 @@ enum Commands { // nation's certificate #[arg(long, default_value = "./certs/ca_cert.pem")] issuer_cert_path: String, + #[arg(default_value = "42")] password: u64, }, /// Generate the proving key and the verification key for RSA circuit GenerateSolidity { - /// k parameter for circuit. - #[arg(long, default_value = "17")] - k: u32, /// trusted setup parameters path. input - #[arg(short, long, default_value = "./params")] - params_path: String, + #[arg(short, long, default_value = "./build/trusted_setup")] + trusted_setup_path: String, /// proving key path. output - #[arg(long, default_value = "./build/rsa.pk")] - pk_path: String, + #[arg(long, default_value = "./build/vk")] + vk_path: String, /// proof path. output #[arg(long, default_value = "./build/myna_verify_rsa.proof")] proof_path: String, @@ -94,6 +124,7 @@ enum Commands { // nation's certificate #[arg(long, default_value = "./certs/ca_cert.pem")] issuer_cert_path: String, + #[arg(default_value = "42")] password: u64, }, } @@ -101,86 +132,199 @@ enum Commands { fn main() { let cli = Cli::parse(); match cli.command { - Commands::TrustedSetup { k, params_path } => { - env::set_var("PARAMS_DIR", params_path); - gen_srs(k); + Commands::TrustedSetup { trusted_setup_path } => { + let trusted_setup_path = Path::new(&trusted_setup_path); + if trusted_setup_path.exists() { + println!("Trusted setup already exists. Overwriting..."); + } + + let mut file = File::create(trusted_setup_path).expect("Failed to create a trusted setup"); + let trusted_setup_file = ParamsKZG::::setup(circuit::K as u32, OsRng); + trusted_setup_file.write(&mut file).expect("Failed to write a trusted setup"); } Commands::GenerateKeys { - k, - params_path, - pk_path, - proof_path, + trusted_setup_path, verify_cert_path, issuer_cert_path, password, + vk_path, + pk_path, } => { - // let nation_pubkey = read_nation_cert(&issuer_cert_path); - // let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(&verify_cert_path); + let nation_pubkey = read_nation_cert(&issuer_cert_path); + let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(&verify_cert_path); - // let mut builder = BaseCircuitBuilder::new(false); - // builder.set_k(k as usize); - // builder.set_lookup_bits(circuit::LOOKUP_BITS); - // builder.set_instance_columns(1); - // let range_chip = builder.range_chip(); - // let ctx = builder.main(0); + let mut builder = BaseCircuitBuilder::new(false); + builder.set_k(circuit::K as usize); + builder.set_lookup_bits(circuit::LOOKUP_BITS); + builder.set_instance_columns(1); + let range_chip = builder.range_chip(); + let ctx = builder.main(0); - // let public = circuit::PublicInput { nation_pubkey }; - // let private = - // circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; - // dbg!(tbs_cert.to_bytes_le().len()); - // let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); + let mut sha256ed = Sha256::digest(tbs_cert.to_bytes_le()); + sha256ed.reverse(); + let mut buf = [0; 32]; + buf[0..16].copy_from_slice(&sha256ed[0..16]); + let sha256lo = Fr::from_bytes(&buf).unwrap(); + buf[0..16].copy_from_slice(&sha256ed[16..32]); + let sha256hi = Fr::from_bytes(&buf).unwrap(); - // builder.assigned_instances[0].extend(outputs); - // let circuit_params = builder.calculate_params(None); - // builder = builder.use_params(circuit_params); + let public_input = circuit::PublicInput { sha256: [sha256lo, sha256hi], nation_pubkey }; + let private_input = circuit::PrivateInput { nation_sig, password: Fr::from(password) }; + let public_output = circuit::proof_of_japanese_residence(ctx, range_chip, public_input, private_input); + builder.assigned_instances[0].extend(public_output); - // if Path::new(&pk_path).exists() { - // match remove_file(&pk_path) { - // Ok(_) => println!("File found, overwriting..."), - // Err(e) => println!("An error occurred: {}", e), - // } - // } + let circuit_shape = builder.calculate_params(None); + let circuit = circuit::ProofOfJapaneseResidence { + halo2base: builder.use_params(circuit_shape), + tbs_cert: tbs_cert.to_bytes_le(), + }; - // env::set_var("PARAMS_DIR", params_path); - // let trusted_setup = gen_srs(k); - // gen_pk(&trusted_setup, &builder, Some(Path::new(&pk_path))); + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) + .expect("The trusted setup is corrupted"); + + let vk = keygen_vk(&trusted_setup, &circuit).unwrap(); + let mut vk_file = File::create(vk_path).unwrap(); + vk.write(&mut vk_file, SerdeFormat::RawBytes).unwrap(); + + let pk = keygen_pk(&trusted_setup, vk, &circuit).unwrap(); + let mut pk_file = File::create(pk_path).unwrap(); + pk.write(&mut pk_file, SerdeFormat::RawBytes).unwrap(); } - Commands::Prove { k, params_path, pk_path, proof_path, verify_cert_path, issuer_cert_path, password } => { - // let nation_pubkey = read_nation_cert(&issuer_cert_path); - // let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); + Commands::Prove { verify_cert_path, issuer_cert_path, password, trusted_setup_path, pk_path, proof_path } => { + let nation_pubkey = read_nation_cert(&issuer_cert_path); + let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(&verify_cert_path); - // let mut builder = BaseCircuitBuilder::new(false); - // builder.set_k(k as usize); - // builder.set_lookup_bits(circuit::LOOKUP_BITS); - // builder.set_instance_columns(1); - // let range_chip = builder.range_chip(); - // let ctx = builder.main(0); + let mut builder = BaseCircuitBuilder::new(false); + builder.set_k(circuit::K as usize); + builder.set_lookup_bits(circuit::LOOKUP_BITS); + builder.set_instance_columns(1); + let range_chip = builder.range_chip(); + let ctx = builder.main(0); - // let public = circuit::PublicInput { nation_pubkey }; - // let private = - // circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; - // let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); + let mut sha256ed = Sha256::digest(tbs_cert.to_bytes_le()); + sha256ed.reverse(); + let mut buf = [0; 32]; + buf[0..16].copy_from_slice(&sha256ed[0..16]); + let sha256lo = Fr::from_bytes(&buf).unwrap(); + buf[0..16].copy_from_slice(&sha256ed[16..32]); + let sha256hi = Fr::from_bytes(&buf).unwrap(); - // builder.assigned_instances[0].extend(outputs); - // let circuit_params = builder.calculate_params(None); - // builder = builder.use_params(circuit_params); + let public_input = circuit::PublicInput { sha256: [sha256lo, sha256hi], nation_pubkey }; + let private_input = circuit::PrivateInput { nation_sig, password: Fr::from(password) }; + let public_output = circuit::proof_of_japanese_residence(ctx, range_chip, public_input, private_input); + builder.assigned_instances[0].extend(public_output); - // if Path::new(&proof_path).exists() { - // match remove_file(&proof_path) { - // Ok(_) => println!("File found, overwriting..."), - // Err(e) => println!("An error occurred: {}", e), - // } - // } + let circuit_shape = builder.calculate_params(None); + let circuit = circuit::ProofOfJapaneseResidence { + halo2base: builder.use_params(circuit_shape), + tbs_cert: tbs_cert.to_bytes_le(), + }; - // env::set_var("PARAMS_DIR", params_path); - // let trusted_setup = gen_srs(k); - // let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); - // gen_snark_shplonk(&trusted_setup, &pk, builder, Some(Path::new(&proof_path))); + let instance_columns: Vec> = circuit + .halo2base + .assigned_instances + .iter() + .map(|public_column| public_column.into_iter().map(|public_cell| public_cell.value().clone()).collect()) + .collect(); + let instance_columns: Vec<&[Fr]> = + instance_columns.iter().map(|instance_column| instance_column.as_slice()).collect(); + + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) + .expect("The trusted setup is corrupted"); + + let mut pk_file = File::open(pk_path).expect("pk not found. Run generate-keys first."); + let pk = ProvingKey::::read::<_, circuit::ProofOfJapaneseResidence>( + &mut pk_file, + SerdeFormat::RawBytes, + circuit.params(), + ) + .unwrap(); + + let proof_file = File::create(proof_path).unwrap(); + println!("Proof generation started at: {:?}", std::time::Instant::now()); + let mut proof = Blake2bWrite::<_, _, Challenge255<_>>::init(proof_file); + create_proof::< + KZGCommitmentScheme, + ProverGWC<'_, Bn256>, + Challenge255, + _, + Blake2bWrite>, + _, + >(&trusted_setup, &pk, &[circuit], &[&instance_columns], OsRng, &mut proof) + .expect("prover should not fail"); + proof.finalize(); + println!("Proof generation finished at: {:?}", std::time::Instant::now()); + } + Commands::Verify { trusted_setup_path, vk_path, proof_path, verify_cert_path, issuer_cert_path, password } => { + let nation_pubkey = read_nation_cert(&issuer_cert_path); + let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(&verify_cert_path); + + let mut builder = BaseCircuitBuilder::new(false); + builder.set_k(circuit::K as usize); + builder.set_lookup_bits(circuit::LOOKUP_BITS); + builder.set_instance_columns(1); + let range_chip = builder.range_chip(); + let ctx = builder.main(0); + + let mut sha256ed = Sha256::digest(tbs_cert.to_bytes_le()); + sha256ed.reverse(); + let mut buf = [0; 32]; + buf[0..16].copy_from_slice(&sha256ed[0..16]); + let sha256lo = Fr::from_bytes(&buf).unwrap(); + buf[0..16].copy_from_slice(&sha256ed[16..32]); + let sha256hi = Fr::from_bytes(&buf).unwrap(); + + let public_input = circuit::PublicInput { sha256: [sha256lo, sha256hi], nation_pubkey }; + let private_input = circuit::PrivateInput { nation_sig, password: Fr::from(password) }; + let public_output = circuit::proof_of_japanese_residence(ctx, range_chip, public_input, private_input); + builder.assigned_instances[0].extend(public_output); + + let circuit_shape = builder.calculate_params(None); + let circuit = circuit::ProofOfJapaneseResidence { + halo2base: builder.use_params(circuit_shape), + tbs_cert: tbs_cert.to_bytes_le(), + }; + + let instance_columns: Vec> = circuit + .halo2base + .assigned_instances + .iter() + .map(|public_column| public_column.into_iter().map(|public_cell| public_cell.value().clone()).collect()) + .collect(); + let instance_columns: Vec<&[Fr]> = + instance_columns.iter().map(|instance_column| instance_column.as_slice()).collect(); + + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) + .expect("The trusted setup is corrupted"); + + let mut vk_file = File::open(vk_path).expect("vk not found. Run generate-keys first."); + let vk = VerifyingKey::::read::<_, circuit::ProofOfJapaneseResidence>( + &mut vk_file, + SerdeFormat::RawBytes, + circuit.params(), + ) + .unwrap(); + + let proof_file = File::open(proof_path).unwrap(); + let mut proof = Blake2bRead::init(&proof_file); + + let result = verify_proof::< + KZGCommitmentScheme, + VerifierGWC<'_, Bn256>, + Challenge255, + Blake2bRead<&File, G1Affine, Challenge255>, + SingleStrategy<'_, Bn256>, + >( + &trusted_setup, &vk, SingleStrategy::new(&trusted_setup), &[&instance_columns], &mut proof + ); + assert!(result.is_ok(), "{:?}", result) } Commands::GenerateSolidity { - k, - params_path, - pk_path, + trusted_setup_path, + vk_path, proof_path, verify_cert_path, issuer_cert_path, diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index 88a0a09..eb6c149 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -39,11 +39,11 @@ pub struct PrivateInput { } // halo2-sha256-unoptimized takes inputs byte by byte so I guess 8 is optimimal -pub const LOOKUP_BITS: usize = 8; +pub const LOOKUP_BITS: usize = 16; const RSA_KEY_SIZE: usize = 2048; const PUBKEY_BEGINS: usize = 2216; const E: usize = 65537; -const K: usize = 22; +pub const K: usize = 18; const LIMB_BITS: usize = 64; const SHA256_BLOCK_BITS: usize = 512; const TBS_CERT_MAX_BITS: usize = 1 << 12; @@ -125,15 +125,15 @@ pub fn split_each_limb( } #[derive(Debug, Clone)] -struct Config { +pub struct Config { halo2base: BaseConfig, sha256: Sha256CircuitConfig, } #[derive(Debug, Clone)] -struct ProofOfJapaneseResidence { - halo2base: BaseCircuitBuilder, - tbs_cert: Vec, +pub struct ProofOfJapaneseResidence { + pub halo2base: BaseCircuitBuilder, + pub tbs_cert: Vec, } impl Circuit for ProofOfJapaneseResidence { @@ -173,20 +173,23 @@ impl Circuit for ProofOfJapaneseResidence { }, )?; - let mut final_block = None; - for block in assigned_blocks.iter() { - block.is_final().value().map(|is_final| { - if Fr::zero() < is_final.evaluate() { - final_block = Some(block); - } - }); - - if let Some(_) = final_block { - break; - } - } - let final_block = final_block.expect("unreachable"); - dbg!(final_block.output()); + // let mut final_block = None; + // for block in assigned_blocks.iter() { + // block.is_final().value().map(|is_final| { + // if Fr::zero() < is_final.evaluate() { + // final_block = Some(block); + // } + // }); + + // if let Some(_) = final_block { + // break; + // } + // } + // let final_block = final_block.expect("zkevm-hashes failed to generate a SHA256 hash"); + // dbg!(final_block.output()); + + // TODO: Support longer inputs; + let final_block = &assigned_blocks[20]; // TODO: Hide these layouter.constrain_instance(final_block.output().lo().cell(), config.halo2base.instance[0], 0); From f1c30a9650f584b1cfcb2c3fc8b1ac5d87594d6d Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sun, 19 Nov 2023 14:02:20 +0900 Subject: [PATCH 14/28] Refactoring --- packages/halo2-circuits/src/bin/cli.rs | 100 ++++--------------------- packages/halo2-circuits/src/circuit.rs | 67 +++++++++-------- 2 files changed, 52 insertions(+), 115 deletions(-) diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index a277069..c1e4a4d 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -24,6 +24,7 @@ use std::{ fmt::Binary, fs::File, io::{Read, Write}, + path::PathBuf, }; // use snark_verifier_sdk:: // use snark_verifier_sdk::{ @@ -150,34 +151,11 @@ fn main() { vk_path, pk_path, } => { - let nation_pubkey = read_nation_cert(&issuer_cert_path); - let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(&verify_cert_path); - - let mut builder = BaseCircuitBuilder::new(false); - builder.set_k(circuit::K as usize); - builder.set_lookup_bits(circuit::LOOKUP_BITS); - builder.set_instance_columns(1); - let range_chip = builder.range_chip(); - let ctx = builder.main(0); - - let mut sha256ed = Sha256::digest(tbs_cert.to_bytes_le()); - sha256ed.reverse(); - let mut buf = [0; 32]; - buf[0..16].copy_from_slice(&sha256ed[0..16]); - let sha256lo = Fr::from_bytes(&buf).unwrap(); - buf[0..16].copy_from_slice(&sha256ed[16..32]); - let sha256hi = Fr::from_bytes(&buf).unwrap(); - - let public_input = circuit::PublicInput { sha256: [sha256lo, sha256hi], nation_pubkey }; - let private_input = circuit::PrivateInput { nation_sig, password: Fr::from(password) }; - let public_output = circuit::proof_of_japanese_residence(ctx, range_chip, public_input, private_input); - builder.assigned_instances[0].extend(public_output); - - let circuit_shape = builder.calculate_params(None); - let circuit = circuit::ProofOfJapaneseResidence { - halo2base: builder.use_params(circuit_shape), - tbs_cert: tbs_cert.to_bytes_le(), - }; + let circuit = circuit::ProofOfJapaneseResidence::new( + issuer_cert_path.into(), + verify_cert_path.into(), + password.into(), + ); let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) @@ -192,34 +170,11 @@ fn main() { pk.write(&mut pk_file, SerdeFormat::RawBytes).unwrap(); } Commands::Prove { verify_cert_path, issuer_cert_path, password, trusted_setup_path, pk_path, proof_path } => { - let nation_pubkey = read_nation_cert(&issuer_cert_path); - let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(&verify_cert_path); - - let mut builder = BaseCircuitBuilder::new(false); - builder.set_k(circuit::K as usize); - builder.set_lookup_bits(circuit::LOOKUP_BITS); - builder.set_instance_columns(1); - let range_chip = builder.range_chip(); - let ctx = builder.main(0); - - let mut sha256ed = Sha256::digest(tbs_cert.to_bytes_le()); - sha256ed.reverse(); - let mut buf = [0; 32]; - buf[0..16].copy_from_slice(&sha256ed[0..16]); - let sha256lo = Fr::from_bytes(&buf).unwrap(); - buf[0..16].copy_from_slice(&sha256ed[16..32]); - let sha256hi = Fr::from_bytes(&buf).unwrap(); - - let public_input = circuit::PublicInput { sha256: [sha256lo, sha256hi], nation_pubkey }; - let private_input = circuit::PrivateInput { nation_sig, password: Fr::from(password) }; - let public_output = circuit::proof_of_japanese_residence(ctx, range_chip, public_input, private_input); - builder.assigned_instances[0].extend(public_output); - - let circuit_shape = builder.calculate_params(None); - let circuit = circuit::ProofOfJapaneseResidence { - halo2base: builder.use_params(circuit_shape), - tbs_cert: tbs_cert.to_bytes_le(), - }; + let circuit = circuit::ProofOfJapaneseResidence::new( + issuer_cert_path.into(), + verify_cert_path.into(), + password.into(), + ); let instance_columns: Vec> = circuit .halo2base @@ -258,34 +213,11 @@ fn main() { println!("Proof generation finished at: {:?}", std::time::Instant::now()); } Commands::Verify { trusted_setup_path, vk_path, proof_path, verify_cert_path, issuer_cert_path, password } => { - let nation_pubkey = read_nation_cert(&issuer_cert_path); - let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(&verify_cert_path); - - let mut builder = BaseCircuitBuilder::new(false); - builder.set_k(circuit::K as usize); - builder.set_lookup_bits(circuit::LOOKUP_BITS); - builder.set_instance_columns(1); - let range_chip = builder.range_chip(); - let ctx = builder.main(0); - - let mut sha256ed = Sha256::digest(tbs_cert.to_bytes_le()); - sha256ed.reverse(); - let mut buf = [0; 32]; - buf[0..16].copy_from_slice(&sha256ed[0..16]); - let sha256lo = Fr::from_bytes(&buf).unwrap(); - buf[0..16].copy_from_slice(&sha256ed[16..32]); - let sha256hi = Fr::from_bytes(&buf).unwrap(); - - let public_input = circuit::PublicInput { sha256: [sha256lo, sha256hi], nation_pubkey }; - let private_input = circuit::PrivateInput { nation_sig, password: Fr::from(password) }; - let public_output = circuit::proof_of_japanese_residence(ctx, range_chip, public_input, private_input); - builder.assigned_instances[0].extend(public_output); - - let circuit_shape = builder.calculate_params(None); - let circuit = circuit::ProofOfJapaneseResidence { - halo2base: builder.use_params(circuit_shape), - tbs_cert: tbs_cert.to_bytes_le(), - }; + let circuit = circuit::ProofOfJapaneseResidence::new( + issuer_cert_path.into(), + verify_cert_path.into(), + password.into(), + ); let instance_columns: Vec> = circuit .halo2base diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index eb6c149..564781e 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -1,3 +1,4 @@ +use crate::helpers::{read_citizen_cert, read_nation_cert}; use halo2_base::{ gates::{ circuit::{builder::BaseCircuitBuilder, BaseCircuitParams, BaseConfig}, @@ -19,7 +20,8 @@ use halo2_rsa::{ }; use num_bigint::BigUint; use num_traits::One; -use sha2::Digest; +use sha2::{Digest, Sha256}; +use std::path::PathBuf; use zkevm_hashes::sha256::vanilla::columns::Sha256CircuitConfig; // use zkevm_hashes::Sha256Chip; @@ -38,12 +40,11 @@ pub struct PrivateInput { pub password: Fr, } -// halo2-sha256-unoptimized takes inputs byte by byte so I guess 8 is optimimal pub const LOOKUP_BITS: usize = 16; const RSA_KEY_SIZE: usize = 2048; const PUBKEY_BEGINS: usize = 2216; const E: usize = 65537; -pub const K: usize = 18; +pub const K: usize = 20; const LIMB_BITS: usize = 64; const SHA256_BLOCK_BITS: usize = 512; const TBS_CERT_MAX_BITS: usize = 1 << 12; @@ -201,6 +202,36 @@ impl Circuit for ProofOfJapaneseResidence { } } +impl ProofOfJapaneseResidence { + pub fn new(nation_cert_path: PathBuf, citizen_cert_path: PathBuf, user_secret: Fr) -> Self { + let nation_pubkey = read_nation_cert(nation_cert_path.to_str().unwrap()); + let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(citizen_cert_path.to_str().unwrap()); + + let mut builder = BaseCircuitBuilder::new(false); + builder.set_k(K as usize); + builder.set_lookup_bits(LOOKUP_BITS); + builder.set_instance_columns(1); + let range_chip = builder.range_chip(); + let ctx = builder.main(0); + + let mut sha256ed = Sha256::digest(tbs_cert.to_bytes_le()); + sha256ed.reverse(); + let mut buf = [0; 32]; + buf[0..16].copy_from_slice(&sha256ed[0..16]); + let sha256lo = Fr::from_bytes(&buf).unwrap(); + buf[0..16].copy_from_slice(&sha256ed[16..32]); + let sha256hi = Fr::from_bytes(&buf).unwrap(); + + let public_input = PublicInput { sha256: [sha256lo, sha256hi], nation_pubkey }; + let private_input = PrivateInput { nation_sig, password: user_secret }; + let public_output = proof_of_japanese_residence(ctx, range_chip, public_input, private_input); + builder.assigned_instances[0].extend(public_output); + + let circuit_shape = builder.calculate_params(Some(K)); + Self { halo2base: builder.use_params(circuit_shape), tbs_cert: tbs_cert.to_bytes_le() } + } +} + pub fn proof_of_japanese_residence( ctx: &mut Context, range_chip: RangeChip, @@ -343,34 +374,8 @@ mod tests { #[test] fn mock() { - let mut builder = BaseCircuitBuilder::default(); - builder.set_k(K); - builder.set_lookup_bits(LOOKUP_BITS); - builder.set_instance_columns(1); - let range_chip = builder.range_chip().clone(); - - let nation_pubkey = read_nation_cert("./certs/ca_cert.pem"); - let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert("./certs/myna_cert.pem"); - - let mut sha256ed = Sha256::digest(tbs_cert.to_bytes_le()); - sha256ed.reverse(); - let mut buf = [0; 32]; - buf[0..16].copy_from_slice(&sha256ed[0..16]); - let sha256lo = Fr::from_bytes(&buf).unwrap(); - buf[0..16].copy_from_slice(&sha256ed[16..32]); - let sha256hi = Fr::from_bytes(&buf).unwrap(); - - let public_input = PublicInput { sha256: [sha256lo, sha256hi], nation_pubkey: nation_pubkey.clone() }; - let private_input = PrivateInput { nation_sig: nation_sig.clone(), password: Fr::from(0xA42) }; - let public_output = - proof_of_japanese_residence(builder.pool(0).main(), range_chip, public_input, private_input); - - dbg!(&public_output); - builder.assigned_instances[0].extend(public_output); - // AUDIT: Is K enough to achieve zero knowledge? - builder.calculate_params(Some(9)); - - let circuit = ProofOfJapaneseResidence { halo2base: builder, tbs_cert: tbs_cert.to_bytes_le() }; + let circuit = + ProofOfJapaneseResidence::new("./certs/ca_cert.pem".into(), "./certs/myna_cert.pem".into(), 0xA42.into()); MockProver::run( K as u32, From de66ba3ec8cbb2e5ec12a0f33a48fb14d258d054 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sun, 19 Nov 2023 20:07:59 +0900 Subject: [PATCH 15/28] Implement a CLI command to generate a solidity code that verifies a proof --- packages/halo2-circuits/Cargo.lock | 818 ++++++++++++++++++++++--- packages/halo2-circuits/Cargo.toml | 25 +- packages/halo2-circuits/src/bin/cli.rs | 107 ++-- 3 files changed, 781 insertions(+), 169 deletions(-) diff --git a/packages/halo2-circuits/Cargo.lock b/packages/halo2-circuits/Cargo.lock index a7e8b8a..e3a6b95 100644 --- a/packages/halo2-circuits/Cargo.lock +++ b/packages/halo2-circuits/Cargo.lock @@ -17,6 +17,18 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +[[package]] +name = "ahash" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91429305e9f0a25f6205c5b8e0d2db09e0708a7a6df0f42212bb56c32c8ac97a" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.2" @@ -26,6 +38,52 @@ dependencies = [ "memchr", ] +[[package]] +name = "allocator-api2" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" + +[[package]] +name = "alloy-primitives" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0628ec0ba5b98b3370bb6be17b12f23bfce8ee4ad83823325a20546d9b03b78" +dependencies = [ + "alloy-rlp", + "bytes", + "cfg-if", + "const-hex", + "derive_more", + "hex-literal", + "itoa", + "ruint", + "tiny-keccak", +] + +[[package]] +name = "alloy-rlp" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc0fac0fc16baf1f63f78b47c3d24718f3619b0714076f6a02957d808d52cbef" +dependencies = [ + "alloy-rlp-derive", + "arrayvec", + "bytes", + "smol_str", +] + +[[package]] +name = "alloy-rlp-derive" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0391754c09fab4eae3404d19d0d297aa1c670c1775ab51d8a5312afeca23157" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + [[package]] name = "anes" version = "0.1.6" @@ -72,6 +130,110 @@ dependencies = [ "windows-sys 0.45.0", ] +[[package]] +name = "ark-ff" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b3235cc41ee7a12aaaf2c575a2ad7b46713a8a50bda2fc3b003a04845c05dd6" +dependencies = [ + "ark-ff-asm 0.3.0", + "ark-ff-macros 0.3.0", + "ark-serialize 0.3.0", + "ark-std 0.3.0", + "derivative", + "num-bigint", + "num-traits", + "paste", + "rustc_version 0.3.3", + "zeroize", +] + +[[package]] +name = "ark-ff" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec847af850f44ad29048935519032c33da8aa03340876d351dfab5660d2966ba" +dependencies = [ + "ark-ff-asm 0.4.2", + "ark-ff-macros 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "derivative", + "digest 0.10.7", + "itertools 0.10.5", + "num-bigint", + "num-traits", + "paste", + "rustc_version 0.4.0", + "zeroize", +] + +[[package]] +name = "ark-ff-asm" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db02d390bf6643fb404d3d22d31aee1c4bc4459600aef9113833d17e786c6e44" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-asm" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed4aa4fe255d0bc6d79373f7e31d2ea147bcf486cba1be5ba7ea85abdb92348" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" +dependencies = [ + "num-bigint", + "num-traits", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-macros" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-serialize" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d6c2b318ee6e10f8c2853e73a83adc0ccb88995aa978d8a3408d492ab2ee671" +dependencies = [ + "ark-std 0.3.0", + "digest 0.9.0", +] + +[[package]] +name = "ark-serialize" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" +dependencies = [ + "ark-std 0.4.0", + "digest 0.10.7", + "num-bigint", +] + [[package]] name = "ark-std" version = "0.3.0" @@ -83,6 +245,16 @@ dependencies = [ "rand", ] +[[package]] +name = "ark-std" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" +dependencies = [ + "num-traits", + "rand", +] + [[package]] name = "array-init" version = "2.1.0" @@ -196,6 +368,38 @@ version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bindgen" +version = "0.66.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b84e06fc203107bfbad243f4aba2af864eb7db3b1cf46ea0a023b0b433d2a7" +dependencies = [ + "bitflags 2.4.1", + "cexpr", + "clang-sys", + "lazy_static", + "lazycell", + "log", + "peeking_take_while", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn 2.0.39", + "which", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -256,6 +460,18 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d696c370c750c948ada61c69a0ee2cbbb9c50b1019ddb86d9317157a99c2cae" +[[package]] +name = "blst" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c94087b935a822949d3291a9989ad2b2051ea141eda0fd4e478a75f6aa3e604b" +dependencies = [ + "cc", + "glob", + "threadpool", + "zeroize", +] + [[package]] name = "bumpalo" version = "3.14.0" @@ -283,6 +499,21 @@ dependencies = [ "serde", ] +[[package]] +name = "c-kzg" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac926d808fb72fe09ebf471a091d6d72918876ccf0b4989766093d2d0d24a0ef" +dependencies = [ + "bindgen", + "blst", + "cc", + "glob", + "hex", + "libc", + "serde", +] + [[package]] name = "cast" version = "0.3.0" @@ -298,6 +529,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + [[package]] name = "cfg-if" version = "1.0.0" @@ -340,6 +580,17 @@ dependencies = [ "half", ] +[[package]] +name = "clang-sys" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c688fc74432808e3eb684cae8830a86be1d66a2bd58e1f248ed0960a590baf6f" +dependencies = [ + "glob", + "libc", + "libloading", +] + [[package]] name = "clap" version = "3.2.25" @@ -479,6 +730,12 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7144d30dcf0fafbce74250a3963025d8d52177934239851c917d29f1df280c2" +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + [[package]] name = "cpufeatures" version = "0.2.11" @@ -609,9 +866,9 @@ dependencies = [ [[package]] name = "crypto-bigint" -version = "0.5.4" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28f85c3514d2a6e64160359b45a3918c3b4178bcbf4ae5d03ab2d02e521c479a" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ "generic-array", "rand_core", @@ -679,14 +936,27 @@ dependencies = [ "powerfmt", ] +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "derive_more" version = "0.99.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" dependencies = [ + "convert_case", "proc-macro2", "quote", + "rustc_version 0.4.0", "syn 1.0.109", ] @@ -724,9 +994,9 @@ dependencies = [ [[package]] name = "ecdsa" -version = "0.16.8" +version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4b1e0c257a9e9f25f90ff76d7a68360ed497ee519c8e428d1825ef0000799d4" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ "der 0.7.8", "digest 0.10.7", @@ -744,12 +1014,12 @@ checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" [[package]] name = "elliptic-curve" -version = "0.13.6" +version = "0.13.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d97ca172ae9dc9f9b779a6e3a65d308f2af74e5b8c921299075bdb4a0370e914" +checksum = "e9775b22bc152ad86a0cf23f0f348b884b26add12bf741e7ffc4d4ab2ab4d205" dependencies = [ "base16ct", - "crypto-bigint 0.5.4", + "crypto-bigint 0.5.5", "digest 0.10.7", "ff", "generic-array", @@ -761,6 +1031,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "enumn" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2ad8cef1d801a4686bfd8919f0b30eac4c8e48968c437a6405ded4fb5272d2b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + [[package]] name = "env_logger" version = "0.10.1" @@ -782,9 +1063,9 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c18ee0ed65a5f1f81cac6b1d213b69c35fa47d4252ad41f1486dbd8226fe36e" +checksum = "f258a7194e7f7c2a7837a8913aeab7fd8c383457034fa20ce4dd3dcb813e8eb8" dependencies = [ "libc", "windows-sys 0.48.0", @@ -840,9 +1121,9 @@ dependencies = [ [[package]] name = "ethers-core" -version = "2.0.10" +version = "2.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0a17f0708692024db9956b31d7a20163607d2745953f5ae8125ab368ba280ad" +checksum = "2f03e0bdc216eeb9e355b90cf610ef6c5bb8aca631f97b5ae9980ce34ea7878d" dependencies = [ "arrayvec", "bytes", @@ -871,6 +1152,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +[[package]] +name = "fastrlp" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139834ddba373bbdd213dffe02c8d110508dcf1726c2be27e8d1f7d7e1856418" +dependencies = [ + "arrayvec", + "auto_impl", + "bytes", +] + [[package]] name = "ff" version = "0.13.0" @@ -957,6 +1249,12 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" +[[package]] +name = "glob" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" + [[package]] name = "group" version = "0.13.0" @@ -975,34 +1273,33 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" [[package]] -name = "halo2-base" +name = "halo2-axiom" version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop#ee12efa86fdd89ae7b37c8f11005888180a1d316" +source = "git+https://github.com/axiom-crypto/halo2.git#e841084b8fb5cffd1390b4901e89812c861dffb1" dependencies = [ - "getset", - "halo2_proofs 0.3.1", + "blake2b_simd", + "crossbeam", + "ff", + "group", + "halo2curves-axiom", "itertools 0.11.0", - "log", - "num-bigint", - "num-integer", - "num-traits", - "poseidon-rs", - "rand_chacha", - "rayon", + "maybe-rayon", + "pairing", + "rand", + "rand_core", "rustc-hash", - "serde", - "serde_json", + "sha3 0.10.8", + "tracing", ] [[package]] name = "halo2-base" version = "0.4.0" -source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#2963e2a3b7ad704505ba6a7c5a8b6b938c7efde8" dependencies = [ - "ark-std", + "ark-std 0.3.0", "getset", - "halo2_proofs 0.2.0", - "halo2_proofs 0.3.1", + "halo2-axiom", + "halo2_proofs", "itertools 0.11.0", "log", "num-bigint", @@ -1027,8 +1324,8 @@ dependencies = [ "env_logger", "getrandom", "getset", - "halo2-base 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", - "halo2-ecc 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", + "halo2-base", + "halo2-ecc", "halo2-rsa", "itertools 0.11.0", "num-bigint", @@ -1040,6 +1337,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "snark-verifier-sdk", "tokio", "x509-parser", "zkevm-hashes", @@ -1048,28 +1346,8 @@ dependencies = [ [[package]] name = "halo2-ecc" version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop#ee12efa86fdd89ae7b37c8f11005888180a1d316" dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", - "itertools 0.10.5", - "num-bigint", - "num-integer", - "num-traits", - "rand", - "rand_chacha", - "rand_core", - "rayon", - "serde", - "serde_json", - "test-case", -] - -[[package]] -name = "halo2-ecc" -version = "0.4.0" -source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#2963e2a3b7ad704505ba6a7c5a8b6b938c7efde8" -dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", + "halo2-base", "itertools 0.10.5", "num-bigint", "num-integer", @@ -1088,8 +1366,8 @@ name = "halo2-rsa" version = "0.1.0" dependencies = [ "env_logger", - "halo2-base 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", - "halo2-ecc 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", + "halo2-base", + "halo2-ecc", "num-bigint", "num-traits", "rand", @@ -1105,7 +1383,7 @@ dependencies = [ "blake2b_simd", "ff", "group", - "halo2curves 0.1.0", + "halo2curves", "maybe-rayon", "rand_chacha", "rand_core", @@ -1113,25 +1391,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "halo2_proofs" -version = "0.3.1" -source = "git+https://github.com/axiom-crypto/halo2.git#58f50f7fa9dfaf0b4864bc431c17a96fef7b177e" -dependencies = [ - "blake2b_simd", - "crossbeam", - "ff", - "group", - "halo2curves 0.4.1", - "maybe-rayon", - "pairing", - "rand", - "rand_core", - "rustc-hash", - "sha3 0.10.8", - "tracing", -] - [[package]] name = "halo2curves" version = "0.1.0" @@ -1153,9 +1412,10 @@ dependencies = [ ] [[package]] -name = "halo2curves" -version = "0.4.1" -source = "git+https://github.com/axiom-crypto/halo2curves.git?branch=main#f11edd061714dea13aeaccda58cc4b271700b367" +name = "halo2curves-axiom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d82f25182a221a5c79ce8d41d1dd3910f10626d7e9d0f9f9e9336e2545b7d1f" dependencies = [ "blake2b_simd", "ff", @@ -1187,6 +1447,10 @@ name = "hashbrown" version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f93e7192158dbcda357bdec5fb5788eebf8bbac027f3f33e719d29135ae84156" +dependencies = [ + "ahash", + "allocator-api2", +] [[package]] name = "heck" @@ -1218,6 +1482,12 @@ dependencies = [ "serde", ] +[[package]] +name = "hex-literal" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" + [[package]] name = "hmac" version = "0.12.1" @@ -1227,6 +1497,15 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "home" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5444c27eef6923071f7ebcc33e3444508466a76f7a2b93da00ed6e19f30c1ddb" +dependencies = [ + "windows-sys 0.48.0", +] + [[package]] name = "humantime" version = "2.1.0" @@ -1337,9 +1616,9 @@ dependencies = [ [[package]] name = "k256" -version = "0.13.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cadb76004ed8e97623117f3df85b17aaa6626ab0b0831e6573f104df16cd1bcc" +checksum = "3f01b677d82ef7a676aa37e099defd83a28e15687112cafdd112d60236b6115b" dependencies = [ "cfg-if", "ecdsa", @@ -1366,12 +1645,28 @@ dependencies = [ "spin", ] +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + [[package]] name = "libc" version = "0.2.150" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c" +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + [[package]] name = "libm" version = "0.2.8" @@ -1451,6 +1746,20 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "num" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05180d69e3da0e530ba2a1dae5110317e49e3b7f3d41be227dc5f92e49ee7af" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + [[package]] name = "num-bigint" version = "0.4.4" @@ -1481,6 +1790,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "num-complex" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ba157ca0885411de85d6ca030ba7e2a83a28636056c7c699b07c8b6f7383214" +dependencies = [ + "num-traits", +] + [[package]] name = "num-integer" version = "0.1.45" @@ -1502,6 +1820,18 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" +dependencies = [ + "autocfg", + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.17" @@ -1704,6 +2034,12 @@ version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" +[[package]] +name = "peeking_take_while" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" + [[package]] name = "pem-rfc7468" version = "0.3.1" @@ -1713,6 +2049,17 @@ dependencies = [ "base64ct", ] +[[package]] +name = "pest" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae9cee2a55a544be8b89dc6848072af97a20f2422603c10865be2a42b580fff5" +dependencies = [ + "memchr", + "thiserror", + "ucd-trie", +] + [[package]] name = "pin-project-lite" version = "0.2.13" @@ -1811,6 +2158,16 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" +[[package]] +name = "prettyplease" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae005bd773ab59b4725093fd7df83fd7892f7d8eafb48dbd7de6e024e4215f9d" +dependencies = [ + "proc-macro2", + "syn 2.0.39", +] + [[package]] name = "primitive-types" version = "0.12.2" @@ -2005,6 +2362,61 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" +[[package]] +name = "revm" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f4ca8ae0345104523b4af1a8a7ea97cfa1865cdb7a7c25d23c1a18d9b48598" +dependencies = [ + "auto_impl", + "revm-interpreter", + "revm-precompile", +] + +[[package]] +name = "revm-interpreter" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f959cafdf64a7f89b014fa73dc2325001cf654b3d9400260b212d19a2ebe3da0" +dependencies = [ + "revm-primitives", +] + +[[package]] +name = "revm-precompile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d360a88223d85709d2e95d4609eb1e19c649c47e28954bfabae5e92bb37e83e" +dependencies = [ + "c-kzg", + "k256", + "num", + "once_cell", + "revm-primitives", + "ripemd", + "secp256k1", + "sha2", + "substrate-bn", +] + +[[package]] +name = "revm-primitives" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51187b852d9e458816a2e19c81f1dd6c924077e1a8fccd16e4f044f865f299d7" +dependencies = [ + "alloy-primitives", + "alloy-rlp", + "auto_impl", + "bitflags 2.4.1", + "bitvec", + "c-kzg", + "enumn", + "hashbrown 0.14.2", + "hex", + "once_cell", +] + [[package]] name = "rfc6979" version = "0.4.0" @@ -2030,6 +2442,15 @@ dependencies = [ "winapi", ] +[[package]] +name = "ripemd" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "rlp" version = "0.5.2" @@ -2073,6 +2494,35 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ruint" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95294d6e3a6192f3aabf91c38f56505a625aa495533442744185a36d75a790c4" +dependencies = [ + "alloy-rlp", + "ark-ff 0.3.0", + "ark-ff 0.4.2", + "bytes", + "fastrlp", + "num-bigint", + "parity-scale-codec", + "primitive-types", + "proptest", + "rand", + "rlp", + "ruint-macro", + "serde", + "valuable", + "zeroize", +] + +[[package]] +name = "ruint-macro" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e666a5496a0b2186dbcd0ff6106e29e093c15591bde62c20d3842007c6978a09" + [[package]] name = "rustc-demangle" version = "0.1.23" @@ -2091,6 +2541,24 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" +[[package]] +name = "rustc_version" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +dependencies = [ + "semver 0.11.0", +] + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver 1.0.20", +] + [[package]] name = "rusticata-macros" version = "4.1.0" @@ -2178,6 +2646,48 @@ dependencies = [ "zeroize", ] +[[package]] +name = "secp256k1" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25996b82292a7a57ed3508f052cfff8640d38d32018784acd714758b43da9c8f" +dependencies = [ + "secp256k1-sys", +] + +[[package]] +name = "secp256k1-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70a129b9e9efbfb223753b9163c4ab3b13cff7fd9c7f010fbac25ab4099fa07e" +dependencies = [ + "cc", +] + +[[package]] +name = "semver" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" +dependencies = [ + "semver-parser", +] + +[[package]] +name = "semver" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" + +[[package]] +name = "semver-parser" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" +dependencies = [ + "pest", +] + [[package]] name = "serde" version = "1.0.192" @@ -2251,11 +2761,17 @@ dependencies = [ "keccak", ] +[[package]] +name = "shlex" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380" + [[package]] name = "signature" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e1788eed21689f9cf370582dfc467ef36ed9c707f073528ddafa8d83e3b8500" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest 0.10.7", "rand_core", @@ -2267,13 +2783,21 @@ version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4dccd0940a2dcdf68d092b8cbab7dc0ad8fa938bf95787e1b916b0e3d0e8e970" +[[package]] +name = "smol_str" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74212e6bbe9a4352329b2f68ba3130c15a3f26fe88ff22dbdc6cdd58fa85e99c" +dependencies = [ + "serde", +] + [[package]] name = "snark-verifier" -version = "0.1.7" -source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=develop#0c306577e58d4725fc3921d6c827168108373816" +version = "0.1.6" dependencies = [ - "halo2-base 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", - "halo2-ecc 0.4.0 (git+https://github.com/axiom-crypto/halo2-lib.git?branch=develop)", + "halo2-base", + "halo2-ecc", "hex", "itertools 0.11.0", "lazy_static", @@ -2282,7 +2806,32 @@ dependencies = [ "num-traits", "pairing", "rand", + "revm", + "ruint", + "serde", + "sha3 0.10.8", +] + +[[package]] +name = "snark-verifier-sdk" +version = "0.1.6" +dependencies = [ + "ark-std 0.3.0", + "bincode", + "ethereum-types", + "getset", + "halo2-base", + "hex", + "itertools 0.11.0", + "lazy_static", + "num-bigint", + "num-integer", + "num-traits", + "rand", + "rand_chacha", "serde", + "serde_json", + "snark-verifier", ] [[package]] @@ -2355,6 +2904,19 @@ dependencies = [ "syn 2.0.39", ] +[[package]] +name = "substrate-bn" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b5bbfa79abbae15dd642ea8176a21a635ff3c00059961d1ea27ad04e5b441c" +dependencies = [ + "byteorder", + "crunchy", + "lazy_static", + "rand", + "rustc-hex", +] + [[package]] name = "subtle" version = "2.5.0" @@ -2425,21 +2987,20 @@ dependencies = [ [[package]] name = "test-case" -version = "3.2.1" +version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8f1e820b7f1d95a0cdbf97a5df9de10e1be731983ab943e56703ac1b8e9d425" +checksum = "eb2550dd13afcd286853192af8601920d959b14c401fcece38071d53bf0768a8" dependencies = [ "test-case-macros", ] [[package]] name = "test-case-core" -version = "3.2.1" +version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54c25e2cb8f5fcd7318157634e8838aa6f7e4715c96637f969fabaccd1ef5462" +checksum = "adcb7fd841cd518e279be3d5a3eb0636409487998a4aff22f3de87b81e88384f" dependencies = [ "cfg-if", - "proc-macro-error", "proc-macro2", "quote", "syn 2.0.39", @@ -2447,11 +3008,10 @@ dependencies = [ [[package]] name = "test-case-macros" -version = "3.2.1" +version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37cfd7bbc88a0104e304229fba519bdc45501a30b760fb72240342f1289ad257" +checksum = "5c89e72a01ed4c579669add59014b9a524d609c0c88c6a585ce37485879f6ffb" dependencies = [ - "proc-macro-error", "proc-macro2", "quote", "syn 2.0.39", @@ -2484,6 +3044,15 @@ dependencies = [ "syn 2.0.39", ] +[[package]] +name = "threadpool" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" +dependencies = [ + "num_cpus", +] + [[package]] name = "time" version = "0.3.30" @@ -2625,6 +3194,12 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +[[package]] +name = "ucd-trie" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" + [[package]] name = "uint" version = "0.9.5" @@ -2667,6 +3242,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + [[package]] name = "vcpkg" version = "0.2.15" @@ -2759,6 +3340,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix", +] + [[package]] name = "winapi" version = "0.3.9" @@ -2958,21 +3551,54 @@ dependencies = [ "time", ] +[[package]] +name = "zerocopy" +version = "0.7.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e97e415490559a91254a2979b4829267a57d2fcd741a98eee8b722fb57289aa0" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd7e48ccf166952882ca8bd778a43502c64f33bf94c12ebe2a7f08e5a0f6689f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + [[package]] name = "zeroize" -version = "1.6.0" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a0956f1ba7c7909bfb66c2e9e4124ab6f6482560f6628b5aaeba39207c9aad9" +checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] [[package]] name = "zkevm-hashes" version = "0.2.0" -source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#2963e2a3b7ad704505ba6a7c5a8b6b938c7efde8" dependencies = [ "array-init", "ethers-core", "getset", - "halo2-base 0.4.0 (git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256)", + "halo2-base", "itertools 0.11.0", "lazy_static", "log", diff --git a/packages/halo2-circuits/Cargo.toml b/packages/halo2-circuits/Cargo.toml index eadf46c..42971b6 100644 --- a/packages/halo2-circuits/Cargo.toml +++ b/packages/halo2-circuits/Cargo.toml @@ -15,25 +15,26 @@ halo2-rsa = { default-features = false, features = [ "halo2-axiom", "display", ], path = "../../../halo2-rsa" } -halo2-base = { branch = "sha256", default-features = false, features = [ +halo2-base = { default-features = false, features = [ "halo2-axiom", "display", "test-utils", -], git = "https://github.com/MynaWallet/halo2-lib.git" } -halo2-ecc = { branch = "sha256", default-features = false, features = [ +], path = "../../../halo2-lib/halo2-base" } +halo2-ecc = { default-features = false, features = [ "halo2-axiom", "display", -], git = "https://github.com/MynaWallet/halo2-lib.git" } -zkevm-hashes = { branch = "sha256", default-features = false, features = [ +], path = "../../../halo2-lib/halo2-ecc" } +zkevm-hashes = { default-features = false, features = [ "halo2-axiom", "display", -], git = "https://github.com/MynaWallet/halo2-lib.git" } -# snark-verifier-sdk = { branch = "release-0.1.7-rc", default-features = false, features = [ -# "halo2-axiom", -# "display", -# "loader_evm", -# "loader_halo2", -# ], git = "https://github.com/axiom-crypto/snark-verifier.git" } +], path = "../../../halo2-lib/hashes/zkevm" } +snark-verifier-sdk = { default-features = false, features = [ + "halo2-axiom", + "display", + "loader_evm", + "loader_halo2", + "revm" +], path = "../../../snark-verifier/snark-verifier-sdk" } x509-parser = { version = "0.15", features = ["verify"] } openssl = "0.10" num-traits = "0.2.15" diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index c1e4a4d..bca531f 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -8,7 +8,7 @@ use halo2_base::{ commitment::Params, kzg::{ commitment::{KZGCommitmentScheme, ParamsKZG}, - multiopen::{ProverGWC, VerifierGWC}, + multiopen::{ProverSHPLONK, VerifierSHPLONK}, strategy::SingleStrategy, }, }, @@ -17,23 +17,24 @@ use halo2_base::{ }, utils::{fs::gen_srs, BigPrimeField}, }; -use halo2_circuits::{circuit, helpers::*}; +use halo2_circuits::{ + circuit::{self, ProofOfJapaneseResidence}, + helpers::*, +}; use rand::rngs::OsRng; use sha2::{Digest, Sha256}; +use snark_verifier_sdk::{ + evm::{evm_verify, gen_evm_proof_shplonk, gen_evm_verifier_shplonk, write_calldata}, + snark_verifier::system::halo2::transcript::evm::EvmTranscript, + CircuitExt, +}; use std::{ + env, fmt::Binary, - fs::File, + fs::{remove_file, File}, io::{Read, Write}, - path::PathBuf, + path::{Path, PathBuf}, }; -// use snark_verifier_sdk:: -// use snark_verifier_sdk::{ -// evm::{gen_evm_proof_shplonk, gen_evm_verifier_shplonk, write_calldata}, -// gen_pk, -// halo2::gen_snark_shplonk, -// read_pk, CircuitExt, -// }; -use std::{env, fs::remove_file, path::Path}; #[derive(Parser, Debug, Clone)] #[command(author, version, about, long_about = None)] @@ -114,11 +115,8 @@ enum Commands { #[arg(short, long, default_value = "./build/trusted_setup")] trusted_setup_path: String, /// proving key path. output - #[arg(long, default_value = "./build/vk")] - vk_path: String, - /// proof path. output - #[arg(long, default_value = "./build/myna_verify_rsa.proof")] - proof_path: String, + #[arg(long, default_value = "./build/pk")] + pk_path: String, // citizen's certificate #[arg(long, default_value = "./certs/myna_cert.pem")] verify_cert_path: String, @@ -202,7 +200,7 @@ fn main() { let mut proof = Blake2bWrite::<_, _, Challenge255<_>>::init(proof_file); create_proof::< KZGCommitmentScheme, - ProverGWC<'_, Bn256>, + ProverSHPLONK<'_, Bn256>, Challenge255, _, Blake2bWrite>, @@ -245,7 +243,7 @@ fn main() { let result = verify_proof::< KZGCommitmentScheme, - VerifierGWC<'_, Bn256>, + VerifierSHPLONK<'_, Bn256>, Challenge255, Blake2bRead<&File, G1Affine, Challenge255>, SingleStrategy<'_, Bn256>, @@ -254,55 +252,42 @@ fn main() { ); assert!(result.is_ok(), "{:?}", result) } - Commands::GenerateSolidity { - trusted_setup_path, - vk_path, - proof_path, - verify_cert_path, - issuer_cert_path, - password, - } => { - // let nation_pubkey = read_nation_cert(&issuer_cert_path); - // let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(&verify_cert_path); - - // let mut builder = BaseCircuitBuilder::new(false); - // builder.set_k(k as usize); - // builder.set_lookup_bits(circuit::LOOKUP_BITS); - // builder.set_instance_columns(1); - // let range_chip = builder.range_chip(); - // let ctx = builder.main(0); - - // let public = circuit::PublicInput { nation_pubkey }; - // let private = - // circuit::PrivateInput { tbs_cert: tbs_cert.to_bytes_le(), nation_sig, password: Fr::from(password) }; - // let outputs = circuit::proof_of_japanese_residence(ctx, range_chip, public, private); - - // builder.assigned_instances[0].extend(outputs); - // let circuit_params = builder.calculate_params(None); - // builder = builder.use_params(circuit_params); + Commands::GenerateSolidity { trusted_setup_path, pk_path, verify_cert_path, issuer_cert_path, password } => { + let circuit = circuit::ProofOfJapaneseResidence::new( + issuer_cert_path.into(), + verify_cert_path.into(), + password.into(), + ); - // env::set_var("PARAMS_DIR", params_path); - // let trusted_setup = gen_srs(k); - // let pk = read_pk::>(Path::new(&pk_path), builder.params()).unwrap(); + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) + .expect("The trusted setup is corrupted"); - // let deployment_code = gen_evm_verifier_shplonk::>( - // &trusted_setup, - // pk.get_vk(), - // builder.num_instance(), - // Some(Path::new("./build/VerifyRsa.sol")), - // ); + let mut pk_file = File::open(pk_path).expect("vk not found. Run generate-keys first."); + let pk = ProvingKey::::read::<_, circuit::ProofOfJapaneseResidence>( + &mut pk_file, + SerdeFormat::RawBytes, + circuit.params(), + ) + .unwrap(); - // let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, builder.clone(), builder.instances()); + let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, circuit.clone(), circuit.halo2base.instances()); + let deployment_code = gen_evm_verifier_shplonk::>( + &trusted_setup, + &pk.get_vk(), + circuit.halo2base.num_instance(), + Some(Path::new("./build/VerifyRsa.sol")), + ); - // println!("Size of the contract: {} bytes", deployment_code.len()); - // println!("Deploying contract..."); + println!("Size of the contract: {} bytes", deployment_code.len()); + println!("Deploying contract..."); - // evm_verify(deployment_code, builder.instances(), proof.clone()); + evm_verify(deployment_code, circuit.halo2base.instances(), proof.clone()); - // println!("Verification success!"); + println!("Verification success!"); - // write_calldata(&builder.instances(), &proof, Path::new("./build/calldata.txt")).unwrap(); - // println!("Succesfully generate calldata!"); + write_calldata(&circuit.halo2base.instances(), &proof, Path::new("./build/calldata.txt")).unwrap(); + println!("Succesfully generate calldata!"); } } } From 4a1eeaa4846b71053b4d1bb5c6f2ed9ec820d424 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sun, 19 Nov 2023 20:12:53 +0900 Subject: [PATCH 16/28] Refactoring --- packages/halo2-circuits/src/bin/cli.rs | 30 ++++++++------------------ 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index bca531f..ddafaf5 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -12,7 +12,7 @@ use halo2_base::{ strategy::SingleStrategy, }, }, - transcript::{Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer}, + transcript::{Challenge255, Keccak256Read, Keccak256Write, TranscriptReadBuffer, TranscriptWriterBuffer}, SerdeFormat, }, utils::{fs::gen_srs, BigPrimeField}, @@ -174,14 +174,8 @@ fn main() { password.into(), ); - let instance_columns: Vec> = circuit - .halo2base - .assigned_instances - .iter() - .map(|public_column| public_column.into_iter().map(|public_cell| public_cell.value().clone()).collect()) - .collect(); - let instance_columns: Vec<&[Fr]> = - instance_columns.iter().map(|instance_column| instance_column.as_slice()).collect(); + let instance_columns = circuit.halo2base.instances(); + let instance_columns: Vec<&[Fr]> = instance_columns.iter().map(|xs| xs.as_slice()).collect(); let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) @@ -197,13 +191,13 @@ fn main() { let proof_file = File::create(proof_path).unwrap(); println!("Proof generation started at: {:?}", std::time::Instant::now()); - let mut proof = Blake2bWrite::<_, _, Challenge255<_>>::init(proof_file); + let mut proof = Keccak256Write::<_, _, Challenge255<_>>::init(proof_file); create_proof::< KZGCommitmentScheme, ProverSHPLONK<'_, Bn256>, Challenge255, _, - Blake2bWrite>, + Keccak256Write>, _, >(&trusted_setup, &pk, &[circuit], &[&instance_columns], OsRng, &mut proof) .expect("prover should not fail"); @@ -217,14 +211,8 @@ fn main() { password.into(), ); - let instance_columns: Vec> = circuit - .halo2base - .assigned_instances - .iter() - .map(|public_column| public_column.into_iter().map(|public_cell| public_cell.value().clone()).collect()) - .collect(); - let instance_columns: Vec<&[Fr]> = - instance_columns.iter().map(|instance_column| instance_column.as_slice()).collect(); + let instance_columns = circuit.halo2base.instances(); + let instance_columns: Vec<&[Fr]> = instance_columns.iter().map(|xs| xs.as_slice()).collect(); let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) @@ -239,13 +227,13 @@ fn main() { .unwrap(); let proof_file = File::open(proof_path).unwrap(); - let mut proof = Blake2bRead::init(&proof_file); + let mut proof = Keccak256Read::init(&proof_file); let result = verify_proof::< KZGCommitmentScheme, VerifierSHPLONK<'_, Bn256>, Challenge255, - Blake2bRead<&File, G1Affine, Challenge255>, + Keccak256Read<&File, G1Affine, Challenge255>, SingleStrategy<'_, Bn256>, >( &trusted_setup, &vk, SingleStrategy::new(&trusted_setup), &[&instance_columns], &mut proof From 4f508591ebe8c4e09a082356b0670190b0fcd548 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sun, 19 Nov 2023 20:55:14 +0900 Subject: [PATCH 17/28] Store the generated solidity --- packages/halo2-circuits/src/bin/cli.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index ddafaf5..8b7bb34 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -120,6 +120,8 @@ enum Commands { // citizen's certificate #[arg(long, default_value = "./certs/myna_cert.pem")] verify_cert_path: String, + #[arg(short, long, default_value = "./build/verifier.sol")] + solidity_path: String, // nation's certificate #[arg(long, default_value = "./certs/ca_cert.pem")] issuer_cert_path: String, @@ -240,7 +242,14 @@ fn main() { ); assert!(result.is_ok(), "{:?}", result) } - Commands::GenerateSolidity { trusted_setup_path, pk_path, verify_cert_path, issuer_cert_path, password } => { + Commands::GenerateSolidity { + trusted_setup_path, + pk_path, + verify_cert_path, + issuer_cert_path, + password, + solidity_path, + } => { let circuit = circuit::ProofOfJapaneseResidence::new( issuer_cert_path.into(), verify_cert_path.into(), @@ -264,7 +273,7 @@ fn main() { &trusted_setup, &pk.get_vk(), circuit.halo2base.num_instance(), - Some(Path::new("./build/VerifyRsa.sol")), + Some(Path::new(&solidity_path)), ); println!("Size of the contract: {} bytes", deployment_code.len()); From 9d737335226906f091dcb1b353dfa680a90ef4dd Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Fri, 24 Nov 2023 02:40:40 +0900 Subject: [PATCH 18/28] bugfix: I've mistaken bytes as bits --- packages/halo2-circuits/src/circuit.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index 564781e..f7e1de8 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -47,7 +47,7 @@ const E: usize = 65537; pub const K: usize = 20; const LIMB_BITS: usize = 64; const SHA256_BLOCK_BITS: usize = 512; -const TBS_CERT_MAX_BITS: usize = 1 << 12; +const TBS_CERT_MAX_BITS: usize = 2048 * 8; pub fn bytes_to_biguint( ctx: &mut Context, @@ -159,6 +159,8 @@ impl Circuit for ProofOfJapaneseResidence { } fn synthesize(&self, config: Self::Config, mut layouter: impl Layouter) -> Result<(), Error> { + dbg!(self.tbs_cert.len()); + let mut assigned_blocks = Vec::new(); layouter.assign_region( || "SHA256", @@ -166,30 +168,29 @@ impl Circuit for ProofOfJapaneseResidence { assigned_blocks = config.sha256.multi_sha256( &mut region, vec![self.tbs_cert.clone()], - None, - // TODO: We should specify here the number of SHA256 blocks thats necessary to fit the input in - // but when I do so zkevm-hashes panics. Why?? Some(TBS_CERT_MAX_BITS / SHA256_BLOCK_BITS) + Some(TBS_CERT_MAX_BITS / SHA256_BLOCK_BITS), ); Ok(()) }, )?; // let mut final_block = None; - // for block in assigned_blocks.iter() { + // for (i, block) in assigned_blocks.iter().enumerate() { // block.is_final().value().map(|is_final| { // if Fr::zero() < is_final.evaluate() { // final_block = Some(block); // } // }); - // if let Some(_) = final_block { - // break; - // } + // // if let Some(_) = final_block { + // // dbg!(i); + // // break; + // // } // } // let final_block = final_block.expect("zkevm-hashes failed to generate a SHA256 hash"); - // dbg!(final_block.output()); - // TODO: Support longer inputs; + // The final block appears in [20] because of the length of certs/myna_cert.pem. + // TODO: Support pem with dynamic length. let final_block = &assigned_blocks[20]; // TODO: Hide these From b7b650c745bdf12b926168d7020beb792534a115 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sat, 25 Nov 2023 02:50:17 +0900 Subject: [PATCH 19/28] Generate an identity commitment --- packages/halo2-circuits/Cargo.lock | 10 + packages/halo2-circuits/Cargo.toml | 1 + packages/halo2-circuits/src/bin/cli.rs | 24 +- packages/halo2-circuits/src/circuit.rs | 426 +++++++++++-------------- 4 files changed, 211 insertions(+), 250 deletions(-) diff --git a/packages/halo2-circuits/Cargo.lock b/packages/halo2-circuits/Cargo.lock index e3a6b95..9087bde 100644 --- a/packages/halo2-circuits/Cargo.lock +++ b/packages/halo2-circuits/Cargo.lock @@ -1331,6 +1331,7 @@ dependencies = [ "num-bigint", "num-traits", "openssl", + "pse-poseidon", "rand", "rayon", "rsa", @@ -2250,6 +2251,15 @@ dependencies = [ "unarray", ] +[[package]] +name = "pse-poseidon" +version = "0.2.0" +source = "git+https://github.com/axiom-crypto/pse-poseidon.git#19d3b09481bda0e95e7c005906365d070fceb752" +dependencies = [ + "halo2curves-axiom", + "subtle", +] + [[package]] name = "quote" version = "1.0.33" diff --git a/packages/halo2-circuits/Cargo.toml b/packages/halo2-circuits/Cargo.toml index 42971b6..dc841a4 100644 --- a/packages/halo2-circuits/Cargo.toml +++ b/packages/halo2-circuits/Cargo.toml @@ -51,6 +51,7 @@ tokio = { version = "1.16", features = [ "rt-multi-thread", "macros", ] } +pse-poseidon = { git = "https://github.com/axiom-crypto/pse-poseidon.git" } [target.'cfg(target_family = "wasm")'.dependencies] getrandom = { version = "0.2", features = ["js"] } diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 8b7bb34..12c1c53 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -2,6 +2,7 @@ use clap::{Parser, Subcommand}; use halo2_base::{ gates::circuit::builder::BaseCircuitBuilder, halo2_proofs::{ + dev::MockProver, halo2curves::bn256::{Bn256, Fr, G1Affine}, plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, Circuit, ProvingKey, VerifyingKey}, poly::{ @@ -175,9 +176,7 @@ fn main() { verify_cert_path.into(), password.into(), ); - - let instance_columns = circuit.halo2base.instances(); - let instance_columns: Vec<&[Fr]> = instance_columns.iter().map(|xs| xs.as_slice()).collect(); + let instance_column = circuit.instance_column(); let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) @@ -201,7 +200,7 @@ fn main() { _, Keccak256Write>, _, - >(&trusted_setup, &pk, &[circuit], &[&instance_columns], OsRng, &mut proof) + >(&trusted_setup, &pk, &[circuit], &[&[&instance_column]], OsRng, &mut proof) .expect("prover should not fail"); proof.finalize(); println!("Proof generation finished at: {:?}", std::time::Instant::now()); @@ -213,9 +212,6 @@ fn main() { password.into(), ); - let instance_columns = circuit.halo2base.instances(); - let instance_columns: Vec<&[Fr]> = instance_columns.iter().map(|xs| xs.as_slice()).collect(); - let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) .expect("The trusted setup is corrupted"); @@ -238,7 +234,11 @@ fn main() { Keccak256Read<&File, G1Affine, Challenge255>, SingleStrategy<'_, Bn256>, >( - &trusted_setup, &vk, SingleStrategy::new(&trusted_setup), &[&instance_columns], &mut proof + &trusted_setup, + &vk, + SingleStrategy::new(&trusted_setup), + &[&[&circuit.instance_column()]], + &mut proof, ); assert!(result.is_ok(), "{:?}", result) } @@ -268,22 +268,22 @@ fn main() { ) .unwrap(); - let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, circuit.clone(), circuit.halo2base.instances()); + let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, circuit.clone(), vec![circuit.instance_column()]); let deployment_code = gen_evm_verifier_shplonk::>( &trusted_setup, &pk.get_vk(), - circuit.halo2base.num_instance(), + vec![circuit.instance_column().len()], Some(Path::new(&solidity_path)), ); println!("Size of the contract: {} bytes", deployment_code.len()); println!("Deploying contract..."); - evm_verify(deployment_code, circuit.halo2base.instances(), proof.clone()); + evm_verify(deployment_code, vec![circuit.instance_column()], proof.clone()); println!("Verification success!"); - write_calldata(&circuit.halo2base.instances(), &proof, Path::new("./build/calldata.txt")).unwrap(); + write_calldata(&[circuit.instance_column()], &proof, Path::new("./build/calldata.txt")).unwrap(); println!("Succesfully generate calldata!"); } } diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index f7e1de8..f79972c 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -11,6 +11,7 @@ use halo2_base::{ plonk::{Assignment, Circuit, ConstraintSystem, Error}, }, poseidon::hasher::{spec::OptimizedPoseidonSpec, PoseidonHasher}, + utils::halo2::Halo2AssignedCell, AssignedValue, Context, QuantumCell, }; use halo2_ecc::bigint::OverflowInteger; @@ -20,10 +21,9 @@ use halo2_rsa::{ }; use num_bigint::BigUint; use num_traits::One; -use sha2::{Digest, Sha256}; -use std::path::PathBuf; -use zkevm_hashes::sha256::vanilla::columns::Sha256CircuitConfig; -// use zkevm_hashes::Sha256Chip; +use pse_poseidon::Poseidon; +use std::{cmp::Ordering, path::PathBuf}; +use zkevm_hashes::sha256::vanilla::{columns::Sha256CircuitConfig, param::NUM_WORDS_TO_ABSORB}; #[derive(Debug, Clone)] pub struct PublicInput { @@ -49,80 +49,118 @@ const LIMB_BITS: usize = 64; const SHA256_BLOCK_BITS: usize = 512; const TBS_CERT_MAX_BITS: usize = 2048 * 8; -pub fn bytes_to_biguint( - ctx: &mut Context, - biguint_chip: BigUintConfig, - bytes: &[AssignedValue], -) -> AssignedBigUint { - let num_bases = (biguint_chip.limb_bits() / 8) as u64; - let bases: Vec> = - (0..num_bases).map(|i| QuantumCell::Constant(Fr::from(2).pow_vartime([i * 8]))).collect(); - let dest_limbs = bytes - .chunks(biguint_chip.limb_bits() / 8) - .map(|bytes_in_limb| { - let dest_limb = biguint_chip.gate().inner_product(ctx, bytes_in_limb.to_vec(), bases.clone()); - biguint_chip.range().range_check(ctx, dest_limb, biguint_chip.limb_bits()); - dest_limb - }) - .collect(); - - let bytes_in_rust: Vec = bytes.iter().map(|byte| byte.value().to_bytes()[0].clone()).collect(); - let dest_in_rust = BigUint::from_bytes_le(&bytes_in_rust); - AssignedBigUint::new(OverflowInteger::new(dest_limbs, biguint_chip.limb_bits()), dest_in_rust) -} - -pub fn bytes_to_64s( - ctx: &mut Context, - range_chip: RangeChip, - src: &[AssignedValue], -) -> Vec> { - // bug - let biguint_chip = BigUintConfig::construct(range_chip, 64); - bytes_to_biguint(ctx, biguint_chip, src).limbs().to_vec() -} - pub fn biguint_to_fr(src: BigUint) -> Fr { let mut buf = [0; 32]; buf[0..src.to_bytes_le().len()].copy_from_slice(&src.to_bytes_le()); Fr::from_bytes(&buf).expect("a BigUint was too big to fit in a Fr") } -pub fn split_each_limb( +pub fn slice_bits( ctx: &mut Context, range_chip: &RangeChip, - big_limbs: &[AssignedValue], - big_limb_bits: usize, - small_limb_bits: usize, + src_limbs: &[AssignedValue], + src_limb_width: usize, + dest_limb_width: usize, + since: usize, + until: usize, ) -> Vec> { - assert_eq!(0, big_limb_bits % small_limb_bits); - assert!(small_limb_bits < big_limb_bits); - - let limb_bases = (0..).map(|x| QuantumCell::Constant(biguint_to_fr(BigUint::one() << (x * small_limb_bits)))); - let mut small_limbs: Vec> = Vec::new(); - for big_limb in big_limbs { - let mut offset = 0; - while offset < big_limb_bits { - let small_limb = - (BigUint::from_bytes_le(&big_limb.value().to_bytes()) >> offset) % (BigUint::one() << small_limb_bits); - let small_limb = ctx.load_witness(biguint_to_fr(small_limb)); - range_chip.range_check(ctx, small_limb, small_limb_bits); - small_limbs.push(small_limb); - offset += small_limb_bits; + assert!(0 < src_limb_width); + assert!(0 < dest_limb_width); + assert!(254 > src_limb_width); + + assert!(254 > dest_limb_width); + let zero_part = (ctx.load_zero(), 0); + let mut parts: Vec<(AssignedValue, usize)> = Vec::new(); + + // split src into parts + let mut read_bits = since; + while read_bits < until { + let read_limbs = read_bits / src_limb_width; + let part_offset = read_bits % src_limb_width; + let part_width = (src_limb_width - read_bits % src_limb_width) + .min(dest_limb_width - (read_bits - since) % dest_limb_width) + .min(until - read_bits); + let part_biguint = (BigUint::from_bytes_le(&src_limbs[read_limbs].value().to_bytes()) >> part_offset) + % (BigUint::one() << part_width); + let part_witness = ctx.load_witness(biguint_to_fr(part_biguint)); + range_chip.range_check(ctx, part_witness, part_width); + parts.push((part_witness, part_width)); + read_bits += part_width; + } + + // constrain against dest + let mut dest_parts: Vec<(AssignedValue, usize)> = Vec::new(); + let mut dest_limbs: Vec> = Vec::new(); + for (i, part) in parts.iter().cloned().enumerate() { + dest_parts.push(part); + + if dest_parts.iter().map(|(_, part_width)| *part_width).sum::() == dest_limb_width + || i == parts.len() - 1 + { + let dest_limb = range_chip.gate().inner_product( + ctx, + dest_parts.iter().map(|(part_witness, _)| part_witness.clone()), + std::iter::once(&zero_part) + .chain(dest_parts.iter()) + .scan(BigUint::one(), |acc, (_, part_width)| { + *acc <<= *part_width; + Some(acc.clone()) + }) + .map(|part_base| QuantumCell::Constant(biguint_to_fr(part_base))), + ); + dest_limbs.push(dest_limb); + dest_parts.clear(); } + } - let small_to_big = range_chip.gate().inner_product( - ctx, - small_limbs - .iter() - .skip(small_limbs.len() - big_limb_bits / small_limb_bits) - .copied() - .map(QuantumCell::Existing), - limb_bases.clone(), - ); - ctx.constrain_equal(big_limb, &small_to_big); + // constrain against src + let first_part_width = since % src_limb_width; + if 0 < first_part_width { + let first_part_witness = ctx.load_witness(biguint_to_fr( + BigUint::from_bytes_le(&src_limbs[since / src_limb_width].value().to_bytes()) + % (BigUint::one() << first_part_width), + )); + parts.insert(0, (first_part_witness, first_part_width)); + } else { + parts.insert(0, zero_part.clone()); + }; + + let last_part_offset = until % src_limb_width; + if 0 < last_part_offset { + let last_part_witness = ctx.load_witness(biguint_to_fr( + BigUint::from_bytes_le(&src_limbs[until / src_limb_width].value().to_bytes()) >> last_part_offset, + )); + let last_part_width = src_limb_width - last_part_offset; + parts.push((last_part_witness, last_part_width)); + } else { + parts.push(zero_part.clone()); } - small_limbs + let mut src_parts: Vec<(AssignedValue, usize)> = Vec::new(); + let mut read_limbs = since / src_limb_width; + for part in parts { + src_parts.push(part); + + if src_parts.iter().map(|(_, part_width)| *part_width).sum::() == src_limb_width { + let src_limb = range_chip.gate().inner_product( + ctx, + src_parts.iter().map(|(part_witness, _)| part_witness.clone()), + std::iter::once(&zero_part) + .chain(src_parts.iter()) + .scan(BigUint::one(), |acc, (_, part_width)| { + *acc <<= *part_width; + Some(acc.clone()) + }) + .map(|part_base| QuantumCell::Constant(biguint_to_fr(part_base))), + ); + + ctx.constrain_equal(&src_limbs[read_limbs], &src_limb); + src_parts.clear(); + read_limbs += 1; + } + } + + dest_limbs } #[derive(Debug, Clone)] @@ -133,8 +171,13 @@ pub struct Config { #[derive(Debug, Clone)] pub struct ProofOfJapaneseResidence { - pub halo2base: BaseCircuitBuilder, pub tbs_cert: Vec, + // 2048 bits + pub nation_sig: BigUint, + // 2048 bits + pub nation_pubkey: BigUint, + pub user_secret: Fr, + pub citizen_pubkey: BigUint, } impl Circuit for ProofOfJapaneseResidence { @@ -147,7 +190,14 @@ impl Circuit for ProofOfJapaneseResidence { } fn params(&self) -> Self::Params { - self.halo2base.config_params.clone() + Self::Params { + k: K, + num_advice_per_phase: vec![1], + num_fixed: 1, + num_lookup_advice_per_phase: vec![1, 0, 0], + lookup_bits: Some(LOOKUP_BITS), + num_instance_columns: 1, + } } fn configure_with_params(meta: &mut ConstraintSystem, params: BaseCircuitParams) -> Self::Config { @@ -191,13 +241,54 @@ impl Circuit for ProofOfJapaneseResidence { // The final block appears in [20] because of the length of certs/myna_cert.pem. // TODO: Support pem with dynamic length. - let final_block = &assigned_blocks[20]; - - // TODO: Hide these - layouter.constrain_instance(final_block.output().lo().cell(), config.halo2base.instance[0], 0); - layouter.constrain_instance(final_block.output().hi().cell(), config.halo2base.instance[0], 1); - - self.halo2base.synthesize(config.halo2base, layouter).unwrap(); + let sha256out = &assigned_blocks[20].output(); + + let mut halo2base = BaseCircuitBuilder::new(false).use_params(self.params()); + let (sha256lo, sha256hi) = { + let mut lock = halo2base.core_mut().copy_manager.lock().unwrap(); + (lock.load_external_assigned(sha256out.lo()), lock.load_external_assigned(sha256out.hi())) + }; + let tbs_cert_32s: Vec> = { + let mut lock = halo2base.core_mut().copy_manager.lock().unwrap(); + assigned_blocks + .iter() + .flat_map(|assigned_block| { + assigned_block.word_values().clone().map(|cell| lock.load_external_assigned(cell)) + }) + .collect() + }; + + let range_chip = halo2base.range_chip(); + let ctx = halo2base.main(0); + + let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); + let rsa_chip = RSAConfig::construct(biguint_chip, RSA_KEY_SIZE, 5); + let mut poseidon = PoseidonHasher::new(OptimizedPoseidonSpec::::new::<8, 57, 0>()); + poseidon.initialize_consts(ctx, rsa_chip.gate()); + + // load public inputs + let nation_pubkey = rsa_chip + .assign_public_key(ctx, RSAPublicKey::new(self.nation_pubkey.clone(), RSAPubE::Fix(E.into()))) + .unwrap(); + + // load private inputs + let nation_sig = rsa_chip.assign_signature(ctx, RSASignature::new(self.nation_sig.clone())).unwrap(); + let user_secret = ctx.load_witness(self.user_secret); + + let sha256ed_64s = slice_bits(ctx, rsa_chip.range(), &[sha256lo, sha256hi], 128, 64, 0, 256); + let is_nation_sig_valid = + rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); + rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); + + let mut identity_commitment_preimage = vec![user_secret]; + let citizen_pubkey = + slice_bits(ctx, rsa_chip.range(), &tbs_cert_32s, 32, 253, PUBKEY_BEGINS, PUBKEY_BEGINS + RSA_KEY_SIZE); + identity_commitment_preimage.extend(citizen_pubkey); + let identity_commitment = poseidon.hash_fix_len_array(ctx, rsa_chip.gate(), &identity_commitment_preimage); + + halo2base.assigned_instances[0].extend(nation_pubkey.n.limbs().to_vec()); + halo2base.assigned_instances[0].push(identity_commitment); + halo2base.synthesize(config.halo2base, layouter).unwrap(); Ok(()) } @@ -206,128 +297,27 @@ impl Circuit for ProofOfJapaneseResidence { impl ProofOfJapaneseResidence { pub fn new(nation_cert_path: PathBuf, citizen_cert_path: PathBuf, user_secret: Fr) -> Self { let nation_pubkey = read_nation_cert(nation_cert_path.to_str().unwrap()); - let (nation_sig, tbs_cert, _citizen_pubkey) = read_citizen_cert(citizen_cert_path.to_str().unwrap()); - - let mut builder = BaseCircuitBuilder::new(false); - builder.set_k(K as usize); - builder.set_lookup_bits(LOOKUP_BITS); - builder.set_instance_columns(1); - let range_chip = builder.range_chip(); - let ctx = builder.main(0); - - let mut sha256ed = Sha256::digest(tbs_cert.to_bytes_le()); - sha256ed.reverse(); - let mut buf = [0; 32]; - buf[0..16].copy_from_slice(&sha256ed[0..16]); - let sha256lo = Fr::from_bytes(&buf).unwrap(); - buf[0..16].copy_from_slice(&sha256ed[16..32]); - let sha256hi = Fr::from_bytes(&buf).unwrap(); - - let public_input = PublicInput { sha256: [sha256lo, sha256hi], nation_pubkey }; - let private_input = PrivateInput { nation_sig, password: user_secret }; - let public_output = proof_of_japanese_residence(ctx, range_chip, public_input, private_input); - builder.assigned_instances[0].extend(public_output); - - let circuit_shape = builder.calculate_params(Some(K)); - Self { halo2base: builder.use_params(circuit_shape), tbs_cert: tbs_cert.to_bytes_le() } + let (nation_sig, tbs_cert, citizen_pubkey) = read_citizen_cert(citizen_cert_path.to_str().unwrap()); + + Self { tbs_cert: tbs_cert.to_bytes_le(), user_secret, nation_sig, nation_pubkey, citizen_pubkey } } -} -pub fn proof_of_japanese_residence( - ctx: &mut Context, - range_chip: RangeChip, - public: PublicInput, - private: PrivateInput, -) -> Vec> { - let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); - let rsa_chip = RSAConfig::construct(biguint_chip, RSA_KEY_SIZE, 5); - // let mut sha256_chip = - // Sha256Chip::construct(vec![SHA256_INPUT_BLOCKS * SHA256_BLOCK_BITS / 8], range_chip.clone(), true); - let mut poseidon = PoseidonHasher::new(OptimizedPoseidonSpec::::new::<8, 57, 0>()); - poseidon.initialize_consts(ctx, rsa_chip.gate()); - - let sha256lo = ctx.load_witness(public.sha256[0]); - let sha256hi = ctx.load_witness(public.sha256[1]); - - // load public inputs - let nation_pubkey = - rsa_chip.assign_public_key(ctx, RSAPublicKey::new(public.nation_pubkey, RSAPubE::Fix(E.into()))).unwrap(); - - // load private inputs - let nation_sig = rsa_chip.assign_signature(ctx, RSASignature::new(private.nation_sig)).unwrap(); - let password = ctx.load_witness(private.password); - - // extract citizen's public key from the tbs certificate - // let n = bytes_to_biguint( - // ctx, - // rsa_chip.biguint_config().clone(), - // &sha256ed.input_bytes[PUBKEY_BEGINS / 8..PUBKEY_BEGINS / 8 + RSA_KEY_SIZE / 8], - // ); - // let citizen_pubkey = AssignedRSAPublicKey::new(n.clone(), AssignedRSAPubE::Fix(E.into())); - - // let sha256ed = sha256_chip.digest(ctx, &private.tbs_cert, None).unwrap(); - // let identity_commitment_preimage: Vec> = sha256ed.input_bytes - // [PUBKEY_BEGINS / 8..(PUBKEY_BEGINS + RSA_KEY_SIZE) / 8] - // .iter() - // .copied() - // .chain(std::iter::once(password)) - // .collect(); - - // println!("sha256ed"); - // for byte in &sha256ed.input_bytes[PUBKEY_BEGINS / 8..(PUBKEY_BEGINS + RSA_KEY_SIZE) / 8] { - // let byte = byte.value().to_repr()[0]; - // print!("{:0b}", byte); - // } - - // let identity_commitment = poseidon.hash_fix_len_array(ctx, rsa_chip.gate(), &identity_commitment_preimage); - - // let sha256ed_64s = - // bytes_to_64s(ctx, range_chip.clone(), &sha256ed.output_bytes.iter().rev().copied().collect::>()); - - // assert_eq!( - // sha256ed_64s.iter().flat_map(|a| a.value().to_bytes()[0..8].to_vec()).collect::>(), - // Sha256::digest(private.tbs_cert).to_vec() - // ); - // println!("sha256ed_64s.len(): {}", sha256ed_64s.len()); - // for bytes in sha256ed_64s.iter() { - // let limbs = bytes.value().to_bytes(); - // for limb in limbs { - // print!("{:0b}", limb); - // } - // } - // println!("aa"); - - // let hashed_tbs = Sha256::digest(private.tbs_cert); - // println!("Hashed TBS: {:?}", hashed_tbs); - // let mut hashed_bytes: Vec> = - // hashed_tbs.iter().map(|limb| ctx.load_witness(Fr::from(*limb as u64))).collect(); - // hashed_bytes.reverse(); - // let bytes_bits = hashed_bytes.len() * 8; - // let limb_bits = 64; - // let limb_bytes = limb_bits / 8; - // let mut hashed_u64s = vec![]; - // let bases: Vec<_> = (0..limb_bytes).map(|i| Fr::from(1u64 << (8 * i))).map(QuantumCell::Constant).collect(); - // for i in 0..(bytes_bits / limb_bits) { - // let left: Vec<_> = - // hashed_bytes[limb_bytes * i..limb_bytes * (i + 1)].iter().map(|x| QuantumCell::Existing(*x)).collect(); - // let sum = rsa_chip.gate().inner_product(ctx, left, bases.clone()); - // hashed_u64s.push(sum); - // } - - // assert_eq!( - // sha256ed_64s.iter().map(|a| a.value()).collect::>(), - // hashed_u64s.iter().map(|a| a.value()).collect::>() - // ); - - let sha256ed_64s = split_each_limb(ctx, rsa_chip.range(), &[sha256lo, sha256hi], 128, 64); - let is_nation_sig_valid = - rsa_chip.verify_pkcs1v15_signature(ctx, &nation_pubkey, &sha256ed_64s, &nation_sig).unwrap(); - rsa_chip.biguint_config().gate().assert_is_const(ctx, &is_nation_sig_valid, &Fr::one()); - - let mut outputs = vec![sha256lo, sha256hi]; - // outputs.push(identity_commitment); - outputs.extend(nation_pubkey.n.limbs().to_vec()); - outputs + pub fn instance_column(&self) -> Vec { + let mut instance_column: Vec = self.nation_pubkey.iter_u64_digits().map(Fr::from).collect(); + let mut hasher = Poseidon::::new(8, 57); + let mut preimage = vec![self.user_secret]; + + for i in 0..=(2048 / 253) { + let limb = (self.citizen_pubkey.clone() >> (i * 253)) % (BigUint::one() << 253); + preimage.push(biguint_to_fr(limb)); + } + + hasher.update(&preimage); + let identity_commitment = hasher.squeeze(); + instance_column.push(identity_commitment); + + instance_column + } } #[cfg(test)] @@ -341,54 +331,14 @@ mod tests { use num_traits::cast::ToPrimitive; use sha2::Sha256; - // TODO: Write tests for failure cases - // #[test] - // fn extract_citizen_pubkey() { - // let (_, tbs_cert, expected_citizen_pubkey) = read_citizen_cert("certs/myna_cert.pem"); - // base_test().k(LOOKUP_BITS as u32).bench_builder((), (), |pool, range_chip, _| { - // let biguint_chip: BigUintConfig = BigUintConfig::construct(range_chip.clone(), LIMB_BITS); - // let tbs_cert = biguint_chip.assign_integer(pool.main(), &tbs_cert, 1 << 15).unwrap(); - // let expected = biguint_chip.assign_constant(pool.main(), expected_citizen_pubkey.clone()).unwrap(); - // let result = - // slice_biguint(pool.main(), &biguint_chip, tbs_cert, PUBKEY_BEGINS, PUBKEY_BEGINS + RSA_KEY_SIZE); - // let is_ok = biguint_chip.is_equal_fresh(pool.main(), &result, &expected).unwrap(); - // let one = pool.main().load_constant(Fr::one()); - // pool.main().constrain_equal(&is_ok, &one); - // }); - // } - - // #[test] - // fn aaa() { - // let two_pow_16 = Fr::from_raw([1 << 16, 0, 0, 0]); - // let mut test_subject = Fr::from_raw([0, 0, 0, 1 << 46]); - // while test_subject != Fr::zero() { - // for j in 1..16 { - // let k = test_subject * Fr::from_raw([1 << j, 0, 0, 0]); - // if two_pow_16 >= k { - // unreachable!("i:{:?},j:{:?},k:{:?}", test_subject.to_repr(), j, k.to_repr()); - // } - // } - - // test_subject += Fr::one(); - // } - // } - #[test] fn mock() { let circuit = ProofOfJapaneseResidence::new("./certs/ca_cert.pem".into(), "./certs/myna_cert.pem".into(), 0xA42.into()); + let instance_column = circuit.instance_column(); - MockProver::run( - K as u32, - &circuit, - circuit - .halo2base - .assigned_instances - .iter() - .map(|public_column| public_column.into_iter().map(|public_cell| public_cell.value().clone()).collect()) - .collect(), - ) - .expect("The circuit generation failed") - .assert_satisfied(); + MockProver::run(K as u32, &circuit, vec![instance_column]) + .expect("The circuit generation failed") + .assert_satisfied(); } } From b29f173c803b5799d70184e7000f0d3aea1f6252 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sat, 25 Nov 2023 18:46:33 +0900 Subject: [PATCH 20/28] Reduce K --- packages/halo2-circuits/src/circuit.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index f79972c..4ef77d0 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -40,11 +40,11 @@ pub struct PrivateInput { pub password: Fr, } -pub const LOOKUP_BITS: usize = 16; const RSA_KEY_SIZE: usize = 2048; const PUBKEY_BEGINS: usize = 2216; const E: usize = 65537; -pub const K: usize = 20; +pub const K: usize = 17; +pub const LOOKUP_BITS: usize = K - 1; const LIMB_BITS: usize = 64; const SHA256_BLOCK_BITS: usize = 512; const TBS_CERT_MAX_BITS: usize = 2048 * 8; From 5d3482a1bb0b6af6acffd622dc74d1867102f59d Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sat, 25 Nov 2023 19:58:51 +0900 Subject: [PATCH 21/28] Store the generated calldata in a file --- packages/halo2-circuits/src/bin/cli.rs | 12 ++++-------- packages/halo2-circuits/src/circuit.rs | 2 +- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 12c1c53..1f55517 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -123,6 +123,8 @@ enum Commands { verify_cert_path: String, #[arg(short, long, default_value = "./build/verifier.sol")] solidity_path: String, + #[arg(short, long, default_value = "./build/calldata.txt")] + calldata_path: String, // nation's certificate #[arg(long, default_value = "./certs/ca_cert.pem")] issuer_cert_path: String, @@ -249,6 +251,7 @@ fn main() { issuer_cert_path, password, solidity_path, + calldata_path, } => { let circuit = circuit::ProofOfJapaneseResidence::new( issuer_cert_path.into(), @@ -276,15 +279,8 @@ fn main() { Some(Path::new(&solidity_path)), ); - println!("Size of the contract: {} bytes", deployment_code.len()); - println!("Deploying contract..."); - + write_calldata(&[circuit.instance_column()], &proof, Path::new(&calldata_path)).unwrap(); evm_verify(deployment_code, vec![circuit.instance_column()], proof.clone()); - - println!("Verification success!"); - - write_calldata(&[circuit.instance_column()], &proof, Path::new("./build/calldata.txt")).unwrap(); - println!("Succesfully generate calldata!"); } } } diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index 4ef77d0..a048e57 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -192,7 +192,7 @@ impl Circuit for ProofOfJapaneseResidence { fn params(&self) -> Self::Params { Self::Params { k: K, - num_advice_per_phase: vec![1], + num_advice_per_phase: vec![3], num_fixed: 1, num_lookup_advice_per_phase: vec![1, 0, 0], lookup_bits: Some(LOOKUP_BITS), From 36869e8749af815592f545f8c466697e6d3e9d40 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sun, 26 Nov 2023 17:27:47 +0900 Subject: [PATCH 22/28] Use BufWriter --- packages/halo2-circuits/src/bin/cli.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 1f55517..2f13660 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -33,7 +33,7 @@ use std::{ env, fmt::Binary, fs::{remove_file, File}, - io::{Read, Write}, + io::{BufWriter, Read, Write}, path::{Path, PathBuf}, }; @@ -193,19 +193,21 @@ fn main() { .unwrap(); let proof_file = File::create(proof_path).unwrap(); - println!("Proof generation started at: {:?}", std::time::Instant::now()); - let mut proof = Keccak256Write::<_, _, Challenge255<_>>::init(proof_file); + + let started_at = std::time::Instant::now(); + println!("Proof generation started at: {:?}", started_at); + let mut proof = Keccak256Write::<_, _, Challenge255<_>>::init(BufWriter::new(proof_file)); create_proof::< KZGCommitmentScheme, ProverSHPLONK<'_, Bn256>, Challenge255, _, - Keccak256Write>, + Keccak256Write, G1Affine, Challenge255<_>>, _, >(&trusted_setup, &pk, &[circuit], &[&[&instance_column]], OsRng, &mut proof) .expect("prover should not fail"); proof.finalize(); - println!("Proof generation finished at: {:?}", std::time::Instant::now()); + println!("Proof generation took: {:?}", started_at.elapsed()); } Commands::Verify { trusted_setup_path, vk_path, proof_path, verify_cert_path, issuer_cert_path, password } => { let circuit = circuit::ProofOfJapaneseResidence::new( @@ -271,7 +273,11 @@ fn main() { ) .unwrap(); + let started_at = std::time::Instant::now(); + println!("Proof generation started at: {:?}", started_at); let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, circuit.clone(), vec![circuit.instance_column()]); + println!("Proof generation took: {:?}", started_at.elapsed()); + let deployment_code = gen_evm_verifier_shplonk::>( &trusted_setup, &pk.get_vk(), From e927353ee5945d0ae222ba309d181187f4589f5a Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Sun, 26 Nov 2023 18:02:50 +0900 Subject: [PATCH 23/28] Make the RSA circuit take the same height as the SHA256 circuit which is k=12 --- packages/halo2-circuits/src/circuit.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index a048e57..e85c848 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -43,7 +43,7 @@ pub struct PrivateInput { const RSA_KEY_SIZE: usize = 2048; const PUBKEY_BEGINS: usize = 2216; const E: usize = 65537; -pub const K: usize = 17; +pub const K: usize = 12; pub const LOOKUP_BITS: usize = K - 1; const LIMB_BITS: usize = 64; const SHA256_BLOCK_BITS: usize = 512; @@ -192,9 +192,9 @@ impl Circuit for ProofOfJapaneseResidence { fn params(&self) -> Self::Params { Self::Params { k: K, - num_advice_per_phase: vec![3], + num_advice_per_phase: vec![101], num_fixed: 1, - num_lookup_advice_per_phase: vec![1, 0, 0], + num_lookup_advice_per_phase: vec![6, 0, 0], lookup_bits: Some(LOOKUP_BITS), num_instance_columns: 1, } @@ -288,6 +288,8 @@ impl Circuit for ProofOfJapaneseResidence { halo2base.assigned_instances[0].extend(nation_pubkey.n.limbs().to_vec()); halo2base.assigned_instances[0].push(identity_commitment); + + dbg!(halo2base.calculate_params(None)); halo2base.synthesize(config.halo2base, layouter).unwrap(); Ok(()) From 5fe5e523ff903df26bb9beb56627d45845cb6ae1 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Tue, 28 Nov 2023 16:31:18 +0900 Subject: [PATCH 24/28] Refactoring --- packages/halo2-circuits/src/circuit.rs | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index e85c848..6d94f26 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -244,19 +244,17 @@ impl Circuit for ProofOfJapaneseResidence { let sha256out = &assigned_blocks[20].output(); let mut halo2base = BaseCircuitBuilder::new(false).use_params(self.params()); - let (sha256lo, sha256hi) = { - let mut lock = halo2base.core_mut().copy_manager.lock().unwrap(); - (lock.load_external_assigned(sha256out.lo()), lock.load_external_assigned(sha256out.hi())) - }; - let tbs_cert_32s: Vec> = { - let mut lock = halo2base.core_mut().copy_manager.lock().unwrap(); - assigned_blocks - .iter() - .flat_map(|assigned_block| { - assigned_block.word_values().clone().map(|cell| lock.load_external_assigned(cell)) - }) - .collect() - }; + + let mut lock = halo2base.core_mut().copy_manager.lock().unwrap(); + let sha256lo = lock.load_external_assigned(sha256out.lo()); + let sha256hi = lock.load_external_assigned(sha256out.hi()); + let tbs_cert_32s: Vec> = assigned_blocks + .iter() + .flat_map(|assigned_block| { + assigned_block.word_values().clone().map(|cell| lock.load_external_assigned(cell)) + }) + .collect(); + std::mem::drop(lock); let range_chip = halo2base.range_chip(); let ctx = halo2base.main(0); From cfc2537f80a1c999870df82e428a6676f6460746 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Wed, 29 Nov 2023 19:12:12 +0900 Subject: [PATCH 25/28] Stop depending on my local files --- Cargo.lock | 336 +++++++++++++++++++++++++---- packages/halo2-circuits/Cargo.toml | 29 +-- 2 files changed, 300 insertions(+), 65 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e5611f9..f9e2aca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -187,6 +187,110 @@ version = "1.0.75" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" +[[package]] +name = "ark-ff" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b3235cc41ee7a12aaaf2c575a2ad7b46713a8a50bda2fc3b003a04845c05dd6" +dependencies = [ + "ark-ff-asm 0.3.0", + "ark-ff-macros 0.3.0", + "ark-serialize 0.3.0", + "ark-std 0.3.0", + "derivative", + "num-bigint", + "num-traits", + "paste", + "rustc_version 0.3.3", + "zeroize", +] + +[[package]] +name = "ark-ff" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec847af850f44ad29048935519032c33da8aa03340876d351dfab5660d2966ba" +dependencies = [ + "ark-ff-asm 0.4.2", + "ark-ff-macros 0.4.2", + "ark-serialize 0.4.2", + "ark-std 0.4.0", + "derivative", + "digest 0.10.7", + "itertools 0.10.5", + "num-bigint", + "num-traits", + "paste", + "rustc_version 0.4.0", + "zeroize", +] + +[[package]] +name = "ark-ff-asm" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db02d390bf6643fb404d3d22d31aee1c4bc4459600aef9113833d17e786c6e44" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-asm" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ed4aa4fe255d0bc6d79373f7e31d2ea147bcf486cba1be5ba7ea85abdb92348" +dependencies = [ + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-macros" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" +dependencies = [ + "num-bigint", + "num-traits", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-ff-macros" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" +dependencies = [ + "num-bigint", + "num-traits", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "ark-serialize" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d6c2b318ee6e10f8c2853e73a83adc0ccb88995aa978d8a3408d492ab2ee671" +dependencies = [ + "ark-std 0.3.0", + "digest 0.9.0", +] + +[[package]] +name = "ark-serialize" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb7b85a02b83d2f22f89bd5cac66c9c89474240cb6207cb1efc16d098e822a5" +dependencies = [ + "ark-std 0.4.0", + "digest 0.10.7", + "num-bigint", +] + [[package]] name = "ark-std" version = "0.3.0" @@ -198,6 +302,22 @@ dependencies = [ "rand", ] +[[package]] +name = "ark-std" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" +dependencies = [ + "num-traits", + "rand", +] + +[[package]] +name = "array-init" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d62b7694a562cdf5a74227903507c56ab2cc8bdd1f781ed5cb4cf9c9f810bfc" + [[package]] name = "arrayref" version = "0.3.7" @@ -293,7 +413,7 @@ checksum = "b6d7b9decdf35d8908a7e3ef02f64c5e9b1695e230154c0e8de3969142d9b94c" dependencies = [ "futures", "pharos", - "rustc_version", + "rustc_version 0.4.0", ] [[package]] @@ -671,7 +791,7 @@ checksum = "e7daec1a2a2129eeba1644b220b4647ec537b0b5d4bfd6876fcc5a540056b592" dependencies = [ "camino", "cargo-platform", - "semver", + "semver 1.0.20", "serde", "serde_json", "thiserror", @@ -1207,6 +1327,17 @@ dependencies = [ "powerfmt", ] +[[package]] +name = "derivative" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "derive_more" version = "0.99.17" @@ -1216,7 +1347,7 @@ dependencies = [ "convert_case", "proc-macro2", "quote", - "rustc_version", + "rustc_version 0.4.0", "syn 1.0.109", ] @@ -1636,7 +1767,7 @@ checksum = "0e53451ea4a8128fbce33966da71132cf9e1040dcfd2a2084fd7733ada7b2045" dependencies = [ "ethers-core", "reqwest", - "semver", + "semver 1.0.20", "serde", "serde_json", "thiserror", @@ -1745,7 +1876,7 @@ dependencies = [ "path-slash", "rayon", "regex", - "semver", + "semver 1.0.20", "serde", "serde_json", "solang-parser", @@ -1774,6 +1905,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +[[package]] +name = "fastrlp" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139834ddba373bbdd213dffe02c8d110508dcf1726c2be27e8d1f7d7e1856418" +dependencies = [ + "arrayvec", + "auto_impl", + "bytes", +] + [[package]] name = "ff" version = "0.13.0" @@ -2073,16 +2215,37 @@ version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" +[[package]] +name = "halo2-axiom" +version = "0.4.1" +source = "git+https://github.com/axiom-crypto/halo2.git#f335ffc4440620e3afaa5ba3373764b60a528c51" +dependencies = [ + "blake2b_simd", + "crossbeam", + "ff", + "group", + "halo2curves-axiom", + "itertools 0.11.0", + "maybe-rayon", + "pairing", + "rand", + "rand_core", + "rustc-hash", + "sha3 0.10.8", + "tracing", +] + [[package]] name = "halo2-base" version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition#262f5c5e074fbbb88c9decf5516568c12413ab94" +source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#6f924e7b8a9fad7d84a6238c1f0095cb337ce4c5" dependencies = [ - "ark-std", + "ark-std 0.3.0", "getset", - "halo2_proofs 0.2.0 (git+https://github.com/privacy-scaling-explorations/halo2.git?rev=7a21656)", - "halo2_proofs 0.2.0 (git+https://github.com/axiom-crypto/halo2.git)", + "halo2-axiom", + "halo2_proofs", "itertools 0.11.0", + "jemallocator", "log", "num-bigint", "num-integer", @@ -2114,6 +2277,7 @@ dependencies = [ "num-bigint", "num-traits", "openssl", + "pse-poseidon", "rand", "rayon", "rsa", @@ -2123,12 +2287,13 @@ dependencies = [ "snark-verifier-sdk", "tokio", "x509-parser", + "zkevm-hashes", ] [[package]] name = "halo2-ecc" version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2-lib.git?branch=community-edition#262f5c5e074fbbb88c9decf5516568c12413ab94" +source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#6f924e7b8a9fad7d84a6238c1f0095cb337ce4c5" dependencies = [ "halo2-base", "itertools 0.10.5", @@ -2147,7 +2312,7 @@ dependencies = [ [[package]] name = "halo2-rsa" version = "0.1.0" -source = "git+https://github.com/MynaWallet/halo2-rsa.git?branch=main#231d5421011276dfb7d6a6f84144a2dea9c9e3fe" +source = "git+https://github.com/MynaWallet/halo2-rsa.git#7a2a439d76f4c5bffad34a203ab8504428e098f0" dependencies = [ "env_logger", "halo2-base", @@ -2162,7 +2327,7 @@ dependencies = [ [[package]] name = "halo2-sha256-unoptimized" version = "0.1.0" -source = "git+https://github.com/zkpdf/halo2-sha256-unoptimized.git?branch=main#ec2d2b28cdb7dd38cb9896b09720d09923fcc2f2" +source = "git+https://github.com/MynaWallet/halo2-sha256-unoptimized.git#6cc3f01cbd25d10d6ada64f9710b7e109041cda2" dependencies = [ "console_error_panic_hook", "env_logger", @@ -2188,7 +2353,7 @@ dependencies = [ "blake2b_simd", "ff", "group", - "halo2curves 0.1.0", + "halo2curves", "maybe-rayon", "rand_chacha", "rand_core", @@ -2196,25 +2361,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "halo2_proofs" -version = "0.2.0" -source = "git+https://github.com/axiom-crypto/halo2.git#4b42325623c9cfea02441ce0cffa17ebf962b3bb" -dependencies = [ - "blake2b_simd", - "crossbeam", - "ff", - "group", - "halo2curves 0.4.0", - "maybe-rayon", - "pairing", - "rand", - "rand_core", - "rustc-hash", - "sha3 0.10.8", - "tracing", -] - [[package]] name = "halo2curves" version = "0.1.0" @@ -2236,9 +2382,10 @@ dependencies = [ ] [[package]] -name = "halo2curves" -version = "0.4.0" -source = "git+https://github.com/axiom-crypto/halo2curves.git?branch=main#e185711b6ba8f3e22f2af8bf24a5fc84b781ca46" +name = "halo2curves-axiom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d82f25182a221a5c79ce8d41d1dd3910f10626d7e9d0f9f9e9336e2545b7d1f" dependencies = [ "blake2b_simd", "ff", @@ -2605,6 +2752,26 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +[[package]] +name = "jemalloc-sys" +version = "0.5.4+5.3.0-patched" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac6c1946e1cea1788cbfde01c993b52a10e2da07f4bac608228d1bed20bfebf2" +dependencies = [ + "cc", + "libc", +] + +[[package]] +name = "jemallocator" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0de374a9f8e63150e6f5e8a60cc14c668226d7a347d8aee1a45766e3c4dd3bc" +dependencies = [ + "jemalloc-sys", + "libc", +] + [[package]] name = "jobserver" version = "0.1.27" @@ -3283,6 +3450,17 @@ version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" +[[package]] +name = "pest" +version = "2.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae9cee2a55a544be8b89dc6848072af97a20f2422603c10865be2a42b580fff5" +dependencies = [ + "memchr", + "thiserror", + "ucd-trie", +] + [[package]] name = "petgraph" version = "0.6.4" @@ -3300,7 +3478,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e9567389417feee6ce15dd6527a8a1ecac205ef62c2932bcf3d9f6fc5b78b414" dependencies = [ "futures", - "rustc_version", + "rustc_version 0.4.0", ] [[package]] @@ -3558,13 +3736,24 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c003ac8c77cb07bb74f5f198bce836a689bcd5a42574612bf14d17bfd08c20e" dependencies = [ "bitflags 2.4.1", + "lazy_static", "num-traits", "rand", "rand_chacha", "rand_xorshift", + "regex-syntax 0.7.5", "unarray", ] +[[package]] +name = "pse-poseidon" +version = "0.2.0" +source = "git+https://github.com/axiom-crypto/pse-poseidon.git#19d3b09481bda0e95e7c005906365d070fceb752" +dependencies = [ + "halo2curves-axiom", + "subtle", +] + [[package]] name = "quote" version = "1.0.33" @@ -3906,8 +4095,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95294d6e3a6192f3aabf91c38f56505a625aa495533442744185a36d75a790c4" dependencies = [ "alloy-rlp", + "ark-ff 0.3.0", + "ark-ff 0.4.2", + "bytes", + "fastrlp", + "num-bigint", + "parity-scale-codec", + "primitive-types", "proptest", "rand", + "rlp", "ruint-macro", "serde", "valuable", @@ -3973,13 +4170,22 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e75f6a532d0fd9f7f13144f392b6ad56a32696bfcd9c78f797f16bbb6f072d6" +[[package]] +name = "rustc_version" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0dfe2087c51c460008730de8b57e6a320782fbfb312e1f4d520e6c6fae155ee" +dependencies = [ + "semver 0.11.0", +] + [[package]] name = "rustc_version" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" dependencies = [ - "semver", + "semver 1.0.20", ] [[package]] @@ -4149,6 +4355,15 @@ dependencies = [ "cc", ] +[[package]] +name = "semver" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" +dependencies = [ + "semver-parser", +] + [[package]] name = "semver" version = "1.0.20" @@ -4158,6 +4373,15 @@ dependencies = [ "serde", ] +[[package]] +name = "semver-parser" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" +dependencies = [ + "pest", +] + [[package]] name = "send_wrapper" version = "0.4.0" @@ -4373,7 +4597,7 @@ dependencies = [ [[package]] name = "snark-verifier" version = "0.1.6" -source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=community-edition#7011e8ce0c2f7e79ab9629aa528cfb6837cdeafe" +source = "git+https://github.com/MynaWallet/snark-verifier.git?branch=release-0.1.6-rc0#fe8d0005c6146a03cc1c01cffc1f955ff73ba639" dependencies = [ "halo2-base", "halo2-ecc", @@ -4386,6 +4610,7 @@ dependencies = [ "pairing", "rand", "revm", + "ruint", "serde", "sha3 0.10.8", ] @@ -4393,15 +4618,15 @@ dependencies = [ [[package]] name = "snark-verifier-sdk" version = "0.1.6" -source = "git+https://github.com/axiom-crypto/snark-verifier.git?branch=community-edition#7011e8ce0c2f7e79ab9629aa528cfb6837cdeafe" +source = "git+https://github.com/MynaWallet/snark-verifier.git?branch=release-0.1.6-rc0#fe8d0005c6146a03cc1c01cffc1f955ff73ba639" dependencies = [ - "ark-std", + "ark-std 0.3.0", "bincode", "ethereum-types", "getset", "halo2-base", "hex", - "itertools 0.10.5", + "itertools 0.11.0", "lazy_static", "num-bigint", "num-integer", @@ -4550,7 +4775,7 @@ dependencies = [ "hex", "once_cell", "reqwest", - "semver", + "semver 1.0.20", "serde", "serde_json", "sha2", @@ -5072,6 +5297,12 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +[[package]] +name = "ucd-trie" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" + [[package]] name = "uint" version = "0.9.5" @@ -5596,7 +5827,7 @@ dependencies = [ "js-sys", "log", "pharos", - "rustc_version", + "rustc_version 0.4.0", "send_wrapper 0.6.0", "thiserror", "wasm-bindgen", @@ -5697,6 +5928,25 @@ dependencies = [ "zstd 0.11.2+zstd.1.5.2", ] +[[package]] +name = "zkevm-hashes" +version = "0.2.0" +source = "git+https://github.com/MynaWallet/halo2-lib.git?branch=sha256#6f924e7b8a9fad7d84a6238c1f0095cb337ce4c5" +dependencies = [ + "array-init", + "ethers-core", + "getset", + "halo2-base", + "itertools 0.11.0", + "lazy_static", + "log", + "num-bigint", + "rand", + "rayon", + "sha3 0.10.8", + "snark-verifier", +] + [[package]] name = "zstd" version = "0.11.2+zstd.1.5.2" diff --git a/packages/halo2-circuits/Cargo.toml b/packages/halo2-circuits/Cargo.toml index dc841a4..a2ef8ba 100644 --- a/packages/halo2-circuits/Cargo.toml +++ b/packages/halo2-circuits/Cargo.toml @@ -11,30 +11,17 @@ num-bigint = { version = "0.4", features = ["rand"] } sha2 = "0.10.6" rand = "0.8.5" rsa = { version = "0.6.1", features = ["serde"] } -halo2-rsa = { default-features = false, features = [ - "halo2-axiom", - "display", -], path = "../../../halo2-rsa" } -halo2-base = { default-features = false, features = [ - "halo2-axiom", - "display", - "test-utils", -], path = "../../../halo2-lib/halo2-base" } -halo2-ecc = { default-features = false, features = [ - "halo2-axiom", - "display", -], path = "../../../halo2-lib/halo2-ecc" } -zkevm-hashes = { default-features = false, features = [ - "halo2-axiom", - "display", -], path = "../../../halo2-lib/hashes/zkevm" } +halo2-rsa = { git = "https://github.com/MynaWallet/halo2-rsa.git" } +halo2-base = { git = "https://github.com/MynaWallet/halo2-lib.git", branch = "sha256" } +halo2-ecc = { git = "https://github.com/MynaWallet/halo2-lib.git", branch = "sha256" } +zkevm-hashes = { git = "https://github.com/MynaWallet/halo2-lib.git", branch = "sha256" } snark-verifier-sdk = { default-features = false, features = [ "halo2-axiom", "display", "loader_evm", "loader_halo2", "revm" -], path = "../../../snark-verifier/snark-verifier-sdk" } +], git = "https://github.com/MynaWallet/snark-verifier.git", branch = "release-0.1.6-rc0" } x509-parser = { version = "0.15", features = ["verify"] } openssl = "0.10" num-traits = "0.2.15" @@ -52,6 +39,7 @@ tokio = { version = "1.16", features = [ "macros", ] } pse-poseidon = { git = "https://github.com/axiom-crypto/pse-poseidon.git" } +halo2-sha256-unoptimized = { git = "https://github.com/MynaWallet/halo2-sha256-unoptimized.git" } [target.'cfg(target_family = "wasm")'.dependencies] getrandom = { version = "0.2", features = ["js"] } @@ -67,7 +55,4 @@ criterion = "0.4" default = ["halo2-axiom", "display"] display = ["halo2-base/display"] halo2-pse = ["halo2-base/halo2-pse"] -halo2-axiom = ["halo2-base/halo2-axiom"] - -[workspace] -resolver = "2" \ No newline at end of file +halo2-axiom = ["halo2-base/halo2-axiom"] \ No newline at end of file From 96fbf5a0e170c02aed3e6918e40ab273f9ec9dc7 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Thu, 7 Dec 2023 17:20:15 +0900 Subject: [PATCH 26/28] Implement CircuitExt --- packages/halo2-circuits/src/circuit.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index 6d94f26..915a676 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -8,7 +8,7 @@ use halo2_base::{ arithmetic::Field, circuit::{Layouter, SimpleFloorPlanner}, halo2curves::bn256::Fr, - plonk::{Assignment, Circuit, ConstraintSystem, Error}, + plonk::{Assignment, Circuit, ConstraintSystem, Error, Selector}, }, poseidon::hasher::{spec::OptimizedPoseidonSpec, PoseidonHasher}, utils::halo2::Halo2AssignedCell, @@ -22,6 +22,7 @@ use halo2_rsa::{ use num_bigint::BigUint; use num_traits::One; use pse_poseidon::Poseidon; +use snark_verifier_sdk::CircuitExt; use std::{cmp::Ordering, path::PathBuf}; use zkevm_hashes::sha256::vanilla::{columns::Sha256CircuitConfig, param::NUM_WORDS_TO_ABSORB}; @@ -320,6 +321,27 @@ impl ProofOfJapaneseResidence { } } +impl CircuitExt for ProofOfJapaneseResidence { + /// Return the number of instances of the circuit. + /// This may depend on extra circuit parameters but NOT on private witnesses. + fn num_instance(&self) -> Vec { + vec![self.instance_column().len()] + } + + fn instances(&self) -> Vec> { + vec![self.instance_column()] + } + + fn accumulator_indices() -> Option> { + None + } + + /// Output the simple selector columns (before selector compression) of the circuit + fn selectors(config: &Self::Config) -> Vec { + config.halo2base.gate().basic_gates[0].iter().map(|basic| basic.q_enable).collect() + } +} + #[cfg(test)] mod tests { use super::*; From 3186cdeef3af7290069afd991cc89aa192e48e95 Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Fri, 8 Dec 2023 20:00:28 +0900 Subject: [PATCH 27/28] Refactor CLI --- packages/halo2-circuits/README.md | 22 +- packages/halo2-circuits/src/bin/cli.rs | 352 ++++++++++++++----------- 2 files changed, 216 insertions(+), 158 deletions(-) diff --git a/packages/halo2-circuits/README.md b/packages/halo2-circuits/README.md index b162acc..6d0f26d 100644 --- a/packages/halo2-circuits/README.md +++ b/packages/halo2-circuits/README.md @@ -58,22 +58,32 @@ You can refer to these repos of RSA verification circuits. - [zkCert](https://github.com/zkCert/halo2-zkcert) ## Example Usage +### Create the directory where proofs are stored +```bash +mkdir -p build/{app,agg} +``` +### Generate the common reference string +```bash +cargo run trusted-setup +``` +### Generate pk & vk ```bash -# `k`: degree that expresses the size of circuit (i.e., 2^k is the number of rows in the circuit) -cargo run -r gen-params --k 17 +cargo run app keys ``` +### Generate a proof ```bash -cargo run -r gen-rsa-keys # generate pk +cargo run app prove ``` +### Run the verification code written in Rust ```bash -cargo run -r prove-rsa # verify rsa locally +cargo run app verify ``` -You need to install solc 0.8.19 or 0.8.20 locally. +### Run the verification code written in Solidity ```bash -cargo run -r gen-rsa-verify-evm-proof # generate a verifier contract and proof inputs for evm +cargo run app evm ``` diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 2f13660..0979a93 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -1,6 +1,6 @@ use clap::{Parser, Subcommand}; use halo2_base::{ - gates::circuit::builder::BaseCircuitBuilder, + gates::circuit::{builder::BaseCircuitBuilder, CircuitBuilderStage}, halo2_proofs::{ dev::MockProver, halo2curves::bn256::{Bn256, Fr, G1Affine}, @@ -10,7 +10,7 @@ use halo2_base::{ kzg::{ commitment::{KZGCommitmentScheme, ParamsKZG}, multiopen::{ProverSHPLONK, VerifierSHPLONK}, - strategy::SingleStrategy, + strategy::{AccumulatorStrategy, SingleStrategy}, }, }, transcript::{Challenge255, Keccak256Read, Keccak256Write, TranscriptReadBuffer, TranscriptWriterBuffer}, @@ -26,8 +26,12 @@ use rand::rngs::OsRng; use sha2::{Digest, Sha256}; use snark_verifier_sdk::{ evm::{evm_verify, gen_evm_proof_shplonk, gen_evm_verifier_shplonk, write_calldata}, + halo2::{ + aggregation::{AggregationCircuit, AggregationConfigParams, VerifierUniversality}, + gen_snark_shplonk, + }, snark_verifier::system::halo2::transcript::evm::EvmTranscript, - CircuitExt, + CircuitExt, SHPLONK, }; use std::{ env, @@ -52,35 +56,105 @@ enum Commands { #[arg(short, long, default_value = "./build/trusted_setup")] trusted_setup_path: String, }, + #[command(subcommand)] + App(AppCommands), + #[command(subcommand)] + Agg(AggCommands), +} + +#[derive(Debug, Subcommand, Clone)] +enum AppCommands { /// Generate the proving key and the verification key for RSA circuit - GenerateKeys { + Keys { /// trusted setup parameters path. input #[arg(short, long, default_value = "./build/trusted_setup")] trusted_setup_path: String, /// proving key path. output - #[arg(long, default_value = "./build/vk")] + #[arg(long, default_value = "./build/app/vk")] vk_path: String, /// proving key path. output - #[arg(long, default_value = "./build/pk")] + #[arg(long, default_value = "./build/app/pk")] pk_path: String, - // citizen's certificate + }, + Prove { + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./build/trusted_setup")] + trusted_setup_path: String, + /// proving key path. input + #[arg(long, default_value = "./build/app/pk")] + pk_path: String, + /// proof path. output + #[arg(long, default_value = "./build/app/proof")] + proof_path: String, + // citizen's certificate. input #[arg(long, default_value = "./certs/myna_cert.pem")] verify_cert_path: String, - // nation's certificate + // nation's certificate. input #[arg(long, default_value = "./certs/ca_cert.pem")] issuer_cert_path: String, #[arg(default_value = "42")] password: u64, }, + Verify { + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./build/trusted_setup")] + trusted_setup_path: String, + /// verification key path. input + #[arg(long, default_value = "./build/app/vk")] + vk_path: String, + /// proof path. input + #[arg(long, default_value = "./build/app/proof")] + proof_path: String, + // citizen's certificate. inut + #[arg(long, default_value = "./certs/myna_cert.pem")] + verify_cert_path: String, + // nation's certificate. input + #[arg(long, default_value = "./certs/ca_cert.pem")] + issuer_cert_path: String, + #[arg(default_value = "42")] + password: u64, + }, + Evm { + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./build/trusted_setup")] + trusted_setup_path: String, + /// verification key path. input + #[arg(long, default_value = "./build/app/pk")] + vk_path: String, + /// proof path. input + #[arg(long, default_value = "./build/app/proof")] + proof_path: String, + /// verifier.sol path. output + #[arg(short, long, default_value = "./build/app/verifier.sol")] + solidity_path: String, + /// calldata path. output + #[arg(long, default_value = "./build/app/calldata.txt")] + calldata_path: String, + }, +} + +#[derive(Debug, Subcommand, Clone)] +enum AggCommands { + Keys { + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./build/trusted_setup")] + trusted_setup_path: String, + /// proving key path. output + #[arg(long, default_value = "./build/agg/vk")] + vk_path: String, + /// proving key path. output + #[arg(long, default_value = "./build/agg/pk")] + pk_path: String, + }, Prove { /// trusted setup parameters path. input #[arg(short, long, default_value = "./build/trusted_setup")] trusted_setup_path: String, /// proving key path. output - #[arg(long, default_value = "./build/pk")] + #[arg(long, default_value = "./build/agg/pk")] pk_path: String, /// proof path. output - #[arg(long, default_value = "./build/proof")] + #[arg(long, default_value = "./build/agg/proof")] proof_path: String, // citizen's certificate #[arg(long, default_value = "./certs/myna_cert.pem")] @@ -96,10 +170,10 @@ enum Commands { #[arg(short, long, default_value = "./build/trusted_setup")] trusted_setup_path: String, /// proving key path. output - #[arg(long, default_value = "./build/vk")] + #[arg(long, default_value = "./build/agg/vk")] vk_path: String, /// proof path. output - #[arg(long, default_value = "./build/proof")] + #[arg(long, default_value = "./build/agg/proof")] proof_path: String, // citizen's certificate #[arg(long, default_value = "./certs/myna_cert.pem")] @@ -110,26 +184,17 @@ enum Commands { #[arg(default_value = "42")] password: u64, }, - /// Generate the proving key and the verification key for RSA circuit - GenerateSolidity { + Evm { /// trusted setup parameters path. input #[arg(short, long, default_value = "./build/trusted_setup")] trusted_setup_path: String, /// proving key path. output - #[arg(long, default_value = "./build/pk")] + #[arg(long, default_value = "./build/agg/pk")] pk_path: String, - // citizen's certificate - #[arg(long, default_value = "./certs/myna_cert.pem")] - verify_cert_path: String, - #[arg(short, long, default_value = "./build/verifier.sol")] + #[arg(short, long, default_value = "./build/agg/verifier.sol")] solidity_path: String, - #[arg(short, long, default_value = "./build/calldata.txt")] + #[arg(short, long, default_value = "./build/agg/calldata.txt")] calldata_path: String, - // nation's certificate - #[arg(long, default_value = "./certs/ca_cert.pem")] - issuer_cert_path: String, - #[arg(default_value = "42")] - password: u64, }, } @@ -146,147 +211,130 @@ fn main() { let trusted_setup_file = ParamsKZG::::setup(circuit::K as u32, OsRng); trusted_setup_file.write(&mut file).expect("Failed to write a trusted setup"); } - Commands::GenerateKeys { - trusted_setup_path, - verify_cert_path, - issuer_cert_path, - password, - vk_path, - pk_path, - } => { - let circuit = circuit::ProofOfJapaneseResidence::new( - issuer_cert_path.into(), - verify_cert_path.into(), - password.into(), - ); + Commands::App(command) => match command { + AppCommands::Keys { trusted_setup_path, pk_path, vk_path } => { + let circuit = circuit::ProofOfJapaneseResidence::new( + "./certs/ca_cert.pem".into(), + "./certs/myna_cert.pem".into(), + 0xA42.into(), + ); - let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); - let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) - .expect("The trusted setup is corrupted"); + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) + .expect("The trusted setup is corrupted"); - let vk = keygen_vk(&trusted_setup, &circuit).unwrap(); - let mut vk_file = File::create(vk_path).unwrap(); - vk.write(&mut vk_file, SerdeFormat::RawBytes).unwrap(); - - let pk = keygen_pk(&trusted_setup, vk, &circuit).unwrap(); - let mut pk_file = File::create(pk_path).unwrap(); - pk.write(&mut pk_file, SerdeFormat::RawBytes).unwrap(); - } - Commands::Prove { verify_cert_path, issuer_cert_path, password, trusted_setup_path, pk_path, proof_path } => { - let circuit = circuit::ProofOfJapaneseResidence::new( - issuer_cert_path.into(), - verify_cert_path.into(), - password.into(), - ); - let instance_column = circuit.instance_column(); + let vk = keygen_vk(&trusted_setup, &circuit).unwrap(); + let mut vk_file = File::create(vk_path).unwrap(); + vk.write(&mut vk_file, SerdeFormat::RawBytes).unwrap(); - let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); - let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) - .expect("The trusted setup is corrupted"); + let pk = keygen_pk(&trusted_setup, vk, &circuit).unwrap(); + let mut pk_file = File::create(pk_path).unwrap(); + pk.write(&mut pk_file, SerdeFormat::RawBytes).unwrap(); + } + AppCommands::Prove { + verify_cert_path, + issuer_cert_path, + password, + trusted_setup_path, + pk_path, + proof_path, + } => { + let circuit = circuit::ProofOfJapaneseResidence::new( + issuer_cert_path.into(), + verify_cert_path.into(), + password.into(), + ); - let mut pk_file = File::open(pk_path).expect("pk not found. Run generate-keys first."); - let pk = ProvingKey::::read::<_, circuit::ProofOfJapaneseResidence>( - &mut pk_file, - SerdeFormat::RawBytes, - circuit.params(), - ) - .unwrap(); + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) + .expect("The trusted setup is corrupted"); - let proof_file = File::create(proof_path).unwrap(); + let mut pk_file = File::open(pk_path).expect("pk not found. Run generate-keys first."); + let pk = ProvingKey::::read::<_, circuit::ProofOfJapaneseResidence>( + &mut pk_file, + SerdeFormat::RawBytes, + circuit.params(), + ) + .unwrap(); - let started_at = std::time::Instant::now(); - println!("Proof generation started at: {:?}", started_at); - let mut proof = Keccak256Write::<_, _, Challenge255<_>>::init(BufWriter::new(proof_file)); - create_proof::< - KZGCommitmentScheme, - ProverSHPLONK<'_, Bn256>, - Challenge255, - _, - Keccak256Write, G1Affine, Challenge255<_>>, - _, - >(&trusted_setup, &pk, &[circuit], &[&[&instance_column]], OsRng, &mut proof) - .expect("prover should not fail"); - proof.finalize(); - println!("Proof generation took: {:?}", started_at.elapsed()); - } - Commands::Verify { trusted_setup_path, vk_path, proof_path, verify_cert_path, issuer_cert_path, password } => { - let circuit = circuit::ProofOfJapaneseResidence::new( - issuer_cert_path.into(), - verify_cert_path.into(), - password.into(), - ); + let mut proof_file = BufWriter::new(File::create(proof_path).unwrap()); + let proof = + gen_evm_proof_shplonk(&trusted_setup, &pk, circuit.clone(), vec![circuit.instance_column()]); + proof_file.write_all(&proof).unwrap(); + } + AppCommands::Verify { + proof_path, + verify_cert_path, + issuer_cert_path, + password, + trusted_setup_path, + vk_path, + } => { + let circuit = circuit::ProofOfJapaneseResidence::new( + issuer_cert_path.into(), + verify_cert_path.into(), + password.into(), + ); - let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); - let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) - .expect("The trusted setup is corrupted"); + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) + .expect("The trusted setup is corrupted"); - let mut vk_file = File::open(vk_path).expect("vk not found. Run generate-keys first."); - let vk = VerifyingKey::::read::<_, circuit::ProofOfJapaneseResidence>( - &mut vk_file, - SerdeFormat::RawBytes, - circuit.params(), - ) - .unwrap(); + let mut vk_file = File::open(vk_path).expect("vk not found. Run generate-keys first."); + let vk = VerifyingKey::::read::<_, circuit::ProofOfJapaneseResidence>( + &mut vk_file, + SerdeFormat::RawBytes, + circuit.params(), + ) + .unwrap(); - let proof_file = File::open(proof_path).unwrap(); - let mut proof = Keccak256Read::init(&proof_file); + let proof_file = File::open(&proof_path).unwrap(); + let mut proof = TranscriptReadBuffer::<_, _, _>::init(&proof_file); + let result = verify_proof::<_, VerifierSHPLONK<'_, Bn256>, _, EvmTranscript<_, _, _, _>, _>( + &trusted_setup, + &vk, + AccumulatorStrategy::new(&trusted_setup), + &[&[&circuit.instance_column()]], + &mut proof, + ); + assert!(result.is_ok(), "Verification failed!"); + println!("Verification succeeded!"); + } + AppCommands::Evm { trusted_setup_path, vk_path, proof_path, solidity_path, calldata_path } => { + let circuit = circuit::ProofOfJapaneseResidence::new( + "./certs/ca_cert.pem".into(), + "./certs/myna_cert.pem".into(), + 0xA42.into(), + ); - let result = verify_proof::< - KZGCommitmentScheme, - VerifierSHPLONK<'_, Bn256>, - Challenge255, - Keccak256Read<&File, G1Affine, Challenge255>, - SingleStrategy<'_, Bn256>, - >( - &trusted_setup, - &vk, - SingleStrategy::new(&trusted_setup), - &[&[&circuit.instance_column()]], - &mut proof, - ); - assert!(result.is_ok(), "{:?}", result) - } - Commands::GenerateSolidity { - trusted_setup_path, - pk_path, - verify_cert_path, - issuer_cert_path, - password, - solidity_path, - calldata_path, - } => { - let circuit = circuit::ProofOfJapaneseResidence::new( - issuer_cert_path.into(), - verify_cert_path.into(), - password.into(), - ); + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) + .expect("The trusted setup is corrupted"); - let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); - let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) - .expect("The trusted setup is corrupted"); + let mut proof_file = File::open(&proof_path).expect("proof not found. Do `cargo run app prove` first."); + let mut proof: Vec = Vec::new(); + proof_file.read_to_end(&mut proof).unwrap(); - let mut pk_file = File::open(pk_path).expect("vk not found. Run generate-keys first."); - let pk = ProvingKey::::read::<_, circuit::ProofOfJapaneseResidence>( - &mut pk_file, - SerdeFormat::RawBytes, - circuit.params(), - ) - .unwrap(); + let mut vk_file = File::open(vk_path).expect("vk not found. Run generate-keys first."); + let vk = VerifyingKey::::read::<_, circuit::ProofOfJapaneseResidence>( + &mut vk_file, + SerdeFormat::RawBytes, + circuit.params(), + ) + .unwrap(); - let started_at = std::time::Instant::now(); - println!("Proof generation started at: {:?}", started_at); - let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, circuit.clone(), vec![circuit.instance_column()]); - println!("Proof generation took: {:?}", started_at.elapsed()); + write_calldata(&[circuit.instance_column()], &proof, Path::new(&calldata_path)).unwrap(); - let deployment_code = gen_evm_verifier_shplonk::>( - &trusted_setup, - &pk.get_vk(), - vec![circuit.instance_column().len()], - Some(Path::new(&solidity_path)), - ); + let verifier = gen_evm_verifier_shplonk::>( + &trusted_setup, + &vk, + vec![circuit.instance_column().len()], + Some(Path::new(&solidity_path)), + ); - write_calldata(&[circuit.instance_column()], &proof, Path::new(&calldata_path)).unwrap(); - evm_verify(deployment_code, vec![circuit.instance_column()], proof.clone()); - } + evm_verify(verifier, vec![circuit.instance_column()], proof.clone()); + } + }, + Commands::Agg(_) => todo!(), } } From ace0c8430e91e6e446879cb1d1554fd37f59dfff Mon Sep 17 00:00:00 2001 From: chokermaxx <135603985+chokermaxx@users.noreply.github.com> Date: Fri, 8 Dec 2023 21:55:07 +0900 Subject: [PATCH 28/28] Implement CLI for aggregation --- Cargo.lock | 1 + packages/halo2-circuits/Cargo.toml | 1 + packages/halo2-circuits/README.md | 42 ++- packages/halo2-circuits/src/bin/cli.rs | 368 ++++++++++++++++++------- packages/halo2-circuits/src/circuit.rs | 22 +- packages/halo2-circuits/src/helpers.rs | 21 +- 6 files changed, 322 insertions(+), 133 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f9e2aca..0206922 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2263,6 +2263,7 @@ dependencies = [ name = "halo2-circuits" version = "0.1.0" dependencies = [ + "bincode", "clap 4.2.1", "console_error_panic_hook", "criterion", diff --git a/packages/halo2-circuits/Cargo.toml b/packages/halo2-circuits/Cargo.toml index a2ef8ba..035ff95 100644 --- a/packages/halo2-circuits/Cargo.toml +++ b/packages/halo2-circuits/Cargo.toml @@ -40,6 +40,7 @@ tokio = { version = "1.16", features = [ ] } pse-poseidon = { git = "https://github.com/axiom-crypto/pse-poseidon.git" } halo2-sha256-unoptimized = { git = "https://github.com/MynaWallet/halo2-sha256-unoptimized.git" } +bincode = "1" [target.'cfg(target_family = "wasm")'.dependencies] getrandom = { version = "0.2", features = ["js"] } diff --git a/packages/halo2-circuits/README.md b/packages/halo2-circuits/README.md index 6d0f26d..481965c 100644 --- a/packages/halo2-circuits/README.md +++ b/packages/halo2-circuits/README.md @@ -57,15 +57,16 @@ You can refer to these repos of RSA verification circuits. - [zk-email-verify](https://github.com/zkemail/zk-email-verify) - [zkCert](https://github.com/zkCert/halo2-zkcert) -## Example Usage +# Usage +## For off-chain verification ### Create the directory where proofs are stored ```bash -mkdir -p build/{app,agg} +mkdir -p build/app ``` ### Generate the common reference string ```bash -cargo run trusted-setup +cargo run app trusted-setup ``` ### Generate pk & vk @@ -84,6 +85,41 @@ cargo run app verify ``` ### Run the verification code written in Solidity +This fails because of the big proof size. ```bash cargo run app evm ``` + +## For on-chain verification +Run `cargo run app keys` first. + +### Create the directory where proofs are stored +```bash +mkdir -p build/agg +``` + +### Generate a proof that's ready to be aggregated +```bash +cargo run app snark +``` + +### Generate pk & vk +```bash +cargo run agg keys +``` + +### Generate a proof +```bash +cargo run agg prove +``` + +### Run the verification code written in Rust +```bash +cargo run agg verify +``` + +### Run the verification code written in Solidity +This succeeds because of the tiny proof size. +```bash +cargo run agg evm +``` diff --git a/packages/halo2-circuits/src/bin/cli.rs b/packages/halo2-circuits/src/bin/cli.rs index 0979a93..205c493 100644 --- a/packages/halo2-circuits/src/bin/cli.rs +++ b/packages/halo2-circuits/src/bin/cli.rs @@ -2,43 +2,32 @@ use clap::{Parser, Subcommand}; use halo2_base::{ gates::circuit::{builder::BaseCircuitBuilder, CircuitBuilderStage}, halo2_proofs::{ - dev::MockProver, halo2curves::bn256::{Bn256, Fr, G1Affine}, - plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, Circuit, ProvingKey, VerifyingKey}, + plonk::{keygen_pk, keygen_vk, verify_proof, Circuit, VerifyingKey}, poly::{ commitment::Params, - kzg::{ - commitment::{KZGCommitmentScheme, ParamsKZG}, - multiopen::{ProverSHPLONK, VerifierSHPLONK}, - strategy::{AccumulatorStrategy, SingleStrategy}, - }, + kzg::{commitment::ParamsKZG, multiopen::VerifierSHPLONK, strategy::AccumulatorStrategy}, }, - transcript::{Challenge255, Keccak256Read, Keccak256Write, TranscriptReadBuffer, TranscriptWriterBuffer}, + transcript::TranscriptReadBuffer, SerdeFormat, }, - utils::{fs::gen_srs, BigPrimeField}, -}; -use halo2_circuits::{ - circuit::{self, ProofOfJapaneseResidence}, - helpers::*, }; +use halo2_circuits::circuit; use rand::rngs::OsRng; -use sha2::{Digest, Sha256}; use snark_verifier_sdk::{ evm::{evm_verify, gen_evm_proof_shplonk, gen_evm_verifier_shplonk, write_calldata}, halo2::{ aggregation::{AggregationCircuit, AggregationConfigParams, VerifierUniversality}, - gen_snark_shplonk, + gen_snark_shplonk, read_snark, }, + read_pk, snark_verifier::system::halo2::transcript::evm::EvmTranscript, CircuitExt, SHPLONK, }; use std::{ - env, - fmt::Binary, - fs::{remove_file, File}, - io::{BufWriter, Read, Write}, - path::{Path, PathBuf}, + fs::File, + io::{BufReader, BufWriter, Read, Write}, + path::Path, }; #[derive(Parser, Debug, Clone)] @@ -50,12 +39,6 @@ struct Cli { #[derive(Debug, Subcommand, Clone)] enum Commands { - /// Generate a trusted setup paramter - TrustedSetup { - /// trusted setup parameters path. input - #[arg(short, long, default_value = "./build/trusted_setup")] - trusted_setup_path: String, - }, #[command(subcommand)] App(AppCommands), #[command(subcommand)] @@ -64,12 +47,18 @@ enum Commands { #[derive(Debug, Subcommand, Clone)] enum AppCommands { + /// Generate a trusted setup paramter + TrustedSetup { + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./build/app/trusted_setup")] + trusted_setup_path: String, + }, /// Generate the proving key and the verification key for RSA circuit Keys { /// trusted setup parameters path. input - #[arg(short, long, default_value = "./build/trusted_setup")] + #[arg(short, long, default_value = "./build/app/trusted_setup")] trusted_setup_path: String, - /// proving key path. output + /// verification key path. output #[arg(long, default_value = "./build/app/vk")] vk_path: String, /// proving key path. output @@ -78,7 +67,7 @@ enum AppCommands { }, Prove { /// trusted setup parameters path. input - #[arg(short, long, default_value = "./build/trusted_setup")] + #[arg(short, long, default_value = "./build/app/trusted_setup")] trusted_setup_path: String, /// proving key path. input #[arg(long, default_value = "./build/app/pk")] @@ -97,7 +86,7 @@ enum AppCommands { }, Verify { /// trusted setup parameters path. input - #[arg(short, long, default_value = "./build/trusted_setup")] + #[arg(short, long, default_value = "./build/app/trusted_setup")] trusted_setup_path: String, /// verification key path. input #[arg(long, default_value = "./build/app/vk")] @@ -116,10 +105,10 @@ enum AppCommands { }, Evm { /// trusted setup parameters path. input - #[arg(short, long, default_value = "./build/trusted_setup")] + #[arg(short, long, default_value = "./build/app/trusted_setup")] trusted_setup_path: String, /// verification key path. input - #[arg(long, default_value = "./build/app/pk")] + #[arg(long, default_value = "./build/app/vk")] vk_path: String, /// proof path. input #[arg(long, default_value = "./build/app/proof")] @@ -131,87 +120,123 @@ enum AppCommands { #[arg(long, default_value = "./build/app/calldata.txt")] calldata_path: String, }, + Snark { + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./build/app/trusted_setup")] + trusted_setup_path: String, + /// proving key path. input + #[arg(long, default_value = "./build/app/pk")] + pk_path: String, + /// partial proof path. output + #[arg(long, default_value = "./build/app/snark")] + snark_path: String, + // citizen's certificate. input + #[arg(long, default_value = "./certs/myna_cert.pem")] + verify_cert_path: String, + // nation's certificate. input + #[arg(long, default_value = "./certs/ca_cert.pem")] + issuer_cert_path: String, + #[arg(default_value = "42")] + password: u64, + }, } #[derive(Debug, Subcommand, Clone)] enum AggCommands { + /// Generate a trusted setup paramter + TrustedSetup { + /// trusted setup parameters path. input + #[arg(short, long, default_value = "./build/agg/trusted_setup")] + trusted_setup_path: String, + }, Keys { /// trusted setup parameters path. input - #[arg(short, long, default_value = "./build/trusted_setup")] + #[arg(short, long, default_value = "./build/agg/trusted_setup")] trusted_setup_path: String, - /// proving key path. output + /// partial proof path. input + #[arg(long, default_value = "./build/app/snark")] + snark_path: String, + /// verification key path. output #[arg(long, default_value = "./build/agg/vk")] vk_path: String, /// proving key path. output #[arg(long, default_value = "./build/agg/pk")] pk_path: String, + /// break points path. output + #[arg(long, default_value = "./build/agg/break_points")] + break_points_path: String, }, Prove { /// trusted setup parameters path. input - #[arg(short, long, default_value = "./build/trusted_setup")] + #[arg(short, long, default_value = "./build/agg/trusted_setup")] trusted_setup_path: String, - /// proving key path. output + /// proving key path. input #[arg(long, default_value = "./build/agg/pk")] pk_path: String, + /// partial proof path. input + #[arg(long, default_value = "./build/app/snark")] + snark_path: String, + /// break points path. input + #[arg(long, default_value = "./build/agg/break_points")] + break_points_path: String, /// proof path. output #[arg(long, default_value = "./build/agg/proof")] proof_path: String, - // citizen's certificate - #[arg(long, default_value = "./certs/myna_cert.pem")] - verify_cert_path: String, - // nation's certificate - #[arg(long, default_value = "./certs/ca_cert.pem")] - issuer_cert_path: String, - #[arg(default_value = "42")] - password: u64, }, Verify { /// trusted setup parameters path. input - #[arg(short, long, default_value = "./build/trusted_setup")] + #[arg(short, long, default_value = "./build/agg/trusted_setup")] trusted_setup_path: String, - /// proving key path. output + /// verification key path. input #[arg(long, default_value = "./build/agg/vk")] vk_path: String, - /// proof path. output + /// proof path. input #[arg(long, default_value = "./build/agg/proof")] proof_path: String, - // citizen's certificate - #[arg(long, default_value = "./certs/myna_cert.pem")] - verify_cert_path: String, - // nation's certificate - #[arg(long, default_value = "./certs/ca_cert.pem")] - issuer_cert_path: String, - #[arg(default_value = "42")] - password: u64, + /// partial proof path. input + #[arg(long, default_value = "./build/app/snark")] + snark_path: String, }, Evm { /// trusted setup parameters path. input - #[arg(short, long, default_value = "./build/trusted_setup")] + #[arg(short, long, default_value = "./build/agg/trusted_setup")] trusted_setup_path: String, - /// proving key path. output - #[arg(long, default_value = "./build/agg/pk")] - pk_path: String, + /// verification key path. input + #[arg(long, default_value = "./build/agg/vk")] + vk_path: String, + /// proof path. input + #[arg(long, default_value = "./build/agg/proof")] + proof_path: String, + /// partial proof path. input + #[arg(long, default_value = "./build/app/snark")] + snark_path: String, + /// verifier.sol path. output #[arg(short, long, default_value = "./build/agg/verifier.sol")] solidity_path: String, - #[arg(short, long, default_value = "./build/agg/calldata.txt")] + /// calldata path. output + #[arg(long, default_value = "./build/agg/calldata.txt")] calldata_path: String, }, } +const AGGREGATION_CONFIG: AggregationConfigParams = + AggregationConfigParams { degree: 23, num_advice: 7, num_fixed: 1, num_lookup_advice: 1, lookup_bits: 22 }; + fn main() { let cli = Cli::parse(); match cli.command { - Commands::TrustedSetup { trusted_setup_path } => { - let trusted_setup_path = Path::new(&trusted_setup_path); - if trusted_setup_path.exists() { - println!("Trusted setup already exists. Overwriting..."); - } - - let mut file = File::create(trusted_setup_path).expect("Failed to create a trusted setup"); - let trusted_setup_file = ParamsKZG::::setup(circuit::K as u32, OsRng); - trusted_setup_file.write(&mut file).expect("Failed to write a trusted setup"); - } Commands::App(command) => match command { + AppCommands::TrustedSetup { trusted_setup_path } => { + let trusted_setup_path = Path::new(&trusted_setup_path); + if trusted_setup_path.exists() { + println!("Trusted setup already exists. Overwriting..."); + } + + let mut file = + BufWriter::new(File::create(trusted_setup_path).expect("Failed to create a trusted setup")); + let trusted_setup_file = ParamsKZG::::setup(circuit::K as u32, OsRng); + trusted_setup_file.write(&mut file).expect("Failed to write a trusted setup"); + } AppCommands::Keys { trusted_setup_path, pk_path, vk_path } => { let circuit = circuit::ProofOfJapaneseResidence::new( "./certs/ca_cert.pem".into(), @@ -220,15 +245,15 @@ fn main() { ); let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); - let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) - .expect("The trusted setup is corrupted"); + let trusted_setup = + ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes).unwrap(); let vk = keygen_vk(&trusted_setup, &circuit).unwrap(); - let mut vk_file = File::create(vk_path).unwrap(); + let mut vk_file = BufWriter::new(File::create(vk_path).unwrap()); vk.write(&mut vk_file, SerdeFormat::RawBytes).unwrap(); let pk = keygen_pk(&trusted_setup, vk, &circuit).unwrap(); - let mut pk_file = File::create(pk_path).unwrap(); + let mut pk_file = BufWriter::new(File::create(pk_path).unwrap()); pk.write(&mut pk_file, SerdeFormat::RawBytes).unwrap(); } AppCommands::Prove { @@ -244,22 +269,17 @@ fn main() { verify_cert_path.into(), password.into(), ); + let instance_column = circuit.instance_column(); let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); - let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) - .expect("The trusted setup is corrupted"); + let trusted_setup = + ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes).unwrap(); - let mut pk_file = File::open(pk_path).expect("pk not found. Run generate-keys first."); - let pk = ProvingKey::::read::<_, circuit::ProofOfJapaneseResidence>( - &mut pk_file, - SerdeFormat::RawBytes, - circuit.params(), - ) - .unwrap(); + let pk = read_pk::(pk_path.as_ref(), circuit.params()) + .expect("pk not found"); let mut proof_file = BufWriter::new(File::create(proof_path).unwrap()); - let proof = - gen_evm_proof_shplonk(&trusted_setup, &pk, circuit.clone(), vec![circuit.instance_column()]); + let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, circuit, vec![instance_column]); proof_file.write_all(&proof).unwrap(); } AppCommands::Verify { @@ -277,10 +297,10 @@ fn main() { ); let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); - let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) - .expect("The trusted setup is corrupted"); + let trusted_setup = + ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes).unwrap(); - let mut vk_file = File::open(vk_path).expect("vk not found. Run generate-keys first."); + let mut vk_file = File::open(vk_path).expect("vk not found."); let vk = VerifyingKey::::read::<_, circuit::ProofOfJapaneseResidence>( &mut vk_file, SerdeFormat::RawBytes, @@ -308,14 +328,14 @@ fn main() { ); let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); - let trusted_setup = ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes) - .expect("The trusted setup is corrupted"); + let trusted_setup = + ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes).unwrap(); - let mut proof_file = File::open(&proof_path).expect("proof not found. Do `cargo run app prove` first."); + let mut proof_file = File::open(&proof_path).expect("proof not found."); let mut proof: Vec = Vec::new(); proof_file.read_to_end(&mut proof).unwrap(); - let mut vk_file = File::open(vk_path).expect("vk not found. Run generate-keys first."); + let mut vk_file = File::open(vk_path).expect("vk not found."); let vk = VerifyingKey::::read::<_, circuit::ProofOfJapaneseResidence>( &mut vk_file, SerdeFormat::RawBytes, @@ -334,7 +354,169 @@ fn main() { evm_verify(verifier, vec![circuit.instance_column()], proof.clone()); } + AppCommands::Snark { + issuer_cert_path, + verify_cert_path, + password, + trusted_setup_path, + pk_path, + snark_path, + } => { + let circuit = circuit::ProofOfJapaneseResidence::new( + issuer_cert_path.into(), + verify_cert_path.into(), + password.into(), + ); + + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = + ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes).unwrap(); + + let pk = read_pk::(pk_path.as_ref(), circuit.params()) + .expect("pk not found."); + + gen_snark_shplonk(&trusted_setup, &pk, circuit, Some(&snark_path)); + } + }, + Commands::Agg(command) => match command { + AggCommands::TrustedSetup { trusted_setup_path } => { + let trusted_setup_path = Path::new(&trusted_setup_path); + if trusted_setup_path.exists() { + println!("Trusted setup already exists. Overwriting..."); + } + + let mut file = + BufWriter::new(File::create(trusted_setup_path).expect("Failed to create a trusted setup")); + let trusted_setup_file = ParamsKZG::::setup(AGGREGATION_CONFIG.degree, OsRng); + trusted_setup_file.write(&mut file).expect("Failed to write a trusted setup"); + } + AggCommands::Keys { trusted_setup_path, break_points_path, snark_path, pk_path, vk_path } => { + let snark = read_snark(&snark_path).expect("proof not found."); + + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = + ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes).unwrap(); + + let circuit = AggregationCircuit::new::( + CircuitBuilderStage::Keygen, + AGGREGATION_CONFIG, + &trusted_setup, + vec![snark], + VerifierUniversality::None, + ); + + let vk = keygen_vk(&trusted_setup, &circuit).unwrap(); + let mut vk_file = BufWriter::new(File::create(vk_path).unwrap()); + vk.write(&mut vk_file, SerdeFormat::RawBytes).unwrap(); + + let pk = keygen_pk(&trusted_setup, vk, &circuit).unwrap(); + let mut pk_file = BufWriter::new(File::create(pk_path).unwrap()); + pk.write(&mut pk_file, SerdeFormat::RawBytes).unwrap(); + + let mut break_points_file = BufWriter::new(File::create(break_points_path).unwrap()); + bincode::serialize_into(&mut break_points_file, &circuit.break_points()).unwrap(); + } + AggCommands::Prove { trusted_setup_path, pk_path, break_points_path, snark_path, proof_path } => { + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = + ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes).unwrap(); + + let pk = read_pk::(pk_path.as_ref(), AGGREGATION_CONFIG).expect("pk not found."); + let snark = read_snark(&snark_path).expect("proof not fonud."); + + let break_points_file = BufReader::new(File::open(break_points_path).expect("break points not found.")); + let break_points = bincode::deserialize_from(break_points_file).unwrap(); + + let circuit = AggregationCircuit::new::( + CircuitBuilderStage::Prover, + AGGREGATION_CONFIG, + &trusted_setup, + vec![snark], + VerifierUniversality::None, + ) + .use_break_points(break_points); + let instance_columns = circuit.instances(); + + let mut proof_file = BufWriter::new(File::create(proof_path).unwrap()); + let proof = gen_evm_proof_shplonk(&trusted_setup, &pk, circuit, instance_columns); + proof_file.write_all(&proof).unwrap(); + } + AggCommands::Verify { snark_path, proof_path, trusted_setup_path, vk_path } => { + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = + ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes).unwrap(); + + let snark = read_snark(&snark_path).expect("proof not found."); + + let circuit = AggregationCircuit::new::( + CircuitBuilderStage::Prover, + AGGREGATION_CONFIG, + &trusted_setup, + vec![snark], + VerifierUniversality::None, + ); + + let mut vk_file = File::open(vk_path).expect("vk not found."); + let vk = VerifyingKey::::read::<_, AggregationCircuit>( + &mut vk_file, + SerdeFormat::RawBytes, + AGGREGATION_CONFIG, + ) + .expect("vk not found."); + + let proof_file = File::open(&proof_path).expect("proof not found."); + let mut proof = TranscriptReadBuffer::<_, _, _>::init(&proof_file); + + let instances = circuit.instances(); + let instance_refs: Vec<&[Fr]> = instances.iter().map(|x| x.as_ref()).collect(); + + let result = verify_proof::<_, VerifierSHPLONK<'_, Bn256>, _, EvmTranscript<_, _, _, _>, _>( + &trusted_setup, + &vk, + AccumulatorStrategy::new(&trusted_setup), + &[&instance_refs], + &mut proof, + ); + assert!(result.is_ok(), "Verification failed!"); + println!("Verification succeeded!"); + } + AggCommands::Evm { trusted_setup_path, vk_path, proof_path, snark_path, solidity_path, calldata_path } => { + let mut trusted_setup_file = File::open(trusted_setup_path).expect("Couldn't open the trusted setup"); + let trusted_setup = + ParamsKZG::::read_custom(&mut trusted_setup_file, SerdeFormat::RawBytes).unwrap(); + + let snark = read_snark(&snark_path).expect("proof not found."); + + let mut vk_file = File::open(vk_path).expect("vk not found."); + let vk = VerifyingKey::::read::<_, AggregationCircuit>( + &mut vk_file, + SerdeFormat::RawBytes, + AGGREGATION_CONFIG, + ) + .expect("vk not found."); + + let mut proof_file = File::open(&proof_path).expect("proof not found."); + let mut proof: Vec = Vec::new(); + proof_file.read_to_end(&mut proof).unwrap(); + + let circuit = AggregationCircuit::new::( + CircuitBuilderStage::Prover, + AGGREGATION_CONFIG, + &trusted_setup, + vec![snark], + VerifierUniversality::None, + ); + + write_calldata(&circuit.instances(), &proof, Path::new(&calldata_path)).unwrap(); + + let verifier = gen_evm_verifier_shplonk::( + &trusted_setup, + &vk, + circuit.num_instance(), + Some(Path::new(&solidity_path)), + ); + evm_verify(verifier, circuit.instances(), proof); + } }, - Commands::Agg(_) => todo!(), } } diff --git a/packages/halo2-circuits/src/circuit.rs b/packages/halo2-circuits/src/circuit.rs index 915a676..a3abb4e 100644 --- a/packages/halo2-circuits/src/circuit.rs +++ b/packages/halo2-circuits/src/circuit.rs @@ -5,26 +5,20 @@ use halo2_base::{ GateInstructions, RangeChip, RangeInstructions, }, halo2_proofs::{ - arithmetic::Field, circuit::{Layouter, SimpleFloorPlanner}, halo2curves::bn256::Fr, - plonk::{Assignment, Circuit, ConstraintSystem, Error, Selector}, + plonk::{Circuit, ConstraintSystem, Error, Selector}, }, poseidon::hasher::{spec::OptimizedPoseidonSpec, PoseidonHasher}, - utils::halo2::Halo2AssignedCell, AssignedValue, Context, QuantumCell, }; -use halo2_ecc::bigint::OverflowInteger; -use halo2_rsa::{ - AssignedBigUint, BigUintConfig, BigUintInstructions, Fresh, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, - RSASignature, -}; +use halo2_rsa::{BigUintConfig, BigUintInstructions, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, RSASignature}; use num_bigint::BigUint; use num_traits::One; use pse_poseidon::Poseidon; use snark_verifier_sdk::CircuitExt; -use std::{cmp::Ordering, path::PathBuf}; -use zkevm_hashes::sha256::vanilla::{columns::Sha256CircuitConfig, param::NUM_WORDS_TO_ABSORB}; +use std::path::PathBuf; +use zkevm_hashes::sha256::vanilla::columns::Sha256CircuitConfig; #[derive(Debug, Clone)] pub struct PublicInput { @@ -345,13 +339,7 @@ impl CircuitExt for ProofOfJapaneseResidence { #[cfg(test)] mod tests { use super::*; - use crate::helpers::{read_citizen_cert, read_nation_cert}; - use halo2_base::{ - halo2_proofs::{dev::MockProver, halo2curves::ff::PrimeField}, - utils::testing::base_test, - }; - use num_traits::cast::ToPrimitive; - use sha2::Sha256; + use halo2_base::halo2_proofs::dev::MockProver; #[test] fn mock() { diff --git a/packages/halo2-circuits/src/helpers.rs b/packages/halo2-circuits/src/helpers.rs index 30cea63..b6f6057 100644 --- a/packages/halo2-circuits/src/helpers.rs +++ b/packages/halo2-circuits/src/helpers.rs @@ -1,23 +1,5 @@ -use halo2_base::{ - gates::{circuit::builder::BaseCircuitBuilder, GateInstructions}, - halo2_proofs::halo2curves::bn256::Fr, - utils::fs::gen_srs, - AssignedValue, - QuantumCell::{Constant, Existing}, -}; -use halo2_rsa::{BigUintConfig, BigUintInstructions, RSAConfig, RSAInstructions, RSAPubE, RSAPublicKey, RSASignature}; -// use snark_verifir_sdk::{gen_pk, halo2::gen_snark_shplonk, Snark}; - -use itertools::Itertools; use num_bigint::BigUint; -use openssl::ssl::{SslConnector, SslMethod}; -use sha2::{Digest, Sha256}; -use std::{ - fs::File, - io::{Read, Write}, - net::TcpStream, - vec, -}; +use std::{fs::File, io::Read}; use x509_parser::{pem::parse_x509_pem, public_key::PublicKey}; pub fn read_nation_cert(cert_path: &str) -> BigUint { @@ -52,7 +34,6 @@ pub fn read_citizen_cert(cert_path: &str) -> (BigUint, BigUint, BigUint) { // Extract the TBS (To-Be-Signed) data from the certificate let tbs_bytes = cert.tbs_certificate.as_ref(); - dbg!(tbs_bytes.len()); let tbs_biguint = BigUint::from_bytes_le(tbs_bytes); // println!("TBS (To-Be-Signed): {:x?}", tbs);