Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: calculate block hash #248

Merged
merged 1 commit into from
May 28, 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
16 changes: 16 additions & 0 deletions src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ use crate::transaction::{Transaction, TransactionHash, TransactionOutput};
/// A block.
#[derive(Debug, Default, Clone, Eq, PartialEq, Deserialize, Serialize)]
pub struct Block {
// TODO: Consider renaming to BlockWithCommitments, for the header use BlockHeaderWithoutHash
// instead of BlockHeader, and add BlockHeaderCommitments and BlockHash fields.
pub header: BlockHeader,
pub body: BlockBody,
}
Expand Down Expand Up @@ -75,6 +77,20 @@ pub struct BlockHeader {
pub starknet_version: StarknetVersion,
}

/// The header of a [Block](`crate::block::Block`) without hashing.
#[derive(Debug, Default, Clone, Eq, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord)]
pub struct BlockHeaderWithoutHash {
pub parent_hash: BlockHash,
pub block_number: BlockNumber,
pub l1_gas_price: GasPricePerToken,
pub l1_data_gas_price: GasPricePerToken,
pub state_root: GlobalRoot,
pub sequencer: SequencerContractAddress,
pub timestamp: BlockTimestamp,
pub l1_da_mode: L1DataAvailabilityMode,
pub starknet_version: StarknetVersion,
}

/// The [transactions](`crate::transaction::Transaction`) and their
/// [outputs](`crate::transaction::TransactionOutput`) in a [block](`crate::block::Block`).
#[derive(Debug, Default, Clone, Eq, PartialEq, Deserialize, Serialize)]
Expand Down
44 changes: 42 additions & 2 deletions src/block_hash/block_hash_calculator.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
use once_cell::sync::Lazy;

use super::event_commitment::{calculate_events_commitment, EventLeafElement};
use super::receipt_commitment::{calculate_receipt_commitment, ReceiptElement};
use super::state_diff_hash::calculate_state_diff_hash;
use super::transaction_commitment::{calculate_transactions_commitment, TransactionLeafElement};
use crate::block::GasPricePerToken;
use crate::block::{BlockHash, BlockHeaderWithoutHash, GasPricePerToken};
use crate::core::{EventCommitment, ReceiptCommitment, StateDiffCommitment, TransactionCommitment};
use crate::crypto::utils::HashChain;
use crate::data_availability::L1DataAvailabilityMode;
use crate::hash::{PoseidonHashCalculator, StarkFelt};
use crate::state::ThinStateDiff;
use crate::transaction::{
TransactionHash, TransactionOutputCommon, TransactionSignature, TransactionVersion,
};
use crate::transaction_hash::ascii_as_felt;

#[cfg(test)]
#[path = "block_hash_calculator_test.rs"]
mod block_hash_calculator_test;

static STARKNET_BLOCK_HASH0: Lazy<StarkFelt> = Lazy::new(|| {
ascii_as_felt("STARKNET_BLOCK_HASH0").expect("ascii_as_felt failed for 'STARKNET_BLOCK_HASH0'")
});

