mirror of
https://github.com/logos-storage/plonky2.git
synced 2026-01-04 23:03:08 +00:00
commit
9c2b7334c8
@ -39,7 +39,7 @@ fn bench_prove<F: Field>() {
|
||||
let gmimc_gate = GMiMCGate::<F, GMIMC_ROUNDS>::with_automatic_constants();
|
||||
|
||||
let config = CircuitConfig {
|
||||
num_wires: 120,
|
||||
num_wires: 134,
|
||||
num_routed_wires: 12,
|
||||
security_bits: 128,
|
||||
rate_bits: 3,
|
||||
|
||||
@ -22,8 +22,13 @@ pub struct CircuitBuilder<F: Field> {
|
||||
/// The types of gates used in this circuit.
|
||||
gates: HashSet<GateRef<F>>,
|
||||
|
||||
/// The concrete placement of each gate.
|
||||
gate_instances: Vec<GateInstance<F>>,
|
||||
|
||||
/// The next available index for a VirtualAdviceTarget.
|
||||
virtual_target_index: usize,
|
||||
|
||||
/// Generators used to generate the witness.
|
||||
generators: Vec<Box<dyn WitnessGenerator<F>>>,
|
||||
}
|
||||
|
||||
@ -33,10 +38,29 @@ impl<F: Field> CircuitBuilder<F> {
|
||||
config,
|
||||
gates: HashSet::new(),
|
||||
gate_instances: Vec::new(),
|
||||
virtual_target_index: 0,
|
||||
generators: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a new "virtual" advice target. This is not an actual wire in the witness, but just a
|
||||
/// target that help facilitate witness generation. In particular, a generator can assign a
|
||||
/// values to a virtual target, which can then be copied to other (virtual or concrete) targets
|
||||
/// via `generate_copy`. When we generate the final witness (a grid of wire values), these
|
||||
/// virtual targets will go away.
|
||||
///
|
||||
/// Since virtual targets are not part of the actual permutation argument, they cannot be used
|
||||
/// with `assert_equal`.
|
||||
pub fn add_virtual_advice_target(&mut self) -> Target {
|
||||
let index = self.virtual_target_index;
|
||||
self.virtual_target_index += 1;
|
||||
Target::VirtualAdviceTarget { index }
|
||||
}
|
||||
|
||||
pub fn add_virtual_advice_targets(&mut self, n: usize) -> Vec<Target> {
|
||||
(0..n).map(|_i| self.add_virtual_advice_target()).collect()
|
||||
}
|
||||
|
||||
pub fn add_gate_no_constants(&mut self, gate_type: GateRef<F>) -> usize {
|
||||
self.add_gate(gate_type, Vec::new())
|
||||
}
|
||||
|
||||
@ -3,37 +3,39 @@ use std::convert::TryInto;
|
||||
use crate::circuit_builder::CircuitBuilder;
|
||||
use crate::field::field::Field;
|
||||
use crate::gates::gmimc::GMiMCGate;
|
||||
use crate::gates::noop::NoopGate;
|
||||
use crate::hash::GMIMC_ROUNDS;
|
||||
use crate::target::Target;
|
||||
use crate::wire::Wire;
|
||||
|
||||
// TODO: Move to be next to native `permute`?
|
||||
impl<F: Field> CircuitBuilder<F> {
|
||||
pub fn permute(&mut self, inputs: [Target; 12]) -> [Target; 12] {
|
||||
let zero = self.zero();
|
||||
self.permute_switched(inputs, zero)
|
||||
}
|
||||
|
||||
pub(crate) fn permute_switched(&mut self, inputs: [Target; 12], switch: Target) -> [Target; 12] {
|
||||
let gate = self.add_gate_no_constants(
|
||||
GMiMCGate::<F, GMIMC_ROUNDS>::with_automatic_constants());
|
||||
|
||||
let switch_wire = GMiMCGate::<F, GMIMC_ROUNDS>::WIRE_SWITCH;
|
||||
let switch_wire = Target::Wire(Wire { gate, input: switch_wire });
|
||||
self.route(switch, switch_wire);
|
||||
// We don't want to swap any inputs, so set that wire to 0.
|
||||
let swap_wire = GMiMCGate::<F, GMIMC_ROUNDS>::WIRE_SWAP;
|
||||
let swap_wire = Target::Wire(Wire { gate, input: swap_wire });
|
||||
self.route(zero, swap_wire);
|
||||
|
||||
// The old accumulator wire doesn't matter, since we won't read the new accumulator wire.
|
||||
// We do have to set it to something though, so we'll arbitrary pick 0.
|
||||
let old_acc_wire = GMiMCGate::<F, GMIMC_ROUNDS>::WIRE_INDEX_ACCUMULATOR_OLD;
|
||||
let old_acc_wire = Target::Wire(Wire { gate, input: old_acc_wire });
|
||||
self.route(zero, old_acc_wire);
|
||||
|
||||
// Route input wires.
|
||||
for i in 0..12 {
|
||||
let in_wire = GMiMCGate::<F, GMIMC_ROUNDS>::wire_output(i);
|
||||
let in_wire = GMiMCGate::<F, GMIMC_ROUNDS>::wire_input(i);
|
||||
let in_wire = Target::Wire(Wire { gate, input: in_wire });
|
||||
self.route(inputs[i], in_wire);
|
||||
}
|
||||
|
||||
// Add a NoopGate just to receive the outputs.
|
||||
let next_gate = self.add_gate_no_constants(NoopGate::get());
|
||||
|
||||
// Collect output wires.
|
||||
(0..12)
|
||||
.map(|i| Target::Wire(
|
||||
Wire { gate: next_gate, input: GMiMCGate::<F, GMIMC_ROUNDS>::wire_output(i) }))
|
||||
Wire { gate, input: GMiMCGate::<F, GMIMC_ROUNDS>::wire_output(i) }))
|
||||
.collect::<Vec<_>>()
|
||||
.try_into()
|
||||
.unwrap()
|
||||
|
||||
@ -1,39 +0,0 @@
|
||||
use crate::circuit_builder::CircuitBuilder;
|
||||
use crate::field::field::Field;
|
||||
use crate::proof::{Hash, HashTarget};
|
||||
use crate::target::Target;
|
||||
|
||||
pub struct MerkleProof<F: Field> {
|
||||
/// The Merkle digest of each sibling subtree, staying from the bottommost layer.
|
||||
pub siblings: Vec<Hash<F>>,
|
||||
}
|
||||
|
||||
pub struct MerkleProofTarget {
|
||||
/// The Merkle digest of each sibling subtree, staying from the bottommost layer.
|
||||
pub siblings: Vec<HashTarget>,
|
||||
}
|
||||
|
||||
/// Verifies that the given leaf data is present at the given index in the Merkle tree with the
|
||||
/// given root.
|
||||
pub(crate) fn verify_merkle_proof<F: Field>(
|
||||
leaf_data: Vec<F>,
|
||||
leaf_index: usize,
|
||||
merkle_root: Hash<F>,
|
||||
proof: MerkleProof<F>,
|
||||
) {
|
||||
todo!()
|
||||
}
|
||||
|
||||
impl<F: Field> CircuitBuilder<F> {
|
||||
/// Verifies that the given leaf data is present at the given index in the Merkle tree with the
|
||||
/// given root.
|
||||
pub(crate) fn verify_merkle_proof(
|
||||
&mut self,
|
||||
leaf_data: Vec<Target>,
|
||||
leaf_index: Target,
|
||||
merkle_root: HashTarget,
|
||||
proof: MerkleProofTarget,
|
||||
) {
|
||||
todo!()
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,3 @@
|
||||
pub(crate) mod arithmetic;
|
||||
pub(crate) mod hash;
|
||||
pub(crate) mod merkle_proofs;
|
||||
pub mod arithmetic;
|
||||
pub mod hash;
|
||||
pub(crate) mod split_join;
|
||||
|
||||
@ -3,22 +3,28 @@ use crate::generator::{SimpleGenerator, WitnessGenerator};
|
||||
use crate::target::Target;
|
||||
use crate::wire::Wire;
|
||||
use crate::witness::PartialWitness;
|
||||
use crate::circuit_builder::CircuitBuilder;
|
||||
|
||||
// /// Constraints for a little-endian split.
|
||||
// pub fn split_le_constraints<F: Field>(
|
||||
// integer: ConstraintPolynomial<F>,
|
||||
// bits: &[ConstraintPolynomial<F>],
|
||||
// ) -> Vec<ConstraintPolynomial<F>> {
|
||||
// let weighted_sum = bits.iter()
|
||||
// .fold(ConstraintPolynomial::zero(), |acc, b| acc.double() + b);
|
||||
// bits.iter()
|
||||
// .rev()
|
||||
// .map(|b| b * (b - 1))
|
||||
// .chain(iter::once(weighted_sum - integer))
|
||||
// .collect()
|
||||
// }
|
||||
impl<F: Field> CircuitBuilder<F> {
|
||||
/// Split the given integer into a list of virtual advice targets, where each one represents a
|
||||
/// bit of the integer, with little-endian ordering.
|
||||
///
|
||||
/// Note that this only handles witness generation; it does not enforce that the decomposition
|
||||
/// is correct. The output should be treated as a "purported" decomposition which must be
|
||||
/// enforced elsewhere.
|
||||
pub(crate) fn split_le_virtual(
|
||||
&mut self,
|
||||
integer: Target,
|
||||
num_bits: usize,
|
||||
) -> Vec<Target> {
|
||||
let bit_targets = self.add_virtual_advice_targets(num_bits);
|
||||
self.add_generator(SplitGenerator { integer, bits: bit_targets.clone() });
|
||||
bit_targets
|
||||
}
|
||||
}
|
||||
|
||||
/// Generator for a little-endian split.
|
||||
#[must_use]
|
||||
pub fn split_le_generator<F: Field>(
|
||||
integer: Target,
|
||||
bits: Vec<Target>,
|
||||
@ -27,6 +33,7 @@ pub fn split_le_generator<F: Field>(
|
||||
}
|
||||
|
||||
/// Generator for a little-endian split.
|
||||
#[must_use]
|
||||
pub fn split_le_generator_local_wires<F: Field>(
|
||||
gate: usize,
|
||||
integer_input_index: usize,
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::circuit_builder::CircuitBuilder;
|
||||
use crate::vars::{EvaluationTargets, EvaluationVars};
|
||||
use crate::field::field::Field;
|
||||
use crate::gates::gate::{Gate, GateRef};
|
||||
use crate::generator::{SimpleGenerator, WitnessGenerator};
|
||||
use crate::gmimc::gmimc_automatic_constants;
|
||||
use crate::target::Target;
|
||||
use crate::vars::{EvaluationTargets, EvaluationVars};
|
||||
use crate::wire::Wire;
|
||||
use crate::witness::PartialWitness;
|
||||
|
||||
@ -15,6 +15,11 @@ const W: usize = 12;
|
||||
|
||||
/// Evaluates a full GMiMC permutation with 12 state elements, and writes the output to the next
|
||||
/// gate's first `width` wires (which could be the input of another `GMiMCGate`).
|
||||
///
|
||||
/// This also has some extra features to make it suitable for efficiently verifying Merkle proofs.
|
||||
/// It has a flag which can be used to swap the first four inputs with the next four, for ordering
|
||||
/// sibling digests. It also has an accumulator that computes the weighted sum of these flags, for
|
||||
/// computing the index of the leaf based on these swap bits.
|
||||
#[derive(Debug)]
|
||||
pub struct GMiMCGate<F: Field, const R: usize> {
|
||||
constants: Arc<[F; R]>,
|
||||
@ -31,24 +36,27 @@ impl<F: Field, const R: usize> GMiMCGate<F, R> {
|
||||
Self::with_constants(constants)
|
||||
}
|
||||
|
||||
/// If this is set to 1, the first four inputs will be swapped with the next four inputs. This
|
||||
/// is useful for ordering hashes in Merkle proofs. Otherwise, this should be set to 0.
|
||||
pub const WIRE_SWITCH: usize = W;
|
||||
|
||||
/// The wire index for the i'th input to the permutation.
|
||||
/// The wire index for the `i`th input to the permutation.
|
||||
pub fn wire_input(i: usize) -> usize {
|
||||
i
|
||||
}
|
||||
|
||||
/// The wire index for the i'th output to the permutation.
|
||||
/// Note that outputs are written to the next gate's wires.
|
||||
/// The wire index for the `i`th output to the permutation.
|
||||
pub fn wire_output(i: usize) -> usize {
|
||||
i
|
||||
W + i
|
||||
}
|
||||
|
||||
/// Used to incrementally compute the index of the leaf based on a series of swap bits.
|
||||
pub const WIRE_INDEX_ACCUMULATOR_OLD: usize = 2 * W;
|
||||
pub const WIRE_INDEX_ACCUMULATOR_NEW: usize = 2 * W + 1;
|
||||
|
||||
/// If this is set to 1, the first four inputs will be swapped with the next four inputs. This
|
||||
/// is useful for ordering hashes in Merkle proofs. Otherwise, this should be set to 0.
|
||||
pub const WIRE_SWAP: usize = 2 * W + 2;
|
||||
|
||||
/// A wire which stores the input to the `i`th cubing.
|
||||
fn wire_cubing_input(i: usize) -> usize {
|
||||
W + 1 + i
|
||||
2 * W + 3 + i
|
||||
}
|
||||
}
|
||||
|
||||
@ -61,26 +69,34 @@ impl<F: Field, const R: usize> Gate<F> for GMiMCGate<F, R> {
|
||||
fn eval_unfiltered(&self, vars: EvaluationVars<F>) -> Vec<F> {
|
||||
let mut constraints = Vec::with_capacity(W + R);
|
||||
|
||||
// Value that is implicitly added to each element.
|
||||
// See https://affine.group/2020/02/starkware-challenge
|
||||
let mut addition_buffer = F::ZERO;
|
||||
// Assert that `swap` is binary.
|
||||
let swap = vars.local_wires[Self::WIRE_SWAP];
|
||||
constraints.push(swap * (swap - F::ONE));
|
||||
|
||||
let old_index_acc = vars.local_wires[Self::WIRE_INDEX_ACCUMULATOR_OLD];
|
||||
let new_index_acc = vars.local_wires[Self::WIRE_INDEX_ACCUMULATOR_NEW];
|
||||
let computed_new_index_acc = F::TWO * old_index_acc + swap;
|
||||
constraints.push(computed_new_index_acc - new_index_acc);
|
||||
|
||||
let switch = vars.local_wires[Self::WIRE_SWITCH];
|
||||
let mut state = Vec::with_capacity(12);
|
||||
for i in 0..4 {
|
||||
let a = vars.local_wires[i];
|
||||
let b = vars.local_wires[i + 4];
|
||||
state.push(a + switch * (b - a));
|
||||
state.push(a + swap * (b - a));
|
||||
}
|
||||
for i in 0..4 {
|
||||
let a = vars.local_wires[i + 4];
|
||||
let b = vars.local_wires[i];
|
||||
state.push(a + switch * (b - a));
|
||||
state.push(a + swap * (b - a));
|
||||
}
|
||||
for i in 8..12 {
|
||||
state.push(vars.local_wires[i]);
|
||||
}
|
||||
|
||||
// Value that is implicitly added to each element.
|
||||
// See https://affine.group/2020/02/starkware-challenge
|
||||
let mut addition_buffer = F::ZERO;
|
||||
|
||||
for r in 0..R {
|
||||
let active = r % W;
|
||||
let cubing_input = state[active] + addition_buffer + self.constants[r];
|
||||
@ -93,7 +109,7 @@ impl<F: Field, const R: usize> Gate<F> for GMiMCGate<F, R> {
|
||||
|
||||
for i in 0..W {
|
||||
state[i] += addition_buffer;
|
||||
constraints.push(state[i] - vars.next_wires[i]);
|
||||
constraints.push(state[i] - vars.local_wires[Self::wire_output(i)]);
|
||||
}
|
||||
|
||||
constraints
|
||||
@ -133,7 +149,7 @@ impl<F: Field, const R: usize> Gate<F> for GMiMCGate<F, R> {
|
||||
}
|
||||
|
||||
fn num_constraints(&self) -> usize {
|
||||
R + W
|
||||
R + W + 2
|
||||
}
|
||||
}
|
||||
|
||||
@ -145,11 +161,15 @@ struct GMiMCGenerator<F: Field, const R: usize> {
|
||||
|
||||
impl<F: Field, const R: usize> SimpleGenerator<F> for GMiMCGenerator<F, R> {
|
||||
fn dependencies(&self) -> Vec<Target> {
|
||||
(0..W)
|
||||
.map(|i| Target::Wire(Wire {
|
||||
gate: self.gate_index,
|
||||
input: GMiMCGate::<F, R>::wire_input(i),
|
||||
}))
|
||||
let mut dep_input_indices = Vec::with_capacity(W + 2);
|
||||
for i in 0..W {
|
||||
dep_input_indices.push(GMiMCGate::<F, R>::wire_input(i));
|
||||
}
|
||||
dep_input_indices.push(GMiMCGate::<F, R>::WIRE_SWAP);
|
||||
dep_input_indices.push(GMiMCGate::<F, R>::WIRE_INDEX_ACCUMULATOR_OLD);
|
||||
|
||||
dep_input_indices.into_iter()
|
||||
.map(|input| Target::Wire(Wire { gate: self.gate_index, input }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@ -163,17 +183,30 @@ impl<F: Field, const R: usize> SimpleGenerator<F> for GMiMCGenerator<F, R> {
|
||||
}))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let switch_value = witness.get_wire(Wire {
|
||||
let swap_value = witness.get_wire(Wire {
|
||||
gate: self.gate_index,
|
||||
input: GMiMCGate::<F, R>::WIRE_SWITCH,
|
||||
input: GMiMCGate::<F, R>::WIRE_SWAP,
|
||||
});
|
||||
debug_assert!(switch_value == F::ZERO || switch_value == F::ONE);
|
||||
if switch_value == F::ONE {
|
||||
debug_assert!(swap_value == F::ZERO || swap_value == F::ONE);
|
||||
if swap_value == F::ONE {
|
||||
for i in 0..4 {
|
||||
state.swap(i, 4 + i);
|
||||
}
|
||||
}
|
||||
|
||||
// Update the index accumulator.
|
||||
let old_index_acc_value = witness.get_wire(Wire {
|
||||
gate: self.gate_index,
|
||||
input: GMiMCGate::<F, R>::WIRE_INDEX_ACCUMULATOR_OLD,
|
||||
});
|
||||
let new_index_acc_value = F::TWO * old_index_acc_value + swap_value;
|
||||
result.set_wire(
|
||||
Wire {
|
||||
gate: self.gate_index,
|
||||
input: GMiMCGate::<F, R>::WIRE_INDEX_ACCUMULATOR_NEW,
|
||||
},
|
||||
new_index_acc_value);
|
||||
|
||||
// Value that is implicitly added to each element.
|
||||
// See https://affine.group/2020/02/starkware-challenge
|
||||
let mut addition_buffer = F::ZERO;
|
||||
@ -196,7 +229,7 @@ impl<F: Field, const R: usize> SimpleGenerator<F> for GMiMCGenerator<F, R> {
|
||||
state[i] += addition_buffer;
|
||||
result.set_wire(
|
||||
Wire {
|
||||
gate: self.gate_index + 1,
|
||||
gate: self.gate_index,
|
||||
input: GMiMCGate::<F, R>::wire_output(i),
|
||||
},
|
||||
state[i]);
|
||||
@ -239,7 +272,12 @@ mod tests {
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let mut witness = PartialWitness::new();
|
||||
witness.set_wire(Wire { gate: 0, input: Gate::WIRE_SWITCH }, F::ZERO);
|
||||
witness.set_wire(
|
||||
Wire { gate: 0, input: Gate::WIRE_INDEX_ACCUMULATOR_OLD },
|
||||
F::from_canonical_usize(7));
|
||||
witness.set_wire(
|
||||
Wire { gate: 0, input: Gate::WIRE_SWAP },
|
||||
F::ZERO);
|
||||
for i in 0..W {
|
||||
witness.set_wire(
|
||||
Wire { gate: 0, input: Gate::wire_input(i) },
|
||||
@ -255,8 +293,12 @@ mod tests {
|
||||
|
||||
for i in 0..W {
|
||||
let out = witness.get_wire(
|
||||
Wire { gate: 1, input: Gate::wire_output(i) });
|
||||
Wire { gate: 0, input: Gate::wire_output(i) });
|
||||
assert_eq!(out, expected_outputs[i]);
|
||||
}
|
||||
|
||||
let acc_new = witness.get_wire(
|
||||
Wire { gate: 0, input: Gate::WIRE_INDEX_ACCUMULATOR_NEW });
|
||||
assert_eq!(acc_new, F::from_canonical_usize(7 * 2));
|
||||
}
|
||||
}
|
||||
|
||||
73
src/hash.rs
73
src/hash.rs
@ -1,12 +1,12 @@
|
||||
//! Concrete instantiation of a hash function.
|
||||
|
||||
use std::convert::TryInto;
|
||||
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::circuit_builder::CircuitBuilder;
|
||||
use crate::field::field::Field;
|
||||
use crate::gmimc::gmimc_permute_array;
|
||||
use crate::proof::Hash;
|
||||
use crate::proof::{Hash, HashTarget};
|
||||
use crate::target::Target;
|
||||
use crate::util::reverse_index_bits_in_place;
|
||||
|
||||
pub(crate) const SPONGE_RATE: usize = 8;
|
||||
@ -25,7 +25,7 @@ const ELEMS_PER_CHUNK: usize = 1 << 8;
|
||||
|
||||
/// Hash the vector if necessary to reduce its length to ~256 bits. If it already fits, this is a
|
||||
/// no-op.
|
||||
pub fn hash_or_noop<F: Field>(mut inputs: Vec<F>) -> Hash<F> {
|
||||
pub fn hash_or_noop<F: Field>(inputs: Vec<F>) -> Hash<F> {
|
||||
if inputs.len() <= 4 {
|
||||
Hash::from_partial(inputs)
|
||||
} else {
|
||||
@ -33,6 +33,64 @@ pub fn hash_or_noop<F: Field>(mut inputs: Vec<F>) -> Hash<F> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: Field> CircuitBuilder<F> {
|
||||
pub fn hash_or_noop(&mut self, inputs: Vec<Target>) -> HashTarget {
|
||||
let zero = self.zero();
|
||||
if inputs.len() <= 4 {
|
||||
HashTarget::from_partial(inputs, zero)
|
||||
} else {
|
||||
self.hash_n_to_hash(inputs, false)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hash_n_to_hash(&mut self, inputs: Vec<Target>, pad: bool) -> HashTarget {
|
||||
HashTarget::from_vec(self.hash_n_to_m(inputs, 4, pad))
|
||||
}
|
||||
|
||||
pub fn hash_n_to_m(
|
||||
&mut self,
|
||||
mut inputs: Vec<Target>,
|
||||
num_outputs: usize,
|
||||
pad: bool,
|
||||
) -> Vec<Target> {
|
||||
let zero = self.zero();
|
||||
let one = self.one();
|
||||
|
||||
if pad {
|
||||
inputs.push(zero);
|
||||
while (inputs.len() + 1) % SPONGE_WIDTH != 0 {
|
||||
inputs.push(one);
|
||||
}
|
||||
inputs.push(zero);
|
||||
}
|
||||
|
||||
let mut state = [zero; SPONGE_WIDTH];
|
||||
|
||||
// Absorb all input chunks.
|
||||
for input_chunk in inputs.chunks(SPONGE_RATE) {
|
||||
// Overwrite the first r elements with the inputs. This differs from a standard sponge,
|
||||
// where we would xor or add in the inputs. This is a well-known variant, though,
|
||||
// sometimes called "overwrite mode".
|
||||
for i in 0..input_chunk.len() {
|
||||
state[i] = input_chunk[i];
|
||||
}
|
||||
state = self.permute(state);
|
||||
}
|
||||
|
||||
// Squeeze until we have the desired number of outputs.
|
||||
let mut outputs = Vec::new();
|
||||
loop {
|
||||
for i in 0..SPONGE_RATE {
|
||||
outputs.push(state[i]);
|
||||
if outputs.len() == num_outputs {
|
||||
return outputs;
|
||||
}
|
||||
}
|
||||
state = self.permute(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-way compression function which takes two ~256 bit inputs and returns a ~256 bit output.
|
||||
pub fn compress<F: Field>(x: Hash<F>, y: Hash<F>) -> Hash<F> {
|
||||
let mut inputs = Vec::with_capacity(8);
|
||||
@ -60,7 +118,7 @@ pub fn hash_n_to_m<F: Field>(mut inputs: Vec<F>, num_outputs: usize, pad: bool)
|
||||
let mut state = [F::ZERO; SPONGE_WIDTH];
|
||||
|
||||
// Absorb all input chunks.
|
||||
for input_chunk in inputs.chunks(SPONGE_WIDTH - 1) {
|
||||
for input_chunk in inputs.chunks(SPONGE_RATE) {
|
||||
for i in 0..input_chunk.len() {
|
||||
state[i] += input_chunk[i];
|
||||
}
|
||||
@ -70,7 +128,7 @@ pub fn hash_n_to_m<F: Field>(mut inputs: Vec<F>, num_outputs: usize, pad: bool)
|
||||
// Squeeze until we have the desired number of outputs.
|
||||
let mut outputs = Vec::new();
|
||||
loop {
|
||||
for i in 0..(SPONGE_WIDTH - 1) {
|
||||
for i in 0..SPONGE_RATE {
|
||||
outputs.push(state[i]);
|
||||
if outputs.len() == num_outputs {
|
||||
return outputs;
|
||||
@ -81,8 +139,7 @@ pub fn hash_n_to_m<F: Field>(mut inputs: Vec<F>, num_outputs: usize, pad: bool)
|
||||
}
|
||||
|
||||
pub fn hash_n_to_hash<F: Field>(inputs: Vec<F>, pad: bool) -> Hash<F> {
|
||||
let elements = hash_n_to_m(inputs, 4, pad).try_into().unwrap();
|
||||
Hash { elements }
|
||||
Hash::from_vec(hash_n_to_m(inputs, 4, pad))
|
||||
}
|
||||
|
||||
pub fn hash_n_to_1<F: Field>(inputs: Vec<F>, pad: bool) -> F {
|
||||
|
||||
@ -8,6 +8,7 @@ pub mod gates;
|
||||
pub mod generator;
|
||||
pub mod gmimc;
|
||||
pub mod hash;
|
||||
pub mod merkle_proofs;
|
||||
pub mod plonk_challenger;
|
||||
pub mod plonk_common;
|
||||
pub mod polynomial;
|
||||
|
||||
100
src/merkle_proofs.rs
Normal file
100
src/merkle_proofs.rs
Normal file
@ -0,0 +1,100 @@
|
||||
use crate::circuit_builder::CircuitBuilder;
|
||||
use crate::field::field::Field;
|
||||
use crate::gates::gmimc::GMiMCGate;
|
||||
use crate::hash::{compress, hash_or_noop};
|
||||
use crate::hash::GMIMC_ROUNDS;
|
||||
use crate::proof::{Hash, HashTarget};
|
||||
use crate::target::Target;
|
||||
use crate::wire::Wire;
|
||||
|
||||
pub struct MerkleProof<F: Field> {
|
||||
/// The Merkle digest of each sibling subtree, staying from the bottommost layer.
|
||||
pub siblings: Vec<Hash<F>>,
|
||||
}
|
||||
|
||||
pub struct MerkleProofTarget {
|
||||
/// The Merkle digest of each sibling subtree, staying from the bottommost layer.
|
||||
pub siblings: Vec<HashTarget>,
|
||||
}
|
||||
|
||||
/// Verifies that the given leaf data is present at the given index in the Merkle tree with the
|
||||
/// given root.
|
||||
pub(crate) fn verify_merkle_proof<F: Field>(
|
||||
leaf_data: Vec<F>,
|
||||
leaf_index: usize,
|
||||
merkle_root: Hash<F>,
|
||||
proof: MerkleProof<F>,
|
||||
) -> bool {
|
||||
let mut current_digest = hash_or_noop(leaf_data);
|
||||
for (i, sibling_digest) in proof.siblings.into_iter().enumerate() {
|
||||
let bit = (leaf_index >> i & 1) == 1;
|
||||
current_digest = if bit {
|
||||
compress(sibling_digest, current_digest)
|
||||
} else {
|
||||
compress(current_digest, sibling_digest)
|
||||
}
|
||||
}
|
||||
current_digest == merkle_root
|
||||
}
|
||||
|
||||
impl<F: Field> CircuitBuilder<F> {
|
||||
/// Verifies that the given leaf data is present at the given index in the Merkle tree with the
|
||||
/// given root.
|
||||
pub(crate) fn verify_merkle_proof(
|
||||
&mut self,
|
||||
leaf_data: Vec<Target>,
|
||||
leaf_index: Target,
|
||||
merkle_root: HashTarget,
|
||||
proof: MerkleProofTarget,
|
||||
) {
|
||||
let zero = self.zero();
|
||||
let height = proof.siblings.len();
|
||||
let purported_index_bits = self.split_le_virtual(leaf_index, height);
|
||||
|
||||
let mut state: HashTarget = self.hash_or_noop(leaf_data);
|
||||
let mut acc_leaf_index = zero;
|
||||
|
||||
for (bit, sibling) in purported_index_bits.into_iter().zip(proof.siblings) {
|
||||
let gate = self.add_gate_no_constants(
|
||||
GMiMCGate::<F, GMIMC_ROUNDS>::with_automatic_constants());
|
||||
|
||||
let swap_wire = GMiMCGate::<F, GMIMC_ROUNDS>::WIRE_SWAP;
|
||||
let swap_wire = Target::Wire(Wire { gate, input: swap_wire });
|
||||
self.generate_copy(bit, swap_wire);
|
||||
|
||||
let old_acc_wire = GMiMCGate::<F, GMIMC_ROUNDS>::WIRE_INDEX_ACCUMULATOR_OLD;
|
||||
let old_acc_wire = Target::Wire(Wire { gate, input: old_acc_wire });
|
||||
self.route(acc_leaf_index, old_acc_wire);
|
||||
|
||||
let new_acc_wire = GMiMCGate::<F, GMIMC_ROUNDS>::WIRE_INDEX_ACCUMULATOR_NEW;
|
||||
let new_acc_wire = Target::Wire(Wire { gate, input: new_acc_wire });
|
||||
acc_leaf_index = new_acc_wire;
|
||||
|
||||
let input_wires = (0..12)
|
||||
.map(|i| Target::Wire(
|
||||
Wire { gate, input: GMiMCGate::<F, GMIMC_ROUNDS>::wire_input(i) }))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for i in 0..4 {
|
||||
self.route(state.elements[i], input_wires[i]);
|
||||
self.route(sibling.elements[i], input_wires[4 + i]);
|
||||
self.route(zero, input_wires[8 + i]);
|
||||
}
|
||||
|
||||
state = HashTarget::from_vec((0..4)
|
||||
.map(|i| Target::Wire(
|
||||
Wire { gate, input: GMiMCGate::<F, GMIMC_ROUNDS>::wire_output(i) }))
|
||||
.collect())
|
||||
}
|
||||
|
||||
self.assert_equal(acc_leaf_index, leaf_index);
|
||||
|
||||
self.assert_hashes_equal(state, merkle_root)
|
||||
}
|
||||
|
||||
pub(crate) fn assert_hashes_equal(&mut self, x: HashTarget, y: HashTarget) {
|
||||
for i in 0..4 {
|
||||
self.assert_equal(x.elements[i], y.elements[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -79,9 +79,11 @@ impl<F: Field> Challenger<F> {
|
||||
/// Absorb any buffered inputs. After calling this, the input buffer will be empty.
|
||||
fn absorb_buffered_inputs(&mut self) {
|
||||
for input_chunk in self.input_buffer.chunks(SPONGE_RATE) {
|
||||
// Add the inputs to our sponge state.
|
||||
// Overwrite the first r elements with the inputs. This differs from a standard sponge,
|
||||
// where we would xor or add in the inputs. This is a well-known variant, though,
|
||||
// sometimes called "overwrite mode".
|
||||
for (i, &input) in input_chunk.iter().enumerate() {
|
||||
self.sponge_state[i] = self.sponge_state[i] + input;
|
||||
self.sponge_state[i] = input;
|
||||
}
|
||||
|
||||
// Apply the permutation.
|
||||
@ -177,9 +179,11 @@ impl RecursiveChallenger {
|
||||
builder: &mut CircuitBuilder<F>,
|
||||
) {
|
||||
for input_chunk in self.input_buffer.chunks(SPONGE_RATE) {
|
||||
// Add the inputs to our sponge state.
|
||||
// Overwrite the first r elements with the inputs. This differs from a standard sponge,
|
||||
// where we would xor or add in the inputs. This is a well-known variant, though,
|
||||
// sometimes called "overwrite mode".
|
||||
for (i, &input) in input_chunk.iter().enumerate() {
|
||||
self.sponge_state[i] = builder.add(self.sponge_state[i], input);
|
||||
self.sponge_state[i] = input;
|
||||
}
|
||||
|
||||
// Apply the permutation.
|
||||
@ -228,7 +232,7 @@ mod tests {
|
||||
|
||||
let config = CircuitConfig {
|
||||
num_wires: 114,
|
||||
num_routed_wires: 13,
|
||||
num_routed_wires: 27,
|
||||
..CircuitConfig::default()
|
||||
};
|
||||
let mut builder = CircuitBuilder::<F>::new(config);
|
||||
|
||||
@ -18,6 +18,8 @@ pub fn evaluate_gate_constraints<F: Field>(
|
||||
for gate in gates {
|
||||
let gate_constraints = gate.0.eval_filtered(vars);
|
||||
for (i, c) in gate_constraints.into_iter().enumerate() {
|
||||
debug_assert!(i < num_gate_constraints,
|
||||
"num_constraints() gave too low of a number");
|
||||
constraints[i] += c;
|
||||
}
|
||||
}
|
||||
|
||||
28
src/proof.rs
28
src/proof.rs
@ -1,14 +1,20 @@
|
||||
use crate::field::field::Field;
|
||||
use crate::target::Target;
|
||||
use crate::gadgets::merkle_proofs::{MerkleProofTarget, MerkleProof};
|
||||
use crate::merkle_proofs::{MerkleProofTarget, MerkleProof};
|
||||
use std::convert::TryInto;
|
||||
|
||||
/// Represents a ~256 bit hash output.
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
||||
pub struct Hash<F: Field> {
|
||||
pub(crate) elements: [F; 4],
|
||||
}
|
||||
|
||||
impl<F: Field> Hash<F> {
|
||||
pub(crate) fn from_vec(elements: Vec<F>) -> Self {
|
||||
debug_assert!(elements.len() == 4);
|
||||
Self { elements: elements.try_into().unwrap() }
|
||||
}
|
||||
|
||||
pub(crate) fn from_partial(mut elements: Vec<F>) -> Self {
|
||||
debug_assert!(elements.len() <= 4);
|
||||
while elements.len() < 4 {
|
||||
@ -18,8 +24,24 @@ impl<F: Field> Hash<F> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a ~256 bit hash output.
|
||||
pub struct HashTarget {
|
||||
pub(crate) elements: Vec<Target>,
|
||||
pub(crate) elements: [Target; 4],
|
||||
}
|
||||
|
||||
impl HashTarget {
|
||||
pub(crate) fn from_vec(elements: Vec<Target>) -> Self {
|
||||
debug_assert!(elements.len() == 4);
|
||||
Self { elements: elements.try_into().unwrap() }
|
||||
}
|
||||
|
||||
pub(crate) fn from_partial(mut elements: Vec<Target>, zero: Target) -> Self {
|
||||
debug_assert!(elements.len() <= 4);
|
||||
while elements.len() < 4 {
|
||||
elements.push(zero);
|
||||
}
|
||||
Self { elements: [elements[0], elements[1], elements[2], elements[3]] }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Proof<F: Field> {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user