Skip to content

Commit

Permalink
refactor(blockifier,starknet_api): gas amount is now a u64, not a u128
Browse files Browse the repository at this point in the history
  • Loading branch information
dorimedini-starkware committed Oct 6, 2024
1 parent 893e4f1 commit a6fdfe0
Show file tree
Hide file tree
Showing 20 changed files with 173 additions and 150 deletions.
4 changes: 2 additions & 2 deletions crates/blockifier/src/bouncer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::state::cached_state::{StateChangesKeys, StorageEntry};
use crate::state::state_api::StateReader;
use crate::transaction::errors::TransactionExecutionError;
use crate::transaction::objects::{ExecutionResourcesTraits, TransactionExecutionResult};
use crate::utils::usize_from_u128;
use crate::utils::usize_from_u64;

#[cfg(test)]
#[path = "bouncer_test.rs"]
Expand Down Expand Up @@ -296,7 +296,7 @@ pub fn get_tx_weights<S: StateReader>(
state_changes_keys: &StateChangesKeys,
) -> TransactionExecutionResult<BouncerWeights> {
let message_resources = &tx_resources.starknet_resources.messages;
let message_starknet_gas = usize_from_u128(message_resources.get_starknet_gas_cost().l1_gas.0)
let message_starknet_gas = usize_from_u64(message_resources.get_starknet_gas_cost().l1_gas.0)
.expect("This conversion should not fail as the value is a converted usize.");
let mut additional_os_resources =
get_casm_hash_calculation_resources(state_reader, executed_class_hashes)?;
Expand Down
21 changes: 8 additions & 13 deletions crates/blockifier/src/execution/entry_point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,13 @@ impl EntryPointExecutionContext {
// New transactions derive the step limit by the L1 gas resource bounds; deprecated
// transactions derive this value from the `max_fee`.
let tx_gas_upper_bound = match tx_info {
TransactionInfo::Deprecated(context) => {
context.max_fee
/ block_info.gas_prices.get_l1_gas_price_by_fee_type(&tx_info.fee_type())
}
TransactionInfo::Current(context) => {
GasAmount(u128::from(context.l1_resource_bounds().max_amount))
}
TransactionInfo::Deprecated(context) => context
.max_fee
.checked_div(
block_info.gas_prices.get_l1_gas_price_by_fee_type(&tx_info.fee_type()),
)
.unwrap_or(GasAmount::MAX),
TransactionInfo::Current(context) => GasAmount(context.l1_resource_bounds().max_amount),
};

// Use saturating upper bound to avoid overflow. This is safe because the upper bound is
Expand All @@ -212,12 +212,7 @@ impl EntryPointExecutionContext {
let upper_bound_u64 = if gas_per_step.is_zero() {
u64::MAX
} else {
// TODO: This panic will disappear once GasAmount is a u64.
(gas_per_step.inv()
* u64::try_from(tx_gas_upper_bound.0).unwrap_or_else(|_| {
panic!("Gas amounts cannot be more than 64 bits; got {tx_gas_upper_bound:?}.")
}))
.to_integer()
(gas_per_step.inv() * tx_gas_upper_bound.0).to_integer()
};
let tx_upper_bound = usize_from_u64(upper_bound_u64).unwrap_or_else(|_| {
log::warn!(
Expand Down
28 changes: 15 additions & 13 deletions crates/blockifier/src/fee/fee_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use crate::test_utils::{
MAX_L1_GAS_AMOUNT,
};
use crate::transaction::test_utils::{account_invoke_tx, all_resource_bounds, l1_resource_bounds};
use crate::utils::{u128_from_usize, u64_from_usize};
use crate::utils::u64_from_usize;
use crate::versioned_constants::VersionedConstants;

fn get_vm_resource_usage() -> ExecutionResources {
Expand Down Expand Up @@ -57,12 +57,12 @@ fn test_simple_get_vm_resource_usage(

// Positive flow.
// Verify calculation - in our case, n_steps is the heaviest resource.
let vm_usage_in_l1_gas = GasAmount(u128::from(
let vm_usage_in_l1_gas = GasAmount(
(versioned_constants.vm_resource_fee_cost().n_steps
* (u64_from_usize(vm_resource_usage.n_steps + n_reverted_steps)))
* u64_from_usize(vm_resource_usage.n_steps + n_reverted_steps))
.ceil()
.to_integer(),
));
);
let expected_gas_vector = gas_vector_from_vm_usage(
vm_usage_in_l1_gas,
&gas_vector_computation_mode,
Expand All @@ -82,7 +82,7 @@ fn test_simple_get_vm_resource_usage(
let n_reverted_steps = 0;
vm_resource_usage.n_steps =
vm_resource_usage.builtin_instance_counter.get(&BuiltinName::range_check).unwrap() - 1;
let vm_usage_in_l1_gas = u128_from_usize(
let vm_usage_in_l1_gas = u64_from_usize(
*vm_resource_usage.builtin_instance_counter.get(&BuiltinName::range_check).unwrap(),
)
.into();
Expand Down Expand Up @@ -113,12 +113,12 @@ fn test_float_get_vm_resource_usage(
// Positive flow.
// Verify calculation - in our case, n_steps is the heaviest resource.
let n_reverted_steps = 300;
let vm_usage_in_l1_gas = GasAmount(u128::from(
let vm_usage_in_l1_gas = GasAmount(
(versioned_constants.vm_resource_fee_cost().n_steps
* u64_from_usize(vm_resource_usage.n_steps + n_reverted_steps))
.ceil()
.to_integer(),
));
);
let expected_gas_vector = gas_vector_from_vm_usage(
vm_usage_in_l1_gas,
&gas_vector_computation_mode,
Expand All @@ -136,14 +136,14 @@ fn test_float_get_vm_resource_usage(

// Another positive flow, this time the heaviest resource is ecdsa_builtin.
vm_resource_usage.n_steps = 200;
let vm_usage_in_l1_gas = GasAmount(u128::from(
let vm_usage_in_l1_gas = GasAmount(
((*versioned_constants.vm_resource_fee_cost().builtins.get(&BuiltinName::ecdsa).unwrap())
* u64_from_usize(
*vm_resource_usage.builtin_instance_counter.get(&BuiltinName::ecdsa).unwrap(),
))
.ceil()
.to_integer(),
));
);
let expected_gas_vector = gas_vector_from_vm_usage(
vm_usage_in_l1_gas,
&gas_vector_computation_mode,
Expand Down Expand Up @@ -172,9 +172,9 @@ fn test_float_get_vm_resource_usage(
fn test_discounted_gas_overdraft(
#[case] gas_price: u128,
#[case] data_gas_price: u128,
#[case] l1_gas_used: u128,
#[case] l1_data_gas_used: u128,
#[case] gas_bound: u128,
#[case] l1_gas_used: u64,
#[case] l1_data_gas_used: u64,
#[case] gas_bound: u64,
#[case] expect_failure: bool,
) {
let (l1_gas_used, l1_data_gas_used, gas_bound) =
Expand Down Expand Up @@ -224,7 +224,9 @@ fn test_discounted_gas_overdraft(
if expect_failure {
let error = report.error().unwrap();
let expected_actual_amount = l1_gas_used
+ (l1_data_gas_used.nonzero_checked_mul(data_gas_price).unwrap()) / gas_price;
+ (l1_data_gas_used.nonzero_checked_mul(data_gas_price).unwrap())
.checked_div(gas_price)
.unwrap();
assert_matches!(
error, FeeCheckError::MaxGasAmountExceeded { resource, max_amount, actual_amount }
if max_amount == gas_bound
Expand Down
4 changes: 2 additions & 2 deletions crates/blockifier/src/fee/fee_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ pub fn get_vm_resources_cost(

// Convert Cairo resource usage to L1 gas usage.
// Do so by taking the maximum of the usage of each builtin + step usage.
let vm_l1_gas_usage = GasAmount(u128::from(
let vm_l1_gas_usage = GasAmount(
vm_resource_fee_costs
.builtins
.iter()
Expand All @@ -66,7 +66,7 @@ pub fn get_vm_resources_cost(
)])
.map(|(cost, usage)| (cost * u64_from_usize(usage)).ceil().to_integer())
.fold(0, u64::max),
));
);

match computation_mode {
GasVectorComputationMode::NoL2Gas => GasVector::from_l1_gas(vm_l1_gas_usage),
Expand Down
8 changes: 4 additions & 4 deletions crates/blockifier/src/fee/gas_usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::fee::eth_gas_constants;
use crate::fee::resources::GasVector;
use crate::state::cached_state::StateChangesCount;
use crate::transaction::account_transaction::AccountTransaction;
use crate::utils::u128_from_usize;
use crate::utils::u64_from_usize;

#[cfg(test)]
#[path = "gas_usage_test.rs"]
Expand Down Expand Up @@ -43,7 +43,7 @@ pub fn get_da_gas_cost(state_changes_count: &StateChangesCount, use_kzg_da: bool
let (l1_gas, blob_gas) = if use_kzg_da {
(
0_u8.into(),
u128_from_usize(
u64_from_usize(
onchain_data_segment_length * eth_gas_constants::DATA_GAS_PER_FIELD_ELEMENT,
)
.into(),
Expand Down Expand Up @@ -71,7 +71,7 @@ pub fn get_da_gas_cost(state_changes_count: &StateChangesCount, use_kzg_da: bool
naive_cost - discount
};

(u128_from_usize(gas).into(), 0_u8.into())
(u64_from_usize(gas).into(), 0_u8.into())
};

GasVector { l1_gas, l1_data_gas: blob_gas, ..Default::default() }
Expand Down Expand Up @@ -136,7 +136,7 @@ pub fn get_log_message_to_l1_emissions_cost(l2_to_l1_payload_lengths: &[usize])

fn get_event_emission_cost(n_topics: usize, data_length: usize) -> GasVector {
GasVector::from_l1_gas(
u128_from_usize(
u64_from_usize(
eth_gas_constants::GAS_PER_LOG
+ (n_topics + constants::N_DEFAULT_TOPICS) * eth_gas_constants::GAS_PER_LOG_TOPIC
+ data_length * eth_gas_constants::GAS_PER_LOG_DATA_WORD,
Expand Down
17 changes: 8 additions & 9 deletions crates/blockifier/src/fee/gas_usage_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::state::cached_state::StateChangesCount;
use crate::test_utils::{DEFAULT_ETH_L1_DATA_GAS_PRICE, DEFAULT_ETH_L1_GAS_PRICE};
use crate::transaction::objects::FeeType;
use crate::transaction::test_utils::account_invoke_tx;
use crate::utils::{u128_from_usize, u64_from_usize};
use crate::utils::u64_from_usize;
use crate::versioned_constants::{ResourceCost, VersionedConstants};
#[fixture]
fn versioned_constants() -> &'static VersionedConstants {
Expand Down Expand Up @@ -90,7 +90,7 @@ fn test_get_event_gas_cost(
let execution_summary = CallInfo::summarize_many(call_infos.iter());
// 8 keys and 11 data words overall.
let expected_gas =
GasAmount(u128::from((data_word_cost * (event_key_factor * 8_u64 + 11_u64)).to_integer()));
GasAmount((data_word_cost * (event_key_factor * 8_u64 + 11_u64)).to_integer());
let expected_gas_vector = match gas_vector_computation_mode {
GasVectorComputationMode::NoL2Gas => GasVector::from_l1_gas(expected_gas),
GasVectorComputationMode::All => GasVector::from_l2_gas(expected_gas),
Expand Down Expand Up @@ -146,7 +146,7 @@ fn test_get_da_gas_cost_basic(#[case] state_changes_count: StateChangesCount) {

let computed_gas_vector = get_da_gas_cost(&state_changes_count, true);
assert_eq!(
GasVector::from_l1_data_gas(u128_from_usize(manual_blob_gas_usage).into()),
GasVector::from_l1_data_gas(u64_from_usize(manual_blob_gas_usage).into()),
computed_gas_vector
);
}
Expand Down Expand Up @@ -195,10 +195,7 @@ fn test_onchain_data_discount() {

let cost_without_discount = (state_changes_count.n_storage_updates * 2) * (512 + 100);
let actual_cost = get_da_gas_cost(&state_changes_count, use_kzg_da).l1_gas;
let cost_ratio = ResourceCost::new(
u64::try_from(actual_cost.0).unwrap(),
u64_from_usize(cost_without_discount),
);
let cost_ratio = ResourceCost::new(actual_cost.0, u64_from_usize(cost_without_discount));
assert!(cost_ratio <= ResourceCost::new(9, 10));
assert!(cost_ratio >= ResourceCost::new(88, 100));
}
Expand Down Expand Up @@ -236,10 +233,12 @@ fn test_discounted_gas_from_gas_vector_computation() {

let result_div_ceil = gas_usage.l1_gas
+ (gas_usage.l1_data_gas.nonzero_checked_mul(DEFAULT_ETH_L1_DATA_GAS_PRICE).unwrap())
.div_ceil(DEFAULT_ETH_L1_GAS_PRICE);
.checked_div_ceil(DEFAULT_ETH_L1_GAS_PRICE)
.unwrap();
let result_div_floor = gas_usage.l1_gas
+ (gas_usage.l1_data_gas.nonzero_checked_mul(DEFAULT_ETH_L1_DATA_GAS_PRICE).unwrap())
/ DEFAULT_ETH_L1_GAS_PRICE;
.checked_div(DEFAULT_ETH_L1_GAS_PRICE)
.unwrap();

assert_eq!(actual_result, result_div_ceil);
assert_eq!(actual_result, result_div_floor + GasAmount(1));
Expand Down
33 changes: 16 additions & 17 deletions crates/blockifier/src/fee/receipt_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use crate::transaction::test_utils::{
create_resource_bounds,
};
use crate::transaction::transactions::ExecutableTransaction;
use crate::utils::{u128_from_usize, u64_from_usize, usize_from_u128};
use crate::utils::{u64_from_usize, usize_from_u64};
use crate::versioned_constants::VersionedConstants;

#[fixture]
Expand Down Expand Up @@ -82,15 +82,15 @@ fn test_calculate_tx_gas_usage_basic<'a>(
let gas_per_code_byte = versioned_constants
.get_archival_data_gas_costs(&gas_vector_computation_mode)
.gas_per_code_byte;
let code_gas_cost = GasAmount(u128::from(
let code_gas_cost = GasAmount(
(gas_per_code_byte
* u64_from_usize(
(class_info.bytecode_length() + class_info.sierra_program_length())
* eth_gas_constants::WORD_WIDTH
+ class_info.abi_length(),
))
.to_integer(),
));
);
let manual_gas_vector = match gas_vector_computation_mode {
GasVectorComputationMode::NoL2Gas => GasVector::from_l1_gas(code_gas_cost),
GasVectorComputationMode::All => GasVector::from_l2_gas(code_gas_cost),
Expand Down Expand Up @@ -126,9 +126,9 @@ fn test_calculate_tx_gas_usage_basic<'a>(
let gas_per_data_felt = versioned_constants
.get_archival_data_gas_costs(&gas_vector_computation_mode)
.gas_per_data_felt;
let calldata_and_signature_gas_cost = u128::from(
(gas_per_data_felt * u64_from_usize(calldata_length + signature_length)).to_integer(),
)
let calldata_and_signature_gas_cost = (gas_per_data_felt
* u64_from_usize(calldata_length + signature_length))
.to_integer()
.into();
let manual_starknet_gas_usage_vector = match gas_vector_computation_mode {
GasVectorComputationMode::NoL2Gas => {
Expand Down Expand Up @@ -165,10 +165,9 @@ fn test_calculate_tx_gas_usage_basic<'a>(

// Manual calculation.
let message_segment_length = get_message_segment_length(&[], Some(l1_handler_payload_size));
let calldata_and_signature_gas_cost = u128::from(
(gas_per_data_felt * u64_from_usize(l1_handler_payload_size + signature_length))
.to_integer(),
)
let calldata_and_signature_gas_cost = (gas_per_data_felt
* u64_from_usize(l1_handler_payload_size + signature_length))
.to_integer()
.into();
let calldata_and_signature_gas_cost_vector = match gas_vector_computation_mode {
GasVectorComputationMode::NoL2Gas => {
Expand All @@ -179,16 +178,16 @@ fn test_calculate_tx_gas_usage_basic<'a>(
let manual_starknet_l1_gas_usage = message_segment_length
* eth_gas_constants::GAS_PER_MEMORY_WORD
+ eth_gas_constants::GAS_PER_COUNTER_DECREASE
+ usize_from_u128(
+ usize_from_u64(
get_consumed_message_to_l2_emissions_cost(Some(l1_handler_payload_size)).l1_gas.0,
)
.unwrap();
let manual_starknet_l1_gas_usage_vector =
GasVector::from_l1_gas(u128_from_usize(manual_starknet_l1_gas_usage).into());
GasVector::from_l1_gas(u64_from_usize(manual_starknet_l1_gas_usage).into());
let manual_sharp_gas_usage =
message_segment_length * eth_gas_constants::SHARP_GAS_PER_MEMORY_WORD;
let manual_gas_computation =
GasVector::from_l1_gas(u128_from_usize(manual_sharp_gas_usage).into())
GasVector::from_l1_gas(u64_from_usize(manual_sharp_gas_usage).into())
+ manual_starknet_l1_gas_usage_vector
+ calldata_and_signature_gas_cost_vector;
assert_eq!(l1_handler_gas_usage_vector, manual_gas_computation);
Expand Down Expand Up @@ -247,16 +246,16 @@ fn test_calculate_tx_gas_usage_basic<'a>(
let n_l2_to_l1_messages = l2_to_l1_payload_lengths.len();
let manual_starknet_gas_usage = message_segment_length * eth_gas_constants::GAS_PER_MEMORY_WORD
+ n_l2_to_l1_messages * eth_gas_constants::GAS_PER_ZERO_TO_NONZERO_STORAGE_SET
+ usize_from_u128(get_log_message_to_l1_emissions_cost(&l2_to_l1_payload_lengths).l1_gas.0)
+ usize_from_u64(get_log_message_to_l1_emissions_cost(&l2_to_l1_payload_lengths).l1_gas.0)
.unwrap();
let manual_sharp_gas_usage = message_segment_length
* eth_gas_constants::SHARP_GAS_PER_MEMORY_WORD
+ usize_from_u128(l2_to_l1_starknet_resources.state.to_gas_vector(use_kzg_da).l1_gas.0)
+ usize_from_u64(l2_to_l1_starknet_resources.state.to_gas_vector(use_kzg_da).l1_gas.0)
.unwrap();
let manual_sharp_blob_gas_usage =
l2_to_l1_starknet_resources.state.to_gas_vector(use_kzg_da).l1_data_gas;
let manual_gas_computation = GasVector {
l1_gas: u128_from_usize(manual_starknet_gas_usage + manual_sharp_gas_usage).into(),
l1_gas: u64_from_usize(manual_starknet_gas_usage + manual_sharp_gas_usage).into(),
l1_data_gas: manual_sharp_blob_gas_usage,
..Default::default()
};
Expand Down Expand Up @@ -331,7 +330,7 @@ fn test_calculate_tx_gas_usage_basic<'a>(
+ storage_writings_gas_usage_vector.l1_gas
// l2_to_l1_messages_gas_usage and storage_writings_gas_usage got a discount each, while
// the combined calculation got it once.
+ u128_from_usize(fee_balance_discount).into(),
+ u64_from_usize(fee_balance_discount).into(),
// Expected blob gas usage is from data availability only.
l1_data_gas: combined_cases_starknet_resources.state.to_gas_vector(use_kzg_da).l1_data_gas,
l2_gas: l1_handler_gas_usage_vector.l2_gas,
Expand Down
Loading

0 comments on commit a6fdfe0

Please sign in to comment.