Skip to content

Commit

Permalink
Migrate to types-rs Felt (#231)
Browse files Browse the repository at this point in the history
* wip

most changes done

cleanup hash.rs

fmt

clippy

fmt

remove Lazy where possible

fixes

changes after the rebase

fix clippy

replace small felts with constants

stark_felt macro

fmt

* fmt

* small fixes

* make felt macro more generic

* fmt

* make TryIntoFelt public

* fmt
  • Loading branch information
maciejka authored Jun 3, 2024
1 parent 450a32d commit c9d67c0
Show file tree
Hide file tree
Showing 28 changed files with 345 additions and 762 deletions.
7 changes: 4 additions & 3 deletions src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ use std::fmt::Display;

use derive_more::Display;
use serde::{Deserialize, Serialize};
use starknet_types_core::hash::{Poseidon, StarkHash as CoreStarkHash};

use crate::core::{
EventCommitment, GlobalRoot, ReceiptCommitment, SequencerContractAddress, SequencerPublicKey,
StateDiffCommitment, TransactionCommitment,
};
use crate::crypto::utils::{verify_message_hash_signature, CryptoError, Signature};
use crate::data_availability::L1DataAvailabilityMode;
use crate::hash::{poseidon_hash_array, StarkHash};
use crate::hash::StarkHash;
use crate::serde_utils::{BytesAsHex, PrefixedBytesAsHex};
use crate::transaction::{Transaction, TransactionHash, TransactionOutput};

Expand Down Expand Up @@ -233,8 +234,8 @@ pub fn verify_block_signature(
state_diff_commitment: &GlobalRoot,
block_hash: &BlockHash,
) -> Result<bool, BlockVerificationError> {
let message_hash = poseidon_hash_array(&[block_hash.0, state_diff_commitment.0]);
verify_message_hash_signature(&message_hash.0, &signature.0, &sequencer_pub_key.0).map_err(
let message_hash = Poseidon::hash_array(&[block_hash.0, state_diff_commitment.0]);
verify_message_hash_signature(&message_hash, &signature.0, &sequencer_pub_key.0).map_err(
|err| BlockVerificationError::BlockSignatureVerificationFailed {
block_hash: *block_hash,
error: err,
Expand Down
20 changes: 10 additions & 10 deletions src/block_hash/block_hash_calculator.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use once_cell::sync::Lazy;
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::Poseidon;

use super::event_commitment::{calculate_events_commitment, EventLeafElement};
use super::receipt_commitment::{calculate_receipt_commitment, ReceiptElement};
Expand All @@ -8,7 +10,6 @@ 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,
Expand All @@ -19,7 +20,7 @@ use crate::transaction_hash::ascii_as_felt;
#[path = "block_hash_calculator_test.rs"]
mod block_hash_calculator_test;

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

Expand All @@ -36,7 +37,7 @@ pub struct BlockHeaderCommitments {
pub events_commitment: EventCommitment,
pub receipts_commitment: ReceiptCommitment,
pub state_diff_commitment: StateDiffCommitment,
pub concatenated_counts: StarkFelt,
pub concatenated_counts: Felt,
}

/// Poseidon (
Expand Down Expand Up @@ -66,7 +67,7 @@ pub fn calculate_block_hash(
.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(&Felt::ZERO)
.chain(&header.parent_hash.0)
.get_poseidon_hash(),
)
Expand All @@ -83,7 +84,7 @@ pub fn calculate_block_commitments(
let transaction_leaf_elements: Vec<TransactionLeafElement> =
transactions_data.iter().map(TransactionLeafElement::from).collect();
let transactions_commitment =
calculate_transactions_commitment::<PoseidonHashCalculator>(&transaction_leaf_elements);
calculate_transactions_commitment::<Poseidon>(&transaction_leaf_elements);

let event_leaf_elements: Vec<EventLeafElement> = transactions_data
.iter()
Expand All @@ -94,12 +95,11 @@ pub fn calculate_block_commitments(
})
})
.collect();
let events_commitment =
calculate_events_commitment::<PoseidonHashCalculator>(&event_leaf_elements);
let events_commitment = calculate_events_commitment::<Poseidon>(&event_leaf_elements);

let receipt_elements: Vec<ReceiptElement> =
transactions_data.iter().map(ReceiptElement::from).collect();
let receipts_commitment = calculate_receipt_commitment::<PoseidonHashCalculator>(
let receipts_commitment = calculate_receipt_commitment::<Poseidon>(
&receipt_elements,
l1_data_gas_price_per_token,
l1_gas_price_per_token,
Expand Down Expand Up @@ -129,7 +129,7 @@ fn concat_counts(
event_count: usize,
state_diff_length: usize,
l1_data_availability_mode: L1DataAvailabilityMode,
) -> StarkFelt {
) -> Felt {
let l1_data_availability_byte: u8 = match l1_data_availability_mode {
L1DataAvailabilityMode::Calldata => 0,
L1DataAvailabilityMode::Blob => 0b10000000,
Expand All @@ -142,7 +142,7 @@ fn concat_counts(
&[0_u8; 7], // zero padding
]
.concat();
StarkFelt::new_unchecked(concat_bytes.try_into().expect("Expect 32 bytes"))
Felt::from_bytes_be_slice(concat_bytes.as_slice())
}

fn to_64_bits(num: usize) -> [u8; 8] {
Expand Down
21 changes: 10 additions & 11 deletions src/block_hash/block_hash_calculator_test.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use starknet_types_core::felt::Felt;

use super::concat_counts;
use crate::block::{
BlockHash, BlockHeaderWithoutHash, BlockNumber, BlockTimestamp, GasPrice, GasPricePerToken,
Expand All @@ -9,14 +11,15 @@ use crate::block_hash::block_hash_calculator::{
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::felt;
use crate::hash::{FeltConverter, TryIntoFelt};
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)),
state_root: GlobalRoot(Felt::from(2_u8)),
sequencer: SequencerContractAddress(ContractAddress(PatriciaKey::from(3_u8))),
timestamp: BlockTimestamp(4),
l1_da_mode: L1DataAvailabilityMode::Blob,
Expand All @@ -26,12 +29,12 @@ fn test_block_hash_regression() {
price_in_wei: GasPrice(9),
},
starknet_version: StarknetVersion("10".to_owned()),
parent_hash: BlockHash(StarkFelt::from(11_u8)),
parent_hash: BlockHash(Felt::from(11_u8)),
};
let transactions_data = vec![TransactionHashingData {
transaction_signature: Some(TransactionSignature(vec![StarkFelt::TWO, StarkFelt::THREE])),
transaction_signature: Some(TransactionSignature(vec![Felt::TWO, Felt::THREE])),
transaction_output: get_transaction_output(),
transaction_hash: TransactionHash(StarkFelt::ONE),
transaction_hash: TransactionHash(Felt::ONE),
transaction_version: TransactionVersion::THREE,
}];

Expand All @@ -44,18 +47,14 @@ fn test_block_hash_regression() {
block_header.l1_da_mode,
);

let expected_hash =
StarkFelt::try_from("0x061e4998d51a248f1d0288d7e17f6287757b0e5e6c5e1e58ddf740616e312134")
.unwrap();
let expected_hash = felt!("0x061e4998d51a248f1d0288d7e17f6287757b0e5e6c5e1e58ddf740616e312134");

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

#[test]
fn concat_counts_test() {
let concated = concat_counts(4, 3, 2, L1DataAvailabilityMode::Blob);
let expected_felt =
StarkFelt::try_from("0x0000000000000004000000000000000300000000000000028000000000000000")
.unwrap();
let expected_felt = felt!("0x0000000000000004000000000000000300000000000000028000000000000000");
assert_eq!(concated, expected_felt)
}
11 changes: 6 additions & 5 deletions src/block_hash/event_commitment.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::StarkHash;

use crate::core::EventCommitment;
use crate::crypto::patricia_hash::calculate_root;
use crate::crypto::utils::HashChain;
use crate::hash::{HashFunction, StarkFelt};
use crate::transaction::{Event, TransactionHash};

#[cfg(test)]
Expand All @@ -16,7 +18,7 @@ pub struct EventLeafElement {
}

/// Returns the root of a Patricia tree where each leaf is an event hash.
pub fn calculate_events_commitment<H: HashFunction>(
pub fn calculate_events_commitment<H: StarkHash>(
event_leaf_elements: &[EventLeafElement],
) -> EventCommitment {
let event_leaves = event_leaf_elements.iter().map(calculate_event_hash).collect();
Expand All @@ -28,9 +30,8 @@ pub fn calculate_events_commitment<H: HashFunction>(
// num_keys, key0, key1, ...,
// num_contents, content0, content1, ...
// ).
fn calculate_event_hash(event_leaf_element: &EventLeafElement) -> StarkFelt {
let keys =
&event_leaf_element.event.content.keys.iter().map(|k| k.0).collect::<Vec<StarkFelt>>();
fn calculate_event_hash(event_leaf_element: &EventLeafElement) -> Felt {
let keys = &event_leaf_element.event.content.keys.iter().map(|k| k.0).collect::<Vec<Felt>>();
let data = &event_leaf_element.event.content.data.0;
HashChain::new()
.chain(event_leaf_element.event.from_address.0.key())
Expand Down
28 changes: 13 additions & 15 deletions src/block_hash/event_commitment_test.rs
Original file line number Diff line number Diff line change
@@ -1,47 +1,45 @@
use super::{calculate_event_hash, EventLeafElement};
use crate::block_hash::event_commitment::calculate_events_commitment;
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::Poseidon;

use super::{calculate_event_hash, calculate_events_commitment, EventLeafElement};
use crate::core::{ContractAddress, EventCommitment, PatriciaKey};
use crate::hash::{PoseidonHashCalculator, StarkFelt, StarkHash};
use crate::hash::{FeltConverter, TryIntoFelt};
use crate::transaction::{Event, EventContent, EventData, EventKey, TransactionHash};
use crate::{contract_address, patricia_key, stark_felt};
use crate::{contract_address, felt, patricia_key};

#[test]
fn test_events_commitment_regression() {
let event_leaf_elements =
[get_event_leaf_element(0), get_event_leaf_element(1), get_event_leaf_element(2)];

let expected_root =
StarkFelt::try_from("0x069bb140ddbbeb01d81c7201ecfb933031306e45dab9c77ff9f9ba3cd4c2b9c3")
.unwrap();
let expected_root = felt!("0x069bb140ddbbeb01d81c7201ecfb933031306e45dab9c77ff9f9ba3cd4c2b9c3");

assert_eq!(
EventCommitment(expected_root),
calculate_events_commitment::<PoseidonHashCalculator>(&event_leaf_elements),
calculate_events_commitment::<Poseidon>(&event_leaf_elements),
);
}

#[test]
fn test_event_hash_regression() {
let event_leaf_element = get_event_leaf_element(2);

let expected_hash =
StarkFelt::try_from("0x367807f532742a4dcbe2d8a47b974b22dd7496faa75edc64a3a5fdb6709057")
.unwrap();
let expected_hash = felt!("0x367807f532742a4dcbe2d8a47b974b22dd7496faa75edc64a3a5fdb6709057");

assert_eq!(expected_hash, calculate_event_hash(&event_leaf_element));
}

fn get_event_leaf_element(seed: u8) -> EventLeafElement {
EventLeafElement {
event: Event {
from_address: contract_address!(seed + 8),
from_address: contract_address!(format!("{:x}", seed + 8).as_str()),
content: EventContent {
keys: [seed, seed + 1].iter().map(|key| EventKey(stark_felt!(*key))).collect(),
keys: [seed, seed + 1].iter().map(|key| EventKey(Felt::from(*key))).collect(),
data: EventData(
[seed + 2, seed + 3, seed + 4].into_iter().map(StarkFelt::from).collect(),
[seed + 2, seed + 3, seed + 4].into_iter().map(Felt::from).collect(),
),
},
},
transaction_hash: TransactionHash(stark_felt!("0x1234")),
transaction_hash: TransactionHash(felt!("0x1234")),
}
}
17 changes: 10 additions & 7 deletions src/block_hash/receipt_commitment.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::StarkHash;

use super::block_hash_calculator::TransactionHashingData;
use crate::block::{GasPrice, GasPricePerToken};
use crate::core::ReceiptCommitment;
use crate::crypto::patricia_hash::calculate_root;
use crate::crypto::utils::HashChain;
use crate::hash::{starknet_keccak_hash, HashFunction, StarkFelt};
use crate::hash::starknet_keccak_hash;
use crate::transaction::{
ExecutionResources, Fee, MessageToL1, TransactionExecutionStatus, TransactionHash,
TransactionOutputCommon, TransactionVersion,
Expand Down Expand Up @@ -32,7 +35,7 @@ impl From<&TransactionHashingData> for ReceiptElement {
}

/// Returns the root of a Patricia tree where each leaf is a receipt hash.
pub fn calculate_receipt_commitment<H: HashFunction>(
pub fn calculate_receipt_commitment<H: StarkHash>(
receipt_elements: &[ReceiptElement],
l1_data_gas_price_per_token: GasPricePerToken,
l1_gas_price_per_token: GasPricePerToken,
Expand All @@ -55,7 +58,7 @@ fn calculate_receipt_hash(
receipt_element: &ReceiptElement,
l1_data_gas_price_per_token: GasPricePerToken,
l1_gas_price_per_token: GasPricePerToken,
) -> StarkFelt {
) -> Felt {
let l1_gas_price =
get_price_by_version(l1_gas_price_per_token, &receipt_element.transaction_version);
let l1_data_gas_price =
Expand All @@ -80,7 +83,7 @@ fn calculate_receipt_hash(
// from_address_0, to_address_0, payload_length_0, payload_0,
// from_address_1, to_address_1, payload_length_1, payload_1, ...
// ).
fn calculate_messages_sent_hash(messages_sent: &Vec<MessageToL1>) -> StarkFelt {
fn calculate_messages_sent_hash(messages_sent: &Vec<MessageToL1>) -> Felt {
let mut messages_hash_chain = HashChain::new().chain(&messages_sent.len().into());
for message_sent in messages_sent {
messages_hash_chain = messages_hash_chain
Expand All @@ -92,9 +95,9 @@ fn calculate_messages_sent_hash(messages_sent: &Vec<MessageToL1>) -> StarkFelt {
}

// Returns starknet-keccak of the revert reason ASCII string, or 0 if the transaction succeeded.
fn get_revert_reason_hash(execution_status: &TransactionExecutionStatus) -> StarkFelt {
fn get_revert_reason_hash(execution_status: &TransactionExecutionStatus) -> Felt {
match execution_status {
TransactionExecutionStatus::Succeeded => StarkFelt::ZERO,
TransactionExecutionStatus::Succeeded => Felt::ZERO,
TransactionExecutionStatus::Reverted(reason) => {
starknet_keccak_hash(reason.revert_reason.as_bytes())
}
Expand All @@ -118,7 +121,7 @@ fn chain_execution_resources(
- (l1_data_gas_price.0) * u128::from(execution_resources.da_l1_data_gas_consumed))
/ l1_gas_price.0;
hash_chain
.chain(&StarkFelt::ZERO) // L2 gas consumed
.chain(&Felt::ZERO) // L2 gas consumed
.chain(&l1_gas_consumed.into())
.chain(&execution_resources.da_l1_data_gas_consumed.into())
}
Expand Down
Loading

0 comments on commit c9d67c0

Please sign in to comment.