Merge branch 'develop' of github.com:JacobEberhardt/ZoKrates into optimize-subtraction
This commit is contained in:
commit
bb10c1f3fa
21 changed files with 1902 additions and 702 deletions
1
.codecov.yml
Normal file
1
.codecov.yml
Normal file
|
@ -0,0 +1 @@
|
|||
comment: off
|
|
@ -14,6 +14,7 @@
|
|||
|
||||
- [Reference](reference/index.md)
|
||||
- [CLI](reference/cli.md)
|
||||
- [Backends](reference/backends.md)
|
||||
- [Verification](reference/verification.md)
|
||||
|
||||
- [Tutorial: Proof of preimage](./sha256example.md)
|
17
zokrates_book/src/reference/backends.md
Normal file
17
zokrates_book/src/reference/backends.md
Normal file
|
@ -0,0 +1,17 @@
|
|||
# Backends
|
||||
|
||||
ZoKrates supports different proof systems to be used as backends. All of the available backends rely on the ALT_BN128 curve, which means that they're all compatible with Ethereum.
|
||||
|
||||
We identify the backends by the reference to the paper that introduced them. Currently the options available are:
|
||||
|
||||
| Name | Paper | CLI flag |
|
||||
| ---- | ----- | -------- |
|
||||
| PGHR13 | [Here](https://eprint.iacr.org/2013/279) | `--backend pghr13` |
|
||||
| GM17 | [Here](https://eprint.iacr.org/2017/540) | `--backend gm17` |
|
||||
|
||||
The default backend is PGHR13.
|
||||
|
||||
When not using the default, the CLI flag has to be provided for the following commands:
|
||||
- `setup`
|
||||
- `export-verifier`
|
||||
- `generate-proof`
|
|
@ -4,4 +4,5 @@ The reference covers the details of various areas of ZoKrates.
|
|||
|
||||
- [ZoKrates Reference](index.md)
|
||||
- [CLI](cli.md)
|
||||
- [Backends](backends.md)
|
||||
- [Verification](verification.md)
|
||||
|
|
|
@ -12,20 +12,31 @@ 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};
|
||||
use std::string::String;
|
||||
use zokrates_core::compile::compile;
|
||||
use zokrates_core::field::{Field, FieldPrime};
|
||||
use zokrates_core::ir::{self, r1cs_program};
|
||||
use zokrates_core::ir;
|
||||
#[cfg(feature = "libsnark")]
|
||||
use zokrates_core::libsnark::{generate_proof, setup};
|
||||
use zokrates_core::verification::CONTRACT_TEMPLATE;
|
||||
use zokrates_core::ir::r1cs_program;
|
||||
#[cfg(feature = "libsnark")]
|
||||
use zokrates_core::proof_system::{ProofSystem, GM17, PGHR13};
|
||||
use zokrates_fs_resolver::resolve as fs_resolve;
|
||||
|
||||
#[cfg(feature = "libsnark")]
|
||||
fn get_backend(backend_str: &str) -> &'static ProofSystem {
|
||||
match backend_str.to_lowercase().as_ref() {
|
||||
"pghr13" => &PGHR13 {},
|
||||
"gm17" => &GM17 {},
|
||||
s => panic!("Backend \"{}\" not supported", s),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
const FLATTENED_CODE_DEFAULT_PATH: &str = "out";
|
||||
const VERIFICATION_KEY_DEFAULT_PATH: &str = "verification.key";
|
||||
|
@ -34,6 +45,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";
|
||||
let default_backend = env::var("ZOKRATES_BACKEND").unwrap_or(String::from("pghr13"));
|
||||
|
||||
// cli specification using clap library
|
||||
let matches = App::new("ZoKrates")
|
||||
|
@ -102,6 +114,15 @@ fn main() {
|
|||
.required(false)
|
||||
.default_value(VARIABLES_INFORMATION_KEY_DEFAULT_PATH)
|
||||
)
|
||||
.arg(Arg::with_name("backend")
|
||||
.short("b")
|
||||
.long("backend")
|
||||
.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)
|
||||
)
|
||||
)
|
||||
.subcommand(SubCommand::with_name("export-verifier")
|
||||
.about("Exports a verifier as Solidity smart contract.")
|
||||
|
@ -122,6 +143,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")
|
||||
|
@ -189,6 +218,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();
|
||||
|
@ -371,9 +408,12 @@ fn main() {
|
|||
}
|
||||
bw.flush().expect("Unable to flush buffer.");
|
||||
}
|
||||
#[cfg(feature = "libsnark")]
|
||||
("setup", Some(sub_matches)) => {
|
||||
println!("Performing setup...");
|
||||
|
||||
let backend = get_backend(sub_matches.value_of("backend").unwrap());
|
||||
|
||||
let path = Path::new(sub_matches.value_of("input").unwrap());
|
||||
let mut file = match File::open(&path) {
|
||||
Ok(file) => file,
|
||||
|
@ -421,110 +461,56 @@ fn main() {
|
|||
let vk_path = sub_matches.value_of("verification-key-path").unwrap();
|
||||
|
||||
// run setup phase
|
||||
#[cfg(feature = "libsnark")]
|
||||
{
|
||||
// number of inputs in the zkSNARK sense, i.e., input variables + output variables
|
||||
println!(
|
||||
"setup successful: {:?}",
|
||||
setup(
|
||||
variables,
|
||||
a,
|
||||
b,
|
||||
c,
|
||||
public_variables_count - 1,
|
||||
pk_path,
|
||||
vk_path
|
||||
)
|
||||
);
|
||||
}
|
||||
// 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...");
|
||||
// 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();
|
||||
{
|
||||
println!("Exporting verifier...");
|
||||
|
||||
let mut template_text = String::from(CONTRACT_TEMPLATE);
|
||||
let ic_template = String::from("vk.IC[index] = Pairing.G1Point(points);"); //copy this for each entry
|
||||
let backend = get_backend(sub_matches.value_of("backend").unwrap());
|
||||
|
||||
//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();
|
||||
// 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);
|
||||
|
||||
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 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 create {}: {}", output_path.display(), why),
|
||||
};
|
||||
|
||||
output_file
|
||||
.write_all(&verifier.as_bytes())
|
||||
.expect("Failed writing output to file.");
|
||||
println!("Finished exporting verifier.");
|
||||
}
|
||||
|
||||
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)) => {
|
||||
println!("Generating proof...");
|
||||
|
||||
let backend = get_backend(sub_matches.value_of("backend").unwrap());
|
||||
|
||||
// deserialize witness
|
||||
let witness_path = Path::new(sub_matches.value_of("witness").unwrap());
|
||||
let witness_file = match File::open(&witness_path) {
|
||||
|
@ -594,13 +580,10 @@ fn main() {
|
|||
let proof_path = sub_matches.value_of("proofpath").unwrap();
|
||||
|
||||
// run libsnark
|
||||
#[cfg(feature = "libsnark")]
|
||||
{
|
||||
println!(
|
||||
"generate-proof successful: {:?}",
|
||||
generate_proof(pk_path, proof_path, public_inputs, private_inputs)
|
||||
);
|
||||
}
|
||||
println!(
|
||||
"generate-proof successful: {:?}",
|
||||
backend.generate_proof(pk_path, proof_path, public_inputs, private_inputs)
|
||||
);
|
||||
}
|
||||
_ => unimplemented!(), // Either no subcommand or one not tested for...
|
||||
}
|
||||
|
@ -611,6 +594,7 @@ mod tests {
|
|||
extern crate glob;
|
||||
use self::glob::glob;
|
||||
use super::*;
|
||||
use zokrates_core::ir::r1cs_program;
|
||||
|
||||
#[test]
|
||||
fn examples() {
|
||||
|
|
|
@ -162,47 +162,55 @@ mod integration {
|
|||
|
||||
#[cfg(feature = "libsnark")]
|
||||
{
|
||||
// SETUP
|
||||
assert_cli::Assert::command(&[
|
||||
"../target/release/zokrates",
|
||||
"setup",
|
||||
"-i",
|
||||
flattened_path.to_str().unwrap(),
|
||||
"-p",
|
||||
proving_key_path.to_str().unwrap(),
|
||||
"-v",
|
||||
verification_key_path.to_str().unwrap(),
|
||||
"-m",
|
||||
variable_information_path.to_str().unwrap(),
|
||||
])
|
||||
.succeeds()
|
||||
.unwrap();
|
||||
for backend in &["pghr13", "gm17"] {
|
||||
// SETUP
|
||||
assert_cli::Assert::command(&[
|
||||
"../target/release/zokrates",
|
||||
"setup",
|
||||
"-i",
|
||||
flattened_path.to_str().unwrap(),
|
||||
"-p",
|
||||
proving_key_path.to_str().unwrap(),
|
||||
"-v",
|
||||
verification_key_path.to_str().unwrap(),
|
||||
"-m",
|
||||
variable_information_path.to_str().unwrap(),
|
||||
"--backend",
|
||||
backend,
|
||||
])
|
||||
.succeeds()
|
||||
.unwrap();
|
||||
|
||||
// EXPORT-VERIFIER
|
||||
assert_cli::Assert::command(&[
|
||||
"../target/release/zokrates",
|
||||
"export-verifier",
|
||||
"-i",
|
||||
verification_key_path.to_str().unwrap(),
|
||||
"-o",
|
||||
verification_contract_path.to_str().unwrap(),
|
||||
])
|
||||
.succeeds()
|
||||
.unwrap();
|
||||
// EXPORT-VERIFIER
|
||||
assert_cli::Assert::command(&[
|
||||
"../target/release/zokrates",
|
||||
"export-verifier",
|
||||
"-i",
|
||||
verification_key_path.to_str().unwrap(),
|
||||
"-o",
|
||||
verification_contract_path.to_str().unwrap(),
|
||||
"--backend",
|
||||
backend,
|
||||
])
|
||||
.succeeds()
|
||||
.unwrap();
|
||||
|
||||
// GENERATE-PROOF
|
||||
assert_cli::Assert::command(&[
|
||||
"../target/release/zokrates",
|
||||
"generate-proof",
|
||||
"-w",
|
||||
witness_path.to_str().unwrap(),
|
||||
"-p",
|
||||
proving_key_path.to_str().unwrap(),
|
||||
"-i",
|
||||
variable_information_path.to_str().unwrap(),
|
||||
])
|
||||
.succeeds()
|
||||
.unwrap();
|
||||
// GENERATE-PROOF
|
||||
assert_cli::Assert::command(&[
|
||||
"../target/release/zokrates",
|
||||
"generate-proof",
|
||||
"-w",
|
||||
witness_path.to_str().unwrap(),
|
||||
"-p",
|
||||
proving_key_path.to_str().unwrap(),
|
||||
"-i",
|
||||
variable_information_path.to_str().unwrap(),
|
||||
"--backend",
|
||||
backend,
|
||||
])
|
||||
.succeeds()
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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
249
zokrates_core/lib/gm17.cpp
Normal 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.query[" << 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 << "]" << "\n";
|
||||
ss << "}" << "\n";
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
@ -1,10 +1,12 @@
|
|||
/**
|
||||
* @file wraplibsnark.hpp
|
||||
* @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
|
||||
|
@ -12,7 +14,7 @@ extern "C" {
|
|||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
bool _setup(const uint8_t* A,
|
||||
bool _gm17_setup(const uint8_t* A,
|
||||
const uint8_t* B,
|
||||
const uint8_t* C,
|
||||
int A_len,
|
||||
|
@ -25,7 +27,7 @@ bool _setup(const uint8_t* A,
|
|||
const char* vk_path
|
||||
);
|
||||
|
||||
bool _generate_proof(const char* pk_path,
|
||||
bool _gm17_generate_proof(const char* pk_path,
|
||||
const char* proof_path,
|
||||
const uint8_t* public_inputs,
|
||||
int public_inputs_length,
|
||||
|
@ -35,4 +37,4 @@ bool _generate_proof(const char* pk_path,
|
|||
|
||||
#ifdef __cplusplus
|
||||
} // extern "C"
|
||||
#endif
|
||||
#endif
|
|
@ -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;
|
||||
|
@ -292,15 +180,27 @@ void printProof(r1cs_ppzksnark_proof<libff::alt_bn128_pp> proof, const char* pro
|
|||
}
|
||||
ss << libsnarkBigintFromBytes(public_inputs + i*32);
|
||||
}
|
||||
ss << "]";
|
||||
ss << "}";
|
||||
ss << "]" << "\n";
|
||||
ss << "}" << "\n";
|
||||
|
||||
std::string s = ss.str();
|
||||
//write json string to proof_path
|
||||
writeToFile(proof_path, s);
|
||||
}
|
||||
|
||||
bool _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)
|
||||
}
|
||||
|
||||
// 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;
|
||||
libff::inhibit_profiling_counters = true;
|
||||
|
@ -308,7 +208,7 @@ bool _setup(const uint8_t* A, const uint8_t* B, const uint8_t* C, int A_len, int
|
|||
//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,23 +218,23 @@ bool _setup(const uint8_t* A, const uint8_t* B, const uint8_t* C, int A_len, int
|
|||
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;
|
||||
}
|
||||
|
||||
bool _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)
|
||||
bool _pghr13_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 = 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 _generate_proof(const char* pk_path, const char* proof_path, const uint8_t*
|
|||
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;
|
42
zokrates_core/lib/pghr13.hpp
Normal file
42
zokrates_core/lib/pghr13.hpp
Normal file
|
@ -0,0 +1,42 @@
|
|||
/**
|
||||
* @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
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
|
||||
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
|
||||
);
|
||||
|
||||
bool _pghr13_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
|
85
zokrates_core/lib/util.cpp
Normal file
85
zokrates_core/lib/util.cpp
Normal 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()) + "\"]]";
|
||||
}
|
50
zokrates_core/lib/util.hpp
Normal file
50
zokrates_core/lib/util.hpp
Normal 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;
|
||||
}
|
|
@ -32,4 +32,5 @@ pub mod flat_absy;
|
|||
pub mod ir;
|
||||
#[cfg(feature = "libsnark")]
|
||||
pub mod libsnark;
|
||||
pub mod verification;
|
||||
#[cfg(feature = "libsnark")]
|
||||
pub mod proof_system;
|
||||
|
|
|
@ -7,38 +7,12 @@
|
|||
extern crate libc;
|
||||
|
||||
use self::libc::{c_char, c_int, uint8_t};
|
||||
use flat_absy::flat_variable::FlatVariable;
|
||||
use std::cmp::max;
|
||||
use std::ffi::CString;
|
||||
use std::string::String;
|
||||
|
||||
use field::Field;
|
||||
|
||||
extern "C" {
|
||||
|
||||
fn _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 _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;
|
||||
|
||||
fn _sha256Constraints() -> *mut c_char;
|
||||
fn _sha256Witness(inputs: *const uint8_t, inputs_length: c_int) -> *mut c_char;
|
||||
|
||||
|
@ -46,163 +20,6 @@ extern "C" {
|
|||
fn _shaEth256Witness(inputs: *const uint8_t, inputs_length: c_int) -> *mut c_char;
|
||||
}
|
||||
|
||||
pub fn setup<T: Field>(
|
||||
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 num_constraints = a.len();
|
||||
let num_variables = variables.len();
|
||||
|
||||
// Create single A,B,C vectors of tuples (constraint_number, variable_id, variable_value)
|
||||
let mut a_vec = vec![];
|
||||
let mut b_vec = vec![];
|
||||
let mut c_vec = vec![];
|
||||
for row in 0..num_constraints {
|
||||
for &(idx, ref val) in &a[row] {
|
||||
a_vec.push((
|
||||
row as i32,
|
||||
idx as i32,
|
||||
vec_as_u8_32_array(&val.into_byte_vector()),
|
||||
));
|
||||
}
|
||||
for &(idx, ref val) in &b[row] {
|
||||
b_vec.push((
|
||||
row as i32,
|
||||
idx as i32,
|
||||
vec_as_u8_32_array(&val.into_byte_vector()),
|
||||
));
|
||||
}
|
||||
for &(idx, ref val) in &c[row] {
|
||||
c_vec.push((
|
||||
row as i32,
|
||||
idx as i32,
|
||||
vec_as_u8_32_array(&val.into_byte_vector()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Sizes and offsets in bytes for our struct {row, id, value}
|
||||
// We're building { i32, i32, i8[32] }
|
||||
const STRUCT_SIZE: usize = 40;
|
||||
|
||||
const ROW_SIZE: usize = 4;
|
||||
|
||||
const IDX_SIZE: usize = 4;
|
||||
const IDX_OFFSET: usize = 4;
|
||||
|
||||
const VALUE_SIZE: usize = 32;
|
||||
const VALUE_OFFSET: usize = 8;
|
||||
|
||||
// Convert above A,B,C vectors to byte arrays for cpp
|
||||
let mut a_arr: Vec<u8> = vec![0u8; STRUCT_SIZE * a_vec.len()];
|
||||
let mut b_arr: Vec<u8> = vec![0u8; STRUCT_SIZE * b_vec.len()];
|
||||
let mut c_arr: Vec<u8> = vec![0u8; STRUCT_SIZE * c_vec.len()];
|
||||
use std::mem::transmute;
|
||||
for (id, (row, idx, val)) in a_vec.iter().enumerate() {
|
||||
let row_bytes: [u8; ROW_SIZE] = unsafe { transmute(row.to_le()) };
|
||||
let idx_bytes: [u8; IDX_SIZE] = unsafe { transmute(idx.to_le()) };
|
||||
|
||||
for x in 0..ROW_SIZE {
|
||||
a_arr[id * STRUCT_SIZE + x] = row_bytes[x];
|
||||
}
|
||||
for x in 0..IDX_SIZE {
|
||||
a_arr[id * STRUCT_SIZE + x + IDX_OFFSET] = idx_bytes[x];
|
||||
}
|
||||
for x in 0..VALUE_SIZE {
|
||||
a_arr[id * STRUCT_SIZE + x + VALUE_OFFSET] = val[x];
|
||||
}
|
||||
}
|
||||
for (id, (row, idx, val)) in b_vec.iter().enumerate() {
|
||||
let row_bytes: [u8; ROW_SIZE] = unsafe { transmute(row.to_le()) };
|
||||
let idx_bytes: [u8; IDX_SIZE] = unsafe { transmute(idx.to_le()) };
|
||||
|
||||
for x in 0..ROW_SIZE {
|
||||
b_arr[id * STRUCT_SIZE + x] = row_bytes[x];
|
||||
}
|
||||
for x in 0..IDX_SIZE {
|
||||
b_arr[id * STRUCT_SIZE + x + IDX_OFFSET] = idx_bytes[x];
|
||||
}
|
||||
for x in 0..VALUE_SIZE {
|
||||
b_arr[id * STRUCT_SIZE + x + VALUE_OFFSET] = val[x];
|
||||
}
|
||||
}
|
||||
for (id, (row, idx, val)) in c_vec.iter().enumerate() {
|
||||
let row_bytes: [u8; ROW_SIZE] = unsafe { transmute(row.to_le()) };
|
||||
let idx_bytes: [u8; IDX_SIZE] = unsafe { transmute(idx.to_le()) };
|
||||
|
||||
for x in 0..ROW_SIZE {
|
||||
c_arr[id * STRUCT_SIZE + x] = row_bytes[x];
|
||||
}
|
||||
for x in 0..IDX_SIZE {
|
||||
c_arr[id * STRUCT_SIZE + x + IDX_OFFSET] = idx_bytes[x];
|
||||
}
|
||||
for x in 0..VALUE_SIZE {
|
||||
c_arr[id * STRUCT_SIZE + x + VALUE_OFFSET] = val[x];
|
||||
}
|
||||
}
|
||||
|
||||
// convert String slices to 'CString's
|
||||
let pk_path_cstring = CString::new(pk_path).unwrap();
|
||||
let vk_path_cstring = CString::new(vk_path).unwrap();
|
||||
|
||||
unsafe {
|
||||
_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(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_proof<T: Field>(
|
||||
pk_path: &str,
|
||||
proof_path: &str,
|
||||
public_inputs: Vec<T>,
|
||||
private_inputs: Vec<T>,
|
||||
) -> bool {
|
||||
let pk_path_cstring = CString::new(pk_path).unwrap();
|
||||
let proof_path_cstring = CString::new(proof_path).unwrap();
|
||||
|
||||
let public_inputs_length = public_inputs.len();
|
||||
let private_inputs_length = private_inputs.len();
|
||||
|
||||
let mut public_inputs_arr: Vec<[u8; 32]> = vec![[0u8; 32]; public_inputs_length];
|
||||
// length must not be zero here, so we apply the max function
|
||||
let mut private_inputs_arr: Vec<[u8; 32]> = vec![[0u8; 32]; max(private_inputs_length, 1)];
|
||||
|
||||
//convert inputs
|
||||
for (index, value) in public_inputs.into_iter().enumerate() {
|
||||
public_inputs_arr[index] = vec_as_u8_32_array(&value.into_byte_vector());
|
||||
}
|
||||
for (index, value) in private_inputs.into_iter().enumerate() {
|
||||
private_inputs_arr[index] = vec_as_u8_32_array(&value.into_byte_vector());
|
||||
}
|
||||
|
||||
unsafe {
|
||||
_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,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_sha256_constraints() -> String {
|
||||
let a = unsafe { CString::from_raw(_sha256Constraints()) };
|
||||
a.into_string().unwrap()
|
||||
|
|
261
zokrates_core/src/proof_system/bn128/gm17.rs
Normal file
261
zokrates_core/src/proof_system/bn128/gm17.rs
Normal file
|
@ -0,0 +1,261 @@
|
|||
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_G2_ADDITION_LIB, 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_G2_ADDITION_LIB, 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
"#;
|
5
zokrates_core/src/proof_system/bn128/mod.rs
Normal file
5
zokrates_core/src/proof_system/bn128/mod.rs
Normal file
|
@ -0,0 +1,5 @@
|
|||
mod gm17;
|
||||
mod pghr13;
|
||||
|
||||
pub use self::gm17::GM17;
|
||||
pub use self::pghr13::PGHR13;
|
280
zokrates_core/src/proof_system/bn128/pghr13.rs
Normal file
280
zokrates_core/src/proof_system/bn128/pghr13.rs
Normal file
|
@ -0,0 +1,280 @@
|
|||
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_G2_ADDITION_LIB, 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_G2_ADDITION_LIB, 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
"#;
|
33
zokrates_core/src/proof_system/mod.rs
Normal file
33
zokrates_core/src/proof_system/mod.rs
Normal file
|
@ -0,0 +1,33 @@
|
|||
mod bn128;
|
||||
mod utils;
|
||||
|
||||
use field::FieldPrime;
|
||||
use std::fs::File;
|
||||
|
||||
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(
|
||||
&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;
|
||||
|
||||
fn generate_proof(
|
||||
&self,
|
||||
pk_path: &str,
|
||||
proof_path: &str,
|
||||
public_inputs: Vec<FieldPrime>,
|
||||
private_inputs: Vec<FieldPrime>,
|
||||
) -> bool;
|
||||
|
||||
fn export_solidity_verifier(&self, reader: BufReader<File>) -> String;
|
||||
}
|
694
zokrates_core/src/proof_system/utils.rs
Normal file
694
zokrates_core/src/proof_system/utils.rs
Normal file
|
@ -0,0 +1,694 @@
|
|||
use field::Field;
|
||||
use flat_absy::flat_variable::FlatVariable;
|
||||
use std::cmp::max;
|
||||
use std::ffi::CString;
|
||||
|
||||
// utility function. Converts a Fields vector-based byte representation to fixed size array.
|
||||
fn vec_as_u8_32_array(vec: &Vec<u8>) -> [u8; 32] {
|
||||
assert!(vec.len() <= 32);
|
||||
let mut array = [0u8; 32];
|
||||
for (index, byte) in vec.iter().enumerate() {
|
||||
array[31 - index] = *byte;
|
||||
}
|
||||
array
|
||||
}
|
||||
|
||||
// proof-system-independent preparation for the setup phase
|
||||
pub fn prepare_setup<T: Field>(
|
||||
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,
|
||||
) -> (
|
||||
Vec<u8>,
|
||||
Vec<u8>,
|
||||
Vec<u8>,
|
||||
Vec<(i32, i32, [u8; 32])>,
|
||||
Vec<(i32, i32, [u8; 32])>,
|
||||
Vec<(i32, i32, [u8; 32])>,
|
||||
usize,
|
||||
usize,
|
||||
usize,
|
||||
CString,
|
||||
CString,
|
||||
) {
|
||||
let num_constraints = a.len();
|
||||
let num_variables = variables.len();
|
||||
|
||||
// Create single A,B,C vectors of tuples (constraint_number, variable_id, variable_value)
|
||||
let mut a_vec = vec![];
|
||||
let mut b_vec = vec![];
|
||||
let mut c_vec = vec![];
|
||||
for row in 0..num_constraints {
|
||||
for &(idx, ref val) in &a[row] {
|
||||
a_vec.push((
|
||||
row as i32,
|
||||
idx as i32,
|
||||
vec_as_u8_32_array(&val.into_byte_vector()),
|
||||
));
|
||||
}
|
||||
for &(idx, ref val) in &b[row] {
|
||||
b_vec.push((
|
||||
row as i32,
|
||||
idx as i32,
|
||||
vec_as_u8_32_array(&val.into_byte_vector()),
|
||||
));
|
||||
}
|
||||
for &(idx, ref val) in &c[row] {
|
||||
c_vec.push((
|
||||
row as i32,
|
||||
idx as i32,
|
||||
vec_as_u8_32_array(&val.into_byte_vector()),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Sizes and offsets in bytes for our struct {row, id, value}
|
||||
// We're building { i32, i32, i8[32] }
|
||||
const STRUCT_SIZE: usize = 40;
|
||||
|
||||
const ROW_SIZE: usize = 4;
|
||||
|
||||
const IDX_SIZE: usize = 4;
|
||||
const IDX_OFFSET: usize = 4;
|
||||
|
||||
const VALUE_SIZE: usize = 32;
|
||||
const VALUE_OFFSET: usize = 8;
|
||||
|
||||
// Convert above A,B,C vectors to byte arrays for cpp
|
||||
let mut a_arr: Vec<u8> = vec![0u8; STRUCT_SIZE * a_vec.len()];
|
||||
let mut b_arr: Vec<u8> = vec![0u8; STRUCT_SIZE * b_vec.len()];
|
||||
let mut c_arr: Vec<u8> = vec![0u8; STRUCT_SIZE * c_vec.len()];
|
||||
use std::mem::transmute;
|
||||
for (id, (row, idx, val)) in a_vec.iter().enumerate() {
|
||||
let row_bytes: [u8; ROW_SIZE] = unsafe { transmute(row.to_le()) };
|
||||
let idx_bytes: [u8; IDX_SIZE] = unsafe { transmute(idx.to_le()) };
|
||||
|
||||
for x in 0..ROW_SIZE {
|
||||
a_arr[id * STRUCT_SIZE + x] = row_bytes[x];
|
||||
}
|
||||
for x in 0..IDX_SIZE {
|
||||
a_arr[id * STRUCT_SIZE + x + IDX_OFFSET] = idx_bytes[x];
|
||||
}
|
||||
for x in 0..VALUE_SIZE {
|
||||
a_arr[id * STRUCT_SIZE + x + VALUE_OFFSET] = val[x];
|
||||
}
|
||||
}
|
||||
for (id, (row, idx, val)) in b_vec.iter().enumerate() {
|
||||
let row_bytes: [u8; ROW_SIZE] = unsafe { transmute(row.to_le()) };
|
||||
let idx_bytes: [u8; IDX_SIZE] = unsafe { transmute(idx.to_le()) };
|
||||
|
||||
for x in 0..ROW_SIZE {
|
||||
b_arr[id * STRUCT_SIZE + x] = row_bytes[x];
|
||||
}
|
||||
for x in 0..IDX_SIZE {
|
||||
b_arr[id * STRUCT_SIZE + x + IDX_OFFSET] = idx_bytes[x];
|
||||
}
|
||||
for x in 0..VALUE_SIZE {
|
||||
b_arr[id * STRUCT_SIZE + x + VALUE_OFFSET] = val[x];
|
||||
}
|
||||
}
|
||||
for (id, (row, idx, val)) in c_vec.iter().enumerate() {
|
||||
let row_bytes: [u8; ROW_SIZE] = unsafe { transmute(row.to_le()) };
|
||||
let idx_bytes: [u8; IDX_SIZE] = unsafe { transmute(idx.to_le()) };
|
||||
|
||||
for x in 0..ROW_SIZE {
|
||||
c_arr[id * STRUCT_SIZE + x] = row_bytes[x];
|
||||
}
|
||||
for x in 0..IDX_SIZE {
|
||||
c_arr[id * STRUCT_SIZE + x + IDX_OFFSET] = idx_bytes[x];
|
||||
}
|
||||
for x in 0..VALUE_SIZE {
|
||||
c_arr[id * STRUCT_SIZE + x + VALUE_OFFSET] = val[x];
|
||||
}
|
||||
}
|
||||
|
||||
// convert String slices to 'CString's
|
||||
let pk_path_cstring = CString::new(pk_path).unwrap();
|
||||
let vk_path_cstring = CString::new(vk_path).unwrap();
|
||||
|
||||
(
|
||||
a_arr,
|
||||
b_arr,
|
||||
c_arr,
|
||||
a_vec,
|
||||
b_vec,
|
||||
c_vec,
|
||||
num_constraints,
|
||||
num_variables,
|
||||
num_inputs,
|
||||
pk_path_cstring,
|
||||
vk_path_cstring,
|
||||
)
|
||||
}
|
||||
|
||||
// proof-system-independent preparation for proof generation
|
||||
pub fn prepare_generate_proof<T: Field>(
|
||||
pk_path: &str,
|
||||
proof_path: &str,
|
||||
public_inputs: Vec<T>,
|
||||
private_inputs: Vec<T>,
|
||||
) -> (CString, CString, Vec<[u8; 32]>, usize, Vec<[u8; 32]>, usize) {
|
||||
let pk_path_cstring = CString::new(pk_path).unwrap();
|
||||
let proof_path_cstring = CString::new(proof_path).unwrap();
|
||||
|
||||
let public_inputs_length = public_inputs.len();
|
||||
let private_inputs_length = private_inputs.len();
|
||||
|
||||
let mut public_inputs_arr: Vec<[u8; 32]> = vec![[0u8; 32]; public_inputs_length];
|
||||
// length must not be zero here, so we apply the max function
|
||||
let mut private_inputs_arr: Vec<[u8; 32]> = vec![[0u8; 32]; max(private_inputs_length, 1)];
|
||||
|
||||
//convert inputs
|
||||
for (index, value) in public_inputs.into_iter().enumerate() {
|
||||
public_inputs_arr[index] = vec_as_u8_32_array(&value.into_byte_vector());
|
||||
}
|
||||
for (index, value) in private_inputs.into_iter().enumerate() {
|
||||
private_inputs_arr[index] = vec_as_u8_32_array(&value.into_byte_vector());
|
||||
}
|
||||
|
||||
(
|
||||
pk_path_cstring,
|
||||
proof_path_cstring,
|
||||
public_inputs_arr,
|
||||
public_inputs_length,
|
||||
private_inputs_arr,
|
||||
private_inputs_length,
|
||||
)
|
||||
}
|
||||
|
||||
pub const SOLIDITY_G2_ADDITION_LIB: &str = r#"// This file is LGPL3 Licensed
|
||||
|
||||
pragma solidity ^0.4.19;
|
||||
|
||||
/**
|
||||
* @title Elliptic curve operations on twist points for alt_bn128
|
||||
* @author Mustafa Al-Bassam (mus@musalbas.com)
|
||||
*/
|
||||
library BN256G2 {
|
||||
uint256 internal constant FIELD_MODULUS = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47;
|
||||
uint256 internal constant TWISTBX = 0x2b149d40ceb8aaae81be18991be06ac3b5b4c5e559dbefa33267e6dc24a138e5;
|
||||
uint256 internal constant TWISTBY = 0x9713b03af0fed4cd2cafadeed8fdf4a74fa084e52d1852e4a2bd0685c315d2;
|
||||
uint internal constant PTXX = 0;
|
||||
uint internal constant PTXY = 1;
|
||||
uint internal constant PTYX = 2;
|
||||
uint internal constant PTYY = 3;
|
||||
uint internal constant PTZX = 4;
|
||||
uint internal constant PTZY = 5;
|
||||
|
||||
/**
|
||||
* @notice Add two twist points
|
||||
* @param pt1xx Coefficient 1 of x on point 1
|
||||
* @param pt1xy Coefficient 2 of x on point 1
|
||||
* @param pt1yx Coefficient 1 of y on point 1
|
||||
* @param pt1yy Coefficient 2 of y on point 1
|
||||
* @param pt2xx Coefficient 1 of x on point 2
|
||||
* @param pt2xy Coefficient 2 of x on point 2
|
||||
* @param pt2yx Coefficient 1 of y on point 2
|
||||
* @param pt2yy Coefficient 2 of y on point 2
|
||||
* @return (pt3xx, pt3xy, pt3yx, pt3yy)
|
||||
*/
|
||||
function ECTwistAdd(
|
||||
uint256 pt1xx, uint256 pt1xy,
|
||||
uint256 pt1yx, uint256 pt1yy,
|
||||
uint256 pt2xx, uint256 pt2xy,
|
||||
uint256 pt2yx, uint256 pt2yy
|
||||
) public pure returns (
|
||||
uint256, uint256,
|
||||
uint256, uint256
|
||||
) {
|
||||
assert(_isOnCurve(
|
||||
pt1xx, pt1xy,
|
||||
pt1yx, pt1yy
|
||||
));
|
||||
|
||||
uint256[6] memory pt3 = _ECTwistAddJacobian(
|
||||
pt1xx, pt1xy,
|
||||
pt1yx, pt1yy,
|
||||
1, 0,
|
||||
pt2xx, pt2xy,
|
||||
pt2yx, pt2yy,
|
||||
1, 0
|
||||
);
|
||||
|
||||
return _fromJacobian(
|
||||
pt3[PTXX], pt3[PTXY],
|
||||
pt3[PTYX], pt3[PTYY],
|
||||
pt3[PTZX], pt3[PTZY]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Multiply a twist point by a scalar
|
||||
* @param s Scalar to multiply by
|
||||
* @param pt1xx Coefficient 1 of x
|
||||
* @param pt1xy Coefficient 2 of x
|
||||
* @param pt1yx Coefficient 1 of y
|
||||
* @param pt1yy Coefficient 2 of y
|
||||
* @return (pt2xx, pt2xy, pt2yx, pt2yy)
|
||||
*/
|
||||
function ECTwistMul(
|
||||
uint256 s,
|
||||
uint256 pt1xx, uint256 pt1xy,
|
||||
uint256 pt1yx, uint256 pt1yy
|
||||
) public pure returns (
|
||||
uint256, uint256,
|
||||
uint256, uint256
|
||||
) {
|
||||
assert(_isOnCurve(
|
||||
pt1xx, pt1xy,
|
||||
pt1yx, pt1yy
|
||||
));
|
||||
|
||||
uint256[6] memory pt2 = _ECTwistMulJacobian(
|
||||
s,
|
||||
pt1xx, pt1xy,
|
||||
pt1yx, pt1yy,
|
||||
1, 0
|
||||
);
|
||||
|
||||
return _fromJacobian(
|
||||
pt2[PTXX], pt2[PTXY],
|
||||
pt2[PTYX], pt2[PTYY],
|
||||
pt2[PTZX], pt2[PTZY]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @notice Get the field modulus
|
||||
* @return The field modulus
|
||||
*/
|
||||
function GetFieldModulus() public pure returns (uint256) {
|
||||
return FIELD_MODULUS;
|
||||
}
|
||||
|
||||
function submod(uint256 a, uint256 b, uint256 n) internal pure returns (uint256) {
|
||||
return addmod(a, n - b, n);
|
||||
}
|
||||
|
||||
function _FQ2Mul(
|
||||
uint256 xx, uint256 xy,
|
||||
uint256 yx, uint256 yy
|
||||
) internal pure returns(uint256, uint256) {
|
||||
return (
|
||||
submod(mulmod(xx, yx, FIELD_MODULUS), mulmod(xy, yy, FIELD_MODULUS), FIELD_MODULUS),
|
||||
addmod(mulmod(xx, yy, FIELD_MODULUS), mulmod(xy, yx, FIELD_MODULUS), FIELD_MODULUS)
|
||||
);
|
||||
}
|
||||
|
||||
function _FQ2Muc(
|
||||
uint256 xx, uint256 xy,
|
||||
uint256 c
|
||||
) internal pure returns(uint256, uint256) {
|
||||
return (
|
||||
mulmod(xx, c, FIELD_MODULUS),
|
||||
mulmod(xy, c, FIELD_MODULUS)
|
||||
);
|
||||
}
|
||||
|
||||
function _FQ2Add(
|
||||
uint256 xx, uint256 xy,
|
||||
uint256 yx, uint256 yy
|
||||
) internal pure returns(uint256, uint256) {
|
||||
return (
|
||||
addmod(xx, yx, FIELD_MODULUS),
|
||||
addmod(xy, yy, FIELD_MODULUS)
|
||||
);
|
||||
}
|
||||
|
||||
function _FQ2Sub(
|
||||
uint256 xx, uint256 xy,
|
||||
uint256 yx, uint256 yy
|
||||
) internal pure returns(uint256 rx, uint256 ry) {
|
||||
return (
|
||||
submod(xx, yx, FIELD_MODULUS),
|
||||
submod(xy, yy, FIELD_MODULUS)
|
||||
);
|
||||
}
|
||||
|
||||
function _FQ2Div(
|
||||
uint256 xx, uint256 xy,
|
||||
uint256 yx, uint256 yy
|
||||
) internal pure returns(uint256, uint256) {
|
||||
(yx, yy) = _FQ2Inv(yx, yy);
|
||||
return _FQ2Mul(xx, xy, yx, yy);
|
||||
}
|
||||
|
||||
function _FQ2Inv(uint256 x, uint256 y) internal pure returns(uint256, uint256) {
|
||||
uint256 inv = _modInv(addmod(mulmod(y, y, FIELD_MODULUS), mulmod(x, x, FIELD_MODULUS), FIELD_MODULUS), FIELD_MODULUS);
|
||||
return (
|
||||
mulmod(x, inv, FIELD_MODULUS),
|
||||
FIELD_MODULUS - mulmod(y, inv, FIELD_MODULUS)
|
||||
);
|
||||
}
|
||||
|
||||
function _isOnCurve(
|
||||
uint256 xx, uint256 xy,
|
||||
uint256 yx, uint256 yy
|
||||
) internal pure returns (bool) {
|
||||
uint256 yyx;
|
||||
uint256 yyy;
|
||||
uint256 xxxx;
|
||||
uint256 xxxy;
|
||||
(yyx, yyy) = _FQ2Mul(yx, yy, yx, yy);
|
||||
(xxxx, xxxy) = _FQ2Mul(xx, xy, xx, xy);
|
||||
(xxxx, xxxy) = _FQ2Mul(xxxx, xxxy, xx, xy);
|
||||
(yyx, yyy) = _FQ2Sub(yyx, yyy, xxxx, xxxy);
|
||||
(yyx, yyy) = _FQ2Sub(yyx, yyy, TWISTBX, TWISTBY);
|
||||
return yyx == 0 && yyy == 0;
|
||||
}
|
||||
|
||||
function _modInv(uint256 a, uint256 n) internal pure returns(uint256 t) {
|
||||
t = 0;
|
||||
uint256 newT = 1;
|
||||
uint256 r = n;
|
||||
uint256 newR = a;
|
||||
uint256 q;
|
||||
while (newR != 0) {
|
||||
q = r / newR;
|
||||
(t, newT) = (newT, submod(t, mulmod(q, newT, n), n));
|
||||
(r, newR) = (newR, r - q * newR);
|
||||
}
|
||||
}
|
||||
|
||||
function _toJacobian(
|
||||
uint256 pt1xx, uint256 pt1xy,
|
||||
uint256 pt1yx, uint256 pt1yy
|
||||
) internal pure returns (
|
||||
uint256, uint256,
|
||||
uint256, uint256,
|
||||
uint256, uint256
|
||||
) {
|
||||
return (
|
||||
pt1xx, pt1xy,
|
||||
pt1yx, pt1yy,
|
||||
1, 0
|
||||
);
|
||||
}
|
||||
|
||||
function _fromJacobian(
|
||||
uint256 pt1xx, uint256 pt1xy,
|
||||
uint256 pt1yx, uint256 pt1yy,
|
||||
uint256 pt1zx, uint256 pt1zy
|
||||
) internal pure returns (
|
||||
uint256 pt2xx, uint256 pt2xy,
|
||||
uint256 pt2yx, uint256 pt2yy
|
||||
) {
|
||||
uint256 invzx;
|
||||
uint256 invzy;
|
||||
(invzx, invzy) = _FQ2Inv(pt1zx, pt1zy);
|
||||
(pt2xx, pt2xy) = _FQ2Mul(pt1xx, pt1xy, invzx, invzy);
|
||||
(pt2yx, pt2yy) = _FQ2Mul(pt1yx, pt1yy, invzx, invzy);
|
||||
}
|
||||
|
||||
function _ECTwistAddJacobian(
|
||||
uint256 pt1xx, uint256 pt1xy,
|
||||
uint256 pt1yx, uint256 pt1yy,
|
||||
uint256 pt1zx, uint256 pt1zy,
|
||||
uint256 pt2xx, uint256 pt2xy,
|
||||
uint256 pt2yx, uint256 pt2yy,
|
||||
uint256 pt2zx, uint256 pt2zy) internal pure returns (uint256[6] pt3) {
|
||||
if (pt1zx == 0 && pt1zy == 0) {
|
||||
(
|
||||
pt3[PTXX], pt3[PTXY],
|
||||
pt3[PTYX], pt3[PTYY],
|
||||
pt3[PTZX], pt3[PTZY]
|
||||
) = (
|
||||
pt2xx, pt2xy,
|
||||
pt2yx, pt2yy,
|
||||
pt2zx, pt2zy
|
||||
);
|
||||
return;
|
||||
} else if (pt2zx == 0 && pt2zy == 0) {
|
||||
(
|
||||
pt3[PTXX], pt3[PTXY],
|
||||
pt3[PTYX], pt3[PTYY],
|
||||
pt3[PTZX], pt3[PTZY]
|
||||
) = (
|
||||
pt1xx, pt1xy,
|
||||
pt1yx, pt1yy,
|
||||
pt1zx, pt1zy
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
(pt2yx, pt2yy) = _FQ2Mul(pt2yx, pt2yy, pt1zx, pt1zy); // U1 = y2 * z1
|
||||
(pt3[PTYX], pt3[PTYY]) = _FQ2Mul(pt1yx, pt1yy, pt2zx, pt2zy); // U2 = y1 * z2
|
||||
(pt2xx, pt2xy) = _FQ2Mul(pt2xx, pt2xy, pt1zx, pt1zy); // V1 = x2 * z1
|
||||
(pt3[PTZX], pt3[PTZY]) = _FQ2Mul(pt1xx, pt1xy, pt2zx, pt2zy); // V2 = x1 * z2
|
||||
|
||||
if (pt2xx == pt3[PTZX] && pt2xy == pt3[PTZY]) {
|
||||
if (pt2yx == pt3[PTYX] && pt2yy == pt3[PTYY]) {
|
||||
(
|
||||
pt3[PTXX], pt3[PTXY],
|
||||
pt3[PTYX], pt3[PTYY],
|
||||
pt3[PTZX], pt3[PTZY]
|
||||
) = _ECTwistDoubleJacobian(pt1xx, pt1xy, pt1yx, pt1yy, pt1zx, pt1zy);
|
||||
return;
|
||||
}
|
||||
(
|
||||
pt3[PTXX], pt3[PTXY],
|
||||
pt3[PTYX], pt3[PTYY],
|
||||
pt3[PTZX], pt3[PTZY]
|
||||
) = (
|
||||
0, 0,
|
||||
0, 0,
|
||||
0, 0
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
(pt2zx, pt2zy) = _FQ2Mul(pt1zx, pt1zy, pt2zx, pt2zy); // W = z1 * z2
|
||||
(pt1xx, pt1xy) = _FQ2Sub(pt2yx, pt2yy, pt3[PTYX], pt3[PTYY]); // U = U1 - U2
|
||||
(pt1yx, pt1yy) = _FQ2Sub(pt2xx, pt2xy, pt3[PTZX], pt3[PTZY]); // V = V1 - V2
|
||||
(pt1zx, pt1zy) = _FQ2Mul(pt1yx, pt1yy, pt1yx, pt1yy); // V_squared = V * V
|
||||
(pt2yx, pt2yy) = _FQ2Mul(pt1zx, pt1zy, pt3[PTZX], pt3[PTZY]); // V_squared_times_V2 = V_squared * V2
|
||||
(pt1zx, pt1zy) = _FQ2Mul(pt1zx, pt1zy, pt1yx, pt1yy); // V_cubed = V * V_squared
|
||||
(pt3[PTZX], pt3[PTZY]) = _FQ2Mul(pt1zx, pt1zy, pt2zx, pt2zy); // newz = V_cubed * W
|
||||
(pt2xx, pt2xy) = _FQ2Mul(pt1xx, pt1xy, pt1xx, pt1xy); // U * U
|
||||
(pt2xx, pt2xy) = _FQ2Mul(pt2xx, pt2xy, pt2zx, pt2zy); // U * U * W
|
||||
(pt2xx, pt2xy) = _FQ2Sub(pt2xx, pt2xy, pt1zx, pt1zy); // U * U * W - V_cubed
|
||||
(pt2zx, pt2zy) = _FQ2Muc(pt2yx, pt2yy, 2); // 2 * V_squared_times_V2
|
||||
(pt2xx, pt2xy) = _FQ2Sub(pt2xx, pt2xy, pt2zx, pt2zy); // A = U * U * W - V_cubed - 2 * V_squared_times_V2
|
||||
(pt3[PTXX], pt3[PTXY]) = _FQ2Mul(pt1yx, pt1yy, pt2xx, pt2xy); // newx = V * A
|
||||
(pt1yx, pt1yy) = _FQ2Sub(pt2yx, pt2yy, pt2xx, pt2xy); // V_squared_times_V2 - A
|
||||
(pt1yx, pt1yy) = _FQ2Mul(pt1xx, pt1xy, pt1yx, pt1yy); // U * (V_squared_times_V2 - A)
|
||||
(pt1xx, pt1xy) = _FQ2Mul(pt1zx, pt1zy, pt3[PTYX], pt3[PTYY]); // V_cubed * U2
|
||||
(pt3[PTYX], pt3[PTYY]) = _FQ2Sub(pt1yx, pt1yy, pt1xx, pt1xy); // newy = U * (V_squared_times_V2 - A) - V_cubed * U2
|
||||
}
|
||||
|
||||
function _ECTwistDoubleJacobian(
|
||||
uint256 pt1xx, uint256 pt1xy,
|
||||
uint256 pt1yx, uint256 pt1yy,
|
||||
uint256 pt1zx, uint256 pt1zy
|
||||
) internal pure returns(
|
||||
uint256 pt2xx, uint256 pt2xy,
|
||||
uint256 pt2yx, uint256 pt2yy,
|
||||
uint256 pt2zx, uint256 pt2zy
|
||||
) {
|
||||
(pt2xx, pt2xy) = _FQ2Muc(pt1xx, pt1xy, 3); // 3 * x
|
||||
(pt2xx, pt2xy) = _FQ2Mul(pt2xx, pt2xy, pt1xx, pt1xy); // W = 3 * x * x
|
||||
(pt1zx, pt1zy) = _FQ2Mul(pt1yx, pt1yy, pt1zx, pt1zy); // S = y * z
|
||||
(pt2yx, pt2yy) = _FQ2Mul(pt1xx, pt1xy, pt1yx, pt1yy); // x * y
|
||||
(pt2yx, pt2yy) = _FQ2Mul(pt2yx, pt2yy, pt1zx, pt1zy); // B = x * y * S
|
||||
(pt1xx, pt1xy) = _FQ2Mul(pt2xx, pt2xy, pt2xx, pt2xy); // W * W
|
||||
(pt2zx, pt2zy) = _FQ2Muc(pt2yx, pt2yy, 8); // 8 * B
|
||||
(pt1xx, pt1xy) = _FQ2Sub(pt1xx, pt1xy, pt2zx, pt2zy); // H = W * W - 8 * B
|
||||
(pt2zx, pt2zy) = _FQ2Mul(pt1zx, pt1zy, pt1zx, pt1zy); // S_squared = S * S
|
||||
(pt2yx, pt2yy) = _FQ2Muc(pt2yx, pt2yy, 4); // 4 * B
|
||||
(pt2yx, pt2yy) = _FQ2Sub(pt2yx, pt2yy, pt1xx, pt1xy); // 4 * B - H
|
||||
(pt2yx, pt2yy) = _FQ2Mul(pt2yx, pt2yy, pt2xx, pt2xy); // W * (4 * B - H)
|
||||
(pt2xx, pt2xy) = _FQ2Muc(pt1yx, pt1yy, 8); // 8 * y
|
||||
(pt2xx, pt2xy) = _FQ2Mul(pt2xx, pt2xy, pt1yx, pt1yy); // 8 * y * y
|
||||
(pt2xx, pt2xy) = _FQ2Mul(pt2xx, pt2xy, pt2zx, pt2zy); // 8 * y * y * S_squared
|
||||
(pt2yx, pt2yy) = _FQ2Sub(pt2yx, pt2yy, pt2xx, pt2xy); // newy = W * (4 * B - H) - 8 * y * y * S_squared
|
||||
(pt2xx, pt2xy) = _FQ2Muc(pt1xx, pt1xy, 2); // 2 * H
|
||||
(pt2xx, pt2xy) = _FQ2Mul(pt2xx, pt2xy, pt1zx, pt1zy); // newx = 2 * H * S
|
||||
(pt2zx, pt2zy) = _FQ2Mul(pt1zx, pt1zy, pt2zx, pt2zy); // S * S_squared
|
||||
(pt2zx, pt2zy) = _FQ2Muc(pt2zx, pt2zy, 8); // newz = 8 * S * S_squared
|
||||
}
|
||||
|
||||
function _ECTwistMulJacobian(
|
||||
uint256 d,
|
||||
uint256 pt1xx, uint256 pt1xy,
|
||||
uint256 pt1yx, uint256 pt1yy,
|
||||
uint256 pt1zx, uint256 pt1zy
|
||||
) internal pure returns(uint256[6] pt2) {
|
||||
while (d != 0) {
|
||||
if ((d & 1) != 0) {
|
||||
pt2 = _ECTwistAddJacobian(
|
||||
pt2[PTXX], pt2[PTXY],
|
||||
pt2[PTYX], pt2[PTYY],
|
||||
pt2[PTZX], pt2[PTZY],
|
||||
pt1xx, pt1xy,
|
||||
pt1yx, pt1yy,
|
||||
pt1zx, pt1zy);
|
||||
}
|
||||
(
|
||||
pt1xx, pt1xy,
|
||||
pt1yx, pt1yy,
|
||||
pt1zx, pt1zy
|
||||
) = _ECTwistDoubleJacobian(
|
||||
pt1xx, pt1xy,
|
||||
pt1yx, pt1yy,
|
||||
pt1zx, pt1zy
|
||||
);
|
||||
|
||||
d = d / 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
"#;
|
||||
|
||||
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 pure returns (G2Point r) {
|
||||
(r.X[1], r.X[0], r.Y[1], r.Y[0]) = BN256G2.ECTwistAdd(p1.X[1],p1.X[0],p1.Y[1],p1.Y[0],p2.X[1],p2.X[0],p2.Y[1],p2.Y[0]);
|
||||
}
|
||||
/// @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);
|
||||
}
|
||||
}
|
||||
"#;
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
"#;
|
Loading…
Reference in a new issue