Skip to content

Commit

Permalink
feat: post compilation size limit validation
Browse files Browse the repository at this point in the history
  • Loading branch information
ArniStarkware committed Jul 11, 2024
1 parent d4ee11d commit 723b4eb
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 16 deletions.
10 changes: 10 additions & 0 deletions config/default_config.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@
"privacy": "Public",
"value": true
},
"gateway_config.compiler_config.max_bytecode_size": {
"description": "Limitation of contract bytecode size",
"privacy": "Public",
"value": 81920
},
"gateway_config.compiler_config.max_raw_class_size": {
"description": "Limitation of contract class object size",
"privacy": "Public",
"value": 4089446
},
"gateway_config.network_config.ip": {
"description": "The gateway server ip.",
"privacy": "Public",
Expand Down
34 changes: 32 additions & 2 deletions crates/gateway/src/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ use crate::utils::is_subsequence;
#[path = "compilation_test.rs"]
mod compilation_test;

// TODO(Define a function for `compile_contract_class` - which ignores the `config` parameter).
#[derive(Clone)]
pub struct GatewayCompiler {
#[allow(dead_code)]
pub config: GatewayCompilerConfig,
}

Expand All @@ -48,7 +48,7 @@ impl GatewayCompiler {
return Err(GatewayError::CompilationError(CompilationUtilError::CompilationPanic));
}
};
self.validate_casm_class(&casm_contract_class)?;
self.validate_casm(&casm_contract_class)?;

let hash_result = CompiledClassHash(casm_contract_class.compiled_class_hash());
if hash_result != tx.compiled_class_hash {
Expand All @@ -69,6 +69,12 @@ impl GatewayCompiler {
Ok(class_info)
}

fn validate_casm(&self, casm_contract_class: &CasmContractClass) -> Result<(), GatewayError> {
self.validate_casm_class(casm_contract_class)?;
self.validate_casm_class_size(casm_contract_class)?;
Ok(())
}

// TODO(Arni): Add test.
fn validate_casm_class(&self, contract_class: &CasmContractClass) -> Result<(), GatewayError> {
let CasmContractEntryPoints { external, l1_handler, constructor } =
Expand All @@ -87,6 +93,30 @@ impl GatewayCompiler {
}
Ok(())
}

fn validate_casm_class_size(
&self,
casm_contract_class: &CasmContractClass,
) -> Result<(), GatewayError> {
let bytecode_size = casm_contract_class.bytecode.len();
if bytecode_size > self.config.max_bytecode_size {
return Err(GatewayError::CasmBytecodeSizeTooLarge {
bytecode_size,
max_bytecode_size: self.config.max_bytecode_size,
});
}
let contract_class_object_size = serde_json::to_string(&casm_contract_class)
.expect("Unexpected error serializing Casm contract class.")
.len();
if contract_class_object_size > self.config.max_raw_class_size {
return Err(GatewayError::CasmContractClassObjectSizeTooLarge {
contract_class_object_size,
max_contract_class_object_size: self.config.max_raw_class_size,
});
}

Ok(())
}
}

// TODO(Arni): Add to a config.
Expand Down
45 changes: 45 additions & 0 deletions crates/gateway/src/compilation_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use starknet_api::rpc_transaction::{RPCDeclareTransaction, RPCTransaction};
use starknet_sierra_compile::errors::CompilationUtilError;

use crate::compilation::GatewayCompiler;
use crate::config::GatewayCompilerConfig;
use crate::errors::GatewayError;

#[fixture]
Expand Down Expand Up @@ -35,6 +36,50 @@ fn test_compile_contract_class_compiled_class_hash_missmatch(gateway_compiler: G
);
}

#[rstest]
#[case::bytecode_size(
GatewayCompilerConfig { max_bytecode_size: 1, max_raw_class_size: usize::MAX},
GatewayError::CasmBytecodeSizeTooLarge { bytecode_size: 4800, max_bytecode_size: 1 }
)]
#[case::raw_class_size(
GatewayCompilerConfig { max_bytecode_size: usize::MAX, max_raw_class_size: 1},
GatewayError::CasmContractClassObjectSizeTooLarge {
contract_class_object_size: 111037, max_contract_class_object_size: 1
}
)]
fn test_compile_contract_class_size_validation(
#[case] sierra_to_casm_compilation_config: GatewayCompilerConfig,
#[case] expected_error: GatewayError,
) {
let declare_tx = match declare_tx() {
RPCTransaction::Declare(declare_tx) => declare_tx,
_ => panic!("Invalid transaction type"),
};

let gateway_compiler = GatewayCompiler { config: sierra_to_casm_compilation_config };
let result = gateway_compiler.compile_contract_class(&declare_tx);
if let GatewayError::CasmBytecodeSizeTooLarge {
bytecode_size: expected_bytecode_size, ..
} = expected_error
{
assert_matches!(
result.unwrap_err(),
GatewayError::CasmBytecodeSizeTooLarge { bytecode_size, .. }
if bytecode_size == expected_bytecode_size
)
} else if let GatewayError::CasmContractClassObjectSizeTooLarge {
contract_class_object_size: expected_contract_class_object_size,
..
} = expected_error
{
assert_matches!(
result.unwrap_err(),
GatewayError::CasmContractClassObjectSizeTooLarge { contract_class_object_size, .. }
if contract_class_object_size == expected_contract_class_object_size
)
}
}

