use ark_ec::pairing::Pairing;
use std::{fs::File, path::Path};
use super::{CircomCircuit, R1CS};
use num_bigint::BigInt;
use std::collections::HashMap;
use crate::{circom::R1CSFile, witness::WitnessCalculator};
use color_eyre::Result;
#[derive(Clone, Debug)]
pub struct CircomBuilder<E: Pairing> {
pub cfg: CircomConfig<E>,
pub inputs: HashMap<String, Vec<BigInt>>,
}
#[derive(Clone, Debug)]
pub struct CircomConfig<E: Pairing> {
pub r1cs: R1CS<E>,
pub wtns: WitnessCalculator,
pub sanity_check: bool,
}
impl<E: Pairing> CircomConfig<E> {
pub fn new(wtns: impl AsRef<Path>, r1cs: impl AsRef<Path>) -> Result<Self> {
let wtns = WitnessCalculator::new(wtns).unwrap();
let reader = File::open(r1cs)?;
let r1cs = R1CSFile::new(reader)?.into();
Ok(Self {
wtns,
r1cs,
sanity_check: false,
})
}
}
impl<E: Pairing> CircomBuilder<E> {
pub fn new(cfg: CircomConfig<E>) -> Self {
Self {
cfg,
inputs: HashMap::new(),
}
}
pub fn push_input<T: Into<BigInt>>(&mut self, name: impl ToString, val: T) {
let values = self.inputs.entry(name.to_string()).or_insert_with(Vec::new);
values.push(val.into());
}
pub fn setup(&self) -> CircomCircuit<E> {
let mut circom = CircomCircuit {
r1cs: self.cfg.r1cs.clone(),
witness: None,
};
circom.r1cs.wire_mapping = None;
circom
}
pub fn build(mut self) -> Result<CircomCircuit<E>> {
let mut circom = self.setup();
let witness = self
.cfg
.wtns
.calculate_witness_element::<E, _>(self.inputs, self.cfg.sanity_check)?;
circom.witness = Some(witness);
debug_assert!({
use ark_relations::r1cs::{ConstraintSynthesizer, ConstraintSystem};
let cs = ConstraintSystem::<E::ScalarField>::new_ref();
circom.clone().generate_constraints(cs.clone()).unwrap();
let is_satisfied = cs.is_satisfied().unwrap();
if !is_satisfied {
println!(
"Unsatisfied constraint: {:?}",
cs.which_is_unsatisfied().unwrap()
);
}
is_satisfied
});
Ok(circom)
}
}