Skip to content

Commit

Permalink
wip switch to Felt252
Browse files Browse the repository at this point in the history
  • Loading branch information
EvolveArt committed Sep 22, 2023
1 parent 4fd0d74 commit 617993e
Show file tree
Hide file tree
Showing 12 changed files with 78 additions and 89 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/business_logic/transaction/types.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashMap;

use cairo_felt::Felt252;
use serde::{Deserialize, Serialize};
use starknet::core::types::FieldElement;

// TODO: Complete this module

Expand All @@ -13,6 +13,6 @@ struct Transaction {

#[derive(Serialize, Deserialize)]
pub struct InternalTransaction {
hash_value: FieldElement,
hash_value: Felt252,
external_to_internal_cls: HashMap<Transaction, Self>,
}
6 changes: 3 additions & 3 deletions src/error/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use starknet::core::types::FieldElement;
use cairo_felt::Felt252;

#[derive(thiserror::Error, Clone, Debug)]
pub enum SnOsError {
Expand All @@ -19,11 +19,11 @@ pub enum CommitmentInfoError {
#[error("Inconsistent tree heights : {0} {1}.")]
InconsistentTreeHeights(usize, usize),
#[error("Inconsistent tree roots : {0} {1}.")]
InconsistentTreeRoots(FieldElement, FieldElement),
InconsistentTreeRoots(Felt252, Felt252),
}

#[derive(thiserror::Error, Clone, Debug)]
pub enum FactTreeError {
#[error("Unexpected result on single leaf index : {0}")]
UnexpectedResult(FieldElement),
UnexpectedResult(Felt252),
}
16 changes: 7 additions & 9 deletions src/fact_state/contract_state.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use starknet::core::types::FieldElement;
use cairo_felt::Felt252;

use crate::{
storage::{DBObject, Fact},
Expand All @@ -13,18 +13,16 @@ use crate::{

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ContractState {
contract_hash: FieldElement,
contract_hash: Felt252,
storage_commitment_tree: PatriciaTree,
nonce: FieldElement,
nonce: Felt252,
}

impl LeafFact for ContractState {
fn is_empty(&self) -> bool {
self.storage_commitment_tree.root
== FieldElement::from_byte_slice_be(EMPTY_NODE_HASH.as_slice()).unwrap()
&& self.contract_hash
== FieldElement::from_byte_slice_be(UNINITIALIZED_CLASS_HASH.as_slice()).unwrap()
&& self.nonce == FieldElement::ZERO
self.storage_commitment_tree.root == Felt252::from_bytes_be(EMPTY_NODE_HASH.as_slice())
&& self.contract_hash == Felt252::from_bytes_be(UNINITIALIZED_CLASS_HASH.as_slice())
&& self.nonce == Felt252::new(0)
}
}

Expand All @@ -36,7 +34,7 @@ impl Fact for ContractState {
return EMPTY_NODE_HASH.to_vec();
}

let contract_state_hash_version = FieldElement::ZERO;
let contract_state_hash_version = Felt252::new(0);

// Set hash_value = H(H(contract_hash, storage_root), RESERVED)
let hash_value = H::hash_elements(self.contract_hash, self.storage_commitment_tree.root);
Expand Down
12 changes: 6 additions & 6 deletions src/os_input.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashMap;

use cairo_felt::Felt252;
use serde::{Deserialize, Serialize};
use starknet::core::types::FieldElement;

use crate::{
business_logic::transaction::types::InternalTransaction,
Expand All @@ -14,11 +14,11 @@ use crate::{
struct StarknetOsInput<S: Storage, H: HasherT> {
contract_state_commitment_info: CommitmentInfo<S, H>,
contract_class_commitment_info: CommitmentInfo<S, H>,
deprecated_compiled_classes: HashMap<FieldElement, FieldElement>, // TODO: Add contract_class module
compiled_classes: HashMap<FieldElement, FieldElement>, // TODO: Add contract_class module
contracts: HashMap<FieldElement, ContractState>,
class_hash_to_compiled_class_hash: HashMap<FieldElement, FieldElement>,
deprecated_compiled_classes: HashMap<Felt252, Felt252>, // TODO: Add contract_class module
compiled_classes: HashMap<Felt252, Felt252>, // TODO: Add contract_class module
contracts: HashMap<Felt252, ContractState>,
class_hash_to_compiled_class_hash: HashMap<Felt252, Felt252>,
general_config: StarknetGeneralConfig,
transactions: Vec<InternalTransaction>,
block_hash: FieldElement,
block_hash: Felt252,
}
18 changes: 9 additions & 9 deletions src/storage/starknet.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, marker::PhantomData};

use starknet::core::types::FieldElement;
use cairo_felt::Felt252;

use crate::{
error::CommitmentInfoError,
Expand All @@ -15,12 +15,12 @@ use crate::{

use super::{FactCheckingContext, Storage};

type CommitmentFacts = HashMap<FieldElement, Vec<FieldElement>>;
type CommitmentFacts = HashMap<Felt252, Vec<Felt252>>;

#[derive(Serialize, Deserialize)]
pub struct CommitmentInfo<S: Storage, H: HasherT> {
pub previous_root: FieldElement,
pub updated_root: FieldElement,
pub previous_root: Felt252,
pub updated_root: Felt252,
tree_height: usize,
commitment_facts: CommitmentFacts,
_phantom_data: PhantomData<S>,
Expand All @@ -35,7 +35,7 @@ impl<S: Storage, H: HasherT> CommitmentInfo<S, H> {
&mut self,
previous_tree: PatriciaTree,
expected_updated_tree: PatriciaTree,
expected_accessed_indices: Vec<FieldElement>,
expected_accessed_indices: Vec<Felt252>,
ffc: FactCheckingContext<S, H>,
) -> Result<CommitmentInfo<S, H>, CommitmentInfoError> {
if previous_tree.height != expected_updated_tree.height {
Expand All @@ -45,7 +45,7 @@ impl<S: Storage, H: HasherT> CommitmentInfo<S, H> {
));
}

let modifications: HashMap<FieldElement, InnerNodeFact> = expected_updated_tree
let modifications: HashMap<Felt252, InnerNodeFact> = expected_updated_tree
.get_leaves(&ffc, expected_accessed_indices, None)
.await;

Expand All @@ -66,15 +66,15 @@ impl<S: Storage, H: HasherT> CommitmentInfo<S, H> {
pub async fn create_from_modifications(
&mut self,
previous_tree: PatriciaTree,
expected_updated_root: FieldElement,
modifications: HashMap<FieldElement, InnerNodeFact>,
expected_updated_root: Felt252,
modifications: HashMap<Felt252, InnerNodeFact>,
ffc: &FactCheckingContext<S, H>,
) -> Result<CommitmentInfo<S, H>, CommitmentInfoError> {
let mut commitment_facts = CommitmentFacts::new();
let actual_updated_tree = previous_tree
.update(ffc, modifications, Some(&mut commitment_facts))
.await;
let actual_updated_root: FieldElement = actual_updated_tree.root;
let actual_updated_root: Felt252 = actual_updated_tree.root;

if actual_updated_root != expected_updated_root {
return Err(CommitmentInfoError::InconsistentTreeRoots(
Expand Down
16 changes: 8 additions & 8 deletions src/utils/commitment_tree/binary_fact_tree.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::HashMap;

use starknet::core::types::FieldElement;
use cairo_felt::Felt252;

use crate::{
error::FactTreeError,
Expand All @@ -10,7 +10,7 @@ use crate::{

use super::nodes::InnerNodeFact;

pub type BinaryFactDict = HashMap<FieldElement, Vec<FieldElement>>;
pub type BinaryFactDict = HashMap<Felt252, Vec<Felt252>>;

pub trait BinaryFactTree<S: Storage, H: HasherT>
where
Expand All @@ -27,28 +27,28 @@ where
async fn get_leaves(
&self,
ffc: &FactCheckingContext<S, H>,
indices: Vec<FieldElement>,
indices: Vec<Felt252>,
facts: Option<BinaryFactDict>,
) -> HashMap<FieldElement, InnerNodeFact>;
) -> HashMap<Felt252, InnerNodeFact>;

async fn _get_leaves(
&self,
ffc: &FactCheckingContext<S, H>,
indices: Vec<FieldElement>,
indices: Vec<Felt252>,
facts: Option<BinaryFactDict>,
) -> HashMap<FieldElement, InnerNodeFact>;
) -> HashMap<Felt252, InnerNodeFact>;

async fn update(
&self,
ffc: &FactCheckingContext<S, H>,
modifications: HashMap<FieldElement, InnerNodeFact>,
modifications: HashMap<Felt252, InnerNodeFact>,
facts: Option<&mut BinaryFactDict>,
) -> Self;

async fn get_leaf(
&self,
ffc: &FactCheckingContext<S, H>,
index: FieldElement,
index: Felt252,
) -> Result<InnerNodeFact, FactTreeError> {
let leaves = self.get_leaves(ffc, vec![index], None).await;
if leaves.keys().ne([index].iter()) {
Expand Down
44 changes: 20 additions & 24 deletions src/utils/commitment_tree/nodes.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use bitvec::{prelude::Msb0, vec::BitVec};
use starknet::core::types::FieldElement;
use cairo_felt::Felt252;

use crate::{
storage::{DBObject, Fact, HASH_BYTES},
Expand All @@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize};

pub const EMPTY_NODE_HASH: [u8; 4] = HASH_BYTES;

pub const EMPTY_NODE_PREIMAGE_LENGTH: FieldElement = FieldElement::ZERO;
pub const EMPTY_NODE_PREIMAGE_LENGTH: Felt252 = Felt252::new(0);

/// A node in a Binary Merkle-Patricia Tree graph.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
Expand All @@ -36,14 +36,14 @@ impl Fact for EmptyNode {

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BinaryNode {
left: FieldElement,
right: FieldElement,
left: Felt252,
right: Felt252,
}

impl BinaryNode {
#[allow(unused)]
pub(crate) fn preimage_length() -> FieldElement {
FieldElement::TWO * FieldElement::from_byte_slice_be(HASH_BYTES.as_slice()).unwrap()
pub(crate) fn preimage_length() -> Felt252 {
Felt252::new(2) * Felt252::from_bytes_be(HASH_BYTES.as_slice()).unwrap()
}
}

Expand All @@ -65,9 +65,8 @@ pub struct EdgeNode {

impl EdgeNode {
#[allow(unused)]
pub(crate) fn preimage_length() -> FieldElement {
FieldElement::TWO * FieldElement::from_byte_slice_be(HASH_BYTES.as_slice()).unwrap()
+ FieldElement::ONE
pub(crate) fn preimage_length() -> Felt252 {
Felt252::new(2) * Felt252::from_bytes_be(HASH_BYTES.as_slice()).unwrap() + Felt252::new(1)
}
}

Expand All @@ -80,7 +79,7 @@ impl Fact for EdgeNode {

let bottom_path_hash = H::hash_elements(
self.bottom_node.hash().unwrap(),
FieldElement::from_byte_slice_be(bvec.as_slice()).unwrap(),
Felt252::from_bytes_be(bvec.as_slice()).unwrap(),
);

// Add the edge length.
Expand All @@ -94,7 +93,7 @@ impl Fact for EdgeNode {

impl InnerNodeFact {
/// Returns true if the node represents an empty node -- this is defined as a node
/// with the [FieldElement::ZERO].
/// with the [Felt252::new(0)].
///
/// This can occur for the root node in an empty graph.
pub fn is_empty(&self) -> bool {
Expand All @@ -109,20 +108,17 @@ impl InnerNodeFact {
}

/// Get the hash of an inner node fact.
pub fn hash(&self) -> Option<FieldElement> {
pub fn hash(&self) -> Option<Felt252> {
match self {
InnerNodeFact::Empty(empty) => Some(
FieldElement::from_byte_slice_be(empty._hash::<PedersenHasher>().as_slice())
.unwrap(),
),
InnerNodeFact::Binary(binary) => Some(
FieldElement::from_byte_slice_be(binary._hash::<PedersenHasher>().as_slice())
.unwrap(),
),
InnerNodeFact::Edge(edge) => Some(
FieldElement::from_byte_slice_be(edge._hash::<PedersenHasher>().as_slice())
.unwrap(),
),
InnerNodeFact::Empty(empty) => {
Some(Felt252::from_bytes_be(empty._hash::<PedersenHasher>().as_slice()).unwrap())
}
InnerNodeFact::Binary(binary) => {
Some(Felt252::from_bytes_be(binary._hash::<PedersenHasher>().as_slice()).unwrap())
}
InnerNodeFact::Edge(edge) => {
Some(Felt252::from_bytes_be(edge._hash::<PedersenHasher>().as_slice()).unwrap())
}
}
}
}
Expand Down
16 changes: 8 additions & 8 deletions src/utils/commitment_tree/patricia_tree.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::HashMap;

use starknet::core::types::FieldElement;
use cairo_felt::Felt252;

use crate::{
error::FactTreeError,
Expand All @@ -15,7 +15,7 @@ use super::{

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PatriciaTree {
pub root: FieldElement,
pub root: Felt252,
pub height: usize,
}

Expand All @@ -32,25 +32,25 @@ impl<S: Storage, H: HasherT> BinaryFactTree<S, H> for PatriciaTree {
async fn get_leaves(
&self,
_ffc: &FactCheckingContext<S, H>,
_indices: Vec<FieldElement>,
_indices: Vec<Felt252>,
_facts: Option<BinaryFactDict>,
) -> HashMap<FieldElement, InnerNodeFact> {
) -> HashMap<Felt252, InnerNodeFact> {
todo!()
}

async fn _get_leaves(
&self,
_ffc: &FactCheckingContext<S, H>,
_indices: Vec<FieldElement>,
_indices: Vec<Felt252>,
_facts: Option<BinaryFactDict>,
) -> HashMap<FieldElement, InnerNodeFact> {
) -> HashMap<Felt252, InnerNodeFact> {
todo!()
}

async fn update(
&self,
_ffc: &FactCheckingContext<S, H>,
_modifications: HashMap<FieldElement, InnerNodeFact>,
_modifications: HashMap<Felt252, InnerNodeFact>,
_facts: Option<&mut BinaryFactDict>,
) -> Self {
todo!()
Expand All @@ -59,7 +59,7 @@ impl<S: Storage, H: HasherT> BinaryFactTree<S, H> for PatriciaTree {
async fn get_leaf(
&self,
_ffc: &FactCheckingContext<S, H>,
_index: FieldElement,
_index: Felt252,
) -> Result<InnerNodeFact, FactTreeError> {
todo!()
}
Expand Down
Loading

0 comments on commit 617993e

Please sign in to comment.