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

Migrate to types-rs Felt #231

Merged
Merged
Show file tree
Hide file tree
Changes from 5 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
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 @@ -217,8 +218,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
7 changes: 4 additions & 3 deletions src/block_hash/block_hash_calculator.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use starknet_types_core::felt::Felt;

use crate::data_availability::L1DataAvailabilityMode;
use crate::hash::StarkFelt;

#[cfg(test)]
#[path = "block_hash_calculator_test.rs"]
Expand All @@ -15,7 +16,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 @@ -28,7 +29,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
7 changes: 3 additions & 4 deletions src/block_hash/block_hash_calculator_test.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use super::concat_counts;
use crate::data_availability::L1DataAvailabilityMode;
use crate::hash::StarkFelt;
use crate::felt;
use crate::hash::{FeltConverter, TryIntoFelt};

#[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
25 changes: 12 additions & 13 deletions src/block_hash/event_commitment_test.rs
Original file line number Diff line number Diff line change
@@ -1,47 +1,46 @@
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::Poseidon;

use super::calculate_event_hash;
use crate::block_hash::event_commitment::{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,8 +1,11 @@
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::StarkHash;

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, TransactionReceipt,
TransactionVersion,
Expand All @@ -13,7 +16,7 @@ use crate::transaction::{
mod receipt_commitment_test;

/// 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>(
transactions_receipt: &[TransactionReceipt],
transaction_version: &TransactionVersion,
l1_data_gas_price_per_token: GasPricePerToken,
Expand Down Expand Up @@ -43,7 +46,7 @@ fn calculate_receipt_hash(
transaction_version: &TransactionVersion,
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, transaction_version);
let l1_data_gas_price = get_price_by_version(l1_data_gas_price_per_token, transaction_version);
let hash_chain = HashChain::new()
Expand All @@ -66,7 +69,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 @@ -78,9 +81,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 @@ -104,7 +107,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
34 changes: 15 additions & 19 deletions src/block_hash/receipt_commitment_test.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
use std::collections::HashMap;

use primitive_types::H160;
use starknet_types_core::felt::Felt;
use starknet_types_core::hash::Poseidon;

use super::calculate_messages_sent_hash;
use crate::block::{BlockHash, BlockNumber, GasPrice, GasPricePerToken};
use crate::block_hash::receipt_commitment::{
calculate_receipt_commitment, calculate_receipt_hash, get_revert_reason_hash,
};
use crate::core::{ContractAddress, EthAddress, ReceiptCommitment};
use crate::hash::{PoseidonHashCalculator, StarkFelt};
use crate::felt;
use crate::hash::{FeltConverter, TryIntoFelt};
use crate::transaction::{
Builtin, ExecutionResources, Fee, InvokeTransactionOutput, L2ToL1Payload, MessageToL1,
RevertedTransactionExecutionStatus, TransactionExecutionStatus, TransactionHash,
Expand Down Expand Up @@ -36,8 +39,8 @@ fn test_receipt_hash_regression() {
execution_resources,
});
let transaction_receipt = TransactionReceipt {
transaction_hash: TransactionHash(StarkFelt::from(1234_u16)),
block_hash: BlockHash(StarkFelt::from(5678_u16)),
transaction_hash: TransactionHash(Felt::from(1234_u16)),
block_hash: BlockHash(Felt::from(5678_u16)),
block_number: BlockNumber(99),
output: invoke_output,
};
Expand All @@ -46,9 +49,7 @@ fn test_receipt_hash_regression() {
let l1_gas_price =
GasPricePerToken { price_in_fri: GasPrice(456), price_in_wei: GasPrice(789) };

let expected_hash =
StarkFelt::try_from("0x06cb27bfc55dee54e6d0fc7a6790e39f0f3c003576d50f7b8e8a1be24c351bcf")
.unwrap();
let expected_hash = felt!("0x06cb27bfc55dee54e6d0fc7a6790e39f0f3c003576d50f7b8e8a1be24c351bcf");
assert_eq!(
calculate_receipt_hash(
&transaction_receipt,
Expand All @@ -59,12 +60,11 @@ fn test_receipt_hash_regression() {
expected_hash
);

let expected_root = ReceiptCommitment(
StarkFelt::try_from("0x03a0af1272fc3b0b83894fd7b6b70d89acb07772bc28efc9091e3cc1c2c72493")
.unwrap(),
);
let expected_root = ReceiptCommitment(felt!(
"0x03a0af1272fc3b0b83894fd7b6b70d89acb07772bc28efc9091e3cc1c2c72493"
));
assert_eq!(
calculate_receipt_commitment::<PoseidonHashCalculator>(
calculate_receipt_commitment::<Poseidon>(
&[transaction_receipt],
&TransactionVersion::THREE,
l1_data_gas_price,
Expand All @@ -78,30 +78,26 @@ fn test_receipt_hash_regression() {
fn test_messages_sent_regression() {
let messages_sent = vec![generate_message_to_l1(0), generate_message_to_l1(1)];
let messages_hash = calculate_messages_sent_hash(&messages_sent);
let expected_hash =
StarkFelt::try_from("0x00c89474a9007dc060aed76caf8b30b927cfea1ebce2d134b943b8d7121004e4")
.unwrap();
let expected_hash = felt!("0x00c89474a9007dc060aed76caf8b30b927cfea1ebce2d134b943b8d7121004e4");
assert_eq!(messages_hash, expected_hash);
}

fn generate_message_to_l1(seed: u64) -> MessageToL1 {
MessageToL1 {
from_address: ContractAddress::from(seed),
to_address: EthAddress(H160::from_low_u64_be(seed + 1)),
payload: L2ToL1Payload(vec![StarkFelt::from(seed + 2), StarkFelt::from(seed + 3)]),
payload: L2ToL1Payload(vec![Felt::from(seed + 2), Felt::from(seed + 3)]),
}
}

#[test]
fn test_revert_reason_hash_regression() {
let execution_succeeded = TransactionExecutionStatus::Succeeded;
assert_eq!(get_revert_reason_hash(&execution_succeeded), StarkFelt::ZERO);
assert_eq!(get_revert_reason_hash(&execution_succeeded), Felt::ZERO);
let execution_reverted =
TransactionExecutionStatus::Reverted(RevertedTransactionExecutionStatus {
revert_reason: "ABC".to_string(),
});
let expected_hash =
StarkFelt::try_from("0x01629b9dda060bb30c7908346f6af189c16773fa148d3366701fbaa35d54f3c8")
.unwrap();
let expected_hash = felt!("0x01629b9dda060bb30c7908346f6af189c16773fa148d3366701fbaa35d54f3c8");
assert_eq!(get_revert_reason_hash(&execution_reverted), expected_hash);
}
11 changes: 6 additions & 5 deletions src/block_hash/state_diff_hash.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
use indexmap::IndexMap;
use once_cell::sync::Lazy;
use starknet_types_core::felt::Felt;

use crate::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce, StateDiffCommitment};
use crate::crypto::utils::HashChain;
use crate::hash::{PoseidonHash, StarkFelt};
use crate::hash::PoseidonHash;
use crate::state::{StorageKey, ThinStateDiff};
use crate::transaction_hash::ascii_as_felt;

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

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

Expand All @@ -26,8 +27,8 @@ pub fn calculate_state_diff_hash(state_diff: &ThinStateDiff) -> StateDiffCommitm
hash_chain = chain_declared_classes(&state_diff.declared_classes, hash_chain);
hash_chain =
chain_deprecated_declared_classes(&state_diff.deprecated_declared_classes, hash_chain);
hash_chain = hash_chain.chain(&StarkFelt::ONE) // placeholder.
.chain(&StarkFelt::ZERO); // placeholder.
hash_chain = hash_chain.chain(&Felt::ONE) // placeholder.
.chain(&Felt::ZERO); // placeholder.
hash_chain = chain_storage_diffs(&state_diff.storage_diffs, hash_chain);
hash_chain = chain_nonces(&state_diff.nonces, hash_chain);
StateDiffCommitment(PoseidonHash(hash_chain.get_poseidon_hash()))
Expand Down Expand Up @@ -75,7 +76,7 @@ fn chain_deprecated_declared_classes(
// contract_address_1, number_of_updates_in_contract_1, key_0, value0, key1, value1, ...,
// ]
fn chain_storage_diffs(
storage_diffs: &IndexMap<ContractAddress, IndexMap<StorageKey, StarkFelt>>,
storage_diffs: &IndexMap<ContractAddress, IndexMap<StorageKey, Felt>>,
hash_chain: HashChain,
) -> HashChain {
let mut n_updated_contracts = 0_u64;
Expand Down
10 changes: 5 additions & 5 deletions src/block_hash/state_diff_hash_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ use crate::block_hash::state_diff_hash::{
};
use crate::core::{ClassHash, CompiledClassHash, Nonce, StateDiffCommitment};
use crate::crypto::utils::HashChain;
use crate::hash::{PoseidonHash, StarkFelt};
use crate::felt;
use crate::hash::{FeltConverter, PoseidonHash, TryIntoFelt};
use crate::state::ThinStateDiff;

#[test]
Expand Down Expand Up @@ -38,10 +39,9 @@ fn test_state_diff_hash_regression() {
},
};

let expected_hash = StateDiffCommitment(PoseidonHash(
StarkFelt::try_from("0x05b8241020c186585f4273cf991d35ad703e808bd9b40242cec584e7f2d86495")
.unwrap(),
));
let expected_hash = StateDiffCommitment(PoseidonHash(felt!(
"0x05b8241020c186585f4273cf991d35ad703e808bd9b40242cec584e7f2d86495"
)));

assert_eq!(expected_hash, calculate_state_diff_hash(&state_diff));
}
Expand Down
Loading