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

refactor(katana): include protocol version in chainspec #2543

Merged
merged 10 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ metrics = "0.23.0"
num-traits = { version = "0.2", default-features = false }
once_cell = "1.0"
parking_lot = "0.12.1"
postcard = { version = "1.0.10", features = [ "use-std" ], default-features = false }
pretty_assertions = "1.2.1"
rand = "0.8.5"
rayon = "1.8.0"
Expand Down
3 changes: 1 addition & 2 deletions crates/katana/core/src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use katana_primitives::block::{
use katana_primitives::chain_spec::ChainSpec;
use katana_primitives::env::BlockEnv;
use katana_primitives::transaction::TxHash;
use katana_primitives::version::CURRENT_STARKNET_VERSION;
use katana_primitives::Felt;
use katana_provider::traits::block::{BlockHashProvider, BlockWriter};
use parking_lot::RwLock;
Expand Down Expand Up @@ -66,7 +65,7 @@ impl<EF: ExecutorFactory> Backend<EF> {
let partial_header = PartialHeader {
number: block_number,
parent_hash: prev_hash,
version: CURRENT_STARKNET_VERSION,
version: self.chain_spec.version.clone(),
timestamp: block_env.timestamp,
sequencer_address: block_env.sequencer_address,
gas_prices: GasPrices {
Expand Down
3 changes: 1 addition & 2 deletions crates/katana/core/src/service/block_producer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use katana_primitives::block::{BlockHashOrNumber, ExecutableBlock, PartialHeader
use katana_primitives::receipt::Receipt;
use katana_primitives::trace::TxExecInfo;
use katana_primitives::transaction::{ExecutableTxWithHash, TxHash, TxWithHash};
use katana_primitives::version::CURRENT_STARKNET_VERSION;
use katana_provider::error::ProviderError;
use katana_provider::traits::block::{BlockHashProvider, BlockNumberProvider};
use katana_provider::traits::env::BlockEnvProvider;
Expand Down Expand Up @@ -581,7 +580,7 @@ impl<EF: ExecutorFactory> InstantBlockProducer<EF> {
timestamp: block_env.timestamp,
gas_prices: block_env.l1_gas_prices.clone(),
sequencer_address: block_env.sequencer_address,
version: CURRENT_STARKNET_VERSION,
version: backend.chain_spec.version.clone(),
},
};

Expand Down
8 changes: 4 additions & 4 deletions crates/katana/executor/tests/fixtures/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use katana_primitives::transaction::{
ExecutableTxWithHash, InvokeTx, InvokeTxV1,
};
use katana_primitives::utils::class::{parse_compiled_class, parse_sierra_class};
use katana_primitives::version::Version;
use katana_primitives::version::CURRENT_STARKNET_VERSION;
use katana_primitives::{address, Felt};
use katana_provider::providers::in_memory::InMemoryProvider;
use katana_provider::traits::block::BlockWriter;
Expand Down Expand Up @@ -88,7 +88,7 @@ pub fn state_provider(chain: &ChainSpec) -> Box<dyn StateProvider> {
/// [state_provider].
#[rstest::fixture]
pub fn valid_blocks() -> [ExecutableBlock; 3] {
let version = Version::new(0, 13, 0);
let version = CURRENT_STARKNET_VERSION;
let chain_id = ChainId::parse("KATANA").unwrap();
let sequencer_address = ContractAddress(1u64.into());

Expand All @@ -102,7 +102,7 @@ pub fn valid_blocks() -> [ExecutableBlock; 3] {
[
ExecutableBlock {
header: PartialHeader {
version,
version: version.clone(),
number: 1,
timestamp: 100,
sequencer_address,
Expand Down Expand Up @@ -150,7 +150,7 @@ pub fn valid_blocks() -> [ExecutableBlock; 3] {
},
ExecutableBlock {
header: PartialHeader {
version,
version: version.clone(),
number: 2,
timestamp: 200,
sequencer_address,
Expand Down
3 changes: 3 additions & 0 deletions crates/katana/node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use katana_pool::validation::stateful::TxValidator;
use katana_pool::TxPool;
use katana_primitives::block::FinalityStatus;
use katana_primitives::env::{CfgEnv, FeeTokenAddressses};
use katana_primitives::version::Version;
use katana_provider::providers::fork::ForkedProvider;
use katana_provider::providers::in_memory::InMemoryProvider;
use katana_rpc::dev::DevApi;
Expand Down Expand Up @@ -204,6 +205,8 @@ pub async fn build(mut config: Config) -> Result<Node> {
panic!("block to be forked is a pending block")
};

config.chain.version = Version::parse(&block.starknet_version)?;

// adjust the genesis to match the forked block
config.chain.genesis.number = block.block_number;
config.chain.genesis.state_root = block.new_root;
Expand Down
1 change: 1 addition & 0 deletions crates/katana/primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ num-bigint = "0.4.6"

[dev-dependencies]
assert_matches.workspace = true
postcard.workspace = true
rstest.workspace = true
similar-asserts.workspace = true

Expand Down
9 changes: 6 additions & 3 deletions crates/katana/primitives/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::genesis::constant::{
use crate::genesis::Genesis;
use crate::state::StateUpdatesWithDeclaredClasses;
use crate::utils::split_u256;
use crate::version::CURRENT_STARKNET_VERSION;
use crate::version::{Version, CURRENT_STARKNET_VERSION};

/// A chain specification.
// TODO: include l1 core contract
Expand All @@ -33,6 +33,8 @@ pub struct ChainSpec {
pub genesis: Genesis,
/// The chain fee token contract.
pub fee_contracts: FeeContracts,
/// The protocol version.
pub version: Version,
}

/// Tokens that can be used for transaction fee payments in the chain. As
Expand All @@ -49,7 +51,7 @@ pub struct FeeContracts {
impl ChainSpec {
pub fn block(&self) -> Block {
let header = Header {
version: CURRENT_STARKNET_VERSION,
version: self.version.clone(),
number: self.genesis.number,
timestamp: self.genesis.timestamp,
state_root: self.genesis.state_root,
Expand Down Expand Up @@ -155,7 +157,7 @@ lazy_static! {
let id = ChainId::parse("KATANA").unwrap();
let genesis = Genesis::default();
let fee_contracts = FeeContracts { eth: DEFAULT_ETH_FEE_TOKEN_ADDRESS, strk: DEFAULT_STRK_FEE_TOKEN_ADDRESS };
ChainSpec { id, genesis, fee_contracts }
ChainSpec { id, genesis, fee_contracts, version: CURRENT_STARKNET_VERSION }
};
}

Expand Down Expand Up @@ -314,6 +316,7 @@ mod tests {
];
let chain_spec = ChainSpec {
id: ChainId::SEPOLIA,
version: CURRENT_STARKNET_VERSION,
genesis: Genesis {
classes,
allocations: BTreeMap::from(allocations.clone()),
Expand Down
151 changes: 105 additions & 46 deletions crates/katana/primitives/src/version.rs
Original file line number Diff line number Diff line change
@@ -1,87 +1,146 @@
use anyhow::anyhow;

/// The currently supported version of the Starknet protocol.
pub static CURRENT_STARKNET_VERSION: Version = Version::new(0, 12, 2); // version 0.12.2
pub const CURRENT_STARKNET_VERSION: Version = Version::new([0, 13, 1, 1]); // version 0.13.1.1

/// Starknet protocol version.
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Version {
major: u64,
minor: u64,
patch: u64,
segments: [u8; 4],
}
kariy marked this conversation as resolved.
Show resolved Hide resolved

kariy marked this conversation as resolved.
Show resolved Hide resolved
impl Version {
pub const fn new(major: u64, minor: u64, patch: u64) -> Self {
Self { major, minor, patch }
pub const fn new(segments: [u8; 4]) -> Self {
Self { segments }
}

pub fn parse(version: &str) -> anyhow::Result<Self> {
let mut parts = version.split('.');
let segments: Result<Vec<u8>, _> = version.split('.').map(|s| s.parse::<u8>()).collect();

if parts.clone().count() > 3 {
return Err(anyhow!("invalid version format"));
match segments {
Ok(segments) if segments.len() == 4 => {
let mut arr = [0u8; 4];
arr.copy_from_slice(&segments);
Ok(Self { segments: arr })
}
_ => Err(anyhow::anyhow!("invalid version format")),
}
kariy marked this conversation as resolved.
Show resolved Hide resolved
}
}
kariy marked this conversation as resolved.
Show resolved Hide resolved

let major = parts.next().map(|s| s.parse::<u64>()).transpose()?.unwrap_or_default();
let minor = parts.next().map(|s| s.parse::<u64>()).transpose()?.unwrap_or_default();
let patch = parts.next().map(|s| s.parse::<u64>()).transpose()?.unwrap_or_default();

Ok(Self::new(major, minor, patch))
impl std::default::Default for Version {
fn default() -> Self {
Version::new([0, 1, 0, 0])
}
}

/// Formats the version as a string, where each segment is separated by a dot.
/// The last segment (fourth part) will not be printed if it's zero.
///
/// For example:
/// - Version::new([1, 2, 3, 4]) will be displayed as "1.2.3.4"
/// - Version::new([1, 2, 3, 0]) will be displayed as "1.2.3"
/// - Version::new([0, 2, 3, 0]) will be displayed as "0.2.3"
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{major}.{minor}.{patch}",
major = self.major,
minor = self.minor,
patch = self.patch
)
for (idx, segment) in self.segments.iter().enumerate() {
// If it's the last segment, don't print it if it's zero.
if idx == self.segments.len() - 1 {
if *segment != 0 {
write!(f, ".{segment}")?;
}
} else if idx == 0 {
write!(f, "{segment}")?;
} else {
write!(f, ".{segment}")?;
}
}

Ok(())
}
}

kariy marked this conversation as resolved.
Show resolved Hide resolved
#[cfg(feature = "serde")]
mod serde {
use super::*;

impl ::serde::Serialize for Version {
fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if serializer.is_human_readable() {
serializer.serialize_str(&self.to_string())
} else {
self.segments.serialize(serializer)
}
}
}

impl<'de> ::serde::Deserialize<'de> for Version {
fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
if deserializer.is_human_readable() {
let s = String::deserialize(deserializer)?;
Version::parse(&s).map_err(::serde::de::Error::custom)
} else {
Ok(Version::new(<[u8; 4]>::deserialize(deserializer)?))
}
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn parse_semver_valid() {
let version = "1.9.0";
let parsed = super::Version::parse(version).unwrap();
assert_eq!(parsed.major, 1);
assert_eq!(parsed.minor, 9);
assert_eq!(parsed.patch, 0);
fn parse_version_valid() {
let version = "1.9.0.0";
let parsed = Version::parse(version).unwrap();
assert_eq!(parsed.segments, [1, 9, 0, 0]);
assert_eq!(String::from("1.9.0"), parsed.to_string());
}

#[test]
fn parse_semver_missing_parts() {
let version = "1.9";
let parsed = super::Version::parse(version).unwrap();
assert_eq!(parsed.major, 1);
assert_eq!(parsed.minor, 9);
assert_eq!(parsed.patch, 0);
assert_eq!(String::from("1.9.0"), parsed.to_string());
fn parse_version_missing_parts() {
let version = "1.9.0";
assert!(Version::parse(version).is_err());
}

#[test]
fn parse_semver_invalid_digit_should_fail() {
let version = "0.fv.1";
assert!(super::Version::parse(version).is_err());
fn parse_version_invalid_digit_should_fail() {
let version = "0.fv.1.0";
assert!(Version::parse(version).is_err());
}

#[test]
fn parse_semver_missing_digit_should_fail() {
let version = "1..";
assert!(super::Version::parse(version).is_err());
fn parse_version_missing_digit_should_fail() {
let version = "1...";
assert!(Version::parse(version).is_err());
}

#[test]
fn parse_semver_too_many_parts_should_fail() {
fn parse_version_many_parts_should_succeed() {
let version = "1.2.3.4";
assert!(super::Version::parse(version).is_err());
let parsed = Version::parse(version).unwrap();
assert_eq!(parsed.segments, [1, 2, 3, 4]);
assert_eq!(String::from("1.2.3.4"), parsed.to_string());
}

#[cfg(feature = "serde")]
mod serde {
use super::*;

#[test]
fn rt_human_readable() {
let version = Version::new([1, 2, 3, 4]);
let serialized = serde_json::to_string(&version).unwrap();
assert_eq!(serialized, "\"1.2.3.4\"");
let deserialized: Version = serde_json::from_str(&serialized).unwrap();
assert_eq!(version, deserialized);
}

#[test]
fn rt_non_human_readable() {
let version = Version::new([1, 2, 3, 4]);
let serialized = postcard::to_stdvec(&version).unwrap();
let deserialized: Version = postcard::from_bytes(&serialized).unwrap();
assert_eq!(version, deserialized);
}
}
}
7 changes: 3 additions & 4 deletions crates/katana/rpc/rpc/src/starknet/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use jsonrpsee::core::{async_trait, Error, RpcResult};
use katana_executor::{EntryPointCall, ExecutionResult, ExecutorFactory};
use katana_primitives::block::{BlockHashOrNumber, BlockIdOrTag, FinalityStatus, PartialHeader};
use katana_primitives::transaction::{ExecutableTx, ExecutableTxWithHash, TxHash};
use katana_primitives::version::CURRENT_STARKNET_VERSION;
use katana_primitives::Felt;
use katana_provider::traits::block::{BlockHashProvider, BlockIdReader, BlockNumberProvider};
use katana_provider::traits::transaction::TransactionProvider;
Expand Down Expand Up @@ -87,7 +86,7 @@ impl<EF: ExecutorFactory> StarknetApiServer for StarknetApi<EF> {
gas_prices,
parent_hash: latest_hash,
timestamp: block_env.timestamp,
version: CURRENT_STARKNET_VERSION,
version: this.inner.backend.chain_spec.version.clone(),
sequencer_address: block_env.sequencer_address,
};

Expand Down Expand Up @@ -174,9 +173,9 @@ impl<EF: ExecutorFactory> StarknetApiServer for StarknetApi<EF> {
number: block_env.number,
gas_prices,
parent_hash: latest_hash,
version: CURRENT_STARKNET_VERSION,
timestamp: block_env.timestamp,
sequencer_address: block_env.sequencer_address,
version: this.inner.backend.chain_spec.version.clone(),
};

// TODO(kariy): create a method that can perform this filtering for us instead
Expand Down Expand Up @@ -231,7 +230,7 @@ impl<EF: ExecutorFactory> StarknetApiServer for StarknetApi<EF> {
number: block_env.number,
gas_prices,
parent_hash: latest_hash,
version: CURRENT_STARKNET_VERSION,
version: this.inner.backend.chain_spec.version.clone(),
timestamp: block_env.timestamp,
sequencer_address: block_env.sequencer_address,
};
Expand Down
6 changes: 1 addition & 5 deletions crates/katana/storage/db/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,7 @@ thiserror.workspace = true
tracing.workspace = true

# codecs
[dependencies.postcard]
default-features = false
features = [ "use-std" ]
optional = true
version = "1.0.8"
postcard = { workspace = true, optional = true }

[dependencies.libmdbx]
git = "https://github.com/paradigmxyz/reth.git"
Expand Down
Loading
Loading