Skip to content

Commit

Permalink
refacto: tx and block hash (#136)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbcaron authored Jun 3, 2024
1 parent a914cd4 commit fa2e897
Show file tree
Hide file tree
Showing 21 changed files with 123 additions and 170 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

- refacor: use db hash
- refactor: l2-sync
- refactor: remove crate mp-mapping-sync
- fix(rpc): get_nonce
Expand Down
19 changes: 9 additions & 10 deletions crates/client/rpc/src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use starknet_ff::FieldElement;

use crate::deoxys_backend_client::get_block_by_block_hash;
use crate::errors::StarknetRpcApiError;
use crate::utils::helpers::{block_hash_from_block_n, block_hash_from_id, block_n_from_id, txs_hashes_from_block_hash};
use crate::Starknet;

impl<BE, C, H> Starknet<BE, C, H>
Expand Down Expand Up @@ -55,7 +56,7 @@ where
let (block_hash, block_number) = if block_id == BlockId::Tag(BlockTag::Pending) {
(None, None)
} else {
(Some(starknet_block.header().hash::<H>().0), Some(starknet_block.header().block_number))
(Some(block_hash_from_id(block_id)?), Some(starknet_block.header().block_number))
};

let emitted_events = tx_hash_and_events
Expand All @@ -73,11 +74,11 @@ where
}

