halo2/src/circuit/gadget/utilities.rs

87 lines
2.0 KiB
Rust
Raw Normal View History

2021-06-02 18:41:03 -07:00
use halo2::{
circuit::{Cell, Layouter, Region},
2021-06-02 18:41:03 -07:00
plonk::{Advice, Column, Error, Permutation},
};
use pasta_curves::arithmetic::FieldExt;
2021-06-02 18:42:36 -07:00
mod cond_swap;
2021-06-04 03:04:51 -07:00
mod enable_flag;
mod lookup_range_check;
2021-06-02 18:41:54 -07:00
mod plonk;
2021-06-02 18:41:03 -07:00
/// A variable representing a number.
#[derive(Copy, Clone, Debug)]
pub struct CellValue<F: FieldExt> {
cell: Cell,
value: Option<F>,
}
pub trait Var<F: FieldExt> {
fn new(cell: Cell, value: Option<F>) -> Self;
fn cell(&self) -> Cell;
fn value(&self) -> Option<F>;
}
impl<F: FieldExt> Var<F> for CellValue<F> {
fn new(cell: Cell, value: Option<F>) -> Self {
Self { cell, value }
}
fn cell(&self) -> Cell {
self.cell
}
fn value(&self) -> Option<F> {
self.value
}
}
pub trait UtilitiesInstructions<F: FieldExt> {
2021-06-02 18:41:03 -07:00
type Var: Var<F>;
fn load_private(
&self,
mut layouter: impl Layouter<F>,
column: Column<Advice>,
value: Option<F>,
) -> Result<Self::Var, Error> {
layouter.assign_region(
|| "load private",
|mut region| {
let cell = region.assign_advice(
|| "load private",
column,
0,
|| value.ok_or(Error::SynthesisError),
)?;
Ok(Var::new(cell, value))
},
)
}
}
/// Assigns a cell at a specific offset within the given region, constraining it
/// to the same value as another cell (which may be in any region).
///
/// Returns an error if either `column` or `copy` is not within `perm`.
2021-06-02 18:41:03 -07:00
pub fn copy<A, AR, F: FieldExt>(
region: &mut Region<'_, F>,
annotation: A,
column: Column<Advice>,
offset: usize,
2021-06-02 18:41:03 -07:00
copy: &CellValue<F>,
perm: &Permutation,
) -> Result<CellValue<F>, Error>
where
A: Fn() -> AR,
AR: Into<String>,
{
let cell = region.assign_advice(annotation, column, offset, || {
2021-06-02 18:41:03 -07:00
copy.value.ok_or(Error::SynthesisError)
})?;
region.constrain_equal(perm, cell, copy.cell)?;
Ok(CellValue::new(cell, copy.value))
}