Skip to content
This repository has been archived by the owner on Aug 2, 2024. It is now read-only.

Commit

Permalink
feat: removing generic hasher from block hash computation, using pede…
Browse files Browse the repository at this point in the history
…rsen -… (#1583)
  • Loading branch information
elielnfinic authored May 7, 2024
1 parent fb909ad commit 674c97b
Show file tree
Hide file tree
Showing 13 changed files with 38 additions and 70 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
- feat(runtime): moved StarkEvents from Substrate
- feat(rpc/trace_api): add `trace_transaction`
- fix(docker): fix dockerfile for `madara-node`
- feat: Remove generic hasher from block hash computation

## v0.7.0

Expand Down
11 changes: 3 additions & 8 deletions crates/client/commitment-state-diff/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ pub struct BlockDAData {
pub state_diff: ThinStateDiff,
pub num_addr_accessed: usize,
pub block_number: u64,
pub config_hash: StarkHash,
pub new_state_root: StarkHash,
pub previous_state_root: StarkHash,
}
Expand Down Expand Up @@ -76,7 +75,7 @@ where
Poll::Ready(Some(storage_notification)) => {
let block_hash = storage_notification.block;

match build_commitment_state_diff::<B, C, H>(
match build_commitment_state_diff::<B, C>(
self_as_mut.client.clone(),
self_as_mut.backend.clone(),
storage_notification,
Expand Down Expand Up @@ -137,7 +136,7 @@ enum BuildCommitmentStateDiffError {
FailedToGetConfigHash(#[from] sp_api::ApiError),
}

fn build_commitment_state_diff<B: BlockT, C, H>(
fn build_commitment_state_diff<B: BlockT, C>(
client: Arc<C>,
backend: Arc<mc_db::Backend<B>>,
storage_notification: StorageNotification<B::Hash>,
Expand All @@ -146,7 +145,6 @@ where
C: ProvideRuntimeApi<B>,
C::Api: StarknetRuntimeApi<B>,
C: HeaderBackend<B>,
H: HasherT,
{
let mut accessed_addrs: IndexSet<ContractAddress> = IndexSet::new();
let mut commitment_state_diff = ThinStateDiff {
Expand Down Expand Up @@ -232,14 +230,11 @@ where
mp_digest_log::find_starknet_block(digest)?
};

let config_hash = client.runtime_api().config_hash(storage_notification.block)?;

Ok(BlockDAData {
block_hash: current_block.header().hash::<H>().into(),
block_hash: current_block.header().hash().into(),
state_diff: commitment_state_diff,
num_addr_accessed: accessed_addrs.len(),
block_number: current_block.header().block_number,
config_hash,
// TODO: fix when we implement state root
new_state_root: backend.temporary_global_state_root_getter(),
previous_state_root: backend.temporary_global_state_root_getter(),
Expand Down
2 changes: 1 addition & 1 deletion crates/client/mapping-sync/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ where
if fire {
self.inner_delay = None;

match sync_blocks::sync_blocks::<_, _, _, H>(
match sync_blocks::sync_blocks::<_, _, _>(
self.client.as_ref(),
self.substrate_backend.as_ref(),
self.madara_backend.as_ref(),
Expand Down
29 changes: 10 additions & 19 deletions crates/client/mapping-sync/src/sync_blocks.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use mc_rpc_core::utils::get_block_by_block_hash;
use mp_digest_log::{find_starknet_block, FindLogError};
use mp_hashers::HasherT;
use mp_transactions::get_transaction_hash;
use num_traits::FromPrimitive;
use pallet_starknet_runtime_api::StarknetRuntimeApi;
Expand All @@ -12,7 +11,7 @@ use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Zero};

use crate::block_metrics::BlockMetrics;

fn sync_block<B: BlockT, C, BE, H>(
fn sync_block<B: BlockT, C, BE>(
client: &C,
backend: &mc_db::Backend<B>,
header: &B::Header,
Expand All @@ -23,7 +22,6 @@ where
C: ProvideRuntimeApi<B>,
C::Api: StarknetRuntimeApi<B>,
BE: Backend<B>,
H: HasherT,
{
// Before storing the new block in the Madara backend database, we want to make sure that the
// wrapped Starknet block it contains is the same that we can find in the storage at this height.
Expand All @@ -36,8 +34,8 @@ where
let opt_storage_starknet_block = get_block_by_block_hash(client, substrate_block_hash);
match opt_storage_starknet_block {
Ok(storage_starknet_block) => {
let digest_starknet_block_hash = digest_starknet_block.header().hash::<H>();
let storage_starknet_block_hash = storage_starknet_block.header().hash::<H>();
let digest_starknet_block_hash = digest_starknet_block.header().hash();
let storage_starknet_block_hash = storage_starknet_block.header().hash();
// Ensure the two blocks sources (chain storage and block digest) agree on the block content
if digest_starknet_block_hash != storage_starknet_block_hash {
Err(anyhow::anyhow!(
Expand Down Expand Up @@ -100,15 +98,10 @@ where
}
}

fn sync_genesis_block<B: BlockT, C, H>(
_client: &C,
backend: &mc_db::Backend<B>,
header: &B::Header,
) -> anyhow::Result<()>
fn sync_genesis_block<B: BlockT, C>(_client: &C, backend: &mc_db::Backend<B>, header: &B::Header) -> anyhow::Result<()>
where
C: HeaderBackend<B>,
B: BlockT,
H: HasherT,
{
let substrate_block_hash = header.hash();

Expand All @@ -119,7 +112,7 @@ where
}
Err(FindLogError::MultipleLogs) => return Err(anyhow::anyhow!("Multiple logs found")),
};
let block_hash = block.header().hash::<H>();
let block_hash = block.header().hash();
let mapping_commitment = mc_db::MappingCommitment::<B> {
block_hash: substrate_block_hash,
starknet_block_hash: block_hash.into(),
Expand All @@ -131,7 +124,7 @@ where
Ok(())
}

fn sync_one_block<B: BlockT, C, BE, H>(
fn sync_one_block<B: BlockT, C, BE>(
client: &C,
substrate_backend: &BE,
madara_backend: &mc_db::Backend<B>,
Expand All @@ -143,7 +136,6 @@ where
C::Api: StarknetRuntimeApi<B>,
C: HeaderBackend<B> + StorageProvider<B, BE>,
BE: Backend<B>,
H: HasherT,
{
let mut current_syncing_tips = madara_backend.meta().current_syncing_tips()?;

Expand Down Expand Up @@ -173,20 +165,20 @@ where
};

if operating_header.number() == &Zero::zero() {
sync_genesis_block::<_, _, H>(client, madara_backend, &operating_header)?;
sync_genesis_block::<_, _>(client, madara_backend, &operating_header)?;

madara_backend.meta().write_current_syncing_tips(current_syncing_tips)?;
Ok(true)
} else {
sync_block::<_, _, _, H>(client, madara_backend, &operating_header, block_metrics)?;
sync_block::<_, _, _>(client, madara_backend, &operating_header, block_metrics)?;

current_syncing_tips.push(*operating_header.parent_hash());
madara_backend.meta().write_current_syncing_tips(current_syncing_tips)?;
Ok(true)
}
}

pub fn sync_blocks<B: BlockT, C, BE, H>(
pub fn sync_blocks<B: BlockT, C, BE>(
client: &C,
substrate_backend: &BE,
madara_backend: &mc_db::Backend<B>,
Expand All @@ -199,13 +191,12 @@ where
C::Api: StarknetRuntimeApi<B>,
C: HeaderBackend<B> + StorageProvider<B, BE>,
BE: Backend<B>,
H: HasherT,
{
let mut synced_any = false;

for _ in 0..limit {
synced_any = synced_any
|| sync_one_block::<_, _, _, H>(client, substrate_backend, madara_backend, sync_from, block_metrics)?;
|| sync_one_block::<_, _, _>(client, substrate_backend, madara_backend, sync_from, block_metrics)?;
}

Ok(synced_any)
Expand Down
2 changes: 1 addition & 1 deletion crates/client/rpc/src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ where
StarknetRpcApiError::InternalServerError
})?;

let block_hash = starknet_block.header().hash::<H>();
let block_hash = starknet_block.header().hash();

let mut emitted_events: Vec<EmittedEvent> = vec![];
for tx_hash in starknet_block.transactions_hashes() {
Expand Down
22 changes: 11 additions & 11 deletions crates/client/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ where
Ok(block) => block,
Err(_) => return Err(StarknetRpcApiError::BlockNotFound),
};
Ok(starknet_block.header().hash::<H>().into())
Ok(starknet_block.header().hash().into())
}

/// Returns the substrate block hash corresponding to the given Starknet block id
Expand Down Expand Up @@ -738,13 +738,13 @@ where
if starting_block.is_ok() && current_block.is_ok() && highest_block.is_ok() {
// Convert block numbers and hashes to the respective type required by the `syncing` endpoint.
let starting_block_num = UniqueSaturatedInto::<u64>::unique_saturated_into(self.starting_block);
let starting_block_hash = starting_block?.header().hash::<H>().0;
let starting_block_hash = starting_block?.header().hash().0;

let current_block_num = UniqueSaturatedInto::<u64>::unique_saturated_into(best_number);
let current_block_hash = current_block?.header().hash::<H>().0;
let current_block_hash = current_block?.header().hash().0;

let highest_block_num = UniqueSaturatedInto::<u64>::unique_saturated_into(highest_number);
let highest_block_hash = highest_block?.header().hash::<H>().0;
let highest_block_hash = highest_block?.header().hash().0;

// Build the `SyncStatus` struct with the respective syn information
Ok(SyncStatusType::Syncing(SyncStatus {
Expand Down Expand Up @@ -831,7 +831,7 @@ where

let starknet_block = get_block_by_block_hash(self.client.as_ref(), substrate_block_hash)?;
let starknet_version = starknet_block.header().protocol_version;
let block_hash = starknet_block.header().hash::<H>();
let block_hash = starknet_block.header().hash();

let transaction_hashes =
starknet_block.transactions_hashes().map(|txh| Felt252Wrapper::from(*txh).into()).collect();
Expand Down Expand Up @@ -1092,7 +1092,7 @@ where

let starknet_block = get_block_by_block_hash(self.client.as_ref(), substrate_block_hash)?;

let block_hash = starknet_block.header().hash::<H>();
let block_hash = starknet_block.header().hash();
let starknet_version = starknet_block.header().protocol_version;
let transactions = starknet_block.transactions().iter().map(|tx| to_starknet_core_tx(tx.clone())).collect();

Expand Down Expand Up @@ -1162,15 +1162,15 @@ where
FieldElement::default()
};

let starknet_block_hash = BlockHash(starknet_block.header().hash::<H>().into());
let starknet_block_hash = BlockHash(starknet_block.header().hash().into());

let state_diff = self.get_state_diff(&starknet_block_hash).map_err(|e| {
error!("Failed to get state diff. Starknet block hash: {starknet_block_hash}, error: {e}");
StarknetRpcApiError::InternalServerError
})?;

let state_update = StateUpdate {
block_hash: starknet_block.header().hash::<H>().into(),
block_hash: starknet_block.header().hash().into(),
new_root: Felt252Wrapper::from(self.backend.temporary_global_state_root_getter()).into(),
old_root,
state_diff,
Expand Down Expand Up @@ -1375,7 +1375,7 @@ where
transactions: transaction_hashes,
// TODO: fill real prices
l1_gas_price: ResourcePrice { price_in_fri: Default::default(), price_in_wei: Default::default() },
parent_hash: latest_block_header.hash::<H>().into(),
parent_hash: latest_block_header.hash().into(),
sequencer_address: Felt252Wrapper::from(latest_block_header.sequencer_address).into(),
starknet_version: latest_block_header.protocol_version.to_string(),
timestamp: calculate_pending_block_timestamp(),
Expand All @@ -1396,7 +1396,7 @@ where
transactions,
// TODO: fill real prices
l1_gas_price: ResourcePrice { price_in_fri: Default::default(), price_in_wei: Default::default() },
parent_hash: latest_block_header.hash::<H>().into(),
parent_hash: latest_block_header.hash().into(),
sequencer_address: Felt252Wrapper::from(latest_block_header.sequencer_address).into(),
starknet_version: latest_block_header.protocol_version.to_string(),
timestamp: calculate_pending_block_timestamp(),
Expand Down Expand Up @@ -1428,7 +1428,7 @@ where
let starknet_block: mp_block::Block = get_block_by_block_hash(self.client.as_ref(), substrate_block_hash)
.map_err(|_e| StarknetRpcApiError::BlockNotFound)?;
let block_header = starknet_block.header();
let block_hash = block_header.hash::<H>().into();
let block_hash = block_header.hash().into();
let block_number = block_header.block_number;

let transaction =
Expand Down
4 changes: 1 addition & 3 deletions crates/pallets/starknet/runtime_api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use alloc::vec::Vec;
use mp_simulations::{InternalSubstrateError, SimulationError, SimulationFlags, TransactionSimulationResult};
use sp_api::BlockT;
use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector, Nonce};
use starknet_api::hash::{StarkFelt, StarkHash};
use starknet_api::hash::StarkFelt;
use starknet_api::state::StorageKey;
use starknet_api::transaction::{Calldata, Event as StarknetEvent, MessageToL1, TransactionHash};

Expand All @@ -41,8 +41,6 @@ sp_api::decl_runtime_apis! {
fn chain_id() -> Felt252Wrapper;
/// Returns the Starknet OS Cairo program hash.
fn program_hash() -> Felt252Wrapper;
/// Returns the Starknet config hash.
fn config_hash() -> StarkHash;
/// Returns the fee token address.
fn fee_token_addresses() -> FeeTokenAddresses;
/// Returns fee estimate
Expand Down
16 changes: 2 additions & 14 deletions crates/pallets/starknet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ use mp_block::{Block as StarknetBlock, Header as StarknetHeader};
use mp_chain_id::MADARA_CHAIN_ID;
use mp_digest_log::MADARA_ENGINE_ID;
use mp_felt::Felt252Wrapper;
use mp_hashers::HasherT;
use mp_sequencer_address::{InherentError, InherentType, DEFAULT_SEQUENCER_ADDRESS, INHERENT_IDENTIFIER};
use mp_storage::{StarknetStorageSchemaVersion, PALLET_STARKNET_SCHEMA};
use mp_transactions::execution::{
Expand All @@ -90,7 +89,7 @@ use sp_runtime::DigestItem;
use starknet_api::block::{BlockNumber, BlockTimestamp};
use starknet_api::core::{ChainId, ClassHash, CompiledClassHash, ContractAddress, EntryPointSelector, Nonce};
use starknet_api::deprecated_contract_class::EntryPointType;
use starknet_api::hash::{StarkFelt, StarkHash};
use starknet_api::hash::StarkFelt;
use starknet_api::state::StorageKey;
use starknet_api::transaction::{
Calldata, Event as StarknetEvent, Fee, MessageToL1, TransactionHash, TransactionVersion,
Expand Down Expand Up @@ -129,8 +128,6 @@ pub mod pallet {
/// mechanism and comply with starknet which uses an ER20 as fee token
#[pallet::config]
pub trait Config: frame_system::Config {
/// The hashing function to use.
type SystemHash: HasherT;
/// The block time
type TimestampProvider: Time;
/// The gas price
Expand Down Expand Up @@ -1014,7 +1011,7 @@ impl<T: Config> Pallet<T> {
// Safe because it could only failed if `transaction_count` does not match `transactions.len()`
.unwrap();
// Save the block number <> hash mapping.
let blockhash = block.header().hash::<T::SystemHash>();
let blockhash = block.header().hash();
BlockHash::<T>::insert(block_number, blockhash);

// Kill pending storage.
Expand Down Expand Up @@ -1145,15 +1142,6 @@ impl<T: Config> Pallet<T> {
T::ProgramHash::get()
}

pub fn config_hash() -> StarkHash {
Felt252Wrapper(T::SystemHash::compute_hash_on_elements(&[
FieldElement::from_byte_slice_be(SN_OS_CONFIG_HASH_VERSION.as_bytes()).unwrap(),
Self::chain_id().into(),
Felt252Wrapper::from(Self::fee_token_addresses().eth_fee_token_address.0.0).0,
]))
.into()
}

pub fn is_transaction_fee_disabled() -> bool {
T::DisableTransactionFee::get()
}
Expand Down
6 changes: 3 additions & 3 deletions crates/pallets/starknet/src/tests/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use super::mock::default_mock::*;
use super::mock::*;
use crate::tests::constants::FEE_TOKEN_ADDRESS;
use crate::tests::get_invoke_dummy;
use crate::{Config, SeqAddrUpdate, SequencerAddress};
use crate::{SeqAddrUpdate, SequencerAddress};

#[test]
fn store_block_no_pending_transactions_works() {
Expand All @@ -34,7 +34,7 @@ fn store_block_no_pending_transactions_works() {
assert_eq!(0, block.transactions().len());

// check BlockHash correct
let blockhash = block.header().hash::<<MockRuntime as Config>::SystemHash>();
let blockhash = block.header().hash();
assert_eq!(blockhash, Starknet::block_hash(BLOCK_NUMBER));
// check pending storage killed
assert_eq!(0, Starknet::pending().len());
Expand Down Expand Up @@ -77,7 +77,7 @@ fn store_block_with_pending_transactions_works() {
assert_eq!(2, block.transactions().len());

// check BlockHash correct
let blockhash = block.header().hash::<<MockRuntime as Config>::SystemHash>();
let blockhash = block.header().hash();
assert_eq!(blockhash, Starknet::block_hash(BLOCK_NUMBER));
// check pending storage killed
assert_eq!(0, Starknet::pending().len());
Expand Down
1 change: 0 additions & 1 deletion crates/pallets/starknet/src/tests/mock/setup_mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ macro_rules! mock_runtime {
}

impl pallet_starknet::Config for MockRuntime {
type SystemHash = mp_hashers::pedersen::PedersenHasher;
type TimestampProvider = Timestamp;
type UnsignedPriority = UnsignedPriority;
type TransactionLongevity = TransactionLongevity;
Expand Down
Loading

0 comments on commit 674c97b

Please sign in to comment.