Skip to content

Commit

Permalink
refactor: simplify block structure at its relationships
Browse files Browse the repository at this point in the history
  • Loading branch information
kariy committed Oct 19, 2024
1 parent b10f124 commit c1618a7
Show file tree
Hide file tree
Showing 13 changed files with 81 additions and 89 deletions.
10 changes: 6 additions & 4 deletions crates/katana/core/src/backend/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use std::sync::Arc;

use katana_db::tables::Receipts;
use katana_executor::{ExecutionOutput, ExecutionResult, ExecutorFactory};
use katana_primitives::block::{
Block, FinalityStatus, GasPrices, Header, PartialHeader, SealedBlock, SealedBlockWithStatus,
Block, FinalityStatus, GasPrices, Header, SealedBlock, SealedBlockWithStatus,
};
use katana_primitives::chain_spec::ChainSpec;
use katana_primitives::da::L1DataAvailabilityMode;
Expand Down Expand Up @@ -37,6 +36,7 @@ pub struct Backend<EF: ExecutorFactory> {
}

impl<EF: ExecutorFactory> Backend<EF> {
// TODO: add test for this function
pub fn do_mine_block(
&self,
block_env: &BlockEnv,
Expand All @@ -62,7 +62,7 @@ impl<EF: ExecutorFactory> Backend<EF> {
// create a new block and compute its commitment
let block = self.commit_block(block_env, txs, &receipts)?;
let block = SealedBlockWithStatus { block, status: FinalityStatus::AcceptedOnL2 };
let block_number = block.block.header.header.number;
let block_number = block.block.header.number;

self.blockchain.provider().insert_block_with_states_and_receipts(
block,
Expand Down Expand Up @@ -105,6 +105,7 @@ impl<EF: ExecutorFactory> Backend<EF> {
transactions: Vec<TxWithHash>,
receipts: &[Receipt],
) -> Result<SealedBlock, BlockProductionError> {
// get the hash of the latest committed block
let parent_hash = self.blockchain.provider().latest_hash()?;
let events_count = receipts.iter().map(|r| r.events().len() as u32).sum::<u32>();
let transaction_count = transactions.len() as u32;
Expand Down Expand Up @@ -134,6 +135,7 @@ impl<EF: ExecutorFactory> Backend<EF> {
protocol_version: self.chain_spec.version.clone(),
};

Ok(Block { header, body: transactions }.seal())
let sealed = Block { header, body: transactions }.seal();
Ok(sealed)
}
}
11 changes: 4 additions & 7 deletions crates/katana/core/src/backend/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,18 +353,15 @@ mod tests {

let block_number = blockchain.provider().latest_number().unwrap();
let block_hash = blockchain.provider().latest_hash().unwrap();
let block = blockchain
.provider()
.block_by_hash(dummy_block.block.header.hash)
.unwrap()
.unwrap();
let block =
blockchain.provider().block_by_hash(dummy_block.block.hash).unwrap().unwrap();

let tx = blockchain.provider().transaction_by_hash(dummy_tx.hash).unwrap().unwrap();
let tx_exec =
blockchain.provider().transaction_execution(dummy_tx.hash).unwrap().unwrap();

assert_eq!(block_hash, dummy_block.block.header.hash);
assert_eq!(block_number, dummy_block.block.header.header.number);
assert_eq!(block_hash, dummy_block.block.hash);
assert_eq!(block_number, dummy_block.block.header.number);
assert_eq!(block, dummy_block.block.unseal());
assert_eq!(tx, dummy_tx);
assert_eq!(tx_exec, TxExecInfo::default());
Expand Down
30 changes: 9 additions & 21 deletions crates/katana/primitives/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use starknet::core::crypto::compute_hash_on_elements;

use crate::contract::ContractAddress;
use crate::da::L1DataAvailabilityMode;
use crate::env::BlockEnv;
use crate::transaction::{ExecutableTxWithHash, TxHash, TxWithHash};
use crate::version::ProtocolVersion;
use crate::Felt;
Expand Down Expand Up @@ -130,11 +129,6 @@ impl Header {
self.parent_hash, // parent hash
])
}

fn seal(self) -> SealedHeader {
let hash = self.compute_hash();
SealedHeader { hash, header: self }
}
}

/// Represents a Starknet full block.
Expand All @@ -155,12 +149,13 @@ pub struct BlockWithTxHashes {
impl Block {
/// Seals the block. This computes the hash of the block.
pub fn seal(self) -> SealedBlock {
SealedBlock { header: self.header.seal(), body: self.body }
let hash = self.header.compute_hash();
SealedBlock { hash, header: self.header, body: self.body }
}

/// Seals the block with a given hash.
pub fn seal_with_hash(self, hash: BlockHash) -> SealedBlock {
SealedBlock { header: SealedHeader { hash, header: self.header }, body: self.body }
SealedBlock { hash, header: self.header, body: self.body }
}

/// Seals the block with a given block hash and status.
Expand All @@ -173,28 +168,21 @@ impl Block {
}
}

#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SealedHeader {
/// The hash of the header.
pub hash: BlockHash,
/// The generic header info.
pub header: Header,
}

/// A full Starknet block that has been sealed.
#[derive(Debug, Clone)]
pub struct SealedBlock {
/// The sealed block header.
pub header: SealedHeader,
/// The block body.
/// The block hash.
pub hash: BlockHash,
/// The block header.
pub header: Header,
/// The block transactions.
pub body: Vec<TxWithHash>,
}

impl SealedBlock {
/// Unseal the block.
pub fn unseal(self) -> Block {
Block { header: self.header.header, body: self.body }
Block { header: self.header, body: self.body }
}
}

Expand Down
5 changes: 5 additions & 0 deletions crates/katana/primitives/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,13 @@ mod tests {
// setup expected storage values
let expected_block = Block {
header: Header {
events_commitment: Felt::ZERO,
receipts_commitment: Felt::ZERO,
state_diff_commitment: Felt::ZERO,
transactions_commitment: Felt::ZERO,
number: chain_spec.genesis.number,
timestamp: chain_spec.genesis.timestamp,
state_root: chain_spec.genesis.state_root,
parent_hash: chain_spec.genesis.parent_hash,
sequencer_address: chain_spec.genesis.sequencer_address,
l1_gas_prices: chain_spec.genesis.gas_prices.clone(),
Expand Down
2 changes: 1 addition & 1 deletion crates/katana/storage/provider/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::ops::{Range, RangeInclusive};
use katana_db::models::block::StoredBlockBodyIndices;
use katana_primitives::block::{
Block, BlockHash, BlockHashOrNumber, BlockNumber, BlockWithTxHashes, FinalityStatus, Header,
SealedBlockWithStatus, SealedHeader,
SealedBlockWithStatus,
};
use katana_primitives::class::{ClassHash, CompiledClass, CompiledClassHash, FlattenedSierraClass};
use katana_primitives::contract::{ContractAddress, StorageKey, StorageValue};
Expand Down
14 changes: 7 additions & 7 deletions crates/katana/storage/provider/src/providers/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use katana_db::tables::{self, DupSort, Table};
use katana_db::utils::KeyValue;
use katana_primitives::block::{
Block, BlockHash, BlockHashOrNumber, BlockNumber, BlockWithTxHashes, FinalityStatus, Header,
SealedBlockWithStatus, SealedHeader,
SealedBlockWithStatus,
};
use katana_primitives::class::{ClassHash, CompiledClassHash};
use katana_primitives::contract::{
Expand Down Expand Up @@ -606,10 +606,10 @@ impl<Db: Database> BlockWriter for DbProvider<Db> {
executions: Vec<TxExecInfo>,
) -> ProviderResult<()> {
self.0.update(move |db_tx| -> ProviderResult<()> {
let block_hash = block.block.header.hash;
let block_number = block.block.header.header.number;
let block_hash = block.block.hash;
let block_number = block.block.header.number;

let block_header = block.block.header.header;
let block_header = block.block.header;
let transactions = block.block.body;

let tx_count = transactions.len() as u64;
Expand Down Expand Up @@ -882,7 +882,7 @@ mod tests {

// get values

let block_id: BlockHashOrNumber = block.block.header.hash.into();
let block_id: BlockHashOrNumber = block.block.hash.into();

let latest_number = provider.latest_number().unwrap();
let latest_hash = provider.latest_hash().unwrap();
Expand Down Expand Up @@ -921,9 +921,9 @@ mod tests {
assert_eq!(body_indices.tx_count, tx_count);

assert_eq!(block_status, FinalityStatus::AcceptedOnL2);
assert_eq!(block.block.header.hash, latest_hash);
assert_eq!(block.block.hash, latest_hash);
assert_eq!(block.block.body.len() as u64, tx_count);
assert_eq!(block.block.header.header.number, latest_number);
assert_eq!(block.block.header.number, latest_number);
assert_eq!(block.block.unseal(), actual_block);

assert_eq!(nonce1, felt!("1"));
Expand Down
6 changes: 3 additions & 3 deletions crates/katana/storage/provider/src/providers/fork/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,10 +469,10 @@ impl BlockWriter for ForkedProvider {
) -> ProviderResult<()> {
let mut storage = self.storage.write();

let block_hash = block.block.header.hash;
let block_number = block.block.header.header.number;
let block_hash = block.block.hash;
let block_number = block.block.header.number;

let block_header = block.block.header.header;
let block_header = block.block.header;
let txs = block.block.body;

// create block body indices
Expand Down
6 changes: 3 additions & 3 deletions crates/katana/storage/provider/src/providers/in_memory/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -463,10 +463,10 @@ impl BlockWriter for InMemoryProvider {
) -> ProviderResult<()> {
let mut storage = self.storage.write();

let block_hash = block.block.header.hash;
let block_number = block.block.header.header.number;
let block_hash = block.block.hash;
let block_number = block.block.header.number;

let block_header = block.block.header.header;
let block_header = block.block.header;
let txs = block.block.body;

// create block body indices
Expand Down
20 changes: 10 additions & 10 deletions crates/katana/storage/provider/tests/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ where
executions.clone(),
)?;

assert_eq!(provider.latest_number().unwrap(), block.block.header.header.number);
assert_eq!(provider.latest_hash().unwrap(), block.block.header.hash);
assert_eq!(provider.latest_number().unwrap(), block.block.header.number);
assert_eq!(provider.latest_hash().unwrap(), block.block.hash);
}

let actual_transactions_in_range = provider.transaction_in_range(0..total_txs).unwrap();
Expand All @@ -117,10 +117,10 @@ where
);

for (block, receipts, executions) in blocks {
let block_id = BlockHashOrNumber::Hash(block.block.header.hash);
let block_id = BlockHashOrNumber::Hash(block.block.hash);

let expected_block_num = block.block.header.header.number;
let expected_block_hash = block.block.header.hash;
let expected_block_num = block.block.header.number;
let expected_block_hash = block.block.hash;
let expected_block = block.block.unseal();

let expected_block_env = BlockEnv {
Expand Down Expand Up @@ -210,8 +210,8 @@ where
vec![],
)?;

assert_eq!(provider.latest_number().unwrap(), block.block.header.header.number);
assert_eq!(provider.latest_hash().unwrap(), block.block.header.hash);
assert_eq!(provider.latest_number().unwrap(), block.block.header.number);
assert_eq!(provider.latest_hash().unwrap(), block.block.hash);
}

let actual_blocks_in_range = provider.blocks_in_range(0..=count)?;
Expand All @@ -223,10 +223,10 @@ where
);

for block in blocks {
let block_id = BlockHashOrNumber::Hash(block.block.header.hash);
let block_id = BlockHashOrNumber::Hash(block.block.hash);

let expected_block_num = block.block.header.header.number;
let expected_block_hash = block.block.header.hash;
let expected_block_num = block.block.header.number;
let expected_block_hash = block.block.hash;
let expected_block = block.block.unseal();

let expected_block_env = BlockEnv {
Expand Down
8 changes: 3 additions & 5 deletions crates/katana/storage/provider/tests/fixtures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::sync::Arc;
use katana_db::mdbx;
use katana_primitives::address;
use katana_primitives::block::{
BlockHashOrNumber, FinalityStatus, Header, SealedBlock, SealedBlockWithStatus, SealedHeader,
BlockHashOrNumber, FinalityStatus, Header, SealedBlock, SealedBlockWithStatus,
};
use katana_primitives::class::{CompiledClass, FlattenedSierraClass, SierraClass};
use katana_primitives::contract::ContractAddress;
Expand Down Expand Up @@ -188,10 +188,8 @@ where
SealedBlockWithStatus {
status: FinalityStatus::AcceptedOnL2,
block: SealedBlock {
header: SealedHeader {
hash: i.into(),
header: Header { number: i, ..Default::default() },
},
hash: i.into(),
header: Header { number: i, ..Default::default() },
body: Default::default(),
},
},
Expand Down
4 changes: 2 additions & 2 deletions crates/katana/storage/provider/tests/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub fn generate_dummy_blocks_and_receipts(
let header = Header { parent_hash, number: i, ..Default::default() };
let block = Block { header, body }.seal_with_hash(Felt::from(rand::random::<u128>()));

parent_hash = block.header.hash;
parent_hash = block.hash;

blocks.push((
SealedBlockWithStatus { block, status: FinalityStatus::AcceptedOnL2 },
Expand All @@ -68,7 +68,7 @@ pub fn generate_dummy_blocks_empty(count: u64) -> Vec<SealedBlockWithStatus> {

let block = Block { header, body }.seal_with_hash(Felt::from(rand::random::<u128>()));

parent_hash = block.header.hash;
parent_hash = block.hash;

blocks.push(SealedBlockWithStatus { block, status: FinalityStatus::AcceptedOnL2 });
}
Expand Down
8 changes: 4 additions & 4 deletions crates/saya/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ impl Saya {
let mut block = self.config.block_range.0.max(1); // Genesis block is not proven. We advance to block 1

let block_before_the_first = self.provider.fetch_block(block - 1).await;
let mut previous_block_state_root = block_before_the_first?.header.header.state_root;
let mut previous_block_state_root = block_before_the_first?.header.state_root;
let mut mock_state_hash = Felt::from(0u64);

loop {
Expand Down Expand Up @@ -293,7 +293,7 @@ impl Saya {
// Shift the state roots to the right by one, as proof of each block is based on the
// previous state root
let mut state_roots = vec![previous_block_state_root];
state_roots.extend(fetched_blocks.iter().map(|block| block.header.header.state_root));
state_roots.extend(fetched_blocks.iter().map(|block| block.header.state_root));
let previous_block_state_root = state_roots.pop().unwrap();

let mut state_updates_and_exec_info = vec![];
Expand Down Expand Up @@ -327,7 +327,7 @@ impl Saya {
.zip(state_roots)
.zip(state_updates_and_exec_info)
.map(|((block, prev_state_root), (state_updates, exec_infos))| FetchedBlockInfo {
block_number: block.header.header.number,
block_number: block.header.number,
block,
prev_state_root,
state_updates,
Expand Down Expand Up @@ -400,7 +400,7 @@ impl Saya {
let mut state_diff_prover_input = ProgramInput {
prev_state_root,
block_number,
block_hash: block.block.header.hash,
block_hash: block.block.hash,
config_hash: Felt::from(0u64),
message_to_starknet_segment,
message_to_appchain_segment,
Expand Down
Loading

0 comments on commit c1618a7

Please sign in to comment.