Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

partially fixing errors in zk memory #47

Merged
merged 8 commits into from
Nov 22, 2023
3 changes: 1 addition & 2 deletions zkmemory/examples/256bits-machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use rbtree::RBTree;
use std::{marker::PhantomData, println};
use zkmemory::{
base::{Base, B256},
commitment::kzg::KZGMemoryCommitment,
config::{AllocatedSection, Config, ConfigArgs, DefaultConfig},
error::Error,
impl_register_machine, impl_stack_machine, impl_state_machine,
Expand Down Expand Up @@ -325,7 +324,7 @@ impl_state_machine!(StateMachine);

fn main() {
// Define the desired machine configuration
let mut machine = StateMachine::<B256, B256, 32, 32>::new(DefaultConfig::default());
let mut machine = StateMachine::<B256, B256, 32, 32>::new(DefaultConfig::default_config());

// Show the section map
machine.show_sections_maps();
Expand Down
48 changes: 24 additions & 24 deletions zkmemory/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,27 +142,27 @@ macro_rules! new_base {
}
}

impl Into<i32> for Uint<U256> {
fn into(self) -> i32 {
self.0.as_i32()
impl From<Uint<U256>> for i32 {
fn from(value: Uint<U256>) -> Self {
value.0.as_i32()
}
}

impl Into<usize> for Uint<U256> {
fn into(self) -> usize {
self.0.as_usize()
impl From<Uint<U256>> for usize {
fn from(value: Uint<U256>) -> Self {
value.0.as_usize()
}
}

impl Into<u64> for Uint<U256> {
fn into(self) -> u64 {
self.0.as_u64()
impl From<Uint<U256>> for u64 {
fn from(value: Uint<U256>) -> Self {
value.0.as_u64()
}
}

impl Into<[u8; $byte_size]> for Uint<U256> {
fn into(self) -> [u8; $byte_size] {
self.0.to_be_bytes()
impl From<Uint<U256>> for [u8; $byte_size] {
fn from(value: Uint<U256>) -> Self {
value.0.to_be_bytes()
}
}

Expand Down Expand Up @@ -214,27 +214,27 @@ macro_rules! new_base {
}
}

impl Into<i32> for Uint<$primitive> {
fn into(self) -> i32 {
self.0 as i32
impl From<Uint<$primitive>> for i32 {
fn from(value: Uint<$primitive>) -> Self {
value.0 as i32
}
}

impl Into<usize> for Uint<$primitive> {
fn into(self) -> usize {
self.0 as usize
impl From<Uint<$primitive>> for usize {
fn from(value: Uint<$primitive>) -> Self {
value.0 as usize
}
}

impl Into<u64> for Uint<$primitive> {
fn into(self) -> u64 {
self.0 as u64
impl From<Uint<$primitive>> for u64 {
fn from(value: Uint<$primitive>) -> Self {
value.0 as u64
}
}

impl Into<[u8; $byte_size]> for Uint<$primitive> {
fn into(self) -> [u8; $byte_size] {
self.0.to_be_bytes()
impl From<Uint<$primitive>> for [u8; $byte_size] {
fn from(value: Uint<$primitive>) -> Self {
value.0.to_be_bytes()
}
}

Expand Down
72 changes: 29 additions & 43 deletions zkmemory/src/commitment/kzg.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
extern crate std;
use core::marker::PhantomData;
use ff::{Field, PrimeField};
use ff::{Field, PrimeField, WithSmallOrderMulGroup};
use group::Curve;
use rand_core::OsRng;
use std::vec::Vec;

use crate::{base::Base, machine::MemoryInstruction, machine::TraceRecord};
use halo2_proofs::halo2curves::bn256::{Bn256, Fr, G1Affine};
Expand Down Expand Up @@ -39,12 +40,21 @@ where
_marker2: PhantomData<V>,
}

impl<K, V, const S: usize, const T: usize> KZGMemoryCommitment<K, V, S, T>
impl<K, V, const S: usize, const T: usize> Default for KZGMemoryCommitment<K, V, S, T>
where
K: Base<S>,
V: Base<T>,
{
fn default() -> Self {
Self::new()
}
}

impl<K, V, const S: usize, const T: usize> KZGMemoryCommitment<K, V, S, T>
where
K: Base<S>,
V: Base<T>,
{
/// Initialize KZG parameters
/// K = 3 since we need the poly degree to be 2^3 = 8
pub fn new() -> Self {
Expand All @@ -56,7 +66,6 @@ where
_marker2: PhantomData::<V>,
}
}

/// Commit a trace record in an execution trace
pub fn commit(&mut self, trace: TraceRecord<K, V, S, T>) -> G1Affine {
// Convert trace record into polynomial
Expand All @@ -66,7 +75,7 @@ where
let commitment = self.kzg_params.commit(&poly, alpha);
commitment.to_affine()
}

// Convert a trace record to 8 field elements
// The last 3 elements will be ZERO
fn trace_to_field(&self, trace: TraceRecord<K, V, S, T>) -> [Fr; 8] {
Expand Down Expand Up @@ -95,7 +104,7 @@ where
],
}
}

// Convert the trace record into a polynomial
fn poly_from_trace(&self, trace: TraceRecord<K, V, S, T>) -> Polynomial<Fr, Coeff> {
let evals = self.trace_to_field(trace);
Expand All @@ -111,9 +120,9 @@ where
// We use successive powers of primitive roots as points
// We use elements in trace record to be the evals
// 3 last evals should be ZERO
for i in 1..8 as usize {
for (_i, point) in (1..=8).zip(points_arr.iter_mut().skip(1)) {
current_point *= Fr::MULTIPLICATIVE_GENERATOR;
points_arr[i] = current_point;
*point = current_point;
}

// Use Lagrange interpolation
Expand All @@ -127,10 +136,9 @@ where
// This is made compatible with the Fr endianess
fn be_bytes_to_field(&self, bytes: &mut [u8]) -> Fr {
bytes.reverse();
let b = bytes.as_ref();
let inner = [0, 8, 16, 24].map(|i| u64::from_le_bytes(b[i..i + 8].try_into().unwrap()));
let result = Fr::from_raw(inner);
result
//let b = bytes.as_ref();
let inner = [0, 8, 16, 24].map(|i| u64::from_le_bytes(bytes[i..i + 8].try_into().unwrap()));
Fr::from_raw(inner)
}

//WARNING: the functions below have not been tested yet
Expand Down Expand Up @@ -186,35 +194,16 @@ where
blind,
};
queries.push(temp);
}

#[cfg(test)]
mod test {

use super::*;
use crate::{base::B256, machine::AbstractTraceRecord};
use halo2_proofs::arithmetic::eval_polynomial;

#[test]
fn test_conversion_fr() {
let kzg_scheme = KZGMemoryCommitment::<B256, B256, 32, 32>::new();

// Create a 32-bytes repr of Base 256
let mut chunk = [0u8; 32];
for i in 0..32 {
chunk[i] = i as u8;
}

// Use my method to convert to Fr
let fr = kzg_scheme.be_bytes_to_field(chunk.as_mut_slice());

// Use Fr's method to convert back to bytes
let chunk_fr: [u8; 32] = fr.try_into().unwrap();
let prover = P::new(params);
prover
.create_proof(&mut OsRng, &mut transcript, queries)
.unwrap();

assert_eq!(chunk_fr, chunk);
transcript.finalize()
}


//Verify KZG openings
// Used to create a friendly KZG API verification function
fn verify_shplonk<
Expand Down Expand Up @@ -287,12 +276,11 @@ mod test {
//borrowed from Thang's commit function
let poly = self.poly_from_trace(trace);
// create the point list of opening
let mut points_list = Vec::new();
points_list.extend([Fr::ONE; 5]);
let mut points_list = Vec::from([Fr::ONE; 5]);
let mut current_point = Fr::ONE;
for i in 1..5 as usize {
for (_i, point) in (1..=5).zip(points_list.iter_mut().skip(1)) {
current_point *= Fr::MULTIPLICATIVE_GENERATOR;
points_list[i] = current_point;
*point = current_point;
}
// initialize the vector of commitments for the create_proof_for_shplonk function
let mut commitment_list = Vec::new();
Expand Down Expand Up @@ -329,9 +317,9 @@ mod test {
let mut points_list = Vec::new();
points_list.extend([Fr::ONE; 5]);
let mut current_point = Fr::ONE;
for i in 1..5 as usize {
for (_i, point) in (1..=5).zip(points_list.iter_mut().skip(1)) {
current_point *= Fr::MULTIPLICATIVE_GENERATOR;
points_list[i] = current_point;
*point = current_point;
}
// finally, verify the opening
self.verify_shplonk::<
Expand Down Expand Up @@ -393,7 +381,6 @@ mod test {
}
}


#[test]
fn test_correct_memory_opening() {
let mut kzg_scheme = KZGMemoryCommitment::<B256, B256, 32, 32>::new();
Expand Down Expand Up @@ -443,5 +430,4 @@ mod test {
let verify = kzg_scheme.verify_trace_element(trace, commit, false_proof);
assert_eq!(verify, false);
}

}
4 changes: 2 additions & 2 deletions zkmemory/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub struct DefaultConfig;

impl DefaultConfig {
/// Create a default config
pub fn default<const S: usize, T: Base<S>>() -> ConfigArgs<T> {
pub fn default_config<const S: usize, T: Base<S>>() -> ConfigArgs<T> {
ConfigArgs {
head_layout: true,
stack_depth: T::from(1024),
Expand Down Expand Up @@ -104,7 +104,7 @@ where
let memory_hi = T::MAX - length;

Self {
word_size: word_size,
word_size,
stack_depth: args.stack_depth,
buffer_size: args.buffer_size,
stack: AllocatedSection(stack_lo, stack_hi),
Expand Down
8 changes: 4 additions & 4 deletions zkmemory/src/machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ where
/// Read from memory (only read one whole cell)
fn dummy_read(&mut self, address: K) -> V {
match self.context().memory().get(&address) {
Some(r) => r.clone(),
Some(r) => *r,
None => V::zero(),
}
}
Expand Down Expand Up @@ -376,7 +376,7 @@ where

match self.write(address, value) {
Ok(v) => Ok((stack_depth, v)),
Err(e) => return Err(e),
Err(e) => Err(e),
}
}

Expand All @@ -394,7 +394,7 @@ where

match self.read(address) {
Ok(v) => Ok((stack_depth, v)),
Err(e) => return Err(e),
Err(e) => Err(e),
}
}
}
Expand Down Expand Up @@ -504,7 +504,7 @@ where
Some(core::cmp::Ordering::Equal) => {
panic!("Time log never been equal")
}
ord => return ord,
ord => ord,
}
}
}
Expand Down
Loading