use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt;
use std::iter;
use std::ops::{Add, Mul, Neg, Range};
use ff::Field;
use crate::plonk::Assigned;
use crate::{
arithmetic::{FieldExt, Group},
plonk::{
permutation, Advice, Any, Assignment, Circuit, Column, ColumnType, ConstraintSystem, Error,
Expression, Fixed, FloorPlanner, Instance, Selector, VirtualCell,
},
poly::Rotation,
};
pub mod metadata;
mod util;
mod failure;
pub use failure::{FailureLocation, VerifyFailure};
pub mod cost;
pub use cost::CircuitCost;
mod gates;
pub use gates::CircuitGates;
#[cfg(feature = "dev-graph")]
mod graph;
#[cfg(feature = "dev-graph")]
#[cfg_attr(docsrs, doc(cfg(feature = "dev-graph")))]
pub use graph::{circuit_dot_graph, layout::CircuitLayout};
#[derive(Debug)]
struct Region {
name: String,
columns: HashSet<Column<Any>>,
rows: Option<(usize, usize)>,
enabled_selectors: HashMap<Selector, Vec<usize>>,
cells: Vec<(Column<Any>, usize)>,
}
impl Region {
fn update_extent(&mut self, column: Column<Any>, row: usize) {
self.columns.insert(column);
let (mut start, mut end) = self.rows.unwrap_or((row, row));
if row < start {
start = row;
}
if row > end {
end = row;
}
self.rows = Some((start, end));
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CellValue<F: Group + Field> {
Unassigned,
Assigned(F),
Poison(usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
enum Value<F: Group + Field> {
Real(F),
Poison,
}
impl<F: Group + Field> From<CellValue<F>> for Value<F> {
fn from(value: CellValue<F>) -> Self {
match value {
CellValue::Unassigned => Value::Real(F::zero()),
CellValue::Assigned(v) => Value::Real(v),
CellValue::Poison(_) => Value::Poison,
}
}
}
impl<F: Group + Field> Neg for Value<F> {
type Output = Self;
fn neg(self) -> Self::Output {
match self {
Value::Real(a) => Value::Real(-a),
_ => Value::Poison,
}
}
}
impl<F: Group + Field> Add for Value<F> {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
match (self, rhs) {
(Value::Real(a), Value::Real(b)) => Value::Real(a + b),
_ => Value::Poison,
}
}
}
impl<F: Group + Field> Mul for Value<F> {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
match (self, rhs) {
(Value::Real(a), Value::Real(b)) => Value::Real(a * b),
(Value::Real(x), Value::Poison) | (Value::Poison, Value::Real(x))
if x.is_zero_vartime() =>
{
Value::Real(F::zero())
}
_ => Value::Poison,
}
}
}
impl<F: Group + Field> Mul<F> for Value<F> {
type Output = Self;
fn mul(self, rhs: F) -> Self::Output {
match self {
Value::Real(lhs) => Value::Real(lhs * rhs),
Value::Poison if rhs.is_zero_vartime() => Value::Real(F::zero()),
_ => Value::Poison,
}
}
}
#[derive(Debug)]
pub struct MockProver<F: Group + Field> {
k: u32,
n: u32,
cs: ConstraintSystem<F>,
regions: Vec<Region>,
current_region: Option<Region>,
fixed: Vec<Vec<CellValue<F>>>,
advice: Vec<Vec<CellValue<F>>>,
instance: Vec<Vec<F>>,
selectors: Vec<Vec<bool>>,
permutation: permutation::keygen::Assembly,
usable_rows: Range<usize>,
}
impl<F: Field + Group> Assignment<F> for MockProver<F> {
fn enter_region<NR, N>(&mut self, name: N)
where
NR: Into<String>,
N: FnOnce() -> NR,
{
assert!(self.current_region.is_none());
self.current_region = Some(Region {
name: name().into(),
columns: HashSet::default(),
rows: None,
enabled_selectors: HashMap::default(),
cells: vec![],
});
}
fn exit_region(&mut self) {
self.regions.push(self.current_region.take().unwrap());
}
fn enable_selector<A, AR>(&mut self, _: A, selector: &Selector, row: usize) -> Result<(), Error>
where
A: FnOnce() -> AR,
AR: Into<String>,
{
if !self.usable_rows.contains(&row) {
return Err(Error::not_enough_rows_available(self.k));
}
self.current_region
.as_mut()
.unwrap()
.enabled_selectors
.entry(*selector)
.or_default()
.push(row);
self.selectors[selector.0][row] = true;
Ok(())
}
fn query_instance(&self, column: Column<Instance>, row: usize) -> Result<Option<F>, Error> {
if !self.usable_rows.contains(&row) {
return Err(Error::not_enough_rows_available(self.k));
}
self.instance
.get(column.index())
.and_then(|column| column.get(row))
.map(|v| Some(*v))
.ok_or(Error::BoundsFailure)
}
fn assign_advice<V, VR, A, AR>(
&mut self,
_: A,
column: Column<Advice>,
row: usize,
to: V,
) -> Result<(), Error>
where
V: FnOnce() -> Result<VR, Error>,
VR: Into<Assigned<F>>,
A: FnOnce() -> AR,
AR: Into<String>,
{
if !self.usable_rows.contains(&row) {
return Err(Error::not_enough_rows_available(self.k));
}
if let Some(region) = self.current_region.as_mut() {
region.update_extent(column.into(), row);
region.cells.push((column.into(), row));
}
*self
.advice
.get_mut(column.index())
.and_then(|v| v.get_mut(row))
.ok_or(Error::BoundsFailure)? = CellValue::Assigned(to()?.into().evaluate());
Ok(())
}
fn assign_fixed<V, VR, A, AR>(
&mut self,
_: A,
column: Column<Fixed>,
row: usize,
to: V,
) -> Result<(), Error>
where
V: FnOnce() -> Result<VR, Error>,
VR: Into<Assigned<F>>,
A: FnOnce() -> AR,
AR: Into<String>,
{
if !self.usable_rows.contains(&row) {
return Err(Error::not_enough_rows_available(self.k));
}
if let Some(region) = self.current_region.as_mut() {
region.update_extent(column.into(), row);
region.cells.push((column.into(), row));
}
*self
.fixed
.get_mut(column.index())
.and_then(|v| v.get_mut(row))
.ok_or(Error::BoundsFailure)? = CellValue::Assigned(to()?.into().evaluate());
Ok(())
}
fn copy(
&mut self,
left_column: Column<Any>,
left_row: usize,
right_column: Column<Any>,
right_row: usize,
) -> Result<(), crate::plonk::Error> {
if !self.usable_rows.contains(&left_row) || !self.usable_rows.contains(&right_row) {
return Err(Error::not_enough_rows_available(self.k));
}
self.permutation
.copy(left_column, left_row, right_column, right_row)
}
fn fill_from_row(
&mut self,
col: Column<Fixed>,
from_row: usize,
to: Option<Assigned<F>>,
) -> Result<(), Error> {
if !self.usable_rows.contains(&from_row) {
return Err(Error::not_enough_rows_available(self.k));
}
for row in self.usable_rows.clone().skip(from_row) {
self.assign_fixed(|| "", col, row, || to.ok_or(Error::Synthesis))?;
}
Ok(())
}
fn push_namespace<NR, N>(&mut self, _: N)
where
NR: Into<String>,
N: FnOnce() -> NR,
{
}
fn pop_namespace(&mut self, _: Option<String>) {
}
}
impl<F: FieldExt> MockProver<F> {
pub fn run<ConcreteCircuit: Circuit<F>>(
k: u32,
circuit: &ConcreteCircuit,
instance: Vec<Vec<F>>,
) -> Result<Self, Error> {
let n = 1 << k;
let mut cs = ConstraintSystem::default();
let config = ConcreteCircuit::configure(&mut cs);
let cs = cs;
if n < cs.minimum_rows() {
return Err(Error::not_enough_rows_available(k));
}
if instance.len() != cs.num_instance_columns {
return Err(Error::InvalidInstances);
}
let instance = instance
.into_iter()
.map(|mut instance| {
if instance.len() > n - (cs.blinding_factors() + 1) {
return Err(Error::InstanceTooLarge);
}
instance.resize(n, F::zero());
Ok(instance)
})
.collect::<Result<Vec<_>, _>>()?;
let fixed = vec![vec![CellValue::Unassigned; n]; cs.num_fixed_columns];
let selectors = vec![vec![false; n]; cs.num_selectors];
let blinding_factors = cs.blinding_factors();
let usable_rows = n - (blinding_factors + 1);
let advice = vec![
{
let mut column = vec![CellValue::Unassigned; n];
for (i, cell) in column.iter_mut().enumerate().skip(usable_rows) {
*cell = CellValue::Poison(i);
}
column
};
cs.num_advice_columns
];
let permutation = permutation::keygen::Assembly::new(n, &cs.permutation);
let constants = cs.constants.clone();
let mut prover = MockProver {
k,
n: n as u32,
cs,
regions: vec![],
current_region: None,
fixed,
advice,
instance,
selectors,
permutation,
usable_rows: 0..usable_rows,
};
ConcreteCircuit::FloorPlanner::synthesize(&mut prover, circuit, config, constants)?;
let (cs, selector_polys) = prover.cs.compress_selectors(prover.selectors.clone());
prover.cs = cs;
prover.fixed.extend(selector_polys.into_iter().map(|poly| {
let mut v = vec![CellValue::Unassigned; n];
for (v, p) in v.iter_mut().zip(&poly[..]) {
*v = CellValue::Assigned(*p);
}
v
}));
Ok(prover)
}
pub fn verify(&self) -> Result<(), Vec<VerifyFailure>> {
let n = self.n as i32;
let selector_errors = self.regions.iter().enumerate().flat_map(|(r_i, r)| {
r.enabled_selectors.iter().flat_map(move |(selector, at)| {
self.cs
.gates
.iter()
.enumerate()
.filter(move |(_, g)| g.queried_selectors().contains(selector))
.flat_map(move |(gate_index, gate)| {
at.iter().flat_map(move |selector_row| {
let gate_row = *selector_row as i32;
gate.queried_cells().iter().filter_map(move |cell| {
let cell_row = ((gate_row + n + cell.rotation.0) % n) as usize;
if r.cells.contains(&(cell.column, cell_row)) {
None
} else {
Some(VerifyFailure::CellNotAssigned {
gate: (gate_index, gate.name()).into(),
region: (r_i, r.name.clone()).into(),
gate_offset: *selector_row,
column: cell.column,
offset: cell_row as isize - r.rows.unwrap().0 as isize,
})
}
})
})
})
})
});
let gate_errors =
self.cs
.gates
.iter()
.enumerate()
.flat_map(|(gate_index, gate)| {
(n..(2 * n)).flat_map(move |row| {
gate.polynomials().iter().enumerate().filter_map(
move |(poly_index, poly)| match poly.evaluate(
&|scalar| Value::Real(scalar),
&|_| panic!("virtual selectors are removed during optimization"),
&util::load(n, row, &self.cs.fixed_queries, &self.fixed),
&util::load(n, row, &self.cs.advice_queries, &self.advice),
&util::load_instance(
n,
row,
&self.cs.instance_queries,
&self.instance,
),
&|a| -a,
&|a, b| a + b,
&|a, b| a * b,
&|a, scalar| a * scalar,
) {
Value::Real(x) if x.is_zero_vartime() => None,
Value::Real(_) => Some(VerifyFailure::ConstraintNotSatisfied {
constraint: (
(gate_index, gate.name()).into(),
poly_index,
gate.constraint_name(poly_index),
)
.into(),
location: FailureLocation::find_expressions(
&self.cs,
&self.regions,
(row - n) as usize,
Some(poly).into_iter(),
),
cell_values: util::cell_values(
gate,
poly,
&util::load(n, row, &self.cs.fixed_queries, &self.fixed),
&util::load(n, row, &self.cs.advice_queries, &self.advice),
&util::load_instance(
n,
row,
&self.cs.instance_queries,
&self.instance,
),
),
}),
Value::Poison => Some(VerifyFailure::ConstraintPoisoned {
constraint: (
(gate_index, gate.name()).into(),
poly_index,
gate.constraint_name(poly_index),
)
.into(),
}),
},
)
})
});
let lookup_errors =
self.cs
.lookups
.iter()
.enumerate()
.flat_map(|(lookup_index, lookup)| {
let load = |expression: &Expression<F>, row| {
expression.evaluate(
&|scalar| Value::Real(scalar),
&|_| panic!("virtual selectors are removed during optimization"),
&|index, _, _| {
let query = self.cs.fixed_queries[index];
let column_index = query.0.index();
let rotation = query.1 .0;
self.fixed[column_index]
[(row as i32 + n + rotation) as usize % n as usize]
.into()
},
&|index, _, _| {
let query = self.cs.advice_queries[index];
let column_index = query.0.index();
let rotation = query.1 .0;
self.advice[column_index]
[(row as i32 + n + rotation) as usize % n as usize]
.into()
},
&|index, _, _| {
let query = self.cs.instance_queries[index];
let column_index = query.0.index();
let rotation = query.1 .0;
Value::Real(
self.instance[column_index]
[(row as i32 + n + rotation) as usize % n as usize],
)
},
&|a| -a,
&|a, b| a + b,
&|a, b| a * b,
&|a, scalar| a * scalar,
)
};
assert!(lookup.table_expressions.len() == lookup.input_expressions.len());
assert!(self.usable_rows.end > 0);
let fill_row: Vec<_> = lookup
.table_expressions
.iter()
.map(move |c| load(c, self.usable_rows.end - 1))
.collect();
let mut table: Vec<Vec<_>> = self
.usable_rows
.clone()
.filter_map(|table_row| {
let t = lookup
.table_expressions
.iter()
.map(move |c| load(c, table_row))
.collect();
if t != fill_row {
Some(t)
} else {
None
}
})
.collect();
table.sort_unstable();
let mut inputs: Vec<(Vec<_>, usize)> = self
.usable_rows
.clone()
.filter_map(|input_row| {
let t = lookup
.input_expressions
.iter()
.map(move |c| load(c, input_row))
.collect();
if t != fill_row {
Some((t, input_row))
} else {
None
}
})
.collect();
inputs.sort_unstable();
let mut i = 0;
inputs
.iter()
.filter_map(move |(input, input_row)| {
while i < table.len() && &table[i] < input {
i += 1;
}
if i == table.len() || &table[i] > input {
assert!(table.binary_search(input).is_err());
Some(VerifyFailure::Lookup {
lookup_index,
location: FailureLocation::find_expressions(
&self.cs,
&self.regions,
*input_row,
lookup.input_expressions.iter(),
),
})
} else {
None
}
})
.collect::<Vec<_>>()
});
let perm_errors = {
let original = |column, row| {
self.cs
.permutation
.get_columns()
.get(column)
.map(|c: &Column<Any>| match c.column_type() {
Any::Advice => self.advice[c.index()][row],
Any::Fixed => self.fixed[c.index()][row],
Any::Instance => CellValue::Assigned(self.instance[c.index()][row]),
})
.unwrap()
};
self.permutation
.mapping
.iter()
.enumerate()
.flat_map(move |(column, values)| {
values.iter().enumerate().filter_map(move |(row, cell)| {
let original_cell = original(column, row);
let permuted_cell = original(cell.0, cell.1);
if original_cell == permuted_cell {
None
} else {
let columns = self.cs.permutation.get_columns();
let column = columns.get(column).unwrap();
Some(VerifyFailure::Permutation {
column: (*column).into(),
location: FailureLocation::find(
&self.regions,
row,
Some(column).into_iter().cloned().collect(),
),
})
}
})
})
};
let mut errors: Vec<_> = iter::empty()
.chain(selector_errors)
.chain(gate_errors)
.chain(lookup_errors)
.chain(perm_errors)
.collect();
if errors.is_empty() {
Ok(())
} else {
errors.dedup_by(|a, b| match (a, b) {
(
a @ VerifyFailure::ConstraintPoisoned { .. },
b @ VerifyFailure::ConstraintPoisoned { .. },
) => a == b,
_ => false,
});
Err(errors)
}
}
pub fn assert_satisfied(&self) {
if let Err(errs) = self.verify() {
for err in errs {
err.emit(self);
eprintln!();
}
panic!("circuit was not satisfied");
}
}
}
#[cfg(test)]
mod tests {
use pasta_curves::Fp;
use super::{FailureLocation, MockProver, VerifyFailure};
use crate::{
circuit::{Layouter, SimpleFloorPlanner},
plonk::{
Advice, Any, Circuit, Column, ConstraintSystem, Error, Expression, Selector,
TableColumn,
},
poly::Rotation,
};
#[test]
fn unassigned_cell() {
const K: u32 = 4;
#[derive(Clone)]
struct FaultyCircuitConfig {
a: Column<Advice>,
q: Selector,
}
struct FaultyCircuit {}
impl Circuit<Fp> for FaultyCircuit {
type Config = FaultyCircuitConfig;
type FloorPlanner = SimpleFloorPlanner;
fn configure(meta: &mut ConstraintSystem<Fp>) -> Self::Config {
let a = meta.advice_column();
let b = meta.advice_column();
let q = meta.selector();
meta.create_gate("Equality check", |cells| {
let a = cells.query_advice(a, Rotation::prev());
let b = cells.query_advice(b, Rotation::cur());
let q = cells.query_selector(q);
vec![q * (a - b)]
});
FaultyCircuitConfig { a, q }
}
fn without_witnesses(&self) -> Self {
Self {}
}
fn synthesize(
&self,
config: Self::Config,
mut layouter: impl Layouter<Fp>,
) -> Result<(), Error> {
layouter.assign_region(
|| "Faulty synthesis",
|mut region| {
config.q.enable(&mut region, 1)?;
region.assign_advice(|| "a", config.a, 0, || Ok(Fp::zero()))?;
Ok(())
},
)
}
}
let prover = MockProver::run(K, &FaultyCircuit {}, vec![]).unwrap();
assert_eq!(
prover.verify(),
Err(vec![VerifyFailure::CellNotAssigned {
gate: (0, "Equality check").into(),
region: (0, "Faulty synthesis".to_owned()).into(),
gate_offset: 1,
column: Column::new(1, Any::Advice),
offset: 1,
}])
);
}
#[test]
fn bad_lookup() {
const K: u32 = 4;
#[derive(Clone)]
struct FaultyCircuitConfig {
a: Column<Advice>,
q: Selector,
table: TableColumn,
}
struct FaultyCircuit {}
impl Circuit<Fp> for FaultyCircuit {
type Config = FaultyCircuitConfig;
type FloorPlanner = SimpleFloorPlanner;
fn configure(meta: &mut ConstraintSystem<Fp>) -> Self::Config {
let a = meta.advice_column();
let q = meta.complex_selector();
let table = meta.lookup_table_column();
meta.lookup(|cells| {
let a = cells.query_advice(a, Rotation::cur());
let q = cells.query_selector(q);
let not_q = Expression::Constant(Fp::one()) - q.clone();
let default = Expression::Constant(Fp::from(2));
vec![(q * a + not_q * default, table)]
});
FaultyCircuitConfig { a, q, table }
}
fn without_witnesses(&self) -> Self {
Self {}
}
fn synthesize(
&self,
config: Self::Config,
mut layouter: impl Layouter<Fp>,
) -> Result<(), Error> {
layouter.assign_table(
|| "Doubling table",
|mut table| {
(1..(1 << (K - 1)))
.map(|i| {
table.assign_cell(
|| format!("table[{}] = {}", i, 2 * i),
config.table,
i - 1,
|| Ok(Fp::from(2 * i as u64)),
)
})
.fold(Ok(()), |acc, res| acc.and(res))
},
)?;
layouter.assign_region(
|| "Good synthesis",
|mut region| {
config.q.enable(&mut region, 0)?;
config.q.enable(&mut region, 1)?;
region.assign_advice(|| "a = 2", config.a, 0, || Ok(Fp::from(2)))?;
region.assign_advice(|| "a = 6", config.a, 1, || Ok(Fp::from(6)))?;
Ok(())
},
)?;
layouter.assign_region(
|| "Faulty synthesis",
|mut region| {
config.q.enable(&mut region, 0)?;
config.q.enable(&mut region, 1)?;
region.assign_advice(|| "a = 4", config.a, 0, || Ok(Fp::from(4)))?;
region.assign_advice(|| "a = 5", config.a, 1, || Ok(Fp::from(5)))?;
Ok(())
},
)
}
}
let prover = MockProver::run(K, &FaultyCircuit {}, vec![]).unwrap();
assert_eq!(
prover.verify(),
Err(vec![VerifyFailure::Lookup {
lookup_index: 0,
location: FailureLocation::InRegion {
region: (2, "Faulty synthesis").into(),
offset: 1,
}
}])
);
}
}