From e7fb9f4d4fde13899e01213312320489e5f4755c Mon Sep 17 00:00:00 2001 From: Edgar Luque Date: Tue, 17 Sep 2024 18:11:18 +0200 Subject: [PATCH] sierra emu --- crates/blockifier/bench/blockifier_bench.rs | 4 +- crates/blockifier/src/bouncer.rs | 7 +- crates/blockifier/src/bouncer_test.rs | 3 +- .../blockifier/src/execution/common_hints.rs | 9 +- .../src/execution/contract_class.rs | 2 +- .../deprecated_entry_point_execution.rs | 4 +- .../deprecated_syscalls_test.rs | 25 +++- .../src/execution/deprecated_syscalls/mod.rs | 29 ++++- .../src/execution/execution_utils.rs | 13 +- .../execution/native/entry_point_execution.rs | 19 ++- .../src/execution/native/syscall_handler.rs | 120 +++++++++++++----- .../blockifier/src/execution/native/utils.rs | 65 +++++++--- .../src/execution/native/utils_test.rs | 8 +- .../syscalls/syscall_tests/get_block_hash.rs | 13 +- .../syscalls/syscall_tests/library_call.rs | 8 +- crates/blockifier/src/fee/actual_cost.rs | 5 +- crates/blockifier/src/fee/fee_checks.rs | 5 +- crates/blockifier/src/fee/fee_test.rs | 18 +-- crates/blockifier/src/test_utils/declare.rs | 12 +- .../src/test_utils/deploy_account.rs | 12 +- crates/blockifier/src/test_utils/invoke.rs | 15 ++- .../src/transaction/objects_test.rs | 6 +- crates/blockifier/src/utils_test.rs | 5 +- .../starknet_feeder_gateway_client_test.rs | 38 +++--- 24 files changed, 322 insertions(+), 123 deletions(-) diff --git a/crates/blockifier/bench/blockifier_bench.rs b/crates/blockifier/bench/blockifier_bench.rs index a59d71d6c0..2097bb1cec 100644 --- a/crates/blockifier/bench/blockifier_bench.rs +++ b/crates/blockifier/bench/blockifier_bench.rs @@ -8,7 +8,9 @@ //! Run the benchmarks using `cargo bench --bench blockifier_bench`. use blockifier::test_utils::transfers_generator::{ - RecipientGeneratorType, TransfersGenerator, TransfersGeneratorConfig, + RecipientGeneratorType, + TransfersGenerator, + TransfersGeneratorConfig, }; use criterion::{criterion_group, criterion_main, Criterion}; diff --git a/crates/blockifier/src/bouncer.rs b/crates/blockifier/src/bouncer.rs index 7ec8d5a627..0aa83d08ad 100644 --- a/crates/blockifier/src/bouncer.rs +++ b/crates/blockifier/src/bouncer.rs @@ -6,7 +6,8 @@ use serde::{Deserialize, Serialize}; use starknet_api::core::ClassHash; use crate::blockifier::transaction_executor::{ - TransactionExecutorError, TransactionExecutorResult, + TransactionExecutorError, + TransactionExecutorResult, }; use crate::execution::call_info::ExecutionSummary; use crate::fee::gas_usage::get_onchain_data_segment_length; @@ -14,7 +15,9 @@ use crate::state::cached_state::{StateChangesKeys, StorageEntry}; use crate::state::state_api::StateReader; use crate::transaction::errors::TransactionExecutionError; use crate::transaction::objects::{ - ExecutionResourcesTraits, TransactionExecutionResult, TransactionResources, + ExecutionResourcesTraits, + TransactionExecutionResult, + TransactionResources, }; #[cfg(test)] diff --git a/crates/blockifier/src/bouncer_test.rs b/crates/blockifier/src/bouncer_test.rs index 9976ca0f13..dc1c2e9736 100644 --- a/crates/blockifier/src/bouncer_test.rs +++ b/crates/blockifier/src/bouncer_test.rs @@ -7,7 +7,8 @@ use starknet_api::{class_hash, contract_address, felt, patricia_key}; use super::BouncerConfig; use crate::blockifier::transaction_executor::{ - TransactionExecutorError, TransactionExecutorResult, + TransactionExecutorError, + TransactionExecutorResult, }; use crate::bouncer::{verify_tx_weights_in_bounds, Bouncer, BouncerWeights, BuiltinCount}; use crate::context::BlockContext; diff --git a/crates/blockifier/src/execution/common_hints.rs b/crates/blockifier/src/execution/common_hints.rs index 962984c0c8..ae188fa307 100644 --- a/crates/blockifier/src/execution/common_hints.rs +++ b/crates/blockifier/src/execution/common_hints.rs @@ -3,10 +3,12 @@ use std::ops::Shl; use std::rc::Rc; use cairo_vm::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::{ - BuiltinHintProcessor, HintFunc, + BuiltinHintProcessor, + HintFunc, }; use cairo_vm::hint_processor::builtin_hint_processor::hint_utils::{ - get_integer_from_var_name, insert_value_from_var_name, + get_integer_from_var_name, + insert_value_from_var_name, }; use cairo_vm::hint_processor::hint_processor_definition::HintReference; use cairo_vm::serde::deserialize_program::ApTracking; @@ -18,7 +20,8 @@ use num_bigint::BigUint; use starknet_types_core::felt::Felt; use crate::execution::hint_code::{ - NORMALIZE_ADDRESS_SET_IS_250_HINT, NORMALIZE_ADDRESS_SET_IS_SMALL_HINT, + NORMALIZE_ADDRESS_SET_IS_250_HINT, + NORMALIZE_ADDRESS_SET_IS_SMALL_HINT, }; /// Transaction execution mode. diff --git a/crates/blockifier/src/execution/contract_class.rs b/crates/blockifier/src/execution/contract_class.rs index 513927cbec..7bc0122f1e 100644 --- a/crates/blockifier/src/execution/contract_class.rs +++ b/crates/blockifier/src/execution/contract_class.rs @@ -649,7 +649,7 @@ pub struct NativeContractClassV1Inner { entry_points_by_type: NativeContractEntryPoints, // Storing the raw sierra program and entry points to be able to fallback to the vm sierra_program_raw: Vec, - program: cairo_lang_sierra::program::Program, // for sierra emu + pub program: cairo_lang_sierra::program::Program, // for sierra emu fallback_entry_points_by_type: SierraContractEntryPoints, } diff --git a/crates/blockifier/src/execution/deprecated_entry_point_execution.rs b/crates/blockifier/src/execution/deprecated_entry_point_execution.rs index 4f84b19d03..878c2e276b 100644 --- a/crates/blockifier/src/execution/deprecated_entry_point_execution.rs +++ b/crates/blockifier/src/execution/deprecated_entry_point_execution.rs @@ -14,7 +14,9 @@ use crate::execution::call_info::{CallExecution, CallInfo}; use crate::execution::contract_class::ContractClassV0; use crate::execution::deprecated_syscalls::hint_processor::DeprecatedSyscallHintProcessor; use crate::execution::entry_point::{ - CallEntryPoint, EntryPointExecutionContext, EntryPointExecutionResult, + CallEntryPoint, + EntryPointExecutionContext, + EntryPointExecutionResult, }; use crate::execution::errors::{PostExecutionError, PreExecutionError}; use crate::execution::execution_utils::{read_execution_retdata, Args, ReadOnlySegments}; diff --git a/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs b/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs index 3106d562db..53722c921f 100644 --- a/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs +++ b/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs @@ -8,7 +8,13 @@ use rstest::rstest; use starknet_api::core::{calculate_contract_address, ChainId, PatriciaKey}; use starknet_api::state::StorageKey; use starknet_api::transaction::{ - Calldata, ContractAddressSalt, EventContent, EventData, EventKey, Fee, TransactionHash, + Calldata, + ContractAddressSalt, + EventContent, + EventData, + EventKey, + Fee, + TransactionHash, TransactionVersion, }; use starknet_api::{calldata, felt}; @@ -27,13 +33,22 @@ use crate::state::state_api::StateReader; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - calldata_for_deploy_test, get_syscall_resources, trivial_external_entry_point_new, - CairoVersion, CHAIN_ID_NAME, CURRENT_BLOCK_NUMBER, CURRENT_BLOCK_NUMBER_FOR_VALIDATE, - CURRENT_BLOCK_TIMESTAMP, CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE, TEST_SEQUENCER_ADDRESS, + calldata_for_deploy_test, + get_syscall_resources, + trivial_external_entry_point_new, + CairoVersion, + CHAIN_ID_NAME, + CURRENT_BLOCK_NUMBER, + CURRENT_BLOCK_NUMBER_FOR_VALIDATE, + CURRENT_BLOCK_TIMESTAMP, + CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE, + TEST_SEQUENCER_ADDRESS, }; use crate::transaction::constants::QUERY_VERSION_BASE_BIT; use crate::transaction::objects::{ - CommonAccountFields, DeprecatedTransactionInfo, TransactionInfo, + CommonAccountFields, + DeprecatedTransactionInfo, + TransactionInfo, }; use crate::versioned_constants::VersionedConstants; use crate::{check_entry_point_execution_error_for_custom_hint, nonce, retdata, storage_key}; diff --git a/crates/blockifier/src/execution/deprecated_syscalls/mod.rs b/crates/blockifier/src/execution/deprecated_syscalls/mod.rs index 1f81cffb80..9e75f5be6b 100644 --- a/crates/blockifier/src/execution/deprecated_syscalls/mod.rs +++ b/crates/blockifier/src/execution/deprecated_syscalls/mod.rs @@ -3,26 +3,45 @@ use cairo_vm::vm::vm_core::VirtualMachine; use serde::Deserialize; use starknet_api::block::{BlockNumber, BlockTimestamp}; use starknet_api::core::{ - calculate_contract_address, ClassHash, ContractAddress, EntryPointSelector, EthAddress, + calculate_contract_address, + ClassHash, + ContractAddress, + EntryPointSelector, + EthAddress, }; use starknet_api::deprecated_contract_class::EntryPointType; use starknet_api::state::StorageKey; use starknet_api::transaction::{ - Calldata, ContractAddressSalt, EventContent, EventData, EventKey, L2ToL1Payload, + Calldata, + ContractAddressSalt, + EventContent, + EventData, + EventKey, + L2ToL1Payload, }; use starknet_types_core::felt::Felt; use strum_macros::EnumIter; use self::hint_processor::{ - execute_inner_call, execute_library_call, felt_to_bool, read_call_params, read_calldata, - read_felt_array, DeprecatedSyscallExecutionError, DeprecatedSyscallHintProcessor, + execute_inner_call, + execute_library_call, + felt_to_bool, + read_call_params, + read_calldata, + read_felt_array, + DeprecatedSyscallExecutionError, + DeprecatedSyscallHintProcessor, }; use super::syscalls::exceeds_event_size_limit; use crate::execution::call_info::{MessageToL1, OrderedEvent, OrderedL2ToL1Message}; use crate::execution::common_hints::ExecutionMode; use crate::execution::entry_point::{CallEntryPoint, CallType, ConstructorContext}; use crate::execution::execution_utils::{ - execute_deployment, felt_from_ptr, write_felt, write_maybe_relocatable, ReadOnlySegment, + execute_deployment, + felt_from_ptr, + write_felt, + write_maybe_relocatable, + ReadOnlySegment, }; #[cfg(test)] diff --git a/crates/blockifier/src/execution/execution_utils.rs b/crates/blockifier/src/execution/execution_utils.rs index 6aa1e48a8c..bfd012edce 100644 --- a/crates/blockifier/src/execution/execution_utils.rs +++ b/crates/blockifier/src/execution/execution_utils.rs @@ -3,7 +3,11 @@ use std::env; use cairo_lang_runner::casm_run::format_next_item; use cairo_vm::serde::deserialize_program::{ - deserialize_array_of_bigint_hex, Attribute, HintParams, Identifier, ReferenceManager, + deserialize_array_of_bigint_hex, + Attribute, + HintParams, + Identifier, + ReferenceManager, }; use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::types::errors::program_errors::ProgramError; @@ -25,8 +29,11 @@ use super::errors::{ConstructorEntryPointExecutionError, EntryPointExecutionErro use crate::execution::call_info::{CallInfo, Retdata}; use crate::execution::contract_class::ContractClass; use crate::execution::entry_point::{ - execute_constructor_entry_point, CallEntryPoint, ConstructorContext, - EntryPointExecutionContext, EntryPointExecutionResult, + execute_constructor_entry_point, + CallEntryPoint, + ConstructorContext, + EntryPointExecutionContext, + EntryPointExecutionResult, }; use crate::execution::errors::PostExecutionError; use crate::execution::native::entry_point_execution as native_entry_point_execution; diff --git a/crates/blockifier/src/execution/native/entry_point_execution.rs b/crates/blockifier/src/execution/native/entry_point_execution.rs index 8e73ecd320..b7ef0c7463 100644 --- a/crates/blockifier/src/execution/native/entry_point_execution.rs +++ b/crates/blockifier/src/execution/native/entry_point_execution.rs @@ -1,13 +1,18 @@ -use cairo_vm::vm::runners::cairo_runner::ExecutionResources; +use std::sync::Arc; use std::time::Instant; +use cairo_vm::vm::runners::cairo_runner::ExecutionResources; + use super::syscall_handler::NativeSyscallHandler; use super::utils::run_native_executor; use crate::execution::call_info::CallInfo; use crate::execution::contract_class::NativeContractClassV1; use crate::execution::entry_point::{ - CallEntryPoint, EntryPointExecutionContext, EntryPointExecutionResult, + CallEntryPoint, + EntryPointExecutionContext, + EntryPointExecutionResult, }; +use crate::execution::native::utils::run_sierra_emu_executor; use crate::state::state_api::State; pub fn execute_entry_point_call( @@ -20,7 +25,7 @@ pub fn execute_entry_point_call( let function_id = contract_class.get_entrypoint(call.entry_point_type, call.entry_point_selector)?; - let syscall_handler: NativeSyscallHandler<'_> = NativeSyscallHandler::new( + let mut syscall_handler: NativeSyscallHandler<'_> = NativeSyscallHandler::new( state, call.caller_address, call.storage_address, @@ -36,8 +41,12 @@ pub fn execute_entry_point_call( let pre_execution_instant = Instant::now(); - let result = if cfg!(feature = "use-sierra-emu") { - todo!() + let result = if cfg!(feature = "use-sierra-emu") { + let vm = sierra_emu::VirtualMachine::new_starknet( + Arc::new(contract_class.program.clone()), + &mut syscall_handler, + ); + run_sierra_emu_executor(vm, function_id, call.clone()) } else { run_native_executor(&contract_class.executor, function_id, call, syscall_handler) }; diff --git a/crates/blockifier/src/execution/native/syscall_handler.rs b/crates/blockifier/src/execution/native/syscall_handler.rs index 477349269a..39dd12015a 100644 --- a/crates/blockifier/src/execution/native/syscall_handler.rs +++ b/crates/blockifier/src/execution/native/syscall_handler.rs @@ -5,38 +5,65 @@ use std::sync::Arc; use ark_ec::short_weierstrass::{Affine, Projective, SWCurveConfig}; use cairo_native::starknet::{ - BlockInfo, ExecutionInfo, ExecutionInfoV2, Secp256k1Point, Secp256r1Point, - StarknetSyscallHandler, SyscallResult, TxInfo, TxV2Info, U256, + BlockInfo, + ExecutionInfo, + ExecutionInfoV2, + Secp256k1Point, + Secp256r1Point, + StarknetSyscallHandler, + SyscallResult, + TxInfo, + TxV2Info, + U256, }; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use num_traits::{ToPrimitive, Zero}; use starknet_api::core::{ - calculate_contract_address, ClassHash, ContractAddress, EntryPointSelector, EthAddress, + calculate_contract_address, + ClassHash, + ContractAddress, + EntryPointSelector, + EthAddress, PatriciaKey, }; use starknet_api::data_availability::DataAvailabilityMode; use starknet_api::deprecated_contract_class::EntryPointType; use starknet_api::state::StorageKey; use starknet_api::transaction::{ - Calldata, ContractAddressSalt, EventContent, EventData, EventKey, L2ToL1Payload, + Calldata, + ContractAddressSalt, + EventContent, + EventData, + EventKey, + L2ToL1Payload, }; use starknet_types_core::felt::Felt; use super::utils::{ - big4int_to_u256, calculate_resource_bounds, contract_address_to_native_felt, - default_tx_v2_info, encode_str_as_felts, u256_to_biguint, + big4int_to_u256, + calculate_resource_bounds, + contract_address_to_native_felt, + default_tx_v2_info, + encode_str_as_felts, + u256_to_biguint, }; use crate::abi::constants; use crate::execution::call_info::{CallInfo, MessageToL1, OrderedEvent, OrderedL2ToL1Message}; use crate::execution::common_hints::ExecutionMode; use crate::execution::contract_class::ContractClass; use crate::execution::entry_point::{ - CallEntryPoint, CallType, ConstructorContext, EntryPointExecutionContext, + CallEntryPoint, + CallType, + ConstructorContext, + EntryPointExecutionContext, }; use crate::execution::execution_utils::{execute_deployment, max_fee_for_execution_info}; use crate::execution::syscalls::hint_processor::{ - SyscallCounter, SyscallExecutionError, BLOCK_NUMBER_OUT_OF_RANGE_ERROR, - INVALID_INPUT_LENGTH_ERROR, OUT_OF_GAS_ERROR, + SyscallCounter, + SyscallExecutionError, + BLOCK_NUMBER_OUT_OF_RANGE_ERROR, + INVALID_INPUT_LENGTH_ERROR, + OUT_OF_GAS_ERROR, }; use crate::execution::syscalls::{exceeds_event_size_limit, SyscallSelector}; use crate::state::state_api::State; @@ -875,28 +902,61 @@ impl<'state> StarknetSyscallHandler for &mut NativeSyscallHandler<'state> { pub mod sierra_emu_impl { use std::sync::Arc; + use num_traits::ToPrimitive; use sierra_emu::starknet::{ - BlockInfo, ExecutionInfo, ExecutionInfoV2, ResourceBounds, Secp256k1Point, Secp256r1Point, SyscallResult, TxInfo, TxV2Info, U256 + BlockInfo, + ExecutionInfo, + ExecutionInfoV2, + ResourceBounds, + Secp256k1Point, + Secp256r1Point, + SyscallResult, + TxInfo, + TxV2Info, + U256, }; - use starknet_api::{core::{calculate_contract_address, ClassHash, ContractAddress, EntryPointSelector, EthAddress, PatriciaKey}, data_availability::DataAvailabilityMode, deprecated_contract_class::EntryPointType, state::StorageKey, transaction::{Calldata, ContractAddressSalt, EventContent, EventData, EventKey, L2ToL1Payload}}; - use starknet_types_core::felt::Felt; - use num_traits::ToPrimitive; - - use crate::{ - abi::constants, - execution::{ - call_info::{MessageToL1, OrderedEvent, OrderedL2ToL1Message}, common_hints::ExecutionMode, contract_class::ContractClass, entry_point::{CallEntryPoint, CallType, ConstructorContext}, execution_utils::{execute_deployment, max_fee_for_execution_info}, native::utils::{ - calculate_resource_bounds, contract_address_to_native_felt, default_tx_v2_info_sierra_emu, encode_str_as_felts - }, syscalls::{ - exceeds_event_size_limit, hint_processor::{SyscallExecutionError, BLOCK_NUMBER_OUT_OF_RANGE_ERROR, INVALID_INPUT_LENGTH_ERROR, OUT_OF_GAS_ERROR}, SyscallSelector - } - }, - transaction::objects::TransactionInfo, + use starknet_api::core::{ + calculate_contract_address, + ClassHash, + ContractAddress, + EntryPointSelector, + EthAddress, + PatriciaKey, + }; + use starknet_api::data_availability::DataAvailabilityMode; + use starknet_api::deprecated_contract_class::EntryPointType; + use starknet_api::state::StorageKey; + use starknet_api::transaction::{ + Calldata, + ContractAddressSalt, + EventContent, + EventData, + EventKey, + L2ToL1Payload, }; + use starknet_types_core::felt::Felt; use super::{to_u256_native, NativeSyscallHandler, Secp256Point}; - - + use crate::abi::constants; + use crate::execution::call_info::{MessageToL1, OrderedEvent, OrderedL2ToL1Message}; + use crate::execution::common_hints::ExecutionMode; + use crate::execution::contract_class::ContractClass; + use crate::execution::entry_point::{CallEntryPoint, CallType, ConstructorContext}; + use crate::execution::execution_utils::{execute_deployment, max_fee_for_execution_info}; + use crate::execution::native::utils::{ + calculate_resource_bounds, + contract_address_to_native_felt, + default_tx_v2_info_sierra_emu, + encode_str_as_felts, + }; + use crate::execution::syscalls::hint_processor::{ + SyscallExecutionError, + BLOCK_NUMBER_OUT_OF_RANGE_ERROR, + INVALID_INPUT_LENGTH_ERROR, + OUT_OF_GAS_ERROR, + }; + use crate::execution::syscalls::{exceeds_event_size_limit, SyscallSelector}; + use crate::transaction::objects::TransactionInfo; impl<'state> sierra_emu::starknet::StarknetSyscallHandler for &mut NativeSyscallHandler<'state> { fn get_block_hash( @@ -925,14 +985,14 @@ pub mod sierra_emu_impl { if current_block_number < constants::STORED_BLOCK_HASH_BUFFER || block_number > current_block_number - constants::STORED_BLOCK_HASH_BUFFER { - // `panic` is unreachable in this case, also this is covered by tests so we can safely - // unwrap + // `panic` is unreachable in this case, also this is covered by tests so we can + // safely unwrap let out_of_range_felt = Felt::from_hex(BLOCK_NUMBER_OUT_OF_RANGE_ERROR).unwrap(); // This error is wrapped into a `SyscallExecutionError::SyscallError` in the VM // implementation, but here it would be more convenient to return it directly, since - // wrapping it like VM does will result in a double encoding to felts, which adds extra - // layer of complication + // wrapping it like VM does will result in a double encoding to felts, which adds + // extra layer of complication return Err(vec![out_of_range_felt]); } diff --git a/crates/blockifier/src/execution/native/utils.rs b/crates/blockifier/src/execution/native/utils.rs index f1917a2d84..a1d97d9ed9 100644 --- a/crates/blockifier/src/execution/native/utils.rs +++ b/crates/blockifier/src/execution/native/utils.rs @@ -1,5 +1,6 @@ use std::collections::{HashMap, HashSet}; use std::hash::RandomState; +use std::sync::atomic::AtomicUsize; use ark_ff::BigInt; use cairo_lang_sierra::ids::FunctionId; @@ -11,12 +12,19 @@ use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use itertools::Itertools; use num_bigint::BigUint; use num_traits::ToBytes; +use sierra_emu::{ProgramTrace, StateDump}; use starknet_api::core::{ContractAddress, EntryPointSelector}; use starknet_api::state::StorageKey; use starknet_api::transaction::Resource; use starknet_types_core::felt::Felt; -use crate::execution::call_info::{CallExecution, CallInfo, OrderedEvent, OrderedL2ToL1Message, Retdata}; +use crate::execution::call_info::{ + CallExecution, + CallInfo, + OrderedEvent, + OrderedL2ToL1Message, + Retdata, +}; use crate::execution::entry_point::{CallEntryPoint, EntryPointExecutionResult}; use crate::execution::errors::EntryPointExecutionError; use crate::execution::native::syscall_handler::NativeSyscallHandler; @@ -69,33 +77,50 @@ pub fn run_native_executor( } pub fn run_sierra_emu_executor( - native_executor: &AotNativeExecutor, + mut vm: sierra_emu::VirtualMachine<&mut NativeSyscallHandler<'_>>, function_id: &FunctionId, call: CallEntryPoint, - mut syscall_handler: NativeSyscallHandler<'_>, ) -> EntryPointExecutionResult { - let execution_result = native_executor.invoke_contract_dynamic( - function_id, - &call.calldata.0, - Some(call.initial_gas.into()), - &mut syscall_handler, - ); + let function = vm.registry().get_function(function_id).unwrap().clone(); - let run_result = match execution_result { - Ok(res) if res.failure_flag => Err(EntryPointExecutionError::NativeExecutionError { - info: if !res.return_values.is_empty() { - decode_felts_as_str(&res.return_values) + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let counter_value = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + + vm.call_contract(&function, call.initial_gas.into(), call.calldata.0.iter().cloned()); + + let mut trace = ProgramTrace::new(); + + while let Some((statement_idx, state)) = vm.step() { + trace.push(StateDump::new(statement_idx, state)); + } + + let execution_result = sierra_emu::ContractExecutionResult::from_trace(&trace).unwrap(); + + let trace = serde_json::to_string_pretty(&trace).unwrap(); + std::fs::create_dir_all("traces/emu/").unwrap(); + std::fs::write(format!("traces/emu/trace_{}.json", counter_value), trace).unwrap(); + + if execution_result.failure_flag { + Err(EntryPointExecutionError::NativeExecutionError { + info: if !execution_result.return_values.is_empty() { + decode_felts_as_str(&execution_result.return_values) + } else if let Some(error_msg) = execution_result.error_msg.clone() { + error_msg } else { String::from("Unknown error") }, - }), - Err(runner_err) => { - Err(EntryPointExecutionError::NativeUnexpectedError { source: runner_err }) - } - Ok(res) => Ok(res), - }?; + })?; + } - create_callinfo(call, run_result, syscall_handler) + create_callinfo_emu( + call.clone(), + execution_result, + vm.syscall_handler.events.clone(), + vm.syscall_handler.l2_to_l1_messages.clone(), + vm.syscall_handler.inner_calls.clone(), + vm.syscall_handler.storage_read_values.clone(), + vm.syscall_handler.accessed_storage_keys.clone(), + ) } fn create_callinfo( diff --git a/crates/blockifier/src/execution/native/utils_test.rs b/crates/blockifier/src/execution/native/utils_test.rs index 1cd541d774..163c2da401 100644 --- a/crates/blockifier/src/execution/native/utils_test.rs +++ b/crates/blockifier/src/execution/native/utils_test.rs @@ -9,8 +9,12 @@ use starknet_api::{contract_address, felt, patricia_key}; use starknet_types_core::felt::Felt; use super::{ - big4int_to_u256, contract_address_to_native_felt, contract_entrypoint_to_entrypoint_selector, - decode_felts_as_str, encode_str_as_felts, u256_to_biguint, + big4int_to_u256, + contract_address_to_native_felt, + contract_entrypoint_to_entrypoint_selector, + decode_felts_as_str, + encode_str_as_felts, + u256_to_biguint, }; #[test] diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/get_block_hash.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/get_block_hash.rs index 03b50bd1fe..0b3880321e 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/get_block_hash.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/get_block_hash.rs @@ -18,7 +18,10 @@ use crate::test_utils::contracts::FeatureContract; use crate::test_utils::dict_state_reader::DictStateReader; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - trivial_external_entry_point_new, CairoVersion, BALANCE, CURRENT_BLOCK_NUMBER, + trivial_external_entry_point_new, + CairoVersion, + BALANCE, + CURRENT_BLOCK_NUMBER, }; fn initialize_state(test_contract: FeatureContract) -> (CachedState, Felt, Felt) { @@ -72,9 +75,11 @@ fn negative_flow_execution_mode_validate(test_contract: FeatureContract) { let error = entry_point_call.execute_directly_in_validate_mode(&mut state).unwrap_err(); - assert!(error - .to_string() - .contains("Unauthorized syscall get_block_hash in execution mode Validate")); + assert!( + error + .to_string() + .contains("Unauthorized syscall get_block_hash in execution mode Validate") + ); } #[test_case(FeatureContract::TestContract(CairoVersion::Native); "Native")] diff --git a/crates/blockifier/src/execution/syscalls/syscall_tests/library_call.rs b/crates/blockifier/src/execution/syscalls/syscall_tests/library_call.rs index ce304ab7e8..7cbed935a7 100644 --- a/crates/blockifier/src/execution/syscalls/syscall_tests/library_call.rs +++ b/crates/blockifier/src/execution/syscalls/syscall_tests/library_call.rs @@ -14,14 +14,18 @@ use crate::context::ChainInfo; use crate::execution::call_info::{CallExecution, CallInfo, Retdata}; use crate::execution::entry_point::{CallEntryPoint, CallType}; use crate::execution::syscalls::syscall_tests::constants::{ - REQUIRED_GAS_LIBRARY_CALL_TEST, REQUIRED_GAS_STORAGE_READ_WRITE_TEST, + REQUIRED_GAS_LIBRARY_CALL_TEST, + REQUIRED_GAS_STORAGE_READ_WRITE_TEST, }; use crate::execution::syscalls::SyscallSelector; use crate::retdata; use crate::test_utils::contracts::FeatureContract; use crate::test_utils::initial_test_state::test_state; use crate::test_utils::{ - get_syscall_resources, trivial_external_entry_point_new, CairoVersion, BALANCE, + get_syscall_resources, + trivial_external_entry_point_new, + CairoVersion, + BALANCE, }; #[test_case(FeatureContract::TestContract(CairoVersion::Native), 187670; "Native" diff --git a/crates/blockifier/src/fee/actual_cost.rs b/crates/blockifier/src/fee/actual_cost.rs index 73d6992da4..36967058b8 100644 --- a/crates/blockifier/src/fee/actual_cost.rs +++ b/crates/blockifier/src/fee/actual_cost.rs @@ -7,7 +7,10 @@ use crate::execution::call_info::CallInfo; use crate::state::cached_state::StateChanges; use crate::transaction::account_transaction::AccountTransaction; use crate::transaction::objects::{ - GasVector, HasRelatedFeeType, StarknetResources, TransactionExecutionResult, + GasVector, + HasRelatedFeeType, + StarknetResources, + TransactionExecutionResult, TransactionResources, }; use crate::transaction::transaction_types::TransactionType; diff --git a/crates/blockifier/src/fee/fee_checks.rs b/crates/blockifier/src/fee/fee_checks.rs index f613ec9848..d09c96de80 100644 --- a/crates/blockifier/src/fee/fee_checks.rs +++ b/crates/blockifier/src/fee/fee_checks.rs @@ -9,7 +9,10 @@ use crate::fee::gas_usage::compute_discounted_gas_from_gas_vector; use crate::state::state_api::StateReader; use crate::transaction::errors::TransactionExecutionError; use crate::transaction::objects::{ - FeeType, GasVector, TransactionExecutionResult, TransactionInfo, + FeeType, + GasVector, + TransactionExecutionResult, + TransactionInfo, }; #[derive(Clone, Copy, Debug, Error)] diff --git a/crates/blockifier/src/fee/fee_test.rs b/crates/blockifier/src/fee/fee_test.rs index a50261e288..9c86e5f9d3 100644 --- a/crates/blockifier/src/fee/fee_test.rs +++ b/crates/blockifier/src/fee/fee_test.rs @@ -51,8 +51,8 @@ fn test_simple_calculate_l1_gas_by_vm_usage() { let l1_gas_by_vm_usage = (*versioned_constants.vm_resource_fee_cost().get(N_STEPS_RESOURCE).unwrap() * (u128_from_usize(vm_resource_usage.n_steps + n_reverted_steps))) - .ceil() - .to_integer(); + .ceil() + .to_integer(); assert_eq!( GasVector::from_l1_gas(l1_gas_by_vm_usage), calculate_l1_gas_by_vm_usage(&versioned_constants, &vm_resource_usage, n_reverted_steps) @@ -83,8 +83,8 @@ fn test_float_calculate_l1_gas_by_vm_usage() { let l1_gas_by_vm_usage = ((*versioned_constants.vm_resource_fee_cost().get(N_STEPS_RESOURCE).unwrap()) * u128_from_usize(vm_resource_usage.n_steps + n_reverted_steps)) - .ceil() - .to_integer(); + .ceil() + .to_integer(); assert_eq!( GasVector::from_l1_gas(l1_gas_by_vm_usage), calculate_l1_gas_by_vm_usage(&versioned_constants, &vm_resource_usage, n_reverted_steps) @@ -98,10 +98,10 @@ fn test_float_calculate_l1_gas_by_vm_usage() { .get(BuiltinName::ecdsa.to_str_with_suffix()) .unwrap()) * u128_from_usize( - *vm_resource_usage.builtin_instance_counter.get(&BuiltinName::ecdsa).unwrap(), - )) - .ceil() - .to_integer(); + *vm_resource_usage.builtin_instance_counter.get(&BuiltinName::ecdsa).unwrap(), + )) + .ceil() + .to_integer(); assert_eq!( GasVector::from_l1_gas(l1_gas_by_vm_usage), @@ -166,7 +166,7 @@ fn test_discounted_gas_overdraft( &tx_receipt, charge_fee, ) - .unwrap(); + .unwrap(); if expect_failure { let error = report.error().unwrap(); diff --git a/crates/blockifier/src/test_utils/declare.rs b/crates/blockifier/src/test_utils/declare.rs index 5259154361..ab5470c130 100644 --- a/crates/blockifier/src/test_utils/declare.rs +++ b/crates/blockifier/src/test_utils/declare.rs @@ -1,8 +1,16 @@ use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; use starknet_api::data_availability::DataAvailabilityMode; use starknet_api::transaction::{ - AccountDeploymentData, DeclareTransactionV0V1, DeclareTransactionV2, DeclareTransactionV3,DeprecatedResourceBoundsMapping, Fee, - PaymasterData, Tip, TransactionHash, TransactionSignature, + AccountDeploymentData, + DeclareTransactionV0V1, + DeclareTransactionV2, + DeclareTransactionV3, + DeprecatedResourceBoundsMapping, + Fee, + PaymasterData, + Tip, + TransactionHash, + TransactionSignature, TransactionVersion, }; diff --git a/crates/blockifier/src/test_utils/deploy_account.rs b/crates/blockifier/src/test_utils/deploy_account.rs index 979fa29509..1ae7a58340 100644 --- a/crates/blockifier/src/test_utils/deploy_account.rs +++ b/crates/blockifier/src/test_utils/deploy_account.rs @@ -1,8 +1,16 @@ use starknet_api::core::{calculate_contract_address, ClassHash, ContractAddress, Nonce}; use starknet_api::data_availability::DataAvailabilityMode; use starknet_api::transaction::{ - Calldata, ContractAddressSalt, DeployAccountTransactionV1, DeployAccountTransactionV3,DeprecatedResourceBoundsMapping, Fee, - PaymasterData, Tip, TransactionHash, TransactionSignature, + Calldata, + ContractAddressSalt, + DeployAccountTransactionV1, + DeployAccountTransactionV3, + DeprecatedResourceBoundsMapping, + Fee, + PaymasterData, + Tip, + TransactionHash, + TransactionSignature, TransactionVersion, }; diff --git a/crates/blockifier/src/test_utils/invoke.rs b/crates/blockifier/src/test_utils/invoke.rs index 8defe1aca7..b1e025bc0e 100644 --- a/crates/blockifier/src/test_utils/invoke.rs +++ b/crates/blockifier/src/test_utils/invoke.rs @@ -2,9 +2,18 @@ use starknet_api::calldata; use starknet_api::core::{ContractAddress, Nonce}; use starknet_api::data_availability::DataAvailabilityMode; use starknet_api::transaction::{ - AccountDeploymentData, Calldata,DeprecatedResourceBoundsMapping, Fee, InvokeTransactionV0, InvokeTransactionV1, - InvokeTransactionV3, PaymasterData, Tip, TransactionHash, - TransactionSignature, TransactionVersion, + AccountDeploymentData, + Calldata, + DeprecatedResourceBoundsMapping, + Fee, + InvokeTransactionV0, + InvokeTransactionV1, + InvokeTransactionV3, + PaymasterData, + Tip, + TransactionHash, + TransactionSignature, + TransactionVersion, }; use crate::abi::abi_utils::selector_from_name; diff --git a/crates/blockifier/src/transaction/objects_test.rs b/crates/blockifier/src/transaction/objects_test.rs index 7d1ef479e1..10e0a954d6 100644 --- a/crates/blockifier/src/transaction/objects_test.rs +++ b/crates/blockifier/src/transaction/objects_test.rs @@ -3,7 +3,11 @@ use starknet_api::core::ClassHash; use starknet_api::{class_hash, felt}; use crate::execution::call_info::{ - CallExecution, CallInfo, ExecutionSummary, OrderedEvent, TestExecutionSummary, + CallExecution, + CallInfo, + ExecutionSummary, + OrderedEvent, + TestExecutionSummary, }; use crate::execution::entry_point::CallEntryPoint; use crate::transaction::objects::TransactionExecutionInfo; diff --git a/crates/blockifier/src/utils_test.rs b/crates/blockifier/src/utils_test.rs index 48a6fb4695..de44312e42 100644 --- a/crates/blockifier/src/utils_test.rs +++ b/crates/blockifier/src/utils_test.rs @@ -4,7 +4,10 @@ use std::num::NonZeroU128; use pretty_assertions::assert_eq; use crate::utils::{ - strict_subtract_mappings, subtract_mappings, u128_div_ceil, STRICT_SUBTRACT_MAPPING_ERROR, + strict_subtract_mappings, + subtract_mappings, + u128_div_ceil, + STRICT_SUBTRACT_MAPPING_ERROR, }; #[test] diff --git a/crates/starknet_client/src/reader/starknet_feeder_gateway_client_test.rs b/crates/starknet_client/src/reader/starknet_feeder_gateway_client_test.rs index 2767a4bb57..835b433501 100644 --- a/crates/starknet_client/src/reader/starknet_feeder_gateway_client_test.rs +++ b/crates/starknet_client/src/reader/starknet_feeder_gateway_client_test.rs @@ -198,15 +198,16 @@ async fn contract_class() { abi: String::from("[\n {\n \"type\": \"function\",\n \"name\": \"test\",\n \"inputs\": [\n {\n \"name\": \"arg\",\n \"ty\": \"core::felt\"\n },\n {\n \"name\": \"arg1\",\n \"ty\": \"core::felt\"\n },\n {\n \"name\": \"arg2\",\n \"ty\": \"core::felt\"\n }\n ],\n \"output_ty\": \"core::felt\",\n \"state_mutability\": \"external\"\n },\n {\n \"type\": \"function\",\n \"name\": \"empty\",\n \"inputs\": [],\n \"output_ty\": \"()\",\n \"state_mutability\": \"external\"\n },\n {\n \"type\": \"function\",\n \"name\": \"call_foo\",\n \"inputs\": [\n {\n \"name\": \"a\",\n \"ty\": \"core::integer::u128\"\n }\n ],\n \"output_ty\": \"core::integer::u128\",\n \"state_mutability\": \"external\"\n }\n]"), }; - let mock_by_hash = - mock( - "GET", - &format!("/feeder_gateway/get_class_by_hash?blockNumber=pending&\ - {CLASS_HASH_QUERY}=0x4e70b19333ae94bd958625f7b61ce9eec631653597e68645e13780061b2136c")[..], - ) - .with_status(200) - .with_body(read_resource_file("reader/contract_class.json")) - .create(); + let mock_by_hash = mock( + "GET", + &format!( + "/feeder_gateway/get_class_by_hash?blockNumber=pending&\ + {CLASS_HASH_QUERY}=0x4e70b19333ae94bd958625f7b61ce9eec631653597e68645e13780061b2136c" + )[..], + ) + .with_status(200) + .with_body(read_resource_file("reader/contract_class.json")) + .create(); let contract_class = starknet_client .class_by_hash(ClassHash(felt!( "0x4e70b19333ae94bd958625f7b61ce9eec631653597e68645e13780061b2136c" @@ -283,15 +284,16 @@ async fn deprecated_contract_class() { ), ]), }; - let mock_by_hash = - mock( - "GET", - &format!("/feeder_gateway/get_class_by_hash?blockNumber=pending&\ - {CLASS_HASH_QUERY}=0x7af612493193c771c1b12f511a8b4d3b0c6d0648242af4680c7cd0d06186f17")[..], - ) - .with_status(200) - .with_body(read_resource_file("reader/deprecated_contract_class.json")) - .create(); + let mock_by_hash = mock( + "GET", + &format!( + "/feeder_gateway/get_class_by_hash?blockNumber=pending&\ + {CLASS_HASH_QUERY}=0x7af612493193c771c1b12f511a8b4d3b0c6d0648242af4680c7cd0d06186f17" + )[..], + ) + .with_status(200) + .with_body(read_resource_file("reader/deprecated_contract_class.json")) + .create(); let contract_class = starknet_client .class_by_hash(ClassHash(felt!( "0x7af612493193c771c1b12f511a8b4d3b0c6d0648242af4680c7cd0d06186f17"