Skip to content
This repository has been archived by the owner on Aug 21, 2024. It is now read-only.

Commit

Permalink
refactor(native_blockifier): flat fields in bouncerinfo
Browse files Browse the repository at this point in the history
  • Loading branch information
ayeletstarkware committed Jan 30, 2024
1 parent eaa027f commit 96ba551
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 68 deletions.
15 changes: 14 additions & 1 deletion crates/blockifier/src/execution/execution_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use cairo_vm::types::program::Program;
use cairo_vm::types::relocatable::{MaybeRelocatable, Relocatable};
use cairo_vm::vm::errors::memory_errors::MemoryError;
use cairo_vm::vm::errors::vm_errors::VirtualMachineError;
use cairo_vm::vm::runners::cairo_runner::CairoArg;
use cairo_vm::vm::runners::cairo_runner::{CairoArg, ExecutionResources as VmExecutionResources};
use cairo_vm::vm::vm_core::VirtualMachine;
use num_bigint::BigUint;
use starknet_api::core::ClassHash;
Expand Down Expand Up @@ -285,3 +285,16 @@ pub fn format_panic_data(felts: &[StarkFelt]) -> String {
}
if let [item] = &items[..] { item.clone() } else { format!("({})", items.join(", ")) }
}

pub fn execution_resources_from_hashmap(input: &HashMap<String, usize>) -> VmExecutionResources {
let mut builtin_instance_counter = HashMap::new();
let pedersen_builtin = input.get("pedersen_builtin").unwrap_or(&0);
builtin_instance_counter.insert("pedersen_builtin".to_string(), *pedersen_builtin);
let range_check_builtin = input.get("range_check_builtin").unwrap_or(&0);
builtin_instance_counter.insert("range_check_builtin".to_string(), *range_check_builtin);
VmExecutionResources {
n_steps: *input.get("n_steps").unwrap_or(&0),
builtin_instance_counter,
n_memory_holes: *input.get("n_memory_holes").unwrap_or(&0),
}
}
39 changes: 1 addition & 38 deletions crates/blockifier/src/transaction/transaction_utils.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::collections::HashMap;

use cairo_vm::vm::runners::builtin_runner::SEGMENT_ARENA_BUILTIN_NAME;
use cairo_vm::vm::runners::cairo_runner::ExecutionResources as VmExecutionResources;
use starknet_api::transaction::TransactionVersion;

use super::objects::GasVector;
Expand All @@ -13,7 +12,7 @@ use crate::fee::os_usage::get_additional_os_resources;
use crate::transaction::errors::TransactionExecutionError;
use crate::transaction::objects::{ResourcesMapping, TransactionExecutionResult};
use crate::transaction::transaction_types::TransactionType;
use crate::utils::{merge_hashmaps, usize_from_u128};
use crate::utils::usize_from_u128;

/// Calculates the total resources needed to include the transaction in a Starknet block as
/// most-recent (recent w.r.t. application on the given state).
Expand Down Expand Up @@ -86,39 +85,3 @@ pub fn verify_contract_class_version(
}
}
}

// TODO(Ayelet, 01/02/2024): Move to VmExecutionResourcesWrapper when merged.
pub fn vm_execution_resources_to_hash_map(
execution_resources: VmExecutionResources,
) -> HashMap<String, usize> {
let mut result = execution_resources.builtin_instance_counter.clone();
result.insert(
String::from("n_steps"),
execution_resources.n_steps + execution_resources.n_memory_holes,
);
result
}

type ResourcesMap = HashMap<String, usize>;

// TODO(Arni, 24/01/2024): Add state_diff_size to tx_weights
pub fn calculate_tx_weights(
additional_os_resources: VmExecutionResources,
actual_resources: ResourcesMap,
message_segment_length: usize,
) -> Result<ResourcesMap, TransactionExecutionError> {
let mut tx_weights: HashMap<String, usize> = HashMap::new();
let mut cairo_resource_usage: HashMap<String, usize> = actual_resources;
let value = cairo_resource_usage.remove("l1_gas_usage").ok_or(
TransactionExecutionError::InvalidTransactionExecutionInfo {
field: "l1_gas_usage".to_string(),
},
)?;
tx_weights.insert("gas_weight".to_string(), value);
let os_cairo_usage: HashMap<String, usize> =
vm_execution_resources_to_hash_map(additional_os_resources);
let cairo_usage = merge_hashmaps(&cairo_resource_usage, &os_cairo_usage);
tx_weights.extend(cairo_usage);
tx_weights.insert("message_segment_length".to_string(), message_segment_length);
Ok(tx_weights)
}
17 changes: 0 additions & 17 deletions crates/blockifier/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
use std::collections::HashMap;
use std::hash::Hash;
use std::ops::{Add, AddAssign};

use crate::transaction::errors::NumericConversionError;

Expand All @@ -24,21 +22,6 @@ pub const fn const_max(a: u128, b: u128) -> u128 {
[a, b][(a < b) as usize]
}

pub fn merge_hashmaps<K, V>(x: &HashMap<K, V>, y: &HashMap<K, V>) -> HashMap<K, V>
where
K: Hash + Eq + Clone,
V: Add<Output = V> + AddAssign + Default + Clone,
{
let mut result = x.clone();
for (key, value) in y {
result
.entry(key.clone())
.and_modify(|v| v.add_assign(value.clone()))
.or_insert(value.clone());
}
result
}