pub struct TransactionHashingData {
pub transaction_signature: Option<TransactionSignature>,
pub transaction_output: TransactionOutputCommon,
Expand All @@ -31,6 +39,39 @@ pub struct BlockHeaderCommitments {
pub concatenated_counts: StarkFelt,
}

/// Poseidon (
/// “STARKNET_BLOCK_HASH0”, block_number, global_state_root, sequencer_address,
/// block_timestamp, concat_counts, state_diff_hash, transaction_commitment,
/// event_commitment, receipt_commitment, gas_price_wei, gas_price_fri,
/// data_gas_price_wei, data_gas_price_fri, starknet_version, 0, parent_block_hash
/// ).
pub fn calculate_block_hash(
header: BlockHeaderWithoutHash,
block_commitments: BlockHeaderCommitments,
) -> BlockHash {
BlockHash(
HashChain::new()
.chain(&STARKNET_BLOCK_HASH0)
.chain(&header.block_number.0.into())
.chain(&header.state_root.0)
.chain(&header.sequencer.0)
.chain(&header.timestamp.0.into())
.chain(&block_commitments.concatenated_counts)
.chain(&block_commitments.state_diff_commitment.0.0)
.chain(&block_commitments.transactions_commitment.0)
.chain(&block_commitments.events_commitment.0)
.chain(&block_commitments.receipts_commitment.0)
.chain(&header.l1_gas_price.price_in_wei.0.into())
.chain(&header.l1_gas_price.price_in_fri.0.into())
.chain(&header.l1_data_gas_price.price_in_wei.0.into())
.chain(&header.l1_data_gas_price.price_in_fri.0.into())
.chain(&ascii_as_felt(&header.starknet_version.0).expect("Expect ASCII version"))
.chain(&StarkFelt::ZERO)
.chain(&header.parent_hash.0)
.get_poseidon_hash(),
)
}

/// Calculates the commitments of the transactions data for the block hash.
pub fn calculate_block_commitments(
transactions_data: &[TransactionHashingData],
Expand Down Expand Up @@ -83,7 +124,6 @@ pub fn calculate_block_commitments(
// transaction_count (64 bits) | event_count (64 bits) | state_diff_length (64 bits)
// | L1 data availability mode: 0 for calldata, 1 for blob (1 bit) | 0 ...
// ].
#[allow(dead_code)]
fn concat_counts(
transaction_count: usize,
event_count: usize,
Expand Down
49 changes: 49 additions & 0 deletions src/block_hash/block_hash_calculator_test.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,55 @@
use super::concat_counts;
use crate::block::{
BlockHash, BlockHeaderWithoutHash, BlockNumber, BlockTimestamp, GasPrice, GasPricePerToken,
StarknetVersion,
};
use crate::block_hash::block_hash_calculator::{
calculate_block_commitments, calculate_block_hash, TransactionHashingData,
};
use crate::block_hash::test_utils::{get_state_diff, get_transaction_output};
use crate::core::{ContractAddress, GlobalRoot, PatriciaKey, SequencerContractAddress};
use crate::data_availability::L1DataAvailabilityMode;
use crate::hash::StarkFelt;
use crate::transaction::{TransactionHash, TransactionSignature, TransactionVersion};

#[test]
fn test_block_hash_regression() {
let block_header = BlockHeaderWithoutHash {
block_number: BlockNumber(1_u64),
state_root: GlobalRoot(StarkFelt::from(2_u8)),
sequencer: SequencerContractAddress(ContractAddress(PatriciaKey::from(3_u8))),
timestamp: BlockTimestamp(4),
l1_da_mode: L1DataAvailabilityMode::Blob,
l1_gas_price: GasPricePerToken { price_in_fri: GasPrice(6), price_in_wei: GasPrice(7) },
l1_data_gas_price: GasPricePerToken {
price_in_fri: GasPrice(10),
price_in_wei: GasPrice(9),
},
starknet_version: StarknetVersion("10".to_owned()),
parent_hash: BlockHash(StarkFelt::from(11_u8)),
};
let transactions_data = vec![TransactionHashingData {
transaction_signature: Some(TransactionSignature(vec![StarkFelt::TWO, StarkFelt::THREE])),
transaction_output: get_transaction_output(),
transaction_hash: TransactionHash(StarkFelt::ONE),
transaction_version: TransactionVersion::THREE,
}];

let state_diff = get_state_diff();
let block_commitments = calculate_block_commitments(
&transactions_data,
&state_diff,
block_header.l1_data_gas_price,
block_header.l1_gas_price,
block_header.l1_da_mode,
);

let expected_hash =
StarkFelt::try_from("0x069c273a5f40b62efb03e0a8f46f6eb68533f578adbfcc57a604e9a63b066f28")
.unwrap();

assert_eq!(BlockHash(expected_hash), calculate_block_hash(block_header, block_commitments),);
}

#[test]
fn concat_counts_test() {
Expand Down
29 changes: 2 additions & 27 deletions src/block_hash/state_diff_hash_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,14 @@ use crate::block_hash::state_diff_hash::{
calculate_state_diff_hash, chain_declared_classes, chain_deployed_contracts,
chain_deprecated_declared_classes, chain_nonces, chain_storage_diffs,
};
use crate::block_hash::test_utils::get_state_diff;
use crate::core::{ClassHash, CompiledClassHash, Nonce, StateDiffCommitment};
use crate::crypto::utils::HashChain;
use crate::hash::{PoseidonHash, StarkFelt};
use crate::state::ThinStateDiff;

#[test]
fn test_state_diff_hash_regression() {
let state_diff = ThinStateDiff {
deployed_contracts: indexmap! {
0u64.into() => ClassHash(1u64.into()),
2u64.into() => ClassHash(3u64.into()),
},
storage_diffs: indexmap! {
4u64.into() => indexmap! {
5u64.into() => 6u64.into(),
7u64.into() => 8u64.into(),
},
9u64.into() => indexmap! {
10u64.into() => 11u64.into(),
},
},
declared_classes: indexmap! {
ClassHash(12u64.into()) => CompiledClassHash(13u64.into()),
ClassHash(14u64.into()) => CompiledClassHash(15u64.into()),
},
deprecated_declared_classes: vec![ClassHash(16u64.into())],
nonces: indexmap! {
17u64.into() => Nonce(18u64.into()),
},
replaced_classes: indexmap! {
19u64.into() => ClassHash(20u64.into()),
},
};
let state_diff = get_state_diff();

let expected_hash = StateDiffCommitment(PoseidonHash(
StarkFelt::try_from("0x05b8241020c186585f4273cf991d35ad703e808bd9b40242cec584e7f2d86495")
Expand Down
33 changes: 32 additions & 1 deletion src/block_hash/test_utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use std::collections::HashMap;

use indexmap::indexmap;
use primitive_types::H160;

use crate::core::{ContractAddress, EthAddress};
use crate::core::{ClassHash, CompiledClassHash, ContractAddress, EthAddress, Nonce};
use crate::hash::StarkFelt;
use crate::state::ThinStateDiff;
use crate::transaction::{
Builtin, ExecutionResources, Fee, L2ToL1Payload, MessageToL1,
RevertedTransactionExecutionStatus, TransactionExecutionStatus, TransactionOutputCommon,
Expand Down Expand Up @@ -37,3 +39,32 @@ pub(crate) fn generate_message_to_l1(seed: u64) -> MessageToL1 {
payload: L2ToL1Payload(vec![StarkFelt::from(seed + 2), StarkFelt::from(seed + 3)]),
}
}

pub(crate) fn get_state_diff() -> ThinStateDiff {
ThinStateDiff {
deployed_contracts: indexmap! {
0u64.into() => ClassHash(1u64.into()),
2u64.into() => ClassHash(3u64.into()),
},
storage_diffs: indexmap! {
4u64.into() => indexmap! {
5u64.into() => 6u64.into(),
7u64.into() => 8u64.into(),
},
9u64.into() => indexmap! {
10u64.into() => 11u64.into(),
},
},
declared_classes: indexmap! {
ClassHash(12u64.into()) => CompiledClassHash(13u64.into()),
ClassHash(14u64.into()) => CompiledClassHash(15u64.into()),
},
deprecated_declared_classes: vec![ClassHash(16u64.into())],
nonces: indexmap! {
17u64.into() => Nonce(18u64.into()),
},
replaced_classes: indexmap! {
19u64.into() => ClassHash(20u64.into()),
},
}
}
Loading