fn get_block_txs_hashes(&self, starknet_block: &DeoxysBlock) -> Result<Vec<FieldElement>, StarknetRpcApiError> {
let block_hash = starknet_block.header().hash::<H>();
let block_number = starknet_block.header().block_number;
let block_hash = block_hash_from_block_n(block_number)?;

// get txs hashes from cache or compute them
let block_txs_hashes: Vec<_> = self
.get_block_transaction_hashes(block_hash.into())?
let block_txs_hashes: Vec<_> = txs_hashes_from_block_hash(block_hash)?
.into_iter()
.map(|h| {
Felt252Wrapper::try_from(h)
Expand Down Expand Up @@ -130,12 +131,10 @@ where

fn get_block_by_tag(&self, block_tag: BlockTag) -> Result<DeoxysBlock, StarknetRpcApiError> {
if block_tag == BlockTag::Latest {
self.get_block_by_number(
self.substrate_block_number_from_starknet_block(BlockId::Tag(BlockTag::Latest)).map_err(|e| {
log::error!("'{e}'");
StarknetRpcApiError::BlockNotFound
})?,
)
self.get_block_by_number(block_n_from_id(BlockId::Tag(BlockTag::Latest)).map_err(|e| {
log::error!("'{e}'");
StarknetRpcApiError::BlockNotFound
})?)
} else {
match get_pending_block() {
Some(block) => Ok(block),
Expand Down
42 changes: 2 additions & 40 deletions crates/client/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ use std::sync::Arc;
use errors::StarknetRpcApiError;
use jsonrpsee::core::RpcResult;
use jsonrpsee::proc_macros::rpc;
use mc_db::DeoxysBackend;
use mc_sync::utility;
use methods::trace::utils::block_number_by_id;
use mp_felt::Felt252Wrapper;
use mp_hashers::HasherT;
use mp_types::block::{DBlockT, DHashT, DHeaderT};
Expand All @@ -29,7 +27,6 @@ use sp_arithmetic::traits::UniqueSaturatedInto;
use sp_blockchain::HeaderBackend;
use sp_core::H256;
use sp_runtime::traits::Header as HeaderT;
use starknet_api::hash::StarkHash;
use starknet_core::serde::unsigned_field_element::UfeHex;
use starknet_core::types::{
BlockHashAndNumber, BlockId, BroadcastedDeclareTransaction, BroadcastedDeployAccountTransaction,
Expand All @@ -39,6 +36,7 @@ use starknet_core::types::{
MaybePendingStateUpdate, MsgFromL1, SimulatedTransaction, SimulationFlag, SimulationFlagForEstimateFee,
SyncStatusType, Transaction, TransactionReceiptWithBlockInfo, TransactionStatus, TransactionTraceWithHash,
};
use utils::helpers::block_n_from_id;

use crate::deoxys_backend_client::get_block_by_block_hash;
use crate::methods::get_block::{
Expand Down Expand Up @@ -268,47 +266,11 @@ where
if let BlockId::Hash(block_hash) = block_id {
deoxys_backend_client::load_hash(self.client.as_ref(), Felt252Wrapper::from(block_hash).into())?
} else {
let block_number = block_number_by_id(block_id)?;
let block_number = block_n_from_id(block_id)?;
self.client
.hash(UniqueSaturatedInto::unique_saturated_into(block_number))
.map_err(|_| StarknetRpcApiError::BlockNotFound)?
}
.ok_or(StarknetRpcApiError::BlockNotFound)
}

/// Helper function to get the substrate block number from a Starknet block id
///
/// # Arguments
///
/// * `block_id` - The Starknet block id
///
/// # Returns
///
/// * `u64` - The substrate block number
fn substrate_block_number_from_starknet_block(&self, block_id: BlockId) -> Result<u64, StarknetRpcApiError> {
// Short circuit on block number
if let BlockId::Number(x) = block_id {
return Ok(x);
}

let substrate_block_hash = self.substrate_block_hash_from_starknet_block(block_id)?;

let starknet_block = match get_block_by_block_hash(self.client.as_ref(), substrate_block_hash) {
Ok(block) => block,
Err(_) => return Err(StarknetRpcApiError::BlockNotFound),
};

Ok(starknet_block.header().block_number)
}

/// Returns a list of all transaction hashes in the given block.
///
/// # Arguments
///
/// * `block_hash` - The hash of the block containing the transactions (starknet block).
fn get_block_transaction_hashes(&self, block_hash: StarkHash) -> Result<Vec<StarkHash>, StarknetRpcApiError> {
DeoxysBackend::mapping()
.transaction_hashes_from_block_hash(block_hash)?
.ok_or(StarknetRpcApiError::BlockNotFound)
}
}
21 changes: 10 additions & 11 deletions crates/client/rpc/src/methods/get_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ use crate::deoxys_backend_client::get_block_by_block_hash;
use crate::utils::block::{
l1_da_mode, l1_data_gas_price, l1_gas_price, new_root, parent_hash, sequencer_address, starknet_version, timestamp,
};
use crate::utils::helpers::{status, tx_conv, tx_hash_compute, tx_hash_retrieve};
use crate::utils::helpers::{
block_hash_from_block_n, status, tx_conv, tx_hash_compute, tx_hash_retrieve, txs_hashes_from_block_hash,
};
use crate::{Felt, Starknet};

pub(crate) fn get_block_with_tx_hashes_finalized<BE, C, H>(
Expand All @@ -28,11 +30,9 @@ where
H: HasherT + Send + Sync + 'static,
{
let starknet_block = get_block_by_block_hash(starknet.client.as_ref(), substrate_block_hash)?;

let block_hash = starknet_block.header().hash::<H>();
let block_txs_hashes = tx_hash_retrieve(starknet.get_block_transaction_hashes(block_hash.into())?);

let block_number = starknet_block.header().block_number;
let block_hash = block_hash_from_block_n(block_number)?;
let block_txs_hashes = tx_hash_retrieve(txs_hashes_from_block_hash(block_hash)?);
let status = status(block_number);
let parent_hash = parent_hash(&starknet_block);
let new_root = new_root(&starknet_block);
Expand All @@ -46,7 +46,7 @@ where
let block_with_tx_hashes = BlockWithTxHashes {
transactions: block_txs_hashes,
status,
block_hash: block_hash.into(),
block_hash,
parent_hash,
block_number,
new_root,
Expand Down Expand Up @@ -101,12 +101,11 @@ where
H: HasherT + Send + Sync + 'static,
{
let starknet_block = get_block_by_block_hash(starknet.client.as_ref(), substrate_block_hash)?;
let block_number = starknet_block.header().block_number;
let block_hash = block_hash_from_block_n(block_number)?;

let block_hash = starknet_block.header().hash::<H>();
let block_txs_hashes = tx_hash_retrieve(starknet.get_block_transaction_hashes(block_hash.into())?);
let block_txs_hashes = tx_hash_retrieve(txs_hashes_from_block_hash(block_hash)?);
let transactions = tx_conv(starknet_block.transactions(), block_txs_hashes);

let block_number = starknet_block.header().block_number;
let status = status(block_number);
let parent_hash = parent_hash(&starknet_block);
let new_root = new_root(&starknet_block);
Expand All @@ -119,7 +118,7 @@ where

let block_with_txs = BlockWithTxs {
status,
block_hash: block_hash.into(),
block_hash,
parent_hash,
block_number,
new_root,
Expand Down
11 changes: 5 additions & 6 deletions crates/client/rpc/src/methods/read/get_block_with_receipts.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use jsonrpsee::core::RpcResult;
use mp_felt::Felt252Wrapper;
use mp_hashers::HasherT;
use mp_transactions::to_starknet_core_transaction::to_starknet_core_tx;
use mp_types::block::DBlockT;
Expand All @@ -19,7 +18,7 @@ use crate::utils::block::{
l1_da_mode, l1_data_gas_price, l1_gas_price, new_root, parent_hash, sequencer_address, starknet_version, timestamp,
};
use crate::utils::execution::{block_context, re_execute_transactions};
use crate::utils::helpers::{status, tx_hash_retrieve};
use crate::utils::helpers::{block_hash_from_block_n, status, tx_hash_retrieve, txs_hashes_from_block_hash};
use crate::utils::transaction::blockifier_transactions;
use crate::Starknet;

Expand All @@ -36,11 +35,11 @@ where
let block = get_block_by_block_hash(starknet.client.as_ref(), substrate_block_hash)?;
let block_header = block.header();
let block_number = block_header.block_number;
let block_hash: Felt252Wrapper = block_header.hash::<H>();
let block_hash = block_hash_from_block_n(block_number)?;

let block_context = block_context(starknet.client.as_ref(), substrate_block_hash)?;

let block_txs_hashes = tx_hash_retrieve(starknet.get_block_transaction_hashes(block_hash.into())?);
let block_txs_hashes = tx_hash_retrieve(txs_hashes_from_block_hash(block_hash)?);

// create a vector of transactions with their corresponding hashes without deploy transactions,
// blockifier does not support deploy transactions
Expand Down Expand Up @@ -103,9 +102,9 @@ where
} else {
let block_with_receipts = BlockWithReceipts {
status: status(starknet_block.header().block_number),
block_hash: starknet_block.header().hash::<H>().into(),
block_hash,
parent_hash: parent_hash(&starknet_block),
block_number: starknet_block.header().block_number,
block_number,
new_root: new_root(&starknet_block),
timestamp: timestamp(&starknet_block),
sequencer_address: sequencer_address(&starknet_block),
Expand Down
4 changes: 2 additions & 2 deletions crates/client/rpc/src/methods/read/get_class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use mp_felt::Felt252Wrapper;
use starknet_core::types::{BlockId, ContractClass, FieldElement};

use crate::errors::StarknetRpcApiError;
use crate::methods::trace::utils::block_number_by_id;
use crate::utils::helpers::block_n_from_id;

/// Get the contract class definition in the given block associated with the given hash.
///
Expand Down Expand Up @@ -38,7 +38,7 @@ pub fn get_class(block_id: BlockId, class_hash: FieldElement) -> RpcResult<Contr
abi_length,
block_number: declared_at_block,
} = class;
if declared_at_block >= block_number_by_id(block_id)? {
if declared_at_block >= block_n_from_id(block_id)? {
return Err(StarknetRpcApiError::ClassHashNotFound.into());
}
Ok(ContractClassWrapper { contract: contract_class, abi, sierra_program_length, abi_length }
Expand Down
4 changes: 2 additions & 2 deletions crates/client/rpc/src/methods/read/get_class_at.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use starknet_api::hash::StarkFelt;
use starknet_core::types::{BlockId, ContractClass, FieldElement};

use crate::errors::StarknetRpcApiError;
use crate::methods::trace::utils::block_number_by_id;
use crate::utils::helpers::block_n_from_id;

/// Get the Contract Class Definition at a Given Address in a Specific Block
///
Expand All @@ -28,7 +28,7 @@ use crate::methods::trace::utils::block_number_by_id;
/// * `BLOCK_NOT_FOUND` - If the specified block does not exist in the blockchain.
/// * `CONTRACT_NOT_FOUND` - If the specified contract address does not exist.
pub fn get_class_at(block_id: BlockId, contract_address: FieldElement) -> RpcResult<ContractClass> {
let block_number = block_number_by_id(block_id)?;
let block_number = block_n_from_id(block_id)?;
let key = ContractAddress(PatriciaKey(StarkFelt(contract_address.to_bytes_be())));

let class_hash = match storage_handler::contract_class_hash().get_at(&key, block_number) {
Expand Down
4 changes: 2 additions & 2 deletions crates/client/rpc/src/methods/read/get_class_hash_at.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use starknet_api::hash::StarkFelt;
use starknet_core::types::{BlockId, FieldElement};

use crate::errors::StarknetRpcApiError;
use crate::methods::trace::utils::block_number_by_id;
use crate::utils::helpers::block_n_from_id;
use crate::Felt;

/// Get the contract class hash in the given block for the contract deployed at the given
Expand All @@ -22,7 +22,7 @@ use crate::Felt;
///
/// * `class_hash` - The class hash of the given contract
pub fn get_class_hash_at(block_id: BlockId, contract_address: FieldElement) -> RpcResult<Felt> {
let block_number = block_number_by_id(block_id)?;
let block_number = block_n_from_id(block_id)?;
let key = ContractAddress(PatriciaKey(StarkFelt(contract_address.to_bytes_be())));

match storage_handler::contract_class_hash().get_at(&key, block_number) {
Expand Down
20 changes: 6 additions & 14 deletions crates/client/rpc/src/methods/read/get_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use starknet_ff::FieldElement;
use crate::constants::{MAX_EVENTS_CHUNK_SIZE, MAX_EVENTS_KEYS};
use crate::errors::StarknetRpcApiError;
use crate::types::ContinuationToken;
use crate::utils::helpers::block_n_from_id;
use crate::Starknet;

/// Returns all events matching the given filter.
Expand Down Expand Up @@ -52,7 +53,7 @@ where

// Get the substrate block numbers for the requested range
let (from_block, to_block, latest_block) =
block_range(filter.event_filter.from_block, filter.event_filter.to_block, starknet)?;
block_range(filter.event_filter.from_block, filter.event_filter.to_block)?;

let continuation_token = match filter.result_page_request.continuation_token {
Some(token) => ContinuationToken::parse(token).map_err(|e| {
Expand Down Expand Up @@ -116,32 +117,23 @@ fn event_match_filter(event: &EmittedEvent, address: Option<Felt252Wrapper>, key
match_from_address && match_keys
}

fn block_range<BE, C, H>(
from_block: Option<BlockId>,
to_block: Option<BlockId>,
starknet: &Starknet<BE, C, H>,
) -> Result<(u64, u64, u64), StarknetRpcApiError>
where
BE: Backend<DBlockT> + 'static,
C: HeaderBackend<DBlockT> + BlockBackend<DBlockT> + StorageProvider<DBlockT, BE> + 'static,
H: HasherT + Send + Sync + 'static,
{
let latest = starknet.substrate_block_number_from_starknet_block(BlockId::Tag(BlockTag::Latest)).map_err(|e| {
fn block_range(from_block: Option<BlockId>, to_block: Option<BlockId>) -> Result<(u64, u64, u64), StarknetRpcApiError> {
let latest = block_n_from_id(BlockId::Tag(BlockTag::Latest)).map_err(|e| {
log::error!("'{e}'");
StarknetRpcApiError::BlockNotFound
})?;
let from = if from_block == Some(BlockId::Tag(BlockTag::Pending)) {
latest + 1
} else {
starknet.substrate_block_number_from_starknet_block(from_block.unwrap_or(BlockId::Number(0))).map_err(|e| {
block_n_from_id(from_block.unwrap_or(BlockId::Number(0))).map_err(|e| {
log::error!("'{e}'");
StarknetRpcApiError::BlockNotFound
})?
};
let to = if to_block == Some(BlockId::Tag(BlockTag::Pending)) {
latest + 1
} else {
starknet.substrate_block_number_from_starknet_block(to_block.unwrap_or(BlockId::Number(0))).map_err(|e| {
block_n_from_id(to_block.unwrap_or(BlockId::Number(0))).map_err(|e| {
log::error!("'{e}'");
StarknetRpcApiError::BlockNotFound
})?
Expand Down
4 changes: 2 additions & 2 deletions crates/client/rpc/src/methods/read/get_nonce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use starknet_api::hash::StarkFelt;
use starknet_core::types::{BlockId, FieldElement};

use crate::errors::StarknetRpcApiError;
use crate::methods::trace::utils::block_number_by_id;
use crate::utils::helpers::block_n_from_id;
use crate::Felt;

/// Get the nonce associated with the given address in the given block.
Expand All @@ -28,7 +28,7 @@ use crate::Felt;
pub fn get_nonce(block_id: BlockId, contract_address: FieldElement) -> RpcResult<Felt> {
let key = ContractAddress(PatriciaKey(StarkFelt(contract_address.to_bytes_be())));

let block_number = block_number_by_id(block_id)?;
let block_number = block_n_from_id(block_id)?;
match storage_handler::contract_nonces().get_at(&key, block_number) {
Err(e) => {
log::error!("Failed to get nonce: {e}");
Expand Down
5 changes: 2 additions & 3 deletions crates/client/rpc/src/methods/read/get_state_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use starknet_core::types::{BlockId, BlockTag, FieldElement, MaybePendingStateUpd

use crate::deoxys_backend_client::get_block_by_block_hash;
use crate::errors::StarknetRpcApiError;
use crate::utils::helpers::block_hash_from_block_n;
use crate::Starknet;

/// Get the information about the result of executing the requested block.
Expand Down Expand Up @@ -59,10 +60,8 @@ where
let substrate_block_hash = starknet.substrate_block_hash_from_starknet_block(block_id)?;

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

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

let block_number = starknet_block.header().block_number;
let block_hash = block_hash_from_block_n(block_number)?;

let new_root = Felt252Wrapper::from(starknet_block.header().global_state_root).into();

Expand Down
Loading

0 comments on commit fa2e897

Please sign in to comment.