Skip to content

Commit

Permalink
refactor(starknet_api): represent starknet version as vec of ints (#838)
Browse files Browse the repository at this point in the history
  • Loading branch information
yoavGrs committed Sep 18, 2024
1 parent 208b583 commit d5e975f
Show file tree
Hide file tree
Showing 15 changed files with 101 additions and 39 deletions.
6 changes: 3 additions & 3 deletions crates/papyrus_execution/src/execution_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -850,9 +850,9 @@ fn blockifier_error_mapping() {
// Test that we retrieve the correct versioned constants.
#[test]
fn test_get_versioned_constants() {
let starknet_version_13_0 = StarknetVersion("0.13.0".to_string());
let starknet_version_13_1 = StarknetVersion("0.13.1".to_string());
let starknet_version_13_2 = StarknetVersion("0.13.2".to_string());
let starknet_version_13_0 = StarknetVersion::try_from("0.13.0".to_string()).unwrap();
let starknet_version_13_1 = StarknetVersion::try_from("0.13.1".to_string()).unwrap();
let starknet_version_13_2 = StarknetVersion::try_from("0.13.2".to_string()).unwrap();
let versioned_constants = get_versioned_constants(Some(&starknet_version_13_0)).unwrap();
assert_eq!(versioned_constants.invoke_tx_max_n_steps, 3_000_000);
let versioned_constants = get_versioned_constants(Some(&starknet_version_13_1)).unwrap();
Expand Down
12 changes: 10 additions & 2 deletions crates/papyrus_protobuf/src/converters/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,15 @@ impl TryFrom<protobuf::SignedBlockHeader> for SignedBlockHeader {

let l1_da_mode = enum_int_to_l1_data_availability_mode(value.l1_data_availability_mode)?;

let starknet_version = StarknetVersion(value.protocol_version);
let starknet_version = match StarknetVersion::try_from(value.protocol_version.to_owned()) {
Ok(version) => version,
Err(_) => {
return Err(ProtobufConversionError::OutOfRangeValue {
type_description: "starknet version",
value_as_str: value.protocol_version,
});
}
};

let l1_gas_price = GasPricePerToken {
price_in_fri: GasPrice(
Expand Down Expand Up @@ -259,7 +267,7 @@ impl From<(BlockHeader, Vec<BlockSignature>)> for protobuf::SignedBlockHeader {
receipts: header
.receipt_commitment
.map(|receipt_commitment| receipt_commitment.0.into()),
protocol_version: header.starknet_version.0,
protocol_version: header.starknet_version.to_string(),
gas_price_wei: Some(header.l1_gas_price.price_in_wei.0.into()),
gas_price_fri: Some(header.l1_gas_price.price_in_fri.0.into()),
data_gas_price_wei: Some(header.l1_data_gas_price.price_in_wei.0.into()),
Expand Down
2 changes: 1 addition & 1 deletion crates/papyrus_rpc/src/v0_6/api/api_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1472,7 +1472,7 @@ async fn read_pending_data<Mode: TransactionKind>(
strk_l1_gas_price: latest_header.l1_gas_price.price_in_fri,
timestamp: latest_header.timestamp,
sequencer_address: latest_header.sequencer,
starknet_version: latest_header.starknet_version.0,
starknet_version: latest_header.starknet_version.to_string(),
..Default::default()
}),
state_update: ClientPendingStateUpdate {
Expand Down
12 changes: 6 additions & 6 deletions crates/papyrus_rpc/src/v0_6/api/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ async fn get_block_w_full_transactions() {
let block_hash = BlockHash(random::<u64>().into());
let sequencer_address = SequencerContractAddress(random::<u64>().into());
let timestamp = BlockTimestamp(random::<u64>());
let starknet_version = StarknetVersion("test".to_owned());
let starknet_version = StarknetVersion(vec![123]);
block.header.block_hash = block_hash;
block.header.sequencer = sequencer_address;
block.header.timestamp = timestamp;
Expand Down Expand Up @@ -595,7 +595,7 @@ async fn get_block_w_full_transactions() {
price_in_wei: pending_l1_gas_price.price_in_wei,
price_in_fri: pending_l1_gas_price.price_in_fri,
},
starknet_version: starknet_version.0.clone(),
starknet_version: starknet_version.to_string(),
}),
status: None,
transactions: Transactions::Full(rpc_transactions),
Expand All @@ -608,7 +608,7 @@ async fn get_block_w_full_transactions() {
*pending_block.timestamp_mutable() = pending_timestamp;
*pending_block.sequencer_address_mutable() = pending_sequencer_address;
pending_block.set_l1_gas_price(&pending_l1_gas_price);
*pending_block.starknet_version_mutable() = starknet_version.0;
*pending_block.starknet_version_mutable() = starknet_version.to_string();
}
// Using call_api_then_assert_and_validate_schema_for_result in order to validate the schema for
// pending block.
Expand Down Expand Up @@ -651,7 +651,7 @@ async fn get_block_w_transaction_hashes() {
let block_hash = BlockHash(random::<u64>().into());
let sequencer_address = SequencerContractAddress(random::<u64>().into());
let timestamp = BlockTimestamp(random::<u64>());
let starknet_version = StarknetVersion("test".to_owned());
let starknet_version = StarknetVersion(vec![123]);
block.header.block_hash = block_hash;
block.header.sequencer = sequencer_address;
block.header.timestamp = timestamp;
Expand Down Expand Up @@ -765,7 +765,7 @@ async fn get_block_w_transaction_hashes() {
price_in_wei: pending_l1_gas_price.price_in_wei,
price_in_fri: pending_l1_gas_price.price_in_fri,
},
starknet_version: starknet_version.0.clone(),
starknet_version: starknet_version.to_string(),
}),
status: None,
transactions: Transactions::Hashes(
Expand All @@ -783,7 +783,7 @@ async fn get_block_w_transaction_hashes() {
*pending_block.timestamp_mutable() = pending_timestamp;
*pending_block.sequencer_address_mutable() = pending_sequencer_address;
pending_block.set_l1_gas_price(&pending_l1_gas_price);
*pending_block.starknet_version_mutable() = starknet_version.0;
*pending_block.starknet_version_mutable() = starknet_version.to_string();
}
// Using call_api_then_assert_and_validate_schema_for_result in order to validate the schema for
// pending block.
Expand Down
2 changes: 1 addition & 1 deletion crates/papyrus_rpc/src/v0_6/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ impl From<starknet_api::block::BlockHeader> for BlockHeader {
price_in_wei: header.l1_gas_price.price_in_wei,
price_in_fri: header.l1_gas_price.price_in_fri,
},
starknet_version: header.starknet_version.0,
starknet_version: header.starknet_version.to_string(),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/papyrus_rpc/src/v0_7/api/api_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1492,7 +1492,7 @@ async fn read_pending_data<Mode: TransactionKind>(
strk_l1_gas_price: latest_header.l1_gas_price.price_in_fri,
timestamp: latest_header.timestamp,
sequencer_address: latest_header.sequencer,
starknet_version: latest_header.starknet_version.0,
starknet_version: latest_header.starknet_version.to_string(),
..Default::default()
}),
state_update: ClientPendingStateUpdate {
Expand Down
18 changes: 9 additions & 9 deletions crates/papyrus_rpc/src/v0_7/api/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -485,7 +485,7 @@ async fn get_block_w_full_transactions() {
let block_hash = BlockHash(random::<u64>().into());
let sequencer_address = SequencerContractAddress(random::<u64>().into());
let timestamp = BlockTimestamp(random::<u64>());
let starknet_version = StarknetVersion("test".to_owned());
let starknet_version = StarknetVersion(vec![123]);
block.header.block_hash = block_hash;
block.header.sequencer = sequencer_address;
block.header.timestamp = timestamp;
Expand Down Expand Up @@ -605,7 +605,7 @@ async fn get_block_w_full_transactions() {
},
l1_data_gas_price: ResourcePrice::default(),
l1_da_mode: L1DataAvailabilityMode::Calldata,
starknet_version: starknet_version.0.clone(),
starknet_version: starknet_version.to_string(),
}),
status: None,
transactions: Transactions::Full(rpc_transactions),
Expand All @@ -618,7 +618,7 @@ async fn get_block_w_full_transactions() {
*pending_block.timestamp_mutable() = pending_timestamp;
*pending_block.sequencer_address_mutable() = pending_sequencer_address;
pending_block.set_l1_gas_price(&pending_l1_gas_price);
*pending_block.starknet_version_mutable() = starknet_version.0;
*pending_block.starknet_version_mutable() = starknet_version.to_string();
}
// Using call_api_then_assert_and_validate_schema_for_result in order to validate the schema for
// pending block.
Expand Down Expand Up @@ -662,7 +662,7 @@ async fn get_block_w_full_transactions_and_receipts() {
let block_hash = BlockHash(random::<u64>().into());
let sequencer_address = SequencerContractAddress(random::<u64>().into());
let timestamp = BlockTimestamp(random::<u64>());
let starknet_version = StarknetVersion("test".to_owned());
let starknet_version = StarknetVersion(vec![123]);
let block_number = block.header.block_number;
block.header.block_hash = block_hash;
block.header.sequencer = sequencer_address;
Expand Down Expand Up @@ -788,7 +788,7 @@ async fn get_block_w_full_transactions_and_receipts() {
},
l1_data_gas_price: ResourcePrice::default(),
l1_da_mode: L1DataAvailabilityMode::Calldata,
starknet_version: starknet_version.0.clone(),
starknet_version: starknet_version.to_string(),
}),
status: None,
transactions: Transactions::FullWithReceipts(
Expand All @@ -811,7 +811,7 @@ async fn get_block_w_full_transactions_and_receipts() {
*pending_block.timestamp_mutable() = pending_timestamp;
*pending_block.sequencer_address_mutable() = pending_sequencer_address;
pending_block.set_l1_gas_price(&pending_l1_gas_price);
*pending_block.starknet_version_mutable() = starknet_version.0;
*pending_block.starknet_version_mutable() = starknet_version.to_string();
}
// Using call_api_then_assert_and_validate_schema_for_result again in order to validate the
// schema for pending block too.
Expand Down Expand Up @@ -855,7 +855,7 @@ async fn get_block_w_transaction_hashes() {
let block_hash = BlockHash(random::<u64>().into());
let sequencer_address = SequencerContractAddress(random::<u64>().into());
let timestamp = BlockTimestamp(random::<u64>());
let starknet_version = StarknetVersion("test".to_owned());
let starknet_version = StarknetVersion(vec![123]);
block.header.block_hash = block_hash;
block.header.sequencer = sequencer_address;
block.header.timestamp = timestamp;
Expand Down Expand Up @@ -971,7 +971,7 @@ async fn get_block_w_transaction_hashes() {
},
l1_data_gas_price: ResourcePrice::default(),
l1_da_mode: L1DataAvailabilityMode::Calldata,
starknet_version: starknet_version.0.clone(),
starknet_version: starknet_version.to_string(),
}),
status: None,
transactions: Transactions::Hashes(
Expand All @@ -989,7 +989,7 @@ async fn get_block_w_transaction_hashes() {
*pending_block.timestamp_mutable() = pending_timestamp;
*pending_block.sequencer_address_mutable() = pending_sequencer_address;
pending_block.set_l1_gas_price(&pending_l1_gas_price);
*pending_block.starknet_version_mutable() = starknet_version.0;
*pending_block.starknet_version_mutable() = starknet_version.to_string();
}
// Using call_api_then_assert_and_validate_schema_for_result in order to validate the schema for
// pending block.
Expand Down
2 changes: 1 addition & 1 deletion crates/papyrus_rpc/src/v0_7/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl From<starknet_api::block::BlockHeader> for BlockHeader {
price_in_fri: header.l1_data_gas_price.price_in_fri,
},
l1_da_mode: header.l1_da_mode,
starknet_version: header.starknet_version.0,
starknet_version: header.starknet_version.to_string(),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/papyrus_storage/src/header_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,8 @@ async fn starknet_version() {
reader.begin_ro_txn().unwrap().get_starknet_version(BlockNumber(1)).unwrap();
assert!(non_existing_block_starknet_version.is_none());

let second_version = StarknetVersion("second_version".to_string());
let yet_another_version = StarknetVersion("yet_another_version".to_string());
let second_version = StarknetVersion(vec![2]);
let yet_another_version = StarknetVersion(vec![3]);

writer
.begin_rw_txn()
Expand Down
2 changes: 1 addition & 1 deletion crates/papyrus_storage/src/serialization/serializers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ auto_storage_serde! {
pub enum StructType {
Struct = 0,
}
pub struct StarknetVersion(pub String);
pub struct StarknetVersion(pub Vec<u8>);
pub struct StateDiffCommitment(pub PoseidonHash);
pub struct Tip(pub u64);
pub struct TransactionCommitment(pub StarkHash);
Expand Down
2 changes: 1 addition & 1 deletion crates/papyrus_test_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ auto_impl_get_test_instance! {
MulMod = 9,
RangeCheck96 = 10,
}
pub struct StarknetVersion(pub String);
pub struct StarknetVersion(pub Vec<u8>);
pub struct Calldata(pub Arc<Vec<Felt>>);
pub struct ClassHash(pub StarkHash);
pub struct CompiledClassHash(pub StarkHash);
Expand Down
41 changes: 37 additions & 4 deletions crates/starknet_api/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod block_test;
use std::fmt::Display;

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

Expand All @@ -22,6 +23,7 @@ use crate::data_availability::L1DataAvailabilityMode;
use crate::hash::StarkHash;
use crate::serde_utils::{BytesAsHex, PrefixedBytesAsHex};
use crate::transaction::{Transaction, TransactionHash, TransactionOutput};
use crate::StarknetApiError;

/// A block.
#[derive(Debug, Default, Clone, Eq, PartialEq, Deserialize, Serialize)]
Expand All @@ -33,18 +35,49 @@ pub struct Block {
}

/// A version of the Starknet protocol used when creating a block.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord)]
pub struct StarknetVersion(pub String);
#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct StarknetVersion(pub Vec<u8>);

impl Default for StarknetVersion {
fn default() -> Self {
Self("0.0.0".to_string())
Self(vec![0, 0, 0])
}
}

impl Display for StarknetVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
write!(f, "{}", self.0.iter().map(|x| x.to_string()).join("."))
}
}

impl TryFrom<String> for StarknetVersion {
type Error = StarknetApiError;

/// Parses a string separated by dots into a StarknetVersion.
fn try_from(starknet_version: String) -> Result<Self, StarknetApiError> {
Ok(Self(starknet_version.split('.').map(|x| x.parse::<u8>()).try_collect()?))
}
}

impl Serialize for StarknetVersion {
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
where
S: serde::Serializer,
{
self.to_string().serialize(serializer)
}
}

impl<'de> Deserialize<'de> for StarknetVersion {
fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error>
where
D: serde::Deserializer<'de>,
{
let version = String::deserialize(deserializer)?;
StarknetVersion::try_from(version).map_err(serde::de::Error::custom)
}
}

Expand Down
8 changes: 5 additions & 3 deletions crates/starknet_api/src/block_hash/block_hash_calculator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ pub enum BlockHashVersion {
impl From<BlockHashVersion> for StarknetVersion {
fn from(value: BlockHashVersion) -> Self {
match value {
BlockHashVersion::VO_13_2 => Self("0.13.2".to_owned()),
BlockHashVersion::VO_13_3 => Self("0.13.3".to_owned()),
BlockHashVersion::VO_13_2 => Self(vec![0, 13, 2]),
BlockHashVersion::VO_13_3 => Self(vec![0, 13, 3]),
}
}
}
Expand Down Expand Up @@ -107,7 +107,9 @@ pub fn calculate_block_hash(
(header.starknet_version >= BlockHashVersion::VO_13_3.into())
.then_some(l2_gas_prices.into_iter())
})
.chain(&ascii_as_felt(&header.starknet_version.0).expect("Expect ASCII version"))
.chain(
&ascii_as_felt(&header.starknet_version.to_string()).expect("Expect ASCII version"),
)
.chain(&Felt::ZERO)
.chain(&header.parent_hash.0)
.get_poseidon_hash(),
Expand Down
21 changes: 20 additions & 1 deletion crates/starknet_api/src/block_test.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use super::verify_block_signature;
use serde_json::json;

use super::{verify_block_signature, StarknetVersion};
use crate::block::{BlockHash, BlockNumber, BlockSignature};
use crate::core::{GlobalRoot, SequencerPublicKey};
use crate::crypto::utils::{PublicKey, Signature};
Expand Down Expand Up @@ -45,3 +47,20 @@ fn block_signature_verification() {
.unwrap()
);
}

#[test]
fn test_vec_version() {
assert_eq!(StarknetVersion::default().to_string(), "0.0.0");

let version_123 = StarknetVersion::try_from("1.2.3".to_owned()).unwrap();
assert_eq!(version_123, StarknetVersion(vec![1, 2, 3]));

let serialized_123 = json!(version_123);
assert_eq!(serialized_123, "1.2.3".to_owned());
assert_eq!(serde_json::from_value::<StarknetVersion>(serialized_123).unwrap(), version_123);

assert!(StarknetVersion(vec![0, 10, 0]) > StarknetVersion(vec![0, 2, 5]));
assert!(StarknetVersion(vec![0, 13, 1]) > StarknetVersion(vec![0, 12, 2]));
assert!(StarknetVersion(vec![0, 13, 0, 1]) > StarknetVersion(vec![0, 13, 0]));
assert!(StarknetVersion(vec![0, 13, 0]) > StarknetVersion(vec![0, 13]));
}
6 changes: 3 additions & 3 deletions crates/starknet_client/src/reader/objects/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub struct BlockPostV0_13_1 {
pub transaction_receipts: Vec<TransactionReceipt>,
// Default since old blocks don't include this field.
#[serde(default)]
pub starknet_version: String,
pub starknet_version: StarknetVersion,
// Additions to the block structure in V0.13.1.
pub l1_da_mode: L1DataAvailabilityMode,
// Replacing the eth_l1_gas_price & strk_l1_gas_price fields with a single field.
Expand Down Expand Up @@ -213,7 +213,7 @@ impl Block {
}
}

pub fn starknet_version(&self) -> String {
pub fn starknet_version(&self) -> StarknetVersion {
match self {
Block::PostV0_13_1(block) => block.starknet_version.clone(),
}
Expand Down Expand Up @@ -305,7 +305,7 @@ impl Block {
state_diff_length: self.state_diff_length(),
n_transactions,
n_events,
starknet_version: StarknetVersion(self.starknet_version()),
starknet_version: self.starknet_version(),
};

let (transactions, transaction_receipts) = self.get_body();
Expand Down

0 comments on commit d5e975f

Please sign in to comment.