Skip to content

Commit

Permalink
refactor(blockifier): refactor blockifier contract class
Browse files Browse the repository at this point in the history
  • Loading branch information
AvivYossef-starkware committed Dec 19, 2024
1 parent 4cb3bca commit 4022be4
Show file tree
Hide file tree
Showing 28 changed files with 127 additions and 90 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"sierra_program": [
"0x1",
"0x6",
"0x5",
"0x0",
"0x2",
"0x7",
Expand Down
4 changes: 2 additions & 2 deletions crates/blockifier/resources/versioned_constants_0_13_0.json
Original file line number Diff line number Diff line change
Expand Up @@ -567,7 +567,7 @@
},
"validate_max_n_steps": 1000000,
"validate_max_sierra_gas": 10000000000,
"min_compiler_version_for_sierra_gas": "100.0.0",
"min_sierra_version_for_sierra_gas": "100.0.0",
"vm_resource_fee_cost": {
"builtins": {
"add_mod_builtin": [
Expand Down Expand Up @@ -620,4 +620,4 @@
1000
]
}
}
}
4 changes: 2 additions & 2 deletions crates/blockifier/resources/versioned_constants_0_13_1.json
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,7 @@
},
"validate_max_n_steps": 1000000,
"validate_max_sierra_gas": 10000000000,
"min_compiler_version_for_sierra_gas": "100.0.0",
"min_sierra_version_for_sierra_gas": "100.0.0",
"vm_resource_fee_cost": {
"builtins": {
"add_mod_builtin": [
Expand Down Expand Up @@ -656,4 +656,4 @@
10000
]
}
}
}
4 changes: 2 additions & 2 deletions crates/blockifier/resources/versioned_constants_0_13_1_1.json
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,7 @@
},
"validate_max_n_steps": 1000000,
"validate_max_sierra_gas": 10000000000,
"min_compiler_version_for_sierra_gas": "100.0.0",
"min_sierra_version_for_sierra_gas": "100.0.0",
"vm_resource_fee_cost": {
"builtins": {
"add_mod_builtin": [
Expand Down Expand Up @@ -656,4 +656,4 @@
10000
]
}
}
}
4 changes: 2 additions & 2 deletions crates/blockifier/resources/versioned_constants_0_13_2.json
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@
},
"validate_max_n_steps": 1000000,
"validate_max_sierra_gas": 10000000000,
"min_compiler_version_for_sierra_gas": "100.0.0",
"min_sierra_version_for_sierra_gas": "100.0.0",
"vm_resource_fee_cost": {
"builtins": {
"add_mod_builtin": [
Expand Down Expand Up @@ -663,4 +663,4 @@
10000
]
}
}
}
4 changes: 2 additions & 2 deletions crates/blockifier/resources/versioned_constants_0_13_2_1.json
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@
},
"validate_max_n_steps": 1000000,
"validate_max_sierra_gas": 10000000000,
"min_compiler_version_for_sierra_gas": "100.0.0",
"min_sierra_version_for_sierra_gas": "100.0.0",
"vm_resource_fee_cost": {
"builtins": {
"add_mod_builtin": [
Expand Down Expand Up @@ -663,4 +663,4 @@
10000
]
}
}
}
4 changes: 2 additions & 2 deletions crates/blockifier/resources/versioned_constants_0_13_3.json
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@
},
"validate_max_n_steps": 1000000,
"validate_max_sierra_gas": 10000000000,
"min_compiler_version_for_sierra_gas": "100.0.0",
"min_sierra_version_for_sierra_gas": "100.0.0",
"vm_resource_fee_cost": {
"builtins": {
"add_mod_builtin": [
Expand Down Expand Up @@ -663,4 +663,4 @@
10000
]
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@
},
"validate_max_n_steps": 1000000,
"validate_max_sierra_gas": 100000000,
"min_compiler_version_for_sierra_gas": "2.8.0",
"min_sierra_version_for_sierra_gas": "1.6.0",
"vm_resource_fee_cost": {
"builtins": {
"add_mod_builtin": [
Expand Down
29 changes: 13 additions & 16 deletions crates/blockifier/src/execution/contract_class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@ use cairo_vm::types::program::Program;
use cairo_vm::types::relocatable::MaybeRelocatable;
use cairo_vm::vm::runners::cairo_runner::ExecutionResources;
use itertools::Itertools;
use semver::Version;
use serde::de::Error as DeserializationError;
use serde::{Deserialize, Deserializer, Serialize};
use starknet_api::contract_class::{ContractClass, EntryPointType, SierraVersion};
use starknet_api::contract_class::{ContractClass, EntryPointType, SierraVersion, VersionedCasm};
use starknet_api::core::EntryPointSelector;
use starknet_api::deprecated_contract_class::{
ContractClass as DeprecatedContractClass,
Expand All @@ -38,7 +37,6 @@ use crate::execution::execution_utils::{poseidon_hash_many_cost, sn_api_to_cairo
#[cfg(feature = "cairo_native")]
use crate::execution::native::contract_class::NativeCompiledClassV1;
use crate::transaction::errors::TransactionExecutionError;
use crate::versioned_constants::CompilerVersion;

#[cfg(test)]
#[path = "contract_class_test.rs"]
Expand Down Expand Up @@ -70,6 +68,7 @@ pub enum RunnableCompiledClass {
/// Represents a runnable compiled class for Cairo, with the Sierra version (for Cairo 1).
#[derive(Clone)]
pub enum VersionedRunnableCompiledClass {
// TODO(Aviv): Delete this enum.
Cairo0(RunnableCompiledClass),
Cairo1((RunnableCompiledClass, SierraVersion)),
}
Expand All @@ -93,7 +92,7 @@ impl TryFrom<ContractClass> for RunnableCompiledClass {
fn try_from(raw_contract_class: ContractClass) -> Result<Self, Self::Error> {
let contract_class: Self = match raw_contract_class {
ContractClass::V0(raw_contract_class) => Self::V0(raw_contract_class.try_into()?),
ContractClass::V1(raw_contract_class) => Self::V1(raw_contract_class.try_into()?),
ContractClass::V1(versioned_casm) => Self::V1(versioned_casm.try_into()?),
};

Ok(contract_class)
Expand Down Expand Up @@ -151,7 +150,7 @@ impl RunnableCompiledClass {
/// Returns whether this contract should run using Cairo steps or Sierra gas.
pub fn tracked_resource(
&self,
min_sierra_version: &CompilerVersion,
min_sierra_version: &SierraVersion,
last_tracked_resource: Option<&TrackedResource>,
) -> TrackedResource {
let contract_tracked_resource = match self {
Expand Down Expand Up @@ -283,8 +282,8 @@ impl CompiledClassV1 {
}

/// Returns whether this contract should run using Cairo steps or Sierra gas.
pub fn tracked_resource(&self, min_sierra_version: &CompilerVersion) -> TrackedResource {
if *min_sierra_version <= self.compiler_version {
pub fn tracked_resource(&self, min_sierra_version: &SierraVersion) -> TrackedResource {
if *min_sierra_version <= self.sierra_version {
TrackedResource::SierraGas
} else {
TrackedResource::CairoSteps
Expand All @@ -310,7 +309,9 @@ impl CompiledClassV1 {

pub fn try_from_json_string(raw_contract_class: &str) -> Result<CompiledClassV1, ProgramError> {
let casm_contract_class: CasmContractClass = serde_json::from_str(raw_contract_class)?;
let contract_class = CompiledClassV1::try_from(casm_contract_class)?;
// TODO(Aviv): Use Sierra version received from Python state reader.
let sierra_version = SierraVersion::DEPRECATED;
let contract_class = CompiledClassV1::try_from((casm_contract_class, sierra_version))?;

Ok(contract_class)
}
Expand Down Expand Up @@ -412,7 +413,7 @@ pub struct ContractClassV1Inner {
pub program: Program,
pub entry_points_by_type: EntryPointsByType<EntryPointV1>,
pub hints: HashMap<String, Hint>,
pub compiler_version: CompilerVersion,
pub sierra_version: SierraVersion,
bytecode_segment_lengths: NestedIntList,
}

Expand All @@ -435,10 +436,10 @@ impl HasSelector for EntryPointV1 {
}
}

impl TryFrom<CasmContractClass> for CompiledClassV1 {
impl TryFrom<VersionedCasm> for CompiledClassV1 {
type Error = ProgramError;

fn try_from(class: CasmContractClass) -> Result<Self, Self::Error> {
fn try_from((class, sierra_version): VersionedCasm) -> Result<Self, Self::Error> {
let data: Vec<MaybeRelocatable> =
class.bytecode.iter().map(|x| MaybeRelocatable::from(Felt::from(&x.value))).collect();

Expand Down Expand Up @@ -484,15 +485,11 @@ impl TryFrom<CasmContractClass> for CompiledClassV1 {
let bytecode_segment_lengths = class
.bytecode_segment_lengths
.unwrap_or_else(|| NestedIntList::Leaf(program.data_len()));
let compiler_version = CompilerVersion(
Version::parse(&class.compiler_version)
.unwrap_or_else(|_| panic!("Invalid version: '{}'", class.compiler_version)),
);
Ok(CompiledClassV1(Arc::new(ContractClassV1Inner {
program,
entry_points_by_type,
hints: string_to_hint,
compiler_version,
sierra_version,
bytecode_segment_lengths,
})))
}
Expand Down
2 changes: 1 addition & 1 deletion crates/blockifier/src/execution/contract_class_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fn test_get_visited_segments() {
program: Default::default(),
entry_points_by_type: Default::default(),
hints: Default::default(),
compiler_version: Default::default(),
sierra_version: Default::default(),
bytecode_segment_lengths: NestedIntList::Node(vec![
NestedIntList::Leaf(151),
NestedIntList::Leaf(104),
Expand Down
2 changes: 1 addition & 1 deletion crates/blockifier/src/execution/execution_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub fn execute_entry_point_call_wrapper(
remaining_gas: &mut u64,
) -> EntryPointExecutionResult<CallInfo> {
let current_tracked_resource = compiled_class.tracked_resource(
&context.versioned_constants().min_compiler_version_for_sierra_gas,
&context.versioned_constants().min_sierra_version_for_sierra_gas,
context.tracked_resource_stack.last(),
);
if current_tracked_resource == TrackedResource::CairoSteps {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ fn test_nested_library_call(runnable_version: RunnableCairo1) {

// The default VersionedConstants is used in the execute_directly call bellow.
let tracked_resource = test_contract.get_runnable_class().tracked_resource(
&VersionedConstants::create_for_testing().min_compiler_version_for_sierra_gas,
&VersionedConstants::create_for_testing().min_sierra_version_for_sierra_gas,
None,
);

Expand Down
7 changes: 4 additions & 3 deletions crates/blockifier/src/test_utils/contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,10 @@ impl FeatureContract {
CairoVersion::Cairo0 => {
ContractClass::V0(DeprecatedContractClass::from_file(&self.get_compiled_path()))
}
CairoVersion::Cairo1(RunnableCairo1::Casm) => {
ContractClass::V1(CasmContractClass::from_file(&self.get_compiled_path()))
}
CairoVersion::Cairo1(RunnableCairo1::Casm) => ContractClass::V1((
CasmContractClass::from_file(&self.get_compiled_path()),
self.get_sierra_version(),
)),
#[cfg(feature = "cairo_native")]
CairoVersion::Cairo1(RunnableCairo1::Native) => {
panic!("Native contracts are not supported by this function.")
Expand Down
14 changes: 13 additions & 1 deletion crates/blockifier/src/test_utils/struct_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ use cairo_native::executor::AotContractExecutor;
use serde_json::Value;
use starknet_api::block::BlockInfo;
use starknet_api::contract_address;
#[cfg(feature = "cairo_native")]
use starknet_api::contract_class::SierraVersion;
use starknet_api::core::{ChainId, ClassHash};
use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContractClass;
use starknet_api::test_utils::{TEST_ERC20_CONTRACT_ADDRESS, TEST_ERC20_CONTRACT_ADDRESS2};
Expand Down Expand Up @@ -212,6 +214,16 @@ impl NativeCompiledClassV1 {
.extract_sierra_program()
.expect("Cannot extract sierra program from sierra contract class");

let sierra_version_values = sierra_contract_class
.sierra_program
.iter()
.take(3)
.map(|x| x.value.clone())
.collect::<Vec<_>>();

let sierra_version = SierraVersion::extract_from_program(&sierra_version_values)
.expect("Cannot extract sierra version from sierra program");

let executor = AotContractExecutor::new(
&sierra_program,
&sierra_contract_class.entry_points_by_type,
Expand All @@ -223,7 +235,7 @@ impl NativeCompiledClassV1 {
let casm_contract_class =
CasmContractClass::from_contract_class(sierra_contract_class, false, usize::MAX)
.expect("Cannot compile sierra contract class into casm contract class");
let casm = CompiledClassV1::try_from(casm_contract_class)
let casm = CompiledClassV1::try_from((casm_contract_class, sierra_version))
.expect("Cannot get CompiledClassV1 from CasmContractClass");

NativeCompiledClassV1::new(executor, casm)
Expand Down
14 changes: 7 additions & 7 deletions crates/blockifier/src/transaction/transactions_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,7 @@ fn test_invoke_tx(

let tracked_resource = account_contract
.get_runnable_class()
.tracked_resource(&versioned_constants.min_compiler_version_for_sierra_gas, None);
.tracked_resource(&versioned_constants.min_sierra_version_for_sierra_gas, None);

// Build expected validate call info.
let expected_account_class_hash = account_contract.get_class_hash();
Expand Down Expand Up @@ -1617,7 +1617,7 @@ fn test_declare_tx(
sender_address,
account
.get_runnable_class()
.tracked_resource(&versioned_constants.min_compiler_version_for_sierra_gas, None),
.tracked_resource(&versioned_constants.min_sierra_version_for_sierra_gas, None),
if tx_version >= TransactionVersion::THREE {
Some(user_initial_gas_from_bounds(default_all_resource_bounds, Some(block_context)))
} else {
Expand Down Expand Up @@ -1826,7 +1826,7 @@ fn test_deploy_account_tx(
cairo_version,
account
.get_runnable_class()
.tracked_resource(&versioned_constants.min_compiler_version_for_sierra_gas, None),
.tracked_resource(&versioned_constants.min_sierra_version_for_sierra_gas, None),
Some(user_initial_gas),
);

Expand Down Expand Up @@ -2365,7 +2365,7 @@ fn test_l1_handler(#[values(false, true)] use_kzg_da: bool) {
accessed_storage_keys: HashSet::from_iter(vec![accessed_storage_key]),
tracked_resource: test_contract
.get_runnable_class()
.tracked_resource(&versioned_constants.min_compiler_version_for_sierra_gas, None),
.tracked_resource(&versioned_constants.min_sierra_version_for_sierra_gas, None),
..Default::default()
};

Expand Down Expand Up @@ -2679,10 +2679,10 @@ fn test_invoke_max_sierra_gas_validate_execute(

let account_tracked_resource = account_contract
.get_runnable_class()
.tracked_resource(&versioned_constants.min_compiler_version_for_sierra_gas, None);
.tracked_resource(&versioned_constants.min_sierra_version_for_sierra_gas, None);

let contract_tracked_resource = test_contract.get_runnable_class().tracked_resource(
&versioned_constants.min_compiler_version_for_sierra_gas,
&versioned_constants.min_sierra_version_for_sierra_gas,
Some(&account_tracked_resource),
);

Expand Down Expand Up @@ -2802,7 +2802,7 @@ fn test_deploy_max_sierra_gas_validate_execute(

let account_tracked_resource = account
.get_runnable_class()
.tracked_resource(&versioned_constants.min_compiler_version_for_sierra_gas, None);
.tracked_resource(&versioned_constants.min_sierra_version_for_sierra_gas, None);

let actual_execution_info = deploy_account.execute(state, &block_context).unwrap();

Expand Down
3 changes: 2 additions & 1 deletion crates/blockifier/src/versioned_constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use serde::de::Error as DeserializationError;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Map, Number, Value};
use starknet_api::block::{GasPrice, StarknetVersion};
use starknet_api::contract_class::SierraVersion;
use starknet_api::core::ContractAddress;
use starknet_api::execution_resources::{GasAmount, GasVector};
use starknet_api::transaction::fields::GasVectorComputationMode;
Expand Down Expand Up @@ -185,7 +186,7 @@ pub struct VersionedConstants {
pub max_recursion_depth: usize,
pub validate_max_n_steps: u32,
pub validate_max_sierra_gas: GasAmount,
pub min_compiler_version_for_sierra_gas: CompilerVersion,
pub min_sierra_version_for_sierra_gas: SierraVersion,
// BACKWARD COMPATIBILITY: If true, the segment_arena builtin instance counter will be
// multiplied by 3. This offsets a bug in the old vm where the counter counted the number of
// cells used by instances of the builtin, instead of the number of instances.
Expand Down
Loading

0 comments on commit 4022be4

Please sign in to comment.