Skip to content
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

refactor(blockifier): remove execution_resources arg #2189

Merged
merged 1 commit into from
Nov 20, 2024
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
1 change: 0 additions & 1 deletion Cargo.lock

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

8 changes: 1 addition & 7 deletions crates/blockifier/src/blockifier/stateful_validator.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::sync::Arc;

use cairo_vm::vm::runners::cairo_runner::ExecutionResources;
use starknet_api::core::{ContractAddress, Nonce};
use starknet_api::executable_transaction::AccountTransaction as ApiTransaction;
use thiserror::Error;
Expand All @@ -12,7 +11,7 @@ use crate::blockifier::transaction_executor::{
BLOCK_STATE_ACCESS_ERR,
};
use crate::context::{BlockContext, TransactionContext};
use crate::execution::call_info::{gas_for_fee_from_call_infos, CallInfo, ChargedResources};
use crate::execution::call_info::CallInfo;
use crate::fee::fee_checks::PostValidationReport;
use crate::fee::receipt::TransactionReceipt;
use crate::state::cached_state::CachedState;
Expand Down Expand Up @@ -111,20 +110,16 @@ impl<S: StateReader> StatefulValidator<S> {
tx: &AccountTransaction,
mut remaining_gas: u64,
) -> StatefulValidatorResult<(Option<CallInfo>, TransactionReceipt)> {
let mut execution_resources = ExecutionResources::default();
let tx_context = Arc::new(self.tx_executor.block_context.to_tx_context(tx));

let limit_steps_by_resources = tx.enforce_fee();
let validate_call_info = tx.validate_tx(
self.tx_executor.block_state.as_mut().expect(BLOCK_STATE_ACCESS_ERR),
&mut execution_resources,
tx_context.clone(),
&mut remaining_gas,
limit_steps_by_resources,
)?;

let gas_for_fee = gas_for_fee_from_call_infos(&validate_call_info, &None);

let tx_receipt = TransactionReceipt::from_account_tx(
tx,
&tx_context,
Expand All @@ -134,7 +129,6 @@ impl<S: StateReader> StatefulValidator<S> {
.as_mut()
.expect(BLOCK_STATE_ACCESS_ERR)
.get_actual_state_changes()?,
&ChargedResources { vm_resources: execution_resources, gas_for_fee },
CallInfo::summarize_many(
validate_call_info.iter(),
&tx_context.block_context.versioned_constants,
Expand Down
53 changes: 33 additions & 20 deletions crates/blockifier/src/execution/call_info.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::HashSet;
use std::iter::Sum;
use std::ops::Add;
use std::ops::{Add, AddAssign};

use cairo_vm::vm::runners::cairo_runner::ExecutionResources;
use serde::Serialize;
Expand Down Expand Up @@ -73,6 +73,7 @@ pub struct EventSummary {

#[derive(Clone, Debug, Default, PartialEq)]
pub struct ExecutionSummary {
pub charged_resources: ChargedResources,
pub executed_class_hashes: HashSet<ClassHash>,
pub visited_storage_entries: HashSet<StorageEntry>,
pub l2_to_l1_payload_lengths: Vec<usize>,
Expand All @@ -83,6 +84,7 @@ impl Add for ExecutionSummary {
type Output = Self;

fn add(mut self, other: Self) -> Self {
self.charged_resources += &other.charged_resources;
self.executed_class_hashes.extend(other.executed_class_hashes);
self.visited_storage_entries.extend(other.visited_storage_entries);
self.l2_to_l1_payload_lengths.extend(other.l2_to_l1_payload_lengths);
Expand Down Expand Up @@ -113,25 +115,22 @@ impl ChargedResources {
}
}

/// Returns the total gas_for_fee used in the given validate and execute calls.
pub fn gas_for_fee_from_call_infos(
validate: &Option<CallInfo>,
execute: &Option<CallInfo>,
) -> GasAmount {
let validate_gas_amount = validate
.as_ref()
.map(|call_info| call_info.charged_resources.gas_for_fee)
.unwrap_or(GasAmount(0));
let execute_gas_amount = execute
.as_ref()
.map(|call_info| call_info.charged_resources.gas_for_fee)
.unwrap_or(GasAmount(0));
validate_gas_amount.checked_add(execute_gas_amount).unwrap_or_else(|| {
panic!(
"Gas for fee overflowed: tried to add {execute_gas_amount} to \
{validate_gas_amount}",
)
})
impl Add<&ChargedResources> for &ChargedResources {
type Output = ChargedResources;

fn add(self, rhs: &ChargedResources) -> ChargedResources {
let mut new = self.clone();
new.add_assign(rhs);
new
}
}

impl AddAssign<&ChargedResources> for ChargedResources {
fn add_assign(&mut self, other: &Self) {
self.vm_resources += &other.vm_resources;
self.gas_for_fee =
self.gas_for_fee.checked_add(other.gas_for_fee).expect("Gas for fee overflowed.");
}
}

/// Represents the full effects of executing an entry point, including the inner calls it invoked.
Expand Down Expand Up @@ -209,6 +208,9 @@ impl CallInfo {
}

ExecutionSummary {
// Note: the charged resourses of a call contains the inner call resources, unlike other
// fields such as events and messages,
charged_resources: self.charged_resources.clone(),
executed_class_hashes,
visited_storage_entries,
l2_to_l1_payload_lengths,
Expand All @@ -222,6 +224,17 @@ impl CallInfo {
) -> ExecutionSummary {
call_infos.map(|call_info| call_info.summarize(versioned_constants)).sum()
}

pub fn summarize_charged_resources<'a>(
call_infos: impl Iterator<Item = &'a CallInfo>,
) -> ChargedResources {
// Note: the charged resourses of a call contains the inner call resources, unlike other
// fields such as events and messages,
call_infos.fold(ChargedResources::default(), |mut acc, inner_call| {
acc += &inner_call.charged_resources;
acc
})
}
}

pub struct CallInfoIter<'a> {
Expand Down
36 changes: 13 additions & 23 deletions crates/blockifier/src/execution/deprecated_entry_point_execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ use cairo_vm::types::builtin_name::BuiltinName;
use cairo_vm::types::layout_name::LayoutName;
use cairo_vm::types::relocatable::{MaybeRelocatable, Relocatable};
use cairo_vm::vm::errors::vm_errors::VirtualMachineError;
use cairo_vm::vm::runners::cairo_runner::{CairoArg, CairoRunner, ExecutionResources};
use cairo_vm::vm::runners::cairo_runner::{CairoArg, CairoRunner};
use starknet_api::abi::abi_utils::selector_from_name;
use starknet_api::abi::constants::{CONSTRUCTOR_ENTRY_POINT_NAME, DEFAULT_ENTRY_POINT_SELECTOR};
use starknet_api::contract_class::EntryPointType;
use starknet_api::core::EntryPointSelector;
use starknet_api::execution_resources::GasAmount;
use starknet_api::hash::StarkHash;

use super::execution_utils::SEGMENT_ARENA_BUILTIN_SIZE;
Expand Down Expand Up @@ -45,11 +46,10 @@ pub fn execute_entry_point_call(
call: CallEntryPoint,
contract_class: ContractClassV0,
state: &mut dyn State,
resources: &mut ExecutionResources,
context: &mut EntryPointExecutionContext,
) -> EntryPointExecutionResult<CallInfo> {
let VmExecutionContext { mut runner, mut syscall_handler, initial_syscall_ptr, entry_point_pc } =
initialize_execution_context(&call, contract_class, state, resources, context)?;
initialize_execution_context(&call, contract_class, state, context)?;

let (implicit_args, args) = prepare_call_arguments(
&call,
Expand All @@ -59,27 +59,16 @@ pub fn execute_entry_point_call(
)?;
let n_total_args = args.len();

// Fix the VM resources, in order to calculate the usage of this run at the end.
let previous_resources = syscall_handler.resources.clone();

// Execute.
run_entry_point(&mut runner, &mut syscall_handler, entry_point_pc, args)?;

Ok(finalize_execution(
runner,
syscall_handler,
call,
previous_resources,
implicit_args,
n_total_args,
)?)
Ok(finalize_execution(runner, syscall_handler, call, implicit_args, n_total_args)?)
}

pub fn initialize_execution_context<'a>(
call: &CallEntryPoint,
contract_class: ContractClassV0,
state: &'a mut dyn State,
resources: &'a mut ExecutionResources,
context: &'a mut EntryPointExecutionContext,
) -> Result<VmExecutionContext<'a>, PreExecutionError> {
// Verify use of cairo0 builtins only.
Expand Down Expand Up @@ -110,7 +99,6 @@ pub fn initialize_execution_context<'a>(
let initial_syscall_ptr = runner.vm.add_memory_segment();
let syscall_handler = DeprecatedSyscallHintProcessor::new(
state,
resources,
context,
initial_syscall_ptr,
call.storage_address,
Expand Down Expand Up @@ -231,7 +219,6 @@ pub fn finalize_execution(
mut runner: CairoRunner,
syscall_handler: DeprecatedSyscallHintProcessor<'_>,
call: CallEntryPoint,
previous_resources: ExecutionResources,
implicit_args: Vec<MaybeRelocatable>,
n_total_args: usize,
) -> Result<CallInfo, PostExecutionError> {
Expand Down Expand Up @@ -263,12 +250,17 @@ pub fn finalize_execution(
.get_mut(&BuiltinName::segment_arena)
.map_or_else(|| {}, |val| *val *= SEGMENT_ARENA_BUILTIN_SIZE);
}
*syscall_handler.resources += &vm_resources_without_inner_calls;
// Take into account the syscall resources of the current call.
*syscall_handler.resources +=
vm_resources_without_inner_calls +=
&versioned_constants.get_additional_os_syscall_resources(&syscall_handler.syscall_counter);

let full_call_resources = &*syscall_handler.resources - &previous_resources;
let charged_resources_without_inner_calls = ChargedResources {
vm_resources: vm_resources_without_inner_calls,
gas_for_fee: GasAmount(0),
};
let charged_resources = &charged_resources_without_inner_calls
+ &CallInfo::summarize_charged_resources(syscall_handler.inner_calls.iter());

Ok(CallInfo {
call,
execution: CallExecution {
Expand All @@ -280,9 +272,7 @@ pub fn finalize_execution(
},
inner_calls: syscall_handler.inner_calls,
tracked_resource: TrackedResource::CairoSteps,
charged_resources: ChargedResources::from_execution_resources(
full_call_resources.filter_unused_builtins(),
),
charged_resources,
storage_read_values: syscall_handler.read_values,
accessed_storage_keys: syscall_handler.accessed_keys,
..Default::default()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use cairo_vm::types::relocatable::{MaybeRelocatable, Relocatable};
use cairo_vm::vm::errors::hint_errors::HintError;
use cairo_vm::vm::errors::memory_errors::MemoryError;
use cairo_vm::vm::errors::vm_errors::VirtualMachineError;
use cairo_vm::vm::runners::cairo_runner::{ExecutionResources, ResourceTracker, RunResources};
use cairo_vm::vm::runners::cairo_runner::{ResourceTracker, RunResources};
use cairo_vm::vm::vm_core::VirtualMachine;
use num_bigint::{BigUint, TryFromBigIntError};
use starknet_api::contract_class::EntryPointType;
Expand Down Expand Up @@ -163,7 +163,6 @@ impl DeprecatedSyscallExecutionError {
pub struct DeprecatedSyscallHintProcessor<'a> {
// Input for execution.
pub state: &'a mut dyn State,
pub resources: &'a mut ExecutionResources,
pub context: &'a mut EntryPointExecutionContext,
pub storage_address: ContractAddress,
pub caller_address: ContractAddress,
Expand Down Expand Up @@ -194,15 +193,13 @@ pub struct DeprecatedSyscallHintProcessor<'a> {
impl<'a> DeprecatedSyscallHintProcessor<'a> {
pub fn new(
state: &'a mut dyn State,
resources: &'a mut ExecutionResources,
context: &'a mut EntryPointExecutionContext,
initial_syscall_ptr: Relocatable,
storage_address: ContractAddress,
caller_address: ContractAddress,
) -> Self {
DeprecatedSyscallHintProcessor {
state,
resources,
context,
storage_address,
caller_address,
Expand Down Expand Up @@ -503,7 +500,6 @@ pub fn execute_inner_call(
// Use `non_reverting_execute` since we don't support reverts here.
let call_info = call.non_reverting_execute(
syscall_handler.state,
syscall_handler.resources,
syscall_handler.context,
&mut remaining_gas,
)?;
Expand Down
1 change: 0 additions & 1 deletion crates/blockifier/src/execution/deprecated_syscalls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,6 @@ pub fn deploy(
let mut remaining_gas = syscall_handler.context.gas_costs().default_initial_gas_cost;
let call_info = execute_deployment(
syscall_handler.state,
syscall_handler.resources,
syscall_handler.context,
ctor_context,
request.constructor_calldata,
Expand Down
28 changes: 6 additions & 22 deletions crates/blockifier/src/execution/entry_point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::cmp::min;
use std::collections::HashMap;
use std::sync::Arc;

use cairo_vm::vm::runners::cairo_runner::{ExecutionResources, ResourceTracker, RunResources};
use cairo_vm::vm::runners::cairo_runner::{ResourceTracker, RunResources};
use num_traits::{Inv, Zero};
use serde::Serialize;
use starknet_api::abi::abi_utils::selector_from_name;
Expand Down Expand Up @@ -116,7 +116,6 @@ impl CallEntryPoint {
pub fn execute(
mut self,
state: &mut dyn State,
resources: &mut ExecutionResources,
context: &mut EntryPointExecutionContext,
remaining_gas: &mut u64,
) -> EntryPointExecutionResult<CallInfo> {
Expand Down Expand Up @@ -158,25 +157,17 @@ impl CallEntryPoint {
));

// This is the last operation of this function.
execute_entry_point_call_wrapper(
self,
contract_class,
state,
resources,
context,
remaining_gas,
)
execute_entry_point_call_wrapper(self, contract_class, state, context, remaining_gas)
}

/// Similar to `execute`, but returns an error if the outer call is reverted.
pub fn non_reverting_execute(
self,
state: &mut dyn State,
resources: &mut ExecutionResources,
context: &mut EntryPointExecutionContext,
remaining_gas: &mut u64,
) -> EntryPointExecutionResult<CallInfo> {
let execution_result = self.execute(state, resources, context, remaining_gas);
let execution_result = self.execute(state, context, remaining_gas);
if let Ok(call_info) = &execution_result {
// If the execution of the outer call failed, revert the transction.
if call_info.execution.failed {
Expand Down Expand Up @@ -409,7 +400,6 @@ impl EntryPointExecutionContext {

pub fn execute_constructor_entry_point(
state: &mut dyn State,
resources: &mut ExecutionResources,
context: &mut EntryPointExecutionContext,
ctor_context: ConstructorContext,
calldata: Calldata,
Expand Down Expand Up @@ -438,15 +428,9 @@ pub fn execute_constructor_entry_point(
initial_gas: *remaining_gas,
};

constructor_call.non_reverting_execute(state, resources, context, remaining_gas).map_err(
|error| {
ConstructorEntryPointExecutionError::new(
error,
&ctor_context,
Some(constructor_selector),
)
},
)
constructor_call.non_reverting_execute(state, context, remaining_gas).map_err(|error| {
ConstructorEntryPointExecutionError::new(error, &ctor_context, Some(constructor_selector))
})
}

pub fn handle_empty_constructor(
Expand Down
Loading
Loading