Skip to content

Commit

Permalink
Merge branch 'main' of github.com:manojkgorle/brainfuckvm
Browse files Browse the repository at this point in the history
  • Loading branch information
soumyathakur44 committed Dec 5, 2024
2 parents 2d7e857 + d9a9df5 commit 8a131b6
Show file tree
Hide file tree
Showing 15 changed files with 534 additions and 229 deletions.
63 changes: 63 additions & 0 deletions src/channel/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
use alloy::{hex::ToHexExt, primitives::U256};

use crate::fields::{Field, FieldElement};
pub struct Channel {
pub state: String,
// proof contains all the messages that are exchanged between prover and verifier.
pub proof: Vec<Vec<u8>>,
// compressed proof contains only the messages that are sent from prover to verifier.
pub compressed_proof: Vec<Vec<u8>>,
}

impl Channel {
pub fn new() -> Channel {
Channel {
state: String::new(),
proof: Vec::new(),
compressed_proof: Vec::new(),
}
}

pub fn send(&mut self, s: Vec<u8>) {
log::debug!("sending to channel");
let data_for_digest = format!("{}:{:?}", self.state, s.clone());
self.state = sha256::digest(data_for_digest);
self.proof.push(s.clone());
self.compressed_proof.push(s);
}

pub fn receive_random_field_element(&mut self, field: Field) -> FieldElement {
let received_int = self.receive_random_int(0, (field.0 - 1) as u64, true);
log::debug!("received_int: {}", received_int);
FieldElement::new(received_int as u128, field)
}

pub fn receive_random_int(&mut self, min: u64, max: u64, show_in_proof: bool) -> u64 {
// convert state to hexadecimal number
let num = (U256::from(min) + U256::from_str_radix(&self.state, 16).unwrap())
% U256::from(max - min + 1);
let t_num = min + num.into_limbs()[0];
let state = self.state.clone() + &t_num.to_be_bytes().to_vec().encode_hex();
self.state = sha256::digest(state);
if show_in_proof {
self.proof.push(num.into_limbs()[0].to_be_bytes().to_vec());
}
min + num.into_limbs()[0]
}

pub fn proof_size(&self) -> usize {
let mut size = 0;
for proof in &self.proof {
size += proof.len();
}
size
}

pub fn compressed_proof_size(&self) -> usize {
let mut size = 0;
for proof in &self.compressed_proof {
size += proof.len();
}
size
}
}
46 changes: 23 additions & 23 deletions src/evaluation_argument/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,19 @@ impl EvaluationArgument{
Self {field, challenge_index, terminal_index, symbols}
}

