use blake2b_simd::Params as Blake2bParams;
use group::ff::{Field, FromUniformBytes, PrimeField};
use crate::arithmetic::CurveAffine;
use crate::helpers::{
polynomial_slice_byte_length, read_polynomial_vec, write_polynomial_slice, SerdeCurveAffine,
SerdePrimeField,
};
use crate::poly::{Coeff, EvaluationDomain, LagrangeCoeff, PinnedEvaluationDomain, Polynomial};
use crate::transcript::{ChallengeScalar, EncodedChallenge, Transcript};
use crate::SerdeFormat;
mod assigned;
mod circuit;
mod error;
mod evaluation;
mod keygen;
mod lookup;
pub mod permutation;
mod vanishing;
mod prover;
mod verifier;
pub use assigned::*;
pub use circuit::*;
pub use error::*;
pub use keygen::*;
pub use prover::*;
pub use verifier::*;
use evaluation::Evaluator;
use std::io;
#[derive(Clone, Debug)]
pub struct VerifyingKey<C: CurveAffine> {
domain: EvaluationDomain<C::Scalar>,
fixed_commitments: Vec<C>,
permutation: permutation::VerifyingKey<C>,
cs: ConstraintSystem<C::Scalar>,
cs_degree: usize,
transcript_repr: C::Scalar,
selectors: Vec<Vec<bool>>,
compress_selectors: bool,
}
impl<C: SerdeCurveAffine> VerifyingKey<C>
where
C::Scalar: SerdePrimeField + FromUniformBytes<64>, {
pub fn write<W: io::Write>(&self, writer: &mut W, format: SerdeFormat) -> io::Result<()> {
writer.write_all(&[0x02])?;
writer.write_all(&self.domain.k().to_le_bytes())?;
writer.write_all(&[self.compress_selectors as u8])?;
writer.write_all(&(self.fixed_commitments.len() as u32).to_le_bytes())?;
for commitment in &self.fixed_commitments {
commitment.write(writer, format)?;
}
self.permutation.write(writer, format)?;
if !self.compress_selectors {
assert!(self.selectors.is_empty());
}
for selector in &self.selectors {
for bits in selector.chunks(8) {
writer.write_all(&[crate::helpers::pack(bits)])?;
}
}
Ok(())
}
pub fn read<R: io::Read, ConcreteCircuit: Circuit<C::Scalar>>(
reader: &mut R,
format: SerdeFormat,
#[cfg(feature = "circuit-params")] params: ConcreteCircuit::Params,
) -> io::Result<Self> {
let mut version_byte = [0u8; 1];
reader.read_exact(&mut version_byte)?;
if 0x02 != version_byte[0] {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"unexpected version byte",
));
}
let mut k = [0u8; 4];
reader.read_exact(&mut k)?;
let k = u32::from_le_bytes(k);
let mut compress_selectors = [0u8; 1];
reader.read_exact(&mut compress_selectors)?;
if compress_selectors[0] != 0 && compress_selectors[0] != 1 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"unexpected compress_selectors not boolean",
));
}
let compress_selectors = compress_selectors[0] == 1;
let (domain, cs, _) = keygen::create_domain::<C, ConcreteCircuit>(
k,
#[cfg(feature = "circuit-params")]
params,
);
let mut num_fixed_columns = [0u8; 4];
reader.read_exact(&mut num_fixed_columns)?;
let num_fixed_columns = u32::from_le_bytes(num_fixed_columns);
let fixed_commitments: Vec<_> = (0..num_fixed_columns)
.map(|_| C::read(reader, format))
.collect::<io::Result<_>>()?;
let permutation = permutation::VerifyingKey::read(reader, &cs.permutation, format)?;
let (cs, selectors) = if compress_selectors {
let selectors: Vec<Vec<bool>> = vec![vec![false; 1 << k]; cs.num_selectors]
.into_iter()
.map(|mut selector| {
let mut selector_bytes = vec![0u8; (selector.len() + 7) / 8];
reader.read_exact(&mut selector_bytes)?;
for (bits, byte) in selector.chunks_mut(8).zip(selector_bytes) {
crate::helpers::unpack(byte, bits);
}
Ok(selector)
})
.collect::<io::Result<_>>()?;
let (cs, _) = cs.compress_selectors(selectors.clone());
(cs, selectors)
} else {
let fake_selectors = vec![vec![false]; cs.num_selectors];
let (cs, _) = cs.directly_convert_selectors_to_fixed(fake_selectors);
(cs, vec![])
};
Ok(Self::from_parts(
domain,
fixed_commitments,
permutation,
cs,
selectors,
compress_selectors,
))
}
pub fn to_bytes(&self, format: SerdeFormat) -> Vec<u8> {
let mut bytes = Vec::<u8>::with_capacity(self.bytes_length());
Self::write(self, &mut bytes, format).expect("Writing to vector should not fail");
bytes
}
pub fn from_bytes<ConcreteCircuit: Circuit<C::Scalar>>(
mut bytes: &[u8],
format: SerdeFormat,
#[cfg(feature = "circuit-params")] params: ConcreteCircuit::Params,
) -> io::Result<Self> {
Self::read::<_, ConcreteCircuit>(
&mut bytes,
format,
#[cfg(feature = "circuit-params")]
params,
)
}
}
impl<C: CurveAffine> VerifyingKey<C> {
fn bytes_length(&self) -> usize {
8 + (self.fixed_commitments.len() * C::default().to_bytes().as_ref().len())
+ self.permutation.bytes_length()
+ self.selectors.len()
* (self
.selectors
.get(0)
.map(|selector| (selector.len() + 7) / 8)
.unwrap_or(0))
}
fn from_parts(
domain: EvaluationDomain<C::Scalar>,
fixed_commitments: Vec<C>,
permutation: permutation::VerifyingKey<C>,
cs: ConstraintSystem<C::Scalar>,
selectors: Vec<Vec<bool>>,
compress_selectors: bool,
) -> Self
where
C::Scalar: FromUniformBytes<64>,
{
let cs_degree = cs.degree();
let mut vk = Self {
domain,
fixed_commitments,
permutation,
cs,
cs_degree,
transcript_repr: C::Scalar::ZERO,
selectors,
compress_selectors,
};
let mut hasher = Blake2bParams::new()
.hash_length(64)
.personal(b"Halo2-Verify-Key")
.to_state();
let s = format!("{:?}", vk.pinned());
hasher.update(&(s.len() as u64).to_le_bytes());
hasher.update(s.as_bytes());
vk.transcript_repr = C::Scalar::from_uniform_bytes(hasher.finalize().as_array());
vk
}
pub fn hash_into<E: EncodedChallenge<C>, T: Transcript<C, E>>(
&self,
transcript: &mut T,
) -> io::Result<()> {
transcript.common_scalar(self.transcript_repr)?;
Ok(())
}
pub fn pinned(&self) -> PinnedVerificationKey<'_, C> {
PinnedVerificationKey {
base_modulus: C::Base::MODULUS,
scalar_modulus: C::Scalar::MODULUS,
domain: self.domain.pinned(),
fixed_commitments: &self.fixed_commitments,
permutation: &self.permutation,
cs: self.cs.pinned(),
}
}
pub fn fixed_commitments(&self) -> &Vec<C> {
&self.fixed_commitments
}
pub fn permutation(&self) -> &permutation::VerifyingKey<C> {
&self.permutation
}
pub fn cs(&self) -> &ConstraintSystem<C::Scalar> {
&self.cs
}
pub fn transcript_repr(&self) -> C::Scalar {
self.transcript_repr
}
}
#[allow(dead_code)]
#[derive(Debug)]
pub struct PinnedVerificationKey<'a, C: CurveAffine> {
base_modulus: &'static str,
scalar_modulus: &'static str,
domain: PinnedEvaluationDomain<'a, C::Scalar>,
cs: PinnedConstraintSystem<'a, C::Scalar>,
fixed_commitments: &'a Vec<C>,
permutation: &'a permutation::VerifyingKey<C>,
}
#[derive(Clone, Debug)]
pub struct ProvingKey<C: CurveAffine> {
vk: VerifyingKey<C>,
l0: Polynomial<C::Scalar, Coeff>,
l_last: Polynomial<C::Scalar, Coeff>,
l_active_row: Polynomial<C::Scalar, Coeff>,
fixed_values: Vec<Polynomial<C::Scalar, LagrangeCoeff>>,
fixed_polys: Vec<Polynomial<C::Scalar, Coeff>>,
permutation: permutation::ProvingKey<C>,
ev: Evaluator<C>,
}
impl<C: CurveAffine> ProvingKey<C>
where
C::Scalar: FromUniformBytes<64>,
{
pub fn get_vk(&self) -> &VerifyingKey<C> {
&self.vk
}
fn bytes_length(&self) -> usize {
let scalar_len = C::Scalar::default().to_repr().as_ref().len();
self.vk.bytes_length()
+ 12
+ scalar_len * (self.l0.len() + self.l_last.len() + self.l_active_row.len())
+ polynomial_slice_byte_length(&self.fixed_values)
+ polynomial_slice_byte_length(&self.fixed_polys)
+ self.permutation.bytes_length()
}
}
impl<C: SerdeCurveAffine> ProvingKey<C>
where
C::Scalar: SerdePrimeField + FromUniformBytes<64>,
{
pub fn write<W: io::Write>(&self, writer: &mut W, format: SerdeFormat) -> io::Result<()> {
self.vk.write(writer, format)?;
self.l0.write(writer, format);
self.l_last.write(writer, format);
self.l_active_row.write(writer, format);
write_polynomial_slice(&self.fixed_values, writer, format);
write_polynomial_slice(&self.fixed_polys, writer, format);
self.permutation.write(writer, format);
Ok(())
}
pub fn read<R: io::Read, ConcreteCircuit: Circuit<C::Scalar>>(
reader: &mut R,
format: SerdeFormat,
#[cfg(feature = "circuit-params")] params: ConcreteCircuit::Params,
) -> io::Result<Self> {
let vk = VerifyingKey::<C>::read::<R, ConcreteCircuit>(
reader,
format,
#[cfg(feature = "circuit-params")]
params,
)?;
let l0 = Polynomial::read(reader, format);
let l_last = Polynomial::read(reader, format);
let l_active_row = Polynomial::read(reader, format);
let fixed_values = read_polynomial_vec(reader, format);
let fixed_polys = read_polynomial_vec(reader, format);
let permutation = permutation::ProvingKey::read(reader, format);
let ev = Evaluator::new(vk.cs());
Ok(Self {
vk,
l0,
l_last,
l_active_row,
fixed_values,
fixed_polys,
permutation,
ev,
})
}
pub fn to_bytes(&self, format: SerdeFormat) -> Vec<u8> {
let mut bytes = Vec::<u8>::with_capacity(self.bytes_length());
Self::write(self, &mut bytes, format).expect("Writing to vector should not fail");
bytes
}
pub fn from_bytes<ConcreteCircuit: Circuit<C::Scalar>>(
mut bytes: &[u8],
format: SerdeFormat,
#[cfg(feature = "circuit-params")] params: ConcreteCircuit::Params,
) -> io::Result<Self> {
Self::read::<_, ConcreteCircuit>(
&mut bytes,
format,
#[cfg(feature = "circuit-params")]
params,
)
}
}
impl<C: CurveAffine> VerifyingKey<C> {
pub fn get_domain(&self) -> &EvaluationDomain<C::Scalar> {
&self.domain
}
}
#[derive(Clone, Copy, Debug)]
struct Theta;
type ChallengeTheta<F> = ChallengeScalar<F, Theta>;
#[derive(Clone, Copy, Debug)]
struct Beta;
type ChallengeBeta<F> = ChallengeScalar<F, Beta>;
#[derive(Clone, Copy, Debug)]
struct Gamma;
type ChallengeGamma<F> = ChallengeScalar<F, Gamma>;
#[derive(Clone, Copy, Debug)]
struct Y;
type ChallengeY<F> = ChallengeScalar<F, Y>;
#[derive(Clone, Copy, Debug)]
struct X;
type ChallengeX<F> = ChallengeScalar<F, X>;