Skip to content

Commit dffdc5a

Browse files
committed
feat: check that the compiled class hash matches the supplied class
1 parent 8e9b2d7 commit dffdc5a

File tree

6 files changed

+94
-4
lines changed

6 files changed

+94
-4
lines changed

crates/gateway/src/errors.rs

+6
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use blockifier::transaction::errors::TransactionExecutionError;
77
use cairo_vm::types::errors::program_errors::ProgramError;
88
use serde_json::{Error as SerdeError, Value};
99
use starknet_api::block::{BlockNumber, GasPrice};
10+
use starknet_api::core::CompiledClassHash;
1011
use starknet_api::transaction::{Resource, ResourceBounds};
1112
use starknet_api::StarknetApiError;
1213
use thiserror::Error;
@@ -19,6 +20,11 @@ use crate::compiler_version::{VersionId, VersionIdError};
1920
pub enum GatewayError {
2021
#[error(transparent)]
2122
CompilationError(#[from] starknet_sierra_compile::compile::CompilationUtilError),
23+
#[error(
24+
"The supplied compiled class hash {supplied:?} does not match the hash of the Casm class \
25+
compiled from the supplied Sierra {hash_result:?}."
26+
)]
27+
CompiledClassHashMismatch { supplied: CompiledClassHash, hash_result: CompiledClassHash },
2228
#[error(transparent)]
2329
DeclaredContractClassError(#[from] ContractClassError),
2430
#[error(transparent)]

crates/gateway/src/gateway.rs

+11
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ use axum::extract::State;
77
use axum::routing::{get, post};
88
use axum::{Json, Router};
99
use blockifier::execution::contract_class::{ClassInfo, ContractClass, ContractClassV1};
10+
use blockifier::execution::execution_utils::felt_to_stark_felt;
11+
use starknet_api::core::CompiledClassHash;
1012
use starknet_api::rpc_transaction::{RPCDeclareTransaction, RPCTransaction};
1113
use starknet_api::transaction::TransactionHash;
1214
use starknet_mempool_types::communication::SharedMempoolClient;
@@ -157,6 +159,15 @@ pub fn compile_contract_class(declare_tx: &RPCDeclareTransaction) -> GatewayResu
157159
}
158160
};
159161

162+
let hash_result =
163+
CompiledClassHash(felt_to_stark_felt(&casm_contract_class.compiled_class_hash()));
164+
if hash_result != tx.compiled_class_hash {
165+
return Err(GatewayError::CompiledClassHashMismatch {
166+
supplied: tx.compiled_class_hash,
167+
hash_result,
168+
});
169+
}
170+
160171
// Convert Casm contract class to Starknet contract class directly.
161172
let blockifier_contract_class =
162173
ContractClass::V1(ContractClassV1::try_from(casm_contract_class)?);

crates/gateway/src/gateway_test.rs

+67-1
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,27 @@
11
use std::sync::Arc;
22

3+
use assert_matches::assert_matches;
34
use axum::body::{Bytes, HttpBody};
45
use axum::extract::State;
56
use axum::http::StatusCode;
67
use axum::response::{IntoResponse, Response};
78
use blockifier::context::ChainInfo;
9+
use blockifier::execution::contract_class::ContractClass;
810
use blockifier::test_utils::CairoVersion;
11+
use cairo_lang_starknet_classes::allowed_libfuncs::AllowedLibfuncsError;
912
use rstest::{fixture, rstest};
10-
use starknet_api::rpc_transaction::RPCTransaction;
13+
use starknet_api::core::CompiledClassHash;
14+
use starknet_api::rpc_transaction::{RPCDeclareTransaction, RPCTransaction};
1115
use starknet_api::transaction::TransactionHash;
1216
use starknet_mempool::communication::create_mempool_server;
1317
use starknet_mempool::mempool::Mempool;
1418
use starknet_mempool_types::communication::{MempoolClientImpl, MempoolRequestAndResponseSender};
19+
use starknet_sierra_compile::compile::CompilationUtilError;
1520
use tokio::sync::mpsc::channel;
1621
use tokio::task;
1722

