Skip to content

Commit

Permalink
dev: update sequencer
Browse files Browse the repository at this point in the history
  • Loading branch information
enitrat committed Dec 3, 2024
1 parent 3387cc8 commit 4b23bbe
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 202 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/blockifier/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ ark-secp256r1.workspace = true
cached.workspace = true
cairo-lang-casm = { workspace = true, features = ["parity-scale-codec"] }
cairo-lang-runner.workspace = true
cairo-lang-utils.workspace = true
cairo-lang-starknet-classes.workspace = true
cairo-native = { workspace = true, optional = true }
cairo-vm.workspace = true
Expand Down
219 changes: 21 additions & 198 deletions crates/blockifier/src/execution/contract_class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ use cairo_vm::types::program::Program;
use cairo_vm::types::relocatable::MaybeRelocatable;
use cairo_vm::vm::runners::cairo_runner::ExecutionResources;
use itertools::Itertools;
use num_traits::Num;

use semver::Version;
use serde::de::Error as DeserializationError;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
Expand All @@ -32,13 +34,11 @@ use starknet_api::deprecated_contract_class::{
use starknet_api::transaction::fields::GasVectorComputationMode;
use starknet_types_core::felt::Felt;

use crate::abi::constants::{self};
use super::execution_utils::{cairo_vm_to_sn_api_program, poseidon_hash_many_cost};
use crate::abi::abi_utils::selector_from_name;
use crate::abi::constants::{self, CONSTRUCTOR_ENTRY_POINT_NAME};
use super::execution_utils::{sn_api_to_cairo_vm_program, cairo_vm_to_sn_api_program, poseidon_hash_many_cost};
use crate::abi::constants;
use crate::execution::entry_point::CallEntryPoint;
use crate::execution::errors::PreExecutionError;
use crate::execution::execution_utils::{poseidon_hash_many_cost, sn_api_to_cairo_vm_program};

#[cfg(feature = "cairo_native")]
use crate::execution::native::contract_class::NativeCompiledClassV1;
use crate::transaction::errors::TransactionExecutionError;
Expand Down Expand Up @@ -213,7 +213,7 @@ impl CompiledClassV0 {

#[derive(Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
pub struct CompiledClassV0Inner {
#[serde(deserialize_with = "deserialize_program")]
#[serde(deserialize_with = "deserialize_program", serialize_with = "serialize_program")]
pub program: Program,
pub entry_points_by_type: HashMap<EntryPointType, Vec<EntryPointV0>>,
}
Expand All @@ -235,9 +235,9 @@ impl TryFrom<DeprecatedContractClass> for CompiledClassV0 {
/// by the VM). We wrap the actual class in an Arc to avoid cloning the program when cloning the
/// class.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompiledClassV1(pub Arc<ContractClassV1Inner>);
pub struct CompiledClassV1(pub Arc<CompiledClassV1Inner>);
impl Deref for CompiledClassV1 {
type Target = ContractClassV1Inner;
type Target = CompiledClassV1Inner;

fn deref(&self) -> &Self::Target {
&self.0
Expand All @@ -249,7 +249,7 @@ impl Serialize for CompiledClassV1 {
where
S: Serializer,
{
// Convert the ContractClassV1 instance to CasmContractClass
// Convert the CompiledClassV1 instance to CasmContractClass
let casm_contract_class: CasmContractClass = self
.try_into()
.map_err(|err: ProgramError| serde::ser::Error::custom(err.to_string()))?;
Expand All @@ -259,57 +259,6 @@ impl Serialize for CompiledClassV1 {
}
}

impl<'de> Deserialize<'de> for CompiledClassV1 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Deserialize into a JSON value
let json_value: serde_json::Value = Deserialize::deserialize(deserializer)?;

// Convert into a JSON string
let json_string = serde_json::to_string(&json_value)
.map_err(|err| DeserializationError::custom(err.to_string()))?;

// Use try_from_json_string to deserialize into ContractClassV1
ContractClassV1::try_from_json_string(&json_string)
.map_err(|err| DeserializationError::custom(err.to_string()))
}
}

impl Serialize for ContractClassV1 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
// Convert the ContractClassV1 instance to CasmContractClass
let casm_contract_class: CasmContractClass = self
.try_into()
.map_err(|err: ProgramError| serde::ser::Error::custom(err.to_string()))?;

// Serialize the JSON string to bytes
casm_contract_class.serialize(serializer)
}
}

impl<'de> Deserialize<'de> for ContractClassV1 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
// Deserialize into a JSON value
let json_value: serde_json::Value = Deserialize::deserialize(deserializer)?;

// Convert into a JSON string
let json_string = serde_json::to_string(&json_value)
.map_err(|err| DeserializationError::custom(err.to_string()))?;

// Use try_from_json_string to deserialize into ContractClassV1
ContractClassV1::try_from_json_string(&json_string)
.map_err(|err| DeserializationError::custom(err.to_string()))
}
}

