Skip to content

feat(starknet_os): implement load deprecated class inner hint #5108

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/starknet_os/src/hints/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ pub enum OsHintError {
BooleanIdExpected { id: Ids, felt: Felt },
#[error("Failed to convert {variant:?} felt value {felt:?} to type {ty}: {reason:?}.")]
ConstConversion { variant: Const, felt: Felt, ty: String, reason: String },
#[error("Tried to iterate past the end of {item_type}.")]
EndOfIterator { item_type: String },
#[error(transparent)]
ExecutionScopes(#[from] ExecScopeError),
#[error("{id:?} value {felt} is not a bit.")]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::any::Any;
use std::collections::hash_map::IntoIter;
use std::collections::{HashMap, HashSet};

use blockifier::state::state_api::StateReader;
Expand All @@ -18,7 +19,7 @@ use starknet_types_core::felt::Felt;
use crate::hints::error::{OsHintError, OsHintExtensionResult, OsHintResult};
use crate::hints::types::HintArgs;
use crate::hints::vars::{CairoStruct, Ids, Scope};
use crate::vm_utils::get_address_of_nested_fields;
use crate::vm_utils::{get_address_of_nested_fields, LoadCairoObject};

pub(crate) fn load_deprecated_class_facts<S: StateReader>(
HintArgs { hint_processor, vm, exec_scopes, ids_data, ap_tracking, .. }: HintArgs<'_, S>,
Expand Down Expand Up @@ -46,9 +47,33 @@ pub(crate) fn load_deprecated_class_facts<S: StateReader>(
}

pub(crate) fn load_deprecated_class_inner<S: StateReader>(
HintArgs { .. }: HintArgs<'_, S>,
HintArgs { hint_processor, vm, exec_scopes, ids_data, ap_tracking, constants }: HintArgs<'_, S>,
) -> OsHintResult {
todo!()
let deprecated_class_iter = exec_scopes
.get_mut_ref::<IntoIter<ClassHash, ContractClass>>(Scope::CompiledClassFacts.into())?;

let (class_hash, deprecated_class) = deprecated_class_iter.next().ok_or_else(|| {
OsHintError::EndOfIterator { item_type: "deprecated_compiled_classes".to_string() }
})?;

let dep_class_base = vm.add_memory_segment();
deprecated_class.load_into(
vm,
&hint_processor.execution_helper.os_program,
dep_class_base,
constants,
)?;

exec_scopes.insert_value(Scope::CompiledClassHash.into(), class_hash);
exec_scopes.insert_value(Scope::CompiledClass.into(), deprecated_class);

Ok(insert_value_from_var_name(
Ids::CompiledClass.into(),
dep_class_base,
vm,
ids_data,
ap_tracking,
)?)
}

pub(crate) fn load_deprecated_class<S: StateReader>(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,68 +1,123 @@
use std::collections::HashMap;

use cairo_vm::serde::deserialize_program::deserialize_array_of_bigint_hex;
use cairo_vm::types::relocatable::{MaybeRelocatable, Relocatable};
use cairo_vm::vm::vm_core::VirtualMachine;
use starknet_api::contract_class::EntryPointType;
use starknet_api::deprecated_contract_class::{ContractClass, EntryPointV0};
use starknet_types_core::felt::Felt;

use crate::hints::error::OsHintResult;
use crate::hints::vars::CairoStruct;
use crate::vm_utils::{
insert_value_to_nested_field,
insert_values_to_fields,
IdentifierGetter,
LoadCairoObject,
use crate::hints::class_hash::hinted_class_hash::{
compute_cairo_hinted_class_hash,
CairoContractDefinition,
};
use crate::hints::error::{OsHintError, OsHintResult};
use crate::hints::vars::{CairoStruct, Const};
use crate::vm_utils::{insert_values_to_fields, CairoSized, IdentifierGetter, LoadCairoObject};

#[allow(clippy::too_many_arguments)]
/// Loads the entry points of a deprecated contract class to a contract class struct, given a
/// specific entry point type.
fn load_entry_points_to_contract_class_struct<IG: IdentifierGetter>(
deprecated_class: &ContractClass,
entry_point_type: &EntryPointType,
class_base: Relocatable,
var_type: CairoStruct,
impl<IG: IdentifierGetter> LoadCairoObject<IG> for ContractClass {
fn load_into(
&self,
vm: &mut VirtualMachine,
identifier_getter: &IG,
address: Relocatable,
constants: &HashMap<String, Felt>,
) -> OsHintResult {
// Insert compiled class version field.
let compiled_class_version = Const::DeprecatedCompiledClassVersion.fetch(constants)?;

// Insert external entry points.
let (externals_list_base, externals_len) =
insert_entry_points(self, vm, identifier_getter, constants, &EntryPointType::External)?;

// Insert l1 handler entry points.
let (l1_handlers_list_base, l1_handlers_len) = insert_entry_points(
self,
vm,
identifier_getter,
constants,
&EntryPointType::L1Handler,
)?;

// Insert constructor entry points.
let (constructors_list_base, constructors_len) = insert_entry_points(
self,
vm,
identifier_getter,
constants,
&EntryPointType::Constructor,
)?;

// Insert builtins.
let builtins: Vec<String> =
serde_json::from_value(self.program.builtins.clone()).map_err(|e| {
OsHintError::SerdeJsonDeserialize { error: e, value: self.program.builtins.clone() }
})?;
let builtins: Vec<MaybeRelocatable> = builtins
.into_iter()
.map(|bi| (Felt::from_bytes_be_slice(bi.as_bytes())).into())
.collect();

let builtin_list_base = vm.add_memory_segment();
vm.load_data(builtin_list_base, &builtins)?;

// Insert hinted class hash.
let contract_definition_vec = serde_json::to_vec(&self)?;
let contract_definition: CairoContractDefinition<'_> =
serde_json::from_slice(&contract_definition_vec).map_err(OsHintError::SerdeJson)?;

let hinted_class_hash = compute_cairo_hinted_class_hash(&contract_definition)?;

// Insert bytecode_ptr.
let bytecode_ptr = deserialize_array_of_bigint_hex(&self.program.data)?;

let bytecode_ptr_base = vm.add_memory_segment();
vm.load_data(bytecode_ptr_base, &bytecode_ptr)?;

// Insert the fields.
let nested_fields_and_value = [
("compiled_class_version", compiled_class_version.into()),
("n_external_functions", Felt::from(externals_len).into()),
("external_functions", externals_list_base.into()),
("n_l1_handlers", Felt::from(l1_handlers_len).into()),
("l1_handlers", l1_handlers_list_base.into()),
("n_constructors", Felt::from(constructors_len).into()),
("constructors", constructors_list_base.into()),
("n_builtins", Felt::from(builtins.len()).into()),
("builtin_list", builtin_list_base.into()),
("hinted_class_hash", hinted_class_hash.into()),
("bytecode_length", Felt::from(bytecode_ptr.len()).into()),
("bytecode_ptr", bytecode_ptr_base.into()),
];
insert_values_to_fields(
address,
CairoStruct::DeprecatedCompiledClass,
vm,
nested_fields_and_value.as_slice(),
identifier_getter,
)?;

Ok(())
}
}

fn insert_entry_points<IG: IdentifierGetter>(
dep_contract_class: &ContractClass,
vm: &mut VirtualMachine,
identifier_getter: &IG,
entry_points_field: &str,
num_entry_points_field: &str,
) -> OsHintResult {
let empty_vec = Vec::new();
let entry_points =
deprecated_class.entry_points_by_type.get(entry_point_type).unwrap_or(&empty_vec);

let flat_entry_point_data: Vec<MaybeRelocatable> = entry_points
.iter()
.flat_map(|entry_point| {
vec![
MaybeRelocatable::from(entry_point.selector.0),
MaybeRelocatable::from(Felt::from(entry_point.offset.0)),
]
})
.collect();

insert_value_to_nested_field(
class_base,
var_type,
vm,
&[num_entry_points_field],
identifier_getter,
Felt::from(entry_points.len()),
)?;

let flat_entry_point_data_base = vm.add_memory_segment();
vm.load_data(flat_entry_point_data_base, &flat_entry_point_data)?;
insert_value_to_nested_field(
class_base,
var_type,
vm,
&[entry_points_field],
identifier_getter,
flat_entry_point_data_base,
)?;

Ok(())
constants: &HashMap<String, Felt>,
entry_point_type: &EntryPointType,
) -> Result<(Relocatable, usize), OsHintError> {
let list_base = vm.add_memory_segment();
let n_entry_points = match dep_contract_class.entry_points_by_type.get(entry_point_type) {
Some(entry_points) => {
entry_points.load_into(vm, identifier_getter, list_base, constants)?;
entry_points.len()
}
None => 0,
};

Ok((list_base, n_entry_points))
}

impl<IG: IdentifierGetter> LoadCairoObject<IG> for EntryPointV0 {
Expand All @@ -87,3 +142,10 @@ impl<IG: IdentifierGetter> LoadCairoObject<IG> for EntryPointV0 {
Ok(())
}
}

impl<IG: IdentifierGetter> CairoSized<IG> for EntryPointV0 {
fn size(_identifier_getter: &IG) -> usize {
// TODO(Rotem): Fetch from IG after we upgrade the VM.
2
}
}
5 changes: 5 additions & 0 deletions crates/starknet_os/src/hints/vars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ pub enum Const {
BlobLength,
BlockHashContractAddress,
CompiledClassVersion,
DeprecatedCompiledClassVersion,
EntryPointInitialBudget,
InitialAvailableAlias,
MerkleHeight,
Expand All @@ -226,6 +227,10 @@ impl From<Const> for &'static str {
Const::CompiledClassVersion => {
"starkware.starknet.core.os.contract_class.compiled_class.COMPILED_CLASS_VERSION"
}
Const::DeprecatedCompiledClassVersion => {
"starkware.starknet.core.os.contract_class.deprecated_compiled_class.\
DEPRECATED_COMPILED_CLASS_VERSION"
}
Const::InitialAvailableAlias => {
"starkware.starknet.core.os.state.aliases.INITIAL_AVAILABLE_ALIAS"
}
Expand Down
Loading