From 104b60a4b8f1f2f30043ca26c27ef6337d38b950 Mon Sep 17 00:00:00 2001 From: 0xevolve Date: Mon, 25 Sep 2023 11:43:01 +0200 Subject: [PATCH] =?UTF-8?q?Revert=20"=E2=9C=A8=20OsInput=20Missing=20Field?= =?UTF-8?q?s=20(#10)"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit b4948de2c8fab72e395e30e103617386faee1504. --- Cargo.lock | 7 +- Cargo.toml | 2 - rust-toolchain.toml | 2 +- src/business_logic/mod.rs | 1 - src/business_logic/transaction/mod.rs | 1 - src/business_logic/transaction/types.rs | 18 -- src/error/mod.rs | 6 +- src/fact_state/contract_state.rs | 61 ----- src/fact_state/mod.rs | 1 - src/lib.rs | 2 - src/os_input.rs | 25 +- src/storage/mod.rs | 24 +- src/storage/starknet.rs | 52 ++-- src/utils/commitment_tree/binary_fact_tree.rs | 44 ++-- src/utils/commitment_tree/mod.rs | 1 - src/utils/commitment_tree/nodes.rs | 155 ------------ src/utils/commitment_tree/patricia_tree.rs | 39 ++- src/utils/definitions/constants.rs | 236 ------------------ src/utils/definitions/general_config.rs | 92 ------- src/utils/definitions/mod.rs | 2 - src/utils/hasher/mod.rs | 40 --- src/utils/hasher/pedersen.rs | 87 ------- src/utils/mod.rs | 2 - 23 files changed, 82 insertions(+), 818 deletions(-) delete mode 100644 src/business_logic/mod.rs delete mode 100644 src/business_logic/transaction/mod.rs delete mode 100644 src/business_logic/transaction/types.rs delete mode 100644 src/fact_state/contract_state.rs delete mode 100644 src/fact_state/mod.rs delete mode 100644 src/utils/commitment_tree/nodes.rs delete mode 100644 src/utils/definitions/constants.rs delete mode 100644 src/utils/definitions/general_config.rs delete mode 100644 src/utils/definitions/mod.rs delete mode 100644 src/utils/hasher/mod.rs delete mode 100644 src/utils/hasher/pedersen.rs diff --git a/Cargo.lock b/Cargo.lock index 1a4110fc5..33e409592 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -258,7 +258,6 @@ checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" dependencies = [ "funty", "radium", - "serde", "tap", "wyz", ] @@ -1803,9 +1802,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.101.6" +version = "0.101.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe" +checksum = "45a27e3b59326c16e23d30aeb7a36a24cc0d29e71d68ff611cdfb4a01d013bed" dependencies = [ "ring", "untrusted", @@ -2014,7 +2013,6 @@ name = "snos" version = "0.1.0" dependencies = [ "base64 0.21.4", - "bitvec", "cairo-felt", "cairo-vm", "hex", @@ -2028,7 +2026,6 @@ dependencies = [ "serde_json", "starknet", "thiserror", - "tokio", "uuid 1.4.1", "zip", ] diff --git a/Cargo.toml b/Cargo.toml index a3398a3c2..4fb1384c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,8 +18,6 @@ hex = "0.4.3" starknet = { git = "https://github.com/xJonathanLEI/starknet-rs" } uuid = { version = "1.4.0", features = ["v4", "serde"] } reqwest = { version = "0.11.18", features = ["blocking", "json"] } -bitvec = { version = "1.0.1", features = ["serde"] } -tokio = "1.32.0" pretty_assertions = "1.4.0" [dev-dependencies] diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 89a31e77d..50c144b52 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "nightly-2023-08-02" +channel = "nightly-2023-08-03" components = ["rustfmt", "clippy"] profile = "minimal" diff --git a/src/business_logic/mod.rs b/src/business_logic/mod.rs deleted file mode 100644 index 37f08066e..000000000 --- a/src/business_logic/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod transaction; diff --git a/src/business_logic/transaction/mod.rs b/src/business_logic/transaction/mod.rs deleted file mode 100644 index cd408564e..000000000 --- a/src/business_logic/transaction/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod types; diff --git a/src/business_logic/transaction/types.rs b/src/business_logic/transaction/types.rs deleted file mode 100644 index 6e0ea0b73..000000000 --- a/src/business_logic/transaction/types.rs +++ /dev/null @@ -1,18 +0,0 @@ -use std::collections::HashMap; - -use cairo_felt::Felt252; -use serde::{Deserialize, Serialize}; - -// TODO: Complete this module - -// TODO: Use a standard type from starknet_api/types-rs -#[derive(Serialize, Deserialize, PartialEq, Eq, Hash)] -struct Transaction { - version: u8, -} - -#[derive(Serialize, Deserialize)] -pub struct InternalTransaction { - hash_value: Felt252, - external_to_internal_cls: HashMap, -} diff --git a/src/error/mod.rs b/src/error/mod.rs index 88501b103..dde69d99f 100644 --- a/src/error/mod.rs +++ b/src/error/mod.rs @@ -1,4 +1,4 @@ -use cairo_felt::Felt252; +use starknet::core::types::FieldElement; #[derive(thiserror::Error, Clone, Debug)] pub enum SnOsError { @@ -19,11 +19,11 @@ pub enum CommitmentInfoError { #[error("Inconsistent tree heights : {0} {1}.")] InconsistentTreeHeights(usize, usize), #[error("Inconsistent tree roots : {0} {1}.")] - InconsistentTreeRoots(Felt252, Felt252), + InconsistentTreeRoots(FieldElement, FieldElement), } #[derive(thiserror::Error, Clone, Debug)] pub enum FactTreeError { #[error("Unexpected result on single leaf index : {0}")] - UnexpectedResult(Felt252), + UnexpectedResult(FieldElement), } diff --git a/src/fact_state/contract_state.rs b/src/fact_state/contract_state.rs deleted file mode 100644 index 5cc084a84..000000000 --- a/src/fact_state/contract_state.rs +++ /dev/null @@ -1,61 +0,0 @@ -use cairo_felt::Felt252; - -use crate::{ - storage::{DBObject, Fact}, - utils::{ - commitment_tree::{ - leaf_fact::LeafFact, nodes::EMPTY_NODE_HASH, patricia_tree::PatriciaTree, - }, - definitions::constants::UNINITIALIZED_CLASS_HASH, - hasher::HasherT, - }, -}; - -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] -pub struct ContractState { - contract_hash: Felt252, - storage_commitment_tree: PatriciaTree, - nonce: Felt252, -} - -impl LeafFact for ContractState { - fn is_empty(&self) -> bool { - 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) - } -} - -impl Fact for ContractState { - /// Computes the hash of the node containing the contract's information, including the contract - /// definition and storage. - fn _hash(&self) -> Vec { - if self.is_empty() { - return EMPTY_NODE_HASH.to_vec(); - } - - 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.clone(), - self.storage_commitment_tree.root.clone(), - ); - let hash_value = H::hash_elements(hash_value, self.nonce.clone()); - - // Return H(hash_value, CONTRACT_STATE_HASH_VERSION). CONTRACT_STATE_HASH_VERSION must be in - // the outermost hash to guarantee unique "decoding". - H::hash_elements(hash_value, contract_state_hash_version) - .to_bytes_be() - .to_vec() - } -} - -impl DBObject for ContractState { - fn db_key(suffix: Vec) -> Vec { - let prefix: &[u8] = "contract_state".as_bytes(); - let sep: &[u8] = ":".as_bytes(); - - [prefix, sep, suffix.as_slice()].concat() - } -} diff --git a/src/fact_state/mod.rs b/src/fact_state/mod.rs deleted file mode 100644 index cce90fd6c..000000000 --- a/src/fact_state/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub mod contract_state; diff --git a/src/lib.rs b/src/lib.rs index e89060852..958813d6d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,8 +1,6 @@ #![feature(async_fn_in_trait)] -pub mod business_logic; pub mod error; -pub mod fact_state; pub mod hints; pub mod os_input; pub mod sharp; diff --git a/src/os_input.rs b/src/os_input.rs index a2e6105fc..232b905a8 100644 --- a/src/os_input.rs +++ b/src/os_input.rs @@ -1,24 +1,15 @@ use std::collections::HashMap; -use cairo_felt::Felt252; use serde::{Deserialize, Serialize}; +use starknet::core::types::FieldElement; -use crate::{ - business_logic::transaction::types::InternalTransaction, - fact_state::contract_state::ContractState, - storage::{starknet::CommitmentInfo, Storage}, - utils::{definitions::general_config::StarknetGeneralConfig, hasher::HasherT}, -}; +use crate::storage::starknet::CommitmentInfo; +// TODO: Add missing fields #[derive(Serialize, Deserialize)] -struct StarknetOsInput { - contract_state_commitment_info: CommitmentInfo, - contract_class_commitment_info: CommitmentInfo, - deprecated_compiled_classes: HashMap, // TODO: Add contract_class module - compiled_classes: HashMap, // TODO: Add contract_class module - contracts: HashMap, - class_hash_to_compiled_class_hash: HashMap, - general_config: StarknetGeneralConfig, - transactions: Vec, - block_hash: Felt252, +struct StarknetOsInput { + contract_state_commitment_info: CommitmentInfo, + contract_class_commitment_info: CommitmentInfo, + class_hash_to_compiled_class_hash: HashMap, + block_hash: FieldElement, } diff --git a/src/storage/mod.rs b/src/storage/mod.rs index 172340d00..6ffb5dce2 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -1,11 +1,9 @@ pub mod starknet; -use std::marker::PhantomData; - use serde::{Deserialize, Serialize}; use serde_json::{from_slice, to_vec}; -use crate::utils::hasher::{pedersen::PedersenHasher, HasherT}; +type HashFunctionType = fn(&[u8], &[u8]) -> Vec; pub trait Storage: Clone { async fn set_value(&self, key: Vec, value: Vec); @@ -13,7 +11,7 @@ pub trait Storage: Clone { async fn del_value(&self, key: Vec); } -pub trait DBObject: Serialize + for<'de> Deserialize<'de> { +pub trait DBObject: Serialize + for<'de> Deserialize<'de> + Copy { /// Method to get the database key for the object fn db_key(suffix: Vec) -> Vec; @@ -36,22 +34,20 @@ pub trait DBObject: Serialize + for<'de> Deserialize<'de> { } } -pub const HASH_BYTES: [u8; 4] = 32u32.to_be_bytes(); - -#[derive(Debug)] -pub struct FactCheckingContext { - pub storage: S, - pub _n_workers: Option, - phantom_data: PhantomData, +#[derive(Debug, Clone)] +pub struct FactCheckingContext { + storage: S, + hash_func: HashFunctionType, + _n_workers: Option, } pub trait Fact: DBObject { /// A fact is a DB object with a DB key that is a hash of its value. /// Use set_fact() and get() to read and write facts. - fn _hash(&self) -> Vec; + fn _hash(&self, hash_func: HashFunctionType) -> Vec; - async fn set_fact(&self, ffc: FactCheckingContext) -> Vec { - let hash_val = self._hash::(); + async fn set_fact(&self, ffc: FactCheckingContext) -> Vec { + let hash_val = self._hash(ffc.hash_func); self.set(&ffc.storage, &hash_val); hash_val } diff --git a/src/storage/starknet.rs b/src/storage/starknet.rs index 918d0ab47..9997a5570 100644 --- a/src/storage/starknet.rs +++ b/src/storage/starknet.rs @@ -1,43 +1,39 @@ use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, marker::PhantomData}; +use std::collections::HashMap; -use cairo_felt::Felt252; +use starknet::core::types::FieldElement; use crate::{ error::CommitmentInfoError, - utils::{ - commitment_tree::{ - binary_fact_tree::BinaryFactTree, nodes::InnerNodeFact, patricia_tree::PatriciaTree, - }, - hasher::HasherT, + utils::commitment_tree::{ + binary_fact_tree::BinaryFactTree, leaf_fact::LeafFact, patricia_tree::PatriciaTree, }, }; use super::{FactCheckingContext, Storage}; -type CommitmentFacts = HashMap>; +type CommitmentFacts = HashMap>; #[derive(Serialize, Deserialize)] -pub struct CommitmentInfo { - pub previous_root: Felt252, - pub updated_root: Felt252, +pub struct CommitmentInfo { + previous_root: FieldElement, + updated_root: FieldElement, tree_height: usize, commitment_facts: CommitmentFacts, - _phantom_data: PhantomData, - _phantom_data_2: PhantomData, } -impl CommitmentInfo { +impl CommitmentInfo { /// # Returns /// * `commitment_info` - Commitment information corresponding to the expected modifications /// and updated tree - pub async fn create_from_expected_updated_tree( + pub async fn create_from_expected_updated_tree( &mut self, previous_tree: PatriciaTree, expected_updated_tree: PatriciaTree, - expected_accessed_indices: Vec, - ffc: FactCheckingContext, - ) -> Result, CommitmentInfoError> { + expected_accessed_indices: Vec, + _leaft_fact_type: L, + ffc: FactCheckingContext, + ) -> Result { if previous_tree.height != expected_updated_tree.height { return Err(CommitmentInfoError::InconsistentTreeHeights( previous_tree.height, @@ -45,8 +41,8 @@ impl CommitmentInfo { )); } - let modifications: HashMap = expected_updated_tree - .get_leaves(&ffc, expected_accessed_indices, None) + let modifications: HashMap = expected_updated_tree + .get_leaves(ffc.clone(), expected_accessed_indices, None) .await; let commitment_info = self @@ -54,7 +50,7 @@ impl CommitmentInfo { previous_tree, expected_updated_tree.root, modifications, - &ffc, + ffc, ) .await?; @@ -63,18 +59,18 @@ impl CommitmentInfo { /// # Returns /// * `commitment_info` - Commitment information corresponding to the given modifications. - pub async fn create_from_modifications( + pub async fn create_from_modifications( &mut self, previous_tree: PatriciaTree, - expected_updated_root: Felt252, - modifications: HashMap, - ffc: &FactCheckingContext, - ) -> Result, CommitmentInfoError> { + expected_updated_root: FieldElement, + modifications: HashMap, + ffc: FactCheckingContext, + ) -> Result { let mut commitment_facts = CommitmentFacts::new(); let actual_updated_tree = previous_tree .update(ffc, modifications, Some(&mut commitment_facts)) .await; - let actual_updated_root: Felt252 = actual_updated_tree.root; + let actual_updated_root: FieldElement = actual_updated_tree.root; if actual_updated_root != expected_updated_root { return Err(CommitmentInfoError::InconsistentTreeRoots( @@ -88,8 +84,6 @@ impl CommitmentInfo { updated_root: actual_updated_root, tree_height: previous_tree.height, commitment_facts, - _phantom_data: PhantomData, - _phantom_data_2: PhantomData, }) } } diff --git a/src/utils/commitment_tree/binary_fact_tree.rs b/src/utils/commitment_tree/binary_fact_tree.rs index e1305812c..81ca3514d 100644 --- a/src/utils/commitment_tree/binary_fact_tree.rs +++ b/src/utils/commitment_tree/binary_fact_tree.rs @@ -1,62 +1,56 @@ use std::collections::HashMap; -use cairo_felt::Felt252; +use starknet::core::types::FieldElement; use crate::{ error::FactTreeError, storage::{FactCheckingContext, Storage}, - utils::hasher::HasherT, }; -use super::nodes::InnerNodeFact; +use super::leaf_fact::LeafFact; -pub type BinaryFactDict = HashMap>; +pub type BinaryFactDict = HashMap>; -pub trait BinaryFactTree +pub trait BinaryFactTree where Self: Sized, { /// Initializes an empty BinaryFactTree of the given height. - async fn empty_tree( - &self, - ffc: FactCheckingContext, - height: usize, - leaft_fact: InnerNodeFact, - ); + async fn empty_tree(&self, ffc: FactCheckingContext, height: usize, leaft_fact: L); /// Returns the values of the leaves whose indices are given. async fn get_leaves( &self, - ffc: &FactCheckingContext, - indices: Vec, + ffc: FactCheckingContext, + indices: Vec, facts: Option, - ) -> HashMap; + ) -> HashMap; async fn _get_leaves( &self, - ffc: &FactCheckingContext, - indices: Vec, + ffc: FactCheckingContext, + indices: Vec, facts: Option, - ) -> HashMap; + ) -> HashMap; async fn update( &self, - ffc: &FactCheckingContext, - modifications: HashMap, + ffc: FactCheckingContext, + modifications: HashMap, facts: Option<&mut BinaryFactDict>, ) -> Self; async fn get_leaf( &self, - ffc: &FactCheckingContext, - index: Felt252, - ) -> Result { - let leaves = self.get_leaves(ffc, vec![index.clone()], None).await; - if leaves.keys().ne([index.clone()].iter()) { + ffc: FactCheckingContext, + index: FieldElement, + ) -> Result { + let leaves = self.get_leaves(ffc, vec![index], None).await; + if leaves.keys().ne([index].iter()) { return Err(FactTreeError::UnexpectedResult(index)); } // TODO: remove unwrap - let leaf = leaves.get(&index).unwrap().clone(); + let leaf = *leaves.get(&index).unwrap(); Ok(leaf) } diff --git a/src/utils/commitment_tree/mod.rs b/src/utils/commitment_tree/mod.rs index 3ab3cfcbe..dc848eb76 100644 --- a/src/utils/commitment_tree/mod.rs +++ b/src/utils/commitment_tree/mod.rs @@ -1,4 +1,3 @@ pub mod binary_fact_tree; pub mod leaf_fact; -pub mod nodes; pub mod patricia_tree; diff --git a/src/utils/commitment_tree/nodes.rs b/src/utils/commitment_tree/nodes.rs deleted file mode 100644 index 9cebfb122..000000000 --- a/src/utils/commitment_tree/nodes.rs +++ /dev/null @@ -1,155 +0,0 @@ -use bitvec::{prelude::Msb0, vec::BitVec}; -use cairo_felt::Felt252; - -use crate::{ - storage::{DBObject, Fact, HASH_BYTES}, - utils::hasher::{pedersen::PedersenHasher, HasherT}, -}; - -use serde::{Deserialize, Serialize}; - -pub const EMPTY_NODE_HASH: [u8; 4] = HASH_BYTES; - -// 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)] -pub enum InnerNodeFact { - /// A node that has not been fetched from storage yet. - /// - /// As such, all we know is its hash. - Empty(EmptyNode), - /// A branch node with exactly two children. - Binary(BinaryNode), - /// Describes a path connecting two other nodes. - Edge(EdgeNode), -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct EmptyNode {} - -impl Fact for EmptyNode { - fn _hash(&self) -> Vec { - HASH_BYTES.to_vec() - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct BinaryNode { - left: Felt252, - right: Felt252, -} - -impl BinaryNode { - #[allow(unused)] - pub(crate) fn preimage_length() -> Felt252 { - Felt252::new(2) * Felt252::from_bytes_be(HASH_BYTES.as_slice()) - } -} - -impl Fact for BinaryNode { - fn _hash(&self) -> Vec { - EMPTY_NODE_HASH.to_vec() - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct EdgeNode { - /// The root of the subtree containing data with value != 0. - bottom_node: Box, - /// The binary representation of the leaf index in the subtree that this node is root of. - edge_path: BitVec, - /// The height of the edge node (the length of the path to the leaf). - edge_length: usize, -} - -impl EdgeNode { - #[allow(unused)] - pub(crate) fn preimage_length() -> Felt252 { - Felt252::new(2) * Felt252::from_bytes_be(HASH_BYTES.as_slice()) + Felt252::new(1) - } -} - -impl Fact for EdgeNode { - fn _hash(&self) -> Vec { - // https://github.com/ferrilab/bitvec/issues/27 - let mut bv = self.edge_path.to_owned(); - bv.force_align(); - let _bvec = bv.into_vec(); - - // TODO: Fix with new Hasher - // let bottom_path_hash = H::hash_elements( - // self.bottom_node.hash().unwrap(), - // Felt252::from_bytes_be(bvec.as_slice()).unwrap(), - // ); - let bottom_path_hash = Felt252::new(0); - - // Add the edge length. - [ - bottom_path_hash.to_bytes_be().as_slice(), - self.edge_length.to_string().as_bytes(), - ] - .concat() - } -} - -impl InnerNodeFact { - /// Returns true if the node represents an empty node -- this is defined as a node - /// with the [Felt252::new(0)]. - /// - /// This can occur for the root node in an empty graph. - pub fn is_empty(&self) -> bool { - match self { - InnerNodeFact::Empty(hash) => hash._hash::() == HASH_BYTES, - _ => false, - } - } - - pub fn is_binary(&self) -> bool { - matches!(self, InnerNodeFact::Binary(..)) - } - - /// Get the hash of an inner node fact. - pub fn hash(&self) -> Option { - match self { - InnerNodeFact::Empty(empty) => Some(Felt252::from_bytes_be( - empty._hash::().as_slice(), - )), - InnerNodeFact::Binary(binary) => Some(Felt252::from_bytes_be( - binary._hash::().as_slice(), - )), - InnerNodeFact::Edge(edge) => Some(Felt252::from_bytes_be( - edge._hash::().as_slice(), - )), - } - } -} - -/// DBObject implementations -/// Required for DBObject trait -/// Prefixes the key with the type of the object - -impl DBObject for EmptyNode { - fn db_key(suffix: Vec) -> Vec { - patricia_node_db_key(suffix) - } -} - -impl DBObject for BinaryNode { - fn db_key(suffix: Vec) -> Vec { - patricia_node_db_key(suffix) - } -} - -impl DBObject for EdgeNode { - fn db_key(suffix: Vec) -> Vec { - patricia_node_db_key(suffix) - } -} - -fn patricia_node_db_key(suffix: Vec) -> Vec { - let prefix: &[u8] = "patricia_node".as_bytes(); - let sep: &[u8] = ":".as_bytes(); - - [prefix, sep, suffix.as_slice()].concat() -} diff --git a/src/utils/commitment_tree/patricia_tree.rs b/src/utils/commitment_tree/patricia_tree.rs index 67d58ccdf..d0e211256 100644 --- a/src/utils/commitment_tree/patricia_tree.rs +++ b/src/utils/commitment_tree/patricia_tree.rs @@ -1,56 +1,49 @@ use std::collections::HashMap; -use cairo_felt::Felt252; +use starknet::core::types::FieldElement; use crate::{ error::FactTreeError, storage::{FactCheckingContext, Storage}, - utils::hasher::HasherT, }; use super::{ binary_fact_tree::{BinaryFactDict, BinaryFactTree}, - nodes::InnerNodeFact, + leaf_fact::LeafFact, }; -#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct PatriciaTree { - pub root: Felt252, + pub root: FieldElement, pub height: usize, } -impl BinaryFactTree for PatriciaTree { - async fn empty_tree( - &self, - _ffc: FactCheckingContext, - _height: usize, - _leaft_fact: InnerNodeFact, - ) { +impl BinaryFactTree for PatriciaTree { + async fn empty_tree(&self, _ffc: FactCheckingContext, _height: usize, _leaft_fact: L) { todo!() } async fn get_leaves( &self, - _ffc: &FactCheckingContext, - _indices: Vec, + _ffc: FactCheckingContext, + _indices: Vec, _facts: Option, - ) -> HashMap { + ) -> HashMap { todo!() } async fn _get_leaves( &self, - _ffc: &FactCheckingContext, - _indices: Vec, + _ffc: FactCheckingContext, + _indices: Vec, _facts: Option, - ) -> HashMap { + ) -> HashMap { todo!() } async fn update( &self, - _ffc: &FactCheckingContext, - _modifications: HashMap, + _ffc: FactCheckingContext, + _modifications: HashMap, _facts: Option<&mut BinaryFactDict>, ) -> Self { todo!() @@ -58,9 +51,9 @@ impl BinaryFactTree for PatriciaTree { async fn get_leaf( &self, - _ffc: &FactCheckingContext, - _index: Felt252, - ) -> Result { + _ffc: FactCheckingContext, + _index: FieldElement, + ) -> Result { todo!() } } diff --git a/src/utils/definitions/constants.rs b/src/utils/definitions/constants.rs deleted file mode 100644 index 3416e104e..000000000 --- a/src/utils/definitions/constants.rs +++ /dev/null @@ -1,236 +0,0 @@ -use cairo_felt::{FIELD_HIGH, FIELD_LOW}; - -use crate::storage::HASH_BYTES; - -// TODO: Use ruint or types-rs field type - -pub const STARKNET_LANG_DIRECTIVE: &str = "starknet"; - -// TODO: add real value -pub const FIELD_SIZE: u128 = 123456; - -pub const FIELD_SIZE_BITS: usize = 251; -pub const ADDRESS_BITS: usize = FIELD_SIZE_BITS; -pub const CONTRACT_ADDRESS_BITS: usize = ADDRESS_BITS; -pub const NONCE_BITS: usize = FIELD_SIZE_BITS; - -pub const FELT_LOWER_BOUND: u128 = FIELD_LOW; -pub const FELT_UPPER_BOUND: u128 = FIELD_HIGH; -pub const BLOCK_HASH_LOWER_BOUND: u128 = 0; -pub const BLOCK_HASH_UPPER_BOUND: u128 = FIELD_SIZE; - -// Address 0 is reserved to distinguish an external transaction from an inner (L2<>L2) one. -pub const L2_ADDRESS_LOWER_BOUND: u128 = 1; -// The address upper bound is defined to be congruent with the storage var address upper bound (see -// storage.cairo). -// TODO: add real value -// pub const L2_ADDRESS_UPPER_BOUND: u128 = (2u8.pow(CONTRACT_ADDRESS_BITS as u32) - 256u8) as u128; -pub const L2_ADDRESS_UPPER_BOUND: u128 = 0; - -pub const CLASS_HASH_BYTES: [u8; 4] = HASH_BYTES; -pub const CLASS_HASH_UPPER_BOUND: u128 = FIELD_SIZE; - -pub const CONTRACT_STATES_COMMITMENT_TREE_HEIGHT: usize = FIELD_SIZE_BITS; -pub const COMPILED_CLASS_HASH_UPPER_BOUND: usize = FIELD_SIZE_BITS; -pub const COMPILED_CLASS_HASH_COMMITMENT_TREE_HEIGHT: usize = FIELD_SIZE_BITS; - -pub const ENTRY_POINT_FUNCTION_IDX_LOWER_BOUND: u128 = 0; -pub const ENTRY_POINT_FUNCTION_IDX_UPPER_BOUND: u128 = FIELD_SIZE; -pub const ENTRY_POINT_OFFSET_LOWER_BOUND: u128 = 0; -pub const ENTRY_POINT_OFFSET_UPPER_BOUND: u128 = FIELD_SIZE; -pub const ENTRY_POINT_SELECTOR_LOWER_BOUND: u128 = 0; -pub const ENTRY_POINT_SELECTOR_UPPER_BOUND: u128 = FIELD_SIZE; - -pub const EVENT_COMMITMENT_TREE_HEIGHT: usize = 64; -pub const FEE_LOWER_BOUND: u128 = 0; -// pub const FEE_UPPER_BOUND: u128 = 2u8.pow(128) as u128; -pub const FEE_UPPER_BOUND: u128 = 0; - -// Default hash to fill the parent_hash field of the first block in the sequence. -pub const GENESIS_PARENT_BLOCK_HASH: u128 = 0; -pub const GAS_PRICE_LOWER_BOUND: u128 = 0; -// pub const GAS_PRICE_UPPER_BOUND: u128 = 2u8.pow(128) as u128; -pub const GAS_PRICE_UPPER_BOUND: u128 = 0; - -pub const MAX_MESSAGE_TO_L1_LENGTH: usize = 100; -pub const NONCE_LOWER_BOUND: u128 = 0; -// pub const NONCE_UPPER_BOUND: u128 = 2u8.pow(NONCE_BITS as u32) as u128; -pub const NONCE_UPPER_BOUND: u128 = 0; - -pub const SIERRA_ARRAY_LEN_BOUND: usize = 2usize.pow(32); -pub const SYSCALL_SELECTOR_UPPER_BOUND: u128 = FIELD_SIZE; - -pub const TRANSACTION_COMMITMENT_TREE_HEIGHT: usize = 64; -pub const TRANSACTION_HASH_LOWER_BOUND: u128 = 0; -pub const TRANSACTION_HASH_UPPER_BOUND: u128 = FIELD_SIZE; -pub const TRANSACTION_VERSION_LOWER_BOUND: u128 = 0; -pub const TRANSACTION_VERSION_UPPER_BOUND: u128 = FIELD_SIZE; - -pub const ADDRESS_LOWER_BOUND: u128 = 0; -// pub const ADDRESS_UPPER_BOUND: u128 = 2u8.pow(ADDRESS_BITS as u32) as u128; -pub const ADDRESS_UPPER_BOUND: u128 = 0; - -pub const UNINITIALIZED_CLASS_HASH: [u8; 4] = HASH_BYTES; - -// In order to identify transactions from unsupported versions. -pub const TRANSACTION_VERSION: u8 = 1; -// The version is considered 0 for L1-Handler transaction hash calculation purposes. -pub const L1_HANDLER_VERSION: u8 = 0; -// Indentation for transactions meant to query and not addressed to the OS. -pub const DECLARE_VERSION: u8 = 2; -// pub const QUERY_VERSION_BASE: u128 = 2u8.pow(128) as u128; -pub const QUERY_VERSION_BASE: u128 = 0; -pub const QUERY_VERSION: u128 = QUERY_VERSION_BASE + TRANSACTION_VERSION as u128; -pub const QUERY_DECLARE_VERSION: u128 = QUERY_VERSION_BASE + DECLARE_VERSION as u128; -pub const DEPRECATED_DECLARE_VERSIONS: [u128; 4] = - [0, 1, QUERY_VERSION_BASE, QUERY_VERSION_BASE + 1]; - -// Sierra -> Casm compilation version. -pub const SIERRA_VERSION: [u8; 3] = [1, 3, 0]; -// Contract classes with sierra version older than MIN_SIERRA_VERSION are not supported. -pub const MIN_SIERRA_VERSION: [u8; 3] = [1, 1, 0]; - -// The version of contract class leaf. -pub const CONTRACT_CLASS_LEAF_VERSION: &[u8] = b"CONTRACT_CLASS_LEAF_V0"; - -// The version of the Starknet global state. -pub const GLOBAL_STATE_VERSION: &[u8] = b"STARKNET_STATE_V0"; - -// The version of a compiled class. -pub const COMPILED_CLASS_VERSION: &[u8] = b"COMPILED_CLASS_V1"; - -// State diff commitment. -pub const BLOCK_SIGNATURE_VERSION: u8 = 0; - -// OS-related constants. -pub const L1_TO_L2_MSG_HEADER_SIZE: usize = 5; -pub const L2_TO_L1_MSG_HEADER_SIZE: usize = 3; -pub const CLASS_UPDATE_SIZE: usize = 1; - -// OS reserved contract addresses. -pub const ORIGIN_ADDRESS: u128 = 0; -pub const BLOCK_HASH_CONTRACT_ADDRESS: u128 = 1; -pub const OS_RESERVED_CONTRACT_ADDRESSES: [u128; 2] = [ORIGIN_ADDRESS, BLOCK_HASH_CONTRACT_ADDRESS]; - -// StarkNet solidity contract-related constants. -pub const N_DEFAULT_TOPICS: usize = 1; // Events have one default topic. - // Excluding the default topic. -pub const LOG_MSG_TO_L1_N_TOPICS: usize = 2; -pub const CONSUMED_MSG_TO_L2_N_TOPICS: usize = 3; -// The headers include the payload size, so we need to add +1 since arrays are encoded with two -// additional parameters (offset and length) in solidity. -pub const LOG_MSG_TO_L1_ENCODED_DATA_SIZE: usize = - (L2_TO_L1_MSG_HEADER_SIZE + 1) - LOG_MSG_TO_L1_N_TOPICS; -pub const CONSUMED_MSG_TO_L2_ENCODED_DATA_SIZE: usize = - (L1_TO_L2_MSG_HEADER_SIZE + 1) - CONSUMED_MSG_TO_L2_N_TOPICS; - -// The (empirical) L1 gas cost of each Cairo step. -pub const N_STEPS_FEE_WEIGHT: f64 = 0.01; - -// Expected return values of a 'validate' entry point. -pub const VALIDATE_RETDATA: &[u8] = b"VALID"; - -// The block number -> block hash mapping is written for the current block number minus this number. -pub const STORED_BLOCK_HASH_BUFFER: u8 = 10; - -pub enum OsOutputConstant { - MerkleUpdateOffset = 0, - BlockNumberOffset = 2, - BlockHashOffset = 3, - ConfigHashOffset = 4, - HeaderSize = 5, -} - -const STEP: u128 = 100; -const RANGE_CHECK: u128 = 70; -const INITIAL: u128 = 10u128.pow(8) * STEP; -const SYSCALL_BASE: u128 = 100 * STEP; -const ENTRY_POINT_INITIAL_BUDGET: u128 = 100 * STEP; -const ENTRY_POINT: u128 = ENTRY_POINT_INITIAL_BUDGET + 500 * STEP; -const FEE_TRANSFER: u128 = ENTRY_POINT + 100 * STEP; -const TRANSACTION: u128 = (2 * ENTRY_POINT_INITIAL_BUDGET) + FEE_TRANSFER + (100 * STEP); -const CALL_CONTRACT: u128 = SYSCALL_BASE + 10 * STEP + ENTRY_POINT; -const DEPLOY: u128 = SYSCALL_BASE + 200 * STEP + ENTRY_POINT; -const GET_BLOCK_HASH: u128 = SYSCALL_BASE + 50 * STEP; -const GET_EXECUTION_INFO: u128 = SYSCALL_BASE + 10 * STEP; -const SECP256K1_ADD: u128 = SYSCALL_BASE + 254 * STEP + 29 * RANGE_CHECK; -const SECP256K1_GET_POINT_FROM_X: u128 = SYSCALL_BASE + 260 * STEP + 30 * RANGE_CHECK; -const SECP256K1_GET_XY: u128 = SYSCALL_BASE + 24 * STEP + 9 * RANGE_CHECK; -const SECP256K1_MUL: u128 = SYSCALL_BASE + 121810 * STEP + 10739 * RANGE_CHECK; -const SECP256K1_NEW: u128 = SYSCALL_BASE + 340 * STEP + 36 * RANGE_CHECK; -const KECCAK: u128 = SYSCALL_BASE; -const KECCAK_ROUND_COST: u128 = 180000; -const LIBRARY_CALL: u128 = CALL_CONTRACT; -const REPLACE_CLASS: u128 = SYSCALL_BASE + 50 * STEP; -const STORAGE_READ: u128 = SYSCALL_BASE + 50 * STEP; -const STORAGE_WRITE: u128 = SYSCALL_BASE + 50 * STEP; -const EMIT_EVENT: u128 = SYSCALL_BASE + 10 * STEP; -const SEND_MESSAGE_TO_L1: u128 = SYSCALL_BASE + 50 * STEP; - -pub struct GasCost { - pub step: u128, - pub range_check: u128, - pub initial: u128, - pub syscall_base: u128, - pub entry_point_initial_budget: u128, - pub entry_point: u128, - pub fee_transfer: u128, - pub transaction: u128, - pub call_contract: u128, - pub deploy: u128, - pub get_block_hash: u128, - pub get_execution_info: u128, - pub secp256k1_add: u128, - pub secp256k1_get_point_from_x: u128, - pub secp256k1_get_xy: u128, - pub secp256k1_mul: u128, - pub secp256k1_new: u128, - pub keccak: u128, - pub keccak_round_cost: u128, - pub library_call: u128, - pub replace_class: u128, - pub storage_read: u128, - pub storage_write: u128, - pub emit_event: u128, - pub send_message_to_l1: u128, - pub n_steps_fee_weight: f64, -} - -impl GasCost { - pub fn new() -> Self { - Self { - step: STEP, - range_check: RANGE_CHECK, - initial: INITIAL, - syscall_base: SYSCALL_BASE, - entry_point_initial_budget: ENTRY_POINT_INITIAL_BUDGET, - entry_point: ENTRY_POINT, - fee_transfer: FEE_TRANSFER, - transaction: TRANSACTION, - call_contract: CALL_CONTRACT, - deploy: DEPLOY, - get_block_hash: GET_BLOCK_HASH, - get_execution_info: GET_EXECUTION_INFO, - secp256k1_add: SECP256K1_ADD, - secp256k1_get_point_from_x: SECP256K1_GET_POINT_FROM_X, - secp256k1_get_xy: SECP256K1_GET_XY, - secp256k1_mul: SECP256K1_MUL, - secp256k1_new: SECP256K1_NEW, - keccak: KECCAK, - keccak_round_cost: KECCAK_ROUND_COST, - library_call: LIBRARY_CALL, - replace_class: REPLACE_CLASS, - storage_read: STORAGE_READ, - storage_write: STORAGE_WRITE, - emit_event: EMIT_EVENT, - send_message_to_l1: SEND_MESSAGE_TO_L1, - n_steps_fee_weight: N_STEPS_FEE_WEIGHT, - } - } -} - -impl Default for GasCost { - fn default() -> Self { - Self::new() - } -} diff --git a/src/utils/definitions/general_config.rs b/src/utils/definitions/general_config.rs deleted file mode 100644 index 5e602ff89..000000000 --- a/src/utils/definitions/general_config.rs +++ /dev/null @@ -1,92 +0,0 @@ -use cairo_felt::Felt252; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use tokio::sync::OnceCell; - -use super::constants; - -const _GENERAL_CONFIG_FILE_NAME: &str = "general_config.yml"; -const _N_STEPS_RESOURCE: &str = "n_steps"; -// const DEFAULT_CHAIN_ID: Felt252 = Felt252::new(0); // Fix this - -// Default configuration values. - -pub const DEFAULT_VALIDATE_MAX_STEPS: usize = 10usize.pow(6); -pub const DEFAULT_TX_MAX_STEPS: usize = 3 * 10usize.pow(6); -pub const DEFAULT_ENFORCE_L1_FEE: bool = true; - -// Given in units of wei -pub const DEFAULT_GAS_PRICE: usize = 10usize.pow(8); - -#[derive(Debug, Serialize, Deserialize)] -struct StarknetOsConfig { - chain_id: Felt252, - fee_token_address: Felt252, -} - -// TODO: add real values -impl Default for StarknetOsConfig { - fn default() -> Self { - StarknetOsConfig { - chain_id: Felt252::new(0), - fee_token_address: Felt252::new(0), - } - } -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct StarknetGeneralConfig { - starknet_os_config: StarknetOsConfig, - contract_storage_commitment_tree_height: usize, - compiled_class_hash_commitment_tree_height: usize, - global_state_commitment_tree_height: usize, - invoke_tx_max_n_steps: usize, - validate_max_n_steps: usize, - min_gas_price: usize, - constant_gas_price: bool, - sequencer_address: Felt252, - tx_commitment_tree_height: usize, - event_commitment_tree_height: usize, - cairo_resource_fee_weights: HashMap, - enforce_l1_handler_fee: bool, -} - -pub static CONFIG: OnceCell = OnceCell::const_new(); - -impl Default for StarknetGeneralConfig { - fn default() -> Self { - StarknetGeneralConfig { - starknet_os_config: StarknetOsConfig::default(), - contract_storage_commitment_tree_height: - constants::CONTRACT_STATES_COMMITMENT_TREE_HEIGHT, - compiled_class_hash_commitment_tree_height: - constants::COMPILED_CLASS_HASH_COMMITMENT_TREE_HEIGHT, - global_state_commitment_tree_height: constants::CONTRACT_ADDRESS_BITS, - invoke_tx_max_n_steps: DEFAULT_TX_MAX_STEPS, - validate_max_n_steps: DEFAULT_VALIDATE_MAX_STEPS, - min_gas_price: DEFAULT_GAS_PRICE, - constant_gas_price: false, - sequencer_address: Felt252::new(0), // TODO: Add real value - tx_commitment_tree_height: constants::TRANSACTION_COMMITMENT_TREE_HEIGHT, - event_commitment_tree_height: constants::EVENT_COMMITMENT_TREE_HEIGHT, - cairo_resource_fee_weights: HashMap::default(), // TODO: Add builtins module - enforce_l1_handler_fee: DEFAULT_ENFORCE_L1_FEE, - } - } -} - -impl StarknetGeneralConfig { - fn _chain_id(&self) -> Felt252 { - self.starknet_os_config.chain_id.clone() - } - - fn _fee_token_address(&self) -> Felt252 { - self.starknet_os_config.fee_token_address.clone() - } -} - -#[allow(unused)] -pub fn build_general_config(raw_general_config: HashMap) -> StarknetGeneralConfig { - // ... logic to build the general config ... - StarknetGeneralConfig::default() -} diff --git a/src/utils/definitions/mod.rs b/src/utils/definitions/mod.rs deleted file mode 100644 index 233975aa1..000000000 --- a/src/utils/definitions/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod constants; -pub mod general_config; diff --git a/src/utils/hasher/mod.rs b/src/utils/hasher/mod.rs deleted file mode 100644 index eeeb84be9..000000000 --- a/src/utils/hasher/mod.rs +++ /dev/null @@ -1,40 +0,0 @@ -use cairo_felt::Felt252; - -pub mod pedersen; - -/// A trait for hashing. -pub trait HasherT { - /// Hashes the given data. - /// # Arguments - /// * `data` - The data to hash. - /// # Returns - /// The hash of the data. - fn hash_bytes(data: &[u8]) -> Felt252; - - /// Hashes the 2 felts sent. - /// - /// # Arguments - /// - /// * `a` - First element to hash. - /// * `b` - Second element to hash. - /// - /// # Returns - /// - /// The hash of the 2 values. - fn hash_elements(a: Felt252, b: Felt252) -> Felt252; - - /// Computes a hash chain over the data, in the following order: - /// h(h(h(h(0, data\[0\]), data\[1\]), ...), data\[n-1\]), n). - /// The hash is initialized with 0 and ends with the data length appended. - /// The length is appended in order to avoid collisions of the following kind: - /// H(\[x,y,z\]) = h(h(x,y),z) = H(\[w, z\]) where w = h(x,y). - /// - /// # Arguments - /// - /// * `elements` - The array to hash. - /// - /// # Returns - /// - /// The hash of the array. - fn compute_hash_on_elements(elements: &[Felt252]) -> Felt252; -} diff --git a/src/utils/hasher/pedersen.rs b/src/utils/hasher/pedersen.rs deleted file mode 100644 index 2016e0f9b..000000000 --- a/src/utils/hasher/pedersen.rs +++ /dev/null @@ -1,87 +0,0 @@ -use super::HasherT; -use cairo_felt::Felt252; -/// The Pedersen hasher. -#[derive(Clone, Copy)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct PedersenHasher; - -/// The Pedersen hasher implementation. -impl HasherT for PedersenHasher { - /// The Pedersen hash function. - /// # Arguments - /// * `data` - The data to hash. - /// # Returns - /// The hash of the data. - fn hash_bytes(data: &[u8]) -> Felt252 { - // Calculate the number of 31-byte chunks we'll need, rounding up. - // (1 byte is used padding to prevent the value of field from being greater than the field's - // modulus) TODO: It is need a way to truncate bytes to fit into values smaller than modular - // (for optimization) - const CHUNK_SIZE: usize = 31; - let mut hash_value = Felt252::new(0); - - for chunk in data.chunks(CHUNK_SIZE) { - // It is safe to unwrap here because we know that the chunk size is 31 and the value can not - // overflow than the field's modulus value. In more detail, the Felt252 Maximum value is 2^251 - // + 17 * 2^192. So the chunk (31 bytes is 248 bits) is smaller than the maximum value (== 2^248 - 1 - // < 2^251 + 17 * 2^192). So it is safe to unwrap here. - let _field_element = Felt252::from_bytes_be(chunk); - // TODO: use lambdaworks - // hash_value = pedersen_hash(&hash_value, &field_element); - hash_value = Felt252::new(0); - } - - hash_value - } - - #[inline(always)] - fn hash_elements(_a: Felt252, _b: Felt252) -> Felt252 { - // TODO: use impl from lambdaworks pedersen_hash(&a, &b) - Felt252::new(0) - } - - /// Compute hash on elements, taken from [starknet-rs](https://github.com/xJonathanLEI/starknet-rs/blob/master/starknet-core/src/crypto.rs#L25) pending a no_std support. - /// - /// # Arguments - /// - /// * `elements` - The elements to hash. - /// - /// # Returns - /// - /// h(h(h(h(0, data\[0\]), data\[1\]), ...), data\[n-1\]), n). - #[inline] - fn compute_hash_on_elements(_elements: &[Felt252]) -> Felt252 { - // TODO: use impl from lambdaworks compute_hash_on_elements(elements) - Felt252::new(0) - } -} - -// #[test] -// fn dynamic_string_hashing() { -// use std::str::FromStr; - -// let message = "Hello, madara!!. It is pedersen hash.".to_string(); // 37 bytes -// let message = message.as_bytes(); -// let hash_value = PedersenHasher::hash_bytes(message); - -// assert_eq!( -// hash_value, -// Felt252::from_str("0x03501abfd0e0606ecab6702213a03294b81837e4d48232df3c39a62b88cc6f73") -// .unwrap() -// ); -// } - -// #[test] -// fn short_string_hashing() { -// use std::str::FromStr; - -// let message = "madara".to_string(); -// let message = message.as_bytes(); -// let hash_value = PedersenHasher::hash_bytes(message); - -// assert_eq!( -// hash_value, -// Felt252::from_str("0x04b1b68d0622d978edcef1071b697f003896a8f432d4d5523a2f72ec812591f8") -// .unwrap() -// ); -// } diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 01436eed4..ddcaedbb5 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,3 +1 @@ pub mod commitment_tree; -pub mod definitions; -pub mod hasher;