Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
EvolveArt committed Jul 31, 2023
2 parents 1873c48 + 433fea4 commit b06c572
Show file tree
Hide file tree
Showing 8 changed files with 2,228 additions and 158 deletions.
20 changes: 10 additions & 10 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,8 @@ cairo-vm = { git = "https://github.com/keep-starknet-strange/cairo-rs", branch =
"cairo-1-hints",
"parity-scale-codec",
] }
starknet-crypto = { version = "0.6.0", default-features = false }
starknet-core = { version = "0.5.0", default-features = false }
starknet-crypto = { version = "0.5.1", default-features = false }
starknet-core = { version = "0.4.0", default-features = false }
starknet-ff = { version = "0.3.4", default-features = false }

blockifier = { git = "https://github.com/keep-starknet-strange/blockifier", branch = "no_std-support", default-features = false, features = [
Expand All @@ -152,26 +152,26 @@ cairo-lang-utils = { git = "https://github.com/keep-starknet-strange/cairo.git",
anyhow = "1.0.71"
flate2 = "1.0.26"
scale-codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false }
scale-info = { version = "2.9.0", default-features = false }
scale-info = { version = "2.8.0", default-features = false }
lazy_static = { version = "1.4.0", default-features = false }
log = { version = "0.4.19", default-features = false }
hex = { version = "0.4.3", default-features = false }
safe-mix = { version = "1.0", default-features = false }
jsonrpsee = { version = "0.16.2", default-features = false }
clap = { version = "4.3.19", default-features = false }
clap = { version = "4.3.10", default-features = false }
futures = { version = "0.3.28", default-features = false }
futures-timer = { version = "3.0.2", default-features = false }
serde = { version = "1.0.175", default-features = false }
serde_json = { version = "1.0.100", default-features = false }
serde = { version = "1.0.163", default-features = false }
serde_json = { version = "1.0.99", default-features = false }
serde_with = "2.3.3"
bitvec = { version = "1", default-features = false }
thiserror = "1.0.44"
thiserror = "1.0.40"
thiserror-no-std = "2.0.2"
derive_more = { version = "0.99.17", default-features = false }
rstest = "0.17.0"
pretty_assertions = "1.4.0"
pretty_assertions = "1.3.0"
linked-hash-map = { version = "0.5.6", default-features = false }
parking_lot = "0.12.1"
async-trait = "0.1.72"
async-trait = "0.1.68"
indexmap = { git = "https://github.com/bluss/indexmap", rev = "ca5f848e10c31e80aeaad0720d14aa2f6dd6cfb1", default-features = false }
num-traits = "0.2.16"
num-traits = "0.2.8"
44 changes: 6 additions & 38 deletions crates/client/storage/src/overrides/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ pub trait StorageOverride<B: BlockT>: Send + Sync {
fn nonce(&self, block_hash: B::Hash, address: ContractAddressWrapper) -> Option<NonceWrapper>;
/// Returns the events for a provided block hash.
fn events(&self, block_hash: B::Hash) -> Option<Vec<EventWrapper>>;
/// Returns the storage value for a provided key and block hash.
fn chain_id(&self, block_hash: B::Hash) -> Option<Felt252Wrapper>;
/// Returns the state commitments for a provider block hash
fn state_commitments(&self, block_hash: B::Hash) -> Option<StateCommitments>;
/// Returns the state root at a provided contract address for the provided block.
Expand Down Expand Up @@ -214,50 +216,16 @@ where
self.client.runtime_api().events(block_hash).ok()
}

/// Return the state commitments for a provided block hash
///
/// # Arguments
///
/// * `block_hash` - The block hash
///
/// # Returns
/// * `Some(commitments)` - The state commitments for the provided block hash
fn state_commitments(&self, block_hash: <B as BlockT>::Hash) -> Option<StateCommitments> {
self.client.runtime_api().get_state_commitments(block_hash).ok()
}

/// Return the contract root for a provided block hash
///
/// # Arguments
///
/// * `block_hash` - The block hash
///
/// # Returns
/// * `Some(contract_root)` - The contract root for the provided block hash
fn contract_state_root_by_address(
&self,
block_hash: <B as BlockT>::Hash,
address: ContractAddressWrapper,
) -> Option<Felt252Wrapper> {
let api = self.client.runtime_api();
api.contract_state_root_by_address(block_hash, address).ok()?
}

/// Return the contract state trie for a provided block hash
/// Return the chain id for a provided block hash.
///
/// # Arguments
///
/// * `block_hash` - The block hash
///
/// # Returns
/// * `Some(state_trie)` - The contract state trie for the provided block hash
fn contract_state_trie_by_address(
&self,
block_hash: <B as BlockT>::Hash,
address: ContractAddressWrapper,
) -> Option<StateTrie> {
let api = self.client.runtime_api();
api.contract_state_trie_by_address(block_hash, address).ok()?
/// * `Some(chain_id)` - The chain id for the provided block hash
fn chain_id(&self, block_hash: <B as BlockT>::Hash) -> Option<Felt252Wrapper> {
self.client.runtime_api().chain_id(block_hash).ok()
}

/// Return the state commitments for a provided block hash
Expand Down
15 changes: 4 additions & 11 deletions crates/client/storage/src/overrides/schema_v1_override.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use frame_system::EventRecord;
use madara_runtime::{Hash, RuntimeEvent};
use mp_starknet::execution::types::{ClassHashWrapper, ContractAddressWrapper, Felt252Wrapper};
use mp_starknet::storage::{
PALLET_STARKNET, PALLET_SYSTEM, STARKNET_CONTRACT_CLASS, STARKNET_CONTRACT_CLASS_HASH,
PALLET_STARKNET, PALLET_SYSTEM, STARKNET_CHAIN_ID, STARKNET_CONTRACT_CLASS, STARKNET_CONTRACT_CLASS_HASH,
STARKNET_CONTRACT_STATE_ROOT, STARKNET_CONTRACT_STATE_TRIES, STARKNET_NONCE, STARKNET_STATE_COMMITMENTS,
STARKNET_STORAGE, SYSTEM_EVENTS,
};
Expand Down Expand Up @@ -172,16 +172,9 @@ where
}
}

fn contract_state_root_by_address(
&self,
block_hash: <B as BlockT>::Hash,
address: ContractAddressWrapper,
) -> Option<ClassHashWrapper> {
let storage_contract_state_root_prefix = storage_prefix_build(PALLET_STARKNET, STARKNET_CONTRACT_STATE_ROOT);
self.query_storage::<ClassHashWrapper>(
block_hash,
&StorageKey(storage_key_build(storage_contract_state_root_prefix, &self.encode_storage_key(&address))),
)
fn chain_id(&self, block_hash: <B as BlockT>::Hash) -> Option<Felt252Wrapper> {
let chain_id_prefix = storage_prefix_build(PALLET_STARKNET, STARKNET_CHAIN_ID);
self.query_storage::<Felt252Wrapper>(block_hash, &StorageKey(chain_id_prefix))
}

fn contract_state_root_by_address(
Expand Down
2 changes: 1 addition & 1 deletion crates/node/chain-specs/testnet-pragma-raw.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,4 @@
"childrenDefault": {}
}
}
}
}
61 changes: 25 additions & 36 deletions crates/pallets/starknet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,19 +155,12 @@ pub mod pallet {
/// As this is a very time-consuming process we preferred to let it optional for now
/// Not every application needs it but if you need to use it you can enable it
type EnableStateRoot: Get<bool>;
/// A bool to disable transaction fees and make all transactions free
#[pallet::constant]
type DisableTransactionFee: Get<bool>;
/// A bool to disable Nonce validation
type DisableNonceValidation: Get<bool>;
#[pallet::constant]
type InvokeTxMaxNSteps: Get<u32>;
#[pallet::constant]
type ValidateMaxNSteps: Get<u32>;
#[pallet::constant]
type ProtocolVersion: Get<u8>;
#[pallet::constant]
type ChainId: Get<Felt252Wrapper>;
}

