file_path
stringlengths
7
180
content
stringlengths
0
811k
repo
stringclasses
11 values
src/layers/batch_mat_mul.rs
use std::{collections::HashMap, marker::PhantomData, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, Axis, IxDyn}; use crate::{ gadgets::gadget::{GadgetConfig, GadgetType}, layers::fully_connected::FullyConnectedConfig, }; use super::{ fully_connected::FullyConnectedChip, layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}, }; pub struct BatchMatMulChip {} impl<F: PrimeField> Layer<F> for BatchMatMulChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp1 = &tensors[0]; let inp2 = &tensors[1]; println!("inp1: {:?}", inp1.shape()); println!("inp2: {:?}", inp2.shape()); assert_eq!(inp1.ndim(), 3); assert_eq!(inp2.ndim(), 3); assert_eq!(inp1.shape()[0], inp2.shape()[0]); let adj_y = layer_config.layer_params[1] == 1; if adj_y { assert_eq!(inp1.shape()[2], inp2.shape()[2]); } else { assert_eq!(inp1.shape()[2], inp2.shape()[1]); } let out_shape = if adj_y { vec![inp1.shape()[0], inp1.shape()[1], inp2.shape()[1]] } else { vec![inp1.shape()[0], inp1.shape()[1], inp2.shape()[2]] }; let fc_chip = FullyConnectedChip::<F> { _marker: PhantomData, config: FullyConnectedConfig::construct(true), }; let mut outp: Vec<CellRc<F>> = vec![]; for i in 0..inp1.shape()[0] { let inp1_slice = inp1.index_axis(Axis(0), i).to_owned(); // Due to tensorflow BS, transpose the "weights" let inp2_slice = if adj_y { inp2.index_axis(Axis(0), i).to_owned() } else { inp2.index_axis(Axis(0), i).t().to_owned() }; println!("inp1_slice: {:?}", inp1_slice.shape()); println!("inp2_slice: {:?}", inp2_slice.shape()); // Batch MM doesn't have a fused activation, so insert it here // TODO: consider putting this in the converter? let tmp_config = LayerConfig { layer_params: vec![0], ..layer_config.clone() }; let outp_slice = fc_chip.forward( layouter.namespace(|| ""), &vec![inp1_slice, inp2_slice], constants, gadget_config.clone(), &tmp_config, )?; outp.extend(outp_slice[0].iter().map(|x| x.clone()).collect::<Vec<_>>()); } let outp = Array::from_shape_vec(IxDyn(out_shape.as_slice()), outp).unwrap(); Ok(vec![outp]) } } impl GadgetConsumer for BatchMatMulChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![ GadgetType::Adder, GadgetType::DotProduct, GadgetType::VarDivRound, GadgetType::InputLookup, ] } }
https://github.com/ddkang/zkml
src/layers/conv2d.rs
// TODO: Speed up Depthwise operations with Freivald's algorithm use std::{collections::HashMap, marker::PhantomData, rc::Rc}; use halo2_proofs::{ circuit::{AssignedCell, Layouter}, halo2curves::ff::PrimeField, plonk::Error, }; use ndarray::{Array, IxDyn}; use crate::{ gadgets::{ bias_div_round_relu6::BiasDivRoundRelu6Chip, dot_prod::DotProductChip, gadget::{Gadget, GadgetConfig, GadgetType}, nonlinear::relu::ReluChip, }, layers::{ fully_connected::{FullyConnectedChip, FullyConnectedConfig}, shape::pad::pad, }, }; use super::layer::{ActivationType, AssignedTensor, GadgetConsumer, Layer, LayerConfig}; #[derive(Default, Clone, Copy, Eq, PartialEq)] pub enum PaddingEnum { #[default] Same, Valid, } #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub enum ConvLayerEnum { #[default] Conv2D, DepthwiseConv2D, } pub struct Conv2DConfig { pub conv_type: ConvLayerEnum, pub padding: PaddingEnum, pub activation: ActivationType, pub stride: (usize, usize), } pub struct Conv2DChip<F: PrimeField> { pub config: LayerConfig, pub _marker: PhantomData<F>, } impl<F: PrimeField> Conv2DChip<F> { // TODO: this is horrible. What's the best way to fix this? pub fn param_vec_to_config(layer_params: Vec<i64>) -> Conv2DConfig { let conv_type = match layer_params[0] { 0 => ConvLayerEnum::Conv2D, 1 => ConvLayerEnum::DepthwiseConv2D, _ => panic!("Invalid conv type"), }; let padding = match layer_params[1] { 0 => PaddingEnum::Same, 1 => PaddingEnum::Valid, _ => panic!("Invalid padding"), }; let activation = match layer_params[2] { 0 => ActivationType::None, 1 => ActivationType::Relu, 3 => ActivationType::Relu6, _ => panic!("Invalid activation type"), }; let stride = (layer_params[3] as usize, layer_params[4] as usize); Conv2DConfig { conv_type, padding, activation, stride, } } pub fn get_padding( h: usize, w: usize, si: usize, sj: usize, ci: usize, cj: usize, ) -> ((usize, usize), (usize, usize)) { let ph = if h % si == 0 { (ci as i64 - sj as i64).max(0) } else { (ci as i64 - (h % si) as i64).max(0) } as usize; let pw = if w % sj == 0 { (cj as i64 - sj as i64).max(0) } else { (cj as i64 - (w % sj) as i64).max(0) } as usize; ((ph / 2, ph - ph / 2), (pw / 2, pw - pw / 2)) } pub fn out_hw( h: usize, w: usize, si: usize, sj: usize, ch: usize, cw: usize, padding: PaddingEnum, ) -> (usize, usize) { /* println!( "H: {}, W: {}, SI: {}, SJ: {}, CH: {}, CW: {}", h, w, si, sj, ch, cw ); */ // https://iq.opengenus.org/same-and-valid-padding/ match padding { PaddingEnum::Same => ((h + si - 1) / si, (w + sj - 1) / sj), // TODO: the above is probably correct, but we always have valid paddings // PaddingEnum::Same => (h / si, w / sj), PaddingEnum::Valid => ((h - ch) / si + 1, (w - cw) / sj + 1), } } pub fn splat<G: Clone>( &self, tensors: &Vec<Array<Rc<G>, IxDyn>>, zero: Rc<G>, ) -> (Vec<Vec<Rc<G>>>, Vec<Vec<Rc<G>>>, Vec<Rc<G>>) { // assert_eq!(tensors.len(), 3); assert!(tensors.len() <= 3); let conv_config = &Self::param_vec_to_config(self.config.layer_params.clone()); let inp = &tensors[0]; let weights = &tensors[1]; let zero_arr = Array::from_elem(IxDyn(&vec![1]), zero.clone()); let biases = if tensors.len() == 3 { &tensors[2] } else { &zero_arr }; let h: usize = inp.shape()[1]; let w: usize = inp.shape()[2]; let ch: usize = weights.shape()[1]; let cw: usize = weights.shape()[2]; let (si, sj) = conv_config.stride; // B, H, W, C assert_eq!(inp.shape().len(), 4); let (ph, pw) = if conv_config.padding == PaddingEnum::Same { Self::get_padding(h, w, si, sj, ch, cw) } else { ((0, 0), (0, 0)) }; // println!("Padding: {:?}", (ph, pw)); let padding = vec![[0, 0], [ph.0, ph.1], [pw.0, pw.1], [0, 0]]; let inp_pad = pad(&inp, padding, &zero); let (oh, ow) = Self::out_hw(h, w, si, sj, ch, cw, conv_config.padding); let mut inp_cells = vec![]; let mut weights_cells = vec![]; let mut biases_cells = vec![]; let mut input_row_idx = 0; let mut weight_row_idx = 0; // (output_channels x inp_channels * C_H * C_W) for chan_out in 0..weights.shape()[0] { weights_cells.push(vec![]); for ci in 0..weights.shape()[1] { for cj in 0..weights.shape()[2] { for ck in 0..weights.shape()[3] { weights_cells[weight_row_idx].push(weights[[chan_out, ci, cj, ck]].clone()); } } } weight_row_idx += 1; } // (O_H * O_W x inp_channels * C_H * C_W) for batch in 0..inp.shape()[0] { for i in 0..oh { for j in 0..ow { inp_cells.push(vec![]); for ci in 0..weights.shape()[1] { for cj in 0..weights.shape()[2] { for ck in 0..weights.shape()[3] { let idx_i = i * si + ci; let idx_j = j * sj + cj; inp_cells[input_row_idx].push(inp_pad[[batch, idx_i, idx_j, ck]].clone()); } } } input_row_idx += 1; } } } for _batch in 0..inp.shape()[0] { for _ in 0..oh { for _ in 0..ow { for chan_out in 0..weights.shape()[0] { if tensors.len() == 3 { biases_cells.push(biases[chan_out].clone()); } else { biases_cells.push(zero.clone()); } } } } } (inp_cells, weights_cells, biases_cells) } pub fn splat_depthwise<G: Clone>( &self, tensors: &Vec<Array<Rc<G>, IxDyn>>, zero: Rc<G>, ) -> (Vec<Vec<Rc<G>>>, Vec<Vec<Rc<G>>>, Vec<Rc<G>>) { let input = &tensors[0]; let weights = &tensors[1]; let biases = &tensors[2]; assert_eq!(tensors.len(), 3); assert_eq!(input.shape().len(), 4); assert_eq!(weights.shape().len(), 4); assert_eq!(input.shape()[0], 1); let conv_config = &Self::param_vec_to_config(self.config.layer_params.clone()); let strides = conv_config.stride; let h: usize = input.shape()[1]; let w: usize = input.shape()[2]; let ch: usize = weights.shape()[1]; let cw: usize = weights.shape()[2]; let (si, sj) = conv_config.stride; let (oh, ow) = Self::out_hw(h, w, si, sj, ch, cw, conv_config.padding); let (ph, pw) = if conv_config.padding == PaddingEnum::Same { Self::get_padding(h, w, si, sj, ch, cw) } else { ((0, 0), (0, 0)) }; let padding = vec![[0, 0], [ph.0, ph.1], [pw.0, pw.1], [0, 0]]; let inp_pad = pad(&input, padding, &zero); let mut inp_cells = vec![]; let mut weight_cells = vec![]; let mut biases_cells = vec![]; let mut row_idx = 0; for i in 0..oh { for j in 0..ow { for chan_out in 0..weights.shape()[3] { inp_cells.push(vec![]); weight_cells.push(vec![]); biases_cells.push(biases[[chan_out]].clone()); for ci in 0..weights.shape()[1] { for cj in 0..weights.shape()[2] { let idx_i = i * strides.0 + ci; let idx_j = j * strides.1 + cj; inp_cells[row_idx].push(inp_pad[[0, idx_i, idx_j, chan_out]].clone()); weight_cells[row_idx].push(weights[[0, ci, cj, chan_out]].clone()); } } row_idx += 1; } } } (inp_cells, weight_cells, biases_cells) } } impl<F: PrimeField> Layer<F> for Conv2DChip<F> { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, Rc<AssignedCell<F, F>>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let conv_config = &Self::param_vec_to_config(self.config.layer_params.clone()); let zero = constants.get(&0).unwrap(); let inp = &tensors[0]; let weights = &tensors[1]; let (oh, ow) = Self::out_hw( inp.shape()[1], inp.shape()[2], conv_config.stride.0, conv_config.stride.1, weights.shape()[1], weights.shape()[2], conv_config.padding, ); let batch_size = inp.shape()[0]; let (splat_inp, splat_weights, splat_biases) = match conv_config.conv_type { ConvLayerEnum::Conv2D => self.splat(tensors, zero.clone()), ConvLayerEnum::DepthwiseConv2D => self.splat_depthwise(tensors, zero.clone()), }; let outp_flat: Vec<AssignedCell<F, F>> = match conv_config.conv_type { ConvLayerEnum::Conv2D => { let fc_chip = FullyConnectedChip::<F> { _marker: PhantomData, config: FullyConnectedConfig::construct(false), }; let conv_size = splat_inp[0].len(); let flattened_inp: Vec<_> = splat_inp.into_iter().flat_map(|x| x.into_iter()).collect(); let flattened_weights = splat_weights .into_iter() .flat_map(|x| x.into_iter()) .collect::<Vec<_>>(); let out_channels = weights.shape()[0]; let inp_array = Array::from_shape_vec(IxDyn(&vec![batch_size * oh * ow, conv_size]), flattened_inp) .unwrap(); let weights_array = Array::from_shape_vec(IxDyn(&vec![out_channels, conv_size]), flattened_weights).unwrap(); let outp_slice = fc_chip .forward( layouter.namespace(|| ""), &vec![weights_array, inp_array], constants, gadget_config.clone(), layer_config, ) .unwrap(); let outp_flat = outp_slice[0] .t() .into_iter() .map(|x| (**x).clone()) .collect::<Vec<_>>(); outp_flat } ConvLayerEnum::DepthwiseConv2D => { // Do the dot products let dot_prod_chip = DotProductChip::<F>::construct(gadget_config.clone()); let mut outp_flat = vec![]; for (inp_vec, weight_vec) in splat_inp.iter().zip(splat_weights.iter()) { let inp_vec = inp_vec.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let weight_vec = weight_vec.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let vec_inputs = vec![inp_vec, weight_vec]; let constants = vec![zero.as_ref()]; let outp = dot_prod_chip .forward(layouter.namespace(|| "dot_prod"), &vec_inputs, &constants) .unwrap(); outp_flat.push(outp[0].clone()); } // println!("outp_flat: {:?}", outp_flat.len()); outp_flat } }; let mut biases = vec![]; for bias in splat_biases.iter() { biases.push(bias.as_ref()); } // Compute the bias + div + relu let bdr_chip = BiasDivRoundRelu6Chip::<F>::construct(gadget_config.clone()); let tmp = vec![zero.as_ref()]; let outp_flat = outp_flat.iter().map(|x| x).collect::<Vec<_>>(); let outp = bdr_chip .forward( layouter.namespace(|| "bias_div_relu"), &vec![outp_flat, biases], &tmp, ) .unwrap(); // TODO: this is also horrible. The bdr chip outputs interleaved [(relu'd, div'd), (relu'd, div'd), ...] // Uninterleave depending on whether or not we're doing the relu let outp = if conv_config.activation == ActivationType::Relu6 { outp .into_iter() .step_by(2) .map(|x| Rc::new(x)) .collect::<Vec<_>>() } else if conv_config.activation == ActivationType::None { outp .into_iter() .skip(1) .step_by(2) .map(|x| Rc::new(x)) .collect::<Vec<_>>() } else if conv_config.activation == ActivationType::Relu { let dived = outp.iter().skip(1).step_by(2).collect::<Vec<_>>(); let relu_chip = ReluChip::<F>::construct(gadget_config.clone()); let relu_outp = relu_chip .forward(layouter.namespace(|| "relu"), &vec![dived], &tmp) .unwrap(); let relu_outp = relu_outp .into_iter() .map(|x| Rc::new(x)) .collect::<Vec<_>>(); relu_outp } else { panic!("Unsupported activation type"); }; let oc = match conv_config.conv_type { ConvLayerEnum::Conv2D => weights.shape()[0], ConvLayerEnum::DepthwiseConv2D => weights.shape()[3], }; let out_shape = vec![batch_size, oh, ow, oc]; let outp = Array::from_shape_vec(IxDyn(&out_shape), outp).unwrap(); Ok(vec![outp]) } } impl<F: PrimeField> GadgetConsumer for Conv2DChip<F> { fn used_gadgets(&self, layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { let conv_config = &Self::param_vec_to_config(layer_params.clone()); let mut outp = vec![ GadgetType::Adder, GadgetType::DotProduct, GadgetType::InputLookup, GadgetType::BiasDivRoundRelu6, ]; if conv_config.activation == ActivationType::Relu { outp.push(GadgetType::Relu); } outp } }
https://github.com/ddkang/zkml
src/layers/dag.rs
use std::{collections::HashMap, fs::File, io::BufWriter, marker::PhantomData, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use crate::{ gadgets::gadget::{convert_to_u64, GadgetConfig}, layers::{ arithmetic::{add::AddChip, div_var::DivVarChip, mul::MulChip, sub::SubChip}, batch_mat_mul::BatchMatMulChip, div_fixed::DivFixedChip, fully_connected::{FullyConnectedChip, FullyConnectedConfig}, logistic::LogisticChip, max_pool_2d::MaxPool2DChip, mean::MeanChip, noop::NoopChip, pow::PowChip, rsqrt::RsqrtChip, shape::{ broadcast::BroadcastChip, concatenation::ConcatenationChip, mask_neg_inf::MaskNegInfChip, pack::PackChip, pad::PadChip, permute::PermuteChip, reshape::ReshapeChip, resize_nn::ResizeNNChip, rotate::RotateChip, slice::SliceChip, split::SplitChip, transpose::TransposeChip, }, softmax::SoftmaxChip, sqrt::SqrtChip, square::SquareChip, squared_diff::SquaredDiffChip, tanh::TanhChip, update::UpdateChip, }, utils::helpers::print_assigned_arr, }; use super::{ avg_pool_2d::AvgPool2DChip, conv2d::Conv2DChip, layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig, LayerType}, }; #[derive(Clone, Debug, Default)] pub struct DAGLayerConfig { pub ops: Vec<LayerConfig>, pub inp_idxes: Vec<Vec<usize>>, pub out_idxes: Vec<Vec<usize>>, pub final_out_idxes: Vec<usize>, } pub struct DAGLayerChip<F: PrimeField + Ord> { dag_config: DAGLayerConfig, _marker: PhantomData<F>, } impl<F: PrimeField + Ord> DAGLayerChip<F> { pub fn construct(dag_config: DAGLayerConfig) -> Self { Self { dag_config, _marker: PhantomData, } } // IMPORTANT: Assumes input tensors are in order. Output tensors can be in any order. pub fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, _layer_config: &LayerConfig, ) -> Result<(HashMap<usize, AssignedTensor<F>>, Vec<AssignedTensor<F>>), Error> { // Tensor map let mut tensor_map = HashMap::new(); for (idx, tensor) in tensors.iter().enumerate() { tensor_map.insert(idx, tensor.clone()); } // Compute the dag for (layer_idx, layer_config) in self.dag_config.ops.iter().enumerate() { let layer_type = &layer_config.layer_type; let inp_idxes = &self.dag_config.inp_idxes[layer_idx]; let out_idxes = &self.dag_config.out_idxes[layer_idx]; println!( "Processing layer {}, type: {:?}, inp_idxes: {:?}, out_idxes: {:?}, layer_params: {:?}", layer_idx, layer_type, inp_idxes, out_idxes, layer_config.layer_params ); let vec_inps = inp_idxes .iter() .map(|idx| tensor_map.get(idx).unwrap().clone()) .collect::<Vec<_>>(); let out = match layer_type { LayerType::Add => { let add_chip = AddChip {}; add_chip.forward( layouter.namespace(|| "dag add"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::AvgPool2D => { let avg_pool_2d_chip = AvgPool2DChip {}; avg_pool_2d_chip.forward( layouter.namespace(|| "dag avg pool 2d"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::MaxPool2D => { let max_pool_2d_chip = MaxPool2DChip { marker: PhantomData::<F>, }; max_pool_2d_chip.forward( layouter.namespace(|| "dag max pool 2d"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::BatchMatMul => { let batch_mat_mul_chip = BatchMatMulChip {}; batch_mat_mul_chip.forward( layouter.namespace(|| "dag batch mat mul"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Broadcast => { let broadcast_chip = BroadcastChip {}; broadcast_chip.forward( layouter.namespace(|| "dag batch mat mul"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Conv2D => { let conv_2d_chip = Conv2DChip { config: layer_config.clone(), _marker: PhantomData, }; conv_2d_chip.forward( layouter.namespace(|| "dag conv 2d"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::DivFixed => { let div_fixed_chip = DivFixedChip {}; div_fixed_chip.forward( layouter.namespace(|| "dag div"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::DivVar => { let div_var_chip = DivVarChip {}; div_var_chip.forward( layouter.namespace(|| "dag div"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::FullyConnected => { let fc_chip = FullyConnectedChip { _marker: PhantomData, config: FullyConnectedConfig::construct(true), }; fc_chip.forward( layouter.namespace(|| "dag fully connected"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Softmax => { let softmax_chip = SoftmaxChip {}; softmax_chip.forward( layouter.namespace(|| "dag softmax"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Mean => { let mean_chip = MeanChip {}; mean_chip.forward( layouter.namespace(|| "dag mean"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Pad => { let pad_chip = PadChip {}; pad_chip.forward( layouter.namespace(|| "dag pad"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Permute => { let pad_chip = PermuteChip {}; pad_chip.forward( layouter.namespace(|| "dag permute"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::SquaredDifference => { let squared_diff_chip = SquaredDiffChip {}; squared_diff_chip.forward( layouter.namespace(|| "dag squared diff"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Rsqrt => { let rsqrt_chip = RsqrtChip {}; rsqrt_chip.forward( layouter.namespace(|| "dag rsqrt"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Sqrt => { let sqrt_chip = SqrtChip {}; sqrt_chip.forward( layouter.namespace(|| "dag sqrt"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Logistic => { let logistic_chip = LogisticChip {}; logistic_chip.forward( layouter.namespace(|| "dag logistic"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Pow => { let pow_chip = PowChip {}; pow_chip.forward( layouter.namespace(|| "dag logistic"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Tanh => { let tanh_chip = TanhChip {}; tanh_chip.forward( layouter.namespace(|| "dag tanh"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Mul => { let mul_chip = MulChip {}; mul_chip.forward( layouter.namespace(|| "dag mul"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Sub => { let sub_chip = SubChip {}; sub_chip.forward( layouter.namespace(|| "dag sub"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Noop => { let noop_chip = NoopChip {}; noop_chip.forward( layouter.namespace(|| "dag noop"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Transpose => { let transpose_chip = TransposeChip {}; transpose_chip.forward( layouter.namespace(|| "dag transpose"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Reshape => { let reshape_chip = ReshapeChip {}; reshape_chip.forward( layouter.namespace(|| "dag reshape"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::ResizeNN => { let resize_nn_chip = ResizeNNChip {}; resize_nn_chip.forward( layouter.namespace(|| "dag resize nn"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Rotate => { let rotate_chip = RotateChip {}; rotate_chip.forward( layouter.namespace(|| "dag rotate"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Concatenation => { let concat_chip = ConcatenationChip {}; concat_chip.forward( layouter.namespace(|| "dag concatenation"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Pack => { let pack_chip = PackChip {}; pack_chip.forward( layouter.namespace(|| "dag pack"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Split => { let split_chip = SplitChip {}; split_chip.forward( layouter.namespace(|| "dag split"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Update => { let split_chip = UpdateChip {}; split_chip.forward( layouter.namespace(|| "dag update"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Slice => { let slice_chip = SliceChip {}; slice_chip.forward( layouter.namespace(|| "dag slice"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::MaskNegInf => { let mask_neg_inf_chip = MaskNegInfChip {}; mask_neg_inf_chip.forward( layouter.namespace(|| "dag mask neg inf"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } LayerType::Square => { let square_chip = SquareChip {}; square_chip.forward( layouter.namespace(|| "dag square"), &vec_inps, constants, gadget_config.clone(), &layer_config, )? } }; for (idx, tensor_idx) in out_idxes.iter().enumerate() { println!("Out {} shape: {:?}", idx, out[idx].shape()); tensor_map.insert(*tensor_idx, out[idx].clone()); } println!(); } let mut final_out = vec![]; for idx in self.dag_config.final_out_idxes.iter() { final_out.push(tensor_map.get(idx).unwrap().clone()); } let print_arr = if final_out.len() > 0 { &final_out[0] } else { if self.dag_config.ops.len() > 0 { let last_layer_idx = self.dag_config.ops.len() - 1; let out_idx = self.dag_config.out_idxes[last_layer_idx][0]; tensor_map.get(&out_idx).unwrap() } else { tensor_map.get(&0).unwrap() } }; let tmp = print_arr.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); print_assigned_arr("final out", &tmp.to_vec(), gadget_config.scale_factor); println!("final out idxes: {:?}", self.dag_config.final_out_idxes); let mut x = vec![]; for cell in print_arr.iter() { cell.value().map(|v| { let bias = 1 << 60 as i64; let v_pos = *v + F::from(bias as u64); let v = convert_to_u64(&v_pos) as i64 - bias; x.push(v); }); } if x.len() > 0 { let out_fname = "out.msgpack"; let f = File::create(out_fname).unwrap(); let mut buf = BufWriter::new(f); rmp_serde::encode::write_named(&mut buf, &x).unwrap(); } Ok((tensor_map, final_out)) } } impl<F: PrimeField + Ord> GadgetConsumer for DAGLayerChip<F> { // Special case: DAG doesn't do anything fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/div_fixed.rs
use std::{collections::HashMap, rc::Rc, vec}; use halo2_proofs::{ circuit::{AssignedCell, Layouter, Value}, halo2curves::ff::PrimeField, plonk::Error, }; use ndarray::{Array, IxDyn}; use crate::gadgets::{ gadget::{Gadget, GadgetConfig, GadgetType}, var_div::VarDivRoundChip, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; #[derive(Clone, Debug)] pub struct DivFixedChip {} impl DivFixedChip { fn get_div_val<F: PrimeField>( &self, mut layouter: impl Layouter<F>, _tensors: &Vec<AssignedTensor<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<AssignedCell<F, F>, Error> { // FIXME: this needs to be revealed let div = layer_config.layer_params[0]; let div = F::from(div as u64); let div = layouter .assign_region( || "division", |mut region| { let div = region .assign_advice( || "avg pool 2d div", gadget_config.columns[0], 0, || Value::known(div), ) .unwrap(); Ok(div) }, ) .unwrap(); Ok(div) } } impl<F: PrimeField> Layer<F> for DivFixedChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let inp_flat = inp.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let zero = constants.get(&0).unwrap().as_ref(); let shape = inp.shape(); let div = self.get_div_val( layouter.namespace(|| "average div"), tensors, gadget_config.clone(), layer_config, )?; let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone()); let dived = var_div_chip.forward( layouter.namespace(|| "average div"), &vec![inp_flat], &vec![zero, &div], )?; let dived = dived.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>(); let out = Array::from_shape_vec(IxDyn(shape), dived).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for DivFixedChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![GadgetType::VarDivRound] } }
https://github.com/ddkang/zkml
src/layers/fully_connected.rs
use std::{collections::HashMap, marker::PhantomData, rc::Rc}; use halo2_proofs::{ circuit::{AssignedCell, Layouter, Region, Value}, halo2curves::ff::PrimeField, plonk::{Advice, Column, Error}, }; use ndarray::{Array, ArrayView, Axis, IxDyn}; use crate::{ gadgets::{ add_pairs::AddPairsChip, dot_prod::DotProductChip, gadget::{Gadget, GadgetConfig, GadgetType}, nonlinear::relu::ReluChip, var_div::VarDivRoundChip, }, layers::layer::ActivationType, utils::helpers::RAND_START_IDX, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; pub struct FullyConnectedConfig { pub normalize: bool, // Should be true } impl FullyConnectedConfig { pub fn construct(normalize: bool) -> Self { Self { normalize } } } pub struct FullyConnectedChip<F: PrimeField> { pub _marker: PhantomData<F>, pub config: FullyConnectedConfig, } impl<F: PrimeField> FullyConnectedChip<F> { pub fn compute_mm( // input: &AssignedTensor<F>, input: &ArrayView<CellRc<F>, IxDyn>, weight: &AssignedTensor<F>, ) -> Array<Value<F>, IxDyn> { assert_eq!(input.ndim(), 2); assert_eq!(weight.ndim(), 2); assert_eq!(input.shape()[1], weight.shape()[0]); let mut outp = vec![]; for i in 0..input.shape()[0] { for j in 0..weight.shape()[1] { let mut sum = input[[i, 0]].value().map(|x: &F| *x) * weight[[0, j]].value(); for k in 1..input.shape()[1] { sum = sum + input[[i, k]].value().map(|x: &F| *x) * weight[[k, j]].value(); } outp.push(sum); } } let out_shape = [input.shape()[0], weight.shape()[1]]; Array::from_shape_vec(IxDyn(out_shape.as_slice()), outp).unwrap() } pub fn assign_array( columns: &Vec<Column<Advice>>, region: &mut Region<F>, array: &Array<Value<F>, IxDyn>, ) -> Result<Array<AssignedCell<F, F>, IxDyn>, Error> { assert_eq!(array.ndim(), 2); let mut outp = vec![]; for (idx, val) in array.iter().enumerate() { let row_idx = idx / columns.len(); let col_idx = idx % columns.len(); let cell = region .assign_advice(|| "assign array", columns[col_idx], row_idx, || *val) .unwrap(); outp.push(cell); } let out_shape = [array.shape()[0], array.shape()[1]]; Ok(Array::from_shape_vec(IxDyn(out_shape.as_slice()), outp).unwrap()) } pub fn random_vector( constants: &HashMap<i64, CellRc<F>>, size: usize, ) -> Result<Vec<CellRc<F>>, Error> { let mut outp = vec![]; for idx in 0..size { let idx = RAND_START_IDX + (idx as i64); if !constants.contains_key(&idx) { println!("Random vector is too small: {:?}", size); } let cell = constants.get(&idx).unwrap().clone(); outp.push(cell); } Ok(outp) } fn get_activation(&self, layer_params: &Vec<i64>) -> ActivationType { let activation = layer_params[0]; match activation { 0 => ActivationType::None, 1 => ActivationType::Relu, _ => panic!("Unsupported activation type for fully connected"), } } } impl<F: PrimeField> Layer<F> for FullyConnectedChip<F> { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { assert!(tensors.len() <= 3); let activation = self.get_activation(&layer_config.layer_params); let input = &tensors[0]; let ndim = input.ndim(); let input = if ndim == 2 { ArrayView::from(input) } else { input.index_axis(Axis(0), 0) }; let weight = &tensors[1].t().into_owned(); let zero = constants.get(&0).unwrap().as_ref(); // Compute and assign the result let mm_result = layouter .assign_region( || "compute and assign mm", |mut region| { let mm_result = Self::compute_mm(&input, weight); let mm_result = Self::assign_array(&gadget_config.columns, &mut region, &mm_result).unwrap(); Ok(mm_result) }, ) .unwrap(); // Generate random vectors let r1 = Self::random_vector(constants, mm_result.shape()[0]).unwrap(); let r2 = Self::random_vector(constants, mm_result.shape()[1]).unwrap(); let dot_prod_chip = DotProductChip::<F>::construct(gadget_config.clone()); let r1_ref = r1.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let r2_ref = r2.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); // Compute r1 * result let mut r1_res = vec![]; // println!("r1_ref: {:?}", r1_ref.len()); // println!("r2_ref: {:?}", r2_ref.len()); // println!("mm_result: {:?}", mm_result.shape()); for i in 0..mm_result.shape()[1] { let tmp = mm_result.index_axis(Axis(1), i); let mm_ci = tmp.iter().collect::<Vec<_>>(); let r1_res_i = dot_prod_chip .forward( layouter.namespace(|| format!("r1_res_{}", i)), &vec![mm_ci, r1_ref.clone()], &vec![zero], ) .unwrap(); r1_res.push(r1_res_i[0].clone()); } // Compute r1 * result * r2 let r1_res_ref = r1_res.iter().collect::<Vec<_>>(); let r1_res_r2 = dot_prod_chip .forward( layouter.namespace(|| "r1_res_r2"), &vec![r1_res_ref, r2_ref.clone()], &vec![zero], ) .unwrap(); let r1_res_r2 = r1_res_r2[0].clone(); // println!("r1_res_r2: {:?}", r1_res_r2); // Compute r1 * input let mut r1_input = vec![]; // println!("input: {:?}", input.shape()); // println!("r1_ref: {:?}", r1_ref.len()); for i in 0..input.shape()[1] { let tmp = input.index_axis(Axis(1), i); let input_ci = tmp.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let r1_input_i = dot_prod_chip .forward( layouter.namespace(|| format!("r1_input_{}", i)), &vec![input_ci, r1_ref.clone()], &vec![zero], ) .unwrap(); r1_input.push(r1_input_i[0].clone()); } // Compute weight * r2 let mut weight_r2 = vec![]; for i in 0..weight.shape()[0] { let tmp = weight.index_axis(Axis(0), i); let weight_ci = tmp.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let weight_r2_i = dot_prod_chip .forward( layouter.namespace(|| format!("weight_r2_{}", i)), &vec![weight_ci, r2_ref.clone()], &vec![zero], ) .unwrap(); weight_r2.push(weight_r2_i[0].clone()); } // Compute (r1 * input) * (weight * r2) let r1_input_ref = r1_input.iter().collect::<Vec<_>>(); let weight_r2_ref = weight_r2.iter().collect::<Vec<_>>(); let r1_inp_weight_r2 = dot_prod_chip .forward( layouter.namespace(|| "r1_inp_weight_r2"), &vec![r1_input_ref, weight_r2_ref], &vec![zero], ) .unwrap(); let r1_inp_weight_r2 = r1_inp_weight_r2[0].clone(); // println!("r1_inp_weight_r2: {:?}", r1_inp_weight_r2); layouter .assign_region( || "fc equality check", |mut region| { let t1 = r1_res_r2 .copy_advice(|| "", &mut region, gadget_config.columns[0], 0) .unwrap(); let t2 = r1_inp_weight_r2 .copy_advice(|| "", &mut region, gadget_config.columns[0], 1) .unwrap(); region.constrain_equal(t1.cell(), t2.cell()).unwrap(); Ok(()) }, ) .unwrap(); let shape = [mm_result.shape()[0], mm_result.shape()[1]]; let final_result_flat = if self.config.normalize { let mm_flat = mm_result.iter().collect::<Vec<_>>(); let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone()); let sf = constants .get(&(gadget_config.scale_factor as i64)) .unwrap() .as_ref(); let mm_div = var_div_chip .forward( layouter.namespace(|| "mm_div"), &vec![mm_flat], &vec![zero, sf], ) .unwrap(); let mm_div = if tensors.len() == 3 { let bias = tensors[2].broadcast(shape.clone()).unwrap(); let bias = bias.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let mm_div = mm_div.iter().collect::<Vec<_>>(); let adder_chip = AddPairsChip::<F>::construct(gadget_config.clone()); let mm_bias = adder_chip .forward( layouter.namespace(|| "mm_bias"), &vec![mm_div, bias], &vec![zero], ) .unwrap(); mm_bias } else { mm_div }; let mm_div = if activation == ActivationType::Relu { let relu_chip = ReluChip::<F>::construct(gadget_config.clone()); let mm_div = mm_div.iter().collect::<Vec<_>>(); let vec_inputs = vec![mm_div]; relu_chip .forward(layouter.namespace(|| "relu"), &vec_inputs, &vec![zero]) .unwrap() } else if activation == ActivationType::None { mm_div } else { panic!("Unsupported activation type"); }; mm_div.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>() } else { mm_result .into_iter() .map(|x| Rc::new(x)) .collect::<Vec<_>>() }; let final_result = Array::from_shape_vec(IxDyn(&shape), final_result_flat).unwrap(); Ok(vec![final_result]) } } impl<F: PrimeField> GadgetConsumer for FullyConnectedChip<F> { fn used_gadgets(&self, layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { let activation = self.get_activation(&layer_params); let mut outp = vec![ GadgetType::Adder, GadgetType::AddPairs, GadgetType::DotProduct, GadgetType::VarDivRound, GadgetType::InputLookup, ]; match activation { ActivationType::Relu => outp.push(GadgetType::Relu), ActivationType::None => (), _ => panic!("Unsupported activation type"), } outp } }
https://github.com/ddkang/zkml
src/layers/layer.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{ circuit::{AssignedCell, Layouter}, halo2curves::ff::PrimeField, plonk::Error, }; use ndarray::{Array, IxDyn}; use crate::gadgets::gadget::{GadgetConfig, GadgetType}; #[derive(Clone, Copy, Debug, Default, Hash, Eq, PartialEq)] pub enum LayerType { Add, AvgPool2D, BatchMatMul, Broadcast, Concatenation, Conv2D, DivVar, DivFixed, FullyConnected, Logistic, MaskNegInf, MaxPool2D, Mean, Mul, #[default] Noop, Pack, Pad, Pow, Permute, Reshape, ResizeNN, Rotate, Rsqrt, Slice, Softmax, Split, Sqrt, Square, SquaredDifference, Sub, Tanh, Transpose, Update, } // NOTE: This is the same order as the TFLite schema // Must not be changed #[derive(Clone, Debug, Default, Hash, Eq, PartialEq)] pub enum ActivationType { #[default] None, Relu, ReluN1To1, Relu6, Tanh, SignBit, } #[derive(Clone, Debug, Default)] pub struct LayerConfig { pub layer_type: LayerType, pub layer_params: Vec<i64>, // This is turned into layer specific configurations at runtime pub inp_shapes: Vec<Vec<usize>>, pub out_shapes: Vec<Vec<usize>>, pub mask: Vec<i64>, } pub type CellRc<F> = Rc<AssignedCell<F, F>>; pub type AssignedTensor<F> = Array<CellRc<F>, IxDyn>; // General issue with rust: I'm not sure how to pass named arguments to a trait... // Currently, the caller must be aware of the order of the tensors and results pub trait Layer<F: PrimeField> { fn forward( &self, layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error>; } pub trait GadgetConsumer { fn used_gadgets(&self, layer_params: Vec<i64>) -> Vec<GadgetType>; }
https://github.com/ddkang/zkml
src/layers/logistic.rs
use std::{collections::HashMap, rc::Rc, vec}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::gadgets::{ gadget::{Gadget, GadgetConfig, GadgetType}, nonlinear::logistic::LogisticGadgetChip, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; #[derive(Clone, Debug)] pub struct LogisticChip {} impl<F: PrimeField> Layer<F> for LogisticChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, _layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let inp_vec = inp.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let zero = constants.get(&0).unwrap().as_ref(); let logistic_chip = LogisticGadgetChip::<F>::construct(gadget_config.clone()); let vec_inps = vec![inp_vec]; let constants = vec![zero]; let out = logistic_chip.forward( layouter.namespace(|| "logistic chip"), &vec_inps, &constants, )?; let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>(); let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for LogisticChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![GadgetType::Logistic, GadgetType::InputLookup] } }
https://github.com/ddkang/zkml
src/layers/max_pool_2d.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::{ gadgets::{ gadget::{Gadget, GadgetConfig, GadgetType}, max::MaxChip, }, layers::conv2d::{Conv2DChip, PaddingEnum}, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; pub struct MaxPool2DChip<F: PrimeField> { pub marker: std::marker::PhantomData<F>, } impl<F: PrimeField> MaxPool2DChip<F> { pub fn shape(inp: &AssignedTensor<F>, layer_config: &LayerConfig) -> (usize, usize) { let params = &layer_config.layer_params; let (fx, fy) = (params[0], params[1]); let (fx, fy) = (fx as usize, fy as usize); let (sx, sy) = (params[2], params[3]); let (sx, sy) = (sx as usize, sy as usize); // Only support batch size 1 for now assert_eq!(inp.shape()[0], 1); let out_shape = Conv2DChip::<F>::out_hw( inp.shape()[1], inp.shape()[2], sx, sy, fx, fy, PaddingEnum::Valid, ); out_shape } pub fn splat( inp: &AssignedTensor<F>, layer_config: &LayerConfig, ) -> Result<Vec<Vec<CellRc<F>>>, Error> { let params = &layer_config.layer_params; let (fx, fy) = (params[0], params[1]); let (fx, fy) = (fx as usize, fy as usize); let (sx, sy) = (params[2], params[3]); let (sx, sy) = (sx as usize, sy as usize); // Only support batch size 1 for now assert_eq!(inp.shape()[0], 1); let out_shape = Self::shape(inp, layer_config); let mut splat = vec![]; for i in 0..out_shape.0 { for j in 0..out_shape.1 { for k in 0..inp.shape()[3] { let mut tmp = vec![]; for x in 0..fx { for y in 0..fy { let x = i * sx + x; let y = j * sy + y; if x < inp.shape()[1] && y < inp.shape()[2] { tmp.push(inp[[0, x, y, k]].clone()); } } } splat.push(tmp); } } } Ok(splat) } } impl<F: PrimeField> Layer<F> for MaxPool2DChip<F> { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let splat = Self::splat(inp, layer_config).unwrap(); let max_chip = MaxChip::<F>::construct(gadget_config.clone()); let mut out = vec![]; for i in 0..splat.len() { let inps = &splat[i]; let inps = inps.iter().map(|x| x.as_ref()).collect(); let max = max_chip .forward( layouter.namespace(|| format!("max {}", i)), &vec![inps], &vec![], ) .unwrap(); out.push(max[0].clone()); } let out = out.into_iter().map(|x| Rc::new(x)).collect(); // TODO: refactor this let out_xy = Self::shape(inp, layer_config); let out_shape = vec![1, out_xy.0, out_xy.1, inp.shape()[3]]; let out = Array::from_shape_vec(IxDyn(&out_shape), out).unwrap(); Ok(vec![out]) } } impl<F: PrimeField> GadgetConsumer for MaxPool2DChip<F> { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<GadgetType> { vec![GadgetType::Max, GadgetType::InputLookup] } }
https://github.com/ddkang/zkml
src/layers/mean.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{ circuit::{AssignedCell, Layouter, Value}, halo2curves::ff::PrimeField, plonk::Error, }; use ndarray::{Array, Axis, IxDyn}; use crate::gadgets::gadget::{GadgetConfig, GadgetType}; use super::{ averager::Averager, layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}, }; pub struct MeanChip {} impl MeanChip { pub fn get_keep_axis(&self, layer_config: &LayerConfig) -> usize { let inp_shape = &layer_config.inp_shapes[0]; let out_shape = &layer_config.out_shapes[0]; assert_eq!(inp_shape[0], 1); assert_eq!(out_shape[0], 1); // Skip the batch axis let mut keep_axes = (1..inp_shape.len()).collect::<Vec<_>>(); for mean_axis in layer_config.layer_params.iter() { keep_axes.retain(|&x| x != *mean_axis as usize); } assert_eq!(keep_axes.len(), 1); keep_axes[0] /* let mut num_same = 0; let mut keep_axis: i64 = -1; for i in 1..inp_shape.len() { if inp_shape[i] == out_shape[i] { keep_axis = i as i64; num_same += 1; } } if keep_axis == -1 { panic!("All axes are different"); } if num_same > 1 { panic!("More than one axis is the same"); } keep_axis as usize */ } } impl<F: PrimeField> Averager<F> for MeanChip { fn splat(&self, input: &AssignedTensor<F>, layer_config: &LayerConfig) -> Vec<Vec<CellRc<F>>> { // Only support batch size = 1 assert_eq!(input.shape()[0], 1); // Only support batch + 2D, summing over one axis // assert_eq!(input.shape().len(), 3); let keep_axis = self.get_keep_axis(layer_config); let mut splat = vec![]; for i in 0..input.shape()[keep_axis] { let mut tmp = vec![]; for x in input.index_axis(Axis(keep_axis), i).iter() { tmp.push(x.clone()); } splat.push(tmp); } splat } fn get_div_val( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<AssignedCell<F, F>, Error> { let inp = &tensors[0]; let keep_axis = self.get_keep_axis(layer_config); let mut div = 1; for i in 0..inp.shape().len() { if i != keep_axis { div *= inp.shape()[i]; } } let div = F::from(div as u64); // FIXME: put this in the fixed column let div = layouter.assign_region( || "mean div", |mut region| { let div = region.assign_advice( || "mean div", gadget_config.columns[0], 0, || Value::known(div), )?; Ok(div) }, )?; Ok(div) } } impl<F: PrimeField> Layer<F> for MeanChip { fn forward( &self, layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let dived = self.avg_forward(layouter, tensors, constants, gadget_config, layer_config)?; let out_shape = layer_config.out_shapes[0] .iter() .map(|x| *x as usize) .collect::<Vec<_>>(); let out = Array::from_shape_vec(IxDyn(&out_shape), dived).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for MeanChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![ GadgetType::Adder, GadgetType::VarDivRound, GadgetType::InputLookup, ] } }
https://github.com/ddkang/zkml
src/layers/noop.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use crate::gadgets::gadget::GadgetConfig; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; pub struct NoopChip {} impl<F: PrimeField> Layer<F> for NoopChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let ret_idx = layer_config.layer_params[0] as usize; Ok(vec![tensors[ret_idx].clone()]) } } impl GadgetConsumer for NoopChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/pow.rs
use std::{collections::HashMap, rc::Rc, vec}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::gadgets::{ gadget::{Gadget, GadgetConfig, GadgetType}, nonlinear::pow::PowGadgetChip, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; #[derive(Clone, Debug)] pub struct PowChip {} impl<F: PrimeField> Layer<F> for PowChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, _layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let inp_vec = inp.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let zero = constants.get(&0).unwrap().as_ref(); let pow_chip = PowGadgetChip::<F>::construct(gadget_config.clone()); let vec_inps = vec![inp_vec]; let constants = vec![zero]; let out = pow_chip.forward(layouter.namespace(|| "pow chip"), &vec_inps, &constants)?; let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>(); let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for PowChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![GadgetType::Pow, GadgetType::InputLookup] } }
https://github.com/ddkang/zkml
src/layers/rsqrt.rs
use std::{collections::HashMap, rc::Rc, vec}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::gadgets::{ gadget::{Gadget, GadgetConfig, GadgetType}, nonlinear::rsqrt::RsqrtGadgetChip, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; #[derive(Clone, Debug)] pub struct RsqrtChip {} impl<F: PrimeField> Layer<F> for RsqrtChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let mut inp_vec = vec![]; let mask = &layer_config.mask; let mut mask_map = HashMap::new(); for i in 0..mask.len() / 2 { mask_map.insert(mask[2 * i], mask[2 * i + 1]); } let min_val = gadget_config.min_val; let min_val = constants.get(&min_val).unwrap().as_ref(); let max_val = gadget_config.max_val; let max_val = constants.get(&max_val).unwrap().as_ref(); for (i, val) in inp.iter().enumerate() { let i = i as i64; if mask_map.contains_key(&i) { let mask_val = *mask_map.get(&i).unwrap(); if mask_val == 1 { inp_vec.push(max_val); } else if mask_val == -1 { inp_vec.push(min_val); } else { panic!(); } } else { inp_vec.push(val.as_ref()); } } let zero = constants.get(&0).unwrap().as_ref(); let rsqrt_chip = RsqrtGadgetChip::<F>::construct(gadget_config.clone()); let vec_inps = vec![inp_vec]; let constants = vec![zero, min_val, max_val]; let out = rsqrt_chip.forward(layouter.namespace(|| "rsqrt chip"), &vec_inps, &constants)?; let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>(); let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for RsqrtChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![GadgetType::Rsqrt, GadgetType::InputLookup] } }
https://github.com/ddkang/zkml
src/layers/shape.rs
pub mod broadcast; pub mod concatenation; pub mod mask_neg_inf; pub mod pack; pub mod pad; pub mod permute; pub mod reshape; pub mod resize_nn; pub mod rotate; pub mod slice; pub mod split; pub mod transpose;
https://github.com/ddkang/zkml
src/layers/shape/broadcast.rs
// // Broadcast is used as a temporary measure to represent a the backprop // of a full-kernel AvgPool2D // use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::Array; use crate::{ gadgets::gadget::GadgetConfig, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct BroadcastChip {} // TODO: Fix this after demo impl<F: PrimeField> Layer<F> for BroadcastChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let shape = inp.shape(); let output_shape = layer_config.out_shapes[0].clone(); // Check that we only broadcast dimensions with shape 1 assert!(shape.len() == output_shape.len()); assert!(shape.len() == 4); for (inp, outp) in shape.iter().zip(output_shape.iter()) { if *inp != *outp && !(*inp == 1) { panic!(); } } let mut output_flat = vec![]; for i in 0..output_shape[0] { for j in 0..output_shape[1] { for k in 0..output_shape[2] { for l in 0..output_shape[3] { let indexes = [i, j, k, l] .iter() .enumerate() .map(|(idx, x)| if shape[idx] == 1 { 0 } else { *x }) .collect::<Vec<_>>(); output_flat.push(inp[[indexes[0], indexes[1], indexes[2], indexes[3]]].clone()); } } } } println!("Broadcast : {:?} -> {:?}", inp.shape(), output_shape); let out = Array::from_shape_vec(output_shape, output_flat).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for BroadcastChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/concatenation.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{concatenate, Axis}; use crate::{ gadgets::gadget::{GadgetConfig, GadgetType}, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct ConcatenationChip {} impl<F: PrimeField> Layer<F> for ConcatenationChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let axis = layer_config.layer_params[0] as usize; let views = tensors.iter().map(|x| x.view()).collect::<Vec<_>>(); // TODO: this is a bit of a hack let out = concatenate(Axis(axis), views.as_slice()).unwrap_or(tensors[0].clone()); Ok(vec![out]) } } impl GadgetConsumer for ConcatenationChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/mask_neg_inf.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::{ gadgets::gadget::GadgetConfig, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct MaskNegInfChip {} impl<F: PrimeField> Layer<F> for MaskNegInfChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let mask_ndim = layer_config.layer_params[0] as usize; let mask_shape = layer_config.layer_params[1..mask_ndim + 1] .iter() .map(|x| *x as usize) .collect::<Vec<_>>(); let mask_vec = layer_config.layer_params[mask_ndim + 1..].to_vec(); let mask = Array::from_shape_vec(IxDyn(&mask_shape), mask_vec).unwrap(); let mask = mask.broadcast(inp.raw_dim()).unwrap(); let min_val = gadget_config.min_val; let min_val = constants.get(&min_val).unwrap().clone(); let mut out_vec = vec![]; for (val, to_mask) in inp.iter().zip(mask.iter()) { if *to_mask == 0 { out_vec.push(val.clone()); } else { out_vec.push(min_val.clone()); } } let outp = Array::from_shape_vec(inp.raw_dim(), out_vec).unwrap(); Ok(vec![outp]) } } impl GadgetConsumer for MaskNegInfChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/pack.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{concatenate, Axis}; use crate::{ gadgets::gadget::{GadgetConfig, GadgetType}, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct PackChip {} impl<F: PrimeField> Layer<F> for PackChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let axis = layer_config.layer_params[0] as usize; if axis > 1 { panic!("Pack only supports axis=0 or axis=1"); } let expanded = tensors .into_iter() .map(|x| x.clone().insert_axis(Axis(axis))) .collect::<Vec<_>>(); let views = expanded.iter().map(|x| x.view()).collect::<Vec<_>>(); // TODO: in some cases, the pack is unnecessary. Simply return the first tensor in this case let out = concatenate(Axis(axis), views.as_slice()).unwrap_or(tensors[0].clone()); Ok(vec![out]) } } impl GadgetConsumer for PackChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/pad.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{ circuit::{AssignedCell, Layouter}, halo2curves::ff::PrimeField, plonk::Error, }; use ndarray::{Array, Axis, IxDyn, Slice}; use crate::{ gadgets::gadget::GadgetConfig, layers::layer::{AssignedTensor, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; // TODO: figure out where to put this pub fn pad<G: Clone>( input: &Array<Rc<G>, IxDyn>, padding: Vec<[usize; 2]>, pad_val: &Rc<G>, ) -> Array<Rc<G>, IxDyn> { let tmp = input.iter().collect(); let input = Array::from_shape_vec(input.raw_dim(), tmp).unwrap(); assert_eq!(input.ndim(), padding.len()); let mut padded_shape = input.raw_dim(); for (ax, (&ax_len, &[pad_lo, pad_hi])) in input.shape().iter().zip(&padding).enumerate() { padded_shape[ax] = ax_len + pad_lo + pad_hi; } let mut padded = Array::from_elem(padded_shape, pad_val); let padded_dim = padded.raw_dim(); { // Select portion of padded array that needs to be copied from the // original array. let mut orig_portion = padded.view_mut(); for (ax, &[pad_lo, pad_hi]) in padding.iter().enumerate() { orig_portion.slice_axis_inplace( Axis(ax), Slice::from(pad_lo as isize..padded_dim[ax] as isize - (pad_hi as isize)), ); } // Copy the data from the original array. orig_portion.assign(&input.view()); } let dim = padded.raw_dim(); let tmp = padded.into_iter().map(|x| x.clone()).collect(); let padded = Array::from_shape_vec(dim, tmp).unwrap(); padded } pub struct PadChip {} pub struct PadConfig { pub padding: Vec<[usize; 2]>, } impl PadChip { pub fn param_vec_to_config(layer_params: Vec<i64>) -> PadConfig { assert!(layer_params.len() % 2 == 0); let padding = layer_params .chunks(2) .map(|chunk| [chunk[0] as usize, chunk[1] as usize]) .collect(); PadConfig { padding } } } impl<F: PrimeField> Layer<F> for PadChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, Rc<AssignedCell<F, F>>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { // FIXME: the pad from tflite is actually two, but mine is one // assert_eq!(tensors.len(), 1); let input = &tensors[0]; let zero = constants.get(&0).unwrap().clone(); let padding = PadChip::param_vec_to_config(layer_config.layer_params.clone()); let padded = pad(input, padding.padding, &zero); Ok(vec![padded]) } } impl GadgetConsumer for PadChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/permute.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::IxDyn; use crate::{ gadgets::gadget::GadgetConfig, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct PermuteChip {} impl<F: PrimeField> Layer<F> for PermuteChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let params = &layer_config .layer_params .iter() .map(|x| *x as usize) .collect::<Vec<_>>()[..]; assert!(inp.ndim() == params.len()); let out = inp.clone(); let out = out.permuted_axes(IxDyn(params)); Ok(vec![out]) } } impl GadgetConsumer for PermuteChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/reshape.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::Array; use crate::{ gadgets::gadget::GadgetConfig, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct ReshapeChip {} impl<F: PrimeField> Layer<F> for ReshapeChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let shape = layer_config.out_shapes[0].clone(); println!("Reshape: {:?} -> {:?}", inp.shape(), shape); let flat = inp.iter().map(|x| x.clone()).collect(); let out = Array::from_shape_vec(shape, flat).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for ReshapeChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/resize_nn.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::{ gadgets::gadget::GadgetConfig, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct ResizeNNChip {} // TODO: this does not work in general impl<F: PrimeField> Layer<F> for ResizeNNChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let output_shape = layer_config.out_shapes[0].clone(); assert_eq!(inp.ndim(), 4); assert_eq!(inp.shape()[0], 1); assert_eq!(inp.shape()[3], output_shape[3]); let mut flat = vec![]; // Do nearest neighbor interpolation over batch, h, w, c // The interpolation is over h and w for b in 0..inp.shape()[0] { for h in 0..output_shape[1] { let h_in = (h as f64 * (inp.shape()[1] as f64 / output_shape[1] as f64)) as usize; for w in 0..output_shape[2] { let w_in = (w as f64 * (inp.shape()[2] as f64 / output_shape[2] as f64)) as usize; for c in 0..inp.shape()[3] { flat.push(inp[[b, h_in, w_in, c]].clone()); } } } } let outp = Array::from_shape_vec(IxDyn(&output_shape), flat).unwrap(); Ok(vec![outp]) } } impl GadgetConsumer for ResizeNNChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/rotate.rs
// TODO: The implementation is not ideal. use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use crate::{ gadgets::gadget::GadgetConfig, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct RotateChip {} // Example: // input: // [1 2 3 4] // [5 6 7 8] // // params: [1] -- flip axis 1 only // output: // [4 3 2 1] // [8 7 6 5] impl<F: PrimeField> Layer<F> for RotateChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let params = &layer_config.layer_params; assert!(inp.shape().len() == 4); let mut flip = vec![false; 4]; for p in params { flip[*p as usize] = true; } let shape = inp.shape(); println!("Rotate: {:?} -> {:?}", inp.shape(), shape); let mut out = inp.clone(); for i in 0..shape[0] { for j in 0..shape[1] { for k in 0..shape[2] { for l in 0..shape[3] { let [ix, jx, kx, lx]: [usize; 4] = [i, j, k, l] .iter() .enumerate() .map(|(idx, x)| if flip[idx] { shape[idx] - 1 - *x } else { *x }) .collect::<Vec<_>>() .try_into() .unwrap(); out[[ix, jx, kx, lx]] = inp[[i, j, k, l]].clone(); } } } } Ok(vec![out]) } } impl GadgetConsumer for RotateChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/slice.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::Slice; use crate::{ gadgets::gadget::{GadgetConfig, GadgetType}, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct SliceChip {} impl<F: PrimeField> Layer<F> for SliceChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let params = &layer_config.layer_params; assert_eq!(params.len() % 2, 0); let num_axes = params.len() / 2; let starts = &params[0..num_axes]; let sizes = &params[num_axes..]; let inp = &tensors[0]; let outp = inp.slice_each_axis(|ax| { let start = starts[ax.axis.0] as usize; let size = sizes[ax.axis.0]; if size == -1 { Slice::from(start..) } else { Slice::from(start..(start + size as usize)) } }); Ok(vec![outp.to_owned()]) } } impl GadgetConsumer for SliceChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/split.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Axis, Slice}; use crate::{ gadgets::gadget::{GadgetConfig, GadgetType}, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct SplitChip {} impl<F: PrimeField> Layer<F> for SplitChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let axis = layer_config.layer_params[0] as usize; let num_splits = layer_config.layer_params[1] as usize; let inp = &tensors[1]; let mut out = vec![]; let split_len = inp.shape()[axis] / num_splits; for i in 0..num_splits { let slice = inp .slice_axis( Axis(axis), Slice::from((i * split_len)..((i + 1) * split_len)), ) .to_owned(); out.push(slice.to_owned()); } Ok(out) } } impl GadgetConsumer for SplitChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/shape/transpose.rs
use std::{collections::HashMap, rc::Rc}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::{ gadgets::gadget::GadgetConfig, layers::layer::{AssignedTensor, CellRc, GadgetConsumer}, }; use super::super::layer::{Layer, LayerConfig}; pub struct TransposeChip {} impl<F: PrimeField> Layer<F> for TransposeChip { fn forward( &self, _layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, _constants: &HashMap<i64, CellRc<F>>, _gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { assert_eq!(layer_config.layer_params.len() % 2, 0); let ndim = layer_config.layer_params.len() / 2; let inp_shape = layer_config.layer_params[0..ndim] .to_vec() .iter() .map(|x| *x as usize) .collect::<Vec<_>>(); let permutation = layer_config.layer_params[ndim..] .to_vec() .iter() .map(|x| *x as usize) .collect::<Vec<_>>(); let inp = &tensors[0]; // Required because of memory layout issues let inp_flat = inp.iter().cloned().collect::<Vec<_>>(); let inp = Array::from_shape_vec(IxDyn(&inp_shape), inp_flat).unwrap(); let inp = inp.permuted_axes(IxDyn(&permutation)); Ok(vec![inp]) } } impl GadgetConsumer for TransposeChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![] } }
https://github.com/ddkang/zkml
src/layers/softmax.rs
use std::{collections::HashMap, rc::Rc, vec}; use halo2_proofs::{ circuit::{AssignedCell, Layouter}, halo2curves::ff::PrimeField, plonk::Error, }; use ndarray::{s, Array, IxDyn}; use crate::gadgets::{ adder::AdderChip, gadget::{Gadget, GadgetConfig, GadgetType}, max::MaxChip, nonlinear::exp::ExpGadgetChip, sub_pairs::SubPairsChip, var_div_big3::VarDivRoundBig3Chip, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; #[derive(Clone, Debug)] pub struct SoftmaxChip {} impl SoftmaxChip { pub fn softmax_flat<F: PrimeField>( mut layouter: impl Layouter<F>, constants: &HashMap<i64, CellRc<F>>, inp_flat: Vec<&AssignedCell<F, F>>, gadget_config: Rc<GadgetConfig>, mask: &Vec<i64>, ) -> Result<Vec<AssignedCell<F, F>>, Error> { let exp_chip = ExpGadgetChip::<F>::construct(gadget_config.clone()); let adder_chip = AdderChip::<F>::construct(gadget_config.clone()); let sub_pairs_chip = SubPairsChip::<F>::construct(gadget_config.clone()); let max_chip = MaxChip::<F>::construct(gadget_config.clone()); let var_div_big_chip = VarDivRoundBig3Chip::<F>::construct(gadget_config.clone()); let zero = constants.get(&0).unwrap().as_ref(); let sf = constants .get(&(gadget_config.scale_factor as i64)) .unwrap() .as_ref(); // Mask the input for max computation and subtraction let inp_take = inp_flat .iter() .enumerate() .filter(|(i, _)| mask[*i] == 0) // Awkwardly, 1 = take negative infinity .map(|(_, x)| *x) .collect::<Vec<_>>(); // Compute the max let max = max_chip .forward( layouter.namespace(|| format!("max")), &vec![inp_take.clone()], &vec![zero], ) .unwrap(); let max = &max[0]; // Subtract the max let max_flat = vec![max; inp_take.len()]; let sub = sub_pairs_chip.forward( layouter.namespace(|| format!("sub")), &vec![inp_take, max_flat], &vec![zero], )?; let sub = sub.iter().collect::<Vec<_>>(); // Compute the exp let exp_slice = exp_chip.forward( layouter.namespace(|| format!("exp")), &vec![sub], &vec![zero], )?; // Compute the sum let sum = adder_chip.forward( layouter.namespace(|| format!("sum")), &vec![exp_slice.iter().collect()], &vec![zero], )?; let sum = sum[0].clone(); let sum_div_sf = var_div_big_chip.forward( layouter.namespace(|| format!("sum div sf")), &vec![vec![&sum]], &vec![zero, sf], )?; let sum_div_sf = sum_div_sf[0].clone(); let dived = var_div_big_chip.forward( layouter.namespace(|| format!("div")), &vec![exp_slice.iter().collect()], &vec![zero, &sum_div_sf], )?; // Take either zero (softmax(-inf)) or the result let mut div_idx = 0; let dived = mask .iter() .map(|x| { if *x == 1 { zero.clone() } else { let tmp = dived[div_idx].clone(); div_idx = div_idx + 1; tmp } }) .collect(); Ok(dived) } } impl<F: PrimeField> Layer<F> for SoftmaxChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; assert!(inp.ndim() == 2 || inp.ndim() == 3 || inp.ndim() == 4); if inp.ndim() == 4 { assert_eq!(inp.shape()[0], 1); } let inp_shape = inp.shape().iter().map(|x| *x).collect::<Vec<_>>(); let mask = if layer_config.layer_params.len() == 0 { Array::from_shape_fn(IxDyn(&inp_shape), |_| 0) } else { let mask_shape_len = layer_config.layer_params[0] as usize; let mask_shape = layer_config.layer_params[1..(1 + mask_shape_len)] .iter() .map(|x| *x as usize) .collect::<Vec<_>>(); let mask = layer_config.layer_params[(1 + mask_shape_len)..].to_vec(); let mask = Array::from_shape_vec(IxDyn(&mask_shape), mask).unwrap(); let mask = mask.broadcast(IxDyn(&inp_shape)).unwrap().to_owned(); mask }; let shape = if inp.ndim() == 2 || inp.ndim() == 3 { inp.shape().iter().map(|x| *x).collect::<Vec<_>>() } else { vec![inp.shape()[1], inp.shape()[2], inp.shape()[3]] }; let inp = inp.to_owned().into_shape(shape.clone()).unwrap(); let mask = mask.into_shape(shape.clone()).unwrap(); let mut outp = vec![]; if inp.ndim() == 2 { for i in 0..shape[0] { let inp_slice = inp.slice(s![i, ..]); let inp_flat = inp_slice.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let mask_slice = mask.slice(s![i, ..]); let mask_flat = mask_slice.iter().map(|x| *x as i64).collect::<Vec<_>>(); let dived = Self::softmax_flat( layouter.namespace(|| format!("softmax {}", i)), constants, inp_flat, gadget_config.clone(), &mask_flat, ) .unwrap(); outp.extend(dived); } } else if inp.ndim() == 3 { for i in 0..shape[0] { for j in 0..shape[1] { let inp_slice = inp.slice(s![i, j, ..]); let inp_flat = inp_slice.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let mask_slice = mask.slice(s![i, j, ..]); let mask_flat = mask_slice.iter().map(|x| *x as i64).collect::<Vec<_>>(); let dived = Self::softmax_flat( layouter.namespace(|| format!("softmax {} {}", i, j)), constants, inp_flat, gadget_config.clone(), &mask_flat, ) .unwrap(); outp.extend(dived); } } } else { panic!("Not implemented"); } let outp = outp.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>(); let outp = Array::from_shape_vec(IxDyn(inp.shape()), outp).unwrap(); Ok(vec![outp]) } } impl GadgetConsumer for SoftmaxChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![ GadgetType::Exp, GadgetType::Adder, GadgetType::VarDivRoundBig3, GadgetType::Max, GadgetType::SubPairs, GadgetType::InputLookup, ] } }
https://github.com/ddkang/zkml
src/layers/sqrt.rs
use std::{collections::HashMap, rc::Rc, vec}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::gadgets::{ gadget::{Gadget, GadgetConfig, GadgetType}, nonlinear::sqrt::SqrtGadgetChip, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; #[derive(Clone, Debug)] pub struct SqrtChip {} impl<F: PrimeField> Layer<F> for SqrtChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let mut inp_vec = vec![]; let mask = &layer_config.mask; let mut mask_map = HashMap::new(); for i in 0..mask.len() / 2 { mask_map.insert(mask[2 * i], mask[2 * i + 1]); } let min_val = gadget_config.min_val; let min_val = constants.get(&min_val).unwrap().as_ref(); let max_val = gadget_config.max_val; let max_val = constants.get(&max_val).unwrap().as_ref(); for (i, val) in inp.iter().enumerate() { let i = i as i64; if mask_map.contains_key(&i) { let mask_val = *mask_map.get(&i).unwrap(); if mask_val == 1 { inp_vec.push(max_val); } else if mask_val == -1 { inp_vec.push(min_val); } else { panic!(); } } else { inp_vec.push(val.as_ref()); } } let zero = constants.get(&0).unwrap().as_ref(); let sqrt_chip = SqrtGadgetChip::<F>::construct(gadget_config.clone()); let vec_inps = vec![inp_vec]; let constants = vec![zero, min_val, max_val]; let out = sqrt_chip.forward(layouter.namespace(|| "sqrt chip"), &vec_inps, &constants)?; let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>(); let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for SqrtChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![GadgetType::Sqrt, GadgetType::InputLookup] } }
https://github.com/ddkang/zkml
src/layers/square.rs
use std::{collections::HashMap, rc::Rc, vec}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::gadgets::{ gadget::{Gadget, GadgetConfig, GadgetType}, square::SquareGadgetChip, var_div::VarDivRoundChip, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; #[derive(Clone, Debug)] pub struct SquareChip {} impl<F: PrimeField> Layer<F> for SquareChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, _layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { assert_eq!(tensors.len(), 1); let inp = &tensors[0]; let zero = constants.get(&0).unwrap().as_ref(); let square_chip = SquareGadgetChip::<F>::construct(gadget_config.clone()); let inp_vec = inp.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let vec_inputs = vec![inp_vec]; let single_inps = vec![zero]; let out = square_chip.forward( layouter.namespace(|| "square chip"), &vec_inputs, &single_inps, )?; let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone()); let div = constants .get(&(gadget_config.scale_factor as i64)) .unwrap() .as_ref(); let single_inps = vec![zero, div]; let out = out.iter().collect::<Vec<_>>(); let vec_inputs = vec![out]; let out = var_div_chip.forward( layouter.namespace(|| "var div chip"), &vec_inputs, &single_inps, )?; let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>(); let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for SquareChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![ GadgetType::Square, GadgetType::VarDivRound, GadgetType::InputLookup, ] } }
https://github.com/ddkang/zkml
src/layers/squared_diff.rs
use std::{collections::HashMap, rc::Rc, vec}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::{ gadgets::{ gadget::{Gadget, GadgetConfig, GadgetType}, squared_diff::SquaredDiffGadgetChip, var_div::VarDivRoundChip, }, utils::helpers::broadcast, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; #[derive(Clone, Debug)] pub struct SquaredDiffChip {} impl<F: PrimeField> Layer<F> for SquaredDiffChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, _layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { assert_eq!(tensors.len(), 2); let inp1 = &tensors[0]; let inp2 = &tensors[1]; // Broadcoasting allowed... can't check shapes easily let (inp1, inp2) = broadcast(inp1, inp2); let zero = constants.get(&0).unwrap().as_ref(); let sq_diff_chip = SquaredDiffGadgetChip::<F>::construct(gadget_config.clone()); let inp1_vec = inp1.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let inp2_vec = inp2.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let vec_inputs = vec![inp1_vec, inp2_vec]; let tmp_constants = vec![zero]; let out = sq_diff_chip.forward( layouter.namespace(|| "sq diff chip"), &vec_inputs, &tmp_constants, )?; let var_div_chip = VarDivRoundChip::<F>::construct(gadget_config.clone()); let div = constants .get(&(gadget_config.scale_factor as i64)) .unwrap() .as_ref(); let single_inputs = vec![zero, div]; let out = out.iter().map(|x| x).collect::<Vec<_>>(); let out = var_div_chip.forward( layouter.namespace(|| "sq diff div"), &vec![out], &single_inputs, )?; let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>(); let out = Array::from_shape_vec(IxDyn(inp1.shape()), out).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for SquaredDiffChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![ GadgetType::SquaredDiff, GadgetType::VarDivRound, GadgetType::InputLookup, ] } }
https://github.com/ddkang/zkml
src/layers/tanh.rs
use std::{collections::HashMap, rc::Rc, vec}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::gadgets::{ gadget::{Gadget, GadgetConfig, GadgetType}, nonlinear::tanh::TanhGadgetChip, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; #[derive(Clone, Debug)] pub struct TanhChip {} impl<F: PrimeField> Layer<F> for TanhChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, _layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let inp = &tensors[0]; let inp_vec = inp.iter().map(|x| x.as_ref()).collect::<Vec<_>>(); let zero = constants.get(&0).unwrap().as_ref(); let tanh_chip = TanhGadgetChip::<F>::construct(gadget_config.clone()); let vec_inps = vec![inp_vec]; let constants = vec![zero]; let out = tanh_chip.forward(layouter.namespace(|| "tanh chip"), &vec_inps, &constants)?; let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>(); let out = Array::from_shape_vec(IxDyn(inp.shape()), out).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for TanhChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![GadgetType::Tanh, GadgetType::InputLookup] } }
https://github.com/ddkang/zkml
src/layers/update.rs
use std::{collections::HashMap, rc::Rc, vec}; use halo2_proofs::{circuit::Layouter, halo2curves::ff::PrimeField, plonk::Error}; use ndarray::{Array, IxDyn}; use crate::gadgets::{ gadget::{Gadget, GadgetConfig, GadgetType}, update::UpdateGadgetChip, }; use super::layer::{AssignedTensor, CellRc, GadgetConsumer, Layer, LayerConfig}; #[derive(Clone, Debug)] pub struct UpdateChip {} impl<F: PrimeField + Ord> Layer<F> for UpdateChip { fn forward( &self, mut layouter: impl Layouter<F>, tensors: &Vec<AssignedTensor<F>>, constants: &HashMap<i64, CellRc<F>>, gadget_config: Rc<GadgetConfig>, _layer_config: &LayerConfig, ) -> Result<Vec<AssignedTensor<F>>, Error> { let w = &tensors[0]; let dw = &tensors[1]; let zero = constants.get(&0).unwrap().as_ref(); let update_chip = UpdateGadgetChip::<F>::construct((*gadget_config).clone()); let flattened_w = w.into_iter().map(|x| (**x).clone()).collect::<Vec<_>>(); let flattened_dw = dw.into_iter().map(|x| (**x).clone()).collect::<Vec<_>>(); let flattened_w_ref = flattened_w.iter().collect::<Vec<_>>(); let flattened_dw_ref = flattened_dw.iter().collect::<Vec<_>>(); let vec_inps = vec![flattened_w_ref, flattened_dw_ref]; let constants = vec![zero]; let out = update_chip.forward(layouter.namespace(|| "update chip"), &vec_inps, &constants)?; let out = out.into_iter().map(|x| Rc::new(x)).collect::<Vec<_>>(); let out = Array::from_shape_vec(IxDyn(w.shape()), out).unwrap(); Ok(vec![out]) } } impl GadgetConsumer for UpdateChip { fn used_gadgets(&self, _layer_params: Vec<i64>) -> Vec<crate::gadgets::gadget::GadgetType> { vec![GadgetType::Update] } }
https://github.com/ddkang/zkml
src/lib.rs
#![feature(int_roundings)] pub mod commitments; pub mod gadgets; pub mod layers; pub mod model; pub mod utils;
https://github.com/ddkang/zkml
src/model.rs
use std::{ collections::{BTreeMap, BTreeSet, HashMap}, marker::PhantomData, rc::Rc, sync::{Arc, Mutex}, }; use halo2_proofs::{ circuit::{Layouter, SimpleFloorPlanner, Value}, halo2curves::ff::{FromUniformBytes, PrimeField}, plonk::{Advice, Circuit, Column, ConstraintSystem, Error, Instance}, }; use lazy_static::lazy_static; use ndarray::{Array, IxDyn}; use num_bigint::BigUint; use crate::{ commitments::{ commit::Commit, packer::PackerChip, poseidon_commit::{PoseidonCommitChip, L, RATE, WIDTH}, }, gadgets::{ add_pairs::AddPairsChip, adder::AdderChip, bias_div_round_relu6::BiasDivRoundRelu6Chip, dot_prod::DotProductChip, gadget::{Gadget, GadgetConfig, GadgetType}, input_lookup::InputLookupChip, max::MaxChip, mul_pairs::MulPairsChip, nonlinear::{exp::ExpGadgetChip, pow::PowGadgetChip, relu::ReluChip, tanh::TanhGadgetChip}, nonlinear::{logistic::LogisticGadgetChip, rsqrt::RsqrtGadgetChip, sqrt::SqrtGadgetChip}, sqrt_big::SqrtBigChip, square::SquareGadgetChip, squared_diff::SquaredDiffGadgetChip, sub_pairs::SubPairsChip, update::UpdateGadgetChip, var_div::VarDivRoundChip, var_div_big::VarDivRoundBigChip, var_div_big3::VarDivRoundBig3Chip, }, layers::{ arithmetic::{add::AddChip, div_var::DivVarChip, mul::MulChip, sub::SubChip}, avg_pool_2d::AvgPool2DChip, batch_mat_mul::BatchMatMulChip, conv2d::Conv2DChip, dag::{DAGLayerChip, DAGLayerConfig}, fully_connected::{FullyConnectedChip, FullyConnectedConfig}, layer::{AssignedTensor, CellRc, GadgetConsumer, LayerConfig, LayerType}, logistic::LogisticChip, max_pool_2d::MaxPool2DChip, mean::MeanChip, noop::NoopChip, pow::PowChip, rsqrt::RsqrtChip, shape::{ broadcast::BroadcastChip, concatenation::ConcatenationChip, mask_neg_inf::MaskNegInfChip, pack::PackChip, pad::PadChip, permute::PermuteChip, reshape::ReshapeChip, resize_nn::ResizeNNChip, rotate::RotateChip, slice::SliceChip, split::SplitChip, transpose::TransposeChip, }, softmax::SoftmaxChip, sqrt::SqrtChip, square::SquareChip, squared_diff::SquaredDiffChip, tanh::TanhChip, update::UpdateChip, }, utils::{ helpers::{convert_to_bigint, RAND_START_IDX}, loader::{load_model_msgpack, ModelMsgpack}, }, }; lazy_static! { pub static ref GADGET_CONFIG: Mutex<GadgetConfig> = Mutex::new(GadgetConfig::default()); pub static ref PUBLIC_VALS: Mutex<Vec<BigUint>> = Mutex::new(vec![]); } #[derive(Clone, Debug, Default)] pub struct ModelCircuit<F: PrimeField> { pub used_gadgets: Arc<BTreeSet<GadgetType>>, pub dag_config: DAGLayerConfig, pub tensors: BTreeMap<i64, Array<F, IxDyn>>, pub commit_before: Vec<Vec<i64>>, pub commit_after: Vec<Vec<i64>>, pub k: usize, pub bits_per_elem: usize, pub inp_idxes: Vec<i64>, pub num_random: i64, } #[derive(Clone, Debug)] pub struct ModelConfig<F: PrimeField + Ord + FromUniformBytes<64>> { pub gadget_config: Rc<GadgetConfig>, pub public_col: Column<Instance>, pub hasher: Option<PoseidonCommitChip<F, WIDTH, RATE, L>>, pub _marker: PhantomData<F>, } impl<F: PrimeField + Ord + FromUniformBytes<64>> ModelCircuit<F> { pub fn assign_tensors_map( &self, mut layouter: impl Layouter<F>, columns: &Vec<Column<Advice>>, tensors: &BTreeMap<i64, Array<F, IxDyn>>, ) -> Result<BTreeMap<i64, AssignedTensor<F>>, Error> { let tensors = layouter.assign_region( || "asssignment", |mut region| { let mut cell_idx = 0; let mut assigned_tensors = BTreeMap::new(); for (tensor_idx, tensor) in tensors.iter() { let mut flat = vec![]; for val in tensor.iter() { let row_idx = cell_idx / columns.len(); let col_idx = cell_idx % columns.len(); let cell = region .assign_advice( || "assignment", columns[col_idx], row_idx, || Value::known(*val), ) .unwrap(); flat.push(Rc::new(cell)); cell_idx += 1; } let tensor = Array::from_shape_vec(tensor.shape(), flat).unwrap(); assigned_tensors.insert(*tensor_idx, tensor); } Ok(assigned_tensors) }, )?; Ok(tensors) } pub fn tensor_map_to_vec( &self, tensor_map: &BTreeMap<i64, Array<CellRc<F>, IxDyn>>, ) -> Result<Vec<AssignedTensor<F>>, Error> { let smallest_tensor = tensor_map .iter() .min_by_key(|(_, tensor)| tensor.len()) .unwrap() .1; let max_tensor_key = tensor_map .iter() .max_by_key(|(key, _)| *key) .unwrap() .0 .clone(); let mut tensors = vec![]; for i in 0..max_tensor_key + 1 { let tensor = tensor_map.get(&i).unwrap_or(smallest_tensor); tensors.push(tensor.clone()); } Ok(tensors) } pub fn assign_tensors_vec( &self, mut layouter: impl Layouter<F>, columns: &Vec<Column<Advice>>, tensors: &BTreeMap<i64, Array<F, IxDyn>>, ) -> Result<Vec<AssignedTensor<F>>, Error> { let tensor_map = self .assign_tensors_map( layouter.namespace(|| "assign_tensors_map"), columns, tensors, ) .unwrap(); self.tensor_map_to_vec(&tensor_map) } pub fn assign_constants( &self, mut layouter: impl Layouter<F>, gadget_config: Rc<GadgetConfig>, ) -> Result<HashMap<i64, CellRc<F>>, Error> { let sf = gadget_config.scale_factor; let min_val = gadget_config.min_val; let max_val = gadget_config.max_val; let constants = layouter.assign_region( || "constants", |mut region| { let mut constants: HashMap<i64, CellRc<F>> = HashMap::new(); let vals = vec![0 as i64, 1, sf as i64, min_val, max_val]; let shift_val_i64 = -min_val * 2; // FIXME let shift_val_f = F::from(shift_val_i64 as u64); for (i, val) in vals.iter().enumerate() { let cell = region.assign_fixed( || format!("constant_{}", i), gadget_config.fixed_columns[0], i, || Value::known(F::from((val + shift_val_i64) as u64) - shift_val_f), )?; constants.insert(*val, Rc::new(cell)); } // TODO: I've made some very bad life decisions // TOOD: this needs to be a random oracle let r_base = F::from(0x123456789abcdef); let mut r = r_base.clone(); for i in 0..self.num_random { let rand = region.assign_fixed( || format!("rand_{}", i), gadget_config.fixed_columns[0], constants.len(), || Value::known(r), )?; r = r * r_base; constants.insert(RAND_START_IDX + (i as i64), Rc::new(rand)); } Ok(constants) }, )?; Ok(constants) } // TODO: for some horrifying reason, assigning to fixed columns causes everything to blow up // Currently get around this by assigning to advice columns // This is secure because of the equality checks but EXTREMELY STUPID pub fn assign_constants2( &self, mut layouter: impl Layouter<F>, gadget_config: Rc<GadgetConfig>, fixed_constants: &HashMap<i64, CellRc<F>>, ) -> Result<HashMap<i64, CellRc<F>>, Error> { let sf = gadget_config.scale_factor; let min_val = gadget_config.min_val; let max_val = gadget_config.max_val; let constants = layouter.assign_region( || "constants", |mut region| { let mut constants: HashMap<i64, CellRc<F>> = HashMap::new(); let vals = vec![0 as i64, 1, sf as i64, min_val, max_val]; let shift_val_i64 = -min_val * 2; // FIXME let shift_val_f = F::from(shift_val_i64 as u64); for (i, val) in vals.iter().enumerate() { let assignment_idx = i as usize; let row_idx = assignment_idx / gadget_config.columns.len(); let col_idx = assignment_idx % gadget_config.columns.len(); let cell = region.assign_advice( || format!("constant_{}", i), gadget_config.columns[col_idx], row_idx, || Value::known(F::from((val + shift_val_i64) as u64) - shift_val_f), )?; constants.insert(*val, Rc::new(cell)); } // TODO: I've made some very bad life decisions // TOOD: this needs to be a random oracle let r_base = F::from(0x123456789abcdef); let mut r = r_base.clone(); for i in 0..self.num_random { let assignment_idx = constants.len(); let row_idx = assignment_idx / gadget_config.columns.len(); let col_idx = assignment_idx % gadget_config.columns.len(); let rand = region.assign_advice( || format!("rand_{}", i), gadget_config.columns[col_idx], row_idx, || Value::known(r), )?; r = r * r_base; constants.insert(RAND_START_IDX + (i as i64), Rc::new(rand)); } for (k, v) in fixed_constants.iter() { let v2 = constants.get(k).unwrap(); region.constrain_equal(v.cell(), v2.cell()).unwrap(); } Ok(constants) }, )?; Ok(constants) } pub fn generate_from_file(config_file: &str, inp_file: &str) -> ModelCircuit<F> { let config = load_model_msgpack(config_file, inp_file); Self::generate_from_msgpack(config, true) } pub fn generate_from_msgpack(config: ModelMsgpack, panic_empty_tensor: bool) -> ModelCircuit<F> { let to_field = |x: i64| { let bias = 1 << 31; let x_pos = x + bias; F::from(x_pos as u64) - F::from(bias as u64) }; let match_layer = |x: &str| match x { "AveragePool2D" => LayerType::AvgPool2D, "Add" => LayerType::Add, "BatchMatMul" => LayerType::BatchMatMul, "Broadcast" => LayerType::Broadcast, "Concatenation" => LayerType::Concatenation, "Conv2D" => LayerType::Conv2D, "Div" => LayerType::DivFixed, // TODO: rename to DivFixed "DivVar" => LayerType::DivVar, "FullyConnected" => LayerType::FullyConnected, "Logistic" => LayerType::Logistic, "MaskNegInf" => LayerType::MaskNegInf, "MaxPool2D" => LayerType::MaxPool2D, "Mean" => LayerType::Mean, "Mul" => LayerType::Mul, "Noop" => LayerType::Noop, "Pack" => LayerType::Pack, "Pad" => LayerType::Pad, "Pow" => LayerType::Pow, "Permute" => LayerType::Permute, "Reshape" => LayerType::Reshape, "ResizeNearestNeighbor" => LayerType::ResizeNN, "Rotate" => LayerType::Rotate, "Rsqrt" => LayerType::Rsqrt, "Slice" => LayerType::Slice, "Softmax" => LayerType::Softmax, "Split" => LayerType::Split, "Sqrt" => LayerType::Sqrt, "Square" => LayerType::Square, "SquaredDifference" => LayerType::SquaredDifference, "Sub" => LayerType::Sub, "Tanh" => LayerType::Tanh, "Transpose" => LayerType::Transpose, "Update" => LayerType::Update, _ => panic!("unknown op: {}", x), }; let mut tensors = BTreeMap::new(); for flat in config.tensors { let value_flat = flat.data.iter().map(|x| to_field(*x)).collect::<Vec<_>>(); let shape = flat.shape.iter().map(|x| *x as usize).collect::<Vec<_>>(); let num_el: usize = shape.iter().product(); if panic_empty_tensor && num_el != value_flat.len() { panic!("tensor shape and data length mismatch"); } if num_el == value_flat.len() { let tensor = Array::from_shape_vec(IxDyn(&shape), value_flat).unwrap(); tensors.insert(flat.idx, tensor); } else { // Do nothing here since we're loading the config }; } let i64_to_usize = |x: &Vec<i64>| x.iter().map(|x| *x as usize).collect::<Vec<_>>(); let mut used_gadgets = BTreeSet::new(); let dag_config = { let ops = config .layers .iter() .map(|layer| { let layer_type = match_layer(&layer.layer_type); let layer_gadgets = match layer_type { LayerType::Add => Box::new(AddChip {}) as Box<dyn GadgetConsumer>, LayerType::AvgPool2D => Box::new(AvgPool2DChip {}) as Box<dyn GadgetConsumer>, LayerType::BatchMatMul => Box::new(BatchMatMulChip {}) as Box<dyn GadgetConsumer>, LayerType::Broadcast => Box::new(BroadcastChip {}) as Box<dyn GadgetConsumer>, LayerType::Concatenation => Box::new(ConcatenationChip {}) as Box<dyn GadgetConsumer>, LayerType::DivFixed => Box::new(ConcatenationChip {}) as Box<dyn GadgetConsumer>, LayerType::DivVar => Box::new(DivVarChip {}) as Box<dyn GadgetConsumer>, LayerType::Conv2D => Box::new(Conv2DChip { config: LayerConfig::default(), _marker: PhantomData::<F>, }) as Box<dyn GadgetConsumer>, LayerType::FullyConnected => Box::new(FullyConnectedChip { config: FullyConnectedConfig { normalize: true }, _marker: PhantomData::<F>, }) as Box<dyn GadgetConsumer>, LayerType::Logistic => Box::new(LogisticChip {}) as Box<dyn GadgetConsumer>, LayerType::MaskNegInf => Box::new(MaskNegInfChip {}) as Box<dyn GadgetConsumer>, LayerType::MaxPool2D => Box::new(MaxPool2DChip { marker: PhantomData::<F>, }) as Box<dyn GadgetConsumer>, LayerType::Mean => Box::new(MeanChip {}) as Box<dyn GadgetConsumer>, LayerType::Mul => Box::new(MulChip {}) as Box<dyn GadgetConsumer>, LayerType::Noop => Box::new(NoopChip {}) as Box<dyn GadgetConsumer>, LayerType::Pack => Box::new(PackChip {}) as Box<dyn GadgetConsumer>, LayerType::Pad => Box::new(PadChip {}) as Box<dyn GadgetConsumer>, LayerType::Pow => Box::new(PowChip {}) as Box<dyn GadgetConsumer>, LayerType::Permute => Box::new(PermuteChip {}) as Box<dyn GadgetConsumer>, LayerType::Reshape => Box::new(ReshapeChip {}) as Box<dyn GadgetConsumer>, LayerType::ResizeNN => Box::new(ResizeNNChip {}) as Box<dyn GadgetConsumer>, LayerType::Rotate => Box::new(RotateChip {}) as Box<dyn GadgetConsumer>, LayerType::Rsqrt => Box::new(RsqrtChip {}) as Box<dyn GadgetConsumer>, LayerType::Slice => Box::new(SliceChip {}) as Box<dyn GadgetConsumer>, LayerType::Softmax => Box::new(SoftmaxChip {}) as Box<dyn GadgetConsumer>, LayerType::Split => Box::new(SplitChip {}) as Box<dyn GadgetConsumer>, LayerType::Sqrt => Box::new(SqrtChip {}) as Box<dyn GadgetConsumer>, LayerType::Square => Box::new(SquareChip {}) as Box<dyn GadgetConsumer>, LayerType::SquaredDifference => Box::new(SquaredDiffChip {}) as Box<dyn GadgetConsumer>, LayerType::Sub => Box::new(SubChip {}) as Box<dyn GadgetConsumer>, LayerType::Tanh => Box::new(TanhChip {}) as Box<dyn GadgetConsumer>, LayerType::Transpose => Box::new(TransposeChip {}) as Box<dyn GadgetConsumer>, LayerType::Update => Box::new(UpdateChip {}) as Box<dyn GadgetConsumer>, } .used_gadgets(layer.params.clone()); for gadget in layer_gadgets { used_gadgets.insert(gadget); } LayerConfig { layer_type, layer_params: layer.params.clone(), inp_shapes: layer.inp_shapes.iter().map(|x| i64_to_usize(x)).collect(), out_shapes: layer.out_shapes.iter().map(|x| i64_to_usize(x)).collect(), mask: layer.mask.clone(), } }) .collect::<Vec<_>>(); let inp_idxes = config .layers .iter() .map(|layer| i64_to_usize(&layer.inp_idxes)) .collect::<Vec<_>>(); let out_idxes = config .layers .iter() .map(|layer| i64_to_usize(&layer.out_idxes)) .collect::<Vec<_>>(); let final_out_idxes = config .out_idxes .iter() .map(|x| *x as usize) .collect::<Vec<_>>(); DAGLayerConfig { inp_idxes, out_idxes, ops, final_out_idxes, } }; // The input lookup is always used used_gadgets.insert(GadgetType::InputLookup); let used_gadgets = Arc::new(used_gadgets); let gadget = &GADGET_CONFIG; let cloned_gadget = gadget.lock().unwrap().clone(); *gadget.lock().unwrap() = GadgetConfig { scale_factor: config.global_sf as u64, shift_min_val: -(config.global_sf * config.global_sf * (1 << 17)), div_outp_min_val: -(1 << (config.k - 1)), min_val: -(1 << (config.k - 1)), max_val: (1 << (config.k - 1)) - 10, k: config.k as usize, num_rows: (1 << config.k) - 10 + 1, num_cols: config.num_cols as usize, used_gadgets: used_gadgets.clone(), commit_before: config.commit_before.clone().unwrap_or(vec![]), commit_after: config.commit_after.clone().unwrap_or(vec![]), use_selectors: config.use_selectors.unwrap_or(true), num_bits_per_elem: config.bits_per_elem.unwrap_or(config.k), ..cloned_gadget }; ModelCircuit { tensors, dag_config, used_gadgets, k: config.k as usize, bits_per_elem: config.bits_per_elem.unwrap_or(config.k) as usize, inp_idxes: config.inp_idxes.clone(), commit_after: config.commit_after.unwrap_or(vec![]), commit_before: config.commit_before.unwrap_or(vec![]), num_random: config.num_random.unwrap_or(0), } } pub fn assign_and_commit( &self, mut layouter: impl Layouter<F>, constants: &HashMap<i64, CellRc<F>>, config: &ModelConfig<F>, tensors: &BTreeMap<i64, Array<F, IxDyn>>, ) -> (BTreeMap<i64, AssignedTensor<F>>, CellRc<F>) { let num_bits = self.bits_per_elem; let packer_config = PackerChip::<F>::construct(num_bits, config.gadget_config.as_ref()); let packer_chip = PackerChip::<F> { config: packer_config, }; let (tensor_map, packed) = packer_chip .assign_and_pack( layouter.namespace(|| "packer"), config.gadget_config.clone(), constants, tensors, ) .unwrap(); let zero = constants.get(&0).unwrap().clone(); let commit_chip = config.hasher.clone().unwrap(); let commitments = commit_chip .commit( layouter.namespace(|| "commit"), config.gadget_config.clone(), constants, &packed, zero.clone(), ) .unwrap(); assert_eq!(commitments.len(), 1); (tensor_map, commitments[0].clone()) } pub fn copy_and_commit( &self, mut layouter: impl Layouter<F>, constants: &HashMap<i64, CellRc<F>>, config: &ModelConfig<F>, tensors: &BTreeMap<i64, AssignedTensor<F>>, ) -> CellRc<F> { let num_bits = self.bits_per_elem; let packer_config = PackerChip::<F>::construct(num_bits, config.gadget_config.as_ref()); let packer_chip = PackerChip::<F> { config: packer_config, }; let packed = packer_chip .copy_and_pack( layouter.namespace(|| "packer"), config.gadget_config.clone(), constants, tensors, ) .unwrap(); let zero = constants.get(&0).unwrap().clone(); let commit_chip = config.hasher.clone().unwrap(); let commitments = commit_chip .commit( layouter.namespace(|| "commit"), config.gadget_config.clone(), constants, &packed, zero.clone(), ) .unwrap(); assert_eq!(commitments.len(), 1); commitments[0].clone() } } impl<F: PrimeField + Ord + FromUniformBytes<64>> Circuit<F> for ModelCircuit<F> { type Config = ModelConfig<F>; type FloorPlanner = SimpleFloorPlanner; type Params = (); fn without_witnesses(&self) -> Self { todo!() } fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config { let mut gadget_config = crate::model::GADGET_CONFIG.lock().unwrap().clone(); let columns = (0..gadget_config.num_cols) .map(|_| meta.advice_column()) .collect::<Vec<_>>(); for col in columns.iter() { meta.enable_equality(*col); } gadget_config.columns = columns; let public_col = meta.instance_column(); meta.enable_equality(public_col); gadget_config.fixed_columns = vec![meta.fixed_column()]; meta.enable_equality(gadget_config.fixed_columns[0]); // The input lookup is always loaded gadget_config = InputLookupChip::<F>::configure(meta, gadget_config); let used_gadgets = gadget_config.used_gadgets.clone(); for gadget_type in used_gadgets.iter() { gadget_config = match gadget_type { GadgetType::AddPairs => AddPairsChip::<F>::configure(meta, gadget_config), GadgetType::Adder => AdderChip::<F>::configure(meta, gadget_config), GadgetType::BiasDivRoundRelu6 => BiasDivRoundRelu6Chip::<F>::configure(meta, gadget_config), GadgetType::BiasDivFloorRelu6 => panic!(), GadgetType::DotProduct => DotProductChip::<F>::configure(meta, gadget_config), GadgetType::Exp => ExpGadgetChip::<F>::configure(meta, gadget_config), GadgetType::Logistic => LogisticGadgetChip::<F>::configure(meta, gadget_config), GadgetType::Max => MaxChip::<F>::configure(meta, gadget_config), GadgetType::MulPairs => MulPairsChip::<F>::configure(meta, gadget_config), GadgetType::Pow => PowGadgetChip::<F>::configure(meta, gadget_config), GadgetType::Relu => ReluChip::<F>::configure(meta, gadget_config), GadgetType::Rsqrt => RsqrtGadgetChip::<F>::configure(meta, gadget_config), GadgetType::Sqrt => SqrtGadgetChip::<F>::configure(meta, gadget_config), GadgetType::SqrtBig => SqrtBigChip::<F>::configure(meta, gadget_config), GadgetType::Square => SquareGadgetChip::<F>::configure(meta, gadget_config), GadgetType::SquaredDiff => SquaredDiffGadgetChip::<F>::configure(meta, gadget_config), GadgetType::SubPairs => SubPairsChip::<F>::configure(meta, gadget_config), GadgetType::Tanh => TanhGadgetChip::<F>::configure(meta, gadget_config), GadgetType::VarDivRound => VarDivRoundChip::<F>::configure(meta, gadget_config), GadgetType::VarDivRoundBig => VarDivRoundBigChip::<F>::configure(meta, gadget_config), GadgetType::VarDivRoundBig3 => VarDivRoundBig3Chip::<F>::configure(meta, gadget_config), GadgetType::InputLookup => gadget_config, // This is always loaded GadgetType::Update => UpdateGadgetChip::<F>::configure(meta, gadget_config), GadgetType::Packer => panic!(), }; } let hasher = if gadget_config.commit_before.len() + gadget_config.commit_after.len() > 0 { let packer_config = PackerChip::<F>::construct(gadget_config.num_bits_per_elem as usize, &gadget_config); gadget_config = PackerChip::<F>::configure(meta, packer_config, gadget_config); // TODO let input = gadget_config.columns[0..L].try_into().unwrap(); let state = gadget_config.columns[L..L + WIDTH].try_into().unwrap(); let partial_sbox = gadget_config.columns[L + WIDTH].into(); Some(PoseidonCommitChip::<F, WIDTH, RATE, L>::configure( meta, input, state, partial_sbox, )) } else { None }; ModelConfig { gadget_config: gadget_config.into(), public_col, hasher, _marker: PhantomData, } } fn synthesize(&self, config: Self::Config, mut layouter: impl Layouter<F>) -> Result<(), Error> { // Assign tables let gadget_rc: Rc<GadgetConfig> = config.gadget_config.clone().into(); for gadget in self.used_gadgets.iter() { match gadget { GadgetType::AddPairs => { let chip = AddPairsChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "add pairs lookup"))?; } GadgetType::Adder => { let chip = AdderChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "adder lookup"))?; } GadgetType::BiasDivRoundRelu6 => { let chip = BiasDivRoundRelu6Chip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "bias div round relu6 lookup"))?; } GadgetType::DotProduct => { let chip = DotProductChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "dot product lookup"))?; } GadgetType::VarDivRound => { let chip = VarDivRoundChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "var div lookup"))?; } GadgetType::Pow => { let chip = PowGadgetChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "pow lookup"))?; } GadgetType::Relu => { let chip = ReluChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "relu lookup"))?; } GadgetType::Rsqrt => { let chip = RsqrtGadgetChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "rsqrt lookup"))?; } GadgetType::Sqrt => { let chip = SqrtGadgetChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "sqrt lookup"))?; } GadgetType::Tanh => { let chip = TanhGadgetChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "tanh lookup"))?; } GadgetType::Exp => { let chip = ExpGadgetChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "exp lookup"))?; } GadgetType::Logistic => { let chip = LogisticGadgetChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "logistic lookup"))?; } GadgetType::InputLookup => { let chip = InputLookupChip::<F>::construct(gadget_rc.clone()); chip.load_lookups(layouter.namespace(|| "input lookup"))?; } GadgetType::VarDivRoundBig => {} GadgetType::VarDivRoundBig3 => {} GadgetType::Max => {} GadgetType::MulPairs => {} GadgetType::SqrtBig => {} GadgetType::Square => {} GadgetType::SquaredDiff => {} GadgetType::SubPairs => {} GadgetType::Update => {} _ => panic!("unsupported gadget {:?}", gadget), } } // Assign weights and constants let constants_base = self .assign_constants( layouter.namespace(|| "constants"), config.gadget_config.clone(), ) .unwrap(); // Some halo2 cancer let constants = self .assign_constants2( layouter.namespace(|| "constants 2"), config.gadget_config.clone(), &constants_base, ) .unwrap(); let mut commitments = vec![]; let tensors = if self.commit_before.len() > 0 { // Commit to the tensors before the DAG let mut tensor_map = BTreeMap::new(); let mut ignore_idxes: Vec<i64> = vec![]; for commit_idxes in self.commit_before.iter() { let to_commit = BTreeMap::from_iter( commit_idxes .iter() .map(|idx| (*idx, self.tensors.get(idx).unwrap().clone())), ); let (mut committed_tensors, commitment) = self.assign_and_commit( layouter.namespace(|| "commit"), &constants, &config, &to_commit, ); commitments.push(commitment); tensor_map.append(&mut committed_tensors); ignore_idxes.extend(commit_idxes.iter()); } // Assign the remainder of the tensors let mut assign_map = BTreeMap::new(); for (idx, tensor) in self.tensors.iter() { if ignore_idxes.contains(idx) { continue; } assign_map.insert(*idx, tensor.clone()); } let mut remainder_tensor_map = self .assign_tensors_map( layouter.namespace(|| "assignment"), &config.gadget_config.columns, &assign_map, ) .unwrap(); // Merge the two maps tensor_map.append(&mut remainder_tensor_map); // Return the tensors self.tensor_map_to_vec(&tensor_map).unwrap() } else { self .assign_tensors_vec( layouter.namespace(|| "assignment"), &config.gadget_config.columns, &self.tensors, ) .unwrap() }; // Perform the dag let dag_chip = DAGLayerChip::<F>::construct(self.dag_config.clone()); let (final_tensor_map, result) = dag_chip.forward( layouter.namespace(|| "dag"), &tensors, &constants, config.gadget_config.clone(), &LayerConfig::default(), )?; if self.commit_after.len() > 0 { for commit_idxes in self.commit_after.iter() { let to_commit = BTreeMap::from_iter(commit_idxes.iter().map(|idx| { ( *idx, final_tensor_map.get(&(*idx as usize)).unwrap().clone(), ) })); let commitment = self.copy_and_commit( layouter.namespace(|| "commit"), &constants, &config, &to_commit, ); commitments.push(commitment); } } let mut pub_layouter = layouter.namespace(|| "public"); let mut total_idx = 0; let mut new_public_vals = vec![]; for cell in commitments.iter() { pub_layouter .constrain_instance(cell.as_ref().cell(), config.public_col, total_idx) .unwrap(); let val = convert_to_bigint(cell.value().map(|x| x.to_owned())); new_public_vals.push(val); total_idx += 1; } for tensor in result { for cell in tensor.iter() { pub_layouter .constrain_instance(cell.as_ref().cell(), config.public_col, total_idx) .unwrap(); let val = convert_to_bigint(cell.value().map(|x| x.to_owned())); new_public_vals.push(val); total_idx += 1; } } *PUBLIC_VALS.lock().unwrap() = new_public_vals; Ok(()) } }
https://github.com/ddkang/zkml
src/utils.rs
pub mod helpers; pub mod loader; pub mod proving_ipa; pub mod proving_kzg;
https://github.com/ddkang/zkml
src/utils/helpers.rs
use halo2_proofs::{ circuit::{AssignedCell, Value}, halo2curves::ff::PrimeField, }; use ndarray::{Array, IxDyn}; use num_bigint::BigUint; use crate::{gadgets::gadget::convert_to_u128, model::PUBLIC_VALS}; // TODO: this is very bad pub const RAND_START_IDX: i64 = i64::MIN; pub const NUM_RANDOMS: i64 = 20001; // Conversion / printing functions pub fn convert_to_bigint<F: PrimeField>(x: Value<F>) -> BigUint { let mut big = Default::default(); x.map(|x| { big = BigUint::from_bytes_le(x.to_repr().as_ref()); }); big } pub fn convert_pos_int<F: PrimeField>(x: Value<F>) -> i128 { let bias = 1 << 60; let x_pos = x + Value::known(F::from(bias as u64)); let mut outp: i128 = 0; x_pos.map(|x| { let x_pos = convert_to_u128(&x); let tmp = x_pos as i128 - bias; outp = tmp; }); return outp; } pub fn print_pos_int<F: PrimeField>(prefix: &str, x: Value<F>, scale_factor: u64) { let tmp = convert_pos_int(x); let tmp_float = tmp as f64 / scale_factor as f64; println!("{} x: {} ({})", prefix, tmp, tmp_float); } pub fn print_assigned_arr<F: PrimeField>( prefix: &str, arr: &Vec<&AssignedCell<F, F>>, scale_factor: u64, ) { for (idx, x) in arr.iter().enumerate() { print_pos_int( &format!("{}[{}]", prefix, idx), x.value().map(|x: &F| x.to_owned()), scale_factor, ); } } // Get the public values pub fn get_public_values<F: PrimeField>() -> Vec<F> { let mut public_vals = vec![]; for val in PUBLIC_VALS.lock().unwrap().iter() { let val = F::from_str_vartime(&val.to_str_radix(10)); public_vals.push(val.unwrap()); } public_vals } // Broadcast fn shape_dominates(s1: &[usize], s2: &[usize]) -> bool { if s1.len() != s2.len() { return false; } for (x1, x2) in s1.iter().zip(s2.iter()) { if x1 < x2 { return false; } } true } // Precondition: s1.len() < s2.len() fn intermediate_shape(s1: &[usize], s2: &[usize]) -> Vec<usize> { let mut res = vec![1; s2.len() - s1.len()]; for s in s1.iter() { res.push(*s); } res } fn final_shape(s1: &[usize], s2: &[usize]) -> Vec<usize> { let mut res = vec![]; for (x1, x2) in s1.iter().zip(s2.iter()) { res.push(std::cmp::max(*x1, *x2)); } res } pub fn broadcast<G: Clone>( x1: &Array<G, IxDyn>, x2: &Array<G, IxDyn>, ) -> (Array<G, IxDyn>, Array<G, IxDyn>) { if x1.shape() == x2.shape() { return (x1.clone(), x2.clone()); } if x1.ndim() == x2.ndim() { let s1 = x1.shape(); let s2 = x2.shape(); if shape_dominates(s1, s2) { return (x1.clone(), x2.broadcast(s1).unwrap().into_owned()); } else if shape_dominates(x2.shape(), x1.shape()) { return (x1.broadcast(s2).unwrap().into_owned(), x2.clone()); } } let (tmp1, tmp2) = if x1.ndim() < x2.ndim() { (x1, x2) } else { (x2, x1) }; // tmp1.ndim() < tmp2.ndim() let s1 = tmp1.shape(); let s2 = tmp2.shape(); let s = intermediate_shape(s1, s2); let final_shape = final_shape(s2, s.as_slice()); let tmp1 = tmp1.broadcast(s.clone()).unwrap().into_owned(); let tmp1 = tmp1.broadcast(final_shape.as_slice()).unwrap().into_owned(); let tmp2 = tmp2.broadcast(final_shape.as_slice()).unwrap().into_owned(); // println!("x1: {:?} x2: {:?}", x1.shape(), x2.shape()); // println!("s1: {:?} s2: {:?} s: {:?}", s1, s2, s); // println!("tmp1 shape: {:?}", tmp1.shape()); // println!("tmp2 shape: {:?}", tmp2.shape()); if x1.ndim() < x2.ndim() { return (tmp1, tmp2); } else { return (tmp2, tmp1); } }
https://github.com/ddkang/zkml
src/utils/loader.rs
use std::{fs::File, io::BufReader}; use serde_derive::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct TensorMsgpack { pub idx: i64, pub shape: Vec<i64>, pub data: Vec<i64>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct LayerMsgpack { pub layer_type: String, pub params: Vec<i64>, pub inp_idxes: Vec<i64>, pub inp_shapes: Vec<Vec<i64>>, pub out_idxes: Vec<i64>, pub out_shapes: Vec<Vec<i64>>, pub mask: Vec<i64>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ModelMsgpack { pub global_sf: i64, pub k: i64, pub num_cols: i64, pub inp_idxes: Vec<i64>, pub out_idxes: Vec<i64>, pub tensors: Vec<TensorMsgpack>, pub layers: Vec<LayerMsgpack>, pub use_selectors: Option<bool>, pub commit_before: Option<Vec<Vec<i64>>>, pub commit_after: Option<Vec<Vec<i64>>>, pub bits_per_elem: Option<i64>, // Specifically for packing for the commitments pub num_random: Option<i64>, } pub fn load_config_msgpack(config_path: &str) -> ModelMsgpack { let model: ModelMsgpack = { let file = File::open(config_path).unwrap(); let mut reader = BufReader::new(file); rmp_serde::from_read(&mut reader).unwrap() }; model } pub fn load_model_msgpack(config_path: &str, inp_path: &str) -> ModelMsgpack { let mut model = load_config_msgpack(config_path); let inp: Vec<TensorMsgpack> = { let file = File::open(inp_path).unwrap(); let mut reader = BufReader::new(file); rmp_serde::from_read(&mut reader).unwrap() }; for tensor in inp { model.tensors.push(tensor); } // Default to using selectors, commit if use_selectors is not specified if model.use_selectors.is_none() { model.use_selectors = Some(true) }; if model.commit_before.is_none() { model.commit_before = Some(vec![]) }; if model.commit_after.is_none() { model.commit_after = Some(vec![]) }; if model.bits_per_elem.is_none() { model.bits_per_elem = Some(model.k) }; if model.num_random.is_none() { model.num_random = Some(20001) }; model }
https://github.com/ddkang/zkml
src/utils/proving_ipa.rs
use std::{ fs::File, io::{BufReader, Write}, path::Path, time::Instant, }; use halo2_proofs::{ dev::MockProver, halo2curves::pasta::{EqAffine, Fp}, plonk::{create_proof, keygen_pk, keygen_vk, verify_proof}, poly::{ commitment::{Params, ParamsProver}, ipa::{ commitment::{IPACommitmentScheme, ParamsIPA}, multiopen::ProverIPA, strategy::SingleStrategy, }, VerificationStrategy, }, transcript::{ Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, }, }; use crate::{model::ModelCircuit, utils::helpers::get_public_values}; pub fn get_ipa_params(params_dir: &str, degree: u32) -> ParamsIPA<EqAffine> { let path = format!("{}/{}.params", params_dir, degree); let params_path = Path::new(&path); if File::open(&params_path).is_err() { let params: ParamsIPA<EqAffine> = ParamsIPA::new(degree); let mut buf = Vec::new(); params.write(&mut buf).expect("Failed to write params"); let mut file = File::create(&params_path).expect("Failed to create params file"); file .write_all(&buf[..]) .expect("Failed to write params to file"); } let params_fs = File::open(&params_path).expect("couldn't load params"); let params: ParamsIPA<EqAffine> = Params::read::<_>(&mut BufReader::new(params_fs)).expect("Failed to read params"); params } pub fn time_circuit_ipa(circuit: ModelCircuit<Fp>) { let rng = rand::thread_rng(); let start = Instant::now(); let degree = circuit.k as u32; let empty_circuit = circuit.clone(); let proof_circuit = circuit; let params = get_ipa_params("./params_ipa", degree); let circuit_duration = start.elapsed(); println!( "Time elapsed in params construction: {:?}", circuit_duration ); let vk = keygen_vk(&params, &empty_circuit).unwrap(); let vk_duration = start.elapsed(); println!( "Time elapsed in generating vkey: {:?}", vk_duration - circuit_duration ); let pk = keygen_pk(&params, vk, &empty_circuit).unwrap(); let pk_duration = start.elapsed(); println!( "Time elapsed in generating pkey: {:?}", pk_duration - vk_duration ); drop(empty_circuit); let fill_duration = start.elapsed(); let _prover = MockProver::run(degree, &proof_circuit, vec![vec![]]).unwrap(); let public_vals = get_public_values(); println!( "Time elapsed in filling circuit: {:?}", fill_duration - pk_duration ); let mut transcript = Blake2bWrite::<_, _, Challenge255<_>>::init(vec![]); create_proof::<IPACommitmentScheme<EqAffine>, ProverIPA<EqAffine>, _, _, _, _>( &params, &pk, &[proof_circuit], &[&[&public_vals]], rng, &mut transcript, ) .unwrap(); let proof = transcript.finalize(); let proof_duration = start.elapsed(); println!("Proving time: {:?}", proof_duration - fill_duration); let proof_size = { let mut folder = std::path::PathBuf::new(); folder.push("proof"); let mut fd = std::fs::File::create(folder.as_path()).unwrap(); folder.pop(); fd.write_all(&proof).unwrap(); fd.metadata().unwrap().len() }; println!("Proof size: {} bytes", proof_size); let strategy = SingleStrategy::new(&params); let mut transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); assert!( verify_proof( &params, pk.get_vk(), strategy, &[&[&public_vals]], &mut transcript ) .is_ok(), "proof did not verify" ); let verify_duration = start.elapsed(); println!("Verifying time: {:?}", verify_duration - proof_duration); }
https://github.com/ddkang/zkml
src/utils/proving_kzg.rs
use std::{ fs::File, io::{BufReader, Write}, path::Path, time::Instant, }; use halo2_proofs::{ dev::MockProver, halo2curves::bn256::{Bn256, Fr, G1Affine}, plonk::{create_proof, keygen_pk, keygen_vk, verify_proof, VerifyingKey}, poly::{ commitment::Params, kzg::{ commitment::{KZGCommitmentScheme, ParamsKZG}, multiopen::{ProverSHPLONK, VerifierSHPLONK}, strategy::SingleStrategy, }, }, transcript::{ Blake2bRead, Blake2bWrite, Challenge255, TranscriptReadBuffer, TranscriptWriterBuffer, }, SerdeFormat, }; use crate::{model::ModelCircuit, utils::helpers::get_public_values}; pub fn get_kzg_params(params_dir: &str, degree: u32) -> ParamsKZG<Bn256> { let rng = rand::thread_rng(); let path = format!("{}/{}.params", params_dir, degree); let params_path = Path::new(&path); if File::open(&params_path).is_err() { let params = ParamsKZG::<Bn256>::setup(degree, rng); let mut buf = Vec::new(); params.write(&mut buf).expect("Failed to write params"); let mut file = File::create(&params_path).expect("Failed to create params file"); file .write_all(&buf[..]) .expect("Failed to write params to file"); } let mut params_fs = File::open(&params_path).expect("couldn't load params"); let params = ParamsKZG::<Bn256>::read(&mut params_fs).expect("Failed to read params"); params } pub fn serialize(data: &Vec<u8>, path: &str) -> u64 { let mut file = File::create(path).unwrap(); file.write_all(data).unwrap(); file.metadata().unwrap().len() } pub fn verify_kzg( params: &ParamsKZG<Bn256>, vk: &VerifyingKey<G1Affine>, strategy: SingleStrategy<Bn256>, public_vals: &Vec<Fr>, mut transcript: Blake2bRead<&[u8], G1Affine, Challenge255<G1Affine>>, ) { assert!( verify_proof::< KZGCommitmentScheme<Bn256>, VerifierSHPLONK<'_, Bn256>, Challenge255<G1Affine>, Blake2bRead<&[u8], G1Affine, Challenge255<G1Affine>>, halo2_proofs::poly::kzg::strategy::SingleStrategy<'_, Bn256>, >(&params, &vk, strategy, &[&[&public_vals]], &mut transcript) .is_ok(), "proof did not verify" ); } pub fn time_circuit_kzg(circuit: ModelCircuit<Fr>) { let rng = rand::thread_rng(); let start = Instant::now(); let degree = circuit.k as u32; let params = get_kzg_params("./params_kzg", degree); let circuit_duration = start.elapsed(); println!( "Time elapsed in params construction: {:?}", circuit_duration ); let vk_circuit = circuit.clone(); let vk = keygen_vk(&params, &vk_circuit).unwrap(); drop(vk_circuit); let vk_duration = start.elapsed(); println!( "Time elapsed in generating vkey: {:?}", vk_duration - circuit_duration ); let vkey_size = serialize(&vk.to_bytes(SerdeFormat::RawBytes), "vkey"); println!("vkey size: {} bytes", vkey_size); let pk_circuit = circuit.clone(); let pk = keygen_pk(&params, vk, &pk_circuit).unwrap(); let pk_duration = start.elapsed(); println!( "Time elapsed in generating pkey: {:?}", pk_duration - vk_duration ); drop(pk_circuit); let pkey_size = serialize(&pk.to_bytes(SerdeFormat::RawBytes), "pkey"); println!("pkey size: {} bytes", pkey_size); let fill_duration = start.elapsed(); let proof_circuit = circuit.clone(); let _prover = MockProver::run(degree, &proof_circuit, vec![vec![]]).unwrap(); let public_vals = get_public_values(); println!( "Time elapsed in filling circuit: {:?}", fill_duration - pk_duration ); // Convert public vals to serializable format let public_vals_u8: Vec<u8> = public_vals .iter() .map(|v: &Fr| v.to_bytes().to_vec()) .flatten() .collect(); let public_vals_u8_size = serialize(&public_vals_u8, "public_vals"); println!("Public vals size: {} bytes", public_vals_u8_size); let mut transcript = Blake2bWrite::<_, G1Affine, Challenge255<_>>::init(vec![]); create_proof::< KZGCommitmentScheme<Bn256>, ProverSHPLONK<'_, Bn256>, Challenge255<G1Affine>, _, Blake2bWrite<Vec<u8>, G1Affine, Challenge255<G1Affine>>, ModelCircuit<Fr>, >( &params, &pk, &[proof_circuit], &[&[&public_vals]], rng, &mut transcript, ) .unwrap(); let proof = transcript.finalize(); let proof_duration = start.elapsed(); println!("Proving time: {:?}", proof_duration - fill_duration); let proof_size = serialize(&proof, "proof"); let proof = std::fs::read("proof").unwrap(); println!("Proof size: {} bytes", proof_size); let strategy = SingleStrategy::new(&params); let transcript_read = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); println!("public vals: {:?}", public_vals); verify_kzg( &params, &pk.get_vk(), strategy, &public_vals, transcript_read, ); let verify_duration = start.elapsed(); println!("Verifying time: {:?}", verify_duration - proof_duration); } // Standalone verification pub fn verify_circuit_kzg( circuit: ModelCircuit<Fr>, vkey_fname: &str, proof_fname: &str, public_vals_fname: &str, ) { let degree = circuit.k as u32; let params = get_kzg_params("./params_kzg", degree); println!("Loaded the parameters"); let vk = VerifyingKey::read::<BufReader<File>, ModelCircuit<Fr>>( &mut BufReader::new(File::open(vkey_fname).unwrap()), SerdeFormat::RawBytes, (), ) .unwrap(); println!("Loaded vkey"); let proof = std::fs::read(proof_fname).unwrap(); let public_vals_u8 = std::fs::read(&public_vals_fname).unwrap(); let public_vals: Vec<Fr> = public_vals_u8 .chunks(32) .map(|chunk| Fr::from_bytes(chunk.try_into().expect("conversion failed")).unwrap()) .collect(); let strategy = SingleStrategy::new(&params); let transcript = Blake2bRead::<_, _, Challenge255<_>>::init(&proof[..]); let start = Instant::now(); let verify_start = start.elapsed(); verify_kzg(&params, &vk, strategy, &public_vals, transcript); let verify_duration = start.elapsed(); println!("Verifying time: {:?}", verify_duration - verify_start); println!("Proof verified!") }
https://github.com/ddkang/zkml
testing/circuits/last_two_layers.py
import tensorflow as tf import os import numpy as np interpreter = tf.lite.Interpreter( model_path=f'./testing/circuits/v2_1.0_224.tflite' ) interpreter.allocate_tensors() NAME_TO_TENSOR = {} for tensor_details in interpreter.get_tensor_details(): NAME_TO_TENSOR[tensor_details['name']] = tensor_details Wc = interpreter.get_tensor(NAME_TO_TENSOR['Const_71']['index']) Bc = interpreter.get_tensor(NAME_TO_TENSOR['MobilenetV2/Conv_1/Conv2D_bias']['index']) class LastTwoLayers(tf.keras.Model): def __init__(self, name=None): super().__init__(name = name) self.a_variable = tf.Variable(5.0, name="train_me") self.conv1 = tf.keras.layers.Conv2D( 1280, (1, 1), activation='relu6', padding='same', input_shape=(1, 7, 7, 320) ) self.avg_pool = tf.keras.layers.AveragePooling2D( pool_size=(7, 7), padding='valid', strides=(1, 1) ) self.conv2 = tf.keras.layers.Conv2D( 102, (1, 1), padding='valid', input_shape=(1, 1, 1, 1280) ) self.softmax = tf.keras.layers.Softmax() def call(self, x): x = self.conv1(x) x = self.avg_pool(x) x = self.conv2(x) x = tf.reshape(x, [1, 102]) x = self.softmax(x) return x my_sequential_model = LastTwoLayers(name="the_model") my_sequential_model.compile(optimizer='sgd', loss='categorical_crossentropy') x = np.random.random((1, 7, 7, 320)) my_sequential_model.predict(x) my_sequential_model.conv1.set_weights([np.transpose(Wc, [1,2,3,0]), Bc]) # x, y, chan_in, chan_out # 1 batch, 7 height, 320 width, 7 channels # 7 height, 1 width, 7 channels, 1280 out channels # 1 height, 320 width, 1280 out channels # 1 Batch, 7 height, 7 width, 320 channels () [This is the input to the layer] # 1 Batch, 7 height, 7 width, 1280 channels (dout) [This is the output of another layer] # We want to transform this so that we rotate the input by 90 degrees W = np.zeros([1, 1, 1280, 102]) my_sequential_model.conv2.set_weights([ W, np.zeros([102]) ]) converter = tf.lite.TFLiteConverter.from_keras_model(my_sequential_model) tflite_model = converter.convert() with open('./examples/v2_1.0_224_truncated/v2_1.0_224_truncated.tflite', 'wb') as f: f.write(tflite_model)
https://github.com/ddkang/zkml
frontend/vite.config.js
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react-swc' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], })
https://github.com/socathie/ZKaggleV2
hardhat/circuits/circuit.circom
pragma circom 2.0.0; include "./model.circom"; include "./utils/cid.circom"; include "./utils/encrypt.circom"; template Main(n) { // private inputs signal input in[n][797*8]; signal input conv2d_weights[3][3][1][4]; signal input conv2d_bias[4]; signal input batch_normalization_a[4]; signal input batch_normalization_b[4]; signal input conv2d_1_weights[3][3][4][16]; signal input conv2d_1_bias[16]; signal input batch_normalization_1_a[16]; signal input batch_normalization_1_b[16]; signal input dense_weights[16][10]; signal input dense_bias[10]; // outputs signal output out[n]; signal output cids[n*2]; signal output hash; // recurring components component pixel[n]; component model[n]; component cid[n]; for (var i = 0; i < n; i++) { model[i] = Model(); pixel[i] = getPixels(); cid[i] = getCid(); for (var i0 = 0; i0 < 797*8; i0++) { pixel[i].in[i0] <== in[i][i0]; cid[i].in[i0] <== in[i][i0]; } // get cid for (var i0 = 0; i0 < 2; i0++) { cids[i*2+i0] <== cid[i].out[i0]; } for (var i0 = 0; i0 < 28; i0++) { for (var i1 = 0; i1 < 28; i1++) { for (var i2 = 0; i2 < 1; i2++) { model[i].in[i0][i1][i2] <== pixel[i].out[i0][i1][i2]; }}} for (var i0 = 0; i0 < 3; i0++) { for (var i1 = 0; i1 < 3; i1++) { for (var i2 = 0; i2 < 1; i2++) { for (var i3 = 0; i3 < 4; i3++) { model[i].conv2d_weights[i0][i1][i2][i3] <== conv2d_weights[i0][i1][i2][i3]; }}}} for (var i0 = 0; i0 < 4; i0++) { model[i].conv2d_bias[i0] <== conv2d_bias[i0]; } for (var i0 = 0; i0 < 4; i0++) { model[i].batch_normalization_a[i0] <== batch_normalization_a[i0]; } for (var i0 = 0; i0 < 4; i0++) { model[i].batch_normalization_b[i0] <== batch_normalization_b[i0]; } for (var i0 = 0; i0 < 3; i0++) { for (var i1 = 0; i1 < 3; i1++) { for (var i2 = 0; i2 < 4; i2++) { for (var i3 = 0; i3 < 16; i3++) { model[i].conv2d_1_weights[i0][i1][i2][i3] <== conv2d_1_weights[i0][i1][i2][i3]; }}}} for (var i0 = 0; i0 < 16; i0++) { model[i].conv2d_1_bias[i0] <== conv2d_1_bias[i0]; } for (var i0 = 0; i0 < 16; i0++) { model[i].batch_normalization_1_a[i0] <== batch_normalization_1_a[i0]; } for (var i0 = 0; i0 < 16; i0++) { model[i].batch_normalization_1_b[i0] <== batch_normalization_1_b[i0]; } for (var i0 = 0; i0 < 16; i0++) { for (var i1 = 0; i1 < 10; i1++) { model[i].dense_weights[i0][i1] <== dense_weights[i0][i1]; }} for (var i0 = 0; i0 < 10; i0++) { model[i].dense_bias[i0] <== dense_bias[i0]; } out[i] <== model[i].out[0]; } // hash model weights component mimc = hash1000(); var idx = 0; for (var i0 = 0; i0 < 3; i0++) { for (var i1 = 0; i1 < 3; i1++) { for (var i2 = 0; i2 < 1; i2++) { for (var i3 = 0; i3 < 4; i3++) { mimc.in[idx] <== conv2d_weights[i0][i1][i2][i3]; idx++; }}}} for (var i0 = 0; i0 < 4; i0++) { mimc.in[idx] <== conv2d_bias[i0]; idx++; } for (var i0 = 0; i0 < 4; i0++) { mimc.in[idx] <== batch_normalization_a[i0]; idx++; } for (var i0 = 0; i0 < 4; i0++) { mimc.in[idx] <== batch_normalization_b[i0]; idx++; } for (var i0 = 0; i0 < 3; i0++) { for (var i1 = 0; i1 < 3; i1++) { for (var i2 = 0; i2 < 4; i2++) { for (var i3 = 0; i3 < 16; i3++) { mimc.in[idx] <== conv2d_1_weights[i0][i1][i2][i3]; idx++; }}}} for (var i0 = 0; i0 < 16; i0++) { mimc.in[idx] <== conv2d_1_bias[i0]; idx++; } for (var i0 = 0; i0 < 16; i0++) { mimc.in[idx] <== batch_normalization_1_a[i0]; idx++; } for (var i0 = 0; i0 < 16; i0++) { mimc.in[idx] <== batch_normalization_1_b[i0]; idx++; } for (var i0 = 0; i0 < 16; i0++) { for (var i1 = 0; i1 < 10; i1++) { mimc.in[idx] <== dense_weights[i0][i1]; idx++; }} for (var i0 = 0; i0 < 10; i0++) { mimc.in[idx] <== dense_bias[i0]; idx++; } // padding for (var i = idx; i < 1000; i++) { mimc.in[i] <== 0; } hash <== mimc.out; } component main = Main(10);
https://github.com/socathie/ZKaggleV2
hardhat/circuits/encryption.circom
pragma circom 2.0.0; include "./utils/encrypt.circom"; template Main() { // public inputs signal input public_key[2]; // private inputs signal input in[1000]; // zero-padded at the end signal input private_key; // outputs signal output hash; signal output shared_key; signal output out[1001]; component hasher = hash1000(); component enc = encrypt1000(); enc.public_key[0] <== public_key[0]; enc.public_key[1] <== public_key[1]; enc.private_key <== private_key; for (var i = 0; i < 1000; i++) { hasher.in[i] <== in[i]; enc.in[i] <== in[i]; } hash <== hasher.out; shared_key <== enc.shared_key; for (var i = 0; i < 1001; i++) { out[i] <== enc.out[i]; } } component main { public [ public_key ] } = Main();
https://github.com/socathie/ZKaggleV2
hardhat/circuits/model.circom
pragma circom 2.0.0; include "../node_modules/circomlib-ml/circuits/BatchNormalization2D.circom"; include "../node_modules/circomlib-ml/circuits/Dense.circom"; include "../node_modules/circomlib-ml/circuits/Conv2D.circom"; include "../node_modules/circomlib-ml/circuits/AveragePooling2D.circom"; include "../node_modules/circomlib-ml/circuits/ArgMax.circom"; include "../node_modules/circomlib-ml/circuits/Poly.circom"; include "../node_modules/circomlib-ml/circuits/GlobalAveragePooling2D.circom"; template Model() { signal input in[28][28][1]; signal input conv2d_weights[3][3][1][4]; signal input conv2d_bias[4]; signal input batch_normalization_a[4]; signal input batch_normalization_b[4]; signal input conv2d_1_weights[3][3][4][16]; signal input conv2d_1_bias[16]; signal input batch_normalization_1_a[16]; signal input batch_normalization_1_b[16]; signal input dense_weights[16][10]; signal input dense_bias[10]; signal output out[1]; component conv2d = Conv2D(28, 28, 1, 4, 3, 1); component batch_normalization = BatchNormalization2D(26, 26, 4); component lambda[26][26][4]; for (var i0 = 0; i0 < 26; i0++) { for (var i1 = 0; i1 < 26; i1++) { for (var i2 = 0; i2 < 4; i2++) { lambda[i0][i1][i2] = Poly(1000000); }}} component average_pooling2d = AveragePooling2D(26, 26, 4, 2, 2, 250); component conv2d_1 = Conv2D(13, 13, 4, 16, 3, 1); component batch_normalization_1 = BatchNormalization2D(11, 11, 16); component lambda_1[11][11][16]; for (var i0 = 0; i0 < 11; i0++) { for (var i1 = 0; i1 < 11; i1++) { for (var i2 = 0; i2 < 16; i2++) { lambda_1[i0][i1][i2] = Poly(1000000000000000000000); }}} component average_pooling2d_1 = AveragePooling2D(11, 11, 16, 2, 2, 250); component global_average_pooling2d = GlobalAveragePooling2D(5, 5, 16, 40); component dense = Dense(16, 10); component softmax = ArgMax(10); for (var i0 = 0; i0 < 28; i0++) { for (var i1 = 0; i1 < 28; i1++) { for (var i2 = 0; i2 < 1; i2++) { conv2d.in[i0][i1][i2] <== in[i0][i1][i2]; }}} for (var i0 = 0; i0 < 3; i0++) { for (var i1 = 0; i1 < 3; i1++) { for (var i2 = 0; i2 < 1; i2++) { for (var i3 = 0; i3 < 4; i3++) { conv2d.weights[i0][i1][i2][i3] <== conv2d_weights[i0][i1][i2][i3]; }}}} for (var i0 = 0; i0 < 4; i0++) { conv2d.bias[i0] <== conv2d_bias[i0]; } for (var i0 = 0; i0 < 26; i0++) { for (var i1 = 0; i1 < 26; i1++) { for (var i2 = 0; i2 < 4; i2++) { batch_normalization.in[i0][i1][i2] <== conv2d.out[i0][i1][i2]; }}} for (var i0 = 0; i0 < 4; i0++) { batch_normalization.a[i0] <== batch_normalization_a[i0]; } for (var i0 = 0; i0 < 4; i0++) { batch_normalization.b[i0] <== batch_normalization_b[i0]; } for (var i0 = 0; i0 < 26; i0++) { for (var i1 = 0; i1 < 26; i1++) { for (var i2 = 0; i2 < 4; i2++) { lambda[i0][i1][i2].in <== batch_normalization.out[i0][i1][i2]; }}} for (var i0 = 0; i0 < 26; i0++) { for (var i1 = 0; i1 < 26; i1++) { for (var i2 = 0; i2 < 4; i2++) { average_pooling2d.in[i0][i1][i2] <== lambda[i0][i1][i2].out; }}} for (var i0 = 0; i0 < 13; i0++) { for (var i1 = 0; i1 < 13; i1++) { for (var i2 = 0; i2 < 4; i2++) { conv2d_1.in[i0][i1][i2] <== average_pooling2d.out[i0][i1][i2]; }}} for (var i0 = 0; i0 < 3; i0++) { for (var i1 = 0; i1 < 3; i1++) { for (var i2 = 0; i2 < 4; i2++) { for (var i3 = 0; i3 < 16; i3++) { conv2d_1.weights[i0][i1][i2][i3] <== conv2d_1_weights[i0][i1][i2][i3]; }}}} for (var i0 = 0; i0 < 16; i0++) { conv2d_1.bias[i0] <== conv2d_1_bias[i0]; } for (var i0 = 0; i0 < 11; i0++) { for (var i1 = 0; i1 < 11; i1++) { for (var i2 = 0; i2 < 16; i2++) { batch_normalization_1.in[i0][i1][i2] <== conv2d_1.out[i0][i1][i2]; }}} for (var i0 = 0; i0 < 16; i0++) { batch_normalization_1.a[i0] <== batch_normalization_1_a[i0]; } for (var i0 = 0; i0 < 16; i0++) { batch_normalization_1.b[i0] <== batch_normalization_1_b[i0]; } for (var i0 = 0; i0 < 11; i0++) { for (var i1 = 0; i1 < 11; i1++) { for (var i2 = 0; i2 < 16; i2++) { lambda_1[i0][i1][i2].in <== batch_normalization_1.out[i0][i1][i2]; }}} for (var i0 = 0; i0 < 11; i0++) { for (var i1 = 0; i1 < 11; i1++) { for (var i2 = 0; i2 < 16; i2++) { average_pooling2d_1.in[i0][i1][i2] <== lambda_1[i0][i1][i2].out; }}} for (var i0 = 0; i0 < 5; i0++) { for (var i1 = 0; i1 < 5; i1++) { for (var i2 = 0; i2 < 16; i2++) { global_average_pooling2d.in[i0][i1][i2] <== average_pooling2d_1.out[i0][i1][i2]; }}} for (var i0 = 0; i0 < 16; i0++) { dense.in[i0] <== global_average_pooling2d.out[i0]; } for (var i0 = 0; i0 < 16; i0++) { for (var i1 = 0; i1 < 10; i1++) { dense.weights[i0][i1] <== dense_weights[i0][i1]; }} for (var i0 = 0; i0 < 10; i0++) { dense.bias[i0] <== dense_bias[i0]; } for (var i0 = 0; i0 < 10; i0++) { softmax.in[i0] <== dense.out[i0]; } out[0] <== softmax.out; }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/ch.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ /* Ch 000 0 001 1 010 0 011 1 100 0 101 0 110 1 111 1 out = a&b ^ (!a)&c => out = a*(b-c) + c */ pragma circom 2.0.0; template Ch_t(n) { signal input a[n]; signal input b[n]; signal input c[n]; signal output out[n]; for (var k=0; k<n; k++) { out[k] <== a[k] * (b[k]-c[k]) + c[k]; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/constants.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ pragma circom 2.0.0; template H(x) { signal output out[32]; var c[8] = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; for (var i=0; i<32; i++) { out[i] <== (c[x] >> i) & 1; } } template K(x) { signal output out[32]; var c[64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; for (var i=0; i<32; i++) { out[i] <== (c[x] >> i) & 1; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/main.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ pragma circom 2.0.0; include "sha256_2.circom"; template Main() { signal input a; signal input b; signal output out; component sha256_2 = Sha256_2(); sha256_2.a <== a; sha256_2.b <== a; out <== sha256_2.out; } component main = Main();
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/maj.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ /* Maj function for sha256 out = a&b ^ a&c ^ b&c => out = a*b + a*c + b*c - 2*a*b*c => out = a*( b + c - 2*b*c ) + b*c => mid = b*c out = a*( b + c - 2*mid ) + mid */ pragma circom 2.0.0; template Maj_t(n) { signal input a[n]; signal input b[n]; signal input c[n]; signal output out[n]; signal mid[n]; for (var k=0; k<n; k++) { mid[k] <== b[k]*c[k]; out[k] <== a[k] * (b[k]+c[k]-2*mid[k]) + mid[k]; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/rotate.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ pragma circom 2.0.0; template RotR(n, r) { signal input in[n]; signal output out[n]; for (var i=0; i<n; i++) { out[i] <== in[ (i+r)%n ]; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/sha256.circom
pragma circom 2.0.0; include "constants.circom"; include "sha256compression.circom"; template Sha256(nBits) { signal input in[nBits]; signal output out[256]; var i; var k; var nBlocks; var bitsLastBlock; nBlocks = ((nBits + 64)\512)+1; signal paddedIn[nBlocks*512]; for (k=0; k<nBits; k++) { paddedIn[k] <== in[k]; } paddedIn[nBits] <== 1; for (k=nBits+1; k<nBlocks*512-64; k++) { paddedIn[k] <== 0; } for (k = 0; k< 64; k++) { paddedIn[nBlocks*512 - k -1] <== (nBits >> k)&1; } component ha0 = H(0); component hb0 = H(1); component hc0 = H(2); component hd0 = H(3); component he0 = H(4); component hf0 = H(5); component hg0 = H(6); component hh0 = H(7); component sha256compression[nBlocks]; for (i=0; i<nBlocks; i++) { sha256compression[i] = Sha256compression() ; if (i==0) { for (k=0; k<32; k++ ) { sha256compression[i].hin[0*32+k] <== ha0.out[k]; sha256compression[i].hin[1*32+k] <== hb0.out[k]; sha256compression[i].hin[2*32+k] <== hc0.out[k]; sha256compression[i].hin[3*32+k] <== hd0.out[k]; sha256compression[i].hin[4*32+k] <== he0.out[k]; sha256compression[i].hin[5*32+k] <== hf0.out[k]; sha256compression[i].hin[6*32+k] <== hg0.out[k]; sha256compression[i].hin[7*32+k] <== hh0.out[k]; } } else { for (k=0; k<32; k++ ) { sha256compression[i].hin[32*0+k] <== sha256compression[i-1].out[32*0+31-k]; sha256compression[i].hin[32*1+k] <== sha256compression[i-1].out[32*1+31-k]; sha256compression[i].hin[32*2+k] <== sha256compression[i-1].out[32*2+31-k]; sha256compression[i].hin[32*3+k] <== sha256compression[i-1].out[32*3+31-k]; sha256compression[i].hin[32*4+k] <== sha256compression[i-1].out[32*4+31-k]; sha256compression[i].hin[32*5+k] <== sha256compression[i-1].out[32*5+31-k]; sha256compression[i].hin[32*6+k] <== sha256compression[i-1].out[32*6+31-k]; sha256compression[i].hin[32*7+k] <== sha256compression[i-1].out[32*7+31-k]; } } for (k=0; k<512; k++) { sha256compression[i].inp[k] <== paddedIn[i*512+k]; } } for (k=0; k<256; k++) { out[k] <== sha256compression[nBlocks-1].out[k]; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/sha256_2.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ pragma circom 2.0.0; include "constants.circom"; include "sha256compression.circom"; include "../../node_modules/circomlib-ml/circuits/circomlib/bitify.circom"; template Sha256_2() { signal input a; signal input b; signal output out; var i; var k; component bits2num = Bits2Num(216); component num2bits[2]; num2bits[0] = Num2Bits(216); num2bits[1] = Num2Bits(216); num2bits[0].in <== a; num2bits[1].in <== b; component sha256compression = Sha256compression() ; component ha0 = H(0); component hb0 = H(1); component hc0 = H(2); component hd0 = H(3); component he0 = H(4); component hf0 = H(5); component hg0 = H(6); component hh0 = H(7); for (k=0; k<32; k++ ) { sha256compression.hin[0*32+k] <== ha0.out[k]; sha256compression.hin[1*32+k] <== hb0.out[k]; sha256compression.hin[2*32+k] <== hc0.out[k]; sha256compression.hin[3*32+k] <== hd0.out[k]; sha256compression.hin[4*32+k] <== he0.out[k]; sha256compression.hin[5*32+k] <== hf0.out[k]; sha256compression.hin[6*32+k] <== hg0.out[k]; sha256compression.hin[7*32+k] <== hh0.out[k]; } for (i=0; i<216; i++) { sha256compression.inp[i] <== num2bits[0].out[215-i]; sha256compression.inp[i+216] <== num2bits[1].out[215-i]; } sha256compression.inp[432] <== 1; for (i=433; i<503; i++) { sha256compression.inp[i] <== 0; } sha256compression.inp[503] <== 1; sha256compression.inp[504] <== 1; sha256compression.inp[505] <== 0; sha256compression.inp[506] <== 1; sha256compression.inp[507] <== 1; sha256compression.inp[508] <== 0; sha256compression.inp[509] <== 0; sha256compression.inp[510] <== 0; sha256compression.inp[511] <== 0; for (i=0; i<216; i++) { bits2num.in[i] <== sha256compression.out[255-i]; } out <== bits2num.out; }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/sha256compression.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ pragma circom 2.0.0; include "constants.circom"; include "t1.circom"; include "t2.circom"; include "../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom"; include "sigmaplus.circom"; include "sha256compression_function.circom"; template Sha256compression() { signal input hin[256]; signal input inp[512]; signal output out[256]; signal a[65][32]; signal b[65][32]; signal c[65][32]; signal d[65][32]; signal e[65][32]; signal f[65][32]; signal g[65][32]; signal h[65][32]; signal w[64][32]; var outCalc[256] = sha256compression(hin, inp); var i; for (i=0; i<256; i++) out[i] <-- outCalc[i]; component sigmaPlus[48]; for (i=0; i<48; i++) sigmaPlus[i] = SigmaPlus(); component ct_k[64]; for (i=0; i<64; i++) ct_k[i] = K(i); component t1[64]; for (i=0; i<64; i++) t1[i] = T1(); component t2[64]; for (i=0; i<64; i++) t2[i] = T2(); component suma[64]; for (i=0; i<64; i++) suma[i] = BinSum(32, 2); component sume[64]; for (i=0; i<64; i++) sume[i] = BinSum(32, 2); component fsum[8]; for (i=0; i<8; i++) fsum[i] = BinSum(32, 2); var k; var t; for (t=0; t<64; t++) { if (t<16) { for (k=0; k<32; k++) { w[t][k] <== inp[t*32+31-k]; } } else { for (k=0; k<32; k++) { sigmaPlus[t-16].in2[k] <== w[t-2][k]; sigmaPlus[t-16].in7[k] <== w[t-7][k]; sigmaPlus[t-16].in15[k] <== w[t-15][k]; sigmaPlus[t-16].in16[k] <== w[t-16][k]; } for (k=0; k<32; k++) { w[t][k] <== sigmaPlus[t-16].out[k]; } } } for (k=0; k<32; k++ ) { a[0][k] <== hin[k]; b[0][k] <== hin[32*1 + k]; c[0][k] <== hin[32*2 + k]; d[0][k] <== hin[32*3 + k]; e[0][k] <== hin[32*4 + k]; f[0][k] <== hin[32*5 + k]; g[0][k] <== hin[32*6 + k]; h[0][k] <== hin[32*7 + k]; } for (t = 0; t<64; t++) { for (k=0; k<32; k++) { t1[t].h[k] <== h[t][k]; t1[t].e[k] <== e[t][k]; t1[t].f[k] <== f[t][k]; t1[t].g[k] <== g[t][k]; t1[t].k[k] <== ct_k[t].out[k]; t1[t].w[k] <== w[t][k]; t2[t].a[k] <== a[t][k]; t2[t].b[k] <== b[t][k]; t2[t].c[k] <== c[t][k]; } for (k=0; k<32; k++) { sume[t].in[0][k] <== d[t][k]; sume[t].in[1][k] <== t1[t].out[k]; suma[t].in[0][k] <== t1[t].out[k]; suma[t].in[1][k] <== t2[t].out[k]; } for (k=0; k<32; k++) { h[t+1][k] <== g[t][k]; g[t+1][k] <== f[t][k]; f[t+1][k] <== e[t][k]; e[t+1][k] <== sume[t].out[k]; d[t+1][k] <== c[t][k]; c[t+1][k] <== b[t][k]; b[t+1][k] <== a[t][k]; a[t+1][k] <== suma[t].out[k]; } } for (k=0; k<32; k++) { fsum[0].in[0][k] <== hin[32*0+k]; fsum[0].in[1][k] <== a[64][k]; fsum[1].in[0][k] <== hin[32*1+k]; fsum[1].in[1][k] <== b[64][k]; fsum[2].in[0][k] <== hin[32*2+k]; fsum[2].in[1][k] <== c[64][k]; fsum[3].in[0][k] <== hin[32*3+k]; fsum[3].in[1][k] <== d[64][k]; fsum[4].in[0][k] <== hin[32*4+k]; fsum[4].in[1][k] <== e[64][k]; fsum[5].in[0][k] <== hin[32*5+k]; fsum[5].in[1][k] <== f[64][k]; fsum[6].in[0][k] <== hin[32*6+k]; fsum[6].in[1][k] <== g[64][k]; fsum[7].in[0][k] <== hin[32*7+k]; fsum[7].in[1][k] <== h[64][k]; } for (k=0; k<32; k++) { out[31-k] === fsum[0].out[k]; out[32+31-k] === fsum[1].out[k]; out[64+31-k] === fsum[2].out[k]; out[96+31-k] === fsum[3].out[k]; out[128+31-k] === fsum[4].out[k]; out[160+31-k] === fsum[5].out[k]; out[192+31-k] === fsum[6].out[k]; out[224+31-k] === fsum[7].out[k]; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/sha256compression_function.circom
// signal input hin[256]; // signal input inp[512]; // signal output out[256]; pragma circom 2.0.0; function rrot(x, n) { return ((x >> n) | (x << (32-n))) & 0xFFFFFFFF; } function bsigma0(x) { return rrot(x,2) ^ rrot(x,13) ^ rrot(x,22); } function bsigma1(x) { return rrot(x,6) ^ rrot(x,11) ^ rrot(x,25); } function ssigma0(x) { return rrot(x,7) ^ rrot(x,18) ^ (x >> 3); } function ssigma1(x) { return rrot(x,17) ^ rrot(x,19) ^ (x >> 10); } function Maj(x, y, z) { return (x&y) ^ (x&z) ^ (y&z); } function Ch(x, y, z) { return (x & y) ^ ((0xFFFFFFFF ^x) & z); } function sha256K(i) { var k[64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; return k[i]; } function sha256compression(hin, inp) { var H[8]; var a; var b; var c; var d; var e; var f; var g; var h; var out[256]; for (var i=0; i<8; i++) { H[i] = 0; for (var j=0; j<32; j++) { H[i] += hin[i*32+j] << j; } } a=H[0]; b=H[1]; c=H[2]; d=H[3]; e=H[4]; f=H[5]; g=H[6]; h=H[7]; var w[64]; var T1; var T2; for (var i=0; i<64; i++) { if (i<16) { w[i]=0; for (var j=0; j<32; j++) { w[i] += inp[i*32+31-j]<<j; } } else { w[i] = (ssigma1(w[i-2]) + w[i-7] + ssigma0(w[i-15]) + w[i-16]) & 0xFFFFFFFF; } T1 = (h + bsigma1(e) + Ch(e,f,g) + sha256K(i) + w[i]) & 0xFFFFFFFF; T2 = (bsigma0(a) + Maj(a,b,c)) & 0xFFFFFFFF; h=g; g=f; f=e; e=(d+T1) & 0xFFFFFFFF; d=c; c=b; b=a; a=(T1+T2) & 0xFFFFFFFF; } H[0] = H[0] + a; H[1] = H[1] + b; H[2] = H[2] + c; H[3] = H[3] + d; H[4] = H[4] + e; H[5] = H[5] + f; H[6] = H[6] + g; H[7] = H[7] + h; for (var i=0; i<8; i++) { for (var j=0; j<32; j++) { out[i*32+31-j] = (H[i] >> j) & 1; } } return out; }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/shift.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ pragma circom 2.0.0; template ShR(n, r) { signal input in[n]; signal output out[n]; for (var i=0; i<n; i++) { if (i+r >= n) { out[i] <== 0; } else { out[i] <== in[ i+r ]; } } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/sigma.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ pragma circom 2.0.0; include "xor3.circom"; include "rotate.circom"; include "shift.circom"; template SmallSigma(ra, rb, rc) { signal input in[32]; signal output out[32]; var k; component rota = RotR(32, ra); component rotb = RotR(32, rb); component shrc = ShR(32, rc); for (k=0; k<32; k++) { rota.in[k] <== in[k]; rotb.in[k] <== in[k]; shrc.in[k] <== in[k]; } component xor3 = Xor3(32); for (k=0; k<32; k++) { xor3.a[k] <== rota.out[k]; xor3.b[k] <== rotb.out[k]; xor3.c[k] <== shrc.out[k]; } for (k=0; k<32; k++) { out[k] <== xor3.out[k]; } } template BigSigma(ra, rb, rc) { signal input in[32]; signal output out[32]; var k; component rota = RotR(32, ra); component rotb = RotR(32, rb); component rotc = RotR(32, rc); for (k=0; k<32; k++) { rota.in[k] <== in[k]; rotb.in[k] <== in[k]; rotc.in[k] <== in[k]; } component xor3 = Xor3(32); for (k=0; k<32; k++) { xor3.a[k] <== rota.out[k]; xor3.b[k] <== rotb.out[k]; xor3.c[k] <== rotc.out[k]; } for (k=0; k<32; k++) { out[k] <== xor3.out[k]; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/sigmaplus.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ pragma circom 2.0.0; include "../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom"; include "sigma.circom"; template SigmaPlus() { signal input in2[32]; signal input in7[32]; signal input in15[32]; signal input in16[32]; signal output out[32]; var k; component sigma1 = SmallSigma(17,19,10); component sigma0 = SmallSigma(7, 18, 3); for (k=0; k<32; k++) { sigma1.in[k] <== in2[k]; sigma0.in[k] <== in15[k]; } component sum = BinSum(32, 4); for (k=0; k<32; k++) { sum.in[0][k] <== sigma1.out[k]; sum.in[1][k] <== in7[k]; sum.in[2][k] <== sigma0.out[k]; sum.in[3][k] <== in16[k]; } for (k=0; k<32; k++) { out[k] <== sum.out[k]; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/t1.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ pragma circom 2.0.0; include "../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom"; include "sigma.circom"; include "ch.circom"; template T1() { signal input h[32]; signal input e[32]; signal input f[32]; signal input g[32]; signal input k[32]; signal input w[32]; signal output out[32]; var ki; component ch = Ch_t(32); component bigsigma1 = BigSigma(6, 11, 25); for (ki=0; ki<32; ki++) { bigsigma1.in[ki] <== e[ki]; ch.a[ki] <== e[ki]; ch.b[ki] <== f[ki]; ch.c[ki] <== g[ki]; } component sum = BinSum(32, 5); for (ki=0; ki<32; ki++) { sum.in[0][ki] <== h[ki]; sum.in[1][ki] <== bigsigma1.out[ki]; sum.in[2][ki] <== ch.out[ki]; sum.in[3][ki] <== k[ki]; sum.in[4][ki] <== w[ki]; } for (ki=0; ki<32; ki++) { out[ki] <== sum.out[ki]; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/t2.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ pragma circom 2.0.0; include "../../node_modules/circomlib-ml/circuits/circomlib/binsum.circom"; include "sigma.circom"; include "maj.circom"; template T2() { signal input a[32]; signal input b[32]; signal input c[32]; signal output out[32]; var k; component bigsigma0 = BigSigma(2, 13, 22); component maj = Maj_t(32); for (k=0; k<32; k++) { bigsigma0.in[k] <== a[k]; maj.a[k] <== a[k]; maj.b[k] <== b[k]; maj.c[k] <== c[k]; } component sum = BinSum(32, 2); for (k=0; k<32; k++) { sum.in[0][k] <== bigsigma0.out[k]; sum.in[1][k] <== maj.out[k]; } for (k=0; k<32; k++) { out[k] <== sum.out[k]; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/sha256/xor3.circom
/* Copyright 2018 0KIMS association. This file is part of circom (Zero Knowledge Circuit Compiler). circom is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. circom is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with circom. If not, see <https://www.gnu.org/licenses/>. */ /* Xor3 function for sha256 out = a ^ b ^ c => out = a+b+c - 2*a*b - 2*a*c - 2*b*c + 4*a*b*c => out = a*( 1 - 2*b - 2*c + 4*b*c ) + b + c - 2*b*c => mid = b*c out = a*( 1 - 2*b -2*c + 4*mid ) + b + c - 2 * mid */ pragma circom 2.0.0; template Xor3(n) { signal input a[n]; signal input b[n]; signal input c[n]; signal output out[n]; signal mid[n]; for (var k=0; k<n; k++) { mid[k] <== b[k]*c[k]; out[k] <== a[k] * (1 -2*b[k] -2*c[k] +4*mid[k]) + b[k] + c[k] -2*mid[k]; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/utils/cid.circom
pragma circom 2.0.0; include "../sha256/sha256.circom"; include "../../node_modules/circomlib-ml/circuits/circomlib/bitify.circom"; // convert a 797x8 bit array (pgm) to 28x28x1 array (pixels) template getPixels() { signal input in[797*8]; signal output out[28][28][1]; component pixels[28][28][1]; for (var i=0; i<28; i++) { for (var j=0; j<28; j++) { pixels[i][j][0] = Bits2Num(8); for (var k=0; k<8; k++) { pixels[i][j][0].in[k] <== in[13*8+i*28*8+j*8+k]; // the pgm header is 13 bytes } out[i][j][0] <== pixels[i][j][0].out; } } } // convert a 797x8 bit array (pgm) to the corresponding CID (in two parts) template getCid() { signal input in[797*8]; signal output out[2]; component sha = Sha256(797*8); for (var i=0; i<797*8; i++) { sha.in[i] <== in[i]; } component b2n[2]; for (var i=1; i>=0; i--) { b2n[i] = Bits2Num(128); for (var j=127; j>=0; j--) { b2n[i].in[127-j] <== sha.out[i*128+j]; } out[i] <== b2n[i].out; } }
https://github.com/socathie/ZKaggleV2
hardhat/circuits/utils/encrypt.circom
pragma circom 2.0.0; include "../../node_modules/circomlib-ml/circuits/crypto/encrypt.circom"; include "../../node_modules/circomlib-ml/circuits/crypto/ecdh.circom"; // encrypt 1000 inputs template encrypt1000() { // public inputs signal input public_key[2]; // private inputs signal input in[1000]; signal input private_key; // outputs signal output shared_key; signal output out[1001]; component ecdh = Ecdh(); ecdh.private_key <== private_key; ecdh.public_key[0] <== public_key[0]; ecdh.public_key[1] <== public_key[1]; component enc = EncryptBits(1000); enc.shared_key <== ecdh.shared_key; for (var i = 0; i < 1000; i++) { enc.plaintext[i] <== in[i]; } for (var i = 0; i < 1001; i++) { out[i] <== enc.out[i]; } shared_key <== ecdh.shared_key; } // fixed MultiMiMC7 with 1000 inputs template hash1000() { signal input in[1000]; signal output out; component mimc = MultiMiMC7(1000, 91); mimc.k <== 0; for (var i = 0; i < 1000; i++) { mimc.in[i] <== in[i]; } out <== mimc.out; }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Bounty.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./ICircuitVerifier.sol"; import "./IEncryptionVerifier.sol"; contract Bounty is Initializable, OwnableUpgradeable { uint public completedStep; IEncryptionVerifier public encryptionVerifier; // variables set by bounty provier at Tx 1 (constructor) string public name; string public description; bytes[] public dataCIDs; uint[] public labels; uint public accuracyThreshold; // in percentage // reward amount is not stored, use contract balance instead // variables set by bounty hunter at Tx 2 address public bountyHunter; bytes public zkeyCID; bytes public circomCID; bytes public verifierCID; ICircuitVerifier public verifier; uint[2] public a; uint[2][2] public b; uint[2] public c; uint public modelHash; // variables set by bounty provider at Tx 3 bool public isComplete; uint[2] public publicKeys; // variables set by bounty hunter at Tx 4 uint[1005] public input; uint8 public constant CID_VERSION = 1; uint8 public constant CID_CODEC = 0x55; // for raw buffer uint8 public constant CID_HASH = 0x12; // for sha256 uint8 public constant CID_LENGTH = 32; // for sha256 // ! current design only allows one bounty hunter to submit proof // TODO: allow multiple bounty hunters to submit proof event BountyUpdated(uint step); /* Tx 1 * take owner address from factory * set bounty details * receive native tokens as bounty reward */ function initialize( address _owner, string memory _name, string memory _description, bytes[] memory _dataCIDs, uint[] memory _labels, uint _accuracyThreshold, address _encryptionVerifier ) public payable initializer { require(msg.value > 0, "Bounty reward must be greater than 0"); // length of dataCIDs and labels should be the same require( _dataCIDs.length == _labels.length, "Invalid dataCIDs or labels length" ); __Ownable_init(); transferOwnership(_owner); name = _name; description = _description; dataCIDs = _dataCIDs; labels = _labels; accuracyThreshold = _accuracyThreshold; encryptionVerifier = IEncryptionVerifier(_encryptionVerifier); completedStep = 1; } /* Tx 2: submit bounty * submit CID of zkey, circom * submit verifier address * submit proof */ function submitBounty( bytes memory _zkeyCID, bytes memory _circomCID, bytes memory _verifierCID, address _verifier, uint[2] memory _a, uint[2][2] memory _b, uint[2] memory _c, uint[] memory _input ) public /* * n = dataCIDs.length * first n elements of input should be the model output * the next 2n elements of input should be the splitted dataCIDs * the last element is the model hash */ { require(bountyHunter == address(0), "Bounty already submitted"); // verifier address should not be 0x0 require(_verifier != address(0), "Invalid verifier address"); uint n = dataCIDs.length; require(_input.length == 3 * n + 1, "Invalid input length"); // check if accuracy threshold is met uint numCorrect = 0; for (uint i = 0; i < n; i++) { if (_input[i] == labels[i]) { numCorrect++; } } require( (numCorrect * 100) / n >= accuracyThreshold, "Accuracy threshold not met" ); for (uint i = 0; i < dataCIDs.length; i++) { require( keccak256(dataCIDs[i]) == keccak256( abi.encodePacked( CID_VERSION, CID_CODEC, CID_HASH, CID_LENGTH, concatDigest( _input[n + i * 2], _input[n + i * 2 + 1] ) ) ), "Data CID mismatch" ); } verifier = ICircuitVerifier(_verifier); require(verifier.verifyProof(_a, _b, _c, _input), "Invalid proof"); a = _a; b = _b; c = _c; modelHash = _input[3 * n]; zkeyCID = _zkeyCID; circomCID = _circomCID; verifierCID = _verifierCID; bountyHunter = msg.sender; emit BountyUpdated(2); completedStep = 2; } /* Tx 3: release bounty * only callable by bounty provider * only callable if bounty is not complete * only callable if bounty hunter has submitted proof */ function releaseBounty(uint[2] memory _publicKeys) public onlyOwner { require(!isComplete, "Bounty is already complete"); require(a[0] != 0, "Bounty hunter has not submitted proof"); publicKeys = _publicKeys; isComplete = true; emit BountyUpdated(3); completedStep = 3; } /* Tx 4: claim bounty * function to submit preimage of hashed input * only callable if SHA256 of preimage matched hashed input * only callable if bounty is complete * _input */ function claimBounty( uint[2] memory _a, uint[2][2] memory _b, uint[2] memory _c, uint[1005] memory _input /* * first element is the model hash * the next element is the shared key * the next 1001 elements are the encrypted input * the last 2 elements are the public keys */ ) public { require( msg.sender == bountyHunter, "Only bounty hunter can claim bounty" ); require(isComplete, "Bounty is not complete"); require(address(this).balance > 0, "Bounty already claimed"); // verify model hash require( modelHash == _input[0], "Model hash does not match submitted proof" ); // verify public keys require( publicKeys[0] == _input[1003] && publicKeys[1] == _input[1004], "Public keys do not match" ); // verify encryption require( encryptionVerifier.verifyProof(_a, _b, _c, _input), "Invalid encryption" ); input = _input; payable(msg.sender).transfer(address(this).balance); emit BountyUpdated(4); completedStep = 4; } // function to concat input into digest function concatDigest( uint input1, uint input2 ) public pure returns (bytes32) { return bytes32((input1 << 128) + input2); } // view function to verify proof function verifyProof( uint[2] memory _a, uint[2][2] memory _b, uint[2] memory _c, uint[] memory _input ) public view returns (bool) { return verifier.verifyProof(_a, _b, _c, _input); } // view function to verify encryption function verifyEncryption( uint[2] memory _a, uint[2][2] memory _b, uint[2] memory _c, uint[1005] memory _input ) public view returns (bool) { return encryptionVerifier.verifyProof(_a, _b, _c, _input); } // TODO: function to cancel bounty and withdraw reward // TODO: function to edit bounty details }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/BountyFactory.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; import "./Bounty.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; contract BountyFactory { address public immutable encryptionVerifier; address public immutable bountyTemplate; address[] public bounties; uint public bountyCount; event BountyCreated(address indexed bounty); constructor(address _encryptionVerifier) { encryptionVerifier = _encryptionVerifier; bountyTemplate = address(new Bounty()); } function createBounty( string memory _name, string memory _description, bytes[] memory _dataCIDs, uint[] memory _labels, uint _accuracyThreshold ) public payable returns (address) { require(msg.value > 0, "BountyFactory: must send more than 0 wei to create bounty"); address clone = Clones.clone(bountyTemplate); Bounty(clone).initialize{value: msg.value}( msg.sender, _name, _description, _dataCIDs, _labels, _accuracyThreshold, encryptionVerifier ); bounties.push(clone); emit BountyCreated(clone); bountyCount++; return clone; } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/ICircuitVerifier.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; interface ICircuitVerifier { function verifyProof( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[] memory input ) external view returns (bool); }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/IEncryptionVerifier.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; interface IEncryptionVerifier { function verifyProof( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[1005] memory input ) external view returns (bool); }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Pairing100.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Pairing100 { struct G1Point { uint X; uint Y; } G1Point[101] public vk; constructor() { vk[0] = G1Point(0,0); vk[1] = G1Point( 3066949056198555590635621162084363174762527476622332118327842035011606793952, 2162571409210902214336812509672057078658587427403012932644293527850387519156 ); vk[2] = G1Point( 8488790424014158852808006439223343295226971170088490706045068147193001550599, 15533262107732603341702625683247434142241321708314454154455671678191112358883 ); vk[3] = G1Point( 15498356887658237969202350156895359735754782519547024837768823850341320383276, 18043358128034609114248819170759582834297009296355155153256975697104654277482 ); vk[4] = G1Point( 6567029474530677569488194734194250250570285395463850727851121497011576634627, 1952169722727701625695211431819915372584015014098667009341874426445277275409 ); vk[5] = G1Point( 7983094460044061917184665751343846528917223973727668540609481601054516669380, 13073411943223982722608981931194140929654969432838450821822380279373205694540 ); vk[6] = G1Point( 6235254487603623311509594370074069771036715566675668423360562477653321213694, 16348146029413394893095677470763579440263315501392573505110251361786086111748 ); vk[7] = G1Point( 12126230703813379196905492399911032289157141882681249791742262746221956435664, 21824357088719214382926551780637722669585190256191017503396653466603977666160 ); vk[8] = G1Point( 10613712952540031218381119319419543617541815295229336208011689530011199688535, 4592079294597931003139600470582401940650194077066693677222963213001984771652 ); vk[9] = G1Point( 3911255295243246572381650626618017989180793092410038772879346029962164371222, 20707153197739152432912301139550552920520579590641272006246634774964843219027 ); vk[10] = G1Point( 11892500116628810223727210540182406632392016834847116628237108078905657482121, 14711114067180791500399151644962712269552453743799493074158273490185336020392 ); vk[11] = G1Point( 9183014413227020895002734499598490676394098841236386025615160839774137140858, 9582865320358157815924266045220199184707642207541576610273447728638869402848 ); vk[12] = G1Point( 13892435818247230557011116927971479775033781875296602336601976433383564563228, 14733448935712935443414454397165120382231825236729361587040978447025752552981 ); vk[13] = G1Point( 17401712645354510672876078146418383500681865058306486281552878566762375427257, 20486073793183479284747068769667013438227637945205924637833865634902153972807 ); vk[14] = G1Point( 12542945177566110147515483264178913219335969620393213829679296068703471654263, 14507302716493402635132650456910109213791510706246873554623739152933578354782 ); vk[15] = G1Point( 17262671835229452055040768758779568490937342065764654420598847161477754030825, 8902971187566518627682001128928050354700036485645478563285262811824680312795 ); vk[16] = G1Point( 2517092168115592419226866474026532297002849402135262172105829244870031873767, 5441677800156144741677796942852428248886812324716256833812586939545360386553 ); vk[17] = G1Point( 16352603512600688738155061629075068863201450829351196946082637536789820772324, 18927273847130979134794259223289142814361248364229652488443571874192685947616 ); vk[18] = G1Point( 2180973227235578788710927545110613481031038894649648025035535210348330223155, 3507425497681887054666522686927478472275561239370715484736685279835745443493 ); vk[19] = G1Point( 21060865790233599822231133344591416589146418696172581714008599651157654485577, 11445704792629508009509530745672449871152458786577656651399880869793578183538 ); vk[20] = G1Point( 14962922779924834333807088380732268106533627899319967840459394518301601944902, 12641115320963479719774006201733593283460207791235448771211717531831128631986 ); vk[21] = G1Point( 4186981001816470806980748781585918132583910335167314696545999009872429264973, 17565855649932537025068269231075491026770085614015983747359821562568883706223 ); vk[22] = G1Point( 16312170887333793475640777226722750017815511399203573224417188753987361268062, 14942299556601867394310962262283413205020816495555982640061951999926073906170 ); vk[23] = G1Point( 11116982558963830693347282315846967801531679296436746818272732121331724415720, 5873619496054897441797349224362529314197498237479985364281745701741828890223 ); vk[24] = G1Point( 7022610961304395808415740511844195116328680518742785550228915385939858023878, 3136892863857862871481332688425068826979796665029750363309374645841360217432 ); vk[25] = G1Point( 8157557205265774407360029054875726935492541606165132860923411819480266205728, 81012924889287601351558230557166415960328857029602316655253741163216562264 ); vk[26] = G1Point( 21387183076392014337790811106800278834050500139493358334136872383128902568974, 7314778968936160478301679546290108816508132795495073939210992055620514882950 ); vk[27] = G1Point( 17445370062398000783311321822998675262681592534816043788545673331055581981338, 4675382597784294729649795567482785231305950693131859255309513051178177175147 ); vk[28] = G1Point( 2098486770907856191452018054264372066670081881036141132191766235747034517957, 1815216053155211776578165772337605223514474799477706574780357340295527292101 ); vk[29] = G1Point( 7247597047636474744927667131995247170347121112158565895891458041517309296389, 192163179728062470503970372632568808101844243963511753219985601280107313588 ); vk[30] = G1Point( 9501203604906811513710929504005271216818701558451549918406058132625156622140, 13415551798489062914081927666384545099868303281595275344663896205914217872078 ); vk[31] = G1Point( 8034595547439438515257075919781050926864947386461328816426271763205695561810, 3642829052524533022920002316425451318885679003862750085869559319724420881642 ); vk[32] = G1Point( 7389684095037929207631024101452345138987391705473424971516979116156341370031, 20579346475224820747653673571292546222054464762132703448050660242437987760856 ); vk[33] = G1Point( 1099064042522969917142691337028490131971642761995798870015264529977810129874, 4136739376632161133724827833970087000788767831702190026854456646968400813758 ); vk[34] = G1Point( 15902640373161477583518974310718417505509060791924961343157477459642931778416, 1762478943943949736546872517381831620025398511173518621074233342446251355911 ); vk[35] = G1Point( 9487596420461016268451980893550096361069347323138723495572679418046046688516, 21544892836467812510793690303334485681390117717928076905731274778121908775623 ); vk[36] = G1Point( 5820742566388270780628696340911428355864552004252479310278041095949430795376, 7641545445878583943991373750714475758318324289158901278777701540735262273286 ); vk[37] = G1Point( 12251320072812281522145414395832737970348394787433255591714150097089431407791, 1532779231870484091585282548681946168911463262567902797320995702737440600730 ); vk[38] = G1Point( 10101613659948566217818739071435123184975710593253921139345225712243031098260, 2640636367314325922533248149727739621985364283675597424474610904727340867587 ); vk[39] = G1Point( 5274085047519363354811875262114176759943519780130758450894988285688729358933, 16937296383981904953674801963392439007888700172373626045529133960039399617263 ); vk[40] = G1Point( 3188599184332565193899369748973079401161586075804055427027494260172731823565, 12968148658083523222968587586141447230993399408675687327780669641109440554181 ); vk[41] = G1Point( 6458679214833537132762167352491386830890325825067568504280547744045616578060, 18468430467927738997242809956404712244666634410317213833141099954108019752365 ); vk[42] = G1Point( 20623060804426468927294862308817315019265876115430041233840695215686630451173, 17087264238689414062897963203925434079076282890481053770322544570572170791084 ); vk[43] = G1Point( 13325627203350085472814451732459661888038862533482320269567426702823739329985, 15776877746534956413446522278166863682458481282527146558228748205100102572752 ); vk[44] = G1Point( 21668441582737826762284872544546266101011979954395973562059583274610785704512, 8277583852037002978546735597203532757285123793571816105035644796689659489126 ); vk[45] = G1Point( 8536734248796214979017755496101738844563999731454217385048880639936148506055, 20050543179037705575872012681412619075809416420502779193387785187983159802429 ); vk[46] = G1Point( 11953986823633174213575339280604577641359038793605491295923798560589727371956, 13147634485185373963488944552653926289625401157498385879547759582230194995039 ); vk[47] = G1Point( 1550712004197774641075033256835604628352158352713007226217725635275012226118, 11203299551088982147798422942849790450362141843828509216540844403325585105151 ); vk[48] = G1Point( 18196271432499014695041842961836011055301353978784919923839413819261319730858, 17098246883967118308242007705459913729702320623322185243317557342538873073008 ); vk[49] = G1Point( 11531116823867493145527748839530207312938155107914319337102872641313100242222, 2697631011753785502387459101482062165916413038880404121649035963091673433064 ); vk[50] = G1Point( 19631156064522474229619641610560117574796667466539324323824988031144145984381, 8937425392860060539170803423572257992722753021855554898593023194915230583803 ); vk[51] = G1Point( 18051666508329012801246216448195697328672943604860514259327889529692653255003, 9776962899569029336118636701542682706337611353719012721741705378235920461022 ); vk[52] = G1Point( 11475939723265162413789647159385731316378041455196431353866586443244485875960, 19711286708431892260060507102028877127791309206835055077147368871237918812844 ); vk[53] = G1Point( 11026344553624187160806030841924275695941597805136178910833830083155671710696, 17162259106859976824562173306587249703506336000572176722780992931150003382282 ); vk[54] = G1Point( 18072014661614829050905335947561719081371194373328681685188989976710752519958, 1048774928195049223435951979787210247304656815367952815402170340291203327793 ); vk[55] = G1Point( 3221143767918066976906625234268647838438505710085915094550693082136124954378, 10609209382910755371095430847148428568017844178029295267934890570954490604373 ); vk[56] = G1Point( 18603265763099527508808162560935573442394246009812715067853557618675227114718, 11587922405411678536596695952166816873905254266295729425002776504155871866385 ); vk[57] = G1Point( 10114761011080890155283117352096466322084587359113823233655131129809908439285, 5508807755576750114007448677480215198205054512071101691922034235838061098992 ); vk[58] = G1Point( 9473224577697192182393997942482349654852015982345608217160238854137662694850, 5232619463453481364828566196626075235351370331947090314816487540777930815749 ); vk[59] = G1Point( 5828405670751893034234121115192004049259338974472201883856438484025352454589, 3633323324079227154005083110521782808490892738558883105373813514476535351512 ); vk[60] = G1Point( 9481001625234164910092417433822014284864981517603152850384837599413333732088, 18386678173060928637493215959625252441776561544797402448843069753038309706398 ); vk[61] = G1Point( 364501025358600818780755326403010729029463316682362019677778479288396511819, 10921245151415767613656441640218247912049165999046837003614440575555392502991 ); vk[62] = G1Point( 7412432117223787136546267187474701163839580784868897752482245004405373487816, 14421834339860903299006524733412603591618190844451037914060151606872119869654 ); vk[63] = G1Point( 6758356448748273679612068112965369625648505132685375942552567389525551794313, 18898694627951555492949080550455672542650697400113643917079813065361088117351 ); vk[64] = G1Point( 2232426915296748097728380112764112830256664229981443467879391402850835961005, 17886990959858849028776727028779317010658807731479716471554709099443198391877 ); vk[65] = G1Point( 19386684389754528007206697728725486021492582825389320018808101756896486223763, 5387944841171208361896631485654248835440117619070885391004123093753703767533 ); vk[66] = G1Point( 12647065993168520043526182937209775921405750220974685444664551951358272974493, 13366972599313287188896739755647120252951756955470758833728145978865191885332 ); vk[67] = G1Point( 18787943133831207667822354828276073727409268368355483818755165180933524613843, 14157388513572656930506703772013995574294570155316280419904839453909945513212 ); vk[68] = G1Point( 21524068563373174125502750466662633697416975469194703149213549758771064143806, 19330633973479566265383470717707159202647232323953472749583165647656210689772 ); vk[69] = G1Point( 18382902852942323899973219125400009598490102054273518026407333530852107135564, 5587556133767484044476916396039091505022130703765554879534031897599284695340 ); vk[70] = G1Point( 9606930799644572048804158116652707177514237680732063560098981656270261037968, 5136249659645845922930624684319684098674157523379969261653636459876902241146 ); vk[71] = G1Point( 13552542113314993893290710085750912895320123663026256826131125947307038096408, 709273112699884026311409013166059830376072517342412739277236776866334978888 ); vk[72] = G1Point( 4877695026492837904576447514487946170274766503110664007065051006317417028911, 9446076080426295446536293256688999725548133948518312450170562478729416816073 ); vk[73] = G1Point( 7745407439919264073462666166103574869059650004645099967253653215503500518730, 8958000654601464310040236040720076000298815451674171928370656192395821571291 ); vk[74] = G1Point( 18666320048773366090983312937110187453777592458193442257099376708416358364469, 5539513286001813732779693880109891933912857627313433936315887072372257898800 ); vk[75] = G1Point( 17762000693904052174149226238971528607238820505142737089093305569141218095604, 21813189192876658164580671884381389056637414147229002438166607672106061685075 ); vk[76] = G1Point( 10620403668573083681678811832492214395842703160132031753632193443445132940858, 9287214924394327270674892448424295944430582227602780738386553108169870248604 ); vk[77] = G1Point( 3225723314799122490693549255900886936628936604463053909144327405767083517367, 13296795156783832061321769403471090730204694557283869635175430523261252422880 ); vk[78] = G1Point( 19394283269851765166190520453710260933464736369229146491483414402572036649235, 8886347394143457971098959915862183096606640244332501467928584161268657741540 ); vk[79] = G1Point( 11211101631546988901713127520653099409246632641328196192389635621453268719604, 7533450628229590941864952327666728681554006380658922550113985739199255638676 ); vk[80] = G1Point( 20281375053270705107000390143308705274685813353750898370539071869251555616918, 4191504470134081448832429650265903916036318956937686405591767766612018536246 ); vk[81] = G1Point( 21730429297217903457297617624317163698633779108372279268294203214963841239599, 3455168649241599958364434680402533707717293629319160914142901270957667623322 ); vk[82] = G1Point( 3733487430670068762717150810067800653321114341709315796018436370189955345854, 16993516290835476757984075812093517551647545212347461054793061694546089118405 ); vk[83] = G1Point( 4069347453305835841899489561884027971507987034637139177752057964697523071884, 1956678427081338497880770997396896779466225278969197692269889397339747587977 ); vk[84] = G1Point( 12688563169962246380429505363810909719278960011517597178276847596058759674530, 2927641600345355068914853681494591852216028218422911788003225244122043842764 ); vk[85] = G1Point( 4455557144275882809490589083576310491054371424484637119621439376441819761829, 9731487948258565288497893143140566785594886936141150696674322531881129525085 ); vk[86] = G1Point( 2619477629022801354541827825039395847140273659251589045546247153678969401001, 17836540777608540858002712754656630392833096079100756487601556239085848528635 ); vk[87] = G1Point( 17062191534864932254047439130752387946329235277076184342923625213771678836935, 12069527596907551270256200398919523423277992112424100276678513119084727281716 ); vk[88] = G1Point( 16805402258218753489165124144746360879274608960953677668700957483879628729815, 10410789682524022432691807145340097146023648177608444718821101447661767567785 ); vk[89] = G1Point( 8008007635828919944721498889155253916141351807179483997112773450223661089031, 3056216602318722957626231548277738119817129937156384969718806681210818813385 ); vk[90] = G1Point( 17667744232917991611151306720567572212556922769873510455013405323308378680476, 2890516289406621384766044747643579791042650014890801167964314867977213603626 ); vk[91] = G1Point( 3143780756554946361446807874127330304332880216504691698401282667783892825765, 5028022739746074390415051300734944677415023517308139648614267686230087830490 ); vk[92] = G1Point( 4441632139452511774754687310993428522463840333562308532916275348517874568273, 3805657638938374125360055067937180653723886063939263403849322700999001648464 ); vk[93] = G1Point( 3013746618735534923159878225091501634239528953276121826823488677950608530535, 13303028874453780721063879979526033805375485792805017809758536559366914354384 ); vk[94] = G1Point( 147897481815608548178330421825812162733090109575127779417863797051852392003, 8640707092187677945028587417279452926189344446161983387648630388517595059973 ); vk[95] = G1Point( 2577256613690079498068095765293720593058588557523481248270938666627067239265, 557967286957109878996836148405729465277762109969903801336199294077387543421 ); vk[96] = G1Point( 8686488647634619838672230770846132946046686268388456771190560796889050807187, 9655938106080828371789874989347293139151622023273311610492266716485237742652 ); vk[97] = G1Point( 16599968643048917866313339039047045832907766174850659964114094763810732985169, 12352676869643809540552538084233558931904841866746829566346313116816615110547 ); vk[98] = G1Point( 9267573706827759556576977525684723234253097476251745496874796559184732114237, 19587468868070611863092114139198146359967042685205673652032650844827081496187 ); vk[99] = G1Point( 11705191676975146315944183303161754911767575431964910047638549236413625571714, 8095106176974497014713170771085910822558210350216200986553411154835804708953 ); vk[100] = G1Point( 5280447958522165271753443781707956962932493679043298614057258828764744713115, 2950965016195187402652016874997101060634411125365212216271760448064603541692 ); } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Pairing1000.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Pairing1000 { struct G1Point { uint X; uint Y; } G1Point[106] public vk; constructor() { vk[0] = G1Point( 19391891390609481429849774145579503985374912055370046060106347963180567737648, 7728129834219170358551601609946089408272789276196019291377633982082964264714 ); vk[1] = G1Point( 228181717483219631881657075204725935385048273455808643893243197164559350421, 15508572652012038327422985835367154161109393774231544670603904898987703339046 ); vk[2] = G1Point( 16754121749542176817018561144730772493675261004204649097804584067550029429764, 17198634116191727394680940996772782519853632044920636906274502553914565398533 ); vk[3] = G1Point( 17957826624334676365790727934855184468288134758298197553821849563875784518295, 11406944883794382503312535656888338714736169159186960939240866611040057953907 ); vk[4] = G1Point( 4430494423928001497300523686255609706462362613573142892959836577073966586667, 13162682470663696321459107672743862398804392623617041025907097398229531565530 ); vk[5] = G1Point( 14257009587274680131434329887478603228568836644077894222628586460501309457074, 11646274224080018681410242920703798265921447377022922965379193380569262526301 ); vk[6] = G1Point( 9705958142725732334171292951895582262453103495226515030924122300318445171445, 13694782303955607160992526693851231852459773108619276337185038380591985756496 ); vk[7] = G1Point( 17144012643506768456362242707497029877693906598559317669357981307632003015152, 11530719059110160059659430237719853818953715174794303473948058261774712009985 ); vk[8] = G1Point( 14483890631953705848041353681278392175692989931587713018682235387322135726786, 17427021586348812404499081252639576599520587094666536022623220701285350530468 ); vk[9] = G1Point( 17889382316777192599293408639688887991696476616460947563545460888753944231405, 20352775334017958538073502200757565414898846974625645781257112656447740307043 ); vk[10] = G1Point( 5951262494284676135349496221747578090299959473645061787220637810949004073376, 14922032753898924330673643869866676805069688661209194494635965419171158760589 ); vk[11] = G1Point( 14157110821921252447764389098290770100004176856427647780277344609571231620687, 20709704698226862108207042948311273224238835582484024370305399265471877818695 ); vk[12] = G1Point( 7728759661843518063486549138063376271515204045617668507188211998990686355923, 10711743748251684178249009586963144563210034088884838210857401639959975316833 ); vk[13] = G1Point( 2651390927031831475551158402902979685807224853052037975527524295438342728413, 11004334363823378697748692777964374325632053561615011779936484804038418721791 ); vk[14] = G1Point( 8246811305647017907134069673379285161957161889986106809441259650967328678244, 20494711448810555007005264172937271620975611130788125438879019136802800991047 ); vk[15] = G1Point( 9227237815575743955536388616372607676700984624496162638091113803457981055424, 7490146127910565474405078546634898959685582216342077796995152448422625084147 ); vk[16] = G1Point( 14988255449888576466983686333725846498816266130898987208151466403609279975637, 171153654716536684403810039714768984905610497645997537317020641135452111030 ); vk[17] = G1Point( 4313051815878873447335298243871896526283302009812695687199895781635541219892, 18022206114946361755183429638924181803457754841419074711392713576527324416177 ); vk[18] = G1Point( 12596501053628393984644163774187853284269767174172592557301269012245428487146, 21204447263079063745466366206201043101439752606465213007704313903164357344632 ); vk[19] = G1Point( 4130034343055488361685767779382955857974023520998228920193364089842314664441, 8542303792250873618267744068827215642358232542234575387855251882269356769896 ); vk[20] = G1Point( 6874451393411262130192832783491921955806954538787269105471079063336949779335, 6461933848170403547021264180029668962878963209941514169961510428223244909955 ); vk[21] = G1Point( 14446083874196363503105045557966370866184469389586599702851903416345637521014, 3794939657763066492124405264096579882646447937001202207430292939220594903055 ); vk[22] = G1Point( 12619429072171004657585865286806128551255324771581379374115006053003312336296, 19034585709515568979275882623176869138315316932867345905842355860246882800271 ); vk[23] = G1Point( 9587228225561280563242073506877752354490385404177352841706335890979927900938, 13956343537392811329003855132730055606205214193873442646494391935942884829436 ); vk[24] = G1Point( 20101337934907004002377597083705994838193569275135806876517069383194438778874, 11932388712951261352094258210650491031751658096692447547561800199948408982592 ); vk[25] = G1Point( 4864969763814313389538966758485110878780529318576302874540654995999903361786, 21172133458608732300887989383427281965171394293400317363673505108237404173045 ); vk[26] = G1Point( 5598686200209475726801826209869416677931202133322427961462147150076924987454, 12622619536843741987254461244719750638031901625031570099275218121269742818251 ); vk[27] = G1Point( 14751187683369284974807198981066190747232275415561207627517237286483560910232, 7370796989413051296003280586660709473139474321751039074813372431405031731783 ); vk[28] = G1Point( 13373281139229644325143068039438096279917013863338833314623078167728933486768, 18183063850705378508093406636734075337683851672731923707148837425651461022765 ); vk[29] = G1Point( 14756358962228304251158891920353940748816049525067429607888240490682964727051, 20018100238418134474422914328691582505033804481193180797273235391424655852304 ); vk[30] = G1Point( 15050376363683056331420166772246738225621521672827061638572803333762939171137, 6692324624851091562518331948429504853563070333909916418627744242683838734585 ); vk[31] = G1Point( 14613643419505957778895147639592351129371688663085961967252736252082421938049, 13492467422136441255221235571918205307022431482664045250662874767261956568072 ); vk[32] = G1Point( 19272459865926252510534687364159235945661180836599787066322921201698318795509, 16068412419077751339494815562144240543858490922842578066695430530869706287406 ); vk[33] = G1Point( 14217590080649035438270780473813500271147838186437137302772374368155325056231, 16845218990033720012206713315597881577890180135341475875645585510779182583901 ); vk[34] = G1Point( 12766219689999522508596366817447705524383432762899487116849913496852028403974, 4442617591051747505650488338566434480312793816520262764041789007779179988292 ); vk[35] = G1Point( 2934784815494397384351742089802347731790762336685129985935528071559993822490, 17880874099099888607726520043741004359341385182615919072159716670997697418122 ); vk[36] = G1Point( 3091792813862966591589586900310729719569763521242154412799763578943493346092, 12290890978553676777434435615322571862215959293936331080984908465327888047012 ); vk[37] = G1Point( 13349543775207628424618511926556727231899969609146526061238742368888352486720, 5003445500192377637035596053952244157270587264435908525609473486606154214324 ); vk[38] = G1Point( 13632797795153659929604438391125254473547917060153457450906928983123223191377, 5708656200864299430493302357901484790017620521269743632664850438879166816962 ); vk[39] = G1Point( 21516403793437117639030947980477132855009778094943037156716379075978787390280, 7868436334373748638648374668468765846000853203993087329280199600531049528370 ); vk[40] = G1Point( 6770897784781928031867397130583859969297957667075284038692545903252609202431, 12046473195834772553947525821743025778710598381179496030496587998620473788606 ); vk[41] = G1Point( 5926176049559574560260760825415608508897247818185031118363669095436999505577, 1284235126934163425152880230217201535104165367449041665405825230750579143459 ); vk[42] = G1Point( 9814794488139713091910995228789191065371188268827695780345623170960847122387, 15870155803409128348333957775616624227522281868352860278925895373376838711032 ); vk[43] = G1Point( 630137277498399446981091669581474261039009945706701335506763273366672636179, 13952577276779470095201114655417544637344887436927155806431990890918153197048 ); vk[44] = G1Point( 15192807545573808832740581991479347066357485231283136831234600432486788338824, 13336740193212789758417221190944155324475645844938488994636724314418921395651 ); vk[45] = G1Point( 7607024848915044030666118805238957943725471764468897335573065792589070610525, 18828486222218564947599361272642509130365988231349565397145165726730105380985 ); vk[46] = G1Point( 19219088923309135511331143862756584023260991705388547107879751789238398902932, 11840728000909187450200302908706078675043705326472195449253543077443288770765 ); vk[47] = G1Point( 8198110311046717662168615086746414716008488843642178474166696280798054527609, 18391623548971096033174898388145095550422306181038552191664535695479873494861 ); vk[48] = G1Point( 20473324992097053080214599560787533368765381847626731312973518541012228935407, 15139100058797500577596377412753454591078218415414562312861822286326595328626 ); vk[49] = G1Point( 16690152730829129171363650035011230427014461803054035287014395891043858902305, 5326966792817389284869617519600725784611480553007555807761966918896487799007 ); vk[50] = G1Point( 18586810049419201902021421770909981604979205904450207333004106074319375484261, 3000873763528382823704879922058832571060952569141847371705147067254092754708 ); vk[51] = G1Point( 6160362872509440327488675888373254687689061222210050599850135296059225220090, 11955733398559263911071101838295129900857283000260075168171477297818776773094 ); vk[52] = G1Point( 14492156678394742115002689633313558714055091005636725204386661729651842287960, 2980665139814186575079397395460047714146959917489383503315814677932929076799 ); vk[53] = G1Point( 4437942380909227322513410180060012980958045771284745269897449720247874839689, 7150494348880348053541326495332743092604904626956271535314626613514430993283 ); vk[54] = G1Point( 10001482437609468168905690425834276810547626250526078900702957349563018037572, 17014991335060100931663517391092589109560972962613182089256344856852776456399 ); vk[55] = G1Point( 1146270991420408915157883757671063620180145253802196811286398183158315238637, 6595381571366057179191301477376853660703424082291020709647253315873432708642 ); vk[56] = G1Point( 2295778711541749139331688618938654319774844488123355539010336352804404868225, 9038534441289298754730651091717232113184375524170344329410952166419901016636 ); vk[57] = G1Point( 18030946263552418600342891101501630584358154999129913737473179136306653430480, 10094754102441716302333922040785128796851364870659094529989236043049046754330 ); vk[58] = G1Point( 20515540872993825885735721479173249600098405292336704804023475489580401026065, 12815186508201140451186217899334134254620120042158973516233694480916914696934 ); vk[59] = G1Point( 1804891765707908198689064720256107365408735953357075069394624098415344430470, 4312888158987705375771863918381406338922739182806784141939327753721205636124 ); vk[60] = G1Point( 16877448648938629336455970504682822004466354494832925338785741819796014329831, 9004801518342253672610622229304283273598061572445418279279029358986672673 ); vk[61] = G1Point( 11684773357441616204473407127066407940187405235118841266149422930304904671101, 4601212052624124091208177291565916707049495386831211638013106687568736240760 ); vk[62] = G1Point( 9200780553406884834747928192666944108171558035410990678489962416081866969139, 245355479222183059321071080146375836278832602529335915498668060326748169409 ); vk[63] = G1Point( 17193390511345077394677912937415581020324899967030747109811423759826062775250, 14696937504671569536105740730959339419173196545590013576300751730484773918342 ); vk[64] = G1Point( 8297139883987906366044974400932874460526844353137077214534106934254464947529, 14639909594931070175367464867880176626775875179760782510898942522291894584639 ); vk[65] = G1Point( 3609661837891552736040452521070929765605206776804107786039109126252989056239, 10853920482510922842280129089725351153170312759841380539906217565931367896137 ); vk[66] = G1Point( 7048912278298591433696726716891346726989208866324514786372956956644445635212, 12157714004316966786418194782795130754506250999436816297735513634950158089609 ); vk[67] = G1Point( 7237253195546107369268020076523471861310952350764543603629859106621717737743, 19116693017681209184478944674814040872992816925296619469639887753314093264028 ); vk[68] = G1Point( 820625138379551054125244647280563550681344648876046036596370519279935595980, 15390303712492827323530771631892852471365986110637908851116363235496682208149 ); vk[69] = G1Point( 8469123334208791102121090147866917462036787879068918118100650044571085670556, 985411289560761222426587701260531417696603744604459001958487372203239838614 ); vk[70] = G1Point( 13489859579431512566327338972385537701090240862822503025335968374670729750179, 15995490443153950629132783532642148356156923684608642055029435450417126828716 ); vk[71] = G1Point( 5025068258170967584974704925088363304406401089212153750732215881376591257673, 246161595180469439871964180140987057585752496762790101427696426737962631903 ); vk[72] = G1Point( 18624725444473222776113747225616131120503456023323493209399495423851291344464, 9092973913660288900922543673887769243869708135622690978610355029219090242011 ); vk[73] = G1Point( 21061649267559242832401893079341589206002708787277690534085280507837218231993, 1900216925036373287933306987274284611233495151280539379320118154386310400384 ); vk[74] = G1Point( 5693819266837633730481574793993745768266196474943094326515211680080687275556, 8001442935407932010447890827128680450594583042442977582211611638286748616423 ); vk[75] = G1Point( 9771493922794336654550195000151837133645846617865062117671322834447274876162, 20138988792268648395724831202845132235993313594369643169024085972293417381258 ); vk[76] = G1Point( 20562331451062703893881754168627416099192602113158327030049126971276681495286, 9922952610656157940491441913447469115396311761440205415203273517602781900330 ); vk[77] = G1Point( 1498434369431250451487086928778526427184171624524365632160766332094635168365, 10944624617277440037922758627002938245363946650386133795299870996528247641094 ); vk[78] = G1Point( 10832377128347608519203756448849245101957725856901326194321191013438270941056, 7576992144586346969235891142502318009466716130788201106309475932341748663598 ); vk[79] = G1Point( 5404747453972409299405410409234055146842412072217069882583020025356846653559, 3428836275574699574063363434174092703696554190928235534549184825651458251596 ); vk[80] = G1Point( 7255017254601736382654669268816814947260432488086305071618299686058285162223, 388230518794721608401893790016913578404082517791606318989885831955879795517 ); vk[81] = G1Point( 4274998285745241118487495635569318784037872516843008992484936039849104436969, 14443139989460339019339671111544342047053107908892353590183300190419623712419 ); vk[82] = G1Point( 21634128749231115557689347711533942752321658258117687994986298238533176713309, 10098417356594951025541196814774222751252911748634174773868142001516047077280 ); vk[83] = G1Point( 4046156447368671967831159377498153821361453924530371493710822968609325137996, 18017858974683766542167316686978896501129877893451827180444219136119997531276 ); vk[84] = G1Point( 21576662739301169631034067114295524106324010408122737616899507736956659368082, 15549928284767128044386306983641879983650007657189247282820571281896321376047 ); vk[85] = G1Point( 1406769679588655346791608544853221495318169507694271345467605886427526915690, 3409297043583054603125408386307169121805510872604185290967931750429507053754 ); vk[86] = G1Point( 18106931570945502786841144602374292011476307636057752946308260680847654343704, 9791468742662328594521401814684679988434087939060398459565194697721566045579 ); vk[87] = G1Point( 7380005378468683252627012582609447422016826052174902627743382133360819693854, 20633054862281771907537793266045250094730636508212325524072161612808367803506 ); vk[88] = G1Point( 21816007361916942614683383057256332048576032449298996257144182426645723007, 10912910615005771985596617300532268853511005944312259503708390682977924203283 ); vk[89] = G1Point( 12001517725790823506681311268316938140899443303693221917009913892717505376340, 18733366505580458632546585000773545702151172407556419331157287281777465198385 ); vk[90] = G1Point( 13038529351805911780242589893720599224800897313574636339730140424280318086809, 604867398672054997877704956089885545998912635452415333991349902105952235548 ); vk[91] = G1Point( 6965452184674160535858129493567304283978585666567675983356581787165057162793, 8188904991803284378320034233479215172581458071883536673427260453562983768793 ); vk[92] = G1Point( 7323426258562249761902177855323941542869198991480596258992292026005765690196, 7734116018069009730025562122809887507597980452974169334081864598385477997973 ); vk[93] = G1Point( 3572211610711428000486113151838078977403731645172584972748286662113382514432, 18711593891651314440023504352017778245051448086570991878012325473969331338616 ); vk[94] = G1Point( 7677036601374967423052162698241883162849333096754182212479474495752708964837, 13798545013798901163002915143037261535691350570216409435910452728915409359004 ); vk[95] = G1Point( 11732505988352344596120544927115732305075423591163239480525667528602339935516, 4069380080273191891307429136149700368963445073424053925195989656180249274574 ); vk[96] = G1Point( 12775129330581327799943466193674752419999697177743962446788076996471746889946, 9836399901287341215772290431451579844703774446363508350054750538806344363660 ); vk[97] = G1Point( 13659216341517969142512653259655976972352364397892462114225201467730133607513, 10152067278164672036207642045055219013398144777524244506209490093573651971267 ); vk[98] = G1Point( 14068442030322336486683798451946234901532576912811507447671823028446914239553, 16568587289510253032355455503323159426432639802135247941810760160977485677894 ); vk[99] = G1Point( 16069986319801270730475863882303863352160415869709497383777418777645617330791, 18994036875310789539672950667776067654503953865260933343246227010190649423581 ); vk[100] = G1Point( 753591038799143596501465994871794478010410947327974571148528957768253266557, 19133326316177193676715715513949481761943512145445692809255783400361270511862 ); vk[101] = G1Point( 20744899546338442536314141733271698486308282549096184473846493749354078388224, 4296266412857756742059317568058584688284189539295482749514608463273525098549 ); vk[102] = G1Point( 18226236009407355395043840129255719097063313226082147037867677763163875120405, 10480138883576441496958501474305678339976728704402016351929843304239062870190 ); vk[103] = G1Point( 6016937058970533393408421385433942222637329271011067359924898855046257306066, 21798492581267253332996483281434717216343667863651530012929767232461027926817 ); vk[104] = G1Point( 14397923115246358515482163360065372202753987754986190144191814556562824064782, 7082562522891172147798139223080980137320210766135394997285006899994054366468 ); vk[105] = G1Point( 10697108852644867098412544109976683532155204204159776614254134730959863833867, 11994867655637815554743636701788514532539361892162110783826887964019001033958 ); } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Pairing200.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Pairing200 { struct G1Point { uint X; uint Y; } G1Point[101] public vk; constructor() { vk[0] = G1Point( 5280447958522165271753443781707956962932493679043298614057258828764744713115, 2950965016195187402652016874997101060634411125365212216271760448064603541692 ); vk[1] = G1Point( 21171113376957878345034662378962277283829747463293532071719928512190671638083, 4805865026742957868954457705535118582692000448362768205304665457685300251605 ); vk[2] = G1Point( 5948188885156296094989198479533447429951534547013344174562478255913477773579, 15032470709573822420914716859455319025910550193812232842748017612741827359467 ); vk[3] = G1Point( 9263852489462342603186337411676045041929248025161376275553876894962863430550, 4863067836782397359634422149128116283913942236114436840608384730993137319432 ); vk[4] = G1Point( 926514064074676681222187110134871296458850595623702907310835724388441736011, 4350423020275254247296522807208833729157693481780274708357059336830695514309 ); vk[5] = G1Point( 14277495816440045423208292967620768290327323010711987232012357921824168022805, 452813406831923392679918618950711804908492322691474669411098750481388360332 ); vk[6] = G1Point( 21160955607465349068877290977785733431510401371411241133134595167149307628387, 21463368050659345551623808905518351596176456104821817707497547918238653733221 ); vk[7] = G1Point( 11183002294006692676638067716768786690162735498453824969473098484064283574745, 21103893027159017522776018105004263486725234249615792521024970644554353834042 ); vk[8] = G1Point( 6418211983475451443013895060380495589190337894004739494517415311641307017083, 19836012302297744923444257568581960487323032696963795456773227561104319792565 ); vk[9] = G1Point( 14671538512368058396179183735665161733543089904313973202465398007941240258821, 9592087156754080309406223247428155890413490914730088426530050927752526693517 ); vk[10] = G1Point( 13286980494255572219962987476569793213337102009906377320669926269537021252215, 3830280696443604677777330555569777642339004031957458355124146714865284291243 ); vk[11] = G1Point( 12493977647977285968818168103715924975419190113667040069597912354234466381993, 17172386031189148645340319582531462049789845775987692452634195419590805547745 ); vk[12] = G1Point( 16866171673489955011148882795394419753508047449368621656003942887805239600594, 4909406224635805270725209167819046708849065048979889396978549845539556317061 ); vk[13] = G1Point( 21549447761498791801993161159982221152603709088751648367126627583554195510992, 19711291914440575810236914432028417340372176108499568040277546145356647512990 ); vk[14] = G1Point( 1722005977130280243783223482577807467329473359104220018892945354984630591817, 10750976379923118030562322138895757591242488366665840197454520203110283314586 ); vk[15] = G1Point( 15330221355422948866378358337302707326804133979111505396813792043700753283152, 9102211923949548182062227220028001245297657315611122269679998204315190981093 ); vk[16] = G1Point( 4266038004610457914557137313288648553992474529741119152251106296746825565775, 11380051686902264120053500481574951946293847546664416180991902246140890052682 ); vk[17] = G1Point( 21802104294986801437165734877814061831768929348457115729908524813655682812688, 4208646051256363722549041860639692308328727768529411623898442602237418228012 ); vk[18] = G1Point( 15550115518156193685814844693713265707931773460490869326408884426922378659401, 6332521871459969520603167336897081588610887316032228531976589188039625036008 ); vk[19] = G1Point( 1303701498786427432624213189517333456026196687778684587615633707365956142288, 15326210099125045196188489368234616376937316575684215785813966064605757886304 ); vk[20] = G1Point( 11298549315792122324272483152810241861261708055490267786567948679289118442793, 14412918880563079612319230428775565566389031996134521852053875295153539716296 ); vk[21] = G1Point( 14252920552827302724502112078148217830072146787137722672010700163285570377137, 17854271046972339797757144990705140996994989276908719939831343397078263897545 ); vk[22] = G1Point( 1843094137434880333976956915871745512068073113685598160750909697695707488144, 20548700663903421631258345406957604165245295201542374338551344788952063295932 ); vk[23] = G1Point( 19364586690399038014037746251979121371907920337930850601445543044430470725740, 3108996770995638962680876404150700020595387634345913637458940693651680405608 ); vk[24] = G1Point( 9711017046111473882147086987926433013327239665642002251154101434458519839035, 3295323532668500836651451275248252398137920959089010096627246479705187668456 ); vk[25] = G1Point( 7662956193333494172807125530006713818381359462891213536299567570648294708688, 10207879831342435320532650361985240869453949315604762398981439620059531155358 ); vk[26] = G1Point( 9593585369128848356113503913814696650954054312728624743764805640196319923539, 6675510683796064694030104451849925190686159386032755390565362955088506529379 ); vk[27] = G1Point( 10179958790781748374921171427096757119084579730536503041739965978096018378257, 11232333648524497390763027902469925331911307765091878433918608574649072092797 ); vk[28] = G1Point( 16384803781987486822646497737990801684306159912726502052380401788180913159906, 10280968134467693352238095218313412653891312838364378109731337009866570875580 ); vk[29] = G1Point( 20570722625415916681896412049272090396062124333889274062182326922388788790808, 4455676676760779998740130483720349824201654140993164028307484456258256736410 ); vk[30] = G1Point( 5550506948556552901948843312893446930792310199685385438117015178909484933291, 20080040338186483946019930996109575302331436627802093735518514375897849507642 ); vk[31] = G1Point( 8932320587099199334914206696790297795863594026737016815581892467078663352797, 4904040155254252133930146814940091630089369828937724021888325552672549445583 ); vk[32] = G1Point( 16876757973528875672548369351866199604759959167883965557938102022970644966871, 5261794650570734697642238547488896647278172159405262373012912488438149948863 ); vk[33] = G1Point( 6901580155303724917730429446205029578595792208881319012511949919656713225530, 3620718364937741509622855726183328770204054697132802578321581257425180870012 ); vk[34] = G1Point( 2438193835863778319994212875367336120619620198060329005605157170435685297043, 19797569917816521293670012507779751046300848041522098441121212450640856760764 ); vk[35] = G1Point( 18438672985542835582912637634772724064134100870696238185111168292385587530437, 21371554437142409054827324698888723001251126425981672070131934491364164997497 ); vk[36] = G1Point( 762620888538686084704185100882201582440423775422592689676720906017011348815, 6260451229513081642642173861311769068163374082576870984158698429303863945102 ); vk[37] = G1Point( 11046703858637605917091865533729604922584219782712638582381178600080923753528, 6862646922304806637513131774162584712954115485111020460746741510910598236283 ); vk[38] = G1Point( 6513333700361514532830060598249782774309152149725332800264309939766223252497, 18344588134244350665718641824247235350690182484263173836385356112222141773774 ); vk[39] = G1Point( 11112064110026980209706715339616548786983441925520567893081786258758800515414, 13100990600709210263230702134750728274893461281219110332648563658632703351355 ); vk[40] = G1Point( 9115936119265507852632015599904409887273187946574057681407028353185510663176, 10790812275128753048378969398626027891082478469357327769985322724010063657211 ); vk[41] = G1Point( 3277173731630511585974410003276679371095981356589614653578085190285929153248, 2364615376255977999605586884815130116862623552230767065712043432315182299750 ); vk[42] = G1Point( 21596987938180582726591334411997526089311434056582966215023525311155704746136, 13331184165697234076499648063859864083707991590733720966441634893517002024490 ); vk[43] = G1Point( 6135088057065872775349305728864433386895394242230358402063744078862948279332, 3141400768544823864088188020891684624944304018601163459825273901533512030175 ); vk[44] = G1Point( 6709417955682056897580374547558594445532554071657252391353021655805070606878, 20818451539617670837857148151613589445144894488442692962771786710131430455547 ); vk[45] = G1Point( 8079954719200519433852355847775839450755775022909846570611933624904541077076, 15874867612163234564271208461324374039826507422867032902739126347420668791450 ); vk[46] = G1Point( 13311623291078916851186159123706983946160227289099890075366773929889079509305, 2451033782492685669321011879211968324176155937238407577989985480793072696452 ); vk[47] = G1Point( 522101543498610259930608600962877079665623748315800114519820231965211030576, 18293630363124950041511623868747866673942288087160063075036300106859213751216 ); vk[48] = G1Point( 13679255030543816984847453129327836253576400280805914075594283496481681511380, 9764397508766904948588123093024507548808281268461765561476055566665837937952 ); vk[49] = G1Point( 4288320468357868549409514400135040476935963129543905468211523257801011897041, 8861800418111510525964031124474575711010404864900428849434864398153132311926 ); vk[50] = G1Point( 13901936880993204616062156488432060305725374998518913130438138989624262562949, 2309744924723778897110793804534539866197179316754873531772172690026815183889 ); vk[51] = G1Point( 17289451806345222086593228086336707095560294277254534579608350911383533013967, 12625539384720474294698327787370638455010179205956288774966107376719580141980 ); vk[52] = G1Point( 653146760409554023605798923465544685519620253038665691036896276890935632296, 20230867730501174333554256563265775915807232296274225577398981473377026870241 ); vk[53] = G1Point( 434047786224928981529079789971059073416808060049887902361195639448111131924, 1260023257336638024914016653169882787694286669579955973336384372976578620516 ); vk[54] = G1Point( 4151709862273797318705125461467982281875369001362723593864260065863297768574, 20825517818521394542181715986848612441290034068657796158139476509001980777226 ); vk[55] = G1Point( 2170999160538069209783573322275917771071941748970677049765182535879015962617, 19047092533825952202813423989937632969784708177794028957062135497207814516494 ); vk[56] = G1Point( 18586980296273630695923799094551395963508492495624917579250443877638622193173, 1709156378361177185000608769033266268057873175646287678680359014267758791 ); vk[57] = G1Point( 13474235397479336187575666791286102482820502173180984429789420757511711768202, 1899556591042274113075720644859592124085178547322001450227597751240226472279 ); vk[58] = G1Point( 2005812720184289353646250827051865819046057496780017994550946832101036204731, 4486611559083460939084460919657379697407050418143224670954667190800447618341 ); vk[59] = G1Point( 13830760675794381365940771985940594932334799156645328968036894870042921431336, 1654030180088395240266425821239410265015443634266723166016811684398610935718 ); vk[60] = G1Point( 11579978283114397499695582131089869431862857390810611299943778812341734377983, 2088896203294635288168945001060414317422876469033393790480894661530158610251 ); vk[61] = G1Point( 13460789588949740582545770689525773986146557994869273871801294802838367032709, 4533837923316941654628238822908514380971930536150069690036861111395921090875 ); vk[62] = G1Point( 21519667628362663736912438946150343030988124386514259212902742582085635854200, 2324434635155020515934794624673453341130922736349633256447432008665670779202 ); vk[63] = G1Point( 9056381623036940123588068171657304614796813515585580409969954923872596245078, 17704933343380515642783846926266523916896932418862540925517302198449341110544 ); vk[64] = G1Point( 7695322306033856409958491547173662966143040668580954550947680468366769035406, 2877193723212967713584922515651828930001713261444528430098244609437057370249 ); vk[65] = G1Point( 13766997127557531982245756335640213754237977839668230567498129922964100688978, 10510699595009615977639335460287871100884854325152001080440087358399681175692 ); vk[66] = G1Point( 14278176010098537699437351946422929138980189970350014914133087132936120929371, 13912352960574404351344999885170158139741892583704676576576975451727730306966 ); vk[67] = G1Point( 978361915002936038941871838840511129506245705526976647023981791112658267376, 19584061077552483611861218662390804555239290680386434604511721142236963193696 ); vk[68] = G1Point( 16134720346064768029627434495793576702843591325706626475200224722736249788044, 7880123762104004353642668788113224608171777803602347205953465297556295711809 ); vk[69] = G1Point( 10883377423534796544175029771036761047650410216663358759968196966972278142571, 14446979927255311432588838171393862554565267760324454060386824540856265575070 ); vk[70] = G1Point( 698147910733838025973111475792431250859708923182673712455836941974961609340, 18140234725528800177535379626583637103030488020915541527527572174148999840442 ); vk[71] = G1Point( 13035289178003051936670555261010714243125509220713271357200655975100245790402, 7889909909807545727653655718720413499719033808361280159819513784841549772116 ); vk[72] = G1Point( 5528581497193346768322150735305590448086775952305100710423803184705388579838, 20021405129330638359565856856376743388452017589539437915207081049767491314478 ); vk[73] = G1Point( 21183721626390872979349180705913033539826780583465743209063732292874735572245, 12183110134915814793504636483874676037895256058938828980469944941241704348911 ); vk[74] = G1Point( 15152473084639958281790797561783856098748593452461905592230821570969564642685, 10005252360549204901228967105774563537457101093205163122979751644618921286256 ); vk[75] = G1Point( 16792072314993010874173160673170409940615676603448165046761658210770879227669, 8873027547444816706870371023608255374817168874255395771545132350966165712312 ); vk[76] = G1Point( 21469589968231462706507455414437771936820724176048742749784146365991008156366, 19102676951961090701198962800517135323468904732435884872398444828133163236867 ); vk[77] = G1Point( 19312887425424676941956404333899533051195982135915073444323038894059796015933, 18901418620724824545584734768831886152743453111896842185464706958514642877496 ); vk[78] = G1Point( 21000488752741561863732693069500217809660570826941056844300525996313238855265, 20424037077286200203520665683096808467028776314394259359070163304104222809003 ); vk[79] = G1Point( 11076178207947960049121274327623286643237936579536668355904540314532786868236, 20372717596038592483882727235354691894426829382240016625806823518575333866399 ); vk[80] = G1Point( 1655378702913447157100270752071609217872726200521046701260356551274657027960, 28967284103668229696181193628850132729139592127642027139325097191177852130 ); vk[81] = G1Point( 18199177513049801651712297443643312553536413112695479395719241094305171418375, 3859860445414768796951669518130669988482548212654373739251748503771012045342 ); vk[82] = G1Point( 7870140345557008634306780520253793397024030639260767811138928662203082400400, 11699624309903026999605564730157309776348571110029711744066071004655661300003 ); vk[83] = G1Point( 18124020071144189152643151997625695986888708792226493330082318087156247093029, 14512216904003607653530801392651366282622291889311608844548507371848354970816 ); vk[84] = G1Point( 10761009456263382772794867246455953971744843949442057865476852836748326631914, 9581712976976789128471522266191455763964114170321263116402077750496677562371 ); vk[85] = G1Point( 21292703428084255769949416076493027590035214578497191239948302029207503223127, 5452128082602780177548790349920977727875188092984116935147350703247979588103 ); vk[86] = G1Point( 19154438377872090186309242377341917565103669099495510833828536427180773379060, 4306818512358352710283997743757941975997271910152506169214110958062894540805 ); vk[87] = G1Point( 3527755320367884710433847836524488324096346170406403589418229268848779341562, 15119647369703275335590153565183790934827857992897342136219743840996149733493 ); vk[88] = G1Point( 13233999056832897449155061235406098031232200012370041234246498105574334427252, 571655669070670499014998080105125235406682739254874487403474094656196983999 ); vk[89] = G1Point( 10875809454343129205416373351261482192600203250051512622387838514201272729359, 3846148216089728272475676822940829787766663698186552908769871343545410787065 ); vk[90] = G1Point( 13523502310925486518618136933704615461787388754091806271994994819638044731535, 13113960307281636606592225514637424603619516326349413709355017397697897159922 ); vk[91] = G1Point( 13265097320177305674600522452940514248121677412354227192856875392753932922874, 18167197366853042263821638004797564633757661249779421455063781655524127665073 ); vk[92] = G1Point( 19681771096820908081089688679931445112134797287633896753737927599356874850421, 16431495911327956876117796860233103062506699511223144116532588704609279115116 ); vk[93] = G1Point( 11344889289070436114978632966578268618959709830378466207099840942185314165983, 8516164251069482640075809123739469886512373857184494272907647308106434456809 ); vk[94] = G1Point( 4866117775684624511095180462924093195763665414329214924605146523256145359964, 4968153995686455206553823328923395188863867299096290331853025273582678720550 ); vk[95] = G1Point( 3302314613912759328010966217888131713893080427027535422827668352799763481599, 8627340542034964868449361015649147101961241319801566753538248082279285454184 ); vk[96] = G1Point( 1385496866542133781136354939130789771283685272635189675502307913581255510706, 10312146981466068905019661463122703802687327505428124254376827225993793224344 ); vk[97] = G1Point( 5866738265868087598970822982183327076713018156854702754274333773717239196129, 20290318502219504323257799207869867067255337146915013406656574857668356684267 ); vk[98] = G1Point( 2946041693840769923426378146465947192756502256020579142482489956259202542492, 3276664474083413183930116859992183320496198005234426831498567432118208718551 ); vk[99] = G1Point( 11872653154234352823865278198226687229259175564408213976433960935388389192307, 972080949564172292336265138288331655554084404799297196880901801416518551020 ); vk[100] = G1Point( 4152372711129164001388267322213971146957149153241123267759240469268693995296, 16544571539237149819430538843718282290150295061723346781981793915262107306295 ); } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Pairing300.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Pairing300 { struct G1Point { uint X; uint Y; } G1Point[101] public vk; constructor() { vk[0] = G1Point( 4152372711129164001388267322213971146957149153241123267759240469268693995296, 16544571539237149819430538843718282290150295061723346781981793915262107306295 ); vk[1] = G1Point( 17038417056061139659946137807051559581737390662259548808156355476974535703438, 13616219462714789817701991847069545873099739203918157796963388700686845410995 ); vk[2] = G1Point( 4269909203941431923700848525155320937917893882736437838404466611318865110777, 17781972087881019433854115516884071053590028501700109054624827919936423967694 ); vk[3] = G1Point( 4199434400061411542729865554425189405602683929509632298821370991550866166174, 2237511483831004857489507549058387223943887825731749819176744496900522260837 ); vk[4] = G1Point( 21222163696400322268272970842972800302179969277992812675694958769997610642033, 895339814933848106648192758199091169823229390061569651896785756515492224174 ); vk[5] = G1Point( 14092397124169615746291174275860732269702769718330125416394432619096139140296, 17534833916820410130577528243444581473366375675553503522815046746401619109758 ); vk[6] = G1Point( 499166961015769431842410240361838028853434717057615901128533168397581825376, 17854820724625378211228691637064441523966178302797193519176862986339310615386 ); vk[7] = G1Point( 21774196242455472804185121040099030674961114748012722059361757445531923979522, 12663785045585488513875897884976145462456305059639486918913665845484989561431 ); vk[8] = G1Point( 5379080663562103928899985704308449514648369722847835806581765968556006461540, 13583896217355105802162268359907593912371300023118655312960615850662155435942 ); vk[9] = G1Point( 3702550142156082827870350690985489389190301923731779513856385272965628579980, 6681799128731339306259152204812929417605866614187466486540534116962244572500 ); vk[10] = G1Point( 16103740944043750938998127192387210497602868817465718427893006337421624150845, 19025275943365157212370147806969111870676146586152504692331226730021117797121 ); vk[11] = G1Point( 21559751585204501645281671262686256862270871137067847377287705207245712015332, 12068343131530084919410024627441941188127429402996117845481073952717145523465 ); vk[12] = G1Point( 20095552964511053177683819908649881168241093142850479056628959561224389426035, 21835512972466395501457904881939746961531487267417263847868688931619508664034 ); vk[13] = G1Point( 13633506580973903430759224393705455612216044620691146649886666064763353266741, 11823825990552450135533148920645558265826888076310767413895214958666594512581 ); vk[14] = G1Point( 6331087831598555852653272698278929340326784507360045768214096636920945436737, 16240667664436296998523323743240250683783240895337209190031585497845992966159 ); vk[15] = G1Point( 12944771810676742667559706856109246499901761289501926375246861304192283488192, 19969967268101772693947699246945492003535686124911069745092859113985388820300 ); vk[16] = G1Point( 3029745854421152621137421314822716120710909759915137376432525003315223490717, 14327734199676433406189129949899218213491335249316761237447075073981015200873 ); vk[17] = G1Point( 21048156346913508694012102010212192581020289295805108400102048530406644429209, 8259688367314383325264901424014443381935686348919885813397723010641328395991 ); vk[18] = G1Point( 12305683190657652202127061329008429966615019099445183364280917925733830718475, 21223812980988918837543009119841694556404608059057714935147626491413780742489 ); vk[19] = G1Point( 799701881759318683138216913967700652752702597365764352106390996686004435831, 5579707131919908928417007159582724709634829584455899344486569307179282085340 ); vk[20] = G1Point( 18405542777295480901591581991276170910527284694330155375610438004450040804136, 15993697792405075833830813747839938952708398813187627514593367927598530046019 ); vk[21] = G1Point( 5338776963846592706034019420367446697985072684253532725105621087545399045480, 3577459043584933085081300684841071150364712449683406921646039132671746468854 ); vk[22] = G1Point( 8233788397833521439534370899272930111768999074632287396548417035483934484405, 16371747182928497533346882723075345553447759797770441676571910322328305141078 ); vk[23] = G1Point( 8723839283777053042589014778220812221378474117826378718090556799361107817903, 13447757731856769640891536261475508390700613747296636549091688530160892572414 ); vk[24] = G1Point( 4267982150783233195799104290475002481024114461188413962698554103157481481398, 19109008882215122234846410828687653078198336526181849579098299412357115795360 ); vk[25] = G1Point( 19915693664676382178334397456424522547534255156685812190161269072695799584426, 3672241588207226988638709871579349749280416826940434324475705909886919872986 ); vk[26] = G1Point( 4836171243863222682433759841603155085951767299206113515586298419607073316417, 4692200367008919258921051575379951593207541454066402985161521490873706741207 ); vk[27] = G1Point( 3773174909760358993477627847123999387763512808550374064108184698403392246087, 577808157649967349359487692527673747611142937132981352253677073360946253998 ); vk[28] = G1Point( 6347879848005997688525621664043055297892721110145230897570943214028469401510, 1834237462623077490164279275291575410254477713297848497248085235015183905671 ); vk[29] = G1Point( 577333949872234615601778989709656874782865026325672764577584878390941419054, 19274890401019868622366723491960187428441203246838870403491504842532477677453 ); vk[30] = G1Point( 20981278288825532109848887707567500808416535769804128127326883656521247745191, 18568816906491361942949485634367620652174037921789749873715931009713007257209 ); vk[31] = G1Point( 19134835691455969062338160462263922137789276911205952137498263112942903647334, 20803000896257375586973248631549382884634892514368351405434307293085922446551 ); vk[32] = G1Point( 2386091113744479468735834388301459360679107908853389497382218972984735025753, 7287765893724150160048148641054010761895808662194311875270320643590683966947 ); vk[33] = G1Point( 5717426629987168024451171200780910738683284769914161907691298691413939343031, 16862323618196447090567093488108348731384560318105657055503872073025964748121 ); vk[34] = G1Point( 622606515070173892284721704690140706775442041333730391539319908694933912337, 13799861397479139835250657218639627330688875648890590045687888986736016908825 ); vk[35] = G1Point( 9842680516355971330241366645923888730853547061410360379680518405604799859376, 9980749832468692247312366115751388566648148269000433893956180017086446193063 ); vk[36] = G1Point( 6811209919444938032279299517001156642980698211627370571343779662029351187530, 8218065660579195254203557946637215582995417237003286067010276389275883124164 ); vk[37] = G1Point( 14349029785162711704830361221087492756691192007758648765142963718432370791106, 1578928192324053669917431169722016011578725016097957570143229924084132081593 ); vk[38] = G1Point( 13363221761826444632090617604586311720473092676761747267436985612574033863983, 898432232155731811867810440359206092840929165360666103748001056621201115412 ); vk[39] = G1Point( 7298418886179423495415953171303089663122214902295724336460826663538154155331, 19681585187525295997974679346477246564750774542706239783533743773327233629523 ); vk[40] = G1Point( 9716096799754609708598158471466918104966918100192029299574262613191954542027, 1756189004106833078491026111200879193191002036755061417708738243369996970392 ); vk[41] = G1Point( 723222355493487324413471583122396313118588605558210374614924275036440232532, 10432839125250845800994334838711778885732683657402922416223676730607519779513 ); vk[42] = G1Point( 9097186880320535289851902427711788879578660373030033051791726128326732113207, 227486243260739890340367073063026695543801086348010057319623142893967086785 ); vk[43] = G1Point( 7124473055375980453052603771330073197687251505239791288810662577878594077000, 18336324245669414299425070000301650422382132428496391419354104096267643724764 ); vk[44] = G1Point( 14598165119473152942483454635139757386186418153066879576312114035192830608005, 18753330316944530476100826982257654169401857745336535391572749276504919385428 ); vk[45] = G1Point( 7564899514389140949018343889291820550456020433348479415651939408554300885302, 1887406313968190396448309972836751633355487692902560363325487489591291151066 ); vk[46] = G1Point( 18840668968813526768730733205656949046327758483739358264182284417128445061467, 18330554368137985987105276843207959670617755506405336871770751327864953978288 ); vk[47] = G1Point( 1557113104695364533820543960324101262598617119492957388434734885030252352619, 2158432394009375034975469985613930272228493215064473099679297970383068736415 ); vk[48] = G1Point( 8868356795570323044596001785707849850290410342127804343117579049619342344228, 18769341574140884193344217189200188860398558849281572915446062514180689022580 ); vk[49] = G1Point( 3106413094037772213448230399685812272106096579686010255614552006807976377745, 3205603704435607621146354334387443983507644913030528214203911894050581039366 ); vk[50] = G1Point( 11431380560098875869979945572370386310260418535514543050251639734518993323090, 12082409209708274970603018682378209832753459972356121878248394788242362882759 ); vk[51] = G1Point( 21458690769522232957938057902747228453530623533537262100178682457575087147238, 17963641186508177946483845027530205032429536184577523287517156393606197318086 ); vk[52] = G1Point( 4488320309958710414236644732507887094278337425614302115893716258052763583371, 6585219425596487297642287533555773789149564468412163948920835498197653236604 ); vk[53] = G1Point( 13054214903558455016181058750362123296972156252705036285835985923950283627707, 4411107936900254386402486933734668565215842855304737716567274357851605660786 ); vk[54] = G1Point( 8836134442110749891260027958113780934568567624029534254772310601340222660816, 18516389664043483924067448895526978451456423078763558084923672906138738079017 ); vk[55] = G1Point( 9427796744161838557396890063039726968797021444813612022384740383801819989904, 18477937289954441422247094311301450612547267080947201294106847253700552578540 ); vk[56] = G1Point( 19490399503064730506057573086139651474697470573155887279868462147318297312800, 4756059465842000709504190216871661004910187360887996732846200456511697763953 ); vk[57] = G1Point( 11690907006402402602940271394686080614941650673001935420180283057992765908992, 8979697205541636606084683945312289558559894268565474813292245851597812669362 ); vk[58] = G1Point( 3426026434219517317699701512472579005505992532036942158668660280919905751142, 19400363881258690583839965183765461206380385659462687297148365229142471127569 ); vk[59] = G1Point( 19960789857885281119567625767403801975322900649972961873828399544446633017265, 19223811125245954497003767738749566307891332076209097538016312768027164779367 ); vk[60] = G1Point( 2624878593350277693961360192440714296597321410876016904826103870847106153709, 13734431351081306809663415655332401971927381205188533230979078223863157181217 ); vk[61] = G1Point( 21059274093612914423015944733347643181714430953567551678349933664165609964283, 12567004863158726451177888157935448676097077494460826446944024661947547535776 ); vk[62] = G1Point( 4173391547982352888996258489739295463441940961276797122807963754763048736369, 5166337359503674349720042404447515774181375480957279620971464186779642146361 ); vk[63] = G1Point( 11510700586909040437017322407979240620564288248825103375857213733086815727719, 564711694063950686928455159175501482830655098085761819029978237586718131027 ); vk[64] = G1Point( 2172753768311809877443925569263943534378645867950393427708322942379233838449, 1494049539045389209000024708327252071321590758861469946940102610661865113735 ); vk[65] = G1Point( 8927270648187351337740084245888055989091755350197739111019174799276805533894, 3493874889219644701503765587283050418696879562656829327821087390901428985285 ); vk[66] = G1Point( 58610388859575517650061285604793105936493869439721127206330009663936187477, 297731796160519780046341464076073452229414177827451864926070334755819543510 ); vk[67] = G1Point( 29893500787040215766822107446507628389417705754394324429751442162985741177, 3573665914249491735292726220283480172934692956202031875808732961197968285384 ); vk[68] = G1Point( 15493371030217856879778475496458003180317830948927781067107235223980611216821, 7628246489532069627711702089908466598461190727156559798501081012567852691665 ); vk[69] = G1Point( 7833811725191265685163572005631595747815074000880424195656578442664865394816, 7365576755871418731434890184649709279510310938451664766773384634175384087711 ); vk[70] = G1Point( 4682147553912642882524157919813508037475773424914942220667230332607417002641, 3062450747701760491341058528916267452925200635393200111592240141108748032804 ); vk[71] = G1Point( 19385671750706494995341678694281380805425293373838336348056703276496811579034, 20831767245729944442260265107123599385541777009588140080235172799678245434460 ); vk[72] = G1Point( 10172964330651928451500393052790728477262488654695734257652326626258241437854, 16591595746933707766919464938463853905197602409951249390957918811090317909268 ); vk[73] = G1Point( 2262943521925428685299635620687677751022579265165360729886809352018095872731, 8769819618868254433334570902644304340678046698188999940403584135715620779710 ); vk[74] = G1Point( 1821098122072480146266422501921518062901901365725568587488921063370472064044, 11801655264023087683764388011821037539566438251995329018552420306883041694722 ); vk[75] = G1Point( 4081810338956661295955795576306603968364291689187026175662224423041752425078, 18921697477105431652081353097690961141366918336719466416587506450308824052599 ); vk[76] = G1Point( 16831871209946948249581038738634171095446265903177751413932899799260460622516, 4272054428904520777349788679201160432474565635088931034413189153770116600587 ); vk[77] = G1Point( 14755251609957523819939823995278236991853529733227909489191791480315239830462, 17483530475599239520475007650762084338354992077213033826376091993847101749917 ); vk[78] = G1Point( 6775350076464163365143783783063226377459228847662055718181198611224152286541, 6119567521590517968827694650385579018849037015008875680722123474018615678527 ); vk[79] = G1Point( 13375034798572176431108896785731181544015017913616958815938790189583036069846, 16259717178749794717828845353678865201285741914852341390110237490875279553756 ); vk[80] = G1Point( 13728965549730907767079538145281659939987539944830605642434868357260143490361, 14798998650859844325566254178550347586057629646703078189328883634376015314187 ); vk[81] = G1Point( 4698522418630758112331681081076732281064460170018097113472844113505246512295, 8704463612916923973854623481657465541719020524526433613314286630383159577537 ); vk[82] = G1Point( 3629022607241282611588252761960646825165921382897786199633842838244988789824, 8611416691899977777194186735743129014260457304231254148048884163751373546260 ); vk[83] = G1Point( 14370296357865692571543921061398049146298892063408032612731229638487286555234, 19585462677681820948685148536635736435862989209643998990766138877551024630535 ); vk[84] = G1Point( 7531490164301608007554814093942451249551554987003973573643214564031557620536, 4668759071165760113288496351814203548987523101302355216154444016283655262376 ); vk[85] = G1Point( 17013138372243739206631693703418019166212891323661487697080423533095178904867, 6101863081275571038923912495964353526372181698975784673438470104166782438192 ); vk[86] = G1Point( 18786778055303766775773041889605889068883655536442862586624768868789727513662, 16500190526423617753931342459058054581094121746358372191990168937301376877591 ); vk[87] = G1Point( 6004406011795428552176406258823605954453277690417628597607077111485251662557, 13188878794168406990832097833587032519415213055954942829134554913718932648734 ); vk[88] = G1Point( 11249444568163448906997847437109940397200779936617923901856898755110299548203, 10744185631568280526784896867770708586433802192619823660664809458707149975163 ); vk[89] = G1Point( 3873858257867761549678429848625608705901951097008729473590302827940083501638, 18146187639909605014358510925714566747500206889191421889496958892244601622931 ); vk[90] = G1Point( 993180406634623466110619757221141381061429597639840244137001796620500690070, 7723483020640454361337709771638680864203094223026031073822710726080098724214 ); vk[91] = G1Point( 783935753826513215536158573601546886282135474051116480282462996780213065878, 4974660699716417686712668227107728230165087678501722328158808291247539130062 ); vk[92] = G1Point( 2973250549957961593646296453115104992218845833336843613866076948557794407754, 21554989633296110453004057526404268854659986759537607955567982494153232662985 ); vk[93] = G1Point( 5657200549875120461499630029283901906870333656453973294749744847924589373365, 6385062108652097685872641309364239635240421158756359788377929871155395223842 ); vk[94] = G1Point( 11356022547485536330665218419684939396636820284906022389283085739333596441177, 14764566569185456296830786123198427123972269858076568890982969153117841934520 ); vk[95] = G1Point( 9496243455909597583063123634278935007088051646697126490324866540258229469320, 21056743422453544822990375399902341614831132168787235671314845442921839143040 ); vk[96] = G1Point( 11832387138043885725618453163322593474081424480298521160068214815726714665724, 8833645982686354129319989489832582428923914023223925737513274223223059724075 ); vk[97] = G1Point( 9569755942881006472020793362256013379799877346565384556147952877238199479593, 7914468044048702662043958879447100143768447093405900232023273351480836533712 ); vk[98] = G1Point( 13246488610358887691124332065461183364219714906137036584375508160882317839454, 14397706757203631307654887327939104246412343869671744077678856208341086399885 ); vk[99] = G1Point( 3404188911357037676895293427628074904767235375519989554652734459966851646422, 8523281169623467264167162469354721430284809524469661063465406198599965720328 ); vk[100] = G1Point( 8449608423833037886689363696679598002380977316690731686317181458570600648998, 10807090869929946241660711363842162694574415385963956639862188261492004518103 ); } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Pairing400.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Pairing400 { struct G1Point { uint X; uint Y; } G1Point[101] public vk; constructor() { vk[0] = G1Point( 8449608423833037886689363696679598002380977316690731686317181458570600648998, 10807090869929946241660711363842162694574415385963956639862188261492004518103 ); vk[1] = G1Point( 4987765922000699190000063413890656698626699992395323520393633298944715902200, 7410420611558777613408270988353971533741699207577718941542056333299104867720 ); vk[2] = G1Point( 1802653648709708124383489889152016910896669090085798558022103491017340007553, 2433672591796689948389406085908308807146200077324925589783263455356345025063 ); vk[3] = G1Point( 18941021601181825974922197419395584561279014464626780008228688283754398727028, 15433879371645053381009391707804385780893228704046932160942999493457563000749 ); vk[4] = G1Point( 11457775978138386475204907544878541216648431984579174292666440067667928346022, 255774361505180617857690702080724230358362609517985738525141899487942911072 ); vk[5] = G1Point( 11048392709951074627164768214827729752987966021965260962292499245205166008152, 560975369669197740307643998141729359043021046869617341037545263648219657039 ); vk[6] = G1Point( 6430293402446310585377447781231648068815362442406274173887569721607656288230, 7389049400195623386440176728692839163517320032667370664428162192427073962167 ); vk[7] = G1Point( 6096138228068865135419920243894536618452195675928731099735760296380930718666, 7864691007806755644240289120076212753306715600850031359282177669679813804240 ); vk[8] = G1Point( 10061144809842725269004929612810137143015517306919216606904196446374676852114, 18547423842557521528708501650703634601817338905175857670553206549299435567669 ); vk[9] = G1Point( 7435455837336027629935299085062133545341679335022352370742749657784206957589, 6272704894798957816397072816101055404111578352125888509436748954299804213379 ); vk[10] = G1Point( 2386020472098105782576266763385435029488285324637819784490968077596868237890, 21296610687648731216804387735352008130999874174045407290690839746651304214512 ); vk[11] = G1Point( 17432508287385017129581246821702055209639492370142007277647290652614655011010, 15855276585163875713755407882944288405425983053894666648469336739669377166344 ); vk[12] = G1Point( 14427995829186694340633534838418145707313555591614730554546232113202149072143, 11353761225635785458881081698882986617023470822836738182059193560991512992699 ); vk[13] = G1Point( 8613251830821230918936112899289877565969148299743731328295728641184637276281, 3982170053930105127235322494560682806129646103465483713577557669373302890646 ); vk[14] = G1Point( 14159729379012631856794168122360757555393560833907294192139043378542924231647, 7363475676741632075890684625424591979687971681092217627417354747808176276324 ); vk[15] = G1Point( 3279983063400017405735313785097543836538107570092341731243895291793319185472, 7880664673837807824440326388862443176268900843545221780705164994920244447475 ); vk[16] = G1Point( 17096112271275632479023105803104446910483368237441393024147484993287722471677, 810087113047178113304849768721565905285531304778526553406712872125967939827 ); vk[17] = G1Point( 35383858622035015563725178884319245318207027840331169949837618929497890739, 2596040529268805952866621347460424158090867956078366940551518683875351195277 ); vk[18] = G1Point( 20224037787024713195385754517802049613158501882723651652267838446939195770843, 5734082904078263841934306572375236128755848566424133369891018070232828840587 ); vk[19] = G1Point( 2996648358063385090866021159838956854832626167238485125787865063256911142904, 662070874276227889269808565071845841402992931039585203536019139066265971388 ); vk[20] = G1Point( 19730148428979769372988346988921260131345545840380314784853334341866664908522, 4269473481277255391429512789903257745383375746622387546144387282321237846486 ); vk[21] = G1Point( 17329610706992780272483606640421515197052841442776861245994579852600101592315, 9116016805793630060316582858790543878045242519451651144226502022455632235336 ); vk[22] = G1Point( 8354396765301249782999984119848628124576415904266727005799482098327927801162, 6121534207911972598732948174628911093401363362488309876965038312497114173011 ); vk[23] = G1Point( 7951113906019293031699965282775777796020748591422773107112446554619168708601, 19620661709414554339737650629362365657510478334127431647887471137663524037650 ); vk[24] = G1Point( 11765703121011506149184724151214389791629712714140165211688109292101183441640, 20306409547205813657755557754036448492195877817121280028535528654308427271768 ); vk[25] = G1Point( 10228409433828672929602682833675675538708379279862799648108466697417806708964, 12689477760567413734768039508181173839349984992738298589205968945496073336538 ); vk[26] = G1Point( 12871779950493435185460843553930420469667713920767546147662189455247917045027, 9462776584491542624950041615661199302988994479116593675280718113064472870036 ); vk[27] = G1Point( 3223948815332722572107175547339640387231983407781575143157664997781768102308, 2002619842439935097482277826964962341945494360267530738785066751396995379961 ); vk[28] = G1Point( 21143380169976828881126300695673140344827025223515609749419394043633020917730, 2546921069673914933587743151951823146654805306564591391648831882347028789561 ); vk[29] = G1Point( 14450365776853588347258351872169381001258599289753328045145814601873377302248, 10422172621693811955606932762570380095411462532869197793645121257200425078445 ); vk[30] = G1Point( 19605307124982622949796381001357586067060714678543991843016079970385667233523, 15644406365529307086919369468493544924385506439057878553640495186080540709271 ); vk[31] = G1Point( 11329643008042969975594461233426884332472238402541569122639612015354895118510, 19699215675370267958563534727947063397370486858910888943120833673708918781723 ); vk[32] = G1Point( 18365389383236403767320629408356898333972538901513733495345228149289905259527, 7989273494142015042620942731157057238239302288960717520358492226812016172084 ); vk[33] = G1Point( 4614112284145655014901089094661816780306033497654586693574012366603324476366, 16569328845479938406636547248607899731697801951873041181838139520833598182850 ); vk[34] = G1Point( 12342247249632202192441042583121642363985491029072376940760539534722920923735, 1374366446564205401715568086580906539335444732202590282556811502363806146878 ); vk[35] = G1Point( 9613951534860347468983102297892171258047786259034573533629537990593802034429, 5017916395614386736421167587362805334230708932204782376684055079258274308907 ); vk[36] = G1Point( 5156296361370818381372949438625754095093880179513944472262356238645573054954, 11725613468584979128797511733333435062714447055200024275744354689670244587672 ); vk[37] = G1Point( 19446318516095762146091962598437802216093999685651408646272183466481978105904, 8014994869922185832300513089921433872593128433366885391169675005365828145062 ); vk[38] = G1Point( 10166923625325146113988468575839588329284508621615657868760410351370045293376, 13356512692649553147904384712029075783311086786634281473334812941261470643599 ); vk[39] = G1Point( 332711170693751806204040327431929534554511979004852800360623449774593001272, 18643846335020111082423002331118112902777107739977353084772579789856974444637 ); vk[40] = G1Point( 6353645237359683243162622767348926052074119370412615263140289005452046769480, 8431304765053116019876638291169055381456237438935586129374370851383480310247 ); vk[41] = G1Point( 14585403543525157505170475975080056091389588731267981271270741011811632180391, 1385155099043255532542186069321534538199668394049330862372739759898812818511 ); vk[42] = G1Point( 10920250089204683945356978745792997085730991831121395462594979949265131925809, 738356690358462897210980636319428269335251520808727376309159448185529823886 ); vk[43] = G1Point( 5359796294178227766350187440852284111613029671423600270420206544024244593990, 18397241835381474165518677163436112836628369716206932990747112553138477669517 ); vk[44] = G1Point( 16799510291820157919828834722411097154617374581129485093170344599747993750769, 9661919173327372074459103818050676268933211291292047052074661282309143408721 ); vk[45] = G1Point( 18438489468003777826897223912294939691758692985497580162023869638529098020646, 17881046364395827595175165589330551402966974326647015216299208245816742828158 ); vk[46] = G1Point( 16279213099530715664259892968085635123242455316178864549158245948885033332327, 21586054225696587157070750835564642450428479720413172231165499681673590437271 ); vk[47] = G1Point( 8775439012123442033538247130849642392232016149268521496886229402237188125664, 10552364397777053240992149749669182329615223593621749403483441227526777877718 ); vk[48] = G1Point( 3188890041729243073452124109727986742765291303666491291539528677620744145065, 13628718900323921745975233220630860619893136816274789122033183054712293180696 ); vk[49] = G1Point( 6568875555326414291178029843365172701961197514168796830625825125393527831624, 14131180648964585729576469036683179776338491230781688682191822590508825283143 ); vk[50] = G1Point( 10100121706663465502617239737015505073463035987864459437119469133515729521068, 20366863750342029329309523287815402998128640825501206619886588928481564435605 ); vk[51] = G1Point( 10684218576194997338347165011089291183297909289859719249436935449945007389732, 2449918211266528051738802329103297878685804172313094060166323741740991833554 ); vk[52] = G1Point( 4397421326625556921353187456160779959148606085541852542520478171990805386796, 6230636981232197475584558125388589717640075310646176507800681827089834717085 ); vk[53] = G1Point( 4582604747687380973883209652453624670466202968827909920797627101641726031979, 9705952646733450955892254571638174286528353789069518565663238059965361642569 ); vk[54] = G1Point( 8672877768551250884561695763275165099535870728648689896823482354161184979934, 7726718631417251661552617294896073236154716443477088792269538249079756256638 ); vk[55] = G1Point( 8213906827594662218180491261261473215507181749839771951179822981092105079453, 11457149547499442524968386969402373902851770177718259175281312467929757984056 ); vk[56] = G1Point( 2844020653836293086652981862356601554090509693295618836220178373671336532419, 14510714631986501053230843146584206886649096906164352574233140890971527321128 ); vk[57] = G1Point( 14332375285118889727108851698647970923336740089196281082123945711353882627567, 141101594605112898649615232940311850542065168276818672418149449584649065746 ); vk[58] = G1Point( 6778217226054814753185272910629306797482333853238929211961815419762432390443, 10408226612722620504114668017787041358599032789336815570881467241673138873676 ); vk[59] = G1Point( 89441093670790953673601974405086017935032772663206117686556260149276709770, 10690565936441277048504791623425380690014596630779626173568511573076598769007 ); vk[60] = G1Point( 5236890323725248981654769061114364912801464296868592373976692992169702294991, 1778276842665667036817991703342176410202300441391300430093074501197189434348 ); vk[61] = G1Point( 1866319676550943812624739915211933596690355201885557660595702445021724742539, 6161679080514980207158892191062490747777737910618482656764433289217396026232 ); vk[62] = G1Point( 10201942094420469114208410146674447564314510280185244425177559397414094367955, 19052097980151008820786500049668079393808905538072772761626175225953996543579 ); vk[63] = G1Point( 7138586575609003945240737716938852641780240591037552032470610043469823862870, 11647207245481215047657228542920199218812840646465591052187336744304096010497 ); vk[64] = G1Point( 20552284598490957432008885212885583206717915771060786259184178445798940012668, 19832738077102857981590711708606808711162714946654805592483071520355161986867 ); vk[65] = G1Point( 13903577686905114305530217779680162558769808824948170165162883124416092755071, 672653457272505284187781077792946857967117084751557783978550746933917600446 ); vk[66] = G1Point( 21688738498632521035376921762008468685908127957761472977561623009030992476258, 6779417367788642410285534703682756185511976721022534857632441353131807123348 ); vk[67] = G1Point( 21656664465367532133705268771109250447017666548180241319162864409963657711101, 10332155612726708017195525436228080547592515902202189329930986671458546696350 ); vk[68] = G1Point( 14295708433010906286964074775251568607875665250824110041338222639511797118767, 5154707604695900834140427940169227919578086626500371519406059423507415550512 ); vk[69] = G1Point( 2914518828148204055727355584005465355276369016592785679203722916925202199464, 10909262175560433173253729334724003245502381534415092702521594942069474572292 ); vk[70] = G1Point( 17472569531675171891662140366852415726090693885530364920137324852510798504372, 2590654498940902209085100183100133217484824927601941674226238250097877448977 ); vk[71] = G1Point( 10187642669485047575977474740586552961607573483563160525829349172379620977959, 6345248219451008558331817528241766475084388697501976890729136761751007577505 ); vk[72] = G1Point( 8880558251698981660922693791555157247069786904229059346902102749430691649113, 19620160588629666666542068978921841365246366449457136939802699147143527506603 ); vk[73] = G1Point( 18214751821864117593426915951422025119575773784215150977220605790624601235144, 10398341434125134453837660080020614619483210263401380182807147347953687756242 ); vk[74] = G1Point( 18189853426550924856315297380280808204034244026893390438869923304743944184329, 19025340377336259124998168739307756753221006118290296080988270008087283324221 ); vk[75] = G1Point( 5980500223012554823262940821241606026511250114550019853136407507382556765396, 7847823219951471354583810510393400356227929512707225046491122942269925850002 ); vk[76] = G1Point( 5596082606828625689072484011432902673290631421377124137839415510591660767516, 19386660529754816764112012103402145177322409237436741400428274713556163024202 ); vk[77] = G1Point( 2783613922687357879263610061751946341047461386062195812590022220432350450208, 5430184091405389593946417054690796725802250813819547095000245553024963572762 ); vk[78] = G1Point( 4780969013598657747647981789846435446281356429410644112840026727401926222300, 6284350962906963220386750105134869521697338380480289944897649435701332636649 ); vk[79] = G1Point( 11962779575503510483597150376051804357184531176597675070683336290631100621307, 5101749612787732948149289339649586413852268791000599175114086239787196323269 ); vk[80] = G1Point( 5836973732384512570782151282373157790645678929169932713737601365905798158513, 11596520216875868121547404923873921743370220694573484566345675452102577190422 ); vk[81] = G1Point( 93393188275131897581960226426815725856047809100611278842100658084057419822, 20619216115545839346769044639288339437935496282798331372536699333632679662536 ); vk[82] = G1Point( 3330491471137810039807672797278064380143151557789143940615821448800453454492, 1897773942513623315132563850901471350278928397369463684030164536253372104529 ); vk[83] = G1Point( 17005674546107867956717355342613130801406510462483167276888316107593577221184, 3231973652564434859290933691096432438909499990419405767637832244423288966436 ); vk[84] = G1Point( 18398555417963705526725737510817589600227288777039473144469996215239679070090, 18271967216244409000131529673824355924981600272105938369737926161294095083019 ); vk[85] = G1Point( 6352471206325505611304995680664589415462615528549772601551124622094105237843, 8073597395498210389236649273951828199060281845366055134225874386675607912204 ); vk[86] = G1Point( 18866077979002977810333336351423177776031273512921088460638118580551244879729, 20232353325373794304805349496845297250641971426115820795531162326507964936614 ); vk[87] = G1Point( 14897152370281609491816309264907721123188095515605969368639344601050920107956, 13262343506326908273902941353565033594030523843240176497478574813524737797903 ); vk[88] = G1Point( 4401431034035759336736839023076592364748177166828823906331550535109834369966, 9447035062696599319200255681823184509926708542648163760300892055504494669163 ); vk[89] = G1Point( 14543609177558237166802777311129026704326225046877517520431707467448363577040, 9424998598105541398810489088095671238916456321148059431958195743607929822552 ); vk[90] = G1Point( 12898623315038343825636569615819167848172238074244307067401266411716135818359, 3588427241218337170994478408422573431546676488360120458010013213999711817027 ); vk[91] = G1Point( 518937046525276211778371652925879483348671390002122590124910715654165846704, 1141938371388755563263875210687647896134314651286035247555520995872202756196 ); vk[92] = G1Point( 4253048248648086040696109348680511050880683474989387902899434441429490275435, 13546825276329134671004677398198078213623377301175547751656873116722167291557 ); vk[93] = G1Point( 15152226943193161359565834327538035085049041608610392006372521873727054889112, 18550559272594384204837092162931193787479996271679746751666344624228370905099 ); vk[94] = G1Point( 20948478496654755700572016220222770216080476124791109554658295053757515953267, 7151274204478540650608167974409303763864374097868423288352505735281920372372 ); vk[95] = G1Point( 14054962623979136522307857763270334893612312296908528830302497613053817969613, 20230818551283838636089720810383176973331565582502954541147513339852152390696 ); vk[96] = G1Point( 154348804010340961196965216979396802746977053903829485798076339066027394911, 6431301766201778630821024131901162740690024477962919383203572886160553051321 ); vk[97] = G1Point( 14012796410695096067182746756572819882384906319438888341570421462970023590753, 20517227714863091510549878199372549875920248215540831397018781271270013623770 ); vk[98] = G1Point( 20766299270928257646113077603787157792358846532570742888352155118864030222461, 10918697045349257395383669284623546940583509560885731346899664842500323418280 ); vk[99] = G1Point( 14455210311838864373095335824390341276735646827311008937241631049425236172472, 400916631010122523401252840520982744259403053940486500918914563008431123345 ); vk[100] = G1Point( 8017365071475770317213092030893590918235912283489212360180207554216851342282, 18361965916130157491790771350159694594438800327133458430459013762768733021874 ); } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Pairing500.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Pairing500 { struct G1Point { uint X; uint Y; } G1Point[101] public vk; constructor() { vk[0] = G1Point( 8017365071475770317213092030893590918235912283489212360180207554216851342282, 18361965916130157491790771350159694594438800327133458430459013762768733021874 ); vk[1] = G1Point( 4304541759568974579397697901807178453851097495141972366526924038313141810366, 20473318768831611269613865608279812716455270667665805296498157284268197301834 ); vk[2] = G1Point( 19977510012501255851301050671950976219374372724623527011309695992378684216756, 2932816899919789764861350628765939797041808102436282693252727236369960112781 ); vk[3] = G1Point( 20916820388690744608110831513816270386890933063962859080657292680583483973080, 16552958872040127216456500093852475650244363631348724291065018493317178959236 ); vk[4] = G1Point( 11212497791300709312516900965813650516709679249800853595246740963024446655806, 14530630388365248990953862059440701080162391348828005098673520994854132099527 ); vk[5] = G1Point( 4053511950851511138965733630031315144392821152858873224877953550608316967381, 21168578858116906637712541523579778123034833564035820747014015413071032248056 ); vk[6] = G1Point( 9632883385651725660184603727856015192489807675961023493198124711243547460969, 11502483789102687532495205566510319709321669852085031867356553739610776861262 ); vk[7] = G1Point( 15676736871994215377464176099736925120119909051392441725206751354518439240524, 10132415200779039829225818585902743413989455419680204706258695955737402214775 ); vk[8] = G1Point( 15334783173261988389463969077014180405086683790265063688235529517270533917650, 6045319531376190352921001410233498604477568462072089798490790164317293239042 ); vk[9] = G1Point( 5027880290341270639780401819770605011057391318752943921761231981849291907167, 9455773520497435064893985903531981876847254598458306642123762765525579940354 ); vk[10] = G1Point( 11623895108365338332058212771695693052388671542313528283198418991782161317522, 8612390934786872972087732070099851647164812338527643399323966316903442983116 ); vk[11] = G1Point( 17690084826846586567369933468826638642072562397827987841518529268821674110556, 2143421304787954398507327382496985482847450255265617088968923511513791319820 ); vk[12] = G1Point( 251573095417040816145539283548271406945582781658210597938203607049972925798, 1308725489856719976523794342919326269901565812502890549950054839060572631683 ); vk[13] = G1Point( 16830452782001446823755158250451335883584938162123377826895416142299931113717, 8771579442638668396946407059819976627306853140878292363230618059312876803274 ); vk[14] = G1Point( 20827278204029883608707386169501515934481198080023344205330983555110284654656, 18269441903333686294621165418630478375224866698587261112953072452720860186667 ); vk[15] = G1Point( 2420957522841539751387302364212636658550448186699327792243676485467872409994, 3193575641239653682368897288495980170510432329845353222172746000782745882775 ); vk[16] = G1Point( 322228733479907168599504150389724041874273401068355463549199965740281460866, 9861924660528696947121810492424883726243721359877143111623957215369520231504 ); vk[17] = G1Point( 860254308465449875214779626178957122211651961540905260030261602356064385535, 4771787247608554576556436553355513875571994318432669121409906571586359635202 ); vk[18] = G1Point( 14959009550015287896764679815745175095914315507644345182798459913554440014939, 6447870883355261693897664051041598089546904228271032852584765352456201760778 ); vk[19] = G1Point( 19259807411501095131679362488634773335720710378668732819030450480104709910859, 13677965295722918609008807643976138705725372154155708020124210311402832096218 ); vk[20] = G1Point( 10557836196714597989147881604222431789546090829144238667115539648305967044859, 15734451144483764675960118105535536565723127372080261772701886003118691800565 ); vk[21] = G1Point( 1274078832688816787011764186163247480174482720548885644187547347294615340847, 13040296641622853767839633277627933969605088270498898558896558134114092301703 ); vk[22] = G1Point( 11030713120140765023740049644148188674497076030818764667201964107526549030084, 21561997324060279345481943505875922463401585748520734580229099361119970524949 ); vk[23] = G1Point( 10957907988981022170770412828999965823403381519601320383943238154651207208794, 6917156101863130549772588825284337491947791547591138906201280056585418517289 ); vk[24] = G1Point( 5967235622407153336281081838611390686315322708505627293526403861614788012341, 488752902265956237380217834951233726199708956710230281140504346717636260818 ); vk[25] = G1Point( 7120522859090406150558246990569909219984492227600388694919687704944945535448, 1425279918749742383315620516634101875196994011868787984960526309149066809608 ); vk[26] = G1Point( 11330219186932024729497941960575430970087737336151055719283698481955230597935, 307409105388812270622985511943675493307105630889652373578592699133354769341 ); vk[27] = G1Point( 10426004155516183371415252544554940188086639338075404987385486939661163762241, 2179193041800174831356027078521986654351659413110915578400026602952033324654 ); vk[28] = G1Point( 19543618116735863451016836074199454712227340647542812749779702366077347190720, 10601471825755589489788694809165065411678638279194900097766487627324933841363 ); vk[29] = G1Point( 14347632846876948086160464689927442355894905036130935388910520699696969055655, 18886967905325516387807035941378846166492972570045452201584998346152932154392 ); vk[30] = G1Point( 1214148960185412539030852911621974057823856030267124005771366380080346599085, 21394623962133714508569626309917281370813300092705062355109929436230089766262 ); vk[31] = G1Point( 9189866194048437667734042256456452877122643790399537277821142783786339796857, 20255038441547858389579834644988181537456268667344166862512034907912862204467 ); vk[32] = G1Point( 6050216815783430694237721203316440654896098233584267913014322242408902022767, 13698340089802624124341000751242586549910367822213610082073953146846983975987 ); vk[33] = G1Point( 20001319643855117433320662280052043500625157005095612332776087889464442337562, 10022968087695317932288060187275198194284742120311978572562118715817573692026 ); vk[34] = G1Point( 9971727375949556007825462737262815059852484519704711166313646771352960271672, 17454859994701552955361863890214553891648302684771171772123210715750909065285 ); vk[35] = G1Point( 10105413709221335950755692623212357614135301304369245454776158035829572174485, 21172279033777729856876600607120700939495705981557864941267821256499196508615 ); vk[36] = G1Point( 6030398850693938437690529800809038290427089356752000751433240213950860214325, 18158389634635690702573860844534140854538087102886816391504545272966544179763 ); vk[37] = G1Point( 11899525799889897503454671223216130387323051617906381840532773243711259088919, 12721955986337670624083494028151230637887399790018187292815389811907468899079 ); vk[38] = G1Point( 18025182099212312759869460085610864638012054109400098580538718756340226789759, 17157170406292621064396140565017687100876332313530590228651597529072670395249 ); vk[39] = G1Point( 7584521350325988890138926941315327206948987740017524631658765390392667221826, 14809651019432757586501707231785874057509503052025842485310649390742738480477 ); vk[40] = G1Point( 15619429371780263056639941808419692828269076759454566387324330214447135740664, 5372299157725707029488376841984469079563476940269589835685995410769370918072 ); vk[41] = G1Point( 10308782984982099559743978574049657251840186030114688266705112866332453762706, 17838298368200063258611116955435229324352584225138221778904760139315004996732 ); vk[42] = G1Point( 11251741559393487831824165431364888260786542801656734079551071976040135197401, 21778319640750718716270457454625892708460851686892742938470621747038304701982 ); vk[43] = G1Point( 19602676074170334263525684949376274816125885222571700775815916124759964664892, 16819099975440257881525901801687754508991500789530040932572540825537511199160 ); vk[44] = G1Point( 1529225456473461005617776610533291209017137980474704473729666838695388825766, 13862398306554383107920126493798270016130151808631321020027477725558589148614 ); vk[45] = G1Point( 32576370183836840827080341831540294408226466974611282317172044096308651478, 3875900519874394709096604345967386383756427166468282754128300888706899564508 ); vk[46] = G1Point( 16640452001187292982538303567053094101514427451081482565823882009720823774759, 7776285599047977882116099247229100826174316609142052559218452971255686412353 ); vk[47] = G1Point( 9305065517620518455485027895752411284816493120084039451538120454718234394025, 17198944018437778924300981515521717553272008056606734923163391332835576718653 ); vk[48] = G1Point( 14412028755337164165033715825349348886350764234653004635916810778452200464081, 1405333300816604257051980556789151898456790069017388590311037858519044866363 ); vk[49] = G1Point( 15039579999810797824832563119564858570880439423551436278192245355465644922174, 9176516284138881995495257518240106331887692360718158497892205380503024356121 ); vk[50] = G1Point( 17766653600667195700794928713783883691770891896186795607025320112795370437593, 21337585719353361396876788435974083098037207436334914880996236225834831321466 ); vk[51] = G1Point( 6892825894581615070083666655767179521829330473221054727853932908076068978081, 9672762645046177427171226165882750825354516138623061816335061323822292821723 ); vk[52] = G1Point( 17095401404866415110660735909127829704083037415762918404669493842280305179843, 15519659126125875181391173753009773984560255699907538476618121381387736669571 ); vk[53] = G1Point( 14989793488156664077667465772478745061698755672972964143529612399572584867044, 1109347563468930715592230246483233726430804047108598541934735395433648521097 ); vk[54] = G1Point( 2830869257820824577179774831677075646263556894687167053704713986875189172804, 11751309471174596046620333559302631634224248167548896399639249518518195540141 ); vk[55] = G1Point( 9011333166511907466547746211170598318088591569389940173642787939139557295057, 20692837883069422632920826286484643204807897585898235525967846700227697742215 ); vk[56] = G1Point( 10464939685382257671960065048290356147978505671558858661913471206754440091806, 460800390255171296341171509286862603267870783596679888201946216147240923431 ); vk[57] = G1Point( 11807364425214749910653767367049462276096076607198023193761897187873318641525, 10061677853638446402941615937867801407734269029510398013109394457439497228158 ); vk[58] = G1Point( 3048442861577026403302708158556540647742844992145191892005589103636216528684, 4386578736456336812430191885928412576096888394657056132057844115468403404787 ); vk[59] = G1Point( 2171131638663563549688360475663147299547320568892704263412028561944413174627, 15695449925490771688186528970086472813265643589396611657251258950852390004540 ); vk[60] = G1Point( 13844277162379382124046630666559332811371952716216866883463032017440714519850, 8871107789374732988101979858993543701904162888800897828405730948757111878404 ); vk[61] = G1Point( 4944729404118963656989644757107419941307271410534011537412653419362519559640, 7783395987198177612134088768531737626842371999090521621751925759265341720256 ); vk[62] = G1Point( 17432533308258302574033611616267297017302773466067840071484822176786118807409, 18060058553859543677568724241303817152189469811590602180147038523604083737949 ); vk[63] = G1Point( 8475972340087985662835423171222759138291630932988635149820496803631342113688, 56745213394092780761418739663962213382078843059473421372358886250150788592 ); vk[64] = G1Point( 10950013690031098204797801327854301687112415784114979969451055689625962012803, 5647448449831630583872972964783802169968456083626290798502140085636840189797 ); vk[65] = G1Point( 18099895133003870125291623007368130054171417501457074333371458037503805636431, 7982980102743421386368288143030048629134941894063855547800083781626854234328 ); vk[66] = G1Point( 8079643377279602042351661158270431474599657170980994490616597334466782255014, 2191628368126823712550733728191572744523183623233049596299065439843828742998 ); vk[67] = G1Point( 1231239166346782351357142480901385927683590654156904192739889193066021313465, 19579888168949670090450503432830245032533441749968894573071999407890058486002 ); vk[68] = G1Point( 5483752993002838253336034386972948990721359372861940543561655937664297548631, 7880109076325538631547972692846717513194330080778047892536073397367429862567 ); vk[69] = G1Point( 14483818733625569269688511296761613491451595854550788207780465329180190991134, 1382581360372289179762659583446011743499641586010083209678015629188051620900 ); vk[70] = G1Point( 2189203511059681768032946711738953978985080610126290835181299384951155312388, 5453796065897797463745819197774272815949802121653618928262165928958111269759 ); vk[71] = G1Point( 9878018968419610405792938671097943794401877177275777517255777098755727467901, 5271185102096819273957380819511286366721730784796911474238168450614569533020 ); vk[72] = G1Point( 15153387253976062002851064123272166908062676188772220475542071592052297414879, 2489413700616444525448917580209826850315048566175599692952656255597542674988 ); vk[73] = G1Point( 18836727376210128825986557814922998373788331013776168458511869391552129093598, 14021484929037784062841092273730557404379129756854637028356927016191156155748 ); vk[74] = G1Point( 19824800727768679417792199615475669918070985553350705667997424475077146761643, 20496903905733813256129001257145672166630983706847495563264595758036424194511 ); vk[75] = G1Point( 11626547214072693792039212654917745064251209998931404214531785445530369795689, 12807190011325995013999855931011599393314899498819859425956647659505590918681 ); vk[76] = G1Point( 20329863600999721916713284695813851927618492960654319317044700075496313502660, 4455330829456852703023585206699537379807763877537594593077772482454063980701 ); vk[77] = G1Point( 17169830810561474698394911390100087715372449946985182152491045822981507766170, 19468466011592483696513838734457009474660068317023294110857901135683597818100 ); vk[78] = G1Point( 9582564960117170576542119356097019749177381387670861109781261269530322386941, 10219397096907331450513625907078435812983407719051951804565619502934298971337 ); vk[79] = G1Point( 14624060747661387865272243569280245949391969706031557098789087058195115943044, 988807413298681846680933465860775732215645476486696298221161565038956446247 ); vk[80] = G1Point( 21499667593226149433528714174415346756014312544321485513020213493872841182223, 9586593363407050940335731074785997002526934853717960374174770784071830545543 ); vk[81] = G1Point( 810985959226505714621969607339055538096455101657721248414246059813700142219, 12189918519277150176345981737854523859422969781197993266697461970435960340720 ); vk[82] = G1Point( 8615544661771555677220302662061866175737345024975435368483410445448569412551, 9405960595317296921280967247319798060322673705216299254348300935752996055008 ); vk[83] = G1Point( 4280301489727095826077982107809413319505845332657021649972229400165304218670, 21480825210386939758288203605441860004898337556150726945413494985511917415473 ); vk[84] = G1Point( 16842901410684551017570200017797525805377888665197655130869623363657403562420, 15294397613571528009150500927563532670976987401813618415729110378783332664837 ); vk[85] = G1Point( 12131557098392449686213860931489122527525352964063730210906000929708810001219, 16961883255862597368549267796324983290399723472917922968879430506674345098848 ); vk[86] = G1Point( 16847910718087706614516497788539664564691499899122428448454988072834179884325, 3629673865324284869457013992823172244154937507734771866915770360107554640035 ); vk[87] = G1Point( 521569922024683695920270223097281425510922901020088505098990305721718044915, 965345204929449930659350727589541563870107260393467199799652465062523583874 ); vk[88] = G1Point( 19645340885332488791269558029730204810443084055301126302505377632928658624488, 626957721766640656925296248809628295895635439199016731086204609937776279305 ); vk[89] = G1Point( 18233617445389259073307389213961649913740609062866793979424822501533045562317, 5554786298613718646684722304734812879813310042703446369498443800844226944897 ); vk[90] = G1Point( 16101646201577482930804060370512628762700427160294952906256357381438096226172, 1530887537564539684444604473601199243010348818320710689274106410555701574515 ); vk[91] = G1Point( 14136768936121243042127261505679756849661355983109509666277684580170607461657, 16108637360648622511491853251316727527602870031735432044730131741601907324448 ); vk[92] = G1Point( 7003469698345441904076185805526143590208587023894417588608223277874404663667, 7266867566897666394170979687613209882755314980857792207814626620750472739330 ); vk[93] = G1Point( 4954231303652339042819599246489124170356991531849173264454143891251842415758, 11214024807763816521895788743871044483911190832305467538408487071942212150046 ); vk[94] = G1Point( 4459704569271538878801649436116999783934841734064032796211420662534299721761, 13732339054560805129169178700490151207715315687871478228254091336429191316963 ); vk[95] = G1Point( 1526324267932589544057651500728643910342855251675543938112908960620922615919, 681877795824366995767477732042618567155652356001930676721633427631580230413 ); vk[96] = G1Point( 7237090428010808996589749162835348315253475844323403672420685527758563908618, 4322657802145556608298543787964912964025095373931809147860227387890554813386 ); vk[97] = G1Point( 21214482533793195992633882109665005062406891258155310928387424967886525716219, 18043875730819678190519200780114577282769928152878007165537113773823454024705 ); vk[98] = G1Point( 16445762844845134682806754201581003759800111995178451655668646850974479397506, 6237975651557433441092458979993459087090010651508183748485404734528160411299 ); vk[99] = G1Point( 20159657021183988462777681624609956627325857198133480756925819692572589388384, 6292446742374209026035617577735782556313590110835153313910418666066612616376 ); vk[100] = G1Point( 1991890746054979274067153105515635741980863425728522437606931770461856188116, 8709422218507846640659975799179145473931881987299362740089298566508329577577 ); } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Pairing600.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Pairing600 { struct G1Point { uint X; uint Y; } G1Point[101] public vk; constructor() { vk[0] = G1Point( 1991890746054979274067153105515635741980863425728522437606931770461856188116, 8709422218507846640659975799179145473931881987299362740089298566508329577577 ); vk[1] = G1Point( 10676337987962840629938904937899033313777170974569020296692141515203754866877, 4440587844409383944912945767414852123696465798075028348577377558092377018066 ); vk[2] = G1Point( 14955757575612589382481659410686993501833216620315306817474546651573700600453, 10370006855950664890995775526934220356746402355041610048337834194799172546317 ); vk[3] = G1Point( 17101563548693945779621991722050262129128380219651176287567962538930496816847, 17229091562189629196247628978774557304526239646048366065617724974799900339234 ); vk[4] = G1Point( 18137988582456323383331773713189020252705583308705720180232789119638922985821, 12948123280335487278510834211390074799078390249789736860220667772417653547423 ); vk[5] = G1Point( 11478737979110458280583755338461427549984571575809702945406892317987885384685, 9358257392993554500199971375049186893232008648130970658899179127211874411453 ); vk[6] = G1Point( 14870682997037439942844026254508603801985911115761607897123828155085440937231, 13112625382249266006030576511593176644228310943813474197089761057758129502826 ); vk[7] = G1Point( 21676549701756573822169999055367466401429556936543592685348653155360389457262, 7591723833513147615575827559044178806079643113655428178782712405304780598876 ); vk[8] = G1Point( 3774442616415136377202191065432272794982237040951528739188372054353005076121, 19774878005079678358711377650806309205672488257633808812644341064915607957878 ); vk[9] = G1Point( 6673933870509987854027529424100431769979840440636733864536859741818140434826, 1089683040083836709437101415304294024366466922974850793464780944710018614571 ); vk[10] = G1Point( 9173170029535526242627026784713148787522898863261830114195268833519033268749, 7183938295050547179781962356413331745319234138793085302715934145167168611387 ); vk[11] = G1Point( 12304420366469338196605591707552140792500464438957410571365408321713750547680, 16228076526598527247814383196122867567160657271006903218459608548948257020149 ); vk[12] = G1Point( 11494174416777704005111533700422796165646373156163696396238301565657533145268, 202199277775470997689025820856192182083225391624115712582022492054167204850 ); vk[13] = G1Point( 16265039846382212305395386427972838126443866673491510721276074764166535370846, 9567393972623453030960032016763056441951464639574229841313299388871047130590 ); vk[14] = G1Point( 18795871325757064601344228490399231883000824898541741137712069305709857221641, 3422919360548875796213514847670369598705363528643105910943109052346067229970 ); vk[15] = G1Point( 19205466540019019701706186697837456307698224428424967349066803164626195337449, 6149245098872623479249285658312345625732987920747632430249091196171265785871 ); vk[16] = G1Point( 5384940027043954752082216976340006228599083005099311795354436970857412309620, 19590565228159052299115965487060979002341582865688874287311183335492203397647 ); vk[17] = G1Point( 3857079719229114024075647208934399441180701749080383675517314615278669341511, 13280985502593575271905876866097810531466295707560754884889094249833961841174 ); vk[18] = G1Point( 17638169986651884779943537330115548699215338425380569535652550562457824198966, 2119478312877586204509892734934244109857983898208082169257426012024104718711 ); vk[19] = G1Point( 3210942036679245762099261328968962896245017378154043898829923603930417014103, 11733871118752652170150134843618035115367952125006342389966644022622283334990 ); vk[20] = G1Point( 2639976868298760643032429720204521406045309223625840213900129914349013356003, 19566188772309183558708621171466254844006168935682484179932109913899313817558 ); vk[21] = G1Point( 2139270971166084064142886322493582668557568654518354506706091668657606649918, 18406686326141760590291039417022029691447522007039299672030865643232638868719 ); vk[22] = G1Point( 1927237659163942945517797802170050024654598093492303166151832821870949168436, 20696170542122237206323397701908829601416564790029348177046784235621549791818 ); vk[23] = G1Point( 14317543828849607859431449048908241632948157957160799908685822418541613863794, 2940949782798759409740642151149106325741967669791538128787772556942818080647 ); vk[24] = G1Point( 2637598738352507870882611179779267654732690768918012223693931967035502868003, 11289944597077752071412885596022974894446205242845940737182086248751501548093 ); vk[25] = G1Point( 1532439963276695166946548130479308531965180057559001520948007948566867871158, 11824176127819503941733147236373404081814469566040241036455678683958197807227 ); vk[26] = G1Point( 112212498393499599623002286431778522543358321687659804681358238387337096968, 12710489464988264182572574589743934391298101509654758972707572637820834678496 ); vk[27] = G1Point( 84450175545802156729674504891337638126050791302274715412374170783053180606, 3026835677602920375948901368579062784474771534672645085750548846318505805771 ); vk[28] = G1Point( 794276541260633883806602022295855713524587963925343681019534063196659431285, 17046821864895129122284070341138756294391938054588473989432903697052161639917 ); vk[29] = G1Point( 15312264798413059191308409616928541635648964494240760673193913260156126804097, 4131000634862162170599562269507094430364609903491238140287970791640467783642 ); vk[30] = G1Point( 6748077842713937770983358852717490406273997438343165720559438615408726825030, 18665832756351907536862209013635594167488823176241740762323398077929991759394 ); vk[31] = G1Point( 5814676701960652148941910036019955703806289995364250418398122986165817511281, 18448532455341544719666423124457037239427632862417060029369281762292398707615 ); vk[32] = G1Point( 1508464233029183382869327031022734606654596728837292774260830083084812375558, 6923955608879999364226182621014358660309505574611219450186197273402940534964 ); vk[33] = G1Point( 10947337562348086381867493348186290521522963819183546520228115369698642712435, 19593894807941204549151973608086579659760153909926221200653845801569084290366 ); vk[34] = G1Point( 19583632207375328540633670298937602951206748364602491105862114536318291640485, 5160613053570362431336986768430425145438210518458073443144269007734801206051 ); vk[35] = G1Point( 8775514004428794000199171534882502338993132879243551032306611712536771741164, 5981406504575102067259862605124706837568952033690832502278052885191394509629 ); vk[36] = G1Point( 19114249651450145081860826564198295282995391429371905996649311568438228657115, 11476526482772414410179901625755346397129144926116141606476468524737144276246 ); vk[37] = G1Point( 15536839644249293583940314834031420069505460303668929415399089419462129069686, 19462533063638600336482773384806310884406032123240091161958679238548518386279 ); vk[38] = G1Point( 20861728658946711486234810805795882096668089311734956466930219635929769011727, 4451208153369907230016200840872204260300683891068410655879493670234295919678 ); vk[39] = G1Point( 10476505588399690248736596313698901455885560083318560703361252735291192502475, 7062241275811484601355698381254679955026977908868968606139703050337629302464 ); vk[40] = G1Point( 10242416938628865623217497984941042540200987372871767293213065276620528731287, 7766852977209102503334933616139359057913477024217486701562210293206658457000 ); vk[41] = G1Point( 19290757574473847832704449017098595519063611101513560256328257990295935875029, 4762892452062341395947156253733004605479015629354094465744116682319206334674 ); vk[42] = G1Point( 3685480043944652090210241852876453878305139778852404219173159179617599199992, 19206490327539556285676670248094425255457119088662368423821634839985795472739 ); vk[43] = G1Point( 18994365877798343676152521756565538575817566967535130828183148992481484742132, 8990587450249403175033796195945793792649230401779271349686447311683886003940 ); vk[44] = G1Point( 2876040824910135159605209469977609004493536925522309192531914227169576267620, 7387352974280493358172485824256789808637131412907860755257309465866240851584 ); vk[45] = G1Point( 15794021595631576516193599476747719363818112371084745376457357538854822951115, 11915599846917807815856091863868625704507923844628525889673419185304535728840 ); vk[46] = G1Point( 19214783225418795080452701267238415262313286563678267644075398068217130704141, 12599422867498856343868011576407836967848344004000670821803236425864873629455 ); vk[47] = G1Point( 19227571667118399512097025453184919778555437782510534053711316257405486673096, 13439970680786385721287285887210216814531201339465405619441060894600930722901 ); vk[48] = G1Point( 4327652468635959864443834599341897531942999355851828953397677497598767889283, 9689928434264636932003920986563191237774203599535812013045114384049763095941 ); vk[49] = G1Point( 18941295447766462691698964792870544680587811979613105599513120582778626794835, 19683314222292010416126375172425891332112317953464767912269660927323799601962 ); vk[50] = G1Point( 12120739014746050219611392444648484874022921397895819512219878173150988028285, 19652166490499132354945392468684977565982799909662176404224654744745265852814 ); vk[51] = G1Point( 237881758234402446954222664497950338546953329230595214464932154014857259810, 14719281298519154581527278689846993887182633656982669338984391792071854460746 ); vk[52] = G1Point( 18632829073150434079184078062978158310281561663108318750482322761901608350237, 11585829267653250865583840264784434968947377312801084021909677935331542058208 ); vk[53] = G1Point( 18303318649200728066996385537355144797366276444827867523233113090431856991553, 4235365151761839575889104844093205347192161976241651275273138734693062995174 ); vk[54] = G1Point( 18890090581021735966617325787828444397230266865321792718532056454143571062087, 20751383109075825084584433957728678864553476389090513256294990631370296966775 ); vk[55] = G1Point( 5836615824430432412845469850217993853363468809169064321161133777224314288956, 18422497239304973494488132787029234164544624132653818065513104257814941620467 ); vk[56] = G1Point( 7589733185782733030323901830971785796043933038412074379542529348116452542009, 11766715718260192175108225030457579337570056102827555057628090049751698952022 ); vk[57] = G1Point( 9284002794021089888237792563919371858561248534111396518056613715339013981764, 14569887250662968688765556238228545429572928572890143209313693988047486877496 ); vk[58] = G1Point( 17043323778763938388540520294617087030687188857752301527180701122590597611931, 10687906490560375541701187007132402841508713771263911096811375502990430583018 ); vk[59] = G1Point( 14221826038609378315287998724283726864362972417471724680789462121102436203348, 11071071433361222743085391621348661563213999443606119289162965962287706907836 ); vk[60] = G1Point( 21594925826229515150079929921599290167488506281953995378516085711794455729443, 5393732559578356519195188735302243112586009982291959247850928095427075449890 ); vk[61] = G1Point( 9774156241709987158891288027242901095420496179841233927400219817441767372464, 19697221154608740394452383204841289366110396368029185754578596937584487958413 ); vk[62] = G1Point( 2026354360306987153408567164279210760409544375767131224724100185674338618404, 8746417320997349034385886335700462185669911108823134667924817847148915347336 ); vk[63] = G1Point( 17167153551489355723201214959310738579634959967962102363751469276595426325816, 7086167752714749227416869760155950483135682524075087259439165981028401935098 ); vk[64] = G1Point( 20198554763097394806891164526885569506992705241828569342283518901388886689377, 11732875265789693726327424337714782234369043179920143122245587061180599568408 ); vk[65] = G1Point( 16936441275108174415382871279660936212816694584217127749435800314024955424778, 17712031854234440871150465658509554958651335591201262736993565954299881246703 ); vk[66] = G1Point( 15541343147993528013387748692192873710549767789832939967293222115709175048396, 18286138647636648933297481758054510371887066590343183750200834396802507054369 ); vk[67] = G1Point( 4887467579260161831622592235842366325990329894086791954002498853086577667766, 12599768813323827579422011820617161718857444906285658311114907962458144374532 ); vk[68] = G1Point( 19036077848419410583506840133132192761572961289384983089968935194354088235629, 16577018619671019046267068634097969598059462253425555669069639463243100747842 ); vk[69] = G1Point( 10589323327496365317781367964937866604015045840960285135061986283790113793435, 9087103423518135119255769906481473722886482025596605541813895320137396749268 ); vk[70] = G1Point( 18842003045251709036119479696528229150303241019822364177083819961595015141039, 15517974467180247095855112596633809292752186132955233504113145394325906048303 ); vk[71] = G1Point( 621470047133153418230065055370325218853405067301277632672729706863610783441, 1699954733295783108415731174577278311520551644294951750020243242549676148951 ); vk[72] = G1Point( 12928066978673525302795425934191228055792821510296155990559686241811730551641, 5687435392608315219617372224692722371478970971680686161675289016966600332002 ); vk[73] = G1Point( 21014891738649053731694722109777721710061025605415518551868045485194157100556, 295697799079964412603322994909430562800635535065837839046710594350095884180 ); vk[74] = G1Point( 14704185573980033596322225212495167180934670683712882419604079607794373927142, 18104955373363843217389791810697933643646368703752062999806939389422664090054 ); vk[75] = G1Point( 21150973253828352776506019175585137583645522531321080474110129101144005266050, 15476352930072943147678403588042480548592566921699068205245617259310442412473 ); vk[76] = G1Point( 2069224127534729711554035166684958165682850879697786311864180623747546377725, 2942484374038376348218498685981841570693477989265484890640673881576399582099 ); vk[77] = G1Point( 15315859492637248346967659903609382952207241383665855249360263323781447030710, 3696246630678696300750866833898715093304100970169309096993212030719240900629 ); vk[78] = G1Point( 1974763047654268386498873454955400277206653866752705515364588990390156023003, 925645981327722971702707136794891600674361676163218764117832492815387764224 ); vk[79] = G1Point( 17884622877944795733031665179693292871714857266199154976848024379706970146638, 5469345949238498948003812109193099731978410786063261781003175974704362558977 ); vk[80] = G1Point( 9181885799005901158707642150087847099905452825385637432860280517016988363569, 15441249842491998626306150762025474856762607708256540486012234479945381928910 ); vk[81] = G1Point( 3759496225362224577248002160411962955814565360065050276980645082402055641627, 5935011984113464681402587154865188867731699601364798939705631309428001462144 ); vk[82] = G1Point( 15097192620507267169986959120043804749683071138365521559349178132037151885051, 17908485359988852043093067898430122752351850455891892934093055401762858197782 ); vk[83] = G1Point( 15537437755033882412101966933599612638981426715605249481930785499739867489224, 20942305010995021647597860020096936003762840210415503625798362396318490275895 ); vk[84] = G1Point( 12119146910409640628091721585894849575650886562946220453779720616519243016436, 13410305235683987603382394290067039930111537434367577245064020179921354302606 ); vk[85] = G1Point( 5249185184085883593078033297186849185311283122318950973375008737958380453429, 1626841357719962040949458263266786940209896969477409173090841052704933529313 ); vk[86] = G1Point( 18464630000378045703134180305927360433848432412796960962363823275154893708775, 7360217317730581401998264706795345661025902785795378266490779940627539852201 ); vk[87] = G1Point( 16918326974254658559854411558404483456103216340170335119692491971223658767572, 13490476801873930080683649088043389957382208134286149325344516629835643752037 ); vk[88] = G1Point( 1459559921851603078766076256163673534939391742779580351772404215873020743579, 20629905480218711853211687273505769648091531837560664940379555357138192831734 ); vk[89] = G1Point( 1558372353523032867054307913585710549511994902648270632889827438756138651460, 9986740180963607562153690897459301965262512228428614018065362803904509691380 ); vk[90] = G1Point( 2506832722024435312827768092615914632599562047480687199337429204780529581070, 10287890505908806279671106644144072406099044994496371048524403968455410854257 ); vk[91] = G1Point( 14817809635479489699641585124944383474153667178766062902712365353514652137164, 14591833902142153814139517258758666620558640323654065675364323604219009464728 ); vk[92] = G1Point( 14292409416184877463021912194087926206835165773003412670633271179704817620161, 351067241732773766932092439700887767467427558258551864929360212248928456114 ); vk[93] = G1Point( 19063353678932378910493336081610845032566166386130909067953996633938909496909, 7433759626972816518131687051012442019608737789459058109109351160296472585652 ); vk[94] = G1Point( 7517486242670988843062885219720937925657930582413962007972135680057733486865, 3949405456060790882720362221650479561334414465835124090168809195243690734025 ); vk[95] = G1Point( 6343077278985446235408248671043126134842272406134312725212438417156826246943, 15103115808567544137964446320105282845532540456536372599538816208782651118557 ); vk[96] = G1Point( 21010047052528842357960005037205410504230955968543846891413421823590037454316, 14549062331351581189899472044923757849425561391976728737079707752355140037982 ); vk[97] = G1Point( 11318303814606514209912371311378864942495474734090319362631534371086598296020, 8244860275937944937356574568939169936401433747206816258183002842802971991032 ); vk[98] = G1Point( 20547861403802667568241638035695757278477295848067410809458249366655752593788, 8022350497062802110338499652086545468597343443366418956216931289823247948618 ); vk[99] = G1Point( 8156483969709513955102273330333281930346892331162458754170897082812221943140, 9559677424494695953773620967422275392896264293969335546549769746568450163841 ); vk[100] = G1Point( 9440809148011862556974623395734247470581005158317701517995290948210647853666, 2369573725572999683063330590312439537535671140222943207639379654947331629112 ); } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Pairing700.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Pairing700 { struct G1Point { uint X; uint Y; } G1Point[101] public vk; constructor() { vk[0] = G1Point( 9440809148011862556974623395734247470581005158317701517995290948210647853666, 2369573725572999683063330590312439537535671140222943207639379654947331629112 ); vk[1] = G1Point( 15318075028679836795452153842860929890016302398392628783129457890273570934487, 6906947448238486597875378661481336160713677511969082375414289173694733965656 ); vk[2] = G1Point( 10232724436155922649395198778712549217665840026298273212843357670274128849176, 16263424411784684658203088908775423557688610856569232734372680115303672658510 ); vk[3] = G1Point( 1665830057909672810829770362814179438938699491220919656214066905371213445470, 2243152354682578176076884939986624863362958181872418838647707880017878562553 ); vk[4] = G1Point( 2736950133174905282810330597718364690869847241891841818631676618288916551505, 2337688783171283155243884169326878511095527547732076243378971300114747490862 ); vk[5] = G1Point( 13556510704376139199626168188675775603460810796407930379490522536905731836294, 15919924705706642804061711676843725449067165094431524794440078218945990108334 ); vk[6] = G1Point( 14640468552519220641136124401086122771188593469934705143936804630076393333597, 1935843002072423197646660058342977272189131140140513884479434649004258548460 ); vk[7] = G1Point( 2196505794822363312427947391802721034682135051475015219495116010458463800735, 6326017855562636768476254250393912677771655624807307911890576808255727989947 ); vk[8] = G1Point( 7984942812854300319489165441380382505934021580459104700582685800596015956131, 3439088260851596304731676827434104438883162676025196961735933714664576910296 ); vk[9] = G1Point( 13646785144913893288514407575480231707781904647426216519867978350750156234246, 2264066216485377730055438779510705111152670759048258400373442050761359364491 ); vk[10] = G1Point( 14652962885171555262102420520822001313650877109646126312563882076647674349484, 10083759214641473438450804798428485640149966640763745307148928748425610394557 ); vk[11] = G1Point( 21744460526132667767687476597625507953835491210624582536418863451658050926245, 15324313694384227589543794247717458321905285040657658012624474963019283039043 ); vk[12] = G1Point( 20087735637033362500699235459774783804678503279569454520777493263320480566651, 4044845098657295152540372208420039082602525260726267312358400323121099101975 ); vk[13] = G1Point( 18468286038775384817453954050843144883017234706115687542389148416203833428154, 1346353683108704894340189284039844693934663232919262270708931938870662445028 ); vk[14] = G1Point( 11955540328636282717797218964642792954477197172256711050605177437240982850121, 1802816533219466412053079762248904783055925068920743406885954839843830259028 ); vk[15] = G1Point( 2324906646254228170059185370672163039701489245850868481717857919533031689139, 17889320468169194961000111033428458781231566473874088294077735025054363646333 ); vk[16] = G1Point( 21530094141565602955128692423806771635835772727037482080901706020938494245053, 12417085588577798931784586299010724179364597473301366716911339929947975718529 ); vk[17] = G1Point( 10839055874712898092844718786794913539625642087879039364516847991478742942662, 9495509572666530034054587362494460037139501416251853898883027026733863446116 ); vk[18] = G1Point( 13737753549448063721497106257624560388939617486326687733428043657018874658062, 18344496113152595829617176049578796514225730499789576343973662736670642504358 ); vk[19] = G1Point( 6454046004836841251988354699311799564400790339156958272645380729957151051861, 7334775708641941775372475268384270433610842559125214162984315356831492034812 ); vk[20] = G1Point( 4985832960599073480917747957463910298045424101068341974358144613129998927929, 15252816997994888008062976409248056483599915347400280731923091723619564412028 ); vk[21] = G1Point( 14304667593420070100606836248166339383790333989468824143039342868768707464368, 369133312246633003904179335285634175029180886023440782195533370236046419339 ); vk[22] = G1Point( 10638050340835437483582284153850558919662538285107039444833944166526052396996, 2416326854948723911020041951744088388170538771642548548511089770080543321563 ); vk[23] = G1Point( 1184576113094836674053974418747252670730632245327780912804003777807008737779, 492589508170803219174060296713985007665453381290523700606395452549066898417 ); vk[24] = G1Point( 139045435506154294305482137647494596325104324063724744065402213944486809494, 190167081571836916600349514520491156169308361044747901097253822629402816714 ); vk[25] = G1Point( 20011817101672486002762129096244368410450976165871542972419461150024114511462, 2268754177645246617760603232154016135005591683438470858703261231650697607414 ); vk[26] = G1Point( 8126676026642507020784966084610609603051746012006143152165739725036116438162, 16301460636769933596924297639691099123279032066830201397997036814854708411234 ); vk[27] = G1Point( 15182371140434545734919976399096156513200344170862705790028451933899990088750, 14886137234879191276754321218771210844645087220883691066177751630733980544858 ); vk[28] = G1Point( 9482105089608262545795941488575944982828037660370638560171572400163063909646, 2478936322789256219800807804480361936040667208279214722379594110551344692030 ); vk[29] = G1Point( 3526858519483000909925080586712720004943102679738469025151963130491726474118, 4221816626308591756087962828353317483319775685411137598790228350928597261585 ); vk[30] = G1Point( 21009385654466261656575466339985816290472884172459452725544957676016658174244, 6940606392732842500906992731432385152348952335194742200111037243366833841029 ); vk[31] = G1Point( 21487289791185583317219560880873212024175148668062626671194632227015133222199, 4678176459822177673341929134380007205388373015951336180858949061095169770339 ); vk[32] = G1Point( 4846338358430393484718989420778440439884942924712160292136034811973321170391, 9276065995362350098493913667710556869028989375939284218506887145545531906308 ); vk[33] = G1Point( 19807352861051076128323371895420679622584824587669303851839822984925468433635, 2819338108717818835966750401327263034769854678308154772288224264666915554500 ); vk[34] = G1Point( 18442821910672854271372135076414665543447027388950355144793274885854570278356, 16110897164840125885115184924229888192957820657963124150253545635057798271182 ); vk[35] = G1Point( 9845196253801508627991031814739337169565915679719272798146816453280317613511, 12217225066674011044197462813174071395493307134207346036288752443912591910240 ); vk[36] = G1Point( 3923991577928869560407118448271935218211526781929533551653244675654424987399, 10670233863120436333851986400321650576317964760778020746262978262519720523467 ); vk[37] = G1Point( 8336898532627120252759686863720369395168904730360098007835038795036150945342, 3378619508622787403718694602199093220355649059515345767006084234536150499983 ); vk[38] = G1Point( 897285997625370664078917573668630146198661974767673900066084547895943597017, 15524491895767300928092219966671572144578566329524261304882078288153471456094 ); vk[39] = G1Point( 13384461114315229634398048586053811915933365986154711031203551918662012281832, 11448176211085735151424618883362500388640800134188666775561558945685832848059 ); vk[40] = G1Point( 18189127221978188942884755581833475186131611253432190657741855375911166761225, 10685515718448251366474366179042702996077788924970477576224012421474733557897 ); vk[41] = G1Point( 17669878833580716738820657576530163660678305606018319861039036613211928620817, 21133146172609391048774366251950682288362049186851806207513109688734317755680 ); vk[42] = G1Point( 20777601464794113064251759589763308438467593962518402398283855435229682299107, 15679067851644842089735396247563945891271816010012252610910185557788361880019 ); vk[43] = G1Point( 14966983593274047863845710067241688224129354842974476374337241633874466579607, 19234292190779201725109147651168659414383152620598049382341940844817018622934 ); vk[44] = G1Point( 1665611100149892926010508881688633103296428822802069109700887727171335246092, 18579787392035344373237138556720281016993504135836210646427065033360300740258 ); vk[45] = G1Point( 21621139916842523940151904650736372715765507445980637564264669378213138587342, 10656936236721347997226972505595642672700344736491654571580898227517267642586 ); vk[46] = G1Point( 3445992935168360957003203982661175892765389403990727161650356622172301618604, 17096344067479737500782690015515577319540076944697298975198589510970212389805 ); vk[47] = G1Point( 8808337981493967708532504567464514716947731837557762493699692522903731420361, 11777725522778475464811091473323155511025217479759858596574036472535468933552 ); vk[48] = G1Point( 10820947876086700990878342770240846363511844052492888606666956824734174582218, 8150867701962639232510639843118886617301614731650697537642292104962218907218 ); vk[49] = G1Point( 20470215736082110876225466023279552718086261383391207857735359415463230727032, 2085842957061910436375271746525475684433040972939319674967459622731274166749 ); vk[50] = G1Point( 11337639513314171351013256585824613676915673825335326239260711580255879801115, 6256085984540539085615027987075404359248123195304523024202811604406467604564 ); vk[51] = G1Point( 21288595457655546321539521842425301747350852589772625480852585020902604902426, 1249843466883315098591086470818121767556973311849681925182351439164834696484 ); vk[52] = G1Point( 19899217332602315880773423298215810052418460371844166790042861464687941166547, 1378572146164806219595743244678836248431567305813489349742760245969238797992 ); vk[53] = G1Point( 21697354656000870693304791510097370069383968646624608868607124771843409088617, 11876413319300247267059440651346949825880735244477435155007039913725655766588 ); vk[54] = G1Point( 17481120850448742286325898054004677716934852008094860216743190813696103743241, 8201297043617640378371278524187651053623476160344124146426957226429953015199 ); vk[55] = G1Point( 3005289924198481738469386520618340385365691375464779190742383298716766106992, 3798750761552265556656507688179605560744908100854758185662716950349458325432 ); vk[56] = G1Point( 12080339691736120532643853171181267931152090956831962914675099644407011242413, 7679216576322951837469485160860080246434668790644856087664310774786340219603 ); vk[57] = G1Point( 3017707941288367829088052277266228335338233603570677991113493444241851347547, 3137876190344429636984844767438201549784097665589492331513832717477830949575 ); vk[58] = G1Point( 3314419641758595753659230864962853929657302210615955058347565360331432842511, 370657694674824888793668707329582442550590401526016252710800442854034822073 ); vk[59] = G1Point( 12531360081127348520803889885893430887143447034660271653024546125313920625041, 3706773617610711184566457860651115015047587714843050105191055901056951123775 ); vk[60] = G1Point( 13273282411973793607861784434723413044950529229053165751072541737431617592633, 2933824629529588293040887033169631059354313042236996327457876788602236178666 ); vk[61] = G1Point( 11454211545482193794268334706906672453070160000425255303478169225799785056171, 4701866737494737667848752430048064790393723029982177174760459025647415493343 ); vk[62] = G1Point( 3226876539587975824253734883494657032240164911972140710515864979983826807576, 18885227222812885519565693818826301632514351665843638955834614001238551664720 ); vk[63] = G1Point( 21256377426860772429157054343932985892905698998661980237211382204396470638714, 20700712575510158621998808888489798414949519986488584579416259248995522851418 ); vk[64] = G1Point( 21861786267281721340727261768960462407333067918067989326447913212770592842276, 591001657621564141201681807588662398350263007914462125203875613968150437657 ); vk[65] = G1Point( 13247142825778829724328102956320331554023905306148180876995955166386182533181, 3617736073023964052562169840230836224459626149212725300135757231277487473772 ); vk[66] = G1Point( 18571408620760464675900058729447123565097914393074749086337801426155531357818, 13743756586552373252834608181468885899640079575730745687516486866135863903645 ); vk[67] = G1Point( 3720980971604229890264847046378487782638291162470091687602731478085296467, 6084172665846193442582973123440713896205228741433466091669997885291480207028 ); vk[68] = G1Point( 18573763810245517418639262092434980232325583684581527263357319084944570213450, 8653273277742119666913461937453761328280502598771865810060367232987628034250 ); vk[69] = G1Point( 17771082345997588650824796512379585216955210531516942698595993660809245269232, 16629893348030263842237883724070855345464922671711466998275130688743450612346 ); vk[70] = G1Point( 7338691400992204970014165784957357668161159776651147037555821666761126907380, 3705924992700866020534892130549475719146989962914702725416258691087385371190 ); vk[71] = G1Point( 2052355044216434821564052981111343609375679060336427387512859984022224044874, 15268326926563766258839885139280714077759092305121832482198777135003010414903 ); vk[72] = G1Point( 18064152787981239149606586028411770599646851087777099175341453985635891048974, 5758261233895935495648223633806227190778857865361754803237621075864794922557 ); vk[73] = G1Point( 19111174614243915368909621978011942943947696253907134871326185228263166811463, 55479280864981829453785909945499596585934663637540490352091218262790817807 ); vk[74] = G1Point( 21572198467165252889522351352380841583977427216856964479483251269372946010366, 2345827745074569280774155697329343452443815213012561331801321306363603342898 ); vk[75] = G1Point( 15941834803493886134336711593614605107429239589267432817886895398197185549212, 3947709907544948327644041953329373960515540515572778616814282410080395508832 ); vk[76] = G1Point( 4633123534127190347827193753807476588202800485371180568344594379882767409472, 449532263245413245826291253249966920449070741031176517806362079985429699204 ); vk[77] = G1Point( 10268447195073622715137083952769200116950216441153401816017144348827097981644, 11014519154992952585639434973281546235674068382469609940982060669012254625049 ); vk[78] = G1Point( 10929521602517897709850629137285162565906147508132403521696170594109080701944, 21509909425895040573950674106120782000241158919930204131530559382950838998391 ); vk[79] = G1Point( 15100619628435171593543850901640490209866254607928075153538760713990045850303, 10442892609047996498519806259742624382008709260868724454066808175184715514873 ); vk[80] = G1Point( 21843959294108881062590024710421326129806024810700259156439039031593999701643, 3172495648177936540367468274822347136571308354704236044741558883273231646525 ); vk[81] = G1Point( 1159965505725043849921965815010783448947155232300987681835997103232694347481, 17895771558635391086993801372767923731437665193374586297480961769145647137160 ); vk[82] = G1Point( 6507616620793362158142805457368779151039507583917257718825202495364366512771, 15681488580781287762163534693440431743803367357345151854182776562998569208980 ); vk[83] = G1Point( 12814039407411091293859374060045673589466191829420083574399940707751465761225, 9921363265528964171864400023090100733610301136126390954832628789086307360330 ); vk[84] = G1Point( 15006028241180564287322274819018849976566235200309642600445049768087552688588, 14361253381523713031854227412596864494866188906783060963450351948055547793422 ); vk[85] = G1Point( 8756721339492266735713698899407035226934130919921494557180936772641389932137, 3548415476667864206509977837524249204352483242015728861933739872119268812336 ); vk[86] = G1Point( 6230313188217542780422481357959556867195597265162307208386521999420475922554, 12851754457568807033120245152349042004417001439091683959351522506453268129018 ); vk[87] = G1Point( 21771047292298211615870361795649989045841286446573616035285681334849994642792, 14661525648026380124158975239185394052839523320557698240566443363101483984706 ); vk[88] = G1Point( 5452997622770127402704007841410646483824633269304350008222506428808016149352, 15964772002156686217844177582357873408670879571833339501331743013322376177413 ); vk[89] = G1Point( 19418627841332101860244780132548095221604204548711828994979491672674661101186, 18641817276522447942931176882796528922352915530694097337534100417837378090505 ); vk[90] = G1Point( 5170178768764059003465306465862923505721180092357892642067482111376422462560, 16292075720542416258281919877302226890334681177149723464984043692849198938515 ); vk[91] = G1Point( 21428458772825703056643431938043979656975497408178147162702507818606254637112, 12669252472492383503929166513607086634606571727926148034366726753377604132130 ); vk[92] = G1Point( 11511741412661577053334100231545519781542601225911626010001773570941781521973, 1922508687221278919615308146316092898338385014957534362889216743475722386874 ); vk[93] = G1Point( 14619278216684346430481470847265257256536064659065561539422115183392054064375, 4923864138475225113538825583664123279747028999618317879907718283379102732160 ); vk[94] = G1Point( 8189555561052452582428870381320959534677546020283223689489980283591445785575, 5683666798184731981996415590358687978684473547462253523588605793555562472541 ); vk[95] = G1Point( 8897957337103869663087162380105747076714883391199581662621194554976044780584, 6927678115923034019960143700173902535965892695901056423853498118708237353848 ); vk[96] = G1Point( 4118147152554157650952803163670081114994515119149218879659651529875426582434, 19521776423474340073081384962305127452679641989910491209025946663191129399856 ); vk[97] = G1Point( 8199369164715592391163039840824830201238287690146271134520067390345622199716, 19049749255599225169445818183746192203784970578733702608166333799300917468408 ); vk[98] = G1Point( 2621331616746047342119107296268526819659807420993801509193016057772588459587, 3714747974293459317220483876903845314809250288107020652709574106317772888105 ); vk[99] = G1Point( 1708215042304182557442018546363952961772236357429287076004515766114579471031, 2425075910704693171603894505443381911930289510088402398879713274371959189682 ); vk[100] = G1Point( 559294184750664917430341870656604694071008897392190220192116267892035169297, 14243148295708619851230110866382409248552700930031870832819191159537034402444 ); } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Pairing800.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Pairing800 { struct G1Point { uint X; uint Y; } G1Point[101] public vk; constructor() { vk[0] = G1Point( 559294184750664917430341870656604694071008897392190220192116267892035169297, 14243148295708619851230110866382409248552700930031870832819191159537034402444 ); vk[1] = G1Point( 4641363513109937726320639129538123435956871701621121784383882099053889085064, 20015785064628801009980544726216690068400827250235677109113321502136446155777 ); vk[2] = G1Point( 16761303904856298299723450063499263261483454775470104686716380205610936215117, 13937501019878575606690787479765559875950982439900898526707819920574210396914 ); vk[3] = G1Point( 4125021621530671520299368135350154138496853482199634065524307735783221506172, 16190459597315725346983317532130332429646848590679639631247767437744875471313 ); vk[4] = G1Point( 19849240995130280756599784958846981127053605278814133448560169288281337309250, 11675912751007343793104404365503374415961442385969482964253099999374794062521 ); vk[5] = G1Point( 9320713791229663102095773152315323259617878871788417932186351427686255118215, 5031819995598549568272731745469059436781312050331635201450144235923913819165 ); vk[6] = G1Point( 13435400523688401353033714173705698526346444283986384351204468887236374243491, 16366291887622641881341748933283220710973724541093918051192758943031982016569 ); vk[7] = G1Point( 6394497756473108680268412783622560947673573875638773476223377474748359340482, 16847378050049511773766978935578345782128941539265621623649163971493855796381 ); vk[8] = G1Point( 20572347536123228112123222354601623030650448134336711995034494364795021967029, 2935563205635769425595140333141174534691698868963874628523314077352096362604 ); vk[9] = G1Point( 8567295467469849108524564940259882891955372381347517958712448925853589665433, 17126506123625180127332158056979074978461293945877981144093438061603200266523 ); vk[10] = G1Point( 8385757135462166537324267186029549888285610930656993261385036491140747602783, 11755922478946920908937886748961603502459105346299168752518518469779230835019 ); vk[11] = G1Point( 11580532764627946652657666049062989910060745795643217021469313338866339876586, 18631367422511443614204583369307231334442077623145794064741115894921611169838 ); vk[12] = G1Point( 14041857815642320602115178041614139704000973370587887995705039985955763424431, 5864590125302963475551411622473450335621230404557783931673319724478240755591 ); vk[13] = G1Point( 13003078901866419565251336650095929315677623453524699304544704118146032693899, 7434577392922660618913874742370426348845330053880326049141102509615656510130 ); vk[14] = G1Point( 8523168013225288039668369351202506283884748730101503095849677161696861727061, 17296927326456089985786458745213007430778604788585175602980164813117398171445 ); vk[15] = G1Point( 9660850928841930392943855243257513271614052667226722573101334729223191871508, 18459663369741235469869910647511028564490332634725235477357676802479305538572 ); vk[16] = G1Point( 16615855050907391851217631456166011888450049810710832615364270265670650659733, 10457433051932657549358211606983093776526347686143076624149865303715361727213 ); vk[17] = G1Point( 17240450537953206327013842785080512909236045058183966403673631770301676553751, 5053117934145447407837524379435256152358093853705164607685296653679303508184 ); vk[18] = G1Point( 15159147874382495636095537308753383252505234063484926711720521810564064894868, 2730602936727665764041791998668828945466088714809904804925269747736936895637 ); vk[19] = G1Point( 11971237997442160578398107588396043422709167969653731697964024015671062484127, 18624368115293893912794901974305653099199554892112368530201890203151889033029 ); vk[20] = G1Point( 14148171926714710541421151615058634067868424745873533826286459021369774822941, 1217293042425251216903486900481475344968197904075908396477749058366360904927 ); vk[21] = G1Point( 3648756337515485492319000929910620903716386323701507924771679882925736405459, 5752358590308137856835442824755986983599641197902351138051053971602974431317 ); vk[22] = G1Point( 209381891984727257109125768588386411146419455690232216153158232964413132704, 7089417592738436341300719490729326354690820629043685201220453351997684142737 ); vk[23] = G1Point( 1764994832824116059592766737448710839428842779486436562970822565609476627624, 10977618615351529441603716772834209463266792823084661596055923061356525574307 ); vk[24] = G1Point( 19369648758696782516645573375916583073152491921276410048538210813076080246665, 11175317312200664742329805582772532883722779774480052491328184169495063673169 ); vk[25] = G1Point( 8984208076995628696275920884394615848732859203175750037018539325125893905015, 18213554000898869653960568096579370168313137924243505286749801854857943405320 ); vk[26] = G1Point( 3064852110349989722997878092689993597406379162130146067448574736107935975509, 10137622525579865627368848743060347355377869324168749065310183578344158294521 ); vk[27] = G1Point( 19889968145673137197340044172321694214792967568470672362854336017322946357118, 16570474991766989094289705454015227878425908060295684975204210736405191583930 ); vk[28] = G1Point( 11130463074147383690697360174461268228037898050713131099737593897262701893800, 1991726988028369955660605485821152006597430781905214903499537837199235078781 ); vk[29] = G1Point( 8557290206677740692987545995107170043268650781450157988800207193128419550641, 19399364359027378002105314683426149972036136696799210863065824006912471534463 ); vk[30] = G1Point( 14813845139854454170967063491974548636206374766806645984427229914816971890269, 8469630046298368462578736674514224373144384794555108842480672376772618857780 ); vk[31] = G1Point( 19696272297318277446148974219367795785176160925123080658796096682846947839099, 15601963952865177248796595795980656131768830043411373657795642680197644125633 ); vk[32] = G1Point( 19321325379329825681586926473146524150458336855530772882422144951457158646184, 17714280203077819102671830011373187991072073433404289632305952140567085223439 ); vk[33] = G1Point( 18229404129763550527789836682419669078651778151302870909023013484829101923277, 8316675992106316482631479790103021816365102565331244485521069234240710542227 ); vk[34] = G1Point( 16983462463988543679912134597738024367927321056405749672110279517034684120756, 3469059523319362523686907070815620464956956429746076771987477696878455818075 ); vk[35] = G1Point( 19463552252930414441780190749485646212691510632079363337460642878403342603781, 10209355483663589165733776069811081154722152222970718843912999345077275964987 ); vk[36] = G1Point( 17486291268496844685353759747743132018398829324074988098634886021666829526120, 7847921824687487315247853200034459813397001655237720587439395103825842477633 ); vk[37] = G1Point( 17722651172175517076018389341863710965250262813407492884009326305220829065046, 10487691456526659835471612235752560625692013273489396243202859376295776923558 ); vk[38] = G1Point( 12744820202486174413654630704075648277206967652161891634716443809645980148619, 9716994079134748793498039006424003304274943924035623988851638295300650726442 ); vk[39] = G1Point( 4261706872562368220521815494673429540987867440678498451594051054386399994855, 20186486428381910208029689089989935515564108102146971834924129763478010008589 ); vk[40] = G1Point( 15454549474124431277518191134193380988246851564390984114008701287659103488738, 5874701094313451297086254207832084969795768666547183008624506347933551613982 ); vk[41] = G1Point( 1676058046629490551051162125725983133518221611201713246164689759687811777230, 17565379092534989417079550071289175809180626496723020798655229615017755897783 ); vk[42] = G1Point( 5746917482619697189210947156745304514304784446541318475379352595515120538103, 20817733075396732890981148463534404853694746012881282255940208250049223546349 ); vk[43] = G1Point( 18793517338798557027747585024866085274494902660297229291689721509348767740905, 21544111236563968882169095579878601719958652484044645551232479643013159573704 ); vk[44] = G1Point( 2050459469015547658107090915715746131330177395869605527888554280113497217464, 13619288754540054083009299344410666963144385746438742435132541338142087254705 ); vk[45] = G1Point( 3649972772852790099909430799691395764313064728266332656591035905877494470290, 13880535846267644520244990301361207558045362873058999463704228357037261536384 ); vk[46] = G1Point( 8709530849166942343432753194071887233880928487708567842014440249006022409104, 5284828882766470867313223435942045546259032415963895813171706958667394056063 ); vk[47] = G1Point( 2135424078714565208896467689927136192173996886982424807286133483392901352846, 14130115279577774334133855529552836877996808719240021869901068967804325838910 ); vk[48] = G1Point( 6022520093976878629503498248026375976407894828309455065335894190022147190220, 11403104453086832749695950325884963130345687536029692444804018665944668604279 ); vk[49] = G1Point( 6949610571741072245423378777184041385742746581345060770731129218528069168691, 2481754069589639819477314027612972874952154233746246533449159092761521799354 ); vk[50] = G1Point( 11262554196517517734273152603768911534102980853976228956329832125031878464588, 11450115278732766246844196258072595414789004372699549092481177190180936235753 ); vk[51] = G1Point( 10655401840334114227397353696707877117940436643479939754864658902040786398751, 12645898306281364802807566563450978718582354145577554431572920212633275587645 ); vk[52] = G1Point( 1451637035525156346691694147408873582423855961904315712768968671379206354579, 21481920505757867684258998732762528712052137268344163677762414259360195551645 ); vk[53] = G1Point( 10729013981785314184824036054045624524903840797211684434083483677275979346326, 18325540548040172388617780552337336329335075502659868916464299784397352071744 ); vk[54] = G1Point( 11786217925076316095415633210734166731161609633336590843883624367476419154373, 17211338965652619543010123190127646262981485090623247613241044905333218441058 ); vk[55] = G1Point( 15340468123188282974305874781885789172768416613401328588469042343942414848136, 13007501387512083390255667518665849815976255590034759546444519357038091395702 ); vk[56] = G1Point( 8927307275862985057176968900862057966277124769034733067746526923706021016947, 1081518948268686012535894079888410190507916582839951366832611407877289978690 ); vk[57] = G1Point( 7293043962612016174753419145270515422879993844018007730285031245876245473202, 4191796304669615611124052242140262221049847889202390246191590368840320602370 ); vk[58] = G1Point( 13968064702532109429288299716872067513610938231338108945584393326307786414315, 5373582137274400082389095358511060894456212114692218467991237813007975689694 ); vk[59] = G1Point( 3758596226285051408983226491469599292571492379629611804571761178033520453320, 2454883224459892089575304907655611952745787207648145654621470832587360531703 ); vk[60] = G1Point( 21555824398889026700599110374151173645106507912479669718559466232214642175824, 12352685420281837674248286258618309863574119337875382535028388183453411756107 ); vk[61] = G1Point( 18049730062183079846403584949671353912918246408147951579960074499070416762114, 17536696467554203271932033732303984353450059074571099901758028703199867702447 ); vk[62] = G1Point( 3630933607012987235630819891456307466800940035904035975747221111257046368475, 13051596363701423220490238974162290343812415144186756556299878322198334040607 ); vk[63] = G1Point( 1839454200491531954187260396212125337005712457038159453201056093307925615085, 19016655735355712552866432640664697526672311891779991552019770538297116297078 ); vk[64] = G1Point( 8211064545860586641177910635560247297250779479724407132339977574519271723024, 1739669868104933659011243756220419911357136446325311819646929275406373361150 ); vk[65] = G1Point( 16724148941054764472568062824771629523364628514117508074493692512209331954096, 10711331414381032858699792577024498842588505914841228834618117127702045196990 ); vk[66] = G1Point( 2194570388763316179703402657245159003043315677123788315625713243440893688296, 671995470696736912416128688819430220033820747604662863380695834045477855300 ); vk[67] = G1Point( 18135805027299617087626828261590661783855335318757338646066300829214463553137, 19269082181857927423577474838734260863386955067923590440578662513729477546006 ); vk[68] = G1Point( 268116089608704424478479959989990433050410604994258150035332274187094677620, 14388240870199792936320046199970508821482397995221901305955222626961729873052 ); vk[69] = G1Point( 9334449454521630198822434918214680333551400653280065117677887979118231345187, 7439337143774043976403427326032167679094189499196247106663000510387774376830 ); vk[70] = G1Point( 17768550841203576351356232018850993428168649072771599775813701984974217201111, 7556553618419178560762378484819183949938378097461705888703375887447514648134 ); vk[71] = G1Point( 8441869719841147118575505423141017970813522129056651387343929851596443769431, 14879817316364942991964690079688034113057179186163077128615378086809422064409 ); vk[72] = G1Point( 9579443613395526712253172774200189648220870485724921908657265599500527230702, 17459261788873286383523148509354868615393377986954158440628411246737714705866 ); vk[73] = G1Point( 3390608244460855862258301402695038218510879083584641774443989208329720854259, 15834689492458317163430784079175232292921792345153915531655165792654771449279 ); vk[74] = G1Point( 6849679790997705865253692203555364267187495003347506687946124126477919577999, 17723145278192624788286311121498707441093870502530696174835981364501571342802 ); vk[75] = G1Point( 6503937712237310286881191786078185358704601190277978724791091353124759909432, 3800106775896939434292500137825778490395899251340705032969163231893271649340 ); vk[76] = G1Point( 7668989545382110621659412264165965219146559678740588857155577104808202010420, 7851305784133474266336683776279120533590472641003892804965525502340233394532 ); vk[77] = G1Point( 13291830509644203463733678098410480652709477228950512322251300735490471954650, 15020179339114286405114478208879350729983076254079657989313891689671534538913 ); vk[78] = G1Point( 5685272599604926199513123830849826918087592171335590110941948947213830053144, 17615123813299894952272327324757312899166667209507365170871678818715172985174 ); vk[79] = G1Point( 18099379234782311553131736224577569089877940478140780901969663647196580452384, 11956537138834467747733645605582822324942100218357110410909453608102744630521 ); vk[80] = G1Point( 21472994645061004459217960142508521848798168027792849518928084754756911165234, 13833779338438939727410219270850047667099739611285602255489077320814672408187 ); vk[81] = G1Point( 18277752520724119196344224874834407736802701621981138444003817990899568097759, 17135166935029497016961989546843127186562328356176611056299322156144253716701 ); vk[82] = G1Point( 18452824877373808637009422245788749152632901131218946908057548736994122850921, 8887308176495410852946052122465737385408206700328538021316204271045231675672 ); vk[83] = G1Point( 17153142649650814620553905208982188194307219068658132877963137610185955164372, 5144376829226231038740423705829695865217266800074682814359546508134586040839 ); vk[84] = G1Point( 6811676667384533421124200000525337648506560026302498757961443070626296021797, 12043662332794120237007270233943229217944539492634173472358516349504738514206 ); vk[85] = G1Point( 4590024033678062432942300426566452319360585320139898170588841545004845486797, 7915368968859514901989049052281653979872587436352607310214929948368777612273 ); vk[86] = G1Point( 13889102698962298748579764030115401457198260073830896894848730619766719570027, 19972577516618214248068764159630002660227918567337219464894216520898915185828 ); vk[87] = G1Point( 8535846098238172710889398519351743014181040376590643741479576724836291257416, 13792938032259236288532655790424501005467444692312851880982730549545400793926 ); vk[88] = G1Point( 13884200005489381505949292637923382303278728967183693544807323421986072573998, 20633312090376438491418509172364924582961994703988641825016545586980028465499 ); vk[89] = G1Point( 9216497959991890827793204543148936197274865975784801593823649820012858451325, 10988946369884624320650856755368018419213866654737020241093840956651324758155 ); vk[90] = G1Point( 14526742690456549362825528413182630955767323179314960371140352305995115852982, 17392982062902854369742163833771298777324128247472361534614968867970755644238 ); vk[91] = G1Point( 3756320054919982438216137458737529701833032294584811638907769165142106244018, 2026317655790277032971780133109928039873859104788708251331308966220057525006 ); vk[92] = G1Point( 18168746196925277957122530070640119923133368120665608227468033990319250683064, 15928004968287655034554779403187356702388373717859559208859559211198530489722 ); vk[93] = G1Point( 2350321360596025017311272098274681869364130774559357167455020174355078296922, 20821466240739658313846666434562490119890440414170796738934298410307994029923 ); vk[94] = G1Point( 7576016952097329337545599688696447948485267660955972370906978561349485435624, 14878628859755697611190819836957201473919004645611944282806804220809238724014 ); vk[95] = G1Point( 11597217674039119094596835611344844946425996403240066224460426561457802713862, 8007511838822340285474996205910408034891631673920084208199667457768934693878 ); vk[96] = G1Point( 13458131216735552749252745527447893400632285346761162408552123571290380935022, 18569250196249321686100757901020499704270976462291506106734664138328832308000 ); vk[97] = G1Point( 19880546657682223881549963383452654370983331362963681408248722144655667884976, 1222970444335859511430541942120238521707626872145745468699182644946185157079 ); vk[98] = G1Point( 15118012150205245414285454420783423739054649341973803838107194785809110289124, 17047026265044764935090336242521610457394983294856036893253394185761254316130 ); vk[99] = G1Point( 8223451871709830052117882645338758668088262575931923010898854132730047969200, 6042153099574221150323639542394054393208297275054855891452516636729575050382 ); vk[100] = G1Point( 18307463072870674736741132489299673350923024551765424057435422228540653970783, 16792651768640733615873201158696903896357564953934877895980220834108412218261 ); } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/Pairing900.sol
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; contract Pairing900 { struct G1Point { uint X; uint Y; } G1Point[101] public vk; constructor() { vk[0] = G1Point( 18307463072870674736741132489299673350923024551765424057435422228540653970783, 16792651768640733615873201158696903896357564953934877895980220834108412218261 ); vk[1] = G1Point( 4789000056073433326156153267653182197217802322824905811327056766712647642695, 14338620651847854558910662138949844057308591460208480064151185711964689436764 ); vk[2] = G1Point( 6578255280609706555177082788663940665339411973700750212075972380156339755679, 3228433145782450591319507897804150771347753627571273489631777898164366613828 ); vk[3] = G1Point( 16574758236366827634585777329773423293106114653923548049318719013559242870759, 19252886055231017922404681227981950440625207824828387687697067340297655941000 ); vk[4] = G1Point( 16555574432268249297072225173376580829558643100562043994673519690907023706670, 11620593188774162183301925169968005830479913657062396204565732720039590002171 ); vk[5] = G1Point( 16764727018082953742300073572884323444567504913343988076904979389682093093412, 16008183983701872668470252826323709319273386261752919872762484660725950394195 ); vk[6] = G1Point( 5829440659715387228077080706469101044615777998393525030381841227827471157950, 1367426294365201074200856383125954244404307990038206824279208969635811867380 ); vk[7] = G1Point( 10695369958073696359464925785121093422900833909569756953880374725937593010335, 12194125366218696157176225816036508850316861213011691830569742976115711054191 ); vk[8] = G1Point( 10809435843739366421210343030371796222421462273177875570148654509477502723134, 16204473949102958684617595152565392925725892190721955438532533184706485673957 ); vk[9] = G1Point( 11149001652463019404634197181059667092708275322411960247876227974825361909533, 19870085536849253778425365050845411527056646581744594552136174435626261992873 ); vk[10] = G1Point( 21633495322331699108936102943984938289871967694225787699478955567855577076277, 8841675697657058186837199897272199281241125039540749760749866366853345250117 ); vk[11] = G1Point( 19458527598824582144696509161993158481600392423740684090731972416543620378918, 5098098442650960828566152174489938600015509615678418748929319316696520456089 ); vk[12] = G1Point( 18163051065276756604410981379630170745584099868080700795597207422977310031694, 12891925540785917799829995466575120813509928365034086816025226811708475680771 ); vk[13] = G1Point( 18148915448457607307771805309124949164252733216024480445767547616596773695423, 15024451534977886278031386395541612474752413190466983004653113166385208262867 ); vk[14] = G1Point( 13567542556403632068871157024019274875365845880663215895985301267051220449915, 21147351992392629598077997073140386368208187323806250865054727635615189480341 ); vk[15] = G1Point( 3709429933279009443013299688619554554278934214896761775054082931305509883920, 2922475459789324154701677654774350903673561145307732452781748450024692439758 ); vk[16] = G1Point( 6207459015420283879112268812206460637912243134090208488981683983479929219501, 19464341533921121379177980354234107647138267823174115114993718278700616243646 ); vk[17] = G1Point( 12573137276608811604660919456417437099900707375770181038105448039923040372508, 4785339390439933486900025669326782829059719078601883112714925799020869250529 ); vk[18] = G1Point( 14495687129759553815385878441596882565883140518530797787341292110068724755317, 9908837939579790533939906238849352722553567333775647475719066660646812631898 ); vk[19] = G1Point( 14624553409362174155284506115343329475954034470871981231712041948820897505806, 4055566348780842984111507965436956949863329573748796703898964573434150896399 ); vk[20] = G1Point( 6336358054678702430512128514698663338467145073234753741670943409016988611841, 21081078821483650976369657459489737716748751238003798448442854876556764583522 ); vk[21] = G1Point( 21778077693541311800764526912528062763820059986333103084626823048120825681154, 178498528808053513655731208200912794633728479503731840846443012602506264472 ); vk[22] = G1Point( 20092784212323459111197432710178189818364277499363354820976672666571117766206, 14039021393890444890907150965357887601333454050225753134347061410201835959266 ); vk[23] = G1Point( 9678747076652075890061941140866585027854061921320841107956049148587077873135, 2405418275493353548325615341270358381792281291370535642128255313696482905433 ); vk[24] = G1Point( 10914160332386626846208296155883803838354007531580988096649426593027349429229, 19513308958140914107981840749041884510898897036102081855133159065505135942235 ); vk[25] = G1Point( 17013325442123840982265270425988582276060365493502071138812002548136449285581, 1528380922305877276691998106216016470833147721725826901333846614237555013029 ); vk[26] = G1Point( 8634434257131053802002335855918396412553878060677568439612339441966650140494, 9500478088969708576493467850662801175479925729547585947874419667731523903091 ); vk[27] = G1Point( 15874050365719980884900984059383308130277935906735474135906824024543309805590, 20311355082892144868040731557861367194417539765824516344987436596022294566783 ); vk[28] = G1Point( 11478929466911074817172552699536282906669073535366530139560666323127010399333, 6187455832101099195081186717967290103059680388511864648852686571948653409720 ); vk[29] = G1Point( 18658619504087916022952320913628967164216879673289502801175356389245791265554, 19249597434406947187138753077277100946837797326096977775126772518933394896670 ); vk[30] = G1Point( 5740756148239604917163046043012671325129790556077681062372536905708358133086, 21028690370455549304306083807333498793551725365830845930784580120332405576477 ); vk[31] = G1Point( 4556922182497280298677997968846941727072154818139992180400736761367731801989, 12033144730059861061132643937799827866054364406801503559178480496934921889439 ); vk[32] = G1Point( 14055239035142027464855790090606515663950909158034746078251721932545422080777, 5816418890251425996741426379519127484058094882188692730692009994088752123536 ); vk[33] = G1Point( 8440252168545611898385538536782138915182984781092035856645867408799623219945, 20215684322588953445964435803266534090301879489606942443191234122940297295959 ); vk[34] = G1Point( 8004299504263995281044671228404062964772071092198761056902501295382499264949, 8917524383385219833361205068674587307943386640835650529127394723762498700226 ); vk[35] = G1Point( 1266405593449423959342654272499280830160858534000134805902964572882344176221, 14730592399119971599629413081858596242827050785353383949532548065719090424424 ); vk[36] = G1Point( 6460184856566866496717666629334954003238728679896696393431936681715938557215, 9385837251352049607599726479064380714009328250815226579236639044132003833296 ); vk[37] = G1Point( 20038397597280131387130908291235300525757777116207925500763680256362215974747, 15789596710921114511299708815137972347824423103633995892189007477008098682432 ); vk[38] = G1Point( 14977179620342361639560323155039295964094393575784932521067001547403571821207, 5084005921095794070371447644223490185437079433157259001224747718163583496249 ); vk[39] = G1Point( 2603608960494030254533242254550209204811718913459550203153417054211926196085, 20119491317779083596649069648139084330079659707307191837443353139378496632282 ); vk[40] = G1Point( 13352417765385861239236882043377637081462713751488001524039994647924371861376, 10015867720858427500714887833930578841810954157407438967793778359200481367291 ); vk[41] = G1Point( 6824208548856181471475405533428069959877933928322938168866360738005352043359, 1275625707509651085224214735614595576100112913199144201028659347523921702370 ); vk[42] = G1Point( 11783915381165086342800153453189512171843728741798456469061325661227546377683, 17643698391422121657405091664637900437348679627693357153186100886852580927218 ); vk[43] = G1Point( 15498853058593810390094130334176163433565242197455892921729693543144628995999, 7060915310104824129452602167671744856523661600092559992144747898417292665502 ); vk[44] = G1Point( 3578042896557087484763665838416273537654955839278877802149275463634617135451, 15952757771847059361682987493826508725813536465705463434405274726476414853004 ); vk[45] = G1Point( 19791464989780891502197175931771002698056138679399576148709306135281737634890, 15038584235951650586061390113144838928579407621791780231316260808529893403257 ); vk[46] = G1Point( 10504829652002152043411151075198760792757001391754005595721909036516222701986, 7314612109070465487349496145479494813591752194581192585198492401872670355966 ); vk[47] = G1Point( 2263316314388115275462133346878405653703830076122312027240177769924172615403, 7490505571851696457669172475943134833535988792530797024799787749858114767755 ); vk[48] = G1Point( 10824830403977863762868621470892898296459194613964026019303248114011021606931, 6777560176089231246097636040358537422207547690759158064840513258627985056199 ); vk[49] = G1Point( 1395192242344963362944606483746632116836878423702653273368795762257222879845, 11627352300493465821659955604463687363663152813305154916480067138740798978572 ); vk[50] = G1Point( 20410354526728405099922418044096022279822051030184592082263557341145140341675, 16916755959160798742301876648201040933226101487533205008998132931358182938726 ); vk[51] = G1Point( 16510714617781504242550648994585448849646561015009575604004828856610715483912, 1341388561114315792903281737313302108483662874950358892151607710070453464146 ); vk[52] = G1Point( 3792245266609657761019054922431751667764747002986596796683598374795088228579, 6775015157835179633382495509949523442589741513527726694611078016648860920225 ); vk[53] = G1Point( 4295977217411094712258561527694095952819350227393933691896387148232696054234, 14315355631172786687124343322135945430381374913409927454788876962534807510067 ); vk[54] = G1Point( 5672678382423505287391236760904297810818696587596372367831733912405629636076, 11750138886868058438573361005095594512750409074576018601290870001421090732139 ); vk[55] = G1Point( 673987209207186917951408319988539910634528601243533215726279312983075853718, 3127460697691845217206582481603431538500064200369814611470300550024183147628 ); vk[56] = G1Point( 9090845515311106600436846379065946318058952289413948072431786810720329894277, 1722460393286107233579238876508677840936009861747420874009138738174760258850 ); vk[57] = G1Point( 2213889945202636137630217627265100992986775825571420924028508761827862915086, 1141968364604334451889887522589191128529733915583920463787937023339932630842 ); vk[58] = G1Point( 20456251219609929297591094856316762598797449654417795771607076592173119770834, 8505554830751982244469586969491963764193166354899055209208744116625949769223 ); vk[59] = G1Point( 20764552363708182108437044609302144079216651782533258856357771881993888180849, 5921191061717335495895332279770326686451945894157952000771270982128757623433 ); vk[60] = G1Point( 15200491309187033689701632744609921588687822717049972773860607965049839358498, 963174101797405264376426772342024356994744317274258835260867706713519099190 ); vk[61] = G1Point( 16907409359263295645490014611417427808286586585673567545549370374423687270932, 19965738920935732212165618198627456481706426962709668717428158398175019622633 ); vk[62] = G1Point( 8525733762824884009931940933269975990468556742128693668478069420206268288958, 17680957562382256477839242533381992422893557640970411982748854729672918653339 ); vk[63] = G1Point( 11543924252775971085638087262239886261896444790986575032898538165024986094767, 18295533857221598255085058623508918462384641096084692938748885507727999045589 ); vk[64] = G1Point( 7650073211562746195287504984432880599500134080888190390185023908018545159212, 8926007449865916826503243560207850774231542132502497737708140518754674515195 ); vk[65] = G1Point( 10910030114197534600661564768248291622559208820070544459540583031788280438050, 2161200733196553722076963828666276486998396660698119820390811182345471844390 ); vk[66] = G1Point( 5619991943329231023586342563071292156848936940252243397784818979776452294394, 17086471386430636827044781369055262728948850562979233008000676670453119931905 ); vk[67] = G1Point( 20029721922638353437616765565750954147967465635811408466336662374931690558864, 12157045576250721417202657406507371059403669196756053696479579894919277155409 ); vk[68] = G1Point( 21135518903999037687700383159674705128503559373593305877591081795645434677800, 14826149418250868867665516729312927912183357232820965249219250101690877051719 ); vk[69] = G1Point( 12716235266612547965522432659702796588728652520165953576885109254764760946605, 1502656029161667595612192784104946048748456206287753606896784110697937038273 ); vk[70] = G1Point( 1049220917141553398666899775374455498324054642642897994229873531044866400312, 20769086632475471411761783937841264352491499614880433868847982280973141672413 ); vk[71] = G1Point( 3614350552551352780806550106639402451345056206997206243944277215031513049373, 5206057445524765927002106886059500476391837098700968541446631114025985784910 ); vk[72] = G1Point( 8055783365824181166702825600356820312061099690523284725576656663176679044116, 1638222926585075350767574412771496589388909043259378375319066944648316994837 ); vk[73] = G1Point( 4057792612019156099527886469601168926861003507392647059213084047169560834646, 6594931307015609958146395288390214967001676005571978717602974701376929545008 ); vk[74] = G1Point( 9950382393274396072720404713158345851200057195628611055661986956843175756293, 7282922667960477094585696814153673802022441822983967842678841595733604007174 ); vk[75] = G1Point( 4586216621225205252031099476870849094841015192052367266638267710491870499101, 4604017147526254722438115051976438786550914352568100746360878795783694704167 ); vk[76] = G1Point( 16799214131908640765084658268392840479345866505817700863114604240164943164257, 15354212741684672046178028260202360583039504621090458373615159126939692802706 ); vk[77] = G1Point( 13138609772016813027991609032179065209970990415242714114775376639090712079350, 15380517677991831032858870866819856499419492092909311846600193251951859042321 ); vk[78] = G1Point( 12681723977387824731895989023500526405308466858542903103055928573501887506887, 11370573709343602505230460979583593651754855121852100216138643349056073782952 ); vk[79] = G1Point( 4200058302555642333283692750835107019807983821991387347796012866346514302605, 14357085568398294016842996105655116738370071081936618062005085850396798772802 ); vk[80] = G1Point( 14137699264377957975776528918800596987631257455548836008761386515677706582563, 2877943046106495432464489171942097254021067591451481943864022445799990140117 ); vk[81] = G1Point( 7480145966790209514588805951103723897773954176759764819231387108562986050867, 12404751866229336820648708250938384384013582100169058004847207735622575043993 ); vk[82] = G1Point( 12970817937144745309785994864230789483629807994776973410040274401977769841052, 5825762304110705990197138035992052772838196210579994473399600004016677423488 ); vk[83] = G1Point( 14988453290426221989095533870965847942554723567967755183069083157996373748616, 8648840510009197738716543586800373429604948580372256694893314143136379863664 ); vk[84] = G1Point( 15145542077656252793870557125161247488411025860428855768932504599780138755577, 2178169336494538462372002990799200948579620951049701898691482757493703042642 ); vk[85] = G1Point( 11135789569088525124827536278606171249701996905898972803869975950803968697579, 3104837136515107621506029430582483708481393523526438371726824112484239803581 ); vk[86] = G1Point( 17066149863746730614554018679517110986144152654411463722880426514835413500149, 11885136744232152755409190843781868227764042786753547405780615738418310637923 ); vk[87] = G1Point( 8848015573236418075663743497372404662739214749989826392286123012148059889680, 1972243942447596180922716596695612444433272877968270983679827686933514965206 ); vk[88] = G1Point( 14865752525354582126252517599134593966808867282046342796694614702712521564336, 18116025354261037812375363008053160294289201308729119292420655212966763428629 ); vk[89] = G1Point( 20008653757824978308869797085409493811497783305061398226809054512392049926827, 2023221323067464241928858421807576285617952900431861729331205253026094553028 ); vk[90] = G1Point( 9427479375857197202287179331720188202666358779957538977247547218804648021559, 13103256830144414831969119769186006894217432078739958285698595391380496268010 ); vk[91] = G1Point( 3022753493095593546667513964979418729795168926723981739728213991436890865173, 15651100209468844976455723098156772118319496522347044594278603917566715835964 ); vk[92] = G1Point( 11863153566289362104600364540490616631416480033499697509671034253106023069686, 6263106079901584198635057982958449515247366171335121668407272647131625665359 ); vk[93] = G1Point( 1632268454934283210866357082989656996613161609804593296738987685077804217796, 8943206385844065158715717104595797380028345892524924749292670404417492092532 ); vk[94] = G1Point( 2514580143298917949844157611116376945011648866679103488807951227637293425228, 1570539622709169759643018064245830768717632289525346051035788970161633534650 ); vk[95] = G1Point( 14995127663646685519705792243009870088473684011447124089592875697835776461681, 10011280883107051614601335912182178771718155707859435453848946557263718614275 ); vk[96] = G1Point( 10837864859142056917623769978173380007817338460373139706119502408994471525015, 5688212466311380080002109574884673535981843432406127069039894776083240717165 ); vk[97] = G1Point( 8184241099722337872655100621160316867350497097484481073516270737365644965184, 8370899682353048184295715026039653844162707028675185918829983378235273090579 ); vk[98] = G1Point( 14336699639296594061188773829570477118517654937378475865402690828519678655979, 18962321517991296846137966567405441567624457545084441947313953041676115679070 ); vk[99] = G1Point( 9460029977525714962867496691244424070473524798482965710433684902814580254803, 13773860226345636507739066933383044706264742752335080543835025360890117637789 ); vk[100] = G1Point( 19391891390609481429849774145579503985374912055370046060106347963180567737648, 7728129834219170358551601609946089408272789276196019291377633982082964264714 ); } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/circuitVerifier.sol
// // 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. // // 2019 OKIMS // ported to solidity 0.6 // fixed linter warnings // added requiere error messages // // // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; 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() internal pure returns (G1Point memory) { return G1Point(1, 2); } /// @return the generator of G2 function P2() internal pure returns (G2Point memory) { // Original code point return G2Point( [11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781], [4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930] ); /* // Changed by Jordi point return G2Point( [10857046999023057135944570762232829481370756359578518086990519993285655852781, 11559732032986387107991004021392285783925812861821192530917403151452391805634], [8495653923123431417604973247489272438418190587263600148770280649306958101930, 4082367875863433681332203403145435568316851327593401208105741076214120093531] ); */ } /// @return r the negation of p, i.e. p.addition(p.negate()) should be zero. function negate(G1Point memory p) internal pure returns (G1Point memory r) { // 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 r the sum of two points of G1 function addition(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { uint[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 6, input, 0xc0, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success,"pairing-add-failed"); } /// @return r 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 memory p, uint s) internal view returns (G1Point memory r) { uint[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 7, input, 0x80, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require (success,"pairing-mul-failed"); } /// @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[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length,"pairing-lengths-failed"); 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; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success,"pairing-opcode-failed"); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view 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 memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2 ) internal view 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 memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2, G1Point memory d1, G2Point memory d2 ) internal view 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 CircuitVerifier { using Pairing for *; struct VerifyingKey { Pairing.G1Point alfa1; Pairing.G2Point beta2; Pairing.G2Point gamma2; Pairing.G2Point delta2; Pairing.G1Point[] IC; } struct Proof { Pairing.G1Point A; Pairing.G2Point B; Pairing.G1Point C; } function verifyingKey() internal pure returns (VerifyingKey memory vk) { vk.alfa1 = Pairing.G1Point( 20491192805390485299153009773594534940189261866228447918068658471970481763042, 9383485363053290200918347156157836566562967994039712273449902621266178545958 ); vk.beta2 = Pairing.G2Point( [4252822878758300859123897981450591353533073413197771768651442665752259397132, 6375614351688725206403948262868962793625744043794305715222011528459656738731], [21847035105528745403288232691147584728191162732299865338377159692350059136679, 10505242626370262277552901082094356697409835680220590971873171140371331206856] ); vk.gamma2 = Pairing.G2Point( [11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781], [4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930] ); vk.delta2 = Pairing.G2Point( [21223509572149436009383842546644857332549415106982951130166482247313305552407, 3651919070680602585131326454611744313033427008208909328852558006475401815457], [18868338637417310549300806688818271707183649362616203659593245255731372694149, 12639385737564052598655546142232001975674170132048529941115373366821228560987] ); vk.IC = new Pairing.G1Point[](32); vk.IC[0] = Pairing.G1Point( 19285368940731314812277377326380883472569493771921601523645257990686666718389, 1372693327773405640347273163919379519555169290873089668969290615157317568035 ); vk.IC[1] = Pairing.G1Point( 20563536359277927673211382785955880671029020113525488954738694785575739831195, 11622487325429485635036204798963062119327899165409993719814798109467539711521 ); vk.IC[2] = Pairing.G1Point( 8875816761637054206953475440341751666786638952753385218037925061132134808360, 10670771010820437935149234172619692113592674470313124621792870855604924174724 ); vk.IC[3] = Pairing.G1Point( 16310041769337439549216324037724832358058235392896021682362617270538374194950, 19324449383987862762752536963119465502812921099286174351059525673474911225532 ); vk.IC[4] = Pairing.G1Point( 5783563821028270213576609919720027429769938502424460091302825153121542109354, 1470669597353590816746365817778990659877634944571654698518112762825899872953 ); vk.IC[5] = Pairing.G1Point( 914937451350736032348203387680959396512999207088712230002930452486647275486, 13278992517431057944065874304895401817561900836300928790090187392043172986310 ); vk.IC[6] = Pairing.G1Point( 18097596007339529406692800143852776601000937260850591264898128684789643908212, 9153937710318033405384133751664845960297229722568264885716854633955663625536 ); vk.IC[7] = Pairing.G1Point( 6193249348722695043944500703095878319595334835001600074904795240215318098962, 7853680886918860231577585366958076401174476205187153074482747182486269572453 ); vk.IC[8] = Pairing.G1Point( 15270422438445823922593250494709654463789987296743911250277775444865091824612, 4102182906941581233304729176391766141314683070891114801586417028043961885657 ); vk.IC[9] = Pairing.G1Point( 1302681630257233329077408872587714433119006291453962064536810133248742069768, 16311982814639644121944335458064770134173125251073766459777997299727849450385 ); vk.IC[10] = Pairing.G1Point( 2547973719675613033586687516381437235939306144752695939764438305531826924266, 18707555548721531003785445481648633019475010768441520378552149383179479150717 ); vk.IC[11] = Pairing.G1Point( 4428496179622071166051755585560830941147382314141057626874137147454947858555, 20313942796395280130218843132871495899105990153866314823037951753327298389440 ); vk.IC[12] = Pairing.G1Point( 21090886813683041019220427702428409885856117842016306648411480480763064485622, 2904286936290379856261715681207382922806286474730092451626811072360471392706 ); vk.IC[13] = Pairing.G1Point( 16953207110836848412348418809752737780820855895491067079125814117205539343156, 1818176631812756401799820926733888831130235415626052739389592258254689714069 ); vk.IC[14] = Pairing.G1Point( 14275611219479745388903161313834529621377028751523300114715470306855103627468, 11395634342520831379817961559538472855919256807836266605671005070285381756811 ); vk.IC[15] = Pairing.G1Point( 9309985145070020350527688966527437090410653959124451822044308620974043195469, 5088783600811643090890999487942869959512873512301353706146318021257882291855 ); vk.IC[16] = Pairing.G1Point( 13845291475527603009053139388380092079280298146548334122387682777257704819701, 19983427718412885469630659039041222500384101588665734536304699212006998692472 ); vk.IC[17] = Pairing.G1Point( 13231858176024723276494898879866156922615784394666546818166548789657182161333, 11199542500735857507253092815482494011222825605932956765796942807430804932442 ); vk.IC[18] = Pairing.G1Point( 15155380983211082488641924827916379578962497681571449333022148252969777764037, 4146224505674490292116190239156754729027337668003337499925105327877886686419 ); vk.IC[19] = Pairing.G1Point( 8169038537569741399573329096561615641148655375190982634441976478639056198693, 11963650259756467569328883816276529262045940085129455596849074710225723789976 ); vk.IC[20] = Pairing.G1Point( 5768155153658025058286442157394530016577292835139355355291835326382757604073, 20084350319318171708307617210896946548033127857641151424695801209275721178484 ); vk.IC[21] = Pairing.G1Point( 12703197821467744408272824365427240188730432752459024271595948028914355362762, 10123119830081479418463659963407526854356320634595089810637209343214392456651 ); vk.IC[22] = Pairing.G1Point( 18202154060412128906014642267610638621848197350141370475801967787541536447902, 7172856910555396735982105446089210786857646719326360443646152381651817923139 ); vk.IC[23] = Pairing.G1Point( 17170777702061064354926492758896433985012177585871248144609849735893537428237, 412998423308992625938675915107301585996363349849877844235609364273086873580 ); vk.IC[24] = Pairing.G1Point( 3545350639001990923140538415427584236524735576470412437640669325012183149004, 20188177885143613106665205433040400257378338431586890569517744733352415194844 ); vk.IC[25] = Pairing.G1Point( 21431297364806809809353204501967336223370018667834067200289961618421550463576, 6224434139824781014957254620472227483320631913991355808517618408479036778646 ); vk.IC[26] = Pairing.G1Point( 20280682591691563582384585973340321812285845652705934582770347952936885495314, 12208275392540746880779008886418423836514168579437691486870715982767835559268 ); vk.IC[27] = Pairing.G1Point( 10015165244416857193592336278992467819961744116081081647783642516266955540912, 20130961332116514755984061027376120975717399625907757330731812572615020936707 ); vk.IC[28] = Pairing.G1Point( 8336371214105638859634154554031929460603615856662424524205559804248139721705, 15877135363481174608851919525400781895600679056573072501733758948126246943151 ); vk.IC[29] = Pairing.G1Point( 14076177816885665971918033670006882703355155560752256957969673368434759377466, 4110228092353627263550493253063698850130425422586685028497387964159506802444 ); vk.IC[30] = Pairing.G1Point( 21779324301473364824100454032265775775351274040721207181034336488931253729090, 501953779072995894027107266033339049457352284371355668744583435564783383240 ); vk.IC[31] = Pairing.G1Point( 17060488929845011250862811192805763333332019172161699169052857724884424599208, 8629028379209702408634728188414144519665064163607186328886948451932454722462 ); } function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; VerifyingKey memory vk = verifyingKey(); require(input.length + 1 == vk.IC.length,"verifier-bad-input"); // Compute the linear combination vk_x Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); for (uint i = 0; i < input.length; i++) { require(input[i] < snark_scalar_field,"verifier-gte-snark-scalar-field"); 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.pairingProd4( Pairing.negate(proof.A), proof.B, vk.alfa1, vk.beta2, vk_x, vk.gamma2, proof.C, vk.delta2 )) return 1; return 0; } /// @return r bool true if proof is valid function verifyProof( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[] memory input ) public view 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]); if (verify(input, proof) == 0) { return true; } else { return false; } } }
https://github.com/socathie/ZKaggleV2
hardhat/contracts/encryptionVerifier.sol
// // 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. // // 2019 OKIMS // ported to solidity 0.6 // fixed linter warnings // added requiere error messages // // // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.17; import "./Pairing100.sol"; import "./Pairing200.sol"; import "./Pairing300.sol"; import "./Pairing400.sol"; import "./Pairing500.sol"; import "./Pairing600.sol"; import "./Pairing700.sol"; import "./Pairing800.sol"; import "./Pairing900.sol"; import "./Pairing1000.sol"; 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() internal pure returns (G1Point memory) { return G1Point(1, 2); } /// @return the generator of G2 function P2() internal pure returns (G2Point memory) { // Original code point return G2Point( [11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781], [4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930] ); /* // Changed by Jordi point return G2Point( [10857046999023057135944570762232829481370756359578518086990519993285655852781, 11559732032986387107991004021392285783925812861821192530917403151452391805634], [8495653923123431417604973247489272438418190587263600148770280649306958101930, 4082367875863433681332203403145435568316851327593401208105741076214120093531] ); */ } /// @return r the negation of p, i.e. p.addition(p.negate()) should be zero. function negate(G1Point memory p) internal pure returns (G1Point memory r) { // 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 r the sum of two points of G1 function addition(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { uint[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 6, input, 0xc0, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success,"pairing-add-failed"); } /// @return r 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 memory p, uint s) internal view returns (G1Point memory r) { uint[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 7, input, 0x80, r, 0x60) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require (success,"pairing-mul-failed"); } /// @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[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length,"pairing-lengths-failed"); 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; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) // Use "invalid" to make gas estimation work switch success case 0 { invalid() } } require(success,"pairing-opcode-failed"); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view 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 memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2 ) internal view 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 memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2, G1Point memory d1, G2Point memory d2 ) internal view 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 EncryptionVerifier { using Pairing for *; address private pairing100; address private pairing200; address private pairing300; address private pairing400; address private pairing500; address private pairing600; address private pairing700; address private pairing800; address private pairing900; address private pairing1000; struct VerifyingKey { Pairing.G1Point alfa1; Pairing.G2Point beta2; Pairing.G2Point gamma2; Pairing.G2Point delta2; Pairing.G1Point[] IC; } struct Proof { Pairing.G1Point A; Pairing.G2Point B; Pairing.G1Point C; } constructor( address add100, address add200, address add300, address add400, address add500, address add600, address add700, address add800, address add900, address add1000 ) { pairing100 = add100; pairing200 = add200; pairing300 = add300; pairing400 = add400; pairing500 = add500; pairing600 = add600; pairing700 = add700; pairing800 = add800; pairing900 = add900; pairing1000 = add1000; } function verifyingKey() internal pure returns (VerifyingKey memory vk) { vk.alfa1 = Pairing.G1Point( 20491192805390485299153009773594534940189261866228447918068658471970481763042, 9383485363053290200918347156157836566562967994039712273449902621266178545958 ); vk.beta2 = Pairing.G2Point( [4252822878758300859123897981450591353533073413197771768651442665752259397132, 6375614351688725206403948262868962793625744043794305715222011528459656738731], [21847035105528745403288232691147584728191162732299865338377159692350059136679, 10505242626370262277552901082094356697409835680220590971873171140371331206856] ); vk.gamma2 = Pairing.G2Point( [11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781], [4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930] ); vk.delta2 = Pairing.G2Point( [6653259084928985759212025249045143654297075953578382745064964143441455343356, 8160999132074616195727858211272521546858233416802944087099739007663370791684], [5005417252240310256132733574742221180631042236600616922722331817516271580377, 535375283190531279782443189967329266724259036468032022432462508232591886570] ); vk.IC = new Pairing.G1Point[](1006); vk.IC[0] = Pairing.G1Point( 3913146479250333998622309518342179854776388675763500448325061276047871385028, 185902641878167853786013541387769876019822308496137446718496175008088134965 ); } function verify(uint[] memory input, Proof memory proof) internal view returns (uint) { uint256 snark_scalar_field = 21888242871839275222246405745257275088548364400416034343698204186575808495617; VerifyingKey memory vk = verifyingKey(); require(input.length + 1 == 1006,"verifier-bad-input"); // Compute the linear combination vk_x Pairing.G1Point memory vk_x = Pairing.G1Point(0, 0); for (uint i = 0; i < 100; i++) { require(input[i] < snark_scalar_field,"verifier-gte-snark-scalar-field"); (uint X, uint Y) = Pairing100(pairing100).vk(i + 1); vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i])); } for (uint i = 0; i < 100; i++) { require(input[i + 100] < snark_scalar_field, "verifier-gte-snark-scalar-field"); (uint X, uint Y) = Pairing200(pairing200).vk(i + 1); vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 100])); } for (uint i = 0; i < 100; i++) { require(input[i + 200] < snark_scalar_field, "verifier-gte-snark-scalar-field"); (uint X, uint Y) = Pairing300(pairing300).vk(i + 1); vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 200])); } for (uint i = 0; i < 100; i++) { require(input[i + 300] < snark_scalar_field, "verifier-gte-snark-scalar-field"); (uint X, uint Y) = Pairing400(pairing400).vk(i + 1); vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 300])); } for (uint i = 0; i < 100; i++) { require(input[i + 400] < snark_scalar_field, "verifier-gte-snark-scalar-field"); (uint X, uint Y) = Pairing500(pairing500).vk(i + 1); vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 400])); } for (uint i = 0; i < 100; i++) { require(input[i + 500] < snark_scalar_field, "verifier-gte-snark-scalar-field"); (uint X, uint Y) = Pairing600(pairing600).vk(i + 1); vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 500])); } for (uint i = 0; i < 100; i++) { require(input[i + 600] < snark_scalar_field, "verifier-gte-snark-scalar-field"); (uint X, uint Y) = Pairing700(pairing700).vk(i + 1); vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 600])); } for (uint i = 0; i < 100; i++) { require(input[i + 700] < snark_scalar_field, "verifier-gte-snark-scalar-field"); (uint X, uint Y) = Pairing800(pairing800).vk(i + 1); vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 700])); } for (uint i = 0; i < 100; i++) { require(input[i + 800] < snark_scalar_field, "verifier-gte-snark-scalar-field"); (uint X, uint Y) = Pairing900(pairing900).vk(i + 1); vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 800])); } for (uint i = 0; i < 105; i++) { require(input[i + 900] < snark_scalar_field, "verifier-gte-snark-scalar-field"); (uint X, uint Y) = Pairing1000(pairing1000).vk(i + 1); vk_x = Pairing.addition(vk_x, Pairing.scalar_mul(Pairing.G1Point(X, Y), input[i + 900])); } vk_x = Pairing.addition(vk_x, vk.IC[0]); if (!Pairing.pairingProd4( Pairing.negate(proof.A), proof.B, vk.alfa1, vk.beta2, vk_x, vk.gamma2, proof.C, vk.delta2 )) return 1; return 0; } /// @return r bool true if proof is valid function verifyProof( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[1005] memory input ) public view 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) { return true; } else { return false; } } }
https://github.com/socathie/ZKaggleV2
hardhat/deploy/deploy.js
module.exports = async ({ getNamedAccounts, deployments }) => { const { deploy } = deployments; const { deployer } = await getNamedAccounts(); const pairing100 = await deploy('Pairing100', { from: deployer, log: true }); const pairing200 = await deploy('Pairing200', { from: deployer, log: true }); const pairing300 = await deploy('Pairing300', { from: deployer, log: true }); const pairing400 = await deploy('Pairing400', { from: deployer, log: true }); const pairing500 = await deploy('Pairing500', { from: deployer, log: true }); const pairing600 = await deploy('Pairing600', { from: deployer, log: true }); const pairing700 = await deploy('Pairing700', { from: deployer, log: true }); const pairing800 = await deploy('Pairing800', { from: deployer, log: true }); const pairing900 = await deploy('Pairing900', { from: deployer, log: true }); const pairing1000 = await deploy('Pairing1000', { from: deployer, log: true }); const encryptionVerifier = await deploy('EncryptionVerifier', { from: deployer, log: true, args: [pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address] }); await deploy('BountyFactory', { from: deployer, log: true, args: [encryptionVerifier.address] }); await deploy('CircuitVerifier', { from: deployer, log: true }); }; module.exports.tags = ['complete'];
https://github.com/socathie/ZKaggleV2
hardhat/hardhat.config.js
require("@nomicfoundation/hardhat-toolbox"); require("@nomiclabs/hardhat-ethers"); require("hardhat-deploy"); require("hardhat-contract-sizer"); require("hardhat-gas-reporter"); require("dotenv").config(); // const { PRIVATE_KEY: GOERLI_PRIVATE_KEY, ALCHEMY_API_KEY } = process.env; module.exports = { solidity: { version: "0.8.17", optimizer: { enabled: true, runs: 1000, } }, networks: { hardhat: { chainId: 1337, allowUnlimitedContractSize: true, gas: 100000000, blockGasLimit: 0x1fffffffffffff, }, // goerli: { // allowUnlimitedContractSize: true, // gas: 100000000, // blockGasLimit: 0x1fffffffffffff, // url: `https://eth-goerli.alchemyapi.io/v2/${ALCHEMY_API_KEY}`, // accounts: [`${GOERLI_PRIVATE_KEY}`], // }, }, namedAccounts: { deployer: 0, }, paths: { deploy: "deploy", deployments: "deployments", }, mocha: { timeout: 1000000 } };
https://github.com/socathie/ZKaggleV2
hardhat/scripts/bump-solidity.js
const fs = require("fs"); const solidityRegex = /pragma solidity \^\d+\.\d+\.\d+/ const inputRegex = /uint\[\d+\] memory input(?!;)/ const contentRegex = /proof\.C = Pairing\.G1Point\(c\[0\], c\[1\]\);([\s\S]*?)if \(verify\(inputValues, proof\) == 0\)/ const verifierRegex = /contract Verifier/ let content = fs.readFileSync("./contracts/circuitVerifier.sol", { encoding: 'utf-8' }); let bumped = content.replace(solidityRegex, 'pragma solidity ^0.8.17'); bumped = bumped.replace(inputRegex, 'uint[] memory input'); bumped = bumped.replace(contentRegex, 'proof.C = Pairing.G1Point(c[0], c[1]);\n\n if (verify(input, proof) == 0)'); let renamed = bumped.replace(verifierRegex, 'contract CircuitVerifier'); fs.writeFileSync("./contracts/circuitVerifier.sol", renamed); content = fs.readFileSync("./contracts/encryptionVerifier.sol", { encoding: 'utf-8' }); bumped = content.replace(solidityRegex, 'pragma solidity ^0.8.17'); // bumped = bumped.replace(inputRegex, 'uint[] memory input'); // bumped = bumped.replace(contentRegex, 'proof.C = Pairing.G1Point(c[0], c[1]);\n\n if (verify(input, proof) == 0)'); renamed = bumped.replace(verifierRegex, 'contract EncryptionVerifier'); fs.writeFileSync("./contracts/encryptionVerifier.sol", renamed);
https://github.com/socathie/ZKaggleV2
hardhat/scripts/upload-data.js
require("dotenv").config(); const lighthouse = require('@lighthouse-web3/sdk'); const fs = require('fs'); const apiKey = process.env.API_KEY; async function main() { const hashes = []; for (let i = 0; i < 1000; i++) { const path = "assets/" + i + ".pgm"; //Give path to the file const response = await lighthouse.uploadFileRaw(path, apiKey); console.log(response.data.Hash); hashes.push(response.data.Hash); if (i == 0) { console.assert(response.data.Hash == "bafkreig42jyiawthjkmskza765hn6krgqs7uk7cmtjmggb6mgnjql7dqje"); } console.assert(response.data.Size == "797"); } fs.writeFileSync("assets/cid.txt", hashes.join("\r")); } main().then(() => process.exit(0)).catch(error => { console.error(error); process.exit(1); });
https://github.com/socathie/ZKaggleV2
hardhat/test/0.lighthouse.test.js
const { expect } = require("chai"); const { ethers } = require("hardhat"); require("dotenv").config(); const lighthouse = require('@lighthouse-web3/sdk'); const { recoverShards } = require("@lighthouse-web3/kavach"); const fs = require("fs"); const privateKey = process.env.PRIVATE_KEY; const publicKey = process.env.PUBLIC_KEY; const privateKeyBob = process.env.PRIVATE_KEY_BOB; const publicKeyBob = process.env.PUBLIC_KEY_BOB; const apiKey = process.env.API_KEY; const path = "assets/0.pgm"; //Give path to the file const sign_auth_message = async (publicKey, privateKey) => { const provider = new ethers.providers.JsonRpcProvider(); const signer = new ethers.Wallet(privateKey, provider); const messageRequested = (await lighthouse.getAuthMessage(publicKey)).data.message; const signedMessage = await signer.signMessage(messageRequested); return (signedMessage) } describe("Lighthouse SDK test", function () { it("Should upload file in raw to lighthouse", async function () { const response = await lighthouse.uploadFileRaw(path, apiKey); expect(response.data.Name).equal("0.pgm"); expect(response.data.Hash).equal("bafkreig42jyiawthjkmskza765hn6krgqs7uk7cmtjmggb6mgnjql7dqje"); expect(response.data.Size).equal("797") }); it("Should upload file to lighthouse", async function () { const response = await lighthouse.upload(path, apiKey); expect(response.data.Name).equal("0.pgm"); expect(response.data.Hash).equal("QmevD3vQfg6Nf9RYWGCrNdfmT49BhLS714sxGkVifqmYg9"); expect(response.data.Size).equal("808") }); let cid; it("Should upload encrypted file to lighthouse", async function () { const signed_message = await sign_auth_message(publicKey, privateKey); const response = await lighthouse.uploadEncrypted( path, apiKey, publicKey, signed_message, ); expect(response.data.Name).equal("0.pgm"); // expect(response.data.Hash).equal("QmeakAMwVmYerw8DgZ5jyNHMV8G1fe6cNMvViezzM6bRqt"); expect(response.data.Size).equal("852"); cid = response.data.Hash; }); it("Should download decrypted file from lighthouse", async function () { const signed_message = await sign_auth_message(publicKey, privateKey); const fileEncryptionKey = await lighthouse.fetchEncryptionKey( cid, publicKey, signed_message ); const decrypted = await lighthouse.decryptFile( cid, fileEncryptionKey.data.key ); expect(decrypted.byteLength).equal(797); }); it("Should share private file with another user", async function () { const signed_message = await sign_auth_message(publicKey, privateKey); const response = await lighthouse.shareFile( publicKey, [publicKeyBob], cid, signed_message, ); expect(response.data.cid).equal(cid); expect(response.data.status).equal("Success"); expect(response.data.shareTo[0]).equal(publicKeyBob); }); it("Should download decrypted file from lighthouse shared with another user", async function () { const signed_message = await sign_auth_message(publicKeyBob, privateKeyBob); const fileEncryptionKey = await lighthouse.fetchEncryptionKey( cid, publicKeyBob, signed_message ); const decrypted = await lighthouse.decryptFile( cid, fileEncryptionKey.data.key ); expect(decrypted.byteLength).equal(797); }); it("Should revoke access to private file from another user", async function () { const signed_message = await sign_auth_message(publicKey, privateKey); const response = await lighthouse.revokeFileAccess( publicKey, [publicKeyBob], cid, signed_message, ); expect(response.data.cid).equal(cid); expect(response.data.status).equal("Success"); expect(response.data.revokeTo[0]).equal(publicKeyBob); }); it("Should not be able to download decrypted file from lighthouse shared with another user", async function () { const signed_message = await sign_auth_message(publicKeyBob, privateKeyBob); const { error, shards } = await recoverShards( publicKeyBob, cid, signed_message, 5 ); expect(shards.length).equal(0); expect(error?.message).equal("you don't have access"); }); });
https://github.com/socathie/ZKaggleV2
hardhat/test/1.circuit.test.js
const { expect, assert } = require("chai"); const { ethers } = require("hardhat"); const { groth16 } = require("snarkjs"); const fs = require("fs"); const crypto = require("crypto"); const base32 = require("base32.js"); const F1Field = require("ffjavascript").F1Field; const Scalar = require("ffjavascript").Scalar; exports.p = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617"); const Fr = new F1Field(exports.p); const { Keypair } = require("circomlib-ml/test/modules/maci-domainobjs"); const { decrypt } = require("circomlib-ml/test/modules/maci-crypto"); const json = require("./circuit.json"); const labels = require("../assets/labels.json"); // read ../assets/cid.txt into an array of strings const cids = fs.readFileSync("assets/cid.txt").toString().split("\r"); // console.log(cids); const idx = 567; let modelHash; describe("circuit.circom test", function () { let INPUT = {}; for (const [key, value] of Object.entries(json)) { if (Array.isArray(value)) { let tmpArray = []; for (let i = 0; i < value.flat().length; i++) { tmpArray.push(Fr.e(value.flat()[i])); } INPUT[key] = tmpArray; } else { INPUT[key] = Fr.e(value); } } let Verifier; let verifier; let a, b, c, Input; const digests = []; before(async function () { Verifier = await ethers.getContractFactory("CircuitVerifier"); verifier = await Verifier.deploy(); await verifier.deployed(); const input = []; for (let i = 0; i < 10; i++) { const bytes = fs.readFileSync("assets/" + (idx + i) + ".pgm"); const binary = [...bytes].map((b) => b.toString(2).padStart(8, "0").split("")).flat(); input.push(binary); const hash = crypto.createHash('sha256'); hash.update(bytes); digests.push(hash.digest('hex')); } // console.log(input.flat().length); INPUT["in"] = input.flat(); const { proof, publicSignals } = await groth16.fullProve(INPUT, "circuits/build/circuit_js/circuit.wasm", "circuits/build/circuit_final.zkey"); const calldata = await groth16.exportSolidityCallData(proof, publicSignals); const argv = calldata.replace(/["[\]\s]/g, "").split(',').map(x => BigInt(x).toString()); a = [argv[0], argv[1]]; b = [[argv[2], argv[3]], [argv[4], argv[5]]]; c = [argv[6], argv[7]]; Input = argv.slice(8); console.log(labels.slice(idx, idx + 10)); console.log(Input.slice(0,10)); const calldataJson = { "a": a, "b": b, "c": c, "input": Input, } // save calldata to json file fs.writeFileSync("./test/circuitCalldata.json", JSON.stringify(calldataJson)); modelHash = Input[30]; }); it("Check circuit output", async () => { for (let i = 0; i < 10; i++) { const digest1 = Fr.e(digests[i].slice(0,32), 16); const digest2 = Fr.e(digests[i].slice(32,64), 16); assert(Fr.eq(Fr.e(Input[i*2+10]),Fr.e(digest1))); assert(Fr.eq(Fr.e(Input[i*2+11]),Fr.e(digest2))); } }); it("Verifier should return true for correct proofs", async function () { expect(await verifier.verifyProof(a, b, c, Input)).to.be.true; }); it("Verifier should return false for invalid proof", async function () { let a = [0, 0]; let b = [[0, 0], [0, 0]]; let c = [0, 0]; expect(await verifier.verifyProof(a, b, c, Input)).to.be.false; }); it("CIDv1 should match that from IPFS", async function () { const cid_version = 1; const cid_codec = 85; // raw 0x55 const hash_function_code = 18; // SHA-256 0x12 const length = 32; for (let i = 0; i < 10; i++) { const cidraw = cid_version.toString(16).padStart(2, "0") + cid_codec.toString(16).padStart(2, "0") + hash_function_code.toString(16).padStart(2, "0") + length.toString(16).padStart(2, "0") + digests[i]; const buf = Buffer.from(cidraw, 'hex'); const encoder = new base32.Encoder(); const cid = encoder.write(buf).finalize().toLowerCase(); expect("b" + cid).equal(cids[idx + i]); } }); }); describe("encryption.circom test", function () { let input = []; for (const [key, value] of Object.entries(json)) { // console.log(key); if (Array.isArray(value)) { let tmpArray = []; for (let i = 0; i < value.flat().length; i++) { tmpArray.push(Fr.e(value.flat()[i])); } input = [...input, ...tmpArray]; } else { input.push(value); } } for (let i = input.length; i< 1000; i++) { input.push(0); } let Verifier; let verifier; let a, b, c, Input; let keypair; let keypair2; let ecdhSharedKey; let INPUT = {}; before(async function () { keypair = new Keypair(); keypair2 = new Keypair(); ecdhSharedKey = Keypair.genEcdhSharedKey( keypair.privKey, keypair2.pubKey, ); INPUT = { 'private_key': keypair.privKey.asCircuitInputs(), 'public_key': keypair2.pubKey.asCircuitInputs(), 'in': input, } // console.log(INPUT); // console.log(INPUT['public_key']); // deploy pairing contracts from pairing100 to pairing1000 const Pairing100 = await ethers.getContractFactory("Pairing100"); const pairing100 = await Pairing100.deploy(); await pairing100.deployed(); const Pairing200 = await ethers.getContractFactory("Pairing200"); const pairing200 = await Pairing200.deploy(); await pairing200.deployed(); const Pairing300 = await ethers.getContractFactory("Pairing300"); const pairing300 = await Pairing300.deploy(); await pairing300.deployed(); const Pairing400 = await ethers.getContractFactory("Pairing400"); const pairing400 = await Pairing400.deploy(); await pairing400.deployed(); const Pairing500 = await ethers.getContractFactory("Pairing500"); const pairing500 = await Pairing500.deploy(); await pairing500.deployed(); const Pairing600 = await ethers.getContractFactory("Pairing600"); const pairing600 = await Pairing600.deploy(); await pairing600.deployed(); const Pairing700 = await ethers.getContractFactory("Pairing700"); const pairing700 = await Pairing700.deploy(); await pairing700.deployed(); const Pairing800 = await ethers.getContractFactory("Pairing800"); const pairing800 = await Pairing800.deploy(); await pairing800.deployed(); const Pairing900 = await ethers.getContractFactory("Pairing900"); const pairing900 = await Pairing900.deploy(); await pairing900.deployed(); const Pairing1000 = await ethers.getContractFactory("Pairing1000"); const pairing1000 = await Pairing1000.deploy(); await pairing1000.deployed(); Verifier = await ethers.getContractFactory("EncryptionVerifier"); verifier = await Verifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address); await verifier.deployed(); const { proof, publicSignals } = await groth16.fullProve(INPUT, "circuits/build/encryption_js/encryption.wasm", "circuits/build/encryption_final.zkey"); const calldata = await groth16.exportSolidityCallData(proof, publicSignals); const argv = calldata.replace(/["[\]\s]/g, "").split(',').map(x => BigInt(x).toString()); a = [argv[0], argv[1]]; b = [[argv[2], argv[3]], [argv[4], argv[5]]]; c = [argv[6], argv[7]]; Input = argv.slice(8); // console.log(Input.slice(1000)); const calldataJson = { "a": a, "b": b, "c": c, "input": Input, } const keysJson = [ { "private_key": keypair.privKey.asCircuitInputs(), "public_key": keypair.pubKey.asCircuitInputs(), }, { "private_key": keypair2.privKey.asCircuitInputs(), "public_key": keypair2.pubKey.asCircuitInputs(), }, ] // save calldata to json file fs.writeFileSync("./test/keys.json", JSON.stringify(keysJson)); fs.writeFileSync("./test/encryptionCalldata.json", JSON.stringify(calldataJson)); }); it("Check circuit output", async () => { assert(Fr.eq(Fr.e(Input[0]),Fr.e(modelHash))); assert(Fr.eq(Fr.e(Input[1]),Fr.e(ecdhSharedKey))); assert(Fr.eq(Fr.e(Input[1003]),Fr.e(INPUT['public_key'][0]))); assert(Fr.eq(Fr.e(Input[1004]),Fr.e(INPUT['public_key'][1]))); }); it("Verifier should return true for correct proofs", async function () { expect(await verifier.verifyProof(a, b, c, Input)).to.be.true; }); it("Verifier should return false for invalid proof", async function () { let a = [0, 0]; let b = [[0, 0], [0, 0]]; let c = [0, 0]; expect(await verifier.verifyProof(a, b, c, Input)).to.be.false; }); it("Decryption should match", async function () { const ciphertext = { iv: Input[2], data: Input.slice(3,1004), } const decrypted = decrypt(ciphertext, ecdhSharedKey); for (let i = 0; i < 1000; i++) { assert(Fr.eq(Fr.e(decrypted[i]), Fr.e(input[i]))); } }); });
https://github.com/socathie/ZKaggleV2
hardhat/test/2.bounty.test.js
const { expect } = require("chai"); const { ethers } = require("hardhat"); const fs = require("fs"); const base32 = require("base32.js"); const labels = require("../assets/labels.json"); const circuitCalldata = require("./circuitCalldata.json"); const encryptionCalldata = require("./encryptionCalldata.json"); // read ../assets/cid.txt into an array of strings const cids = fs.readFileSync("assets/cid.txt").toString().split("\r"); const idx = 567; const _labels = []; describe("Bounty contract test", function () { const cidraw = []; // raw CIDs of the uploaded files let encryptionVerifierAddress; describe("Tx 1: Creating a bounty", function () { before(async function () { // deploy pairing contracts from pairing100 to pairing1000 const Pairing100 = await ethers.getContractFactory("Pairing100"); const pairing100 = await Pairing100.deploy(); await pairing100.deployed(); const Pairing200 = await ethers.getContractFactory("Pairing200"); const pairing200 = await Pairing200.deploy(); await pairing200.deployed(); const Pairing300 = await ethers.getContractFactory("Pairing300"); const pairing300 = await Pairing300.deploy(); await pairing300.deployed(); const Pairing400 = await ethers.getContractFactory("Pairing400"); const pairing400 = await Pairing400.deploy(); await pairing400.deployed(); const Pairing500 = await ethers.getContractFactory("Pairing500"); const pairing500 = await Pairing500.deploy(); await pairing500.deployed(); const Pairing600 = await ethers.getContractFactory("Pairing600"); const pairing600 = await Pairing600.deploy(); await pairing600.deployed(); const Pairing700 = await ethers.getContractFactory("Pairing700"); const pairing700 = await Pairing700.deploy(); await pairing700.deployed(); const Pairing800 = await ethers.getContractFactory("Pairing800"); const pairing800 = await Pairing800.deploy(); await pairing800.deployed(); const Pairing900 = await ethers.getContractFactory("Pairing900"); const pairing900 = await Pairing900.deploy(); await pairing900.deployed(); const Pairing1000 = await ethers.getContractFactory("Pairing1000"); const pairing1000 = await Pairing1000.deploy(); await pairing1000.deployed(); const EncyrptionVerifier = await ethers.getContractFactory("EncryptionVerifier"); const encryptionVerifier = await EncyrptionVerifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address); await encryptionVerifier.deployed(); encryptionVerifierAddress = encryptionVerifier.address; for (let i = 0; i < 10; i++) { const decoder = new base32.Decoder(); cidraw.push(decoder.write(cids[idx + i].slice(1)).finalize()); _labels.push(labels[idx + i]); } // write cidraw into a json file fs.writeFileSync("./test/cidraw.json", JSON.stringify(cidraw.map((cid) => '0x' + cid.toString('hex')))); // write _labels into a json file fs.writeFileSync("./test/labels.json", JSON.stringify(_labels)); }); it("Should reject deploying the contract is msg.value is 0", async function () { const owner = await ethers.provider.getSigner(0).getAddress(); const Bounty = await ethers.getContractFactory("Bounty"); const bounty = await Bounty.deploy(); await bounty.deployed(); await expect(bounty.initialize( owner, "Bounty 1", "This is the first bounty", cidraw, _labels, 70, encryptionVerifierAddress, )).to.be.revertedWith("Bounty reward must be greater than 0"); }); it("Should deploy the contract and set owner to first input", async function () { const owner = await ethers.provider.getSigner(0).getAddress(); const Bounty = await ethers.getContractFactory("Bounty"); const bounty = await Bounty.deploy(); await bounty.deployed(); const tx = await bounty.initialize( owner, "Bounty 1", "This is the first bounty", cidraw, _labels, 70, encryptionVerifierAddress, { value: ethers.utils.parseEther("1") } ); await tx.wait(); expect(await bounty.name()).to.equal("Bounty 1"); expect(await bounty.description()).to.equal("This is the first bounty"); for (let i = 0; i < 10; i++) { expect(await bounty.dataCIDs(i)).to.equal('0x' + cidraw[i].toString('hex')); expect(await bounty.labels(i)).to.equal(_labels[i]); } expect(await bounty.owner()).to.equal(owner); expect(await bounty.completedStep()).to.equal(1); }); }); let a, b, c, Input; describe("Tx 2: Submitting a bounty", function () { let bounty, verifier, encryptionVerifierAddress; const digests = []; before(async function () { // deploy pairing contracts from pairing100 to pairing1000 const Pairing100 = await ethers.getContractFactory("Pairing100"); const pairing100 = await Pairing100.deploy(); await pairing100.deployed(); const Pairing200 = await ethers.getContractFactory("Pairing200"); const pairing200 = await Pairing200.deploy(); await pairing200.deployed(); const Pairing300 = await ethers.getContractFactory("Pairing300"); const pairing300 = await Pairing300.deploy(); await pairing300.deployed(); const Pairing400 = await ethers.getContractFactory("Pairing400"); const pairing400 = await Pairing400.deploy(); await pairing400.deployed(); const Pairing500 = await ethers.getContractFactory("Pairing500"); const pairing500 = await Pairing500.deploy(); await pairing500.deployed(); const Pairing600 = await ethers.getContractFactory("Pairing600"); const pairing600 = await Pairing600.deploy(); await pairing600.deployed(); const Pairing700 = await ethers.getContractFactory("Pairing700"); const pairing700 = await Pairing700.deploy(); await pairing700.deployed(); const Pairing800 = await ethers.getContractFactory("Pairing800"); const pairing800 = await Pairing800.deploy(); await pairing800.deployed(); const Pairing900 = await ethers.getContractFactory("Pairing900"); const pairing900 = await Pairing900.deploy(); await pairing900.deployed(); const Pairing1000 = await ethers.getContractFactory("Pairing1000"); const pairing1000 = await Pairing1000.deploy(); await pairing1000.deployed(); const EncyrptionVerifier = await ethers.getContractFactory("EncryptionVerifier"); const encryptionVerifier = await EncyrptionVerifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address); await encryptionVerifier.deployed(); encryptionVerifierAddress = encryptionVerifier.address; const owner = await ethers.provider.getSigner(0).getAddress(); const Bounty = await ethers.getContractFactory("Bounty"); bounty = await Bounty.deploy(); await bounty.deployed(); const tx = await bounty.initialize( owner, "Bounty 1", "This is the first bounty", cidraw, _labels, 70, encryptionVerifierAddress, { value: ethers.utils.parseEther("1") } ); await tx.wait(); // Deploy the verifier const Verifier = await ethers.getContractFactory("CircuitVerifier"); verifier = await Verifier.deploy(); await verifier.deployed(); a = circuitCalldata.a; b = circuitCalldata.b; c = circuitCalldata.c; Input = circuitCalldata.input; }); it("Should reject a bounty with wrong proof", async function () { await expect(bounty.connect(ethers.provider.getSigner(1)). submitBounty( 0x0, 0x0, 0x0, verifier.address, [0, 0], [[0, 0], [0, 0]], [0, 0], Input )).to.be.revertedWith("Invalid proof"); }); it("Should reject a bounty with wrong verifier", async function () { await expect(bounty.connect(ethers.provider.getSigner(1)). submitBounty( 0x0, 0x0, 0x0, ethers.constants.AddressZero, a, b, c, Input )).to.be.revertedWith("Invalid verifier address"); }); it("Should reject a bounty with wrong input", async function () { await expect(bounty.connect(ethers.provider.getSigner(1)). submitBounty( 0x0, 0x0, 0x0, verifier.address, a, b, c, [..._labels, ...Array(21).keys()] )).to.be.revertedWith("Data CID mismatch"); }); it("Should reject a bounty with low accuracy", async function () { await expect(bounty.connect(ethers.provider.getSigner(1)). submitBounty( 0x0, 0x0, 0x0, verifier.address, a, b, c, [...Array(31).keys()] )).to.be.revertedWith("Accuracy threshold not met"); }); it("Should submit a bounty", async function () { const submitter = await ethers.provider.getSigner(1).getAddress(); const tx = await bounty.connect(ethers.provider.getSigner(1)). submitBounty( 0x0, 0x0, 0x0, verifier.address, a, b, c, Input ); await tx.wait(); expect(tx).to.emit(bounty, "BountySubmitted"); expect(await bounty.bountyHunter()).to.equal(submitter); expect(await bounty.completedStep()).to.equal(2); }); it("Should reject submitting a submitted bounty", async function () { await expect(bounty.connect(ethers.provider.getSigner(1)). submitBounty( 0x0, 0x0, 0x0, verifier.address, a, b, c, Input )).to.be.revertedWith("Bounty already submitted"); }); }); let publicKeys; describe("Tx 3: Releasing a bounty", function () { let bounty, verifier, encryptionVerifierAddress; before(async function () { // deploy pairing contracts from pairing100 to pairing1000 const Pairing100 = await ethers.getContractFactory("Pairing100"); const pairing100 = await Pairing100.deploy(); await pairing100.deployed(); const Pairing200 = await ethers.getContractFactory("Pairing200"); const pairing200 = await Pairing200.deploy(); await pairing200.deployed(); const Pairing300 = await ethers.getContractFactory("Pairing300"); const pairing300 = await Pairing300.deploy(); await pairing300.deployed(); const Pairing400 = await ethers.getContractFactory("Pairing400"); const pairing400 = await Pairing400.deploy(); await pairing400.deployed(); const Pairing500 = await ethers.getContractFactory("Pairing500"); const pairing500 = await Pairing500.deploy(); await pairing500.deployed(); const Pairing600 = await ethers.getContractFactory("Pairing600"); const pairing600 = await Pairing600.deploy(); await pairing600.deployed(); const Pairing700 = await ethers.getContractFactory("Pairing700"); const pairing700 = await Pairing700.deploy(); await pairing700.deployed(); const Pairing800 = await ethers.getContractFactory("Pairing800"); const pairing800 = await Pairing800.deploy(); await pairing800.deployed(); const Pairing900 = await ethers.getContractFactory("Pairing900"); const pairing900 = await Pairing900.deploy(); await pairing900.deployed(); const Pairing1000 = await ethers.getContractFactory("Pairing1000"); const pairing1000 = await Pairing1000.deploy(); await pairing1000.deployed(); const EncyrptionVerifier = await ethers.getContractFactory("EncryptionVerifier"); const encryptionVerifier = await EncyrptionVerifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address); await encryptionVerifier.deployed(); encryptionVerifierAddress = encryptionVerifier.address; const owner = await ethers.provider.getSigner(0).getAddress(); const Bounty = await ethers.getContractFactory("Bounty"); bounty = await Bounty.deploy(); await bounty.deployed(); const tx = await bounty.initialize( owner, "Bounty 1", "This is the first bounty", cidraw, _labels, 70, encryptionVerifierAddress, { value: ethers.utils.parseEther("1") } ); await tx.wait(); // Deploy the verifier const Verifier = await ethers.getContractFactory("CircuitVerifier"); verifier = await Verifier.deploy(); await verifier.deployed(); publicKeys = [encryptionCalldata.input[1003], encryptionCalldata.input[1004]]; }); it("Should reject releasing an unsubmitted bounty", async function () { await expect(bounty.releaseBounty(publicKeys)).to.be.revertedWith("Bounty hunter has not submitted proof"); }); it("Should reject releasing a bounty by non-owner", async function () { const tx = await bounty.connect(ethers.provider.getSigner(1)). submitBounty( 0x0, 0x0, 0x0, verifier.address, a, b, c, Input ); await tx.wait(); await expect(bounty.connect(ethers.provider.getSigner(1)).releaseBounty(publicKeys)).to.be.revertedWith("Ownable: caller is not the owner"); }); it("Should release a bounty", async function () { const tx = await bounty.releaseBounty(publicKeys); await tx.wait(); expect(tx).to.emit(bounty, "BountyReleased"); expect(await bounty.isComplete()).to.equal(true); expect(await bounty.completedStep()).to.equal(3); }); it("Should reject releasing a bounty twice", async function () { await expect(bounty.releaseBounty(publicKeys)).to.be.revertedWith("Bounty is already complete"); }); }); describe("Tx 4: Claiming a bounty", function () { let bounty, verifier, encryptionVerifierAddress; before(async function () { // deploy pairing contracts from pairing100 to pairing1000 const Pairing100 = await ethers.getContractFactory("Pairing100"); const pairing100 = await Pairing100.deploy(); await pairing100.deployed(); const Pairing200 = await ethers.getContractFactory("Pairing200"); const pairing200 = await Pairing200.deploy(); await pairing200.deployed(); const Pairing300 = await ethers.getContractFactory("Pairing300"); const pairing300 = await Pairing300.deploy(); await pairing300.deployed(); const Pairing400 = await ethers.getContractFactory("Pairing400"); const pairing400 = await Pairing400.deploy(); await pairing400.deployed(); const Pairing500 = await ethers.getContractFactory("Pairing500"); const pairing500 = await Pairing500.deploy(); await pairing500.deployed(); const Pairing600 = await ethers.getContractFactory("Pairing600"); const pairing600 = await Pairing600.deploy(); await pairing600.deployed(); const Pairing700 = await ethers.getContractFactory("Pairing700"); const pairing700 = await Pairing700.deploy(); await pairing700.deployed(); const Pairing800 = await ethers.getContractFactory("Pairing800"); const pairing800 = await Pairing800.deploy(); await pairing800.deployed(); const Pairing900 = await ethers.getContractFactory("Pairing900"); const pairing900 = await Pairing900.deploy(); await pairing900.deployed(); const Pairing1000 = await ethers.getContractFactory("Pairing1000"); const pairing1000 = await Pairing1000.deploy(); await pairing1000.deployed(); const EncyrptionVerifier = await ethers.getContractFactory("EncryptionVerifier"); const encryptionVerifier = await EncyrptionVerifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address); await encryptionVerifier.deployed(); encryptionVerifierAddress = encryptionVerifier.address; const owner = await ethers.provider.getSigner(0).getAddress(); const Bounty = await ethers.getContractFactory("Bounty"); bounty = await Bounty.deploy(); await bounty.deployed(); let tx = await bounty.initialize( owner, "Bounty 1", "This is the first bounty", cidraw, _labels, 70, encryptionVerifierAddress, { value: ethers.utils.parseEther("1") } ); await tx.wait(); // Deploy the verifier const Verifier = await ethers.getContractFactory("CircuitVerifier"); verifier = await Verifier.deploy(); await verifier.deployed(); tx = await bounty.connect(ethers.provider.getSigner(1)). submitBounty( 0x0, 0x0, 0x0, verifier.address, a, b, c, Input ); await tx.wait(); a = encryptionCalldata.a; b = encryptionCalldata.b; c = encryptionCalldata.c; Input = encryptionCalldata.input; }); it("Should reject claiming a bounty by non bounty hunter", async function () { await expect(bounty.connect(ethers.provider.getSigner(2)) .claimBounty(a, b, c, Input)).to.be.revertedWith("Only bounty hunter can claim bounty"); }); it("Should reject claiming an uncompleted bounty", async function () { await expect(bounty.connect(ethers.provider.getSigner(1)) .claimBounty(a, b, c, Input)) .to.be.revertedWith("Bounty is not complete"); }); it("Should claim a bounty", async function () { const bountyHunter = await ethers.provider.getSigner(1).getAddress(); const balance = await ethers.provider.getBalance(bountyHunter); let tx = await bounty.releaseBounty(publicKeys); await tx.wait(); tx = await bounty.connect(ethers.provider.getSigner(1)) .claimBounty(a, b, c, Input); await tx.wait(); expect(tx).to.emit(bounty, "BountyClaimed"); // Check that the bounty hunter has been paid expect(await ethers.provider.getBalance(bountyHunter)).to.greaterThan(balance); expect(await bounty.completedStep()).to.equal(4); }); it("Should reject claiming a claimed bounty", async function () { await expect(bounty.connect(ethers.provider.getSigner(1)) .claimBounty(a, b, c, Input)) .to.be.revertedWith("Bounty already claimed"); }); // TODO: add more tests for new features }); });
https://github.com/socathie/ZKaggleV2
hardhat/test/3.factory.test.js
const { expect } = require("chai"); const { ethers } = require("hardhat"); const fs = require("fs"); const base32 = require("base32.js"); const labels = require("../assets/labels.json"); // read ../assets/cid.txt into an array of strings const cids = fs.readFileSync("assets/cid.txt").toString().split("\r"); const idx = 567; const _labels = []; describe("BountyFactory test", function () { let factory; let Bounty; const cidraw = []; // raw CIDs of the uploaded files before(async function () { // deploy pairing contracts from pairing100 to pairing1000 const Pairing100 = await ethers.getContractFactory("Pairing100"); const pairing100 = await Pairing100.deploy(); await pairing100.deployed(); const Pairing200 = await ethers.getContractFactory("Pairing200"); const pairing200 = await Pairing200.deploy(); await pairing200.deployed(); const Pairing300 = await ethers.getContractFactory("Pairing300"); const pairing300 = await Pairing300.deploy(); await pairing300.deployed(); const Pairing400 = await ethers.getContractFactory("Pairing400"); const pairing400 = await Pairing400.deploy(); await pairing400.deployed(); const Pairing500 = await ethers.getContractFactory("Pairing500"); const pairing500 = await Pairing500.deploy(); await pairing500.deployed(); const Pairing600 = await ethers.getContractFactory("Pairing600"); const pairing600 = await Pairing600.deploy(); await pairing600.deployed(); const Pairing700 = await ethers.getContractFactory("Pairing700"); const pairing700 = await Pairing700.deploy(); await pairing700.deployed(); const Pairing800 = await ethers.getContractFactory("Pairing800"); const pairing800 = await Pairing800.deploy(); await pairing800.deployed(); const Pairing900 = await ethers.getContractFactory("Pairing900"); const pairing900 = await Pairing900.deploy(); await pairing900.deployed(); const Pairing1000 = await ethers.getContractFactory("Pairing1000"); const pairing1000 = await Pairing1000.deploy(); await pairing1000.deployed(); const EncyrptionVerifier = await ethers.getContractFactory("EncryptionVerifier"); const encryptionVerifier = await EncyrptionVerifier.deploy(pairing100.address, pairing200.address, pairing300.address, pairing400.address, pairing500.address, pairing600.address, pairing700.address, pairing800.address, pairing900.address, pairing1000.address); await encryptionVerifier.deployed(); const BountyFactory = await ethers.getContractFactory("BountyFactory"); factory = await BountyFactory.deploy(encryptionVerifier.address); await factory.deployed(); Bounty = await ethers.getContractFactory("Bounty"); for (let i = 0; i < 10; i++) { const decoder = new base32.Decoder(); cidraw.push(decoder.write(cids[idx + i].slice(1)).finalize()); _labels.push(labels[idx + i]); } }); it("Should create a new bounty", async function () { const tx = await factory.createBounty( "Bounty 1", "This is the first bounty", cidraw, _labels, 70, { value: ethers.utils.parseEther("1") } ); await tx.wait(); const bounty = await Bounty.attach(await factory.bounties(0)); expect(await bounty.owner()).to.equal(await ethers.provider.getSigner(0).getAddress()); expect(await ethers.provider.getBalance(bounty.address)).to.equal(ethers.utils.parseEther("1")); expect(await bounty.name()).to.equal("Bounty 1"); expect(await bounty.description()).to.equal("This is the first bounty"); expect(await factory.bountyCount()).to.equal(1); // TODO: add more checks }); it("Should calculate future bounty address", async function () { const nonce = await ethers.provider.getTransactionCount(factory.address); const futureAddress = ethers.utils.getContractAddress({ from: factory.address, nonce: nonce }); await expect(factory.createBounty( "Bounty 2", "This is the second bounty", cidraw, _labels, 70, { value: ethers.utils.parseEther("1") } )).to.emit(factory, "BountyCreated").withArgs(futureAddress); expect(await factory.bountyCount()).to.equal(2); }); });
https://github.com/socathie/ZKaggleV2
pgm.ipynb
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from tensorflow import keras\n", "from PIL import Image\n", "import json" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "for i in range(1000):\n", " image = Image.fromarray(x_train[i], mode='L')\n", " image.save('./hardhat/assets/'+str(i)+'.pgm')" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "with open('./hardhat/assets/labels.json', 'w') as f:\n", " json.dump(y_train[:1000].tolist(), f)\n", " f.close()" ] } ], "metadata": { "kernelspec": { "display_name": "keras2circom", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.13" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }
https://github.com/socathie/ZKaggleV2