Skip to content

feat: checks on upper bounds of contract storage sizes #169

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

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions crates/config/src/opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ pub struct UnstableOpts {
#[cfg_attr(feature = "clap", arg(long))]
pub ast_stats: bool,

/// Print contract's max storage size.
#[cfg_attr(feature = "clap", arg(long))]
pub print_contract_max_storage_size: bool,

/// Print help.
#[cfg_attr(feature = "clap", arg(long, action = clap::ArgAction::Help))]
pub help: (),
Expand All @@ -170,6 +174,7 @@ pub struct UnstableOpts {
#[cfg(test)]
#[cfg_attr(feature = "clap", arg(long))]
pub test_bool: bool,

#[cfg(test)]
#[cfg_attr(feature = "clap", arg(long))]
pub test_value: Option<usize>,
Expand Down
79 changes: 77 additions & 2 deletions crates/sema/src/typeck/mod.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,98 @@
use crate::{
ast_lowering::resolve::{Declaration, Declarations},
hir::{self, Res},
ty::{Gcx, Ty},
hir::{self, Res, Variable},
ty::{Gcx, Ty, TyKind},
};
use alloy_primitives::U256;
use rayon::prelude::*;
use solar_ast::DataLocation;
use solar_data_structures::{map::FxHashSet, parallel};

pub(crate) fn check(gcx: Gcx<'_>) {
parallel!(
gcx.sess,
gcx.hir.par_contract_ids().for_each(|id| {
check_duplicate_definitions(gcx, &gcx.symbol_resolver.contract_scopes[id]);
check_storage_size_upper_bound(gcx, id);
}),
gcx.hir.par_source_ids().for_each(|id| {
check_duplicate_definitions(gcx, &gcx.symbol_resolver.source_scopes[id]);
}),
);
}

/// Checks for violation of maximum storage size to ensure slot allocation algorithms works.
/// Reference: https://github.com/ethereum/solidity/blob/03e2739809769ae0c8d236a883aadc900da60536/libsolidity/analysis/ContractLevelChecker.cpp#L556C1-L570C2
fn check_storage_size_upper_bound(gcx: Gcx<'_>, contract_id: hir::ContractId) {
let mut total_size = U256::ZERO;
for item_id in gcx.hir.contract_item_ids(contract_id) {
// Skip constant and immutable variables
if let hir::Item::Variable(Variable { mutability: None, .. }) = gcx.hir.item(item_id) {
let t = gcx.type_of_item(item_id);
match ty_upper_bound_storage_var_size(t, gcx)
.and_then(|size_contribution| total_size.checked_add(size_contribution))
{
Some(sz) => {
total_size = sz;
}
None => {
let contract = gcx.hir.contract(contract_id);
gcx.dcx()
.err("contract requires too much storage")
.span(contract.name.span)
.emit();
return;
}
}
}
}

if gcx.sess.opts.unstable.print_contract_max_storage_size {
let full_contract_name = gcx.contract_fully_qualified_name(contract_id);
println!("{full_contract_name} requires a maximum of {total_size} storage slots");
}
}

fn ty_upper_bound_storage_var_size(ty: Ty<'_>, gcx: Gcx<'_>) -> Option<U256> {
match ty.kind {
TyKind::Elementary(..)
| TyKind::StringLiteral(..)
| TyKind::IntLiteral(..)
| TyKind::Mapping(..)
| TyKind::Contract(..)
| TyKind::Udvt(..)
| TyKind::Enum(..)
| TyKind::DynArray(..) => Some(U256::from(1)),
TyKind::Ref(ty, DataLocation::Storage) => ty_upper_bound_storage_var_size(ty, gcx),
TyKind::Ref(..)
| TyKind::Tuple(..)
| TyKind::FnPtr(..)
| TyKind::Module(..)
| TyKind::BuiltinModule(..)
| TyKind::Event(..)
| TyKind::Meta(..)
| TyKind::Err(..)
| TyKind::Error(..) => {
unreachable!()
}
TyKind::Array(ty, uint) => {
// Reference: https://github.com/ethereum/solidity/blob/03e2739809769ae0c8d236a883aadc900da60536/libsolidity/ast/Types.cpp#L1800C1-L1806C2
let elem_size = ty_upper_bound_storage_var_size(ty, gcx)?;
uint.checked_mul(elem_size)
}
TyKind::Struct(struct_id) => {
// Reference https://github.com/ethereum/solidity/blob/03e2739809769ae0c8d236a883aadc900da60536/libsolidity/ast/Types.cpp#L2303C1-L2309C2
let mut total_size = U256::from(1);
for t in gcx.struct_field_types(struct_id) {
let size_contribution = ty_upper_bound_storage_var_size(*t, gcx)?;
total_size = total_size.checked_add(size_contribution)?;
}
Some(total_size)
}
TyKind::Type(ty) => ty_upper_bound_storage_var_size(ty, gcx),
}
}

/// Checks for definitions that have the same name and parameter types in the given scope.
fn check_duplicate_definitions(gcx: Gcx<'_>, scope: &Declarations) {
let is_duplicate = |a: Declaration, b: Declaration| -> bool {
Expand Down
14 changes: 14 additions & 0 deletions tests/ui/typeck/contract_storage_illegal_size.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//@ compile-flags: -Zprint-contract-max-storage-size

// Okay because 2^256 - 1 slots, which are the maximum permissible slots, are used
contract BarelyLegal {
uint256[115792089237316195423570985008687907853269984665640564039457584007913129639935]
public x;
}

// Not Okay because 2^256 slots are used
contract Illegal { //~ ERROR: contract requires too much storage
uint256[115792089237316195423570985008687907853269984665640564039457584007913129639935]
public x;
uint256 y;
}
9 changes: 9 additions & 0 deletions tests/ui/typeck/contract_storage_illegal_size.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
error: contract requires too much storage
--> ROOT/tests/ui/typeck/contract_storage_illegal_size.sol:LL:CC
|
LL | contract Illegal {
| ^^^^^^^
|

error: aborting due to 1 previous error

1 change: 1 addition & 0 deletions tests/ui/typeck/contract_storage_illegal_size.stdout
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ROOT/tests/ui/typeck/contract_storage_illegal_size.sol:BarelyLegal requires a maximum of 115792089237316195423570985008687907853269984665640564039457584007913129639935 storage slots
41 changes: 41 additions & 0 deletions tests/ui/typeck/contract_storage_size_check.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//@ compile-flags: -Zprint-contract-max-storage-size

struct Person {
string name;
uint age;
}

contract B {
uint c;
bool x;
}

// Total = 1 + 1 = 2

contract A {
uint256 a; // 1
bool b; // 1
B c; // 1
Person e; // 1 + 2 fields = 3
int128 f; // 1
Person[] g; // 1
Person[23] h; // 23 * 3 = 69
}

// Total = 1 + 1 + 1 + 3 + 1 + 1 + 69 = 77

contract M {
struct P1 {
string first;
string middle;
string last;
}

P1 my; // 4
mapping(string => uint256) public a; // 1
P1[] public b; // 1
bool c; // 1
B d; // 1
}

// Total = 4 + 1 + 1 + 1 + 1 = 8
3 changes: 3 additions & 0 deletions tests/ui/typeck/contract_storage_size_check.stdout
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ROOT/tests/ui/typeck/contract_storage_size_check.sol:B requires a maximum of 2 storage slots
ROOT/tests/ui/typeck/contract_storage_size_check.sol:A requires a maximum of 77 storage slots
ROOT/tests/ui/typeck/contract_storage_size_check.sol:M requires a maximum of 8 storage slots