Skip to content

Commit

Permalink
chore(starknet_batcher): use block info to create block info
Browse files Browse the repository at this point in the history
  • Loading branch information
ArniStarkware committed Dec 1, 2024
1 parent d3ead1e commit 5ec7bac
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 53 deletions.
5 changes: 0 additions & 5 deletions config/sequencer/default_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,6 @@
"privacy": "Public",
"value": 100
},
"batcher_config.block_builder_config.use_kzg_da": {
"description": "Indicates whether the kzg mechanism is used for data availability.",
"privacy": "Public",
"value": true
},
"batcher_config.block_builder_config.versioned_constants_overrides.invoke_tx_max_n_steps": {
"description": "Maximum number of steps the invoke function is allowed to run.",
"pointer_target": "versioned_constants_overrides.invoke_tx_max_n_steps",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,8 @@ impl ConsensusContext for SequencerConsensusContext {
number: BlockNumber::default(),
hash: BlockHash::default(),
}),
// TODO(Dan, Matan): Fill block info.
// TODO(Dan, Matan): Fill block info. Override the sequencer address in the block info
// in the BlockBuilderFactory.
block_info: BlockInfo {
block_number: proposal_init.height,
gas_prices: TEMPORARY_GAS_PRICES,
Expand Down Expand Up @@ -357,7 +358,8 @@ impl SequencerConsensusContext {
number: BlockNumber::default(),
hash: BlockHash::default(),
}),
// TODO: Fill block info.
// TODO(Dan, Matan): Fill block info. Override the sequencer address in the block info
// in the BlockBuilderFactory.
block_info: BlockInfo {
block_number: height,
gas_prices: TEMPORARY_GAS_PRICES,
Expand Down
9 changes: 5 additions & 4 deletions crates/starknet_api/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ impl GasPrice {

/// Utility struct representing a non-zero gas price. Useful when a gas amount must be computed by
/// taking a fee amount and dividing by the gas price.
#[derive(Copy, Clone, Debug, Deserialize, Serialize, derive_more::Display)]
#[derive(Copy, Clone, Debug, Deserialize, Eq, PartialEq, Serialize, derive_more::Display)]
pub struct NonzeroGasPrice(GasPrice);

impl NonzeroGasPrice {
Expand Down Expand Up @@ -439,7 +439,8 @@ macro_rules! impl_try_from_uint_for_nonzero_gas_price {

impl_try_from_uint_for_nonzero_gas_price!(u8, u16, u32, u64, u128);

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
// TODO(Arni): Remove derive of Default. Gas prices should always be set.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct GasPriceVector {
pub l1_gas_price: NonzeroGasPrice,
pub l1_data_gas_price: NonzeroGasPrice,
Expand All @@ -453,7 +454,7 @@ pub enum FeeType {
}

// TODO(Arni): Remove derive of Default. Gas prices should always be set.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct GasPrices {
pub eth_gas_prices: GasPriceVector, // In wei.
pub strk_gas_prices: GasPriceVector, // In fri.
Expand Down Expand Up @@ -486,7 +487,7 @@ impl GasPrices {
)]
pub struct BlockTimestamp(pub u64);

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct BlockInfo {
pub block_number: BlockNumber,
pub block_timestamp: BlockTimestamp,
Expand Down
7 changes: 2 additions & 5 deletions crates/starknet_batcher/src/batcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ impl Batcher {
.block_builder_factory
.create_block_builder(
BlockMetadata {
height: active_height,
block_info: propose_block_input.block_info,
retrospective_block_hash: propose_block_input.retrospective_block_hash,
},
BlockBuilderExecutionParams {
Expand Down Expand Up @@ -203,7 +203,7 @@ impl Batcher {
.block_builder_factory
.create_block_builder(
BlockMetadata {
height: active_height,
block_info: validate_block_input.block_info,
retrospective_block_hash: validate_block_input.retrospective_block_hash,
},
BlockBuilderExecutionParams {
Expand Down Expand Up @@ -473,7 +473,6 @@ fn verify_block_input(
) -> BatcherResult<()> {
verify_non_empty_retrospective_block_hash(height, retrospective_block_hash)?;
verify_block_number(height, block_number)?;

Ok(())
}

Expand All @@ -486,14 +485,12 @@ fn verify_non_empty_retrospective_block_hash(
{
return Err(BatcherError::MissingRetrospectiveBlockHash);
}

Ok(())
}

fn verify_block_number(height: BlockNumber, block_number: BlockNumber) -> BatcherResult<()> {
if block_number != height {
return Err(BatcherError::InvalidBlockNumber { active_height: height, block_number });
}

Ok(())
}
12 changes: 8 additions & 4 deletions crates/starknet_batcher/src/batcher_test.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::{Arc, LazyLock};

use assert_matches::assert_matches;
use async_trait::async_trait;
use blockifier::abi::constants;
use blockifier::test_utils::struct_impls::BlockInfoExt;
use chrono::Utc;
use futures::future::BoxFuture;
use futures::FutureExt;
Expand Down Expand Up @@ -61,6 +62,9 @@ const STREAMING_CHUNK_SIZE: usize = 3;
const BLOCK_GENERATION_TIMEOUT: tokio::time::Duration = tokio::time::Duration::from_secs(1);
const PROPOSAL_ID: ProposalId = ProposalId(0);

static INITIAL_BLOCK_INFO: LazyLock<BlockInfo> =
LazyLock::new(|| BlockInfo { block_number: INITIAL_HEIGHT, ..BlockInfo::create_for_testing() });

fn proposal_commitment() -> ProposalCommitment {
ProposalCommitment {
state_diff_commitment: StateDiffCommitment(PoseidonHash(felt!(u128::try_from(7).unwrap()))),
Expand Down Expand Up @@ -268,7 +272,7 @@ async fn validate_block_full_flow() {
proposal_id: PROPOSAL_ID,
deadline: deadline(),
retrospective_block_hash: None,
block_info: BlockInfo { block_number: INITIAL_HEIGHT, ..Default::default() },
block_info: INITIAL_BLOCK_INFO.clone(),
};
batcher.validate_block(validate_block_input).await.unwrap();

Expand Down Expand Up @@ -388,7 +392,7 @@ async fn send_finish_to_an_invalid_proposal() {
proposal_id: PROPOSAL_ID,
deadline: deadline(),
retrospective_block_hash: None,
block_info: BlockInfo { block_number: INITIAL_HEIGHT, ..Default::default() },
block_info: INITIAL_BLOCK_INFO.clone(),
};
batcher.validate_block(validate_block_input).await.unwrap();

Expand Down Expand Up @@ -421,7 +425,7 @@ async fn propose_block_full_flow() {
proposal_id: PROPOSAL_ID,
retrospective_block_hash: None,
deadline: chrono::Utc::now() + chrono::Duration::seconds(1),
block_info: BlockInfo { block_number: INITIAL_HEIGHT, ..Default::default() },
block_info: INITIAL_BLOCK_INFO.clone(),
})
.await
.unwrap();
Expand Down
41 changes: 9 additions & 32 deletions crates/starknet_batcher/src/block_builder.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::collections::BTreeMap;

use async_trait::async_trait;
use blockifier::blockifier::block::validated_gas_prices;
use blockifier::blockifier::config::TransactionExecutorConfig;
use blockifier::blockifier::transaction_executor::{
TransactionExecutor,
Expand All @@ -26,13 +25,7 @@ use papyrus_config::{ParamPath, ParamPrivacyInput, SerializedParam};
use papyrus_state_reader::papyrus_state::PapyrusReader;
use papyrus_storage::StorageReader;
use serde::{Deserialize, Serialize};
use starknet_api::block::{
BlockHashAndNumber,
BlockInfo,
BlockNumber,
BlockTimestamp,
NonzeroGasPrice,
};
use starknet_api::block::{BlockHashAndNumber, BlockInfo};
use starknet_api::core::ContractAddress;
use starknet_api::executable_transaction::Transaction;
use starknet_api::transaction::TransactionHash;
Expand All @@ -45,8 +38,6 @@ use crate::transaction_provider::{NextTxs, TransactionProvider, TransactionProvi

#[derive(Debug, Error)]
pub enum BlockBuilderError {
#[error(transparent)]
BadTimestamp(#[from] std::num::TryFromIntError),
#[error(transparent)]
BlockifierStateError(#[from] StateError),
#[error(transparent)]
Expand Down Expand Up @@ -224,7 +215,7 @@ async fn collect_execution_results_and_stream_txs(
}

pub struct BlockMetadata {
pub height: BlockNumber,
pub block_info: BlockInfo,
pub retrospective_block_hash: Option<BlockHashAndNumber>,
}

Expand All @@ -248,7 +239,6 @@ pub struct BlockBuilderConfig {
pub execute_config: TransactionExecutorConfig,
pub bouncer_config: BouncerConfig,
pub sequencer_address: ContractAddress,
pub use_kzg_da: bool,
pub tx_chunk_size: usize,
pub versioned_constants_overrides: VersionedConstantsOverrides,
}
Expand All @@ -261,7 +251,6 @@ impl Default for BlockBuilderConfig {
execute_config: TransactionExecutorConfig::default(),
bouncer_config: BouncerConfig::default(),
sequencer_address: ContractAddress::default(),
use_kzg_da: true,
tx_chunk_size: 100,
versioned_constants_overrides: VersionedConstantsOverrides::default(),
}
Expand All @@ -279,12 +268,6 @@ impl SerializeConfig for BlockBuilderConfig {
"The address of the sequencer.",
ParamPrivacyInput::Public,
)]));
dump.append(&mut BTreeMap::from([ser_param(
"use_kzg_da",
&self.use_kzg_da,
"Indicates whether the kzg mechanism is used for data availability.",
ParamPrivacyInput::Public,
)]));
dump.append(&mut BTreeMap::from([ser_param(
"tx_chunk_size",
&self.tx_chunk_size,
Expand All @@ -308,33 +291,27 @@ pub struct BlockBuilderFactory {
impl BlockBuilderFactory {
fn preprocess_and_create_transaction_executor(
&self,
block_metadata: &BlockMetadata,
block_metadata: BlockMetadata,
) -> BlockBuilderResult<TransactionExecutor<PapyrusReader>> {
let height = block_metadata.block_info.block_number;
let block_builder_config = self.block_builder_config.clone();
let next_block_info = BlockInfo {
block_number: block_metadata.height,
block_timestamp: BlockTimestamp(chrono::Utc::now().timestamp().try_into()?),
let block_info = BlockInfo {
sequencer_address: block_builder_config.sequencer_address,
// TODO (yael 7/10/2024): add logic to compute gas prices
gas_prices: {
let tmp_val = NonzeroGasPrice::MIN;
validated_gas_prices(tmp_val, tmp_val, tmp_val, tmp_val, tmp_val, tmp_val)
},
use_kzg_da: block_builder_config.use_kzg_da,
..block_metadata.block_info
};
let versioned_constants = VersionedConstants::get_versioned_constants(
block_builder_config.versioned_constants_overrides,
);
let block_context = BlockContext::new(
next_block_info,
block_info,
block_builder_config.chain_info,
versioned_constants,
block_builder_config.bouncer_config,
);

let state_reader = PapyrusReader::new(
self.storage_reader.clone(),
block_metadata.height,
height,
self.global_class_hash_to_class.clone(),
);

Expand All @@ -358,7 +335,7 @@ impl BlockBuilderFactoryTrait for BlockBuilderFactory {
output_content_sender: Option<tokio::sync::mpsc::UnboundedSender<Transaction>>,
abort_signal_receiver: tokio::sync::oneshot::Receiver<()>,
) -> BlockBuilderResult<Box<dyn BlockBuilderTrait>> {
let executor = self.preprocess_and_create_transaction_executor(&block_metadata)?;
let executor = self.preprocess_and_create_transaction_executor(block_metadata)?;
Ok(Box::new(BlockBuilder::new(
Box::new(executor),
tx_provider,
Expand Down
2 changes: 1 addition & 1 deletion crates/starknet_batcher/src/proposal_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ struct ProposalTask {
/// Taking care of:
/// - Proposing new blocks.
/// - Validating incoming proposals.
/// - Commiting accepted proposals to the storage.
/// - Committing accepted proposals to the storage.
///
/// Triggered by the consensus.
pub(crate) struct ProposalManager {
Expand Down

0 comments on commit 5ec7bac

Please sign in to comment.