fn compute_terminal(&self, challenges: &Vec<FieldElement>)-> FieldElement{
fn compute_terminal(&self, challenges: &[FieldElement])-> FieldElement{
let field = self.field;
let iota = challenges[self.challenge_index];
let mut acc = FieldElement::zero(field);

for i in 0..self.symbols.len(){
acc = iota.clone()*acc + FieldElement::new(self.symbols[i], field);
acc = iota*acc + FieldElement::new(self.symbols[i], field);
}
acc
}

fn select_terminal(&self, terminals: &Vec<FieldElement>)->FieldElement{
terminals[self.terminal_index].clone()
fn select_terminal(&self, terminals: &[FieldElement])->FieldElement{
terminals[self.terminal_index]
}
}

Expand All @@ -48,17 +48,17 @@ impl ProgramEvaluationArgument{
program,
}
}
``
fn compute_terminal(&self, challenges: &Vec<FieldElement>)->FieldElement{

fn compute_terminal(&self, challenges: &[FieldElement])->FieldElement{
let field = self.field;
let trimmed_challenges: Vec<FieldElement> = self
.challenge_indices
.iter()
.map(|&i| challenges[i].clone())
.map(|&i| challenges[i])
.collect();
let [a, b, c, eta]: [FieldElement; 4] = trimmed_challenges.try_into().unwrap();
let mut running_sum = FieldElement::zero(field);
let mut previous_address = -1 as isize;
let mut previous_address = -1_isize;

let padded_program: Vec<FieldElement> = self
.program
Expand All @@ -69,35 +69,35 @@ impl ProgramEvaluationArgument{
//@todo ci goes till last element of program in last step of running sum, ni is zero for the last step

for i in 0..padded_program.len()-1 {
let address = i as usize;
let current_instruction = padded_program[i].clone();
let next_instruction = padded_program[i + 1].clone();
let address = i;
let current_instruction = padded_program[i];
let next_instruction = padded_program[i + 1];

if previous_address != address as isize {
running_sum = running_sum * eta.clone()
+ a.clone() * FieldElement::new(address.clone() as u128, field)
+ b.clone() * current_instruction
+ c.clone() * next_instruction;
running_sum = running_sum * eta
+ a * FieldElement::new(address as u128, field)
+ b * current_instruction
+ c * next_instruction;
println!("{}:{}:{}:{}:{}", i, address, current_instruction.0, next_instruction.0, running_sum.0 );
}
previous_address = address as isize;
}

let index = padded_program.len() - 1;
let address = FieldElement::new(index as u128, field);
let current_instruction = padded_program[index].clone();
let current_instruction = padded_program[index];
let next_instruction = FieldElement::zero(field);

running_sum = running_sum * eta.clone()
+ a.clone() * address
+ b.clone() * current_instruction
+ c.clone() * next_instruction;
running_sum = running_sum * eta
+ a * address
+ b * current_instruction
+ c * next_instruction;
println!("{}:{}:{}:{}:{}", index, address.0, current_instruction.0, next_instruction.0, running_sum.0 );
running_sum
}

fn select_terminal(&self, terminals: &[FieldElement]) -> FieldElement {
terminals[self.terminal_index].clone()
terminals[self.terminal_index]
}
}

Expand Down Expand Up @@ -128,7 +128,7 @@ mod tests {
];

// Instantiate EvaluationArgument
let eval_arg = EvaluationArgument::new(field.clone(), challenge_index, terminal_index, symbols);
let eval_arg = EvaluationArgument::new(field, challenge_index, terminal_index, symbols);

// Compute terminal using challenges
let computed_terminal = eval_arg.compute_terminal(&challenges);
Expand Down Expand Up @@ -163,7 +163,7 @@ mod tests {

// Instantiate ProgramEvaluationArgument
let prog_eval_arg = ProgramEvaluationArgument::new(
field.clone(),
field,
challenge_indices,
terminal_index,
program,
Expand Down
36 changes: 35 additions & 1 deletion src/fields/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
#![allow(dead_code)]
use core::hash::{Hash, Hasher};
use std::fmt::write;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use std::cmp::{Ord, PartialOrd};
use std::fmt::{Debug, Display};
// Define a field
// Define a field element
// Define arithmetic operations on field elements
#[allow(clippy::derived_hash_with_manual_eq)]
#[derive(Debug, Clone, Copy, Hash)]
pub struct Field(pub u128);

Expand Down Expand Up @@ -45,7 +49,7 @@ impl PartialEq for Field {
}
}

#[derive(Debug, Clone, Copy)]
#[derive(Clone, Copy)]
pub struct FieldElement(pub u128, pub Field);

impl FieldElement {
Expand Down Expand Up @@ -241,6 +245,36 @@ impl Hash for FieldElement {
}
}

impl PartialOrd for FieldElement {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
if self.1 != other.1 {
return None;
}
self.0.partial_cmp(&other.0)
}
}

impl Ord for FieldElement {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
if self.1 != other.1 {
panic!("Fields must be same");
}
self.0.cmp(&other.0)
}
}

impl Display for FieldElement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}

impl Debug for FieldElement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}

