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
m-pandey5 committed Dec 4, 2024
2 parents e5d473b + 9d32ca9 commit 72f8c87
Show file tree
Hide file tree
Showing 7 changed files with 353 additions and 64 deletions.
2 changes: 0 additions & 2 deletions src/channel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ impl Channel {
log::debug!("sending to channel");
let data_for_digest = format!("{}:{:?}", self.state, s.clone());
self.state = sha256::digest(data_for_digest);
// in stark101 from starkware, we push parent function and s into the proof.
// there is no straight forward way to know parent function in rust.
self.proof.push(s.clone());
self.compressed_proof.push(s);
}
Expand Down
35 changes: 34 additions & 1 deletion src/fields/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#![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
Expand Down Expand Up @@ -46,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 @@ -242,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
41 changes: 41 additions & 0 deletions src/tables/instruction.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use crate::fields::{Field, FieldElement};
use super::{Table, roundup_npow2, derive_omicron};
pub struct InstructionTable {
pub table: Table,
}

pub enum Indices {
// Named indices for base columns
Address,
CurrentInstruction,
NextInstruction,
// Named indices for extension columns
PermutationArg,
EvaluationArg,
}

impl InstructionTable {
pub fn new(field: Field, length:u128, num_randomizers: u128, generator: FieldElement, order: u128) -> Self {
let base_width = 3;
let full_width = base_width + 2;
let height = roundup_npow2(length);
let omicron = derive_omicron(generator, order, height);
let matrix = vec![vec![FieldElement::zero(field); full_width as usize]; height as usize];
let table = Table::new(field, base_width, full_width, length, num_randomizers, height, omicron, generator, order, matrix);
Self { table: table }
}

pub fn get_table(&self) -> &Table {
&self.table
}

// Note: Before padding initiate the matrix in table.
// Add padding rows to convert the matrix derived from trace to a matrix of length of a power of 2
pub fn pad(&mut self) {
let zero = FieldElement::new(0, self.table.field);
for _ in 0..(self.table.height - self.table.length) {
let new_row = vec![self.table.matrix.last().unwrap()[Indices::Address as usize],zero, zero, zero, zero];
self.table.matrix.push(new_row);
}
}
}
58 changes: 58 additions & 0 deletions src/tables/memory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use crate::fields::{Field, FieldElement};
use super::processor::Indices as ProcessorIndices;
use super::Table;
pub struct Memory {
pub table : Table,
}

pub enum Indices {
// Named indices for base columns
Cycle,
MemoryPointer,
MemoryValue,
Dummy,
// Named indices for extension columns
PermutationArg,
}

impl Memory {
pub fn derive_matrix(processor_matrix: &[Vec::<FieldElement>]) -> Vec<Vec<FieldElement>> {
let field = processor_matrix[0][0].1;
let zero = FieldElement::zero(field);
let one = FieldElement::one(field);

let mut matrix: Vec<Vec<FieldElement>> = processor_matrix
.iter()
.filter(|pt| pt[ProcessorIndices::CurrentInstruction as usize] != zero)
.map(|pt| vec![
pt[ProcessorIndices::Cycle as usize].clone(),
pt[ProcessorIndices::MemoryPointer as usize].clone(),
pt[ProcessorIndices::MemoryValue as usize].clone(),
zero, // Equivalent to 'zero' in Python
])
.collect();

// Sort by memory_pointer
matrix.sort_by(|a, b| {
a[Indices::MemoryPointer as usize]
.partial_cmp(&b[Indices::MemoryPointer as usize])
.unwrap_or(std::cmp::Ordering::Equal)
});

// Insert dummy rows for smooth clock jumps
let mut i = 0;
while i < matrix.len() - 1 {
if matrix[i][Indices::MemoryPointer as usize] == matrix[i + 1][Indices::MemoryPointer as usize] && matrix[i + 1][Indices::Cycle as usize] != matrix[i][Indices::Cycle as usize] + one{
matrix.insert(i + 1,vec![
matrix[i][Indices::Cycle as usize].clone() + one,
matrix[i][Indices::MemoryPointer as usize].clone(),
matrix[i][Indices::MemoryValue as usize].clone(),
one
],
);
}
i += 1;
}
matrix
}
}
86 changes: 32 additions & 54 deletions src/tables/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use rand::*;
use crate::fri::*;
use crate::ntt::*;
// we will implement abstract methods in rust using the traits.

