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

Make BlockContext a newtype around BlockInfo #1323

Merged
merged 1 commit into from
Jan 18, 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
17 changes: 11 additions & 6 deletions crates/blockifier/src/block_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ use crate::transaction::objects::FeeType;

#[derive(Clone, Debug)]
pub struct BlockContext {
pub block_info: BlockInfo,
}

impl BlockContext {
pub fn fee_token_address(&self, fee_type: &FeeType) -> ContractAddress {
self.block_info.fee_token_addresses.get_by_fee_type(fee_type)
}
}

#[derive(Clone, Debug)]
pub struct BlockInfo {
pub chain_id: ChainId,
pub block_number: BlockNumber,
pub block_timestamp: BlockTimestamp,
Expand All @@ -25,12 +36,6 @@ pub struct BlockContext {
pub max_recursion_depth: usize,
}

impl BlockContext {
pub fn fee_token_address(&self, fee_type: &FeeType) -> ContractAddress {
self.fee_token_addresses.get_by_fee_type(fee_type)
}
}

#[derive(Clone, Debug)]
pub struct FeeTokenAddresses {
pub strk_fee_token_address: ContractAddress,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,8 @@ impl<'a> DeprecatedSyscallHintProcessor<'a> {
tx_signature_length.into(),
tx_signature_start_ptr.into(),
stark_felt_to_felt(account_tx_context.transaction_hash().0).into(),
Felt252::from_bytes_be(self.context.block_context.chain_id.0.as_bytes()).into(),
Felt252::from_bytes_be(self.context.block_context.block_info.chain_id.0.as_bytes())
.into(),
stark_felt_to_felt(account_tx_context.nonce().0).into(),
];

Expand Down
8 changes: 5 additions & 3 deletions crates/blockifier/src/execution/deprecated_syscalls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,9 @@ pub fn get_block_number(
syscall_handler: &mut DeprecatedSyscallHintProcessor<'_>,
) -> DeprecatedSyscallResult<GetBlockNumberResponse> {
// TODO(Yoni, 1/5/2024): disable for validate.
Ok(GetBlockNumberResponse { block_number: syscall_handler.context.block_context.block_number })
Ok(GetBlockNumberResponse {
block_number: syscall_handler.context.block_context.block_info.block_number,
})
}

// GetBlockTimestamp syscall.
Expand All @@ -423,7 +425,7 @@ pub fn get_block_timestamp(
) -> DeprecatedSyscallResult<GetBlockTimestampResponse> {
// TODO(Yoni, 1/5/2024): disable for validate.
Ok(GetBlockTimestampResponse {
block_timestamp: syscall_handler.context.block_context.block_timestamp,
block_timestamp: syscall_handler.context.block_context.block_info.block_timestamp,
})
}

Expand Down Expand Up @@ -476,7 +478,7 @@ pub fn get_sequencer_address(
) -> DeprecatedSyscallResult<GetSequencerAddressResponse> {
syscall_handler.verify_not_in_validate_mode("get_sequencer_address")?;
Ok(GetSequencerAddressResponse {
address: syscall_handler.context.block_context.sequencer_address,
address: syscall_handler.context.block_context.block_info.sequencer_address,
})
}

Expand Down
15 changes: 8 additions & 7 deletions crates/blockifier/src/execution/entry_point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ impl EntryPointExecutionContext {
error_stack: vec![],
account_tx_context: account_tx_context.clone(),
current_recursion_depth: Default::default(),
max_recursion_depth: block_context.max_recursion_depth,
max_recursion_depth: block_context.block_info.max_recursion_depth,
block_context: block_context.clone(),
execution_mode: mode,
})
Expand Down Expand Up @@ -212,18 +212,19 @@ impl EntryPointExecutionContext {
mode: &ExecutionMode,
limit_steps_by_resources: bool,
) -> TransactionExecutionResult<usize> {
let block_info = &block_context.block_info;
let block_upper_bound = match mode {
// TODO(Ori, 1/2/2024): Write an indicative expect message explaining why the conversion
// works.
ExecutionMode::Validate => min(
block_context
block_info
.validate_max_n_steps
.try_into()
.expect("Failed to convert u32 to usize."),
constants::MAX_VALIDATE_STEPS_PER_TX,
),
ExecutionMode::Execute => min(
block_context
block_info
.invoke_tx_max_n_steps
.try_into()
.expect("Failed to convert u32 to usize."),
Expand All @@ -236,16 +237,16 @@ impl EntryPointExecutionContext {
}

let gas_per_step =
block_context.vm_resource_fee_cost.get(constants::N_STEPS_RESOURCE).unwrap_or_else(
|| panic!("{} must appear in `vm_resource_fee_cost`.", constants::N_STEPS_RESOURCE),
);
block_info.vm_resource_fee_cost.get(constants::N_STEPS_RESOURCE).unwrap_or_else(|| {
panic!("{} must appear in `vm_resource_fee_cost`.", constants::N_STEPS_RESOURCE)
});

// 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 account_tx_context {
AccountTransactionContext::Deprecated(context) => {
let max_cairo_steps = context.max_fee.0
/ block_context
/ block_info
.gas_prices
.get_gas_price_by_fee_type(&account_tx_context.fee_type());
// TODO(Ori, 1/2/2024): Write an indicative expect message explaining why the
Expand Down
21 changes: 10 additions & 11 deletions crates/blockifier/src/execution/syscalls/hint_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,23 +434,21 @@ impl<'a> SyscallHintProcessor<'a> {
&mut self,
vm: &mut VirtualMachine,
) -> SyscallResult<Relocatable> {
let block_context = &self.context.block_context;
let block_info: Vec<StarkFelt> = if self.is_validate_mode() {
let block_info = &self.context.block_context.block_info;
let block_timestamp = StarkFelt::from(block_info.block_timestamp.0);
let block_number = StarkFelt::from(block_info.block_number.0);
let block_data: Vec<StarkFelt> = if self.is_validate_mode() {
vec![
// TODO(Yoni, 1/5/2024): set the number to be zero for `validate`.
StarkFelt::from(block_context.block_number.0),
block_number,
// TODO(Yoni, 1/5/2024): set the timestamp to be zero for `validate`.
StarkFelt::from(block_context.block_timestamp.0),
block_timestamp,
StarkFelt::ZERO,
]
} else {
vec![
StarkFelt::from(block_context.block_number.0),
StarkFelt::from(block_context.block_timestamp.0),
*block_context.sequencer_address.0.key(),
]
vec![block_number, block_timestamp, *block_info.sequencer_address.0.key()]
};
let (block_info_segment_start_ptr, _) = self.allocate_data_segment(vm, block_info)?;
let (block_info_segment_start_ptr, _) = self.allocate_data_segment(vm, block_data)?;

Ok(block_info_segment_start_ptr)
}
Expand Down Expand Up @@ -478,7 +476,8 @@ impl<'a> SyscallHintProcessor<'a> {
tx_signature_start_ptr.into(),
tx_signature_end_ptr.into(),
stark_felt_to_felt((self.context.account_tx_context).transaction_hash().0).into(),
Felt252::from_bytes_be(self.context.block_context.chain_id.0.as_bytes()).into(),
Felt252::from_bytes_be(self.context.block_context.block_info.chain_id.0.as_bytes())
.into(),
stark_felt_to_felt((self.context.account_tx_context).nonce().0).into(),
];

Expand Down
2 changes: 1 addition & 1 deletion crates/blockifier/src/execution/syscalls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ pub fn get_block_hash(
}

let requested_block_number = request.block_number.0;
let current_block_number = syscall_handler.context.block_context.block_number.0;
let current_block_number = syscall_handler.context.block_context.block_info.block_number.0;

if current_block_number < constants::STORED_BLOCK_HASH_BUFFER
|| requested_block_number > current_block_number - constants::STORED_BLOCK_HASH_BUFFER
Expand Down
8 changes: 4 additions & 4 deletions crates/blockifier/src/fee/fee_checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use starknet_api::hash::StarkFelt;
use starknet_api::transaction::Fee;
use thiserror::Error;

use crate::block_context::BlockContext;
use crate::block_context::{BlockContext, BlockInfo};
use crate::fee::actual_cost::ActualCost;
use crate::fee::fee_utils::{
calculate_tx_l1_gas_usage, get_balance_and_if_covers_fee, get_fee_by_l1_gas_usage,
Expand Down Expand Up @@ -55,7 +55,7 @@ impl FeeCheckReport {
pub fn from_fee_check_error(
actual_fee: Fee,
error: FeeCheckError,
block_context: &BlockContext,
block_info: &BlockInfo,
account_tx_context: &AccountTransactionContext,
) -> TransactionExecutionResult<Self> {
let recommended_fee = match error {
Expand All @@ -70,7 +70,7 @@ impl FeeCheckReport {
FeeCheckError::MaxFeeExceeded { .. } | FeeCheckError::MaxL1GasAmountExceeded { .. } => {
match account_tx_context {
AccountTransactionContext::Current(context) => get_fee_by_l1_gas_usage(
block_context,
block_info,
context.l1_resource_bounds()?.max_amount.into(),
&FeeType::Strk,
),
Expand Down Expand Up @@ -227,7 +227,7 @@ impl PostExecutionReport {
return Ok(Self(FeeCheckReport::from_fee_check_error(
*actual_fee,
fee_check_error,
block_context,
&block_context.block_info,
account_tx_context,
)?));
}
Expand Down
10 changes: 5 additions & 5 deletions crates/blockifier/src/fee/fee_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use starknet_api::hash::StarkFelt;
use starknet_api::transaction::Fee;

use crate::abi::constants;
use crate::block_context::BlockContext;
use crate::block_context::{BlockContext, BlockInfo};
use crate::state::state_api::StateReader;
use crate::transaction::errors::TransactionFeeError;
use crate::transaction::objects::{
Expand All @@ -31,7 +31,7 @@ pub fn calculate_l1_gas_by_vm_usage(
block_context: &BlockContext,
vm_resource_usage: &ResourcesMapping,
) -> TransactionFeeResult<f64> {
let vm_resource_fee_costs = &block_context.vm_resource_fee_cost;
let vm_resource_fee_costs = &block_context.block_info.vm_resource_fee_cost;
let vm_resource_names = HashSet::<&String>::from_iter(vm_resource_usage.0.keys());
if !vm_resource_names.is_subset(&HashSet::from_iter(vm_resource_fee_costs.keys())) {
return Err(TransactionFeeError::CairoResourcesNotContainedInFeeCosts);
Expand Down Expand Up @@ -63,11 +63,11 @@ pub fn calculate_tx_l1_gas_usage(
}

pub fn get_fee_by_l1_gas_usage(
block_context: &BlockContext,
block_info: &BlockInfo,
l1_gas_usage: u128,
fee_type: &FeeType,
) -> Fee {
Fee(l1_gas_usage * block_context.gas_prices.get_gas_price_by_fee_type(fee_type))
Fee(l1_gas_usage * block_info.gas_prices.get_gas_price_by_fee_type(fee_type))
}

/// Calculates the fee that should be charged, given execution resources.
Expand All @@ -77,7 +77,7 @@ pub fn calculate_tx_fee(
fee_type: &FeeType,
) -> TransactionFeeResult<Fee> {
let l1_gas_usage = calculate_tx_l1_gas_usage(resources, block_context)?;
Ok(get_fee_by_l1_gas_usage(block_context, l1_gas_usage, fee_type))
Ok(get_fee_by_l1_gas_usage(&block_context.block_info, l1_gas_usage, fee_type))
}

/// Returns the current fee balance and a boolean indicating whether the balance covers the fee.
Expand Down
2 changes: 1 addition & 1 deletion crates/blockifier/src/fee/gas_usage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,5 +225,5 @@ pub fn estimate_minimal_fee(
tx: &AccountTransaction,
) -> TransactionExecutionResult<Fee> {
let estimated_minimal_l1_gas = estimate_minimal_l1_gas(block_context, tx)?;
Ok(get_fee_by_l1_gas_usage(block_context, estimated_minimal_l1_gas, &tx.fee_type()))
Ok(get_fee_by_l1_gas_usage(&block_context.block_info, estimated_minimal_l1_gas, &tx.fee_type()))
}
2 changes: 1 addition & 1 deletion crates/blockifier/src/state/cached_state_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ fn test_state_changes_merge() {
let mut state: CachedState<DictStateReader> = CachedState::default();
let mut transactional_state = CachedState::create_transactional(&mut state);
let block_context = BlockContext::create_for_testing();
let fee_token_address = block_context.fee_token_addresses.eth_fee_token_address;
let fee_token_address = block_context.block_info.fee_token_addresses.eth_fee_token_address;
let state_changes1 = create_state_changes_for_test(&mut transactional_state, fee_token_address);
transactional_state.commit();

Expand Down
6 changes: 3 additions & 3 deletions crates/blockifier/src/test_utils/prices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ fn fee_transfer_resources(
let fee_transfer_call = CallEntryPoint {
entry_point_selector: selector_from_name(constants::TRANSFER_ENTRY_POINT_NAME),
calldata: calldata![
*block_context.sequencer_address.0.key(), // Recipient.
stark_felt!(7_u8), // LSB of Amount.
stark_felt!(0_u8) // MSB of Amount.
*block_context.block_info.sequencer_address.0.key(), // Recipient.
stark_felt!(7_u8), // LSB of Amount.
stark_felt!(0_u8) // MSB of Amount.
],
storage_address: token_address,
caller_address: account_contract_address,
Expand Down
23 changes: 17 additions & 6 deletions crates/blockifier/src/test_utils/struct_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use super::{
};
use crate::abi::constants;
use crate::abi::constants::{MAX_STEPS_PER_TX, MAX_VALIDATE_STEPS_PER_TX};
use crate::block_context::{BlockContext, FeeTokenAddresses, GasPrices};
use crate::block_context::{BlockContext, BlockInfo, FeeTokenAddresses, GasPrices};
use crate::execution::call_info::{CallExecution, CallInfo, Retdata};
use crate::execution::contract_class::{ContractClassV0, ContractClassV1};
use crate::execution::entry_point::{
Expand Down Expand Up @@ -84,9 +84,9 @@ impl CallEntryPoint {
}
}

impl BlockContext {
pub fn create_for_testing() -> BlockContext {
BlockContext {
impl BlockInfo {
pub fn create_for_testing() -> Self {
Self {
chain_id: ChainId(CHAIN_ID_NAME.to_string()),
block_number: BlockNumber(CURRENT_BLOCK_NUMBER),
block_timestamp: BlockTimestamp(CURRENT_BLOCK_TIMESTAMP),
Expand Down Expand Up @@ -115,7 +115,7 @@ impl BlockContext {
}
}

pub fn create_for_account_testing() -> BlockContext {
pub fn create_for_account_testing() -> Self {
let vm_resource_fee_cost = Arc::new(HashMap::from([
(constants::N_STEPS_RESOURCE.to_string(), 1_f64),
(HASH_BUILTIN_NAME.to_string(), 1_f64),
Expand All @@ -126,7 +126,18 @@ impl BlockContext {
(OUTPUT_BUILTIN_NAME.to_string(), 1_f64),
(EC_OP_BUILTIN_NAME.to_string(), 1_f64),
]));
BlockContext { vm_resource_fee_cost, ..BlockContext::create_for_testing() }

Self { vm_resource_fee_cost, ..Self::create_for_testing() }
}
}

impl BlockContext {
pub fn create_for_testing() -> Self {
Self { block_info: BlockInfo::create_for_testing() }
}

pub fn create_for_account_testing() -> Self {
Self { block_info: BlockInfo::create_for_account_testing() }
}
}

Expand Down
10 changes: 5 additions & 5 deletions crates/blockifier/src/transaction/account_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ impl AccountTransaction {
block_context: &BlockContext,
) -> TransactionPreValidationResult<()> {
let minimal_l1_gas_amount = estimate_minimal_l1_gas(block_context, self)?;
let block_info = &block_context.block_info;

match account_tx_context {
AccountTransactionContext::Current(context) => {
Expand All @@ -190,9 +191,8 @@ impl AccountTransaction {
})?;
}

let actual_l1_gas_price = block_context
.gas_prices
.get_gas_price_by_fee_type(&account_tx_context.fee_type());
let actual_l1_gas_price =
block_info.gas_prices.get_gas_price_by_fee_type(&account_tx_context.fee_type());
if max_l1_gas_price < actual_l1_gas_price {
return Err(TransactionFeeError::MaxL1GasPriceTooLow {
max_l1_gas_price,
Expand All @@ -203,7 +203,7 @@ impl AccountTransaction {
AccountTransactionContext::Deprecated(context) => {
let max_fee = context.max_fee;
let min_fee = get_fee_by_l1_gas_usage(
block_context,
block_info,
minimal_l1_gas_amount,
&account_tx_context.fee_type(),
);
Expand Down Expand Up @@ -306,7 +306,7 @@ impl AccountTransaction {
entry_point_type: EntryPointType::External,
entry_point_selector: selector_from_name(constants::TRANSFER_ENTRY_POINT_NAME),
calldata: calldata![
*block_context.sequencer_address.0.key(), // Recipient.
*block_context.block_info.sequencer_address.0.key(), // Recipient.
lsb_amount,
msb_amount
],
Expand Down
Loading
Loading