/// Conversion from usize to u128. Currently, usize has 64 bits, so this conversion should never
/// fail.
pub fn usize_from_u128(val: u128) -> Result<usize, NumericConversionError> {
Expand Down
55 changes: 48 additions & 7 deletions crates/native_blockifier/src/py_transaction_execution_info.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::collections::{HashMap, HashSet};
use std::ops::Add;

use blockifier::execution::call_info::{CallInfo, OrderedEvent, OrderedL2ToL1Message};
use blockifier::execution::entry_point::CallType;
use blockifier::transaction::objects::TransactionExecutionInfo;
use blockifier::transaction::errors::TransactionExecutionError;
use blockifier::transaction::objects::{TransactionExecutionInfo, TransactionExecutionResult};
use cairo_vm::vm::runners::cairo_runner::ExecutionResources as VmExecutionResources;
use pyo3::prelude::*;
use starknet_api::deprecated_contract_class::EntryPointType;
Expand Down Expand Up @@ -217,14 +219,53 @@ impl From<VmExecutionResources> for PyVmExecutionResources {

#[pyclass]
#[derive(Clone, Default)]
// TODO(Ayelet, 24/01/2024): Consider remove message_segment_length, state_diff_size.
pub struct PyBouncerInfo {
#[pyo3(get)]
// The number of felts needed to store L1<>L2 messages.
pub message_segment_length: usize,
pub state_diff_size: usize, // The number of felts needed to store the state diff.
#[pyo3(get)]
// The number of felts needed to store the state diff.
pub state_diff_size: usize,
pub l1_gas_amount: usize,
#[pyo3(get)]
pub tx_weights: HashMap<String, usize>,
pub message_segment_length: usize, // The number of felts needed to store L1<>L2 messages.
#[pyo3(get)]
pub execution_resources: PyVmExecutionResources,
}

impl PyBouncerInfo {
pub fn calculate(
additional_os_resources: VmExecutionResources,
actual_resources: VmExecutionResources,
message_segment_length: usize,
state_diff_size: usize,
l1_gas_amount: usize,
) -> TransactionExecutionResult<Self> {
let merged_resources = additional_os_resources.add(&actual_resources);

let n_steps = merged_resources.n_steps + merged_resources.n_memory_holes;

let pedersen_builtin = merged_resources
.builtin_instance_counter
.get("pedersen_builtin")
.ok_or_else(|| TransactionExecutionError::InvalidTransactionExecutionInfo {
field: "pedersen_builtin".to_string(),
})?;

let range_check_builtin = merged_resources
.builtin_instance_counter
.get("range_check_builtin")
.ok_or_else(|| TransactionExecutionError::InvalidTransactionExecutionInfo {
field: "range_check_builtin".to_string(),
})?;

let mut builtin_instance_counter = HashMap::new();
builtin_instance_counter.insert("pedersen_builtin".to_string(), *pedersen_builtin);
builtin_instance_counter.insert("range_check_builtin".to_string(), *range_check_builtin);

let execution_resources = PyVmExecutionResources {
n_steps,
builtin_instance_counter,
n_memory_holes: merged_resources.n_memory_holes,
};

Ok(Self { state_diff_size, l1_gas_amount, message_segment_length, execution_resources })
}
}
22 changes: 17 additions & 5 deletions crates/native_blockifier/src/transaction_executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ use blockifier::block_context::BlockContext;
use blockifier::block_execution::pre_process_block;
use blockifier::execution::call_info::{CallInfo, MessageL1CostInfo};
use blockifier::execution::entry_point::ExecutionResources;
use blockifier::execution::execution_utils::execution_resources_from_hashmap;
use blockifier::fee::actual_cost::ActualCost;
use blockifier::state::cached_state::{
CachedState, GlobalContractCache, StagedTransactionalState, StorageEntry, TransactionalState,
};
use blockifier::state::state_api::{State, StateReader};
use blockifier::transaction::account_transaction::AccountTransaction;
use blockifier::transaction::errors::TransactionExecutionError;
use blockifier::transaction::transaction_execution::Transaction;
use blockifier::transaction::transaction_utils::calculate_tx_weights;
use blockifier::transaction::transactions::{ExecutableTransaction, ValidatableTransaction};
use cairo_vm::vm::runners::builtin_runner::HASH_BUILTIN_NAME;
use cairo_vm::vm::runners::cairo_runner::ExecutionResources as VmExecutionResources;
Expand Down Expand Up @@ -114,15 +115,26 @@ impl<S: StateReader> TransactionExecutor<S> {
&self.visited_storage_entries,
&tx_visited_storage_entries,
)?;

let actual_resources =
execution_resources_from_hashmap(&tx_execution_info.actual_resources.0);

let l1_gas_amount =
tx_execution_info.actual_resources.0.get("l1_gas_usage").ok_or_else(|| {
TransactionExecutionError::InvalidTransactionExecutionInfo {
field: "l1_gas_usage".to_string(),
}
})?;

let state_diff_size = 0;
let actual_resources = tx_execution_info.actual_resources.0.clone();
let tx_weights = calculate_tx_weights(

let py_bouncer_info = PyBouncerInfo::calculate(
additional_os_resources,
actual_resources,
message_segment_length,
state_diff_size,
*l1_gas_amount,
)?;
let py_bouncer_info =
PyBouncerInfo { message_segment_length, state_diff_size, tx_weights };
self.staged_for_commit_state = Some(
transactional_state.stage(tx_executed_class_hashes, tx_visited_storage_entries),
);
Expand Down

0 comments on commit 96ba551

Please sign in to comment.