/// The Starknet pallet hooks.
Expand Down Expand Up @@ -317,6 +310,11 @@ pub mod pallet {
#[pallet::getter(fn fee_token_address)]
pub(super) type FeeTokenAddress<T: Config> = StorageValue<_, ContractAddressWrapper, ValueQuery>;

/// The chain id.
#[pallet::storage]
#[pallet::getter(fn chain_id)]
pub(super) type ChainId<T: Config> = StorageValue<_, Felt252Wrapper, ValueQuery>;

/// Current sequencer address.
#[pallet::storage]
#[pallet::getter(fn sequencer_address)]
Expand Down Expand Up @@ -347,6 +345,8 @@ pub mod pallet {
/// Must be set to the address of the fee token ERC20 contract.
pub fee_token_address: ContractAddressWrapper,
pub _phantom: PhantomData<T>,
/// The chain id.
pub chain_id: Felt252Wrapper,
pub seq_addr_updated: bool,
}

Expand All @@ -359,6 +359,7 @@ pub mod pallet {
storage: vec![],
fee_token_address: ContractAddressWrapper::default(),
_phantom: PhantomData,
chain_id: Default::default(),
seq_addr_updated: true,
}
}
Expand Down Expand Up @@ -413,6 +414,8 @@ pub mod pallet {
LastKnownEthBlock::<T>::set(None);
// Set the fee token address from the genesis config.
FeeTokenAddress::<T>::set(self.fee_token_address);
// Set the chain id from the genesis config.
ChainId::<T>::put(self.chain_id);
SeqAddrUpdate::<T>::put(self.seq_addr_updated);
}
}
Expand Down Expand Up @@ -511,16 +514,10 @@ pub mod pallet {

// Get current block context
let block_context = Self::get_block_context();
let chain_id = T::ChainId::get();
let chain_id = Self::chain_id();
let transaction: Transaction = transaction.from_invoke(chain_id);

let call_info = transaction.execute(
&mut BlockifierStateAdapter::<T>::default(),
&block_context,
TxType::Invoke,
T::DisableNonceValidation::get(),
None,
);
let call_info =
transaction.execute(&mut BlockifierStateAdapter::<T>::default(), &block_context, TxType::Invoke, None);
let receipt = match call_info {
Ok(TransactionExecutionInfoWrapper {
validate_call_info: _validate_call_info,
Expand Down Expand Up @@ -569,7 +566,7 @@ pub mod pallet {
// This ensures that the function can only be called via unsigned transaction.
ensure_none(origin)?;

let chain_id = T::ChainId::get();
let chain_id = Self::chain_id();

let transaction: Transaction = transaction.from_declare(chain_id);
// Check that contract class is not None
Expand All @@ -592,7 +589,6 @@ pub mod pallet {
&mut BlockifierStateAdapter::<T>::default(),
&block_context,
TxType::Declare,
T::DisableNonceValidation::get(),
Some(contract_class),
);
let receipt = match call_info {
Expand Down Expand Up @@ -646,7 +642,7 @@ pub mod pallet {
// This ensures that the function can only be called via unsigned transaction.
ensure_none(origin)?;

let chain_id = T::ChainId::get();
let chain_id = Self::chain_id();
let transaction: Transaction =
transaction.from_deploy(chain_id).map_err(|_| Error::<T>::TransactionConversionError)?;

Expand All @@ -664,7 +660,6 @@ pub mod pallet {
&mut BlockifierStateAdapter::<T>::default(),
&block_context,
TxType::DeployAccount,
T::DisableNonceValidation::get(),
None,
);
let receipt = match call_info {
Expand Down Expand Up @@ -728,7 +723,6 @@ pub mod pallet {
&mut BlockifierStateAdapter::<T>::default(),
&block_context,
TxType::L1Handler,
true,
None,
) {
Ok(v) => {
Expand Down Expand Up @@ -847,9 +841,9 @@ impl<T: Config> Pallet<T> {
/// The transaction
fn get_call_transaction(call: Call<T>) -> Result<Transaction, ()> {
match call {
Call::<T>::invoke { transaction } => Ok(transaction.from_invoke(T::ChainId::get())),
Call::<T>::declare { transaction } => Ok(transaction.from_declare(T::ChainId::get())),
Call::<T>::deploy_account { transaction } => transaction.from_deploy(T::ChainId::get()).map_err(|_| ()),
Call::<T>::invoke { transaction } => Ok(transaction.from_invoke(Self::chain_id())),
Call::<T>::declare { transaction } => Ok(transaction.from_declare(Self::chain_id())),
Call::<T>::deploy_account { transaction } => transaction.from_deploy(Self::chain_id()).map_err(|_| ()),
Call::<T>::consume_l1_message { transaction } => Ok(transaction),
_ => Err(()),
}
Expand All @@ -869,12 +863,9 @@ impl<T: Config> Pallet<T> {
let block_context = Self::get_block_context();
let mut state: BlockifierStateAdapter<T> = BlockifierStateAdapter::<T>::default();
let mut execution_resources = ExecutionResources::default();
transaction.validate_account_tx(&mut state, &mut execution_resources, &block_context, &tx_type).map_err(
|e| {
log!(error, "Transaction pool validation failed: {:?}", e);
TransactionValidityError::Invalid(InvalidTransaction::BadProof)
},
)?;
transaction
.validate_account_tx(&mut state, &mut execution_resources, &block_context, &tx_type)
.map_err(|_| TransactionValidityError::Invalid(InvalidTransaction::BadProof))?;

Ok(())
}
Expand Down Expand Up @@ -913,7 +904,7 @@ impl<T: Config> Pallet<T> {
/// convert chain_id
#[inline(always)]
pub fn chain_id_str() -> String {
unsafe { from_utf8_unchecked(&T::ChainId::get().0.to_bytes_be()).to_string() }
unsafe { from_utf8_unchecked(&Self::chain_id().0.to_bytes_be()).to_string() }
}

/// Get the block hash of the previous block.
Expand Down Expand Up @@ -1111,11 +1102,13 @@ impl<T: Config> Pallet<T> {

/// Estimate the fee associated with transaction
pub fn estimate_fee(transaction: Transaction) -> Result<(u64, u64), DispatchError> {
// Check if contract is deployed
ensure!(ContractClassHashes::<T>::contains_key(transaction.sender_address), Error::<T>::AccountNotDeployed);

match transaction.execute(
&mut BlockifierStateAdapter::<T>::default(),
&Self::get_block_context(),
transaction.tx_type.clone(),
T::DisableNonceValidation::get(),
transaction.contract_class.clone(),
) {
Ok(v) => {
Expand Down Expand Up @@ -1205,8 +1198,4 @@ impl<T: Config> Pallet<T> {

global_state_root
}

pub fn chain_id() -> Felt252Wrapper {
T::ChainId::get()
}
}
23 changes: 11 additions & 12 deletions crates/pallets/starknet/src/tests/state_root.rs
Original file line number Diff line number Diff line change
@@ -1,36 +1,35 @@
use mp_starknet::execution::types::Felt252Wrapper;

use super::mock::{default_mock, state_root_mock, *};
use super::mock::state_root_mock::{basic_test_setup_state_root, new_test_ext_with_state_root};
use super::mock::*;
use crate::tests::mock::state_root_mock::MockStateRootRuntime;

#[test]
fn given_default_runtime_with_state_root_disabled_default_value_is_correct() {
new_test_ext::<default_mock::MockRuntime>().execute_with(|| {
default_mock::basic_test_setup(2);
new_test_ext().execute_with(|| {
basic_test_setup_state_root::<MockRuntime>(2);

// Check that state root is not set when disabled
pretty_assertions::assert_eq!(
default_mock::Starknet::compute_and_store_state_root(),
Felt252Wrapper::default()
);
pretty_assertions::assert_eq!(Starknet::compute_and_store_state_root(), Felt252Wrapper::default());
});
}

#[test]
fn given_default_runtime_with_state_root_enabled_default_value_is_correct() {
new_test_ext::<state_root_mock::MockRuntime>().execute_with(|| {
state_root_mock::basic_test_setup(2);
new_test_ext_with_state_root().execute_with(|| {
basic_test_setup_state_root::<MockStateRootRuntime>(2);

// Check the default state root value when enabled
// We fetch this value using current genesis state and starkware python package
pretty_assertions::assert_eq!(
state_root_mock::Starknet::compute_and_store_state_root(),
Felt252Wrapper::from_hex_be("0x066a4b57d6d9f0c3d15f1bebfac552d0e0e39ca89a1627b190838344620ecbe1").unwrap()
Starknet::compute_and_store_state_root(),
Felt252Wrapper::from_hex_be("0x04b355b75d79a84b2782b185f25a8c5831854addbf3433805a246f9931beec87").unwrap()
);

let account_address = get_account_address(AccountType::V0(AccountTypeV0Inner::Argent));

pretty_assertions::assert_eq!(
state_root_mock::Starknet::contract_state_root_by_address(account_address).unwrap(),
Starknet::contract_state_root_by_address(account_address).unwrap(),
Felt252Wrapper::from_hex_be("0x04b9de03767569b7b86924fd58d86cb1a0ba1b9c3eb3078187b4533d0d2af340").unwrap()
)
});
Expand Down
Loading

0 comments on commit b06c572

Please sign in to comment.