From 674c97ba9818e663d55e8fb347daa1623008495f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eliel=20=EC=88=98=ED=95=99?= <46634774+elielnfinic@users.noreply.github.com> Date: Tue, 7 May 2024 06:07:10 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20removing=20generic=20hasher=20from=20bl?= =?UTF-8?q?ock=20hash=20computation,=20using=20pedersen=20-=E2=80=A6=20(#1?= =?UTF-8?q?583)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 1 + .../client/commitment-state-diff/src/lib.rs | 11 ++----- crates/client/mapping-sync/src/lib.rs | 2 +- crates/client/mapping-sync/src/sync_blocks.rs | 29 +++++++------------ crates/client/rpc/src/events/mod.rs | 2 +- crates/client/rpc/src/lib.rs | 22 +++++++------- .../pallets/starknet/runtime_api/src/lib.rs | 4 +-- crates/pallets/starknet/src/lib.rs | 16 ++-------- crates/pallets/starknet/src/tests/block.rs | 6 ++-- .../starknet/src/tests/mock/setup_mock.rs | 1 - crates/primitives/block/src/header.rs | 7 +++-- crates/runtime/src/lib.rs | 6 +--- crates/runtime/src/pallets.rs | 1 - 13 files changed, 38 insertions(+), 70 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a70cd2d44..e6ead47c87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/crates/client/commitment-state-diff/src/lib.rs b/crates/client/commitment-state-diff/src/lib.rs index f94ebff11a..1323a913b2 100644 --- a/crates/client/commitment-state-diff/src/lib.rs +++ b/crates/client/commitment-state-diff/src/lib.rs @@ -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, } @@ -76,7 +75,7 @@ where Poll::Ready(Some(storage_notification)) => { let block_hash = storage_notification.block; - match build_commitment_state_diff::( + match build_commitment_state_diff::( self_as_mut.client.clone(), self_as_mut.backend.clone(), storage_notification, @@ -137,7 +136,7 @@ enum BuildCommitmentStateDiffError { FailedToGetConfigHash(#[from] sp_api::ApiError), } -fn build_commitment_state_diff( +fn build_commitment_state_diff( client: Arc, backend: Arc>, storage_notification: StorageNotification, @@ -146,7 +145,6 @@ where C: ProvideRuntimeApi, C::Api: StarknetRuntimeApi, C: HeaderBackend, - H: HasherT, { let mut accessed_addrs: IndexSet = IndexSet::new(); let mut commitment_state_diff = ThinStateDiff { @@ -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::().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(), diff --git a/crates/client/mapping-sync/src/lib.rs b/crates/client/mapping-sync/src/lib.rs index 04a89ca9b5..11de815608 100644 --- a/crates/client/mapping-sync/src/lib.rs +++ b/crates/client/mapping-sync/src/lib.rs @@ -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(), diff --git a/crates/client/mapping-sync/src/sync_blocks.rs b/crates/client/mapping-sync/src/sync_blocks.rs index 2deadafa90..d2f0753789 100644 --- a/crates/client/mapping-sync/src/sync_blocks.rs +++ b/crates/client/mapping-sync/src/sync_blocks.rs @@ -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; @@ -12,7 +11,7 @@ use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Zero}; use crate::block_metrics::BlockMetrics; -fn sync_block( +fn sync_block( client: &C, backend: &mc_db::Backend, header: &B::Header, @@ -23,7 +22,6 @@ where C: ProvideRuntimeApi, C::Api: StarknetRuntimeApi, BE: Backend, - 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. @@ -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::(); - let storage_starknet_block_hash = storage_starknet_block.header().hash::(); + 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!( @@ -100,15 +98,10 @@ where } } -fn sync_genesis_block( - _client: &C, - backend: &mc_db::Backend, - header: &B::Header, -) -> anyhow::Result<()> +fn sync_genesis_block(_client: &C, backend: &mc_db::Backend, header: &B::Header) -> anyhow::Result<()> where C: HeaderBackend, B: BlockT, - H: HasherT, { let substrate_block_hash = header.hash(); @@ -119,7 +112,7 @@ where } Err(FindLogError::MultipleLogs) => return Err(anyhow::anyhow!("Multiple logs found")), }; - let block_hash = block.header().hash::(); + let block_hash = block.header().hash(); let mapping_commitment = mc_db::MappingCommitment:: { block_hash: substrate_block_hash, starknet_block_hash: block_hash.into(), @@ -131,7 +124,7 @@ where Ok(()) } -fn sync_one_block( +fn sync_one_block( client: &C, substrate_backend: &BE, madara_backend: &mc_db::Backend, @@ -143,7 +136,6 @@ where C::Api: StarknetRuntimeApi, C: HeaderBackend + StorageProvider, BE: Backend, - H: HasherT, { let mut current_syncing_tips = madara_backend.meta().current_syncing_tips()?; @@ -173,12 +165,12 @@ 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)?; @@ -186,7 +178,7 @@ where } } -pub fn sync_blocks( +pub fn sync_blocks( client: &C, substrate_backend: &BE, madara_backend: &mc_db::Backend, @@ -199,13 +191,12 @@ where C::Api: StarknetRuntimeApi, C: HeaderBackend + StorageProvider, BE: Backend, - 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) diff --git a/crates/client/rpc/src/events/mod.rs b/crates/client/rpc/src/events/mod.rs index 872dc65702..a9683f2540 100644 --- a/crates/client/rpc/src/events/mod.rs +++ b/crates/client/rpc/src/events/mod.rs @@ -57,7 +57,7 @@ where StarknetRpcApiError::InternalServerError })?; - let block_hash = starknet_block.header().hash::(); + let block_hash = starknet_block.header().hash(); let mut emitted_events: Vec = vec![]; for tx_hash in starknet_block.transactions_hashes() { diff --git a/crates/client/rpc/src/lib.rs b/crates/client/rpc/src/lib.rs index 3475049568..0a5c819b20 100644 --- a/crates/client/rpc/src/lib.rs +++ b/crates/client/rpc/src/lib.rs @@ -160,7 +160,7 @@ where Ok(block) => block, Err(_) => return Err(StarknetRpcApiError::BlockNotFound), }; - Ok(starknet_block.header().hash::().into()) + Ok(starknet_block.header().hash().into()) } /// Returns the substrate block hash corresponding to the given Starknet block id @@ -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::::unique_saturated_into(self.starting_block); - let starting_block_hash = starting_block?.header().hash::().0; + let starting_block_hash = starting_block?.header().hash().0; let current_block_num = UniqueSaturatedInto::::unique_saturated_into(best_number); - let current_block_hash = current_block?.header().hash::().0; + let current_block_hash = current_block?.header().hash().0; let highest_block_num = UniqueSaturatedInto::::unique_saturated_into(highest_number); - let highest_block_hash = highest_block?.header().hash::().0; + let highest_block_hash = highest_block?.header().hash().0; // Build the `SyncStatus` struct with the respective syn information Ok(SyncStatusType::Syncing(SyncStatus { @@ -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::(); + let block_hash = starknet_block.header().hash(); let transaction_hashes = starknet_block.transactions_hashes().map(|txh| Felt252Wrapper::from(*txh).into()).collect(); @@ -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::(); + 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(); @@ -1162,7 +1162,7 @@ where FieldElement::default() }; - let starknet_block_hash = BlockHash(starknet_block.header().hash::().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}"); @@ -1170,7 +1170,7 @@ where })?; let state_update = StateUpdate { - block_hash: starknet_block.header().hash::().into(), + block_hash: starknet_block.header().hash().into(), new_root: Felt252Wrapper::from(self.backend.temporary_global_state_root_getter()).into(), old_root, state_diff, @@ -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::().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(), @@ -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::().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(), @@ -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::().into(); + let block_hash = block_header.hash().into(); let block_number = block_header.block_number; let transaction = diff --git a/crates/pallets/starknet/runtime_api/src/lib.rs b/crates/pallets/starknet/runtime_api/src/lib.rs index 70657e3425..f0a6a055d4 100644 --- a/crates/pallets/starknet/runtime_api/src/lib.rs +++ b/crates/pallets/starknet/runtime_api/src/lib.rs @@ -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}; @@ -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 diff --git a/crates/pallets/starknet/src/lib.rs b/crates/pallets/starknet/src/lib.rs index da25ce2d00..cc156e0b55 100644 --- a/crates/pallets/starknet/src/lib.rs +++ b/crates/pallets/starknet/src/lib.rs @@ -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::{ @@ -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, @@ -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 @@ -1014,7 +1011,7 @@ impl Pallet { // 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::(); + let blockhash = block.header().hash(); BlockHash::::insert(block_number, blockhash); // Kill pending storage. @@ -1145,15 +1142,6 @@ impl Pallet { 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() } diff --git a/crates/pallets/starknet/src/tests/block.rs b/crates/pallets/starknet/src/tests/block.rs index 866a33f20f..5cfe3fefcb 100644 --- a/crates/pallets/starknet/src/tests/block.rs +++ b/crates/pallets/starknet/src/tests/block.rs @@ -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() { @@ -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::<::SystemHash>(); + let blockhash = block.header().hash(); assert_eq!(blockhash, Starknet::block_hash(BLOCK_NUMBER)); // check pending storage killed assert_eq!(0, Starknet::pending().len()); @@ -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::<::SystemHash>(); + let blockhash = block.header().hash(); assert_eq!(blockhash, Starknet::block_hash(BLOCK_NUMBER)); // check pending storage killed assert_eq!(0, Starknet::pending().len()); diff --git a/crates/pallets/starknet/src/tests/mock/setup_mock.rs b/crates/pallets/starknet/src/tests/mock/setup_mock.rs index 7df41d2653..fcc2098249 100644 --- a/crates/pallets/starknet/src/tests/mock/setup_mock.rs +++ b/crates/pallets/starknet/src/tests/mock/setup_mock.rs @@ -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; diff --git a/crates/primitives/block/src/header.rs b/crates/primitives/block/src/header.rs index 34e781c49e..fd7d76aa66 100644 --- a/crates/primitives/block/src/header.rs +++ b/crates/primitives/block/src/header.rs @@ -1,5 +1,6 @@ use blockifier::blockifier::block::GasPrices; use mp_felt::Felt252Wrapper; +use mp_hashers::pedersen::PedersenHasher; use mp_hashers::HasherT; use sp_core::U256; use starknet_api::core::ContractAddress; @@ -59,8 +60,8 @@ impl Header { } } - /// Compute the hash of the header. - pub fn hash(&self) -> Felt252Wrapper { + /// Compute the hash using the Pedersen hasher according to [the Starknet protocol specification](https://docs.starknet.io/documentation/architecture_and_concepts/Network_Architecture/header/#block_hash). + pub fn hash(&self) -> Felt252Wrapper { let data: &[Felt252Wrapper] = &[ self.block_number.into(), self.sequencer_address.0.0.into(), @@ -72,6 +73,6 @@ impl Header { self.parent_block_hash.into(), ]; - H::compute_hash_on_wrappers(data) + PedersenHasher::compute_hash_on_wrappers(data) } } diff --git a/crates/runtime/src/lib.rs b/crates/runtime/src/lib.rs index 7754e10d04..f10c0e3e30 100644 --- a/crates/runtime/src/lib.rs +++ b/crates/runtime/src/lib.rs @@ -53,7 +53,7 @@ pub use sp_runtime::{Perbill, Permill}; use sp_std::prelude::*; use sp_version::RuntimeVersion; 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}; /// Import the types. @@ -267,10 +267,6 @@ impl_runtime_apis! { Starknet::program_hash() } - fn config_hash() -> StarkHash { - Starknet::config_hash() - } - fn fee_token_addresses() -> FeeTokenAddresses { Starknet::fee_token_addresses() } diff --git a/crates/runtime/src/pallets.rs b/crates/runtime/src/pallets.rs index b934f82694..d9b7ad6bd9 100644 --- a/crates/runtime/src/pallets.rs +++ b/crates/runtime/src/pallets.rs @@ -35,7 +35,6 @@ use crate::*; /// Configure the Starknet pallet in pallets/starknet. impl pallet_starknet::Config for Runtime { - type SystemHash = StarknetHasher; type TimestampProvider = Timestamp; type UnsignedPriority = UnsignedPriority; type TransactionLongevity = TransactionLongevity;