Skip to content

Commit

Permalink
replaced felts and hashers with types-core types (#137)
Browse files Browse the repository at this point in the history
Co-authored-by: jbcaron <[email protected]>
  • Loading branch information
antiyro and jbcaron authored Jun 6, 2024
1 parent 244831c commit f82d2bd
Show file tree
Hide file tree
Showing 12 changed files with 274 additions and 205 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Next release

- fix(hashers): cleaned hashers using types core hashers and Felt
- refactor: remove substrate block storage
- feat(infra): Added boilerplate to deploy a grafana/prometheus dashboard
- refacor: use db hash
Expand Down
4 changes: 1 addition & 3 deletions crates/client/db/src/storage_handler/class_trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::sync::{RwLockReadGuard, RwLockWriteGuard};
use bonsai_trie::id::BasicId;
use bonsai_trie::BonsaiStorage;
use starknet_api::core::ClassHash;
use starknet_ff::FieldElement;
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::Poseidon;

Expand Down Expand Up @@ -72,10 +71,9 @@ impl ClassTrieViewMut<'_> {
self.0.root_hash(bonsai_identifier::CLASS).map_err(|_| DeoxysStorageError::TrieRootError(TrieType::Class))
}

pub fn update(&mut self, updates: Vec<(&ClassHash, FieldElement)>) -> Result<(), DeoxysStorageError> {
pub fn update(&mut self, updates: Vec<(&ClassHash, Felt)>) -> Result<(), DeoxysStorageError> {
for (key, value) in updates {
let key = conv_class_key(key);
let value = Felt::from_bytes_be(&value.to_bytes_be());
self.0
.insert(bonsai_identifier::CLASS, &key, &value)
.map_err(|_| DeoxysStorageError::StorageInsertionError(StorageType::Class))?;
Expand Down
23 changes: 9 additions & 14 deletions crates/client/sync/src/commitments/classes.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
use blockifier::state::cached_state::CommitmentStateDiff;
use mc_db::storage_handler::{self, DeoxysStorageError};
use mp_felt::Felt252Wrapper;
use mp_hashers::poseidon::PoseidonHasher;
use mp_hashers::HasherT;
use rayon::prelude::*;
use starknet_ff::FieldElement;
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::{Poseidon, StarkHash};

// "CONTRACT_CLASS_LEAF_V0"
const CONTRACT_CLASS_HASH_VERSION: FieldElement =
FieldElement::from_mont([9331882290187415277, 12057587991035439952, 18444375821049509847, 115292049744600508]);
const CONTRACT_CLASS_HASH_VERSION: Felt =
Felt::from_raw([115292049744600508, 18444375821049509847, 12057587991035439952, 9331882290187415277]);

/// Calculates the class trie root
///
Expand All @@ -21,17 +19,17 @@ const CONTRACT_CLASS_HASH_VERSION: FieldElement =
/// # Returns
///
/// The class root.
pub fn class_trie_root(csd: &CommitmentStateDiff, block_number: u64) -> Result<Felt252Wrapper, DeoxysStorageError> {
pub fn class_trie_root(csd: &CommitmentStateDiff, block_number: u64) -> Result<Felt, DeoxysStorageError> {
let mut handler_class = storage_handler::class_trie_mut();

let updates = csd
.class_hash_to_compiled_class_hash
.iter()
.par_bridge()
.map(|(class_hash, compiled_class_hash)| {
let compiled_class_hash = FieldElement::from_bytes_be(&compiled_class_hash.0.0).unwrap();
let compiled_class_hash = Felt::from_bytes_be(&compiled_class_hash.0.0);

let hash = PoseidonHasher::hash_elements(CONTRACT_CLASS_HASH_VERSION, compiled_class_hash);
let hash = Poseidon::hash(&CONTRACT_CLASS_HASH_VERSION, &compiled_class_hash);

(class_hash, hash)
})
Expand All @@ -41,7 +39,7 @@ pub fn class_trie_root(csd: &CommitmentStateDiff, block_number: u64) -> Result<F
handler_class.update(updates)?;
handler_class.commit(block_number)?;

Ok(handler_class.root()?.into())
handler_class.root()
}

#[cfg(test)]
Expand All @@ -50,9 +48,6 @@ mod tests {

#[test]
fn test_contract_class_hash_version() {
assert_eq!(
CONTRACT_CLASS_HASH_VERSION,
FieldElement::from_byte_slice_be("CONTRACT_CLASS_LEAF_V0".as_bytes()).unwrap(),
);
assert_eq!(CONTRACT_CLASS_HASH_VERSION, Felt::from_bytes_be_slice("CONTRACT_CLASS_LEAF_V0".as_bytes()));
}
}
23 changes: 9 additions & 14 deletions crates/client/sync/src/commitments/contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@ use std::collections::HashSet;

use blockifier::state::cached_state::CommitmentStateDiff;
use mc_db::storage_handler::{self, DeoxysStorageError, StorageView};
use mp_felt::Felt252Wrapper;
use mp_hashers::pedersen::PedersenHasher;
use mp_hashers::HasherT;
use rayon::prelude::*;
use starknet_api::core::ContractAddress;
use starknet_ff::FieldElement;
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::{Pedersen, StarkHash};

/// Calculates the contract trie root
///
Expand All @@ -20,7 +17,7 @@ use starknet_types_core::felt::Felt;
/// # Returns
///
/// The contract root.
pub fn contract_trie_root(csd: &CommitmentStateDiff, block_number: u64) -> Result<Felt252Wrapper, DeoxysStorageError> {
pub fn contract_trie_root(csd: &CommitmentStateDiff, block_number: u64) -> Result<Felt, DeoxysStorageError> {
// NOTE: handlers implicitely acquire a lock on their respective tries
// for the duration of their livetimes
let mut handler_contract = storage_handler::contract_trie_mut();
Expand Down Expand Up @@ -73,7 +70,7 @@ pub fn contract_trie_root(csd: &CommitmentStateDiff, block_number: u64) -> Resul
handler_contract.update(updates)?;
handler_contract.commit(block_number)?;

Ok(handler_contract.root()?.into())
handler_contract.root()
}

/// Computes the contract state leaf hash
Expand All @@ -94,14 +91,12 @@ fn contract_state_leaf_hash(
) -> Result<Felt, DeoxysStorageError> {
let (class_hash, nonce) = class_hash_and_nonce(csd, contract_address)?;

let storage_root = FieldElement::from_bytes_be(&storage_root.to_bytes_be()).unwrap();

// computes the contract state leaf hash
let contract_state_hash = PedersenHasher::hash_elements(class_hash, storage_root);
let contract_state_hash = PedersenHasher::hash_elements(contract_state_hash, nonce);
let contract_state_hash = PedersenHasher::hash_elements(contract_state_hash, FieldElement::ZERO);
let contract_state_hash = Pedersen::hash(&class_hash, &storage_root);
let contract_state_hash = Pedersen::hash(&contract_state_hash, &nonce);
let contract_state_hash = Pedersen::hash(&contract_state_hash, &Felt::ZERO);

Ok(Felt::from_bytes_be(&contract_state_hash.to_bytes_be()))
Ok(contract_state_hash)
}

/// Retrieves the class hash and nonce of a contract address
Expand All @@ -117,7 +112,7 @@ fn contract_state_leaf_hash(
fn class_hash_and_nonce(
csd: &CommitmentStateDiff,
contract_address: &ContractAddress,
) -> Result<(FieldElement, FieldElement), DeoxysStorageError> {
) -> Result<(Felt, Felt), DeoxysStorageError> {
let class_hash = match csd.address_to_class_hash.get(contract_address) {
Some(class_hash) => *class_hash,
None => storage_handler::contract_class_hash().get(contract_address)?.unwrap_or_default(),
Expand All @@ -126,5 +121,5 @@ fn class_hash_and_nonce(
Some(nonce) => *nonce,
None => storage_handler::contract_nonces().get(contract_address)?.unwrap_or_default(),
};
Ok((FieldElement::from_bytes_be(&class_hash.0.0).unwrap(), FieldElement::from_bytes_be(&nonce.0.0).unwrap()))
Ok((Felt::from_bytes_be(&class_hash.0.0), Felt::from_bytes_be(&nonce.0.0)))
}
46 changes: 15 additions & 31 deletions crates/client/sync/src/commitments/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,10 @@ use bonsai_trie::databases::HashMapDb;
use bonsai_trie::id::{BasicId, BasicIdBuilder};
use bonsai_trie::{BonsaiStorage, BonsaiStorageConfig};
use mc_db::storage_handler::bonsai_identifier;
use mp_felt::Felt252Wrapper;
use mp_hashers::pedersen::PedersenHasher;
use mp_hashers::HasherT;
use rayon::prelude::*;
use starknet_api::transaction::Event;
use starknet_ff::FieldElement;
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::Pedersen;
use starknet_types_core::hash::{Pedersen, StarkHash};

/// Calculate the hash of the event.
///
Expand All @@ -20,33 +16,22 @@ use starknet_types_core::hash::Pedersen;
///
/// # Returns
///
/// The event hash as `FieldElement`.
pub fn calculate_event_hash<H: HasherT>(event: &Event) -> FieldElement {
/// The event hash as `Felt`.
pub fn calculate_event_hash(event: &Event) -> Felt {
let (keys_hash, data_hash) = rayon::join(
|| {
H::compute_hash_on_elements(
&event
.content
.keys
.iter()
.map(|key| FieldElement::from(Felt252Wrapper::from(key.0)))
.collect::<Vec<FieldElement>>(),
Pedersen::hash_array(
&event.content.keys.iter().map(|key| Felt::from_bytes_be(&key.0.0)).collect::<Vec<Felt>>(),
)
},
|| {
H::compute_hash_on_elements(
&event
.content
.data
.0
.iter()
.map(|data| FieldElement::from(Felt252Wrapper::from(*data)))
.collect::<Vec<FieldElement>>(),
Pedersen::hash_array(
&event.content.data.0.iter().map(|data| Felt::from_bytes_be(&data.0)).collect::<Vec<Felt>>(),
)
},
);
let from_address = FieldElement::from(Felt252Wrapper::from(event.from_address.0.0));
H::compute_hash_on_elements(&[from_address, keys_hash, data_hash])
let from_address = Felt::from_bytes_be(&event.from_address.0.0.0);
Pedersen::hash_array(&[from_address, keys_hash, data_hash])
}

/// Calculate the event commitment in memory using HashMapDb (which is more efficient for this
Expand All @@ -58,11 +43,10 @@ pub fn calculate_event_hash<H: HasherT>(event: &Event) -> FieldElement {
///
/// # Returns
///
/// The event commitment as `Felt252Wrapper`.
pub fn memory_event_commitment(events: &[Event]) -> Result<Felt252Wrapper, String> {
// TODO @cchudant refacto/optimise this function
/// The event commitment as `Felt`.
pub fn memory_event_commitment(events: &[Event]) -> Result<Felt, String> {
if events.is_empty() {
return Ok(Felt252Wrapper::ZERO);
return Ok(Felt::ZERO);
}

let config = BonsaiStorageConfig::default();
Expand All @@ -72,12 +56,12 @@ pub fn memory_event_commitment(events: &[Event]) -> Result<Felt252Wrapper, Strin
let identifier = bonsai_identifier::EVENT;

// event hashes are computed in parallel
let events = events.par_iter().map(calculate_event_hash::<PedersenHasher>).collect::<Vec<_>>();
let events = events.par_iter().map(calculate_event_hash).collect::<Vec<_>>();

// once event hashes have finished computing, they are inserted into the local Bonsai db
for (i, event_hash) in events.into_iter().enumerate() {
let key = BitVec::from_vec(i.to_be_bytes().to_vec());
let value = Felt::from(Felt252Wrapper::from(event_hash));
let value = event_hash;
bonsai_storage.insert(identifier, key.as_bitslice(), &value).expect("Failed to insert into bonsai storage");
}

Expand All @@ -93,5 +77,5 @@ pub fn memory_event_commitment(events: &[Event]) -> Result<Felt252Wrapper, Strin
bonsai_storage.commit(id).expect("Failed to commit to bonsai storage");
let root_hash = bonsai_storage.root_hash(identifier).expect("Failed to get root hash");

Ok(Felt252Wrapper::from(root_hash))
Ok(root_hash)
}
Loading

0 comments on commit f82d2bd

Please sign in to comment.