1823
use crate::config::{StatefulTransactionValidatorConfig, StatelessTransactionValidatorConfig};
24+
use crate::errors::GatewayError;
1925
use crate::gateway::{add_tx, compile_contract_class, AppState, SharedMempoolClient};
2026
use crate::starknet_api_test_utils::{declare_tx, deploy_account_tx, invoke_tx};
2127
use crate::state_reader_test_utils::{
@@ -103,6 +109,66 @@ async fn test_add_tx(
103109
assert_eq!(tx_hash, serde_json::from_slice(response_bytes).unwrap());
104110
}
105111

112+
#[test]
113+
fn test_compile_contract_class_compiled_class_hash_missmatch() {
114+
let mut tx = assert_matches!(
115+
declare_tx(),
116+
RPCTransaction::Declare(RPCDeclareTransaction::V3(tx)) => tx
117+
);
118+
let expected_hash_result = tx.compiled_class_hash;
119+
let supplied_hash = CompiledClassHash::default();
120+
121+
tx.compiled_class_hash = supplied_hash;
122+
let declare_tx = RPCDeclareTransaction::V3(tx);
123+
124+
let result = compile_contract_class(&declare_tx);
125+
assert_matches!(
126+
result.unwrap_err(),
127+
GatewayError::CompiledClassHashMismatch { supplied, hash_result }
128+
if supplied == supplied_hash && hash_result == expected_hash_result
129+
);
130+
}
131+
132+
#[test]
133+
fn test_compile_contract_class_bad_sierra() {
134+
let mut tx = assert_matches!(
135+
declare_tx(),
136+
RPCTransaction::Declare(RPCDeclareTransaction::V3(tx)) => tx
137+
);
138+
// Truncate the sierra program to trigger an error.
139+
tx.contract_class.sierra_program = tx.contract_class.sierra_program[..100].to_vec();
140+
let declare_tx = RPCDeclareTransaction::V3(tx);
141+
142+
let result = compile_contract_class(&declare_tx);
143+
assert_matches!(
144+
result.unwrap_err(),
145+
GatewayError::CompilationError(CompilationUtilError::AllowedLibfuncsError(
146+
AllowedLibfuncsError::SierraProgramError
147+
))
148+
)
149+
}
150+
151+
#[test]
152+
fn test_compile_contract_class() {
153+
let declare_tx = assert_matches!(
154+
declare_tx(),
155+
RPCTransaction::Declare(declare_tx) => declare_tx
156+
);
157+
let RPCDeclareTransaction::V3(declare_tx_v3) = &declare_tx;
158+
let contract_class = &declare_tx_v3.contract_class;
159+
160+
let result = compile_contract_class(&declare_tx);
161+
// Asserts the compilation was succesful.
162+
let class_info = assert_matches!(
163+
result,
164+
Ok(class_info) => class_info
165+
);
166+
// Asserts the compilation result is as expected.
167+
assert_matches!(class_info.contract_class(), ContractClass::V1(_));
168+
assert_eq!(class_info.sierra_program_length(), contract_class.sierra_program.len());
169+
assert_eq!(class_info.abi_length(), contract_class.abi.len());
170+
}
171+
106172
async fn to_bytes(res: Response) -> Bytes {
107173
res.into_body().collect().await.unwrap().to_bytes()
108174
}

crates/gateway/src/starknet_api_test_utils.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@ use starknet_api::transaction::{
1818
TransactionSignature, TransactionVersion,
1919
};
2020
use starknet_api::{calldata, stark_felt};
21-
use test_utils::{get_absolute_path, CONTRACT_CLASS_FILE, TEST_FILES_FOLDER};
21+
use test_utils::{
22+
get_absolute_path, COMPILED_CLASS_HASH_OF_CONTRACT_CLASS, CONTRACT_CLASS_FILE,
23+
TEST_FILES_FOLDER,
24+
};
2225

2326
use crate::{declare_tx_args, deploy_account_tx_args, invoke_tx_args};
2427

@@ -97,6 +100,7 @@ pub fn declare_tx() -> RPCTransaction {
97100
env::set_current_dir(get_absolute_path(TEST_FILES_FOLDER)).expect("Couldn't set working dir.");
98101
let json_file_path = Path::new(CONTRACT_CLASS_FILE);
99102
let contract_class = serde_json::from_reader(File::open(json_file_path).unwrap()).unwrap();
103+
let compiled_class_hash = CompiledClassHash(stark_felt!(COMPILED_CLASS_HASH_OF_CONTRACT_CLASS));
100104

101105
let account_contract = FeatureContract::AccountWithoutValidations(CairoVersion::Cairo1);
102106
let account_address = account_contract.get_instance_address(0);
@@ -108,7 +112,8 @@ pub fn declare_tx() -> RPCTransaction {
108112
sender_address: account_address,
109113
resource_bounds: executable_resource_bounds_mapping(),
110114
nonce,
111-
contract_class
115+
class_hash: compiled_class_hash,
116+
contract_class,
112117
))
113118
}
114119

crates/gateway/src/stateful_transaction_validator_test.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ use crate::stateful_transaction_validator::StatefulTransactionValidator;
4646
declare_tx(),
4747
local_test_state_reader_factory(CairoVersion::Cairo1, false),
4848
Ok(TransactionHash(StarkFelt::try_from(
49-
"0x0278ed2700d5a30254a6b895d4e1140438d7d1a3b2b2ce0c096a9d5ee1c61f39"
49+
"0x02da54b89e00d2e201f8e3ed2bcc715a69e89aefdce88aff2d2facb8dec55c0a"
5050
).unwrap()))
5151
)]
5252
#[case::invalid_tx(

crates/test_utils/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ use std::path::{Path, PathBuf};
33

44
pub const TEST_FILES_FOLDER: &str = "crates/test_utils/test_files";
55
pub const CONTRACT_CLASS_FILE: &str = "contract_class.json";
6+
pub const COMPILED_CLASS_HASH_OF_CONTRACT_CLASS: &str =
7+
"0x01e4f1248860f32c336f93f2595099aaa4959be515e40b75472709ef5243ae17";
68

79
/// Returns the absolute path from the project root.
810
pub fn get_absolute_path(relative_path: &str) -> PathBuf {

0 commit comments

Comments
 (0)