Skip to content

Commit

Permalink
fix: Ensure sender nonce does not overflow (#237)
Browse files Browse the repository at this point in the history
Close #168 

Note to reviewer: this is a fix imported from C4 mitigation, ensure the
fix was correctly ported by looking at the corresponding issue and PR.
  • Loading branch information
obatirou authored Dec 9, 2024
1 parent bff12c0 commit 5e773bf
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
1 change: 1 addition & 0 deletions cairo/programs/os.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ func apply_transactions{

// Validate nonce
with_attr error_message("Invalid nonce") {
assert_le(tx.signer_nonce, 2 ** 64 - 2);
assert tx.signer_nonce = account.nonce;
}

Expand Down
36 changes: 36 additions & 0 deletions cairo/tests/programs/test_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,39 @@ def test_create_tx_returndata(self, cairo_run):
bytes.fromhex(
"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3"
) == state["accounts"]["0x32dCAB0EF3FB2De2fce1D2E0799D36239671F04A"]["code"]

@given(nonce=integers(min_value=2**64, max_value=2**248 - 1))
def test_should_raise_when_nonce_is_greater_u64(self, cairo_run, nonce):
initial_state = {
OWNER: {
"code": [],
"storage": {},
"balance": int(1e18),
"nonce": nonce,
},
OTHER: {
"code": [],
"storage": {},
"balance": int(1e18),
"nonce": 0,
},
COINBASE: {
"code": [],
"storage": {},
"balance": 0,
"nonce": 0,
},
}
transaction = {
"to": OTHER,
"data": "",
"value": 0,
"signer": OWNER,
}

with cairo_error("Invalid nonce"):
cairo_run(
"test_os",
block=block([transaction], nonces={OWNER: nonce}),
state=State.model_validate(initial_state),
)
4 changes: 2 additions & 2 deletions cairo/tests/utils/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
from tests.utils.models import Block


def block(transactions=None):
nonces = defaultdict(int)
def block(transactions=None, nonces=None):
nonces = nonces or defaultdict(int)
transactions = transactions or []

for transaction in transactions:
Expand Down

0 comments on commit 5e773bf

Please sign in to comment.