From 63f63200373660f47532571f33d2bf35bbb36455 Mon Sep 17 00:00:00 2001 From: Mathieu <60658558+enitrat@users.noreply.github.com> Date: Wed, 20 Nov 2024 15:36:55 +0700 Subject: [PATCH] [KGA-100] [KGA-56] fix: memory expansion early return condition (#1619) 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 --- cairo_zero/kakarot/gas.cairo | 2 +- cairo_zero/tests/src/kakarot/test_gas.py | 13 +++++++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/cairo_zero/kakarot/gas.cairo b/cairo_zero/kakarot/gas.cairo index fe4f97c75..3f2521aac 100644 --- a/cairo_zero/kakarot/gas.cairo +++ b/cairo_zero/kakarot/gas.cairo @@ -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); diff --git a/cairo_zero/tests/src/kakarot/test_gas.py b/cairo_zero/tests/src/kakarot/test_gas.py index 272e86c11..5b813d7eb 100644 --- a/cairo_zero/tests/src/kakarot/test_gas.py +++ b/cairo_zero/tests/src/kakarot/test_gas.py @@ -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), @@ -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