impl<'de> Deserialize<'de> for CompiledClassV1 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand Down Expand Up @@ -474,7 +423,7 @@ fn get_visited_segments(
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContractClassV1Inner {
pub struct CompiledClassV1Inner {
pub program: Program,
pub entry_points_by_type: EntryPointsByType<EntryPointV1>,
pub hints: HashMap<String, Hint>,
Expand Down Expand Up @@ -553,136 +502,7 @@ impl TryInto<CasmContractClass> for &CompiledClassV1 {
// Transform the entry points of type Constructor into CasmContractEntryPoint.
let constructor = self
.entry_points_by_type
.get(&EntryPointType::Constructor)
.unwrap_or(&vec![])
.iter()
.map(|constructor| CasmContractEntryPoint {
selector: num_bigint::BigUint::from_bytes_be(&constructor.selector.0.to_bytes_be()),
offset: constructor.offset.0,
builtins: constructor
.builtins
.clone()
.into_iter()
.map(|x| x.to_string().into())
.collect(),
})
.collect();

// Transform the entry points of type External into CasmContractEntryPoint.
let external = self
.entry_points_by_type
.get(&EntryPointType::External)
.unwrap_or(&vec![])
.iter()
.map(|external| CasmContractEntryPoint {
selector: num_bigint::BigUint::from_bytes_be(&external.selector.0.to_bytes_be()),
offset: external.offset.0,
builtins: external
.builtins
.clone()
.into_iter()
.map(|x| x.to_string().into())
.collect(),
})
.collect();

// Transform the entry points of type L1Handler into CasmContractEntryPoint.
let l1_handler = self
.entry_points_by_type
.get(&EntryPointType::L1Handler)
.unwrap_or(&vec![])
.iter()
.map(|l1_handler| CasmContractEntryPoint {
selector: num_bigint::BigUint::from_bytes_be(&l1_handler.selector.0.to_bytes_be()),
offset: l1_handler.offset.0,
builtins: l1_handler
.builtins
.clone()
.into_iter()
.map(|x| x.to_string().into())
.collect(),
})
.collect();

// Construct the CasmContractClass from the extracted and transformed data.
Ok(CasmContractClass {
prime: num_bigint::BigUint::from_str_radix(&self.program.prime()[2..], 16)
.expect("failed to parse prime"),
compiler_version: "".to_string(),
bytecode,
bytecode_segment_lengths,
hints,
pythonic_hints: None,
entry_points_by_type:
cairo_lang_starknet_classes::casm_contract_class::CasmContractEntryPoints {
constructor,
external,
l1_handler,
},
})
}
}

// Implementation of the TryInto trait to convert a reference of ContractClassV1 into
// CasmContractClass.
impl TryInto<CasmContractClass> for &ContractClassV1 {
// Definition of the error type that can be returned during the conversion.
type Error = ProgramError;

// Implementation of the try_into function which performs the conversion.
fn try_into(self) -> Result<CasmContractClass, Self::Error> {
// Converting the program data into a vector of BigUintAsHex.
let bytecode: Vec<cairo_lang_utils::bigint::BigUintAsHex> = self
.program
.iter_data()
.map(|x| cairo_lang_utils::bigint::BigUintAsHex {
value: x.get_int_ref().unwrap().to_biguint(),
})
.collect();

// Serialize the Program object to JSON bytes.
let serialized_program = self.program.serialize()?;
// Deserialize the JSON bytes into a serde_json::Value.
let json_value: serde_json::Value = serde_json::from_slice(&serialized_program)?;

// Extract the hints from the JSON value.
let hints = json_value.get("hints").ok_or_else(|| {
ProgramError::Parse(serde::ser::Error::custom("failed to parse hints"))
})?;

// Transform the hints into a vector of tuples (usize, Vec<Hint>).
let hints: Vec<(usize, Vec<Hint>)> = hints
.as_object() // Convert to JSON object.
.unwrap()
.iter()
.map(|(key, value)| {
// Transform each hint value into a Vec<Hint>.
let hints: Vec<Hint> = value
.as_array() // Convert to JSON array.
.unwrap()
.iter()
.map(|hint_params| {
// Extract the "code" parameter and convert to a string.
let hint_param_code = hint_params.get("code").unwrap().clone();
let hint_string = hint_param_code.as_str().expect("failed to parse hint as string");

// Retrieve the hint from the self.hints map.
self.hints.get(hint_string).expect("failed to get hint").clone()
})
.collect();
// Convert the key to usize and create a tuple (usize, Vec<Hint>).
(key.parse().unwrap(), hints)
})
.collect();

// Define the bytecode segment lengths
let bytecode_segment_lengths = Some(self.bytecode_segment_lengths.clone());

// Transform the entry points of type Constructor into CasmContractEntryPoint.
let constructor = self
.entry_points_by_type
.get(&EntryPointType::Constructor)
.unwrap_or(&vec![])
.constructor
.iter()
.map(|constructor| CasmContractEntryPoint {
selector: num_bigint::BigUint::from_bytes_be(&constructor.selector.0.to_bytes_be()),
Expand All @@ -699,8 +519,7 @@ impl TryInto<CasmContractClass> for &ContractClassV1 {
// Transform the entry points of type External into CasmContractEntryPoint.
let external = self
.entry_points_by_type
.get(&EntryPointType::External)
.unwrap_or(&vec![])
.external
.iter()
.map(|external| CasmContractEntryPoint {
selector: num_bigint::BigUint::from_bytes_be(&external.selector.0.to_bytes_be()),
Expand All @@ -717,8 +536,7 @@ impl TryInto<CasmContractClass> for &ContractClassV1 {
// Transform the entry points of type L1Handler into CasmContractEntryPoint.
let l1_handler = self
.entry_points_by_type
.get(&EntryPointType::L1Handler)
.unwrap_or(&vec![])
.l1_handler
.iter()
.map(|l1_handler| CasmContractEntryPoint {
selector: num_bigint::BigUint::from_bytes_be(&l1_handler.selector.0.to_bytes_be()),
Expand All @@ -736,7 +554,7 @@ impl TryInto<CasmContractClass> for &ContractClassV1 {
Ok(CasmContractClass {
prime: num_bigint::BigUint::from_str_radix(&self.program.prime()[2..], 16)
.expect("failed to parse prime"),
compiler_version: "".to_string(),
compiler_version: self.compiler_version.0.to_string(),
bytecode,
bytecode_segment_lengths,
hints,
Expand Down Expand Up @@ -810,7 +628,7 @@ impl TryFrom<CasmContractClass> for CompiledClassV1 {
Version::parse(&class.compiler_version)
.unwrap_or_else(|_| panic!("Invalid version: '{}'", class.compiler_version)),
);
Ok(CompiledClassV1(Arc::new(ContractClassV1Inner {
Ok(CompiledClassV1(Arc::new(CompiledClassV1Inner {
program,
entry_points_by_type,
hints: string_to_hint,
Expand Down Expand Up @@ -864,7 +682,12 @@ fn convert_entry_points_v1(external: &[CasmContractEntryPoint]) -> Vec<EntryPoin
builtins: ep
.builtins
.iter()
.map(|builtin| BuiltinName::from_str(builtin).expect("Unrecognized builtin."))
.map(|builtin| match BuiltinName::from_str(&builtin) {
Some(builtin) => builtin,
None => {
BuiltinName::from_str_with_suffix(&builtin).expect("Unrecognized builtin.")
}
})
.collect(),
})
.collect()
Expand Down
2 changes: 2 additions & 0 deletions crates/blockifier/src/execution/contract_class_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use cairo_lang_starknet_classes::NestedIntList;
use rstest::rstest;

use crate::execution::contract_class::{CompiledClassV1, CompiledClassV0, CompiledClassV1Inner};
use crate::test_utils::struct_impls::LoadContractFromFile;
use crate::transaction::errors::TransactionExecutionError;

#[rstest]
Expand Down Expand Up @@ -45,6 +46,7 @@ fn test_get_visited_segments() {
);
}


#[test]
fn test_deserialization_of_contract_class_v_0() {
let contract_class: CompiledClassV0 =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2736,13 +2736,13 @@
}
},
"entry_points_by_type": {
"L1_HANDLER": [],
"CONSTRUCTOR": [],
"EXTERNAL": [
{
"selector": "0x3b82f69851fa1625b367ea6c116252a84257da483dcec4d4e4bc270eb5c70a7",
"offset": "0x179"
}
]
],
"L1_HANDLER": [],
"CONSTRUCTOR": []
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"prime": "0x800000000000011000000000000000000000000000000000000000000000001",
"compiler_version": "",
"compiler_version": "2.2.0",
"bytecode": [
"0xa0680017fff8000",
"0x7",
Expand Down
14 changes: 14 additions & 0 deletions crates/blockifier/src/test_utils/struct_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use crate::bouncer::{BouncerConfig, BouncerWeights, BuiltinCount};
use crate::context::{BlockContext, ChainInfo, FeeTokenAddresses, TransactionContext};
use crate::execution::call_info::{CallExecution, CallInfo, Retdata};
use crate::execution::common_hints::ExecutionMode;
use crate::execution::contract_class::{CompiledClassV0, CompiledClassV1};
#[cfg(feature = "cairo_native")]
use crate::execution::contract_class::CompiledClassV1;
use crate::execution::entry_point::{
Expand Down Expand Up @@ -240,6 +241,19 @@ pub trait LoadContractFromFile: serde::de::DeserializeOwned {
impl LoadContractFromFile for CasmContractClass {}
impl LoadContractFromFile for DeprecatedContractClass {}

impl LoadContractFromFile for CompiledClassV1 {
fn from_file(contract_path: &str) -> Self {
let raw_contract_class = get_raw_contract_class(contract_path);
CompiledClassV1::try_from_json_string(&raw_contract_class).unwrap()
}
}
impl LoadContractFromFile for CompiledClassV0 {
fn from_file(contract_path: &str) -> Self {
let raw_contract_class = get_raw_contract_class(contract_path);
CompiledClassV0::try_from_json_string(&raw_contract_class).unwrap()
}
}

impl BouncerWeights {
pub fn create_for_testing(builtin_count: BuiltinCount) -> Self {
Self { builtin_count, ..Self::empty() }
Expand Down

0 comments on commit 4b23bbe

Please sign in to comment.