#[rstest]
fn test_compile_contract_class_bad_sierra(gateway_compiler: GatewayCompiler) {
let mut tx = assert_matches!(
Expand Down
34 changes: 29 additions & 5 deletions crates/gateway/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ use validator::Validate;

use crate::compiler_version::VersionId;

const MAX_BYTECODE_SIZE: usize = 81920;
const MAX_RAW_CLASS_SIZE: usize = 4089446;

#[derive(Clone, Debug, Default, Serialize, Deserialize, Validate, PartialEq)]
pub struct GatewayConfig {
pub network_config: GatewayNetworkConfig,
Expand Down Expand Up @@ -88,8 +91,8 @@ impl Default for StatelessTransactionValidatorConfig {
validate_non_zero_l2_gas_fee: false,
max_calldata_length: 4000,
max_signature_length: 4000,
max_bytecode_size: 81920,
max_raw_class_size: 4089446,
max_bytecode_size: MAX_BYTECODE_SIZE,
max_raw_class_size: MAX_RAW_CLASS_SIZE,
min_sierra_version: VersionId { major: 1, minor: 1, patch: 0 },
max_sierra_version: VersionId { major: 1, minor: 5, patch: usize::MAX },
}
Expand Down Expand Up @@ -295,12 +298,33 @@ impl StatefulTransactionValidatorConfig {
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Validate, PartialEq)]
pub struct GatewayCompilerConfig {
pub max_bytecode_size: usize,
pub max_raw_class_size: usize,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, Validate, PartialEq)]
pub struct GatewayCompilerConfig {}
impl Default for GatewayCompilerConfig {
fn default() -> Self {
Self { max_bytecode_size: MAX_BYTECODE_SIZE, max_raw_class_size: MAX_RAW_CLASS_SIZE }
}
}

impl SerializeConfig for GatewayCompilerConfig {
fn dump(&self) -> BTreeMap<ParamPath, SerializedParam> {
BTreeMap::new()
BTreeMap::from_iter([
ser_param(
"max_bytecode_size",
&self.max_bytecode_size,
"Limitation of contract bytecode size",
ParamPrivacyInput::Public,
),
ser_param(
"max_raw_class_size",
&self.max_raw_class_size,
"Limitation of contract class object size",
ParamPrivacyInput::Public,
),
])
}
}
13 changes: 13 additions & 0 deletions crates/gateway/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,19 @@ use crate::compiler_version::{VersionId, VersionIdError};
/// Errors directed towards the end-user, as a result of gateway requests.
#[derive(Debug, Error)]
pub enum GatewayError {
#[error(
"Cannot declare Casm contract class with bytecode size of {bytecode_size}; max allowed \
size: {max_bytecode_size}."
)]
CasmBytecodeSizeTooLarge { bytecode_size: usize, max_bytecode_size: usize },
#[error(
"Cannot declare Casm contract class with size of {contract_class_object_size}; max \
allowed size: {max_contract_class_object_size}."
)]
CasmContractClassObjectSizeTooLarge {
contract_class_object_size: usize,
max_contract_class_object_size: usize,
},
#[error(transparent)]
CompilationError(#[from] CompilationUtilError),
#[error(
Expand Down
15 changes: 11 additions & 4 deletions crates/gateway/src/gateway_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,28 @@ pub fn app_state(
mempool_client: SharedMempoolClient,
state_reader_factory: TestStateReaderFactory,
) -> AppState {
const MAX_BYTECODE_SIZE: usize = 10000;
const MAX_RAW_CLASS_SIZE: usize = 1000000;
AppState {
stateless_tx_validator: StatelessTransactionValidator {
config: StatelessTransactionValidatorConfig {
validate_non_zero_l1_gas_fee: true,
max_calldata_length: 10,
max_signature_length: 2,
max_bytecode_size: 10000,
max_raw_class_size: 1000000,
max_bytecode_size: MAX_BYTECODE_SIZE,
max_raw_class_size: MAX_RAW_CLASS_SIZE,
..Default::default()
},
},
stateful_tx_validator: Arc::new(StatefulTransactionValidator {
config: StatefulTransactionValidatorConfig::create_for_testing(),
}),
gateway_compiler: GatewayCompiler { config: GatewayCompilerConfig {} },
gateway_compiler: GatewayCompiler {
config: GatewayCompilerConfig {
max_bytecode_size: MAX_BYTECODE_SIZE,
max_raw_class_size: MAX_RAW_CLASS_SIZE,
},
},
state_reader_factory: Arc::new(state_reader_factory),
mempool_client,
}
Expand Down Expand Up @@ -114,7 +121,7 @@ async fn to_bytes(res: Response) -> Bytes {
fn calculate_hash(external_tx: &RPCTransaction) -> TransactionHash {
let optional_class_info = match &external_tx {
RPCTransaction::Declare(declare_tx) => Some(
GatewayCompiler { config: GatewayCompilerConfig {} }
GatewayCompiler { config: GatewayCompilerConfig::default() }
.compile_contract_class(declare_tx)
.unwrap(),
),
Expand Down
9 changes: 4 additions & 5 deletions crates/gateway/src/stateful_transaction_validator_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,10 @@ fn test_stateful_tx_validator(
},
};
let optional_class_info = match &external_tx {
RPCTransaction::Declare(declare_tx) => Some(
GatewayCompiler { config: GatewayCompilerConfig {} }
.compile_contract_class(declare_tx)
.unwrap(),
),
RPCTransaction::Declare(declare_tx) => {
let gateway_compiler = GatewayCompiler { config: GatewayCompilerConfig::default() };
Some(gateway_compiler.compile_contract_class(declare_tx).unwrap())
}
_ => None,
};

Expand Down

0 comments on commit 723b4eb

Please sign in to comment.