Skip to content

Commit

Permalink
[KGA-100] [KGA-56] fix: memory expansion early return condition (#1619)
Browse files Browse the repository at this point in the history
Fixes the early return condition in `calculate_gas_extend_memory` that
was off-by-one.
This had no impact on the code, as the correct memory was computed
after. This just did not early returned in all cases.

Co-authored-by: Oba <[email protected]>
  • Loading branch information
enitrat and obatirou authored Nov 20, 2024
1 parent 6fbdc16 commit 63f6320
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
2 changes: 1 addition & 1 deletion cairo_zero/kakarot/gas.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ namespace Gas {
) -> model.MemoryExpansion {
alloc_locals;
let is_memory_length_not_zero = is_not_zero(words_len);
let current_memory_length = (words_len * 32 - 1) * is_memory_length_not_zero;
let current_memory_length = (words_len * 32) * is_memory_length_not_zero;
let memory_expansion = is_le_felt(current_memory_length, max_offset);
if (memory_expansion == FALSE) {
let expansion = model.MemoryExpansion(cost=0, new_words_len=words_len);
Expand Down
13 changes: 9 additions & 4 deletions cairo_zero/tests/src/kakarot/test_gas.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,21 +40,24 @@ def test_should_return_correct_expansion_cost(
size_1=integers(min_value=0, max_value=DEFAULT_PRIME - 1),
offset_2=integers(min_value=0, max_value=DEFAULT_PRIME - 1),
size_2=integers(min_value=0, max_value=DEFAULT_PRIME - 1),
words_len=integers(
min_value=0, max_value=0x3C0000
), # upper bound reaching 30M gas limit on expansion
)
def test_should_return_max_expansion_cost(
self, cairo_run, offset_1, size_1, offset_2, size_2
self, cairo_run, offset_1, size_1, offset_2, size_2, words_len
):
memory_cost_u32 = calculate_memory_gas_cost(2**32 - 1)
output = cairo_run(
"test__max_memory_expansion_cost",
words_len=0,
words_len=words_len,
offset_1=int_to_uint256(offset_1),
size_1=int_to_uint256(size_1),
offset_2=int_to_uint256(offset_2),
size_2=int_to_uint256(size_2),
)
expansion = calculate_gas_extend_memory(
b"",
b"\x00" * 32 * words_len,
[
(offset_1, size_1),
(offset_2, size_2),
Expand All @@ -64,7 +67,9 @@ def test_should_return_max_expansion_cost(
# If the memory expansion is greater than 2**27 words of 32 bytes
# We saturate it to the hardcoded value corresponding the the gas cost of a 2**32 memory size
expected_saturated = (
memory_cost_u32 if expansion.expand_by >= 2**32 else expansion.cost
memory_cost_u32
if (words_len * 32 + expansion.expand_by) >= 2**32
else expansion.cost
)
assert output == expected_saturated

Expand Down

0 comments on commit 63f6320

Please sign in to comment.