pub mod instruction;
pub mod memory;
pub mod processor;
#[derive(Debug, Clone)]
pub struct Table {
pub field: Field,
Expand All @@ -19,6 +21,7 @@ pub struct Table {
order: u128,//order of the generator.
matrix: Vec<Vec<FieldElement>>,
}

impl Table {
// Constructor method to create a new instance of `table`
pub fn new(
Expand Down Expand Up @@ -70,9 +73,8 @@ impl Table {
return 0;
}
omega_order/self.height


}

// wrong implementation in py
pub fn get_interpolating_domain_length( &self)->u128{
self.height
Expand Down Expand Up @@ -137,18 +139,20 @@ impl Table {
polynomial.push(poly);
}
polynomial
}
}
// fn lde(self,domain:FriDomain)->Vec<FieldElement>{
// let polynomials = self.interpolate_columns(domain.omega, self.height, (0..self.full_width).collect());
// for p in polynomials{

// }


// trait TableOperations {
// type Field
// }
// }

pub fn boundary_constraints_ext(self,challeneges:Vec<FieldElement>){
}
// pub fn boundary_constraints_ext(self,challeneges:Vec<FieldElement>){
// }
// pub fn boundary_quotients(self,fri_domain:FriDomain,codewords:Vec<Vec<FieldElement>>,challenges:Vec<FieldElement>)->Vec<Vec<FieldElement>>{
// if (codewords.len()==0){
// println!("panic! because codewords' argument must have nonzero length")
Expand All @@ -172,58 +176,34 @@ pub fn boundary_constraints_ext(self,challeneges:Vec<FieldElement>){

// }
// }






}







pub fn roundup_npow2( len:u128)->u128{
if len==0{
return 0;

}
else if len == 1 {
return 1;
}
// Calculate the next power of two
let bit_representation = format!("{:b}", len - 1);



1 <<
(bit_representation.len() as u128)

pub fn roundup_npow2( len:u128)->u128{
if len==0{
return 0;
}else if len == 1 {
return 1;
}
// mutable or clone doubt
pub fn derive_omicron(generator:FieldElement,generator_order:u128,target_order:u128)->FieldElement{
let mut t_generator=generator;
let mut t_order=generator_order;

while t_order!=target_order{
t_generator=t_generator.pow(2);
t_order/=2;
}
t_generator

// Calculate the next power of two
let bit_representation = format!("{:b}", len - 1);
1 << (bit_representation.len() as u128)
}

// mutable or clone doubt
pub fn derive_omicron(generator:FieldElement,generator_order:u128,target_order:u128)->FieldElement{
let mut t_generator=generator;
let mut t_order=generator_order;

while t_order!=target_order{
t_generator=t_generator.pow(2);
t_order/=2;
}
pub fn has_order_po2( order: u128) -> bool {
(order & (order - 1)) == 0
}



t_generator
}

pub fn has_order_po2( order: u128) -> bool {
(order & (order - 1)) == 0
}

#[cfg(test)]
mod test_operations{
Expand Down Expand Up @@ -255,5 +235,3 @@ mod test_operations{

}



15 changes: 15 additions & 0 deletions src/tables/processor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
pub enum Indices {
// Named indices for registers
Cycle,
InstructionPointer,
CurrentInstruction,
NextInstruction,
MemoryPointer,
MemoryValue,
MemoryValueInvers,
// Named indices for extension columns
InstructionPermutaion,
MemoryPermuation,
InputEvaluation,
OutputEvaluation,
}
Loading

0 comments on commit 72f8c87

Please sign in to comment.