Skip to content
This repository was archived by the owner on Jul 22, 2024. It is now read-only.

Commit 998013b

Browse files
Antonio Calvín Garcíafannyguthmann
authored andcommitted
Refactor class hash (#1095)
* state with warnings * fix test * fix test * remove unnecessary clone * clippy * update latest native version * mend * fix import
1 parent 6a27c04 commit 998013b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+746
-645
lines changed

bench/internals.rs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,27 +18,24 @@ use starknet_in_rust::{
1818
state::in_memory_state_reader::InMemoryStateReader,
1919
state::{cached_state::CachedState, state_api::State},
2020
transaction::{declare::Declare, Deploy, DeployAccount, InvokeFunction},
21-
utils::Address,
21+
utils::{Address, ClassHash},
2222
};
2323
use std::{collections::HashMap, hint::black_box, sync::Arc};
2424

2525
#[cfg(feature = "cairo-native")]
26-
use {
27-
starknet_in_rust::utils::ClassHash,
28-
std::{cell::RefCell, rc::Rc},
29-
};
26+
use std::{cell::RefCell, rc::Rc};
3027

3128
lazy_static! {
3229
// include_str! doesn't seem to work in CI
3330
static ref CONTRACT_CLASS: ContractClass = ContractClass::from_path(
3431
"starknet_programs/account_without_validation.json",
3532
).unwrap();
36-
static ref CLASS_HASH: Felt252 = compute_deprecated_class_hash(&CONTRACT_CLASS).unwrap();
37-
static ref CLASS_HASH_BYTES: [u8; 32] = CLASS_HASH.clone().to_be_bytes();
33+
static ref CLASS_HASH_FELT: Felt252 = compute_deprecated_class_hash(&CONTRACT_CLASS).unwrap();
34+
static ref CLASS_HASH: ClassHash = ClassHash(CLASS_HASH_FELT.to_be_bytes());
3835
static ref SALT: Felt252 = felt_str!(
3936
"2669425616857739096022668060305620640217901643963991674344872184515580705509"
4037
);
41-
static ref CONTRACT_ADDRESS: Address = Address(calculate_contract_address(&SALT.clone(), &CLASS_HASH.clone(), &[], Address(0.into())).unwrap());
38+
static ref CONTRACT_ADDRESS: Address = Address(calculate_contract_address(&SALT, &CLASS_HASH_FELT, &[], Address(0.into())).unwrap());
4239
static ref SIGNATURE: Vec<Felt252> = vec![
4340
felt_str!("3233776396904427614006684968846859029149676045084089832563834729503047027074"),
4441
felt_str!("707039245213420890976709143988743108543645298941971188668773816813012281203"),
@@ -81,7 +78,7 @@ fn deploy_account(
8178

8279
state
8380
.set_contract_class(
84-
&CLASS_HASH_BYTES,
81+
&CLASS_HASH,
8582
&CompiledClass::Deprecated(Arc::new(CONTRACT_CLASS.clone())),
8683
)
8784
.unwrap();
@@ -90,7 +87,7 @@ fn deploy_account(
9087

9188
for _ in 0..RUNS {
9289
let mut state_copy = state.clone();
93-
let class_hash = *CLASS_HASH_BYTES;
90+
let class_hash = *CLASS_HASH;
9491
let signature = SIGNATURE.clone();
9592
scope(|| {
9693
// new consumes more execution time than raw struct instantiation
@@ -162,7 +159,7 @@ fn deploy(#[cfg(feature = "cairo-native")] program_cache: Rc<RefCell<ProgramCach
162159

163160
state
164161
.set_contract_class(
165-
&CLASS_HASH_BYTES,
162+
&CLASS_HASH,
166163
&CompiledClass::Deprecated(Arc::new(CONTRACT_CLASS.clone())),
167164
)
168165
.unwrap();
@@ -205,7 +202,7 @@ fn invoke(#[cfg(feature = "cairo-native")] program_cache: Rc<RefCell<ProgramCach
205202

206203
state
207204
.set_contract_class(
208-
&CLASS_HASH_BYTES,
205+
&CLASS_HASH,
209206
&CompiledClass::Deprecated(Arc::new(CONTRACT_CLASS.clone())),
210207
)
211208
.unwrap();

bench/native_bench.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ pub fn main() {
6363
fn bench_fibo(executions: usize, native: bool) {
6464
// Create state reader with class hash data
6565
let mut contract_class_cache = HashMap::new();
66-
static CASM_CLASS_HASH: ClassHash = [2; 32];
66+
static CASM_CLASS_HASH: ClassHash = ClassHash([2; 32]);
6767

6868
let (contract_class, constructor_selector) = match native {
6969
true => {
@@ -137,7 +137,7 @@ fn bench_fibo(executions: usize, native: bool) {
137137
fn bench_fact(executions: usize, native: bool) {
138138
// Create state reader with class hash data
139139
let mut contract_class_cache = HashMap::new();
140-
static CASM_CLASS_HASH: ClassHash = [2; 32];
140+
static CASM_CLASS_HASH: ClassHash = ClassHash([2; 32]);
141141

142142
let (contract_class, constructor_selector) = match native {
143143
true => {
@@ -216,9 +216,9 @@ fn bench_erc20(executions: usize, native: bool) {
216216
let mut contract_class_cache = HashMap::new();
217217

218218
lazy_static! {
219-
static ref ERC20_CLASS_HASH: ClassHash = felt_str!("2").to_be_bytes();
220-
static ref DEPLOYER_CLASS_HASH: ClassHash = felt_str!("10").to_be_bytes();
221-
static ref ACCOUNT1_CLASS_HASH: ClassHash = felt_str!("1").to_be_bytes();
219+
static ref ERC20_CLASS_HASH: ClassHash = ClassHash::from(felt_str!("2"));
220+
static ref DEPLOYER_CLASS_HASH: ClassHash = ClassHash::from(felt_str!("10"));
221+
static ref ACCOUNT1_CLASS_HASH: ClassHash = ClassHash::from(felt_str!("1"));
222222
static ref DEPLOYER_ADDRESS: Address = Address(1111.into());
223223
static ref ERC20_NAME: Felt252 = Felt252::from_bytes_be(b"be");
224224
static ref ERC20_SYMBOL: Felt252 = Felt252::from_bytes_be(b"be");
@@ -227,7 +227,7 @@ fn bench_erc20(executions: usize, native: bool) {
227227
static ref ERC20_RECIPIENT: Felt252 = felt_str!("111");
228228
static ref ERC20_SALT: Felt252 = felt_str!("1234");
229229
static ref ERC20_DEPLOYER_CALLDATA: [Felt252; 7] = [
230-
Felt252::from_bytes_be(&ERC20_CLASS_HASH.clone()),
230+
Felt252::from_bytes_be(ERC20_CLASS_HASH.to_bytes_be()),
231231
ERC20_SALT.clone(),
232232
ERC20_RECIPIENT.clone(),
233233
ERC20_NAME.clone(),
@@ -419,8 +419,8 @@ fn bench_erc20(executions: usize, native: bool) {
419419
.unwrap();
420420
state
421421
.set_compiled_class_hash(
422-
&Felt252::from_bytes_be(&ACCOUNT1_CLASS_HASH.clone()),
423-
&Felt252::from_bytes_be(&ACCOUNT1_CLASS_HASH.clone()),
422+
&Felt252::from_bytes_be(ACCOUNT1_CLASS_HASH.to_bytes_be()),
423+
&Felt252::from_bytes_be(ACCOUNT1_CLASS_HASH.to_bytes_be()),
424424
)
425425
.unwrap();
426426

fuzzer/src/main.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use cairo_vm::felt::Felt252;
77
use cairo_vm::vm::runners::cairo_runner::ExecutionResources;
88
use num_traits::Zero;
99
use starknet_in_rust::execution::execution_entry_point::ExecutionResult;
10+
use starknet_in_rust::utils::ClassHash;
1011
use starknet_in_rust::EntryPointType;
1112
use starknet_in_rust::{
1213
definitions::{block_context::BlockContext, constants::TRANSACTION_VERSION},
@@ -115,7 +116,7 @@ fn main() {
115116
// ------------ contract data --------------------
116117

117118
let address = Address(1111.into());
118-
let class_hash = [1; 32];
119+
let class_hash: ClassHash = ClassHash([1; 32]);
119120

120121
contract_class_cache.insert(
121122
class_hash,
@@ -166,7 +167,8 @@ fn main() {
166167
);
167168
let mut resources_manager = ExecutionResourcesManager::default();
168169

169-
let expected_key = calculate_sn_keccak("_counter".as_bytes());
170+
let expected_key_bytes = calculate_sn_keccak("_counter".as_bytes());
171+
let expected_key = ClassHash(expected_key_bytes);
170172

171173
let mut expected_accessed_storage_keys = HashSet::new();
172174
expected_accessed_storage_keys.insert(expected_key);
@@ -205,7 +207,7 @@ fn main() {
205207
state
206208
.cache()
207209
.storage_writes()
208-
.get(&(address, expected_key))
210+
.get(&(address, expected_key_bytes))
209211
.cloned(),
210212
Some(Felt252::from_bytes_be(data_to_ascii(data).as_bytes()))
211213
);

rpc_state_reader/tests/sir_tests.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ pub struct RpcStateReader(RpcState);
4141

4242
impl StateReader for RpcStateReader {
4343
fn get_contract_class(&self, class_hash: &ClassHash) -> Result<CompiledClass, StateError> {
44-
let hash = SNClassHash(StarkHash::new(*class_hash).unwrap());
44+
let hash = SNClassHash(StarkHash::new(class_hash.0).unwrap());
4545
Ok(CompiledClass::from(
4646
self.0.get_contract_class(&hash).unwrap(),
4747
))
@@ -56,7 +56,7 @@ impl StateReader for RpcStateReader {
5656
);
5757
let mut bytes = [0u8; 32];
5858
bytes.copy_from_slice(self.0.get_class_hash_at(&address).0.bytes());
59-
Ok(bytes)
59+
Ok(ClassHash(bytes))
6060
}
6161

6262
fn get_nonce_at(&self, contract_address: &Address) -> Result<Felt252, StateError> {
@@ -83,7 +83,7 @@ impl StateReader for RpcStateReader {
8383
Ok(Felt252::from_bytes_be(value.bytes()))
8484
}
8585

86-
fn get_compiled_class_hash(&self, class_hash: &ClassHash) -> Result<[u8; 32], StateError> {
86+
fn get_compiled_class_hash(&self, class_hash: &ClassHash) -> Result<ClassHash, StateError> {
8787
Ok(*class_hash)
8888
}
8989
}
@@ -156,7 +156,7 @@ pub fn execute_tx_configurable(
156156
RpcState::new_infura(network, (block_number.next()).into()).unwrap(),
157157
);
158158
let contract_class = next_block_state_reader
159-
.get_contract_class(tx.class_hash().0.bytes().try_into().unwrap())
159+
.get_contract_class(&ClassHash(tx.class_hash().0.bytes().try_into().unwrap()))
160160
.unwrap();
161161

162162
if tx.version() != TransactionVersion(2_u8.into()) {
@@ -177,7 +177,7 @@ pub fn execute_tx_configurable(
177177
.collect(),
178178
Felt252::from_bytes_be(tx.nonce().0.bytes()),
179179
Felt252::from_bytes_be(tx_hash.0.bytes()),
180-
tx.class_hash().0.bytes().try_into().unwrap(),
180+
ClassHash(tx.class_hash().0.bytes().try_into().unwrap()),
181181
)
182182
.unwrap();
183183
declare.create_for_simulation(skip_validate, false, false, false, skip_nonce_check)

src/bin/fibonacci.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use starknet_in_rust::{
1414
},
1515
state::cached_state::CachedState,
1616
state::{in_memory_state_reader::InMemoryStateReader, ExecutionResourcesManager},
17-
utils::Address,
17+
utils::{Address, ClassHash},
1818
EntryPointType,
1919
};
2020

@@ -33,7 +33,7 @@ lazy_static! {
3333

3434
static ref CONTRACT_PATH: PathBuf = PathBuf::from("starknet_programs/fibonacci.json");
3535

36-
static ref CONTRACT_CLASS_HASH: [u8; 32] = [1; 32];
36+
static ref CONTRACT_CLASS_HASH: ClassHash = ClassHash([1; 32]);
3737

3838
static ref CONTRACT_ADDRESS: Address = Address(1.into());
3939

src/bin/invoke.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use starknet_in_rust::{
1111
state::cached_state::CachedState,
1212
state::in_memory_state_reader::InMemoryStateReader,
1313
transaction::{InvokeFunction, Transaction},
14-
utils::Address,
14+
utils::{Address, ClassHash},
1515
};
1616

1717
use lazy_static::lazy_static;
@@ -31,7 +31,7 @@ lazy_static! {
3131

3232
static ref CONTRACT_PATH: PathBuf = PathBuf::from("starknet_programs/first_contract.json");
3333

34-
static ref CONTRACT_CLASS_HASH: [u8; 32] = [1; 32];
34+
static ref CONTRACT_CLASS_HASH: ClassHash = ClassHash([1; 32]);
3535

3636
static ref CONTRACT_ADDRESS: Address = Address(1.into());
3737

src/bin/invoke_with_cachedstate.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use starknet_in_rust::{
1414
state::in_memory_state_reader::InMemoryStateReader,
1515
state::{cached_state::CachedState, BlockInfo},
1616
transaction::InvokeFunction,
17-
utils::Address,
17+
utils::{Address, ClassHash},
1818
};
1919

2020
use lazy_static::lazy_static;
@@ -34,7 +34,7 @@ lazy_static! {
3434

3535
static ref CONTRACT_PATH: PathBuf = PathBuf::from("starknet_programs/first_contract.json");
3636

37-
static ref CONTRACT_CLASS_HASH: [u8; 32] = [5, 133, 114, 83, 104, 231, 159, 23, 87, 255, 235, 75, 170, 4, 84, 140, 49, 77, 101, 41, 147, 198, 201, 231, 38, 189, 215, 84, 231, 141, 140, 122];
37+
static ref CONTRACT_CLASS_HASH: ClassHash = ClassHash([5, 133, 114, 83, 104, 231, 159, 23, 87, 255, 235, 75, 170, 4, 84, 140, 49, 77, 101, 41, 147, 198, 201, 231, 38, 189, 215, 84, 231, 141, 140, 122]);
3838

3939
static ref CONTRACT_ADDRESS: Address = Address(1.into());
4040

src/execution/execution_entry_point.rs

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use super::{
22
CallInfo, CallResult, CallType, OrderedEvent, OrderedL2ToL1Message, TransactionExecutionContext,
33
};
4+
#[cfg(feature = "cairo-native")]
5+
use crate::state::StateDiff;
46
use crate::{
57
definitions::{block_context::BlockContext, constants::DEFAULT_ENTRY_POINT_SELECTOR},
68
runner::StarknetRunner,
@@ -23,11 +25,9 @@ use crate::{
2325
transaction::error::TransactionError,
2426
utils::{
2527
get_deployed_address_class_hash_at_address, parse_builtin_names,
26-
validate_contract_deployed, Address,
28+
validate_contract_deployed, Address, ClassHash,
2729
},
2830
};
29-
#[cfg(feature = "cairo-native")]
30-
use crate::{state::StateDiff, utils::ClassHash};
3131
use cairo_lang_sierra::program::Program as SierraProgram;
3232
use cairo_lang_starknet::casm_contract_class::{CasmContractClass, CasmContractEntryPoint};
3333
use cairo_lang_starknet::contract_class::ContractEntryPoints;
@@ -74,7 +74,7 @@ pub struct ExecutionEntryPoint {
7474
pub(crate) call_type: CallType,
7575
pub(crate) contract_address: Address,
7676
pub(crate) code_address: Option<Address>,
77-
pub(crate) class_hash: Option<[u8; 32]>,
77+
pub(crate) class_hash: Option<ClassHash>,
7878
pub(crate) calldata: Vec<Felt252>,
7979
pub(crate) caller_address: Address,
8080
pub(crate) entry_point_selector: Felt252,
@@ -90,7 +90,7 @@ impl ExecutionEntryPoint {
9090
caller_address: Address,
9191
entry_point_type: EntryPointType,
9292
call_type: Option<CallType>,
93-
class_hash: Option<[u8; 32]>,
93+
class_hash: Option<ClassHash>,
9494
initial_gas: u128,
9595
) -> Self {
9696
ExecutionEntryPoint {
@@ -126,7 +126,7 @@ impl ExecutionEntryPoint {
126126
T: StateReader,
127127
{
128128
// lookup the compiled class from the state.
129-
let class_hash = self.get_code_class_hash(state)?;
129+
let class_hash = self.get_class_hash(state)?;
130130
let contract_class = state
131131
.get_contract_class(&class_hash)
132132
.map_err(|_| TransactionError::MissingCompiledClass)?;
@@ -236,7 +236,7 @@ impl ExecutionEntryPoint {
236236
fn get_selected_entry_point_v0(
237237
&self,
238238
contract_class: &ContractClass,
239-
_class_hash: [u8; 32],
239+
_class_hash: ClassHash,
240240
) -> Result<ContractEntryPoint, TransactionError> {
241241
let entry_points = contract_class
242242
.entry_points_by_type
@@ -267,7 +267,7 @@ impl ExecutionEntryPoint {
267267
fn get_selected_entry_point(
268268
&self,
269269
contract_class: &CasmContractClass,
270-
_class_hash: [u8; 32],
270+
_class_hash: ClassHash,
271271
) -> Result<CasmContractEntryPoint, TransactionError> {
272272
let entry_points = match self.entry_point_type {
273273
EntryPointType::External => &contract_class.entry_points_by_type.external,
@@ -312,7 +312,7 @@ impl ExecutionEntryPoint {
312312
call_type: Some(self.call_type.clone()),
313313
contract_address: self.contract_address.clone(),
314314
code_address: self.code_address.clone(),
315-
class_hash: Some(self.get_code_class_hash(starknet_storage_state.state)?),
315+
class_hash: Some(self.get_class_hash(starknet_storage_state.state)?),
316316
entry_point_selector: Some(self.entry_point_selector.clone()),
317317
entry_point_type: Some(self.entry_point_type),
318318
calldata: self.calldata.clone(),
@@ -345,7 +345,7 @@ impl ExecutionEntryPoint {
345345
call_type: Some(self.call_type.clone()),
346346
contract_address: self.contract_address.clone(),
347347
code_address: self.code_address.clone(),
348-
class_hash: Some(self.get_code_class_hash(starknet_storage_state.state)?),
348+
class_hash: Some(self.get_class_hash(starknet_storage_state.state)?),
349349
entry_point_selector: Some(self.entry_point_selector.clone()),
350350
entry_point_type: Some(self.entry_point_type),
351351
calldata: self.calldata.clone(),
@@ -366,7 +366,7 @@ impl ExecutionEntryPoint {
366366
}
367367

368368
/// Returns the hash of the executed contract class.
369-
fn get_code_class_hash<S: State>(&self, state: &mut S) -> Result<[u8; 32], TransactionError> {
369+
fn get_class_hash<S: State>(&self, state: &mut S) -> Result<ClassHash, TransactionError> {
370370
if let Some(class_hash) = self.class_hash {
371371
match self.call_type {
372372
CallType::Delegate => return Ok(class_hash),
@@ -394,7 +394,7 @@ impl ExecutionEntryPoint {
394394
block_context: &BlockContext,
395395
tx_execution_context: &mut TransactionExecutionContext,
396396
contract_class: Arc<ContractClass>,
397-
class_hash: [u8; 32],
397+
class_hash: ClassHash,
398398
) -> Result<CallInfo, TransactionError> {
399399
let previous_cairo_usage = resources_manager.cairo_usage.clone();
400400
// fetch selected entry point
@@ -499,7 +499,7 @@ impl ExecutionEntryPoint {
499499
block_context: &BlockContext,
500500
tx_execution_context: &mut TransactionExecutionContext,
501501
contract_class: Arc<CasmContractClass>,
502-
class_hash: [u8; 32],
502+
class_hash: ClassHash,
503503
support_reverted: bool,
504504
) -> Result<CallInfo, TransactionError> {
505505
let previous_cairo_usage = resources_manager.cairo_usage.clone();
@@ -666,7 +666,7 @@ impl ExecutionEntryPoint {
666666
sierra_program_and_entrypoints: Arc<(SierraProgram, ContractEntryPoints)>,
667667
tx_execution_context: &TransactionExecutionContext,
668668
block_context: &BlockContext,
669-
class_hash: &[u8; 32],
669+
class_hash: &ClassHash,
670670
program_cache: Rc<RefCell<ProgramCache<'_, ClassHash>>>,
671671
) -> Result<CallInfo, TransactionError> {
672672
use crate::{
@@ -826,9 +826,7 @@ impl ExecutionEntryPoint {
826826
call_type: Some(self.call_type.clone()),
827827
contract_address: self.contract_address.clone(),
828828
code_address: self.code_address.clone(),
829-
class_hash: Some(
830-
self.get_code_class_hash(syscall_handler.starknet_storage_state.state)?,
831-
),
829+
class_hash: Some(self.get_class_hash(syscall_handler.starknet_storage_state.state)?),
832830
entry_point_selector: Some(self.entry_point_selector.clone()),
833831
entry_point_type: Some(self.entry_point_type),
834832
calldata: self.calldata.clone(),

0 commit comments

Comments
 (0)