#[cfg(test)]
mod test_field_operations {
use std::primitive;
Expand Down
20 changes: 10 additions & 10 deletions src/fri/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ impl Fri{
pub fn num_rounds(&self)-> usize{
let mut codeword_len = self.initial_domain_length;
let mut num =0;
while codeword_len>1 as u128{
codeword_len= codeword_len/2;
while codeword_len>1_u128{
codeword_len /= 2;
num+=1;
}
num
Expand Down Expand Up @@ -87,13 +87,13 @@ impl FriDomain{
Self { offset, omega, length }
}
pub fn call(&self, index: usize)->FieldElement{
let _x = self.omega.pow(index as u128)*self.offset;
_x

self.omega.pow(index as u128)*self.offset
}
pub fn list(&self)->Vec<FieldElement>{
let mut list: Vec<FieldElement>= vec![];
for i in 0..self.length{
list.push(self.omega.pow(i as u128)*self.offset);
list.push(self.omega.pow(i)*self.offset);
}
list
}
Expand All @@ -102,7 +102,7 @@ impl FriDomain{
let polynomial = polynomial.scalar_mul(self.offset);
let mut result: Vec<FieldElement> = vec![];
for i in 0..self.length{
result.push(polynomial.evaluate(self.omega.pow(i as u128)));
result.push(polynomial.evaluate(self.omega.pow(i)));
}
result
}
Expand All @@ -120,8 +120,8 @@ impl FriDomain{
for i in 0..values.len(){
list.push(self.omega.pow(i as u128));
}
let polynomial = interpolate_lagrange_polynomials(list, values).scalar_mul(self.offset.inverse());
polynomial

interpolate_lagrange_polynomials(list, values).scalar_mul(self.offset.inverse())
}
//not written xinterpolate, as it is used for extension field
}
Expand All @@ -132,7 +132,7 @@ mod test_fri{
fn test_evaluate(){
let field = Field::new(17);
let offset = FieldElement::new(2, field);
let length = 4 as u128;
let length = 4_u128;
let omega = FieldElement::new(13, field);
println!("omega ={:?}", omega);
let domain = FriDomain::new(offset, omega, length);
Expand All @@ -149,7 +149,7 @@ mod test_fri{
fn test_interpolate(){
let field = Field::new(17);
let offset = FieldElement::new(2, field);
let length = 4 as u128;
let length = 4_u128;
let omega = FieldElement::new(13, field);
println!("omega ={:?}", omega);
let domain = FriDomain::new(offset, omega, length);
Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod evaluation_argument;
pub mod permutation_argument;
pub mod merkle;
pub mod fri;
pub mod channel;

fn main() {
println!("Hello, world!");
Expand Down
9 changes: 4 additions & 5 deletions src/merkle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ pub struct MerkleTree {
impl MerkleTree {
pub fn new(data: &[FieldElement]) -> MerkleTree {
let leaves: Vec<[u8; 32]> = data
.into_iter()
.iter()
.map(|x| Sha256::hash(&x.to_bytes()))
.collect();
let merkle_tree = MerkleTreeTrait::<Sha256>::from_leaves(&leaves);
MerkleTree {
data: data.to_vec(),
leaves: leaves,
leaves,
inner: merkle_tree,
}
}
Expand Down Expand Up @@ -74,9 +74,8 @@ mod test_merkle_implementation {
let merkle_root = merkle_tree.inner.root().unwrap().to_vec();
let proof = merkle_tree.get_authentication_path(0);
let root = merkle_tree.clone().root().to_vec();
assert_eq!(
MerkleTree::validate(merkle_root.clone(), proof, 0, data[0].to_bytes(), 6),
true
assert!(
MerkleTree::validate(merkle_root.clone(), proof, 0, data[0].to_bytes(), 6)
);
assert_eq!(merkle_root, root);
for i in 0..root.len(){
Expand Down
Loading

0 comments on commit 8a131b6

Please sign in to comment.