1
0
Fork 0
mirror of synced 2025-09-23 12:18:44 +00:00

implement gm17, verification contract not working for now

This commit is contained in:
schaeff 2018-11-13 15:31:37 +01:00
parent 4dbf85c79a
commit e02d4fffeb
16 changed files with 1446 additions and 744 deletions

View file

@ -12,8 +12,9 @@ extern crate zokrates_fs_resolver;
use bincode::{deserialize_from, serialize_into, Infinite};
use clap::{App, AppSettings, Arg, SubCommand};
use regex::Regex;
#[cfg(feature = "libsnark")]
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{stdin, BufRead, BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
@ -21,10 +22,10 @@ use std::string::String;
use zokrates_core::compile::compile;
use zokrates_core::field::{Field, FieldPrime};
use zokrates_core::flat_absy::FlatProg;
use zokrates_core::proof_system::{ProofSystem, PGHR13};
#[cfg(feature = "libsnark")]
use zokrates_core::proof_system::{ProofSystem, GM17, PGHR13};
#[cfg(feature = "libsnark")]
use zokrates_core::r1cs::r1cs_program;
use zokrates_core::verification::CONTRACT_TEMPLATE;
use zokrates_fs_resolver::resolve as fs_resolve;
fn main() {
@ -35,7 +36,7 @@ fn main() {
const WITNESS_DEFAULT_PATH: &str = "witness";
const VARIABLES_INFORMATION_KEY_DEFAULT_PATH: &str = "variables.inf";
const JSON_PROOF_PATH: &str = "proof.json";
const DEFAULT_BACKEND: &str = "pghr13";
let default_backend = env::var("ZOKRATES_BACKEND").unwrap_or(String::from("pghr13"));
// cli specification using clap library
let matches = App::new("ZoKrates")
@ -107,11 +108,11 @@ fn main() {
.arg(Arg::with_name("backend")
.short("b")
.long("backend")
.help("Backend to use in the setup. Currently only PGHR13")
.help("Backend to use in the setup. Available options are PGHR13 and GM17")
.value_name("FILE")
.takes_value(true)
.required(false)
.default_value(DEFAULT_BACKEND)
.default_value(&default_backend)
)
)
.subcommand(SubCommand::with_name("export-verifier")
@ -133,6 +134,14 @@ fn main() {
.takes_value(true)
.required(false)
.default_value(VERIFICATION_CONTRACT_DEFAULT_PATH)
).arg(Arg::with_name("backend")
.short("b")
.long("backend")
.help("Backend to use to export the verifier. Available options are PGHR13 and GM17")
.value_name("FILE")
.takes_value(true)
.required(false)
.default_value(&default_backend)
)
)
.subcommand(SubCommand::with_name("compute-witness")
@ -200,6 +209,14 @@ fn main() {
.takes_value(true)
.required(false)
.default_value(VARIABLES_INFORMATION_KEY_DEFAULT_PATH)
).arg(Arg::with_name("backend")
.short("b")
.long("backend")
.help("Backend to use to generate the proof. Available options are PGHR13 and GM17")
.value_name("FILE")
.takes_value(true)
.required(false)
.default_value(&default_backend)
)
)
.get_matches();
@ -393,256 +410,215 @@ fn main() {
}
bw.flush().expect("Unable to flush buffer.");
}
#[cfg(feature = "libsnark")]
("setup", Some(sub_matches)) => {
#[cfg(feature = "libsnark")]
{
println!("Performing setup...");
println!("Performing setup...");
let backend = match sub_matches
let backend: &ProofSystem = match sub_matches
.value_of("backend")
.unwrap()
.to_lowercase()
.as_ref()
{
"pghr13" => &PGHR13 {},
"gm17" => &GM17 {},
s => panic!("Backend \"{}\" not supported", s),
};
let path = Path::new(sub_matches.value_of("input").unwrap());
let mut file = match File::open(&path) {
Ok(file) => file,
Err(why) => panic!("couldn't open {}: {}", path.display(), why),
};
let program_ast: FlatProg<FieldPrime> = match deserialize_from(&mut file, Infinite) {
Ok(x) => x,
Err(why) => {
println!("{:?}", why);
std::process::exit(1);
}
};
let main_flattened = program_ast
.functions
.iter()
.find(|x| x.id == "main")
.unwrap();
// print deserialized flattened program
println!("{}", main_flattened);
// transform to R1CS
let (variables, public_variables_count, a, b, c) = r1cs_program(&program_ast);
// write variables meta information to file
let var_inf_path = Path::new(sub_matches.value_of("meta-information").unwrap());
let var_inf_file = match File::create(&var_inf_path) {
Ok(file) => file,
Err(why) => panic!("couldn't open {}: {}", var_inf_path.display(), why),
};
let mut bw = BufWriter::new(var_inf_file);
write!(
&mut bw,
"Private inputs offset:\n{}\n",
public_variables_count
)
.expect("Unable to write data to file.");
write!(&mut bw, "R1CS variable order:\n").expect("Unable to write data to file.");
for var in &variables {
write!(&mut bw, "{} ", var).expect("Unable to write data to file.");
}
write!(&mut bw, "\n").expect("Unable to write data to file.");
bw.flush().expect("Unable to flush buffer.");
// get paths for proving and verification keys
let pk_path = sub_matches.value_of("proving-key-path").unwrap();
let vk_path = sub_matches.value_of("verification-key-path").unwrap();
// run setup phase
// number of inputs in the zkSNARK sense, i.e., input variables + output variables
println!(
"setup successful: {:?}",
backend.setup(
variables,
a,
b,
c,
public_variables_count - 1,
pk_path,
vk_path
)
);
}
#[cfg(feature = "libsnark")]
("export-verifier", Some(sub_matches)) => {
{
println!("Exporting verifier...");
let backend: &ProofSystem = match sub_matches
.value_of("backend")
.unwrap()
.to_lowercase()
.as_ref()
{
"pghr13" => PGHR13::new(),
"pghr13" => &PGHR13 {},
"gm17" => &GM17 {},
s => panic!("Backend \"{}\" not supported", s),
};
let path = Path::new(sub_matches.value_of("input").unwrap());
let mut file = match File::open(&path) {
// read vk file
let input_path = Path::new(sub_matches.value_of("input").unwrap());
let input_file = match File::open(&input_path) {
Ok(input_file) => input_file,
Err(why) => panic!("couldn't open {}: {}", input_path.display(), why),
};
let reader = BufReader::new(input_file);
let verifier = backend.export_solidity_verifier(reader);
//write output file
let output_path = Path::new(sub_matches.value_of("output").unwrap());
let mut output_file = match File::create(&output_path) {
Ok(file) => file,
Err(why) => panic!("couldn't open {}: {}", path.display(), why),
Err(why) => panic!("couldn't create {}: {}", output_path.display(), why),
};
let program_ast: FlatProg<FieldPrime> = match deserialize_from(&mut file, Infinite)
{
Ok(x) => x,
Err(why) => {
println!("{:?}", why);
std::process::exit(1);
}
};
let main_flattened = program_ast
.functions
.iter()
.find(|x| x.id == "main")
.unwrap();
// print deserialized flattened program
println!("{}", main_flattened);
// transform to R1CS
let (variables, public_variables_count, a, b, c) = r1cs_program(&program_ast);
// write variables meta information to file
let var_inf_path = Path::new(sub_matches.value_of("meta-information").unwrap());
let var_inf_file = match File::create(&var_inf_path) {
Ok(file) => file,
Err(why) => panic!("couldn't open {}: {}", var_inf_path.display(), why),
};
let mut bw = BufWriter::new(var_inf_file);
write!(
&mut bw,
"Private inputs offset:\n{}\n",
public_variables_count
)
.expect("Unable to write data to file.");
write!(&mut bw, "R1CS variable order:\n").expect("Unable to write data to file.");
for var in &variables {
write!(&mut bw, "{} ", var).expect("Unable to write data to file.");
}
write!(&mut bw, "\n").expect("Unable to write data to file.");
bw.flush().expect("Unable to flush buffer.");
// get paths for proving and verification keys
let pk_path = sub_matches.value_of("proving-key-path").unwrap();
let vk_path = sub_matches.value_of("verification-key-path").unwrap();
// run setup phase
// number of inputs in the zkSNARK sense, i.e., input variables + output variables
println!(
"setup successful: {:?}",
backend.setup(
variables,
a,
b,
c,
public_variables_count - 1,
pk_path,
vk_path
)
);
output_file
.write_all(&verifier.as_bytes())
.expect("Failed writing output to file.");
println!("Finished exporting verifier.");
}
}
("export-verifier", Some(sub_matches)) => {
println!("Exporting verifier...");
// read vk file
let input_path = Path::new(sub_matches.value_of("input").unwrap());
let input_file = match File::open(&input_path) {
Ok(input_file) => input_file,
Err(why) => panic!("couldn't open {}: {}", input_path.display(), why),
};
let reader = BufReader::new(input_file);
let mut lines = reader.lines();
let mut template_text = String::from(CONTRACT_TEMPLATE);
let ic_template = String::from("vk.IC[index] = Pairing.G1Point(points);"); //copy this for each entry
//replace things in template
let vk_regex = Regex::new(r#"(<%vk_[^i%]*%>)"#).unwrap();
let vk_ic_len_regex = Regex::new(r#"(<%vk_ic_length%>)"#).unwrap();
let vk_ic_index_regex = Regex::new(r#"index"#).unwrap();
let vk_ic_points_regex = Regex::new(r#"points"#).unwrap();
let vk_ic_repeat_regex = Regex::new(r#"(<%vk_ic_pts%>)"#).unwrap();
let vk_input_len_regex = Regex::new(r#"(<%vk_input_length%>)"#).unwrap();
for _ in 0..7 {
let current_line: String = lines
.next()
.expect("Unexpected end of file in verification key!")
.unwrap();
let current_line_split: Vec<&str> = current_line.split("=").collect();
assert_eq!(current_line_split.len(), 2);
template_text = vk_regex
.replace(template_text.as_str(), current_line_split[1].trim())
.into_owned();
}
let current_line: String = lines
.next()
.expect("Unexpected end of file in verification key!")
.unwrap();
let current_line_split: Vec<&str> = current_line.split("=").collect();
assert_eq!(current_line_split.len(), 2);
let ic_count: i32 = current_line_split[1].trim().parse().unwrap();
template_text = vk_ic_len_regex
.replace(template_text.as_str(), format!("{}", ic_count).as_str())
.into_owned();
template_text = vk_input_len_regex
.replace(template_text.as_str(), format!("{}", ic_count - 1).as_str())
.into_owned();
let mut ic_repeat_text = String::new();
for x in 0..ic_count {
let mut curr_template = ic_template.clone();
let current_line: String = lines
.next()
.expect("Unexpected end of file in verification key!")
.unwrap();
let current_line_split: Vec<&str> = current_line.split("=").collect();
assert_eq!(current_line_split.len(), 2);
curr_template = vk_ic_index_regex
.replace(curr_template.as_str(), format!("{}", x).as_str())
.into_owned();
curr_template = vk_ic_points_regex
.replace(curr_template.as_str(), current_line_split[1].trim())
.into_owned();
ic_repeat_text.push_str(curr_template.as_str());
if x < ic_count - 1 {
ic_repeat_text.push_str("\n ");
}
}
template_text = vk_ic_repeat_regex
.replace(template_text.as_str(), ic_repeat_text.as_str())
.into_owned();
//write output file
let output_path = Path::new(sub_matches.value_of("output").unwrap());
let mut output_file = match File::create(&output_path) {
Ok(file) => file,
Err(why) => panic!("couldn't create {}: {}", output_path.display(), why),
};
output_file
.write_all(&template_text.as_bytes())
.expect("Failed writing output to file.");
println!("Finished exporting verifier.");
}
#[cfg(feature = "libsnark")]
("generate-proof", Some(sub_matches)) => {
#[cfg(feature = "libsnark")]
println!("Generating proof...");
let backend: &ProofSystem = match sub_matches
.value_of("backend")
.unwrap()
.to_lowercase()
.as_ref()
{
println!("Generating proof...");
"pghr13" => &PGHR13 {},
"gm17" => &GM17 {},
s => panic!("Backend \"{}\" not supported", s),
};
let backend = PGHR13::new();
// deserialize witness
let witness_path = Path::new(sub_matches.value_of("witness").unwrap());
let witness_file = match File::open(&witness_path) {
Ok(file) => file,
Err(why) => panic!("couldn't open {}: {}", witness_path.display(), why),
};
// deserialize witness
let witness_path = Path::new(sub_matches.value_of("witness").unwrap());
let witness_file = match File::open(&witness_path) {
Ok(file) => file,
Err(why) => panic!("couldn't open {}: {}", witness_path.display(), why),
};
let reader = BufReader::new(witness_file);
let mut lines = reader.lines();
let mut witness_map = HashMap::new();
let reader = BufReader::new(witness_file);
let mut lines = reader.lines();
let mut witness_map = HashMap::new();
loop {
match lines.next() {
Some(Ok(ref x)) => {
let pairs: Vec<&str> = x.split_whitespace().collect();
witness_map.insert(
pairs[0].to_string(),
FieldPrime::from_dec_string(pairs[1].to_string()),
);
}
None => break,
Some(Err(err)) => panic!("Error reading witness: {}", err),
loop {
match lines.next() {
Some(Ok(ref x)) => {
let pairs: Vec<&str> = x.split_whitespace().collect();
witness_map.insert(
pairs[0].to_string(),
FieldPrime::from_dec_string(pairs[1].to_string()),
);
}
None => break,
Some(Err(err)) => panic!("Error reading witness: {}", err),
}
// determine variable order
let var_inf_path = Path::new(sub_matches.value_of("meta-information").unwrap());
let var_inf_file = match File::open(&var_inf_path) {
Ok(file) => file,
Err(why) => panic!("couldn't open {}: {}", var_inf_path.display(), why),
};
let var_reader = BufReader::new(var_inf_file);
let mut var_lines = var_reader.lines();
// get private inputs offset
let private_inputs_offset;
if let Some(Ok(ref o)) = var_lines.nth(1) {
// consumes first 2 lines
private_inputs_offset =
o.parse().expect("Failed parsing private inputs offset");
} else {
panic!("Error reading private inputs offset");
}
// get variables vector
let mut variables: Vec<String> = Vec::new();
if let Some(Ok(ref v)) = var_lines.nth(1) {
let iter = v.split_whitespace();
for i in iter {
variables.push(i.to_string());
}
} else {
panic!("Error reading variables.");
}
println!("Using Witness: {:?}", witness_map);
let witness: Vec<_> = variables.iter().map(|x| witness_map[x].clone()).collect();
// split witness into public and private inputs at offset
let mut public_inputs: Vec<_> = witness.clone();
let private_inputs: Vec<_> = public_inputs.split_off(private_inputs_offset);
println!("Public inputs: {:?}", public_inputs);
println!("Private inputs: {:?}", private_inputs);
let pk_path = sub_matches.value_of("provingkey").unwrap();
let proof_path = sub_matches.value_of("proofpath").unwrap();
// run libsnark
println!(
"generate-proof successful: {:?}",
backend.generate_proof(pk_path, proof_path, public_inputs, private_inputs)
);
}
// determine variable order
let var_inf_path = Path::new(sub_matches.value_of("meta-information").unwrap());
let var_inf_file = match File::open(&var_inf_path) {
Ok(file) => file,
Err(why) => panic!("couldn't open {}: {}", var_inf_path.display(), why),
};
let var_reader = BufReader::new(var_inf_file);
let mut var_lines = var_reader.lines();
// get private inputs offset
let private_inputs_offset;
if let Some(Ok(ref o)) = var_lines.nth(1) {
// consumes first 2 lines
private_inputs_offset = o.parse().expect("Failed parsing private inputs offset");
} else {
panic!("Error reading private inputs offset");
}
// get variables vector
let mut variables: Vec<String> = Vec::new();
if let Some(Ok(ref v)) = var_lines.nth(1) {
let iter = v.split_whitespace();
for i in iter {
variables.push(i.to_string());
}
} else {
panic!("Error reading variables.");
}
println!("Using Witness: {:?}", witness_map);
let witness: Vec<_> = variables.iter().map(|x| witness_map[x].clone()).collect();
// split witness into public and private inputs at offset
let mut public_inputs: Vec<_> = witness.clone();
let private_inputs: Vec<_> = public_inputs.split_off(private_inputs_offset);
println!("Public inputs: {:?}", public_inputs);
println!("Private inputs: {:?}", private_inputs);
let pk_path = sub_matches.value_of("provingkey").unwrap();
let proof_path = sub_matches.value_of("proofpath").unwrap();
// run libsnark
println!(
"generate-proof successful: {:?}",
backend.generate_proof(pk_path, proof_path, public_inputs, private_inputs)
);
}
_ => unimplemented!(), // Either no subcommand or one not tested for...
}

View file

@ -26,7 +26,9 @@ fn main() {
.include(libsnark_source_path.join("depends/libff"))
.include(libsnark_source_path.join("depends/libfqfft"))
.define("CURVE_ALT_BN128", None)
.file("lib/wraplibsnark.cpp")
.file("lib/util.cpp")
.file("lib/gm17.cpp")
.file("lib/pghr13.cpp")
.compile("libwraplibsnark.a");
cc::Build::new()

249
zokrates_core/lib/gm17.cpp Normal file
View file

@ -0,0 +1,249 @@
/**
* @file wraplibsnark.cpp
* @author Jacob Eberhardt <jacob.eberhardt@tu-berlin.de
* @author Dennis Kuhnert <dennis.kuhnert@campus.tu-berlin.de>
* @date 2017
*/
#include "util.hpp"
#include "gm17.hpp"
#include <fstream>
#include <iostream>
#include <cassert>
#include <iomanip>
// contains definition of alt_bn128 ec public parameters
#include "libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp"
// contains required interfaces and types (keypair, proof, generator, prover, verifier)
#include <libsnark/zk_proof_systems/ppzksnark/r1cs_se_ppzksnark/r1cs_se_ppzksnark.hpp>
typedef long integer_coeff_t;
using namespace std;
using namespace libsnark;
namespace gm17 {
//takes input and puts it into constraint system
r1cs_se_ppzksnark_constraint_system<libff::alt_bn128_pp> createConstraintSystem(const uint8_t* A, const uint8_t* B, const uint8_t* C, int A_len, int B_len, int C_len, int constraints, int variables, int inputs)
{
r1cs_se_ppzksnark_constraint_system<libff::alt_bn128_pp> cs;
cs.primary_input_size = inputs;
cs.auxiliary_input_size = variables - inputs - 1; // ~one not included
cout << "num variables: " << variables <<endl;
cout << "num constraints: " << constraints <<endl;
cout << "num inputs: " << inputs <<endl;
struct VariableValueMapping {
int constraint_id;
int variable_id;
uint8_t variable_value[32];
};
const VariableValueMapping* A_vvmap = (VariableValueMapping*) A;
const VariableValueMapping* B_vvmap = (VariableValueMapping*) B;
const VariableValueMapping* C_vvmap = (VariableValueMapping*) C;
int A_id = 0;
int B_id = 0;
int C_id = 0;
libff::alt_bn128_pp::init_public_params();
for (int row = 0; row < constraints; row++) {
linear_combination<libff::Fr<libff::alt_bn128_pp> > lin_comb_A, lin_comb_B, lin_comb_C;
while (A_id < A_len && A_vvmap[A_id].constraint_id == row) {
libff::bigint<libff::alt_bn128_r_limbs> value = libsnarkBigintFromBytes(A_vvmap[A_id].variable_value);
if (!value.is_zero())
lin_comb_A.add_term(A_vvmap[A_id].variable_id, value);
A_id++;
}
while (B_id < B_len && B_vvmap[B_id].constraint_id == row) {
libff::bigint<libff::alt_bn128_r_limbs> value = libsnarkBigintFromBytes(B_vvmap[B_id].variable_value);
if (!value.is_zero())
lin_comb_B.add_term(B_vvmap[B_id].variable_id, value);
B_id++;
}
while (C_id < C_len && C_vvmap[C_id].constraint_id == row) {
libff::bigint<libff::alt_bn128_r_limbs> value = libsnarkBigintFromBytes(C_vvmap[C_id].variable_value);
if (!value.is_zero())
lin_comb_C.add_term(C_vvmap[C_id].variable_id, value);
C_id++;
}
cs.add_constraint(r1cs_constraint<libff::Fr<libff::alt_bn128_pp> >(lin_comb_A, lin_comb_B, lin_comb_C));
}
return cs;
}
// keypair generateKeypair(constraints)
r1cs_se_ppzksnark_keypair<libff::alt_bn128_pp> generateKeypair(const r1cs_se_ppzksnark_constraint_system<libff::alt_bn128_pp> &cs){
// from r1cs_se_ppzksnark.hpp
return r1cs_se_ppzksnark_generator<libff::alt_bn128_pp>(cs);
}
void serializeProvingKeyToFile(r1cs_se_ppzksnark_proving_key<libff::alt_bn128_pp> pk, const char* pk_path){
writeToFile(pk_path, pk);
}
r1cs_se_ppzksnark_proving_key<libff::alt_bn128_pp> deserializeProvingKeyFromFile(const char* pk_path){
return loadFromFile<r1cs_se_ppzksnark_proving_key<libff::alt_bn128_pp>>(pk_path);
}
void serializeVerificationKeyToFile(r1cs_se_ppzksnark_verification_key<libff::alt_bn128_pp> vk, const char* vk_path){
std::stringstream ss;
unsigned queryLength = vk.query.size();
ss << "\t\tvk.H = " << outputPointG2AffineAsHex(vk.H) << endl;
ss << "\t\tvk.Galpha = " << outputPointG1AffineAsHex(vk.G_alpha) << endl;
ss << "\t\tvk.Hbeta = " << outputPointG2AffineAsHex(vk.H_beta) << endl;
ss << "\t\tvk.Ggamma = " << outputPointG1AffineAsHex(vk.G_gamma) << endl;
ss << "\t\tvk.Hgamma = " << outputPointG2AffineAsHex(vk.H_gamma) << endl;
ss << "\t\tvk.query.len() = " << queryLength << endl;
for (size_t i = 0; i < queryLength; ++i)
{
auto vkqueryi = outputPointG1AffineAsHex(vk.query[i]);
ss << "\t\tvk.IC[" << i << "] = " << vkqueryi << endl;
}
std::ofstream fh;
fh.open(vk_path, std::ios::binary);
ss.rdbuf()->pubseekpos(0, std::ios_base::out);
fh << ss.rdbuf();
fh.flush();
fh.close();
}
// compliant with solidty verification example
void exportVerificationKey(r1cs_se_ppzksnark_keypair<libff::alt_bn128_pp> keypair){
auto vk = keypair.vk;
unsigned queryLength = vk.query.size();
cout << "\t\tvk.H = " << outputPointG2AffineAsHex(vk.H) << endl;
cout << "\t\tvk.Galpha = " << outputPointG1AffineAsHex(vk.G_alpha) << endl;
cout << "\t\tvk.Hbeta = " << outputPointG2AffineAsHex(vk.H_beta) << endl;
cout << "\t\tvk.Ggamma = " << outputPointG1AffineAsHex(vk.G_gamma) << endl;
cout << "\t\tvk.Hgamma = " << outputPointG2AffineAsHex(vk.H_gamma) << endl;
cout << "\t\tvk.query.len() = " << queryLength << endl;
for (size_t i = 0; i < queryLength; ++i)
{
auto vkqueryi = outputPointG1AffineAsHex(vk.query[i]);
cout << "\t\tvk.query[" << i << "] = " << vkqueryi << endl;
}
cout << "\t\t}" << endl;
}
void printProof(r1cs_se_ppzksnark_proof<libff::alt_bn128_pp> proof, const char* proof_path, const uint8_t* public_inputs,
int public_inputs_length){
cout << "Proof:"<< endl;
cout << "A = Pairing.G1Point(" << outputPointG1AffineAsHex(proof.A)<< ");" << endl;
cout << "B = Pairing.G2Point(" << outputPointG2AffineAsHex(proof.B)<< ");" << endl;
cout << "C = Pairing.G1Point(" << outputPointG1AffineAsHex(proof.C)<< ");" << endl;
//create JSON file
std::stringstream ss;
ss << "{" << "\n";
ss << "\t\"proof\":" << "\n";
ss << "\t{" << "\n";
ss << "\t\t\"A\":" <<outputPointG1AffineAsHexJson(proof.A) << ",\n";
ss << "\t\t\"B\":" << "\n";
ss << "\t\t\t" << outputPointG2AffineAsHexJson(proof.B) << ",\n";
ss << "\t\t\n";
ss << "\t\t\"C\":" <<outputPointG1AffineAsHexJson(proof.C) << ",\n";
ss << "\t}," << "\n";
//add input to json
ss << "\t\"input\":" << "[";
for (int i = 1; i < public_inputs_length; i++) {
if(i!=1){
ss << ",";
}
ss << libsnarkBigintFromBytes(public_inputs + i*32);
}
ss << "]";
ss << "}";
std::string s = ss.str();
//write json string to proof_path
writeToFile(proof_path, s);
}
// compliant with solidty verification example
void exportInput(r1cs_primary_input<libff::Fr<libff::alt_bn128_pp>> input){
cout << "\tInput in Solidity compliant format:{" << endl;
for (size_t i = 0; i < input.size(); ++i)
{
cout << "\t\tinput[" << i << "] = " << HexStringFromLibsnarkBigint(input[i].as_bigint()) << ";" << endl;
}
cout << "\t\t}" << endl;
}
}
bool _gm17_setup(const uint8_t* A, const uint8_t* B, const uint8_t* C, int A_len, int B_len, int C_len, int constraints, int variables, int inputs, const char* pk_path, const char* vk_path)
{
libff::inhibit_profiling_info = true;
libff::inhibit_profiling_counters = true;
//initialize curve parameters
libff::alt_bn128_pp::init_public_params();
auto cs = gm17::createConstraintSystem(A, B, C, A_len, B_len, C_len, constraints, variables, inputs);
assert(cs.num_variables() >= (unsigned)inputs);
assert(cs.num_inputs() == (unsigned)inputs);
assert(cs.num_constraints() == (unsigned)constraints);
// create keypair
auto keypair = r1cs_se_ppzksnark_generator<libff::alt_bn128_pp>(cs);
// Export vk and pk to files
gm17::serializeProvingKeyToFile(keypair.pk, pk_path);
gm17::serializeVerificationKeyToFile(keypair.vk, vk_path);
// Print VerificationKey in Solidity compatible format
gm17::exportVerificationKey(keypair);
return true;
}
bool _gm17_generate_proof(const char* pk_path, const char* proof_path, const uint8_t* public_inputs, int public_inputs_length, const uint8_t* private_inputs, int private_inputs_length)
{
libff::inhibit_profiling_info = true;
libff::inhibit_profiling_counters = true;
//initialize curve parameters
libff::alt_bn128_pp::init_public_params();
auto pk = gm17::deserializeProvingKeyFromFile(pk_path);
// assign variables based on witness values, excludes ~one
r1cs_variable_assignment<libff::Fr<libff::alt_bn128_pp> > full_variable_assignment;
for (int i = 1; i < public_inputs_length; i++) {
full_variable_assignment.push_back(libff::Fr<libff::alt_bn128_pp>(libsnarkBigintFromBytes(public_inputs + i*32)));
}
for (int i = 0; i < private_inputs_length; i++) {
full_variable_assignment.push_back(libff::Fr<libff::alt_bn128_pp>(libsnarkBigintFromBytes(private_inputs + i*32)));
}
// split up variables into primary and auxiliary inputs. Does *NOT* include the constant 1
// Public variables belong to primary input, private variables are auxiliary input.
r1cs_primary_input<libff::Fr<libff::alt_bn128_pp>> primary_input(full_variable_assignment.begin(), full_variable_assignment.begin() + public_inputs_length-1);
r1cs_primary_input<libff::Fr<libff::alt_bn128_pp>> auxiliary_input(full_variable_assignment.begin() + public_inputs_length-1, full_variable_assignment.end());
// for debugging
// cout << "full variable assignment:"<< endl << full_variable_assignment;
// cout << "primary input:"<< endl << primary_input;
// cout << "auxiliary input:"<< endl << auxiliary_input;
// Proof Generation
auto proof = r1cs_se_ppzksnark_prover<libff::alt_bn128_pp>(pk, primary_input, auxiliary_input);
// print proof
gm17::printProof(proof, proof_path, public_inputs, public_inputs_length);
// TODO? print inputs
return true;
}

View file

@ -0,0 +1,40 @@
/**
* @file gm17.hpp
* @author Jacob Eberhardt <jacob.eberhardt@tu-berlin.de
* @author Dennis Kuhnert <dennis.kuhnert@campus.tu-berlin.de>
* @date 2017
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdint.h>
bool _gm17_setup(const uint8_t* A,
const uint8_t* B,
const uint8_t* C,
int A_len,
int B_len,
int C_len,
int constraints,
int variables,
int inputs,
const char* pk_path,
const char* vk_path
);
bool _gm17_generate_proof(const char* pk_path,
const char* proof_path,
const uint8_t* public_inputs,
int public_inputs_length,
const uint8_t* private_inputs,
int private_inputs_length
);
#ifdef __cplusplus
} // extern "C"
#endif

View file

@ -5,7 +5,8 @@
* @date 2017
*/
#include "wraplibsnark.hpp"
#include "util.hpp"
#include "pghr13.hpp"
#include <fstream>
#include <iostream>
#include <cassert>
@ -21,80 +22,7 @@ typedef long integer_coeff_t;
using namespace std;
using namespace libsnark;
// conversion byte[32] <-> libsnark bigint.
libff::bigint<libff::alt_bn128_r_limbs> libsnarkBigintFromBytes(const uint8_t* _x)
{
libff::bigint<libff::alt_bn128_r_limbs> x;
for (unsigned i = 0; i < 4; i++) {
for (unsigned j = 0; j < 8; j++) {
x.data[3 - i] |= uint64_t(_x[i * 8 + j]) << (8 * (7-j));
}
}
return x;
}
std::string HexStringFromLibsnarkBigint(libff::bigint<libff::alt_bn128_r_limbs> _x){
uint8_t x[32];
for (unsigned i = 0; i < 4; i++)
for (unsigned j = 0; j < 8; j++)
x[i * 8 + j] = uint8_t(uint64_t(_x.data[3 - i]) >> (8 * (7 - j)));
std::stringstream ss;
ss << std::setfill('0');
for (unsigned i = 0; i<32; i++) {
ss << std::hex << std::setw(2) << (int)x[i];
}
std::string str = ss.str();
return str.erase(0, min(str.find_first_not_of('0'), str.size()-1));
}
std::string outputPointG1AffineAsHex(libff::alt_bn128_G1 _p)
{
libff::alt_bn128_G1 aff = _p;
aff.to_affine_coordinates();
return
"0x" +
HexStringFromLibsnarkBigint(aff.X.as_bigint()) +
", 0x" +
HexStringFromLibsnarkBigint(aff.Y.as_bigint());
}
std::string outputPointG1AffineAsHexJson(libff::alt_bn128_G1 _p)
{
libff::alt_bn128_G1 aff = _p;
aff.to_affine_coordinates();
return
"[\"0x" +
HexStringFromLibsnarkBigint(aff.X.as_bigint()) +
"\", \"0x" +
HexStringFromLibsnarkBigint(aff.Y.as_bigint())+"\"]";
}
std::string outputPointG2AffineAsHex(libff::alt_bn128_G2 _p)
{
libff::alt_bn128_G2 aff = _p;
aff.to_affine_coordinates();
return
"[0x" +
HexStringFromLibsnarkBigint(aff.X.c1.as_bigint()) + ", 0x" +
HexStringFromLibsnarkBigint(aff.X.c0.as_bigint()) + "], [0x" +
HexStringFromLibsnarkBigint(aff.Y.c1.as_bigint()) + ", 0x" +
HexStringFromLibsnarkBigint(aff.Y.c0.as_bigint()) + "]";
}
std::string outputPointG2AffineAsHexJson(libff::alt_bn128_G2 _p)
{
libff::alt_bn128_G2 aff = _p;
aff.to_affine_coordinates();
return
"[[\"0x" +
HexStringFromLibsnarkBigint(aff.X.c1.as_bigint()) + "\", \"0x" +
HexStringFromLibsnarkBigint(aff.X.c0.as_bigint()) + "\"], [\"0x" +
HexStringFromLibsnarkBigint(aff.Y.c1.as_bigint()) + "\", \"0x" +
HexStringFromLibsnarkBigint(aff.Y.c0.as_bigint()) + "\"]]";
}
namespace pghr13 {
//takes input and puts it into constraint system
r1cs_ppzksnark_constraint_system<libff::alt_bn128_pp> createConstraintSystem(const uint8_t* A, const uint8_t* B, const uint8_t* C, int A_len, int B_len, int C_len, int constraints, int variables, int inputs)
@ -156,36 +84,6 @@ r1cs_ppzksnark_keypair<libff::alt_bn128_pp> generateKeypair(const r1cs_ppzksnark
return r1cs_ppzksnark_generator<libff::alt_bn128_pp>(cs);
}
template<typename T>
void writeToFile(std::string path, T& obj) {
std::stringstream ss;
ss << obj;
std::ofstream fh;
fh.open(path, std::ios::binary);
ss.rdbuf()->pubseekpos(0, std::ios_base::out);
fh << ss.rdbuf();
fh.flush();
fh.close();
}
template<typename T>
T loadFromFile(std::string path) {
std::stringstream ss;
std::ifstream fh(path, std::ios::binary);
assert(fh.is_open());
ss << fh.rdbuf();
fh.close();
ss.rdbuf()->pubseekpos(0, std::ios_base::in);
T obj;
ss >> obj;
return obj;
}
void serializeProvingKeyToFile(r1cs_ppzksnark_proving_key<libff::alt_bn128_pp> pk, const char* pk_path){
writeToFile(pk_path, pk);
}
@ -224,38 +122,28 @@ void serializeVerificationKeyToFile(r1cs_ppzksnark_verification_key<libff::alt_b
// compliant with solidty verification example
void exportVerificationKey(r1cs_ppzksnark_keypair<libff::alt_bn128_pp> keypair){
unsigned icLength = keypair.vk.encoded_IC_query.rest.indices.size() + 1;
auto vk = keypair.vk;
unsigned icLength = vk.encoded_IC_query.rest.indices.size() + 1;
cout << "\tVerification key in Solidity compliant format:{" << endl;
cout << "\t\tvk.A = Pairing.G2Point(" << outputPointG2AffineAsHex(keypair.vk.alphaA_g2) << ");" << endl;
cout << "\t\tvk.B = Pairing.G1Point(" << outputPointG1AffineAsHex(keypair.vk.alphaB_g1) << ");" << endl;
cout << "\t\tvk.C = Pairing.G2Point(" << outputPointG2AffineAsHex(keypair.vk.alphaC_g2) << ");" << endl;
cout << "\t\tvk.gamma = Pairing.G2Point(" << outputPointG2AffineAsHex(keypair.vk.gamma_g2) << ");" << endl;
cout << "\t\tvk.gammaBeta1 = Pairing.G1Point(" << outputPointG1AffineAsHex(keypair.vk.gamma_beta_g1) << ");" << endl;
cout << "\t\tvk.gammaBeta2 = Pairing.G2Point(" << outputPointG2AffineAsHex(keypair.vk.gamma_beta_g2) << ");" << endl;
cout << "\t\tvk.Z = Pairing.G2Point(" << outputPointG2AffineAsHex(keypair.vk.rC_Z_g2) << ");" << endl;
cout << "\t\tvk.A = Pairing.G2Point(" << outputPointG2AffineAsHex(vk.alphaA_g2) << ");" << endl;
cout << "\t\tvk.B = Pairing.G1Point(" << outputPointG1AffineAsHex(vk.alphaB_g1) << ");" << endl;
cout << "\t\tvk.C = Pairing.G2Point(" << outputPointG2AffineAsHex(vk.alphaC_g2) << ");" << endl;
cout << "\t\tvk.gamma = Pairing.G2Point(" << outputPointG2AffineAsHex(vk.gamma_g2) << ");" << endl;
cout << "\t\tvk.gammaBeta1 = Pairing.G1Point(" << outputPointG1AffineAsHex(vk.gamma_beta_g1) << ");" << endl;
cout << "\t\tvk.gammaBeta2 = Pairing.G2Point(" << outputPointG2AffineAsHex(vk.gamma_beta_g2) << ");" << endl;
cout << "\t\tvk.Z = Pairing.G2Point(" << outputPointG2AffineAsHex(vk.rC_Z_g2) << ");" << endl;
cout << "\t\tvk.IC = new Pairing.G1Point[](" << icLength << ");" << endl;
cout << "\t\tvk.IC[0] = Pairing.G1Point(" << outputPointG1AffineAsHex(keypair.vk.encoded_IC_query.first) << ");" << endl;
cout << "\t\tvk.IC[0] = Pairing.G1Point(" << outputPointG1AffineAsHex(vk.encoded_IC_query.first) << ");" << endl;
for (size_t i = 1; i < icLength; ++i)
{
auto vkICi = outputPointG1AffineAsHex(keypair.vk.encoded_IC_query.rest.values[i - 1]);
auto vkICi = outputPointG1AffineAsHex(vk.encoded_IC_query.rest.values[i - 1]);
cout << "\t\tvk.IC[" << i << "] = Pairing.G1Point(" << vkICi << ");" << endl;
}
cout << "\t\t}" << endl;
}
// compliant with solidty verification example
void exportInput(r1cs_primary_input<libff::Fr<libff::alt_bn128_pp>> input){
cout << "\tInput in Solidity compliant format:{" << endl;
for (size_t i = 0; i < input.size(); ++i)
{
cout << "\t\tinput[" << i << "] = " << HexStringFromLibsnarkBigint(input[i].as_bigint()) << ";" << endl;
}
cout << "\t\t}" << endl;
}
void printProof(r1cs_ppzksnark_proof<libff::alt_bn128_pp> proof, const char* proof_path, const uint8_t* public_inputs,
int public_inputs_length){
cout << "Proof:"<< endl;
@ -300,6 +188,18 @@ void printProof(r1cs_ppzksnark_proof<libff::alt_bn128_pp> proof, const char* pro
writeToFile(proof_path, s);
}
}
// compliant with solidty verification example
void exportInput(r1cs_primary_input<libff::Fr<libff::alt_bn128_pp>> input){
cout << "\tInput in Solidity compliant format:{" << endl;
for (size_t i = 0; i < input.size(); ++i)
{
cout << "\t\tinput[" << i << "] = " << HexStringFromLibsnarkBigint(input[i].as_bigint()) << ";" << endl;
}
cout << "\t\t}" << endl;
}
bool _pghr13_setup(const uint8_t* A, const uint8_t* B, const uint8_t* C, int A_len, int B_len, int C_len, int constraints, int variables, int inputs, const char* pk_path, const char* vk_path)
{
libff::inhibit_profiling_info = true;
@ -308,7 +208,7 @@ bool _pghr13_setup(const uint8_t* A, const uint8_t* B, const uint8_t* C, int A_l
//initialize curve parameters
libff::alt_bn128_pp::init_public_params();
auto cs = createConstraintSystem(A, B, C, A_len, B_len, C_len, constraints, variables, inputs);
auto cs = pghr13::createConstraintSystem(A, B, C, A_len, B_len, C_len, constraints, variables, inputs);
assert(cs.num_variables() >= (unsigned)inputs);
assert(cs.num_inputs() == (unsigned)inputs);
@ -318,11 +218,11 @@ bool _pghr13_setup(const uint8_t* A, const uint8_t* B, const uint8_t* C, int A_l
auto keypair = r1cs_ppzksnark_generator<libff::alt_bn128_pp>(cs);
// Export vk and pk to files
serializeProvingKeyToFile(keypair.pk, pk_path);
serializeVerificationKeyToFile(keypair.vk, vk_path);
pghr13::serializeProvingKeyToFile(keypair.pk, pk_path);
pghr13::serializeVerificationKeyToFile(keypair.vk, vk_path);
// Print VerificationKey in Solidity compatible format
exportVerificationKey(keypair);
pghr13::exportVerificationKey(keypair);
return true;
}
@ -334,7 +234,7 @@ bool _pghr13_generate_proof(const char* pk_path, const char* proof_path, const u
//initialize curve parameters
libff::alt_bn128_pp::init_public_params();
auto pk = deserializeProvingKeyFromFile(pk_path);
auto pk = pghr13::deserializeProvingKeyFromFile(pk_path);
// assign variables based on witness values, excludes ~one
r1cs_variable_assignment<libff::Fr<libff::alt_bn128_pp> > full_variable_assignment;
@ -359,7 +259,7 @@ bool _pghr13_generate_proof(const char* pk_path, const char* proof_path, const u
auto proof = r1cs_ppzksnark_prover<libff::alt_bn128_pp>(pk, primary_input, auxiliary_input);
// print proof
printProof(proof, proof_path, public_inputs, public_inputs_length);
pghr13::printProof(proof, proof_path, public_inputs, public_inputs_length);
// TODO? print inputs
return true;

View file

@ -1,10 +1,14 @@
/**
* @file wraplibsnark.hpp
* @file pghr13.hpp
* @author Jacob Eberhardt <jacob.eberhardt@tu-berlin.de
* @author Dennis Kuhnert <dennis.kuhnert@campus.tu-berlin.de>
* @date 2017
*/
#pragma once
#include "util.hpp"
#ifdef __cplusplus
extern "C" {
#endif

View file

@ -0,0 +1,85 @@
/**
* @file wraplibsnark.cpp
* @author Jacob Eberhardt <jacob.eberhardt@tu-berlin.de
* @author Dennis Kuhnert <dennis.kuhnert@campus.tu-berlin.de>
* @date 2017
*/
#include "util.hpp"
using namespace std;
// conversion byte[32] <-> libsnark bigint.
libff::bigint<libff::alt_bn128_r_limbs> libsnarkBigintFromBytes(const uint8_t* _x)
{
libff::bigint<libff::alt_bn128_r_limbs> x;
for (unsigned i = 0; i < 4; i++) {
for (unsigned j = 0; j < 8; j++) {
x.data[3 - i] |= uint64_t(_x[i * 8 + j]) << (8 * (7-j));
}
}
return x;
}
std::string HexStringFromLibsnarkBigint(libff::bigint<libff::alt_bn128_r_limbs> _x){
uint8_t x[32];
for (unsigned i = 0; i < 4; i++)
for (unsigned j = 0; j < 8; j++)
x[i * 8 + j] = uint8_t(uint64_t(_x.data[3 - i]) >> (8 * (7 - j)));
std::stringstream ss;
ss << std::setfill('0');
for (unsigned i = 0; i<32; i++) {
ss << std::hex << std::setw(2) << (int)x[i];
}
std::string str = ss.str();
return str.erase(0, min(str.find_first_not_of('0'), str.size()-1));
}
std::string outputPointG1AffineAsHex(libff::alt_bn128_G1 _p)
{
libff::alt_bn128_G1 aff = _p;
aff.to_affine_coordinates();
return
"0x" +
HexStringFromLibsnarkBigint(aff.X.as_bigint()) +
", 0x" +
HexStringFromLibsnarkBigint(aff.Y.as_bigint());
}
std::string outputPointG1AffineAsHexJson(libff::alt_bn128_G1 _p)
{
libff::alt_bn128_G1 aff = _p;
aff.to_affine_coordinates();
return
"[\"0x" +
HexStringFromLibsnarkBigint(aff.X.as_bigint()) +
"\", \"0x" +
HexStringFromLibsnarkBigint(aff.Y.as_bigint())+"\"]";
}
std::string outputPointG2AffineAsHex(libff::alt_bn128_G2 _p)
{
libff::alt_bn128_G2 aff = _p;
aff.to_affine_coordinates();
return
"[0x" +
HexStringFromLibsnarkBigint(aff.X.c1.as_bigint()) + ", 0x" +
HexStringFromLibsnarkBigint(aff.X.c0.as_bigint()) + "], [0x" +
HexStringFromLibsnarkBigint(aff.Y.c1.as_bigint()) + ", 0x" +
HexStringFromLibsnarkBigint(aff.Y.c0.as_bigint()) + "]";
}
std::string outputPointG2AffineAsHexJson(libff::alt_bn128_G2 _p)
{
libff::alt_bn128_G2 aff = _p;
aff.to_affine_coordinates();
return
"[[\"0x" +
HexStringFromLibsnarkBigint(aff.X.c1.as_bigint()) + "\", \"0x" +
HexStringFromLibsnarkBigint(aff.X.c0.as_bigint()) + "\"], [\"0x" +
HexStringFromLibsnarkBigint(aff.Y.c1.as_bigint()) + "\", \"0x" +
HexStringFromLibsnarkBigint(aff.Y.c0.as_bigint()) + "\"]]";
}

View file

@ -0,0 +1,50 @@
#pragma once
// contains definition of alt_bn128 ec public parameters
#include "libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp"
#include <fstream>
#include <iostream>
#include <cassert>
#include <iomanip>
libff::bigint<libff::alt_bn128_r_limbs> libsnarkBigintFromBytes(const uint8_t* _x);
std::string HexStringFromLibsnarkBigint(libff::bigint<libff::alt_bn128_r_limbs> _x);
std::string outputPointG1AffineAsHex(libff::alt_bn128_G1 _p);
std::string outputPointG1AffineAsHexJson(libff::alt_bn128_G1 _p);
std::string outputPointG2AffineAsHex(libff::alt_bn128_G2 _p);
std::string outputPointG2AffineAsHexJson(libff::alt_bn128_G2 _p);
template<typename T>
void writeToFile(std::string path, T& obj) {
std::stringstream ss;
ss << obj;
std::ofstream fh;
fh.open(path, std::ios::binary);
ss.rdbuf()->pubseekpos(0, std::ios_base::out);
fh << ss.rdbuf();
fh.flush();
fh.close();
}
template<typename T>
T loadFromFile(std::string path) {
std::stringstream ss;
std::ifstream fh(path, std::ios::binary);
assert(fh.is_open());
ss << fh.rdbuf();
fh.close();
ss.rdbuf()->pubseekpos(0, std::ios_base::in);
T obj;
ss >> obj;
return obj;
}

View file

@ -34,4 +34,3 @@ pub mod libsnark;
#[cfg(feature = "libsnark")]
pub mod proof_system;
pub mod r1cs;
pub mod verification;

View file

@ -0,0 +1,277 @@
extern crate libc;
use self::libc::{c_char, c_int, uint8_t};
use flat_absy::flat_variable::FlatVariable;
use proof_system::utils::{prepare_generate_proof, prepare_setup, SOLIDITY_PAIRING_LIB};
use proof_system::ProofSystem;
use regex::Regex;
use std::fs::File;
use std::io::{BufRead, BufReader};
use field::FieldPrime;
pub struct GM17 {}
impl GM17 {
pub fn new() -> GM17 {
GM17 {}
}
}
extern "C" {
fn _gm17_setup(
A: *const uint8_t,
B: *const uint8_t,
C: *const uint8_t,
A_len: c_int,
B_len: c_int,
C_len: c_int,
constraints: c_int,
variables: c_int,
inputs: c_int,
pk_path: *const c_char,
vk_path: *const c_char,
) -> bool;
fn _gm17_generate_proof(
pk_path: *const c_char,
proof_path: *const c_char,
publquery_inputs: *const uint8_t,
publquery_inputs_length: c_int,
private_inputs: *const uint8_t,
private_inputs_length: c_int,
) -> bool;
}
impl ProofSystem for GM17 {
fn setup(
&self,
variables: Vec<FlatVariable>,
a: Vec<Vec<(usize, FieldPrime)>>,
b: Vec<Vec<(usize, FieldPrime)>>,
c: Vec<Vec<(usize, FieldPrime)>>,
num_inputs: usize,
pk_path: &str,
vk_path: &str,
) -> bool {
let (
a_arr,
b_arr,
c_arr,
a_vec,
b_vec,
c_vec,
num_constraints,
num_variables,
num_inputs,
pk_path_cstring,
vk_path_cstring,
) = prepare_setup(variables, a, b, c, num_inputs, pk_path, vk_path);
unsafe {
_gm17_setup(
a_arr.as_ptr(),
b_arr.as_ptr(),
c_arr.as_ptr(),
a_vec.len() as i32,
b_vec.len() as i32,
c_vec.len() as i32,
num_constraints as i32,
num_variables as i32,
num_inputs as i32,
pk_path_cstring.as_ptr(),
vk_path_cstring.as_ptr(),
)
}
}
fn generate_proof(
&self,
pk_path: &str,
proof_path: &str,
publquery_inputs: Vec<FieldPrime>,
private_inputs: Vec<FieldPrime>,
) -> bool {
let (
pk_path_cstring,
proof_path_cstring,
publquery_inputs_arr,
publquery_inputs_length,
private_inputs_arr,
private_inputs_length,
) = prepare_generate_proof(pk_path, proof_path, publquery_inputs, private_inputs);
unsafe {
_gm17_generate_proof(
pk_path_cstring.as_ptr(),
proof_path_cstring.as_ptr(),
publquery_inputs_arr[0].as_ptr(),
publquery_inputs_length as i32,
private_inputs_arr[0].as_ptr(),
private_inputs_length as i32,
)
}
}
fn export_solidity_verifier(&self, reader: BufReader<File>) -> String {
let mut lines = reader.lines();
let mut template_text = String::from(CONTRACT_TEMPLATE);
let query_template = String::from("vk.query[index] = Pairing.G1Point(points);"); //copy this for each entry
//replace things in template
let vk_regex = Regex::new(r#"(<%vk_[^i%]*%>)"#).unwrap();
let vk_query_len_regex = Regex::new(r#"(<%vk_query_length%>)"#).unwrap();
let vk_query_index_regex = Regex::new(r#"index"#).unwrap();
let vk_query_points_regex = Regex::new(r#"points"#).unwrap();
let vk_query_repeat_regex = Regex::new(r#"(<%vk_query_pts%>)"#).unwrap();
let vk_input_len_regex = Regex::new(r#"(<%vk_input_length%>)"#).unwrap();
for _ in 0..5 {
let current_line: String = lines
.next()
.expect("Unexpected end of file in verification key!")
.unwrap();
let current_line_split: Vec<&str> = current_line.split("=").collect();
assert_eq!(current_line_split.len(), 2);
template_text = vk_regex
.replace(template_text.as_str(), current_line_split[1].trim())
.into_owned();
}
let current_line: String = lines
.next()
.expect("Unexpected end of file in verification key!")
.unwrap();
let current_line_split: Vec<&str> = current_line.split("=").collect();
assert_eq!(current_line_split.len(), 2);
let query_count: i32 = current_line_split[1].trim().parse().unwrap();
template_text = vk_query_len_regex
.replace(template_text.as_str(), format!("{}", query_count).as_str())
.into_owned();
template_text = vk_input_len_regex
.replace(
template_text.as_str(),
format!("{}", query_count - 1).as_str(),
)
.into_owned();
let mut query_repeat_text = String::new();
for x in 0..query_count {
let mut curr_template = query_template.clone();
let current_line: String = lines
.next()
.expect("Unexpected end of file in verification key!")
.unwrap();
let current_line_split: Vec<&str> = current_line.split("=").collect();
assert_eq!(current_line_split.len(), 2);
curr_template = vk_query_index_regex
.replace(curr_template.as_str(), format!("{}", x).as_str())
.into_owned();
curr_template = vk_query_points_regex
.replace(curr_template.as_str(), current_line_split[1].trim())
.into_owned();
query_repeat_text.push_str(curr_template.as_str());
if x < query_count - 1 {
query_repeat_text.push_str("\n ");
}
}
template_text = vk_query_repeat_regex
.replace(template_text.as_str(), query_repeat_text.as_str())
.into_owned();
format!("{}{}", SOLIDITY_PAIRING_LIB, template_text)
}
}
const CONTRACT_TEMPLATE: &str = r#"
contract Verifier {
using Pairing for *;
struct VerifyingKey {
Pairing.G2Point H;
Pairing.G1Point Galpha;
Pairing.G2Point Hbeta;
Pairing.G1Point Ggamma;
Pairing.G2Point Hgamma;
Pairing.G1Point[] query;
}
struct Proof {
Pairing.G1Point A;
Pairing.G2Point B;
Pairing.G1Point C;
}
function verifyingKey() pure internal returns (VerifyingKey vk) {
vk.H = Pairing.G2Point(<%vk_h%>);
vk.Galpha = Pairing.G1Point(<%vk_g_alpha%>);
vk.Hbeta = Pairing.G2Point(<%vk_h_beta%>);
vk.Ggamma = Pairing.G1Point(<%vk_g_gamma%>);
vk.Hgamma = Pairing.G2Point(<%vk_h_gamma%>);
vk.query = new Pairing.G1Point[](<%vk_query_length%>);
<%vk_query_pts%>
}
function verify(uint[] input, Proof proof) internal returns (uint) {
VerifyingKey memory vk = verifyingKey();
require(input.length + 1 == vk.query.length);
// Compute the linear combination vk_x
Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0);
for (uint i = 0; i < input.length; i++)
vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.query[i + 1], input[i]));
vk_x = Pairing.addition(vk_x, vk.query[0]);
/**
* e(A*G^{alpha}, B*H^{beta}) = e(G^{alpha}, H^{beta}) * e(G^{psi}, H^{gamma})
* * e(C, H)
* where psi = \sum_{i=0}^l input_i pvk.query[i]
*/
if (!Pairing.pairingProd4(vk.Galpha, vk.Hbeta, vk_x, vk.Hgamma, proof.C, vk.H, Pairing.negate(Pairing.addition(proof.A, vk.Galpha)), Pairing.addition(proof.B, vk.Hbeta))) return 1;
/**
* e(A, H^{gamma}) = e(G^{gamma}, B)
*/
if (!Pairing.pairingProd2(proof.A, vk.Hgamma, Pairing.negate(vk.Ggamma), proof.B)) return 2;
return 0;
}
event Verified(string s);
function verifyTx(
uint[2] a,
uint[2][2] b,
uint[2] c,
uint[<%vk_input_length%>] input
) public returns (bool r) {
Proof memory proof;
proof.A = Pairing.G1Point(a[0], a[1]);
proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]);
proof.C = Pairing.G1Point(c[0], c[1]);
uint[] memory inputValues = new uint[](input.length);
for(uint i = 0; i < input.length; i++){
inputValues[i] = input[i];
}
if (verify(inputValues, proof) == 0) {
emit Verified("Transaction successfully verified.");
return true;
} else {
return false;
}
}
}
"#;
#[cfg(test)]
mod tests {
use super::*;
#[cfg(test)]
mod test_gm17 {
use super::*;
use field::FieldPrime;
// #[test]
// fn setup() {
// GM17::setup::<FieldPrime>(vec![], vec![], vec![], vec![], 1, "", "");
// }
// #[test]
// fn generate_proof() {
// GM17::generate_proof::<FieldPrime>("", "", vec![], vec![]);
// }
}
}

View file

@ -0,0 +1,5 @@
mod gm17;
mod pghr13;
pub use self::gm17::GM17;
pub use self::pghr13::PGHR13;

View file

@ -0,0 +1,296 @@
extern crate libc;
use self::libc::{c_char, c_int, uint8_t};
use flat_absy::flat_variable::FlatVariable;
use proof_system::utils::{prepare_generate_proof, prepare_setup, SOLIDITY_PAIRING_LIB};
use proof_system::ProofSystem;
use regex::Regex;
use std::fs::File;
use std::io::{BufRead, BufReader};
use field::FieldPrime;
pub struct PGHR13 {}
impl PGHR13 {
pub fn new() -> PGHR13 {
PGHR13 {}
}
}
extern "C" {
fn _pghr13_setup(
A: *const uint8_t,
B: *const uint8_t,
C: *const uint8_t,
A_len: c_int,
B_len: c_int,
C_len: c_int,
constraints: c_int,
variables: c_int,
inputs: c_int,
pk_path: *const c_char,
vk_path: *const c_char,
) -> bool;
fn _pghr13_generate_proof(
pk_path: *const c_char,
proof_path: *const c_char,
public_inputs: *const uint8_t,
public_inputs_length: c_int,
private_inputs: *const uint8_t,
private_inputs_length: c_int,
) -> bool;
}
impl ProofSystem for PGHR13 {
fn setup(
&self,
variables: Vec<FlatVariable>,
a: Vec<Vec<(usize, FieldPrime)>>,
b: Vec<Vec<(usize, FieldPrime)>>,
c: Vec<Vec<(usize, FieldPrime)>>,
num_inputs: usize,
pk_path: &str,
vk_path: &str,
) -> bool {
let (
a_arr,
b_arr,
c_arr,
a_vec,
b_vec,
c_vec,
num_constraints,
num_variables,
num_inputs,
pk_path_cstring,
vk_path_cstring,
) = prepare_setup(variables, a, b, c, num_inputs, pk_path, vk_path);
unsafe {
_pghr13_setup(
a_arr.as_ptr(),
b_arr.as_ptr(),
c_arr.as_ptr(),
a_vec.len() as i32,
b_vec.len() as i32,
c_vec.len() as i32,
num_constraints as i32,
num_variables as i32,
num_inputs as i32,
pk_path_cstring.as_ptr(),
vk_path_cstring.as_ptr(),
)
}
}
fn generate_proof(
&self,
pk_path: &str,
proof_path: &str,
public_inputs: Vec<FieldPrime>,
private_inputs: Vec<FieldPrime>,
) -> bool {
let (
pk_path_cstring,
proof_path_cstring,
public_inputs_arr,
public_inputs_length,
private_inputs_arr,
private_inputs_length,
) = prepare_generate_proof(pk_path, proof_path, public_inputs, private_inputs);
unsafe {
_pghr13_generate_proof(
pk_path_cstring.as_ptr(),
proof_path_cstring.as_ptr(),
public_inputs_arr[0].as_ptr(),
public_inputs_length as i32,
private_inputs_arr[0].as_ptr(),
private_inputs_length as i32,
)
}
}
fn export_solidity_verifier(&self, reader: BufReader<File>) -> String {
let mut lines = reader.lines();
let mut template_text = String::from(CONTRACT_TEMPLATE);
let ic_template = String::from("vk.IC[index] = Pairing.G1Point(points);"); //copy this for each entry
//replace things in template
let vk_regex = Regex::new(r#"(<%vk_[^i%]*%>)"#).unwrap();
let vk_ic_len_regex = Regex::new(r#"(<%vk_ic_length%>)"#).unwrap();
let vk_ic_index_regex = Regex::new(r#"index"#).unwrap();
let vk_ic_points_regex = Regex::new(r#"points"#).unwrap();
let vk_ic_repeat_regex = Regex::new(r#"(<%vk_ic_pts%>)"#).unwrap();
let vk_input_len_regex = Regex::new(r#"(<%vk_input_length%>)"#).unwrap();
for _ in 0..7 {
let current_line: String = lines
.next()
.expect("Unexpected end of file in verification key!")
.unwrap();
let current_line_split: Vec<&str> = current_line.split("=").collect();
assert_eq!(current_line_split.len(), 2);
template_text = vk_regex
.replace(template_text.as_str(), current_line_split[1].trim())
.into_owned();
}
let current_line: String = lines
.next()
.expect("Unexpected end of file in verification key!")
.unwrap();
let current_line_split: Vec<&str> = current_line.split("=").collect();
assert_eq!(current_line_split.len(), 2);
let ic_count: i32 = current_line_split[1].trim().parse().unwrap();
template_text = vk_ic_len_regex
.replace(template_text.as_str(), format!("{}", ic_count).as_str())
.into_owned();
template_text = vk_input_len_regex
.replace(template_text.as_str(), format!("{}", ic_count - 1).as_str())
.into_owned();
let mut ic_repeat_text = String::new();
for x in 0..ic_count {
let mut curr_template = ic_template.clone();
let current_line: String = lines
.next()
.expect("Unexpected end of file in verification key!")
.unwrap();
let current_line_split: Vec<&str> = current_line.split("=").collect();
assert_eq!(current_line_split.len(), 2);
curr_template = vk_ic_index_regex
.replace(curr_template.as_str(), format!("{}", x).as_str())
.into_owned();
curr_template = vk_ic_points_regex
.replace(curr_template.as_str(), current_line_split[1].trim())
.into_owned();
ic_repeat_text.push_str(curr_template.as_str());
if x < ic_count - 1 {
ic_repeat_text.push_str("\n ");
}
}
template_text = vk_ic_repeat_regex
.replace(template_text.as_str(), ic_repeat_text.as_str())
.into_owned();
format!("{}{}", SOLIDITY_PAIRING_LIB, template_text)
}
}
const CONTRACT_TEMPLATE: &str = r#"contract Verifier {
using Pairing for *;
struct VerifyingKey {
Pairing.G2Point A;
Pairing.G1Point B;
Pairing.G2Point C;
Pairing.G2Point gamma;
Pairing.G1Point gammaBeta1;
Pairing.G2Point gammaBeta2;
Pairing.G2Point Z;
Pairing.G1Point[] IC;
}
struct Proof {
Pairing.G1Point A;
Pairing.G1Point A_p;
Pairing.G2Point B;
Pairing.G1Point B_p;
Pairing.G1Point C;
Pairing.G1Point C_p;
Pairing.G1Point K;
Pairing.G1Point H;
}
function verifyingKey() pure internal returns (VerifyingKey vk) {
vk.A = Pairing.G2Point(<%vk_a%>);
vk.B = Pairing.G1Point(<%vk_b%>);
vk.C = Pairing.G2Point(<%vk_c%>);
vk.gamma = Pairing.G2Point(<%vk_g%>);
vk.gammaBeta1 = Pairing.G1Point(<%vk_gb1%>);
vk.gammaBeta2 = Pairing.G2Point(<%vk_gb2%>);
vk.Z = Pairing.G2Point(<%vk_z%>);
vk.IC = new Pairing.G1Point[](<%vk_ic_length%>);
<%vk_ic_pts%>
}
function verify(uint[] input, Proof proof) internal returns (uint) {
VerifyingKey memory vk = verifyingKey();
require(input.length + 1 == vk.IC.length);
// Compute the linear combination vk_x
Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0);
for (uint i = 0; i < input.length; i++)
vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i]));
vk_x = Pairing.addition(vk_x, vk.IC[0]);
if (!Pairing.pairingProd2(proof.A, vk.A, Pairing.negate(proof.A_p), Pairing.P2())) return 1;
if (!Pairing.pairingProd2(vk.B, proof.B, Pairing.negate(proof.B_p), Pairing.P2())) return 2;
if (!Pairing.pairingProd2(proof.C, vk.C, Pairing.negate(proof.C_p), Pairing.P2())) return 3;
if (!Pairing.pairingProd3(
proof.K, vk.gamma,
Pairing.negate(Pairing.addition(vk_x, Pairing.addition(proof.A, proof.C))), vk.gammaBeta2,
Pairing.negate(vk.gammaBeta1), proof.B
)) return 4;
if (!Pairing.pairingProd3(
Pairing.addition(vk_x, proof.A), proof.B,
Pairing.negate(proof.H), vk.Z,
Pairing.negate(proof.C), Pairing.P2()
)) return 5;
return 0;
}
event Verified(string s);
function verifyTx(
uint[2] a,
uint[2] a_p,
uint[2][2] b,
uint[2] b_p,
uint[2] c,
uint[2] c_p,
uint[2] h,
uint[2] k,
uint[<%vk_input_length%>] input
) public returns (bool r) {
Proof memory proof;
proof.A = Pairing.G1Point(a[0], a[1]);
proof.A_p = Pairing.G1Point(a_p[0], a_p[1]);
proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]);
proof.B_p = Pairing.G1Point(b_p[0], b_p[1]);
proof.C = Pairing.G1Point(c[0], c[1]);
proof.C_p = Pairing.G1Point(c_p[0], c_p[1]);
proof.H = Pairing.G1Point(h[0], h[1]);
proof.K = Pairing.G1Point(k[0], k[1]);
uint[] memory inputValues = new uint[](input.length);
for(uint i = 0; i < input.length; i++){
inputValues[i] = input[i];
}
if (verify(inputValues, proof) == 0) {
emit Verified("Transaction successfully verified.");
return true;
} else {
return false;
}
}
}
"#;
#[cfg(test)]
mod tests {
use super::*;
#[cfg(test)]
mod test_pghr13 {
use super::*;
use field::FieldPrime;
// #[test]
// fn setup() {
// PGHR13::setup::<FieldPrime>(vec![], vec![], vec![], vec![], 1, "", "");
// }
// #[test]
// fn generate_proof() {
// PGHR13::generate_proof::<FieldPrime>("", "", vec![], vec![]);
// }
}
}

View file

@ -1,28 +1,33 @@
mod pghr13;
mod bn128;
mod utils;
pub use self::pghr13::PGHR13;
use field::FieldPrime;
use std::fs::File;
use field::Field;
pub use self::bn128::GM17;
pub use self::bn128::PGHR13;
use flat_absy::flat_variable::FlatVariable;
use std::io::BufReader;
pub trait ProofSystem {
fn setup<T: Field>(
fn setup(
&self,
variables: Vec<FlatVariable>,
a: Vec<Vec<(usize, T)>>,
b: Vec<Vec<(usize, T)>>,
c: Vec<Vec<(usize, T)>>,
a: Vec<Vec<(usize, FieldPrime)>>,
b: Vec<Vec<(usize, FieldPrime)>>,
c: Vec<Vec<(usize, FieldPrime)>>,
num_inputs: usize,
pk_path: &str,
vk_path: &str,
) -> bool;
fn generate_proof<T: Field>(
fn generate_proof(
&self,
pk_path: &str,
proof_path: &str,
public_inputs: Vec<T>,
private_inputs: Vec<T>,
public_inputs: Vec<FieldPrime>,
private_inputs: Vec<FieldPrime>,
) -> bool;
fn export_solidity_verifier(&self, reader: BufReader<File>) -> String;
}

View file

@ -1,133 +0,0 @@
extern crate libc;
use self::libc::{c_char, c_int, uint8_t};
use flat_absy::flat_variable::FlatVariable;
use proof_system::utils::{prepare_generate_proof, prepare_setup};
use proof_system::ProofSystem;
use field::Field;
pub struct PGHR13 {}
impl PGHR13 {
pub fn new() -> Self {
PGHR13 {}
}
}
extern "C" {
fn _pghr13_setup(
A: *const uint8_t,
B: *const uint8_t,
C: *const uint8_t,
A_len: c_int,
B_len: c_int,
C_len: c_int,
constraints: c_int,
variables: c_int,
inputs: c_int,
pk_path: *const c_char,
vk_path: *const c_char,
) -> bool;
fn _pghr13_generate_proof(
pk_path: *const c_char,
proof_path: *const c_char,
public_inputs: *const uint8_t,
public_inputs_length: c_int,
private_inputs: *const uint8_t,
private_inputs_length: c_int,
) -> bool;
}
impl ProofSystem for PGHR13 {
fn setup<T: Field>(
&self,
variables: Vec<FlatVariable>,
a: Vec<Vec<(usize, T)>>,
b: Vec<Vec<(usize, T)>>,
c: Vec<Vec<(usize, T)>>,
num_inputs: usize,
pk_path: &str,
vk_path: &str,
) -> bool {
let (
a_arr,
b_arr,
c_arr,
a_vec,
b_vec,
c_vec,
num_constraints,
num_variables,
num_inputs,
pk_path_cstring,
vk_path_cstring,
) = prepare_setup(variables, a, b, c, num_inputs, pk_path, vk_path);
unsafe {
_pghr13_setup(
a_arr.as_ptr(),
b_arr.as_ptr(),
c_arr.as_ptr(),
a_vec.len() as i32,
b_vec.len() as i32,
c_vec.len() as i32,
num_constraints as i32,
num_variables as i32,
num_inputs as i32,
pk_path_cstring.as_ptr(),
vk_path_cstring.as_ptr(),
)
}
}
fn generate_proof<T: Field>(
&self,
pk_path: &str,
proof_path: &str,
public_inputs: Vec<T>,
private_inputs: Vec<T>,
) -> bool {
let (
pk_path_cstring,
proof_path_cstring,
public_inputs_arr,
public_inputs_length,
private_inputs_arr,
private_inputs_length,
) = prepare_generate_proof(pk_path, proof_path, public_inputs, private_inputs);
unsafe {
_pghr13_generate_proof(
pk_path_cstring.as_ptr(),
proof_path_cstring.as_ptr(),
public_inputs_arr[0].as_ptr(),
public_inputs_length as i32,
private_inputs_arr[0].as_ptr(),
private_inputs_length as i32,
)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(test)]
mod test_pghr13 {
use super::*;
use field::FieldPrime;
// #[test]
// fn setup() {
// PGHR13::setup::<FieldPrime>(vec![], vec![], vec![], vec![], 1, "", "");
// }
// #[test]
// fn generate_proof() {
// PGHR13::generate_proof::<FieldPrime>("", "", vec![], vec![]);
// }
}
}

View file

@ -179,3 +179,183 @@ pub fn prepare_generate_proof<T: Field>(
private_inputs_length,
)
}
pub const SOLIDITY_PAIRING_LIB : &str = r#"// This file is MIT Licensed.
//
// Copyright 2017 Christian Reitwiessner
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.4.14;
library Pairing {
struct G1Point {
uint X;
uint Y;
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
/// @return the generator of G1
function P1() pure internal returns (G1Point) {
return G1Point(1, 2);
}
/// @return the generator of G2
function P2() pure internal returns (G2Point) {
return G2Point(
[11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781],
[4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930]
);
}
/// @return the negation of p, i.e. p.addition(p.negate()) should be zero.
function negate(G1Point p) pure internal returns (G1Point) {
// The prime q in the base field F_q for G1
uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
if (p.X == 0 && p.Y == 0)
return G1Point(0, 0);
return G1Point(p.X, q - (p.Y % q));
}
/// @return the sum of two points of G1
function addition(G1Point p1, G1Point p2) internal returns (G1Point r) {
uint[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success;
assembly {
success := call(sub(gas, 2000), 6, 0, input, 0xc0, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success);
}
/// @return the sum of two points of G2
function addition(G2Point p1, G2Point p2) internal returns (G2Point r) {
uint[4] memory inputX;
inputX[0] = p1.X[0];
inputX[1] = p1.X[1];
inputX[2] = p2.X[0];
inputX[3] = p2.X[1];
uint[4] memory inputY;
inputX[0] = p1.Y[0];
inputX[1] = p1.Y[1];
inputX[2] = p2.Y[0];
inputX[3] = p2.Y[1];
G1Point memory resX;
G1Point memory resY;
bool success;
assembly {
success := call(sub(gas, 2000), 6, 0, inputX, 0xc0, resX, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success);
assembly {
success := call(sub(gas, 2000), 6, 0, inputY, 0xc0, resY, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success);
r.X[0] = resX.X;
r.X[1] = resX.Y;
r.Y[0] = resY.X;
r.Y[1] = resY.Y;
}
/// @return the product of a point on G1 and a scalar, i.e.
/// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p.
function scalar_mul(G1Point p, uint s) internal returns (G1Point r) {
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
assembly {
success := call(sub(gas, 2000), 7, 0, input, 0x80, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require (success);
}
/// @return the result of computing the pairing check
/// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1
/// For example pairing([P1(), P1().negate()], [P2(), P2()]) should
/// return true.
function pairing(G1Point[] p1, G2Point[] p2) internal returns (bool) {
require(p1.length == p2.length);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)
{
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
assembly {
success := call(sub(gas, 2000), 8, 0, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(G1Point a1, G2Point a2, G1Point b1, G2Point b2) internal returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for three pairs.
function pairingProd3(
G1Point a1, G2Point a2,
G1Point b1, G2Point b2,
G1Point c1, G2Point c2
) internal returns (bool) {
G1Point[] memory p1 = new G1Point[](3);
G2Point[] memory p2 = new G2Point[](3);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for four pairs.
function pairingProd4(
G1Point a1, G2Point a2,
G1Point b1, G2Point b2,
G1Point c1, G2Point c2,
G1Point d1, G2Point d2
) internal returns (bool) {
G1Point[] memory p1 = new G1Point[](4);
G2Point[] memory p2 = new G2Point[](4);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p1[3] = d1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
p2[3] = d2;
return pairing(p1, p2);
}
}
"#;

View file

@ -1,233 +0,0 @@
pub const CONTRACT_TEMPLATE: &str = r#"// This file is MIT Licensed.
//
// Copyright 2017 Christian Reitwiessner
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.4.14;
library Pairing {
struct G1Point {
uint X;
uint Y;
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
/// @return the generator of G1
function P1() pure internal returns (G1Point) {
return G1Point(1, 2);
}
/// @return the generator of G2
function P2() pure internal returns (G2Point) {
return G2Point(
[11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781],
[4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930]
);
}
/// @return the negation of p, i.e. p.addition(p.negate()) should be zero.
function negate(G1Point p) pure internal returns (G1Point) {
// The prime q in the base field F_q for G1
uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
if (p.X == 0 && p.Y == 0)
return G1Point(0, 0);
return G1Point(p.X, q - (p.Y % q));
}
/// @return the sum of two points of G1
function addition(G1Point p1, G1Point p2) internal returns (G1Point r) {
uint[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success;
assembly {
success := call(sub(gas, 2000), 6, 0, input, 0xc0, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success);
}
/// @return the product of a point on G1 and a scalar, i.e.
/// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p.
function scalar_mul(G1Point p, uint s) internal returns (G1Point r) {
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
assembly {
success := call(sub(gas, 2000), 7, 0, input, 0x80, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require (success);
}
/// @return the result of computing the pairing check
/// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1
/// For example pairing([P1(), P1().negate()], [P2(), P2()]) should
/// return true.
function pairing(G1Point[] p1, G2Point[] p2) internal returns (bool) {
require(p1.length == p2.length);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)
{
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
assembly {
success := call(sub(gas, 2000), 8, 0, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(G1Point a1, G2Point a2, G1Point b1, G2Point b2) internal returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for three pairs.
function pairingProd3(
G1Point a1, G2Point a2,
G1Point b1, G2Point b2,
G1Point c1, G2Point c2
) internal returns (bool) {
G1Point[] memory p1 = new G1Point[](3);
G2Point[] memory p2 = new G2Point[](3);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
return pairing(p1, p2);
}
/// Convenience method for a pairing check for four pairs.
function pairingProd4(
G1Point a1, G2Point a2,
G1Point b1, G2Point b2,
G1Point c1, G2Point c2,
G1Point d1, G2Point d2
) internal returns (bool) {
G1Point[] memory p1 = new G1Point[](4);
G2Point[] memory p2 = new G2Point[](4);
p1[0] = a1;
p1[1] = b1;
p1[2] = c1;
p1[3] = d1;
p2[0] = a2;
p2[1] = b2;
p2[2] = c2;
p2[3] = d2;
return pairing(p1, p2);
}
}
contract Verifier {
using Pairing for *;
struct VerifyingKey {
Pairing.G2Point A;
Pairing.G1Point B;
Pairing.G2Point C;
Pairing.G2Point gamma;
Pairing.G1Point gammaBeta1;
Pairing.G2Point gammaBeta2;
Pairing.G2Point Z;
Pairing.G1Point[] IC;
}
struct Proof {
Pairing.G1Point A;
Pairing.G1Point A_p;
Pairing.G2Point B;
Pairing.G1Point B_p;
Pairing.G1Point C;
Pairing.G1Point C_p;
Pairing.G1Point K;
Pairing.G1Point H;
}
function verifyingKey() pure internal returns (VerifyingKey vk) {
vk.A = Pairing.G2Point(<%vk_a%>);
vk.B = Pairing.G1Point(<%vk_b%>);
vk.C = Pairing.G2Point(<%vk_c%>);
vk.gamma = Pairing.G2Point(<%vk_g%>);
vk.gammaBeta1 = Pairing.G1Point(<%vk_gb1%>);
vk.gammaBeta2 = Pairing.G2Point(<%vk_gb2%>);
vk.Z = Pairing.G2Point(<%vk_z%>);
vk.IC = new Pairing.G1Point[](<%vk_ic_length%>);
<%vk_ic_pts%>
}
function verify(uint[] input, Proof proof) internal returns (uint) {
VerifyingKey memory vk = verifyingKey();
require(input.length + 1 == vk.IC.length);
// Compute the linear combination vk_x
Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0);
for (uint i = 0; i < input.length; i++)
vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(vk.IC[i + 1], input[i]));
vk_x = Pairing.addition(vk_x, vk.IC[0]);
if (!Pairing.pairingProd2(proof.A, vk.A, Pairing.negate(proof.A_p), Pairing.P2())) return 1;
if (!Pairing.pairingProd2(vk.B, proof.B, Pairing.negate(proof.B_p), Pairing.P2())) return 2;
if (!Pairing.pairingProd2(proof.C, vk.C, Pairing.negate(proof.C_p), Pairing.P2())) return 3;
if (!Pairing.pairingProd3(
proof.K, vk.gamma,
Pairing.negate(Pairing.addition(vk_x, Pairing.addition(proof.A, proof.C))), vk.gammaBeta2,
Pairing.negate(vk.gammaBeta1), proof.B
)) return 4;
if (!Pairing.pairingProd3(
Pairing.addition(vk_x, proof.A), proof.B,
Pairing.negate(proof.H), vk.Z,
Pairing.negate(proof.C), Pairing.P2()
)) return 5;
return 0;
}
event Verified(string s);
function verifyTx(
uint[2] a,
uint[2] a_p,
uint[2][2] b,
uint[2] b_p,
uint[2] c,
uint[2] c_p,
uint[2] h,
uint[2] k,
uint[<%vk_input_length%>] input
) public returns (bool r) {
Proof memory proof;
proof.A = Pairing.G1Point(a[0], a[1]);
proof.A_p = Pairing.G1Point(a_p[0], a_p[1]);
proof.B = Pairing.G2Point([b[0][0], b[0][1]], [b[1][0], b[1][1]]);
proof.B_p = Pairing.G1Point(b_p[0], b_p[1]);
proof.C = Pairing.G1Point(c[0], c[1]);
proof.C_p = Pairing.G1Point(c_p[0], c_p[1]);
proof.H = Pairing.G1Point(h[0], h[1]);
proof.K = Pairing.G1Point(k[0], k[1]);
uint[] memory inputValues = new uint[](input.length);
for(uint i = 0; i < input.length; i++){
inputValues[i] = input[i];
}
if (verify(inputValues, proof) == 0) {
emit Verified("Transaction successfully verified.");
return true;
} else {
return false;
}
}
}
"#;