diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c655c11d3..a4189ed073 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ * refactor: Limit ret opcode decodeing to Cairo0's standards. [#1925](https://github.com/lambdaclass/cairo-vm/pull/1925) +* feat: define HashMap of hint groups along with hint strings [#1943](https://github.com/lambdaclass/cairo-vm/pull/1943) + #### [2.0.0-rc4] - 2025-01-23 * feat: implement `kzg` data availability hints [#1887](https://github.com/lambdaclass/cairo-vm/pull/1887) diff --git a/Cargo.lock b/Cargo.lock index 52fb70192f..822d666866 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -933,6 +933,7 @@ dependencies = [ "hashbrown 0.15.2", "hex", "iai-callgrind", + "indoc", "keccak", "lazy_static", "mimalloc", diff --git a/Cargo.toml b/Cargo.toml index f0ac0c0f67..35ee36aac0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,6 +48,7 @@ starknet-crypto = { version = "0.7.3", default-features = false, features = [ "alloc", ] } sha3 = { version = "0.10.8", default-features = false } +indoc = { version = "2.0.5", default-features = false } lazy_static = { version = "1.4.0", default-features = false, features = [ "spin_no_std", ] } diff --git a/vm/Cargo.toml b/vm/Cargo.toml index a01a0ce2c0..0fc15c5f4b 100644 --- a/vm/Cargo.toml +++ b/vm/Cargo.toml @@ -50,6 +50,7 @@ hex = { workspace = true } bincode = { workspace = true } starknet-crypto = { workspace = true } sha3 = { workspace = true } +indoc = { workspace = true } lazy_static = { workspace = true } nom = { workspace = true } sha2 = { workspace = true } diff --git a/vm/src/hint_processor/builtin_hint_processor/hint_code.rs b/vm/src/hint_processor/builtin_hint_processor/hint_code.rs index 27f3a7bb31..c8c5aaebc2 100644 --- a/vm/src/hint_processor/builtin_hint_processor/hint_code.rs +++ b/vm/src/hint_processor/builtin_hint_processor/hint_code.rs @@ -1,44 +1,41 @@ -pub const ADD_SEGMENT: &str = "memory[ap] = segments.add()"; - -pub const VM_ENTER_SCOPE: &str = "vm_enter_scope()"; -pub const VM_EXIT_SCOPE: &str = "vm_exit_scope()"; - -pub const MEMCPY_ENTER_SCOPE: &str = "vm_enter_scope({'n': ids.len})"; -pub const MEMCPY_CONTINUE_COPYING: &str = r#"n -= 1 -ids.continue_copying = 1 if n > 0 else 0"#; - -pub const MEMSET_ENTER_SCOPE: &str = "vm_enter_scope({'n': ids.n})"; -pub const MEMSET_CONTINUE_LOOP: &str = r#"n -= 1 -ids.continue_loop = 1 if n > 0 else 0"#; - -pub const POW: &str = "ids.locs.bit = (ids.prev_locs.exp % PRIME) & 1"; - -pub const IS_NN: &str = "memory[ap] = 0 if 0 <= (ids.a % PRIME) < range_check_builtin.bound else 1"; -pub const IS_NN_OUT_OF_RANGE: &str = - "memory[ap] = 0 if 0 <= ((-ids.a - 1) % PRIME) < range_check_builtin.bound else 1"; -pub const IS_LE_FELT: &str = "memory[ap] = 0 if (ids.a % PRIME) <= (ids.b % PRIME) else 1"; -pub const IS_POSITIVE: &str = r#"from starkware.cairo.common.math_utils import is_positive +use indoc::indoc; + +use crate::define_hint_string_map; +use crate::stdlib::collections::HashMap; + +define_hint_string_map! { + HINT_CODES, +(ADD_SEGMENT, indoc! {r#"memory[ap] = segments.add()"#}), +(VM_ENTER_SCOPE, indoc! {r#"vm_enter_scope()"#}), +(VM_EXIT_SCOPE, indoc! {r#"vm_exit_scope()"#}), +(MEMCPY_ENTER_SCOPE, indoc! {r#"vm_enter_scope({'n': ids.len})"#}), +(MEMCPY_CONTINUE_COPYING, indoc! {r#"n -= 1 +ids.continue_copying = 1 if n > 0 else 0"#}), +(MEMSET_ENTER_SCOPE, indoc! {r#"vm_enter_scope({'n': ids.n})"#}), +(MEMSET_CONTINUE_LOOP, indoc! {r#"n -= 1 +ids.continue_loop = 1 if n > 0 else 0"#}), +(POW, indoc! {r#"ids.locs.bit = (ids.prev_locs.exp % PRIME) & 1"#}), +(IS_NN, indoc! {r#"memory[ap] = 0 if 0 <= (ids.a % PRIME) < range_check_builtin.bound else 1"#}), +(IS_NN_OUT_OF_RANGE, indoc! {r#"memory[ap] = 0 if 0 <= ((-ids.a - 1) % PRIME) < range_check_builtin.bound else 1"#}), +(IS_LE_FELT, indoc! {r#"memory[ap] = 0 if (ids.a % PRIME) <= (ids.b % PRIME) else 1"#}), +(IS_POSITIVE, indoc! {r#"from starkware.cairo.common.math_utils import is_positive ids.is_positive = 1 if is_positive( - value=ids.value, prime=PRIME, rc_bound=range_check_builtin.bound) else 0"#; - -pub const ASSERT_NN: &str = r#"from starkware.cairo.common.math_utils import assert_integer + value=ids.value, prime=PRIME, rc_bound=range_check_builtin.bound) else 0"#}), +(ASSERT_NN, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer assert_integer(ids.a) -assert 0 <= ids.a % PRIME < range_check_builtin.bound, f'a = {ids.a} is out of range.'"#; - -pub const ASSERT_NOT_ZERO: &str = r#"from starkware.cairo.common.math_utils import assert_integer +assert 0 <= ids.a % PRIME < range_check_builtin.bound, f'a = {ids.a} is out of range.'"#}), +(ASSERT_NOT_ZERO, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer assert_integer(ids.value) -assert ids.value % PRIME != 0, f'assert_not_zero failed: {ids.value} = 0.'"#; - -pub const ASSERT_NOT_EQUAL: &str = r#"from starkware.cairo.lang.vm.relocatable import RelocatableValue +assert ids.value % PRIME != 0, f'assert_not_zero failed: {ids.value} = 0.'"#}), +(ASSERT_NOT_EQUAL, indoc! {r#"from starkware.cairo.lang.vm.relocatable import RelocatableValue both_ints = isinstance(ids.a, int) and isinstance(ids.b, int) both_relocatable = ( isinstance(ids.a, RelocatableValue) and isinstance(ids.b, RelocatableValue) and ids.a.segment_index == ids.b.segment_index) assert both_ints or both_relocatable, \ f'assert_not_equal failed: non-comparable values: {ids.a}, {ids.b}.' -assert (ids.a - ids.b) % PRIME != 0, f'assert_not_equal failed: {ids.a} = {ids.b}.'"#; - -pub const ASSERT_LE_FELT: &str = r#"import itertools +assert (ids.a - ids.b) % PRIME != 0, f'assert_not_equal failed: {ids.a} = {ids.b}.'"#}), +(ASSERT_LE_FELT, indoc! {r#"import itertools from starkware.cairo.common.math_utils import assert_integer assert_integer(ids.a) @@ -56,17 +53,13 @@ excluded = lengths_and_indices[2][1] memory[ids.range_check_ptr + 1], memory[ids.range_check_ptr + 0] = ( divmod(lengths_and_indices[0][0], ids.PRIME_OVER_3_HIGH)) memory[ids.range_check_ptr + 3], memory[ids.range_check_ptr + 2] = ( - divmod(lengths_and_indices[1][0], ids.PRIME_OVER_2_HIGH))"#; - -pub const ASSERT_LE_FELT_V_0_6: &str = - "from starkware.cairo.common.math_utils import assert_integer + divmod(lengths_and_indices[1][0], ids.PRIME_OVER_2_HIGH))"#}), +(ASSERT_LE_FELT_V_0_6, "from starkware.cairo.common.math_utils import assert_integer assert_integer(ids.a) assert_integer(ids.b) assert (ids.a % PRIME) <= (ids.b % PRIME), \\ - f'a = {ids.a % PRIME} is not less than or equal to b = {ids.b % PRIME}.'"; - -pub const ASSERT_LE_FELT_V_0_8: &str = - "from starkware.cairo.common.math_utils import assert_integer + f'a = {ids.a % PRIME} is not less than or equal to b = {ids.b % PRIME}.'"), +(ASSERT_LE_FELT_V_0_8, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer assert_integer(ids.a) assert_integer(ids.b) a = ids.a % PRIME @@ -74,65 +67,52 @@ b = ids.b % PRIME assert a <= b, f'a = {a} is not less than or equal to b = {b}.' ids.small_inputs = int( - a < range_check_builtin.bound and (b - a) < range_check_builtin.bound)"; - -pub const ASSERT_LE_FELT_EXCLUDED_0: &str = "memory[ap] = 1 if excluded != 0 else 0"; -pub const ASSERT_LE_FELT_EXCLUDED_1: &str = "memory[ap] = 1 if excluded != 1 else 0"; -pub const ASSERT_LE_FELT_EXCLUDED_2: &str = "assert excluded == 2"; - -pub const ASSERT_LT_FELT: &str = r#"from starkware.cairo.common.math_utils import assert_integer + a < range_check_builtin.bound and (b - a) < range_check_builtin.bound)"#}), +(ASSERT_LE_FELT_EXCLUDED_0, indoc! {r#"memory[ap] = 1 if excluded != 0 else 0"#}), +(ASSERT_LE_FELT_EXCLUDED_1, indoc! {r#"memory[ap] = 1 if excluded != 1 else 0"#}), +(ASSERT_LE_FELT_EXCLUDED_2, indoc! {r#"assert excluded == 2"#}), +(ASSERT_LT_FELT, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer assert_integer(ids.a) assert_integer(ids.b) assert (ids.a % PRIME) < (ids.b % PRIME), \ - f'a = {ids.a % PRIME} is not less than b = {ids.b % PRIME}.'"#; - -pub const SPLIT_INT_ASSERT_RANGE: &str = - "assert ids.value == 0, 'split_int(): value is out of range.'"; - -pub const ASSERT_250_BITS: &str = r#"from starkware.cairo.common.math_utils import as_int + f'a = {ids.a % PRIME} is not less than b = {ids.b % PRIME}.'"#}), +(SPLIT_INT_ASSERT_RANGE, indoc! {r#"assert ids.value == 0, 'split_int(): value is out of range.'"#}), +(ASSERT_250_BITS, indoc! {r#"from starkware.cairo.common.math_utils import as_int # Correctness check. value = as_int(ids.value, PRIME) % PRIME assert value < ids.UPPER_BOUND, f'{value} is outside of the range [0, 2**250).' # Calculation for the assertion. -ids.high, ids.low = divmod(ids.value, ids.SHIFT)"#; - -pub const IS_250_BITS: &str = r#"ids.is_250 = 1 if ids.addr < 2**250 else 0"#; - -pub const IS_ADDR_BOUNDED: &str = r#"# Verify the assumptions on the relationship between 2**250, ADDR_BOUND and PRIME. +ids.high, ids.low = divmod(ids.value, ids.SHIFT)"#}), +(IS_250_BITS, indoc! {r#"ids.is_250 = 1 if ids.addr < 2**250 else 0"#}), +(IS_ADDR_BOUNDED, indoc! {r#"# Verify the assumptions on the relationship between 2**250, ADDR_BOUND and PRIME. ADDR_BOUND = ids.ADDR_BOUND % PRIME assert (2**250 < ADDR_BOUND <= 2**251) and (2 * 2**250 < PRIME) and ( ADDR_BOUND * 2 > PRIME), \ 'normalize_address() cannot be used with the current constants.' -ids.is_small = 1 if ids.addr < ADDR_BOUND else 0"#; - -pub const SPLIT_INT: &str = r#"memory[ids.output] = res = (int(ids.value) % PRIME) % ids.base -assert res < ids.bound, f'split_int(): Limb {res} is out of range.'"#; - -pub const SPLIT_64: &str = r#"ids.low = ids.a & ((1<<64) - 1) -ids.high = ids.a >> 64"#; - -pub const SPLIT_FELT: &str = r#"from starkware.cairo.common.math_utils import assert_integer +ids.is_small = 1 if ids.addr < ADDR_BOUND else 0"#}), +(SPLIT_INT, indoc! {r#"memory[ids.output] = res = (int(ids.value) % PRIME) % ids.base +assert res < ids.bound, f'split_int(): Limb {res} is out of range.'"#}), +(SPLIT_64, indoc! {r#"ids.low = ids.a & ((1<<64) - 1) +ids.high = ids.a >> 64"#}), +(SPLIT_FELT, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer assert ids.MAX_HIGH < 2**128 and ids.MAX_LOW < 2**128 assert PRIME - 1 == ids.MAX_HIGH * 2**128 + ids.MAX_LOW assert_integer(ids.value) ids.low = ids.value & ((1 << 128) - 1) -ids.high = ids.value >> 128"#; - -pub const SQRT: &str = r#"from starkware.python.math_utils import isqrt +ids.high = ids.value >> 128"#}), +(SQRT, indoc! {r#"from starkware.python.math_utils import isqrt value = ids.value % PRIME assert value < 2 ** 250, f"value={value} is outside of the range [0, 2**250)." assert 2 ** 250 < PRIME -ids.root = isqrt(value)"#; - -pub const UNSIGNED_DIV_REM: &str = r#"from starkware.cairo.common.math_utils import assert_integer +ids.root = isqrt(value)"#}), +(UNSIGNED_DIV_REM, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer assert_integer(ids.div) assert 0 < ids.div <= PRIME // range_check_builtin.bound, \ f'div={hex(ids.div)} is out of the valid range.' -ids.q, ids.r = divmod(ids.value, ids.div)"#; - -pub const SIGNED_DIV_REM: &str = r#"from starkware.cairo.common.math_utils import as_int, assert_integer +ids.q, ids.r = divmod(ids.value, ids.div)"#}), +(SIGNED_DIV_REM, indoc! {r#"from starkware.cairo.common.math_utils import as_int, assert_integer assert_integer(ids.div) assert 0 < ids.div <= PRIME // range_check_builtin.bound, \ @@ -148,18 +128,16 @@ q, ids.r = divmod(int_value, ids.div) assert -ids.bound <= q < ids.bound, \ f'{int_value} / {ids.div} = {q} is out of the range [{-ids.bound}, {ids.bound}).' -ids.biased_q = q + ids.bound"#; - -pub const IS_QUAD_RESIDUE: &str = r#"from starkware.crypto.signature.signature import FIELD_PRIME +ids.biased_q = q + ids.bound"#}), +(IS_QUAD_RESIDUE, indoc! {r#"from starkware.crypto.signature.signature import FIELD_PRIME from starkware.python.math_utils import div_mod, is_quad_residue, sqrt x = ids.x if is_quad_residue(x, FIELD_PRIME): ids.y = sqrt(x, FIELD_PRIME) else: - ids.y = sqrt(div_mod(x, 3, FIELD_PRIME), FIELD_PRIME)"#; - -pub const FIND_ELEMENT: &str = r#"array_ptr = ids.array_ptr + ids.y = sqrt(div_mod(x, 3, FIELD_PRIME), FIELD_PRIME)"#}), +(FIND_ELEMENT, indoc! {r#"array_ptr = ids.array_ptr elm_size = ids.elm_size assert isinstance(elm_size, int) and elm_size > 0, \ f'Invalid value for elm_size. Got: {elm_size}.' @@ -187,9 +165,8 @@ else: ids.index = i break else: - raise ValueError(f'Key {key} was not found.')"#; - -pub const SEARCH_SORTED_LOWER: &str = r#"array_ptr = ids.array_ptr + raise ValueError(f'Key {key} was not found.')"#}), +(SEARCH_SORTED_LOWER, indoc! {r#"array_ptr = ids.array_ptr elm_size = ids.elm_size assert isinstance(elm_size, int) and elm_size > 0, \ f'Invalid value for elm_size. Got: {elm_size}.' @@ -207,9 +184,8 @@ for i in range(n_elms): ids.index = i break else: - ids.index = n_elms"#; - -pub const SET_ADD: &str = r#"assert ids.elm_size > 0 + ids.index = n_elms"#}), +(SET_ADD, indoc! {r#"assert ids.elm_size > 0 assert ids.set_ptr <= ids.set_end_ptr elm_list = memory.get_range(ids.elm_ptr, ids.elm_size) for i in range(0, ids.set_end_ptr - ids.set_ptr, ids.elm_size): @@ -218,31 +194,26 @@ for i in range(0, ids.set_end_ptr - ids.set_ptr, ids.elm_size): ids.is_elm_in_set = 1 break else: - ids.is_elm_in_set = 0"#; - -pub const DEFAULT_DICT_NEW: &str = r#"if '__dict_manager' not in globals(): + ids.is_elm_in_set = 0"#}), +(DEFAULT_DICT_NEW, indoc! {r#"if '__dict_manager' not in globals(): from starkware.cairo.common.dict import DictManager __dict_manager = DictManager() -memory[ap] = __dict_manager.new_default_dict(segments, ids.default_value)"#; - -pub const DICT_NEW: &str = r#"if '__dict_manager' not in globals(): +memory[ap] = __dict_manager.new_default_dict(segments, ids.default_value)"#}), +(DICT_NEW, indoc! {r#"if '__dict_manager' not in globals(): from starkware.cairo.common.dict import DictManager __dict_manager = DictManager() memory[ap] = __dict_manager.new_dict(segments, initial_dict) -del initial_dict"#; - -pub const DICT_READ: &str = r#"dict_tracker = __dict_manager.get_tracker(ids.dict_ptr) +del initial_dict"#}), +(DICT_READ, indoc! {r#"dict_tracker = __dict_manager.get_tracker(ids.dict_ptr) dict_tracker.current_ptr += ids.DictAccess.SIZE -ids.value = dict_tracker.data[ids.key]"#; - -pub const DICT_WRITE: &str = r#"dict_tracker = __dict_manager.get_tracker(ids.dict_ptr) +ids.value = dict_tracker.data[ids.key]"#}), +(DICT_WRITE, indoc! {r#"dict_tracker = __dict_manager.get_tracker(ids.dict_ptr) dict_tracker.current_ptr += ids.DictAccess.SIZE ids.dict_ptr.prev_value = dict_tracker.data[ids.key] -dict_tracker.data[ids.key] = ids.new_value"#; - -pub const DICT_UPDATE: &str = r#"# Verify dict pointer and prev value. +dict_tracker.data[ids.key] = ids.new_value"#}), +(DICT_UPDATE, indoc! {r#"# Verify dict pointer and prev value. dict_tracker = __dict_manager.get_tracker(ids.dict_ptr) current_value = dict_tracker.data[ids.key] assert current_value == ids.prev_value, \ @@ -250,9 +221,8 @@ assert current_value == ids.prev_value, \ # Update value. dict_tracker.data[ids.key] = ids.new_value -dict_tracker.current_ptr += ids.DictAccess.SIZE"#; - -pub const SQUASH_DICT: &str = r#"dict_access_size = ids.DictAccess.SIZE +dict_tracker.current_ptr += ids.DictAccess.SIZE"#}), +(SQUASH_DICT, indoc! {r#"dict_access_size = ids.DictAccess.SIZE address = ids.dict_accesses.address_ assert ids.ptr_diff % dict_access_size == 0, \ 'Accesses array size must be divisible by DictAccess.SIZE' @@ -270,53 +240,41 @@ for i in range(n_accesses): keys = sorted(access_indices.keys(), reverse=True) # Are the keys used bigger than range_check bound. ids.big_keys = 1 if keys[0] >= range_check_builtin.bound else 0 -ids.first_key = key = keys.pop()"#; - -pub const SQUASH_DICT_INNER_SKIP_LOOP: &str = - "ids.should_skip_loop = 0 if current_access_indices else 1"; -pub const SQUASH_DICT_INNER_FIRST_ITERATION: &str = r#"current_access_indices = sorted(access_indices[key])[::-1] +ids.first_key = key = keys.pop()"#}), +(SQUASH_DICT_INNER_SKIP_LOOP, indoc! {r#"ids.should_skip_loop = 0 if current_access_indices else 1"#}), +(SQUASH_DICT_INNER_FIRST_ITERATION, indoc! {r#"current_access_indices = sorted(access_indices[key])[::-1] current_access_index = current_access_indices.pop() -memory[ids.range_check_ptr] = current_access_index"#; - -pub const SQUASH_DICT_INNER_CHECK_ACCESS_INDEX: &str = r#"new_access_index = current_access_indices.pop() +memory[ids.range_check_ptr] = current_access_index"#}), +(SQUASH_DICT_INNER_CHECK_ACCESS_INDEX, indoc! {r#"new_access_index = current_access_indices.pop() ids.loop_temps.index_delta_minus1 = new_access_index - current_access_index - 1 -current_access_index = new_access_index"#; - -pub const SQUASH_DICT_INNER_CONTINUE_LOOP: &str = - "ids.loop_temps.should_continue = 1 if current_access_indices else 0"; -pub const SQUASH_DICT_INNER_ASSERT_LEN_KEYS: &str = "assert len(keys) == 0"; -pub const SQUASH_DICT_INNER_LEN_ASSERT: &str = "assert len(current_access_indices) == 0"; -pub const SQUASH_DICT_INNER_USED_ACCESSES_ASSERT: &str = - "assert ids.n_used_accesses == len(access_indices[key])"; -pub const SQUASH_DICT_INNER_NEXT_KEY: &str = r#"assert len(keys) > 0, 'No keys left but remaining_accesses > 0.' -ids.next_key = key = keys.pop()"#; - -pub const DICT_SQUASH_COPY_DICT: &str = r#"# Prepare arguments for dict_new. In particular, the same dictionary values should be copied +current_access_index = new_access_index"#}), +(SQUASH_DICT_INNER_CONTINUE_LOOP, indoc! {r#"ids.loop_temps.should_continue = 1 if current_access_indices else 0"#}), +(SQUASH_DICT_INNER_ASSERT_LEN_KEYS, indoc! {r#"assert len(keys) == 0"#}), +(SQUASH_DICT_INNER_LEN_ASSERT, indoc! {r#"assert len(current_access_indices) == 0"#}), +(SQUASH_DICT_INNER_USED_ACCESSES_ASSERT, indoc! {r#"assert ids.n_used_accesses == len(access_indices[key])"#}), +(SQUASH_DICT_INNER_NEXT_KEY, indoc! {r#"assert len(keys) > 0, 'No keys left but remaining_accesses > 0.' +ids.next_key = key = keys.pop()"#}), +(DICT_SQUASH_COPY_DICT, indoc! {r#"# Prepare arguments for dict_new. In particular, the same dictionary values should be copied # to the new (squashed) dictionary. vm_enter_scope({ # Make __dict_manager accessible. '__dict_manager': __dict_manager, # Create a copy of the dict, in case it changes in the future. 'initial_dict': dict(__dict_manager.get_dict(ids.dict_accesses_end)), -})"#; - -pub const DICT_SQUASH_UPDATE_PTR: &str = r#"# Update the DictTracker's current_ptr to point to the end of the squashed dict. +})"#}), +(DICT_SQUASH_UPDATE_PTR, indoc! {r#"# Update the DictTracker's current_ptr to point to the end of the squashed dict. __dict_manager.get_tracker(ids.squashed_dict_start).current_ptr = \ - ids.squashed_dict_end.address_"#; - -pub const BIGINT_TO_UINT256: &str = "ids.low = (ids.x.d0 + ids.x.d1 * ids.BASE) & ((1 << 128) - 1)"; -pub const UINT256_ADD: &str = r#"sum_low = ids.a.low + ids.b.low + ids.squashed_dict_end.address_"#}), +(BIGINT_TO_UINT256, indoc! {r#"ids.low = (ids.x.d0 + ids.x.d1 * ids.BASE) & ((1 << 128) - 1)"#}), +(UINT256_ADD, indoc! {r#"sum_low = ids.a.low + ids.b.low ids.carry_low = 1 if sum_low >= ids.SHIFT else 0 sum_high = ids.a.high + ids.b.high + ids.carry_low -ids.carry_high = 1 if sum_high >= ids.SHIFT else 0"#; - -pub const UINT256_ADD_LOW: &str = r#"sum_low = ids.a.low + ids.b.low -ids.carry_low = 1 if sum_low >= ids.SHIFT else 0"#; - -pub const UINT128_ADD: &str = r#"res = ids.a + ids.b -ids.carry = 1 if res >= ids.SHIFT else 0"#; - -pub const UINT256_SUB: &str = r#"def split(num: int, num_bits_shift: int = 128, length: int = 2): +ids.carry_high = 1 if sum_high >= ids.SHIFT else 0"#}), +(UINT256_ADD_LOW, indoc! {r#"sum_low = ids.a.low + ids.b.low +ids.carry_low = 1 if sum_low >= ids.SHIFT else 0"#}), +(UINT128_ADD, indoc! {r#"res = ids.a + ids.b +ids.carry = 1 if res >= ids.SHIFT else 0"#}), +(UINT256_SUB, indoc! {r#"def split(num: int, num_bits_shift: int = 128, length: int = 2): a = [] for _ in range(length): a.append( num & ((1 << num_bits_shift) - 1) ) @@ -332,42 +290,36 @@ b = pack(ids.b) res = (a - b)%2**256 res_split = split(res) ids.res.low = res_split[0] -ids.res.high = res_split[1]"#; - -pub const UINT256_SQRT: &str = r#"from starkware.python.math_utils import isqrt +ids.res.high = res_split[1]"#}), +(UINT256_SQRT, indoc! {r#"from starkware.python.math_utils import isqrt n = (ids.n.high << 128) + ids.n.low root = isqrt(n) assert 0 <= root < 2 ** 128 ids.root.low = root -ids.root.high = 0"#; - -pub const UINT256_SQRT_FELT: &str = r#"from starkware.python.math_utils import isqrt +ids.root.high = 0"#}), +(UINT256_SQRT_FELT, indoc! {r#"from starkware.python.math_utils import isqrt n = (ids.n.high << 128) + ids.n.low root = isqrt(n) assert 0 <= root < 2 ** 128 -ids.root = root"#; - -pub const UINT256_SIGNED_NN: &str = "memory[ap] = 1 if 0 <= (ids.a.high % PRIME) < 2 ** 127 else 0"; - -pub const UINT256_UNSIGNED_DIV_REM: &str = r#"a = (ids.a.high << 128) + ids.a.low +ids.root = root"#}), +(UINT256_SIGNED_NN, indoc! {r#"memory[ap] = 1 if 0 <= (ids.a.high % PRIME) < 2 ** 127 else 0"#}), +(UINT256_UNSIGNED_DIV_REM, indoc! {r#"a = (ids.a.high << 128) + ids.a.low div = (ids.div.high << 128) + ids.div.low quotient, remainder = divmod(a, div) ids.quotient.low = quotient & ((1 << 128) - 1) ids.quotient.high = quotient >> 128 ids.remainder.low = remainder & ((1 << 128) - 1) -ids.remainder.high = remainder >> 128"#; - -pub const UINT256_EXPANDED_UNSIGNED_DIV_REM: &str = r#"a = (ids.a.high << 128) + ids.a.low +ids.remainder.high = remainder >> 128"#}), +(UINT256_EXPANDED_UNSIGNED_DIV_REM, indoc! {r#"a = (ids.a.high << 128) + ids.a.low div = (ids.div.b23 << 128) + ids.div.b01 quotient, remainder = divmod(a, div) ids.quotient.low = quotient & ((1 << 128) - 1) ids.quotient.high = quotient >> 128 ids.remainder.low = remainder & ((1 << 128) - 1) -ids.remainder.high = remainder >> 128"#; - -pub const UINT256_MUL_DIV_MOD: &str = r#"a = (ids.a.high << 128) + ids.a.low +ids.remainder.high = remainder >> 128"#}), +(UINT256_MUL_DIV_MOD, indoc! {r#"a = (ids.a.high << 128) + ids.a.low b = (ids.b.high << 128) + ids.b.low div = (ids.div.high << 128) + ids.div.low quotient, remainder = divmod(a * b, div) @@ -377,11 +329,9 @@ ids.quotient_low.high = (quotient >> 128) & ((1 << 128) - 1) ids.quotient_high.low = (quotient >> 256) & ((1 << 128) - 1) ids.quotient_high.high = quotient >> 384 ids.remainder.low = remainder & ((1 << 128) - 1) -ids.remainder.high = remainder >> 128"#; - -pub const USORT_ENTER_SCOPE: &str = - "vm_enter_scope(dict(__usort_max_size = globals().get('__usort_max_size')))"; -pub const USORT_BODY: &str = r#"from collections import defaultdict +ids.remainder.high = remainder >> 128"#}), +(USORT_ENTER_SCOPE, indoc! {r#"vm_enter_scope(dict(__usort_max_size = globals().get('__usort_max_size')))"#}), +(USORT_BODY, indoc! {r#"from collections import defaultdict input_ptr = ids.input input_len = int(ids.input_len) @@ -399,20 +349,16 @@ for i in range(input_len): output = sorted(positions_dict.keys()) ids.output_len = len(output) ids.output = segments.gen_arg(output) -ids.multiplicities = segments.gen_arg([len(positions_dict[k]) for k in output])"#; - -pub const USORT_VERIFY: &str = r#"last_pos = 0 -positions = positions_dict[ids.value][::-1]"#; - -pub const USORT_VERIFY_MULTIPLICITY_ASSERT: &str = "assert len(positions) == 0"; -pub const USORT_VERIFY_MULTIPLICITY_BODY: &str = r#"current_pos = positions.pop() +ids.multiplicities = segments.gen_arg([len(positions_dict[k]) for k in output])"#}), +(USORT_VERIFY, indoc! {r#"last_pos = 0 +positions = positions_dict[ids.value][::-1]"#}), +(USORT_VERIFY_MULTIPLICITY_ASSERT, indoc! {r#"assert len(positions) == 0"#}), +(USORT_VERIFY_MULTIPLICITY_BODY, indoc! {r#"current_pos = positions.pop() ids.next_item_index = current_pos - last_pos -last_pos = current_pos + 1"#; - -pub const BLAKE2S_COMPUTE: &str = r#"from starkware.cairo.common.cairo_blake2s.blake2s_utils import compute_blake2s_func -compute_blake2s_func(segments=segments, output_ptr=ids.output)"#; - -pub const BLAKE2S_FINALIZE: &str = r#"# Add dummy pairs of input and output. +last_pos = current_pos + 1"#}), +(BLAKE2S_COMPUTE, indoc! {r#"from starkware.cairo.common.cairo_blake2s.blake2s_utils import compute_blake2s_func +compute_blake2s_func(segments=segments, output_ptr=ids.output)"#}), +(BLAKE2S_FINALIZE, indoc! {r#"# Add dummy pairs of input and output. from starkware.cairo.common.cairo_blake2s.blake2s_utils import IV, blake2s_compress _n_packed_instances = int(ids.N_PACKED_INSTANCES) @@ -431,9 +377,8 @@ output = blake2s_compress( f1=0, ) padding = (modified_iv + message + [0, 0xffffffff] + output) * (_n_packed_instances - 1) -segments.write_arg(ids.blake2s_ptr_end, padding)"#; - -pub const BLAKE2S_FINALIZE_V2: &str = r#"# Add dummy pairs of input and output. +segments.write_arg(ids.blake2s_ptr_end, padding)"#}), +(BLAKE2S_FINALIZE_V2, indoc! {r#"# Add dummy pairs of input and output. from starkware.cairo.common.cairo_blake2s.blake2s_utils import IV, blake2s_compress _n_packed_instances = int(ids.N_PACKED_INSTANCES) @@ -452,9 +397,8 @@ output = blake2s_compress( f1=0, ) padding = (modified_iv + message + [0, 0xffffffff] + output) * (_n_packed_instances - 1) -segments.write_arg(ids.blake2s_ptr_end, padding)"#; - -pub const BLAKE2S_FINALIZE_V3: &str = r#"# Add dummy pairs of input and output. +segments.write_arg(ids.blake2s_ptr_end, padding)"#}), +(BLAKE2S_FINALIZE_V3, indoc! {r#"# Add dummy pairs of input and output. from starkware.cairo.common.cairo_blake2s.blake2s_utils import IV, blake2s_compress _n_packed_instances = int(ids.N_PACKED_INSTANCES) @@ -473,19 +417,16 @@ output = blake2s_compress( f1=0, ) padding = (message + modified_iv + [0, 0xffffffff] + output) * (_n_packed_instances - 1) -segments.write_arg(ids.blake2s_ptr_end, padding)"#; - -pub const BLAKE2S_ADD_UINT256: &str = r#"B = 32 +segments.write_arg(ids.blake2s_ptr_end, padding)"#}), +(BLAKE2S_ADD_UINT256, indoc! {r#"B = 32 MASK = 2 ** 32 - 1 segments.write_arg(ids.data, [(ids.low >> (B * i)) & MASK for i in range(4)]) -segments.write_arg(ids.data + 4, [(ids.high >> (B * i)) & MASK for i in range(4)])"#; - -pub const BLAKE2S_ADD_UINT256_BIGEND: &str = r#"B = 32 +segments.write_arg(ids.data + 4, [(ids.high >> (B * i)) & MASK for i in range(4)])"#}), +(BLAKE2S_ADD_UINT256_BIGEND, indoc! {r#"B = 32 MASK = 2 ** 32 - 1 segments.write_arg(ids.data, [(ids.high >> (B * (3 - i))) & MASK for i in range(4)]) -segments.write_arg(ids.data + 4, [(ids.low >> (B * (3 - i))) & MASK for i in range(4)])"#; - -pub const EXAMPLE_BLAKE2S_COMPRESS: &str = r#"from starkware.cairo.common.cairo_blake2s.blake2s_utils import IV, blake2s_compress +segments.write_arg(ids.data + 4, [(ids.low >> (B * (3 - i))) & MASK for i in range(4)])"#}), +(EXAMPLE_BLAKE2S_COMPRESS, indoc! {r#"from starkware.cairo.common.cairo_blake2s.blake2s_utils import IV, blake2s_compress _blake2s_input_chunk_size_felts = int(ids.BLAKE2S_INPUT_CHUNK_SIZE_FELTS) assert 0 <= _blake2s_input_chunk_size_felts < 100 @@ -499,52 +440,42 @@ new_state = blake2s_compress( f1=0, ) -segments.write_arg(ids.output, new_state)"#; - -pub const NONDET_BIGINT3_V1: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import split - -segments.write_arg(ids.res.address_, split(value))"#; +segments.write_arg(ids.output, new_state)"#}), +(NONDET_BIGINT3_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import split -pub const NONDET_BIGINT3_V2: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import split -segments.write_arg(ids.res.address_, split(value))"#; - -pub const VERIFY_ZERO_V1: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +segments.write_arg(ids.res.address_, split(value))"#}), +(NONDET_BIGINT3_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import split +segments.write_arg(ids.res.address_, split(value))"#}), +(VERIFY_ZERO_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack q, r = divmod(pack(ids.val, PRIME), SECP_P) assert r == 0, f"verify_zero: Invalid input {ids.val.d0, ids.val.d1, ids.val.d2}." -ids.q = q % PRIME"#; - -pub const VERIFY_ZERO_V2: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P +ids.q = q % PRIME"#}), +(VERIFY_ZERO_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P q, r = divmod(pack(ids.val, PRIME), SECP_P) assert r == 0, f"verify_zero: Invalid input {ids.val.d0, ids.val.d1, ids.val.d2}." -ids.q = q % PRIME"#; - -pub const VERIFY_ZERO_V3: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +ids.q = q % PRIME"#}), +(VERIFY_ZERO_V3, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack SECP_P = 2**255-19 to_assert = pack(ids.val, PRIME) q, r = divmod(pack(ids.val, PRIME), SECP_P) assert r == 0, f"verify_zero: Invalid input {ids.val.d0, ids.val.d1, ids.val.d2}." -ids.q = q % PRIME"#; - -pub const VERIFY_ZERO_EXTERNAL_SECP: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +ids.q = q % PRIME"#}), +(VERIFY_ZERO_EXTERNAL_SECP, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack q, r = divmod(pack(ids.val, PRIME), SECP_P) assert r == 0, f"verify_zero: Invalid input {ids.val.d0, ids.val.d1, ids.val.d2}." -ids.q = q % PRIME"#; - -pub const REDUCE_V1: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack - -value = pack(ids.x, PRIME) % SECP_P"#; - -pub const REDUCE_V2: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack -value = pack(ids.x, PRIME) % SECP_P"#; +ids.q = q % PRIME"#}), +(REDUCE_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack -pub const REDUCE_ED25519: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = pack(ids.x, PRIME) % SECP_P"#}), +(REDUCE_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = pack(ids.x, PRIME) % SECP_P"#}), +(REDUCE_ED25519, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack SECP_P=2**255-19 -value = pack(ids.x, PRIME) % SECP_P"#; - -pub const UNSAFE_KECCAK: &str = r#"from eth_hash.auto import keccak +value = pack(ids.x, PRIME) % SECP_P"#}), +(UNSAFE_KECCAK, indoc! {r#"from eth_hash.auto import keccak data, length = ids.data, ids.length @@ -562,72 +493,58 @@ for word_i, byte_i in enumerate(range(0, length, 16)): hashed = keccak(keccak_input) ids.high = int.from_bytes(hashed[:16], 'big') -ids.low = int.from_bytes(hashed[16:32], 'big')"#; - -pub const UNSAFE_KECCAK_FINALIZE: &str = r#"from eth_hash.auto import keccak +ids.low = int.from_bytes(hashed[16:32], 'big')"#}), +(UNSAFE_KECCAK_FINALIZE, indoc! {r#"from eth_hash.auto import keccak keccak_input = bytearray() n_elms = ids.keccak_state.end_ptr - ids.keccak_state.start_ptr for word in memory.get_range(ids.keccak_state.start_ptr, n_elms): keccak_input += word.to_bytes(16, 'big') hashed = keccak(keccak_input) ids.high = int.from_bytes(hashed[:16], 'big') -ids.low = int.from_bytes(hashed[16:32], 'big')"#; - -pub const IS_ZERO_NONDET: &str = "memory[ap] = to_felt_or_relocatable(x == 0)"; -pub const IS_ZERO_INT: &str = "memory[ap] = int(x == 0)"; -pub const IS_ZERO_PACK_V1: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack - -x = pack(ids.x, PRIME) % SECP_P"#; - -pub const IS_ZERO_PACK_V2: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack -x = pack(ids.x, PRIME) % SECP_P"#; - -pub const IS_ZERO_PACK_EXTERNAL_SECP_V1: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack - -x = pack(ids.x, PRIME) % SECP_P"#; - -pub const IS_ZERO_PACK_EXTERNAL_SECP_V2: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack -x = pack(ids.x, PRIME) % SECP_P"#; - -pub const IS_ZERO_PACK_ED25519: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +ids.low = int.from_bytes(hashed[16:32], 'big')"#}), +(IS_ZERO_NONDET, indoc! {r#"memory[ap] = to_felt_or_relocatable(x == 0)"#}), +(IS_ZERO_INT, indoc! {r#"memory[ap] = int(x == 0)"#}), +(IS_ZERO_PACK_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack + +x = pack(ids.x, PRIME) % SECP_P"#}), +(IS_ZERO_PACK_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +x = pack(ids.x, PRIME) % SECP_P"#}), +(IS_ZERO_PACK_EXTERNAL_SECP_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack + +x = pack(ids.x, PRIME) % SECP_P"#}), +(IS_ZERO_PACK_EXTERNAL_SECP_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +x = pack(ids.x, PRIME) % SECP_P"#}), +(IS_ZERO_PACK_ED25519, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack SECP_P=2**255-19 -x = pack(ids.x, PRIME) % SECP_P"#; - -pub const IS_ZERO_ASSIGN_SCOPE_VARS: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P +x = pack(ids.x, PRIME) % SECP_P"#}), +(IS_ZERO_ASSIGN_SCOPE_VARS, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P from starkware.python.math_utils import div_mod -value = x_inv = div_mod(1, x, SECP_P)"#; +value = x_inv = div_mod(1, x, SECP_P)"#}), +(IS_ZERO_ASSIGN_SCOPE_VARS_EXTERNAL_SECP, indoc! {r#"from starkware.python.math_utils import div_mod -pub const IS_ZERO_ASSIGN_SCOPE_VARS_EXTERNAL_SECP: &str = r#"from starkware.python.math_utils import div_mod - -value = x_inv = div_mod(1, x, SECP_P)"#; - -pub const IS_ZERO_ASSIGN_SCOPE_VARS_ED25519: &str = r#"SECP_P=2**255-19 +value = x_inv = div_mod(1, x, SECP_P)"#}), +(IS_ZERO_ASSIGN_SCOPE_VARS_ED25519, indoc! {r#"SECP_P=2**255-19 from starkware.python.math_utils import div_mod -value = x_inv = div_mod(1, x, SECP_P)"#; - -pub const DIV_MOD_N_PACKED_DIVMOD_V1: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import N, pack +value = x_inv = div_mod(1, x, SECP_P)"#}), +(DIV_MOD_N_PACKED_DIVMOD_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import N, pack from starkware.python.math_utils import div_mod, safe_div a = pack(ids.a, PRIME) b = pack(ids.b, PRIME) -value = res = div_mod(a, b, N)"#; - -pub const DIV_MOD_N_PACKED_DIVMOD_EXTERNAL_N: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = res = div_mod(a, b, N)"#}), +(DIV_MOD_N_PACKED_DIVMOD_EXTERNAL_N, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack from starkware.python.math_utils import div_mod, safe_div a = pack(ids.a, PRIME) b = pack(ids.b, PRIME) -value = res = div_mod(a, b, N)"#; - -pub const DIV_MOD_N_SAFE_DIV: &str = r#"value = k = safe_div(res * b - a, N)"#; - -pub const GET_FELT_BIT_LENGTH: &str = r#"x = ids.x -ids.bit_length = x.bit_length()"#; - -pub const BIGINT_PACK_DIV_MOD: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = res = div_mod(a, b, N)"#}), +(DIV_MOD_N_SAFE_DIV, indoc! {r#"value = k = safe_div(res * b - a, N)"#}), +(GET_FELT_BIT_LENGTH, indoc! {r#"x = ids.x +ids.bit_length = x.bit_length()"#}), +(BIGINT_PACK_DIV_MOD, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack from starkware.cairo.common.math_utils import as_int from starkware.python.math_utils import div_mod, safe_div @@ -635,16 +552,12 @@ p = pack(ids.P, PRIME) x = pack(ids.x, PRIME) + as_int(ids.x.d3, PRIME) * ids.BASE ** 3 + as_int(ids.x.d4, PRIME) * ids.BASE ** 4 y = pack(ids.y, PRIME) -value = res = div_mod(x, y, p)"#; - -pub const BIGINT_SAFE_DIV: &str = r#"k = safe_div(res * y - x, p) +value = res = div_mod(x, y, p)"#}), +(BIGINT_SAFE_DIV, indoc! {r#"k = safe_div(res * y - x, p) value = k if k > 0 else 0 - k -ids.flag = 1 if k > 0 else 0"#; - -pub const DIV_MOD_N_SAFE_DIV_PLUS_ONE: &str = - r#"value = k_plus_one = safe_div(res * b - a, N) + 1"#; - -pub const GET_POINT_FROM_X: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +ids.flag = 1 if k > 0 else 0"#}), +(DIV_MOD_N_SAFE_DIV_PLUS_ONE, indoc! {r#"value = k_plus_one = safe_div(res * b - a, N) + 1"#}), +(GET_POINT_FROM_X, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack x_cube_int = pack(ids.x_cube, PRIME) % SECP_P y_square_int = (x_cube_int + ids.BETA) % SECP_P @@ -654,64 +567,56 @@ y = pow(y_square_int, (SECP_P + 1) // 4, SECP_P) if ids.v % 2 == y % 2: value = y else: - value = (-y) % SECP_P"#; - -pub const EC_NEGATE: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack + value = (-y) % SECP_P"#}), +(EC_NEGATE, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack y = pack(ids.point.y, PRIME) % SECP_P # The modulo operation in python always returns a nonnegative number. -value = (-y) % SECP_P"#; - -pub const EC_NEGATE_EMBEDDED_SECP: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = (-y) % SECP_P"#}), +(EC_NEGATE_EMBEDDED_SECP, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack SECP_P = 2**255-19 y = pack(ids.point.y, PRIME) % SECP_P # The modulo operation in python always returns a nonnegative number. -value = (-y) % SECP_P"#; - -pub const EC_DOUBLE_SLOPE_V1: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +value = (-y) % SECP_P"#}), +(EC_DOUBLE_SLOPE_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack from starkware.python.math_utils import ec_double_slope # Compute the slope. x = pack(ids.point.x, PRIME) y = pack(ids.point.y, PRIME) -value = slope = ec_double_slope(point=(x, y), alpha=0, p=SECP_P)"#; - -pub const EC_DOUBLE_SLOPE_V2: &str = r#"from starkware.python.math_utils import ec_double_slope +value = slope = ec_double_slope(point=(x, y), alpha=0, p=SECP_P)"#}), +(EC_DOUBLE_SLOPE_V2, indoc! {r#"from starkware.python.math_utils import ec_double_slope from starkware.cairo.common.cairo_secp.secp_utils import pack SECP_P = 2**255-19 # Compute the slope. x = pack(ids.point.x, PRIME) y = pack(ids.point.y, PRIME) -value = slope = ec_double_slope(point=(x, y), alpha=42204101795669822316448953119945047945709099015225996174933988943478124189485, p=SECP_P)"#; - -pub const EC_DOUBLE_SLOPE_V3: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +value = slope = ec_double_slope(point=(x, y), alpha=42204101795669822316448953119945047945709099015225996174933988943478124189485, p=SECP_P)"#}), +(EC_DOUBLE_SLOPE_V3, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack from starkware.python.math_utils import div_mod # Compute the slope. x = pack(ids.pt.x, PRIME) y = pack(ids.pt.y, PRIME) -value = slope = div_mod(3 * x ** 2, 2 * y, SECP_P)"#; - -pub const EC_DOUBLE_SLOPE_V4: &str = r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_ALPHA, SECP256R1_P +value = slope = div_mod(3 * x ** 2, 2 * y, SECP_P)"#}), +(EC_DOUBLE_SLOPE_V4, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_ALPHA, SECP256R1_P from starkware.cairo.common.cairo_secp.secp_utils import pack from starkware.python.math_utils import ec_double_slope # Compute the slope. x = pack(ids.point.x, SECP256R1_P) y = pack(ids.point.y, SECP256R1_P) -value = slope = ec_double_slope(point=(x, y), alpha=SECP256R1_ALPHA, p=SECP256R1_P)"#; - -pub const EC_DOUBLE_SLOPE_EXTERNAL_CONSTS: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = slope = ec_double_slope(point=(x, y), alpha=SECP256R1_ALPHA, p=SECP256R1_P)"#}), +(EC_DOUBLE_SLOPE_EXTERNAL_CONSTS, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack from starkware.python.math_utils import ec_double_slope # Compute the slope. x = pack(ids.point.x, PRIME) y = pack(ids.point.y, PRIME) -value = slope = ec_double_slope(point=(x, y), alpha=ALPHA, p=SECP_P)"#; - -pub const COMPUTE_SLOPE_V1: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +value = slope = ec_double_slope(point=(x, y), alpha=ALPHA, p=SECP_P)"#}), +(COMPUTE_SLOPE_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack from starkware.python.math_utils import line_slope # Compute the slope. @@ -719,9 +624,8 @@ x0 = pack(ids.point0.x, PRIME) y0 = pack(ids.point0.y, PRIME) x1 = pack(ids.point1.x, PRIME) y1 = pack(ids.point1.y, PRIME) -value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP_P)"#; - -pub const COMPUTE_SLOPE_V2: &str = r#"from starkware.python.math_utils import line_slope +value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP_P)"#}), +(COMPUTE_SLOPE_V2, indoc! {r#"from starkware.python.math_utils import line_slope from starkware.cairo.common.cairo_secp.secp_utils import pack SECP_P = 2**255-19 # Compute the slope. @@ -729,9 +633,8 @@ x0 = pack(ids.point0.x, PRIME) y0 = pack(ids.point0.y, PRIME) x1 = pack(ids.point1.x, PRIME) y1 = pack(ids.point1.y, PRIME) -value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP_P)"#; - -pub const COMPUTE_SLOPE_SECP256R1_V1: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP_P)"#}), +(COMPUTE_SLOPE_SECP256R1_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack from starkware.python.math_utils import line_slope # Compute the slope. @@ -739,9 +642,8 @@ x0 = pack(ids.point0.x, PRIME) y0 = pack(ids.point0.y, PRIME) x1 = pack(ids.point1.x, PRIME) y1 = pack(ids.point1.y, PRIME) -value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP_P)"#; - -pub const COMPUTE_SLOPE_SECP256R1_V2: &str = r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P +value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP_P)"#}), +(COMPUTE_SLOPE_SECP256R1_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P from starkware.cairo.common.cairo_secp.secp_utils import pack from starkware.python.math_utils import line_slope @@ -750,12 +652,9 @@ x0 = pack(ids.point0.x, PRIME) y0 = pack(ids.point0.y, PRIME) x1 = pack(ids.point1.x, PRIME) y1 = pack(ids.point1.y, PRIME) -value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP256R1_P)"#; - -pub const IMPORT_SECP256R1_P: &str = - "from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P as SECP_P"; - -pub const COMPUTE_SLOPE_WHITELIST: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP256R1_P)"#}), +(IMPORT_SECP256R1_P, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P as SECP_P"#}), +(COMPUTE_SLOPE_WHITELIST, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack from starkware.python.math_utils import div_mod # Compute the slope. @@ -763,46 +662,39 @@ x0 = pack(ids.pt0.x, PRIME) y0 = pack(ids.pt0.y, PRIME) x1 = pack(ids.pt1.x, PRIME) y1 = pack(ids.pt1.y, PRIME) -value = slope = div_mod(y0 - y1, x0 - x1, SECP_P)"#; - -pub const EC_DOUBLE_ASSIGN_NEW_X_V1: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +value = slope = div_mod(y0 - y1, x0 - x1, SECP_P)"#}), +(EC_DOUBLE_ASSIGN_NEW_X_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack slope = pack(ids.slope, PRIME) x = pack(ids.point.x, PRIME) y = pack(ids.point.y, PRIME) -value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#; - -pub const EC_DOUBLE_ASSIGN_NEW_X_V2: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#}), +(EC_DOUBLE_ASSIGN_NEW_X_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack slope = pack(ids.slope, PRIME) x = pack(ids.point.x, PRIME) y = pack(ids.point.y, PRIME) -value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#; - -pub const EC_DOUBLE_ASSIGN_NEW_X_V3: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#}), +(EC_DOUBLE_ASSIGN_NEW_X_V3, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack SECP_P = 2**255-19 slope = pack(ids.slope, PRIME) x = pack(ids.point.x, PRIME) y = pack(ids.point.y, PRIME) -value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#; - -pub const EC_DOUBLE_ASSIGN_NEW_X_V4: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#}), +(EC_DOUBLE_ASSIGN_NEW_X_V4, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack slope = pack(ids.slope, PRIME) x = pack(ids.pt.x, PRIME) y = pack(ids.pt.y, PRIME) -value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#; - -pub const EC_DOUBLE_ASSIGN_NEW_Y: &str = r#"value = new_y = (slope * (x - new_x) - y) % SECP_P"#; - -pub const SHA256_INPUT: &str = r#"ids.full_word = int(ids.n_bytes >= 4)"#; - -pub const SHA256_MAIN_CONSTANT_INPUT_LENGTH: &str = r#"from starkware.cairo.common.cairo_sha256.sha256_utils import ( +value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#}), +(EC_DOUBLE_ASSIGN_NEW_Y, indoc! {r#"value = new_y = (slope * (x - new_x) - y) % SECP_P"#}), +(SHA256_INPUT, indoc! {r#"ids.full_word = int(ids.n_bytes >= 4)"#}), +(SHA256_MAIN_CONSTANT_INPUT_LENGTH, indoc! {r#"from starkware.cairo.common.cairo_sha256.sha256_utils import ( IV, compute_message_schedule, sha2_compress_function) _sha256_input_chunk_size_felts = int(ids.SHA256_INPUT_CHUNK_SIZE_FELTS) @@ -811,9 +703,8 @@ assert 0 <= _sha256_input_chunk_size_felts < 100 w = compute_message_schedule(memory.get_range( ids.sha256_start, _sha256_input_chunk_size_felts)) new_state = sha2_compress_function(IV, w) -segments.write_arg(ids.output, new_state)"#; - -pub const SHA256_MAIN_ARBITRARY_INPUT_LENGTH: &str = r#"from starkware.cairo.common.cairo_sha256.sha256_utils import ( +segments.write_arg(ids.output, new_state)"#}), +(SHA256_MAIN_ARBITRARY_INPUT_LENGTH, indoc! {r#"from starkware.cairo.common.cairo_sha256.sha256_utils import ( compute_message_schedule, sha2_compress_function) _sha256_input_chunk_size_felts = int(ids.SHA256_INPUT_CHUNK_SIZE_FELTS) @@ -823,9 +714,8 @@ assert 0 <= _sha256_state_size_felts < 100 w = compute_message_schedule(memory.get_range( ids.sha256_start, _sha256_input_chunk_size_felts)) new_state = sha2_compress_function(memory.get_range(ids.state, _sha256_state_size_felts), w) -segments.write_arg(ids.output, new_state)"#; - -pub const SHA256_FINALIZE: &str = r#"# Add dummy pairs of input and output. +segments.write_arg(ids.output, new_state)"#}), +(SHA256_FINALIZE, indoc! {r#"# Add dummy pairs of input and output. from starkware.cairo.common.cairo_sha256.sha256_utils import ( IV, compute_message_schedule, sha2_compress_function) @@ -838,72 +728,59 @@ message = [0] * _sha256_input_chunk_size_felts w = compute_message_schedule(message) output = sha2_compress_function(IV, w) padding = (message + IV + output) * (_block_size - 1) -segments.write_arg(ids.sha256_ptr_end, padding)"#; - -pub const KECCAK_WRITE_ARGS: &str = r#"segments.write_arg(ids.inputs, [ids.low % 2 ** 64, ids.low // 2 ** 64]) -segments.write_arg(ids.inputs + 2, [ids.high % 2 ** 64, ids.high // 2 ** 64])"#; - -pub const COMPARE_BYTES_IN_WORD_NONDET: &str = - r#"memory[ap] = to_felt_or_relocatable(ids.n_bytes < ids.BYTES_IN_WORD)"#; - -pub const COMPARE_KECCAK_FULL_RATE_IN_BYTES_NONDET: &str = - r#"memory[ap] = to_felt_or_relocatable(ids.n_bytes >= ids.KECCAK_FULL_RATE_IN_BYTES)"#; - -pub const BLOCK_PERMUTATION: &str = r#"from starkware.cairo.common.keccak_utils.keccak_utils import keccak_func +segments.write_arg(ids.sha256_ptr_end, padding)"#}), +(KECCAK_WRITE_ARGS, indoc! {r#"segments.write_arg(ids.inputs, [ids.low % 2 ** 64, ids.low // 2 ** 64]) +segments.write_arg(ids.inputs + 2, [ids.high % 2 ** 64, ids.high // 2 ** 64])"#}), +(COMPARE_BYTES_IN_WORD_NONDET, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.n_bytes < ids.BYTES_IN_WORD)"#}), +(COMPARE_KECCAK_FULL_RATE_IN_BYTES_NONDET, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.n_bytes >= ids.KECCAK_FULL_RATE_IN_BYTES)"#}), +(BLOCK_PERMUTATION, indoc! {r#"from starkware.cairo.common.keccak_utils.keccak_utils import keccak_func _keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS) assert 0 <= _keccak_state_size_felts < 100 output_values = keccak_func(memory.get_range( ids.keccak_ptr - _keccak_state_size_felts, _keccak_state_size_felts)) -segments.write_arg(ids.keccak_ptr, output_values)"#; - +segments.write_arg(ids.keccak_ptr, output_values)"#}), // The 0.10.3 whitelist uses this variant (instead of the one used by the common library), but both hints have the same behaviour // We should check for future refactors that may discard one of the variants -pub const BLOCK_PERMUTATION_WHITELIST_V1: &str = r#"from starkware.cairo.common.cairo_keccak.keccak_utils import keccak_func +(BLOCK_PERMUTATION_WHITELIST_V1, indoc! {r#"from starkware.cairo.common.cairo_keccak.keccak_utils import keccak_func _keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS) assert 0 <= _keccak_state_size_felts < 100 output_values = keccak_func(memory.get_range( ids.keccak_ptr - _keccak_state_size_felts, _keccak_state_size_felts)) -segments.write_arg(ids.keccak_ptr, output_values)"#; - -pub const BLOCK_PERMUTATION_WHITELIST_V2: &str = r#"from starkware.cairo.common.cairo_keccak.keccak_utils import keccak_func +segments.write_arg(ids.keccak_ptr, output_values)"#}), +(BLOCK_PERMUTATION_WHITELIST_V2, indoc! {r#"from starkware.cairo.common.cairo_keccak.keccak_utils import keccak_func _keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS) assert 0 <= _keccak_state_size_felts < 100 output_values = keccak_func(memory.get_range( ids.keccak_ptr_start, _keccak_state_size_felts)) -segments.write_arg(ids.output, output_values)"#; - -pub const CAIRO_KECCAK_INPUT_IS_FULL_WORD: &str = r#"ids.full_word = int(ids.n_bytes >= 8)"#; - -pub const CAIRO_KECCAK_FINALIZE_V1: &str = r#"# Add dummy pairs of input and output. +segments.write_arg(ids.output, output_values)"#}), +(CAIRO_KECCAK_INPUT_IS_FULL_WORD, indoc! {r#"ids.full_word = int(ids.n_bytes >= 8)"#}), +(CAIRO_KECCAK_FINALIZE_V1, indoc! {r#"# Add dummy pairs of input and output. _keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS) _block_size = int(ids.BLOCK_SIZE) assert 0 <= _keccak_state_size_felts < 100 assert 0 <= _block_size < 10 inp = [0] * _keccak_state_size_felts padding = (inp + keccak_func(inp)) * _block_size -segments.write_arg(ids.keccak_ptr_end, padding)"#; - -pub const CAIRO_KECCAK_FINALIZE_V2: &str = r#"# Add dummy pairs of input and output. +segments.write_arg(ids.keccak_ptr_end, padding)"#}), +(CAIRO_KECCAK_FINALIZE_V2, indoc! {r#"# Add dummy pairs of input and output. _keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS) _block_size = int(ids.BLOCK_SIZE) assert 0 <= _keccak_state_size_felts < 100 assert 0 <= _block_size < 1000 inp = [0] * _keccak_state_size_felts padding = (inp + keccak_func(inp)) * _block_size -segments.write_arg(ids.keccak_ptr_end, padding)"#; - -pub const FAST_EC_ADD_ASSIGN_NEW_X: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +segments.write_arg(ids.keccak_ptr_end, padding)"#}), +(FAST_EC_ADD_ASSIGN_NEW_X, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack slope = pack(ids.slope, PRIME) x0 = pack(ids.point0.x, PRIME) x1 = pack(ids.point1.x, PRIME) y0 = pack(ids.point0.y, PRIME) -value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#; - -pub const FAST_EC_ADD_ASSIGN_NEW_X_V2: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#}), +(FAST_EC_ADD_ASSIGN_NEW_X_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack SECP_P = 2**255-19 slope = pack(ids.slope, PRIME) @@ -911,50 +788,35 @@ x0 = pack(ids.point0.x, PRIME) x1 = pack(ids.point1.x, PRIME) y0 = pack(ids.point0.y, PRIME) -value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#; - -pub const FAST_EC_ADD_ASSIGN_NEW_X_V3: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack +value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#}), +(FAST_EC_ADD_ASSIGN_NEW_X_V3, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack slope = pack(ids.slope, PRIME) x0 = pack(ids.pt0.x, PRIME) x1 = pack(ids.pt1.x, PRIME) y0 = pack(ids.pt0.y, PRIME) -value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#; - -pub const FAST_EC_ADD_ASSIGN_NEW_Y: &str = - r#"value = new_y = (slope * (x0 - new_x) - y0) % SECP_P"#; - -pub const EC_MUL_INNER: &str = r#"memory[ap] = (ids.scalar % PRIME) % 2"#; - -pub const RELOCATE_SEGMENT: &str = - r#"memory.add_relocation_rule(src_ptr=ids.src_ptr, dest_ptr=ids.dest_ptr)"#; - -pub const TEMPORARY_ARRAY: &str = r#"ids.temporary_array = segments.add_temp_segment()"#; -pub const VERIFY_ECDSA_SIGNATURE: &str = - r#"ecdsa_builtin.add_signature(ids.ecdsa_ptr.address_, (ids.signature_r, ids.signature_s))"#; - -pub const SPLIT_OUTPUT_0: &str = "ids.output0_low = ids.output0 & ((1 << 128) - 1) -ids.output0_high = ids.output0 >> 128"; -pub const SPLIT_OUTPUT_1: &str = "ids.output1_low = ids.output1 & ((1 << 128) - 1) -ids.output1_high = ids.output1 >> 128"; - -pub const SPLIT_INPUT_3: &str = "ids.high3, ids.low3 = divmod(memory[ids.inputs + 3], 256)"; -pub const SPLIT_INPUT_6: &str = "ids.high6, ids.low6 = divmod(memory[ids.inputs + 6], 256 ** 2)"; -pub const SPLIT_INPUT_9: &str = "ids.high9, ids.low9 = divmod(memory[ids.inputs + 9], 256 ** 3)"; -pub const SPLIT_INPUT_12: &str = - "ids.high12, ids.low12 = divmod(memory[ids.inputs + 12], 256 ** 4)"; -pub const SPLIT_INPUT_15: &str = - "ids.high15, ids.low15 = divmod(memory[ids.inputs + 15], 256 ** 5)"; - -pub const SPLIT_N_BYTES: &str = - "ids.n_words_to_copy, ids.n_bytes_left = divmod(ids.n_bytes, ids.BYTES_IN_WORD)"; -pub const SPLIT_OUTPUT_MID_LOW_HIGH: &str = "tmp, ids.output1_low = divmod(ids.output1, 256 ** 7) -ids.output1_high, ids.output1_mid = divmod(tmp, 2 ** 128)"; - -pub const NONDET_N_GREATER_THAN_10: &str = "memory[ap] = to_felt_or_relocatable(ids.n >= 10)"; -pub const NONDET_N_GREATER_THAN_2: &str = "memory[ap] = to_felt_or_relocatable(ids.n >= 2)"; -pub const RANDOM_EC_POINT: &str = r#"from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME +value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#}), +(FAST_EC_ADD_ASSIGN_NEW_Y, indoc! {r#"value = new_y = (slope * (x0 - new_x) - y0) % SECP_P"#}), +(EC_MUL_INNER, indoc! {r#"memory[ap] = (ids.scalar % PRIME) % 2"#}), +(RELOCATE_SEGMENT, indoc! {r#"memory.add_relocation_rule(src_ptr=ids.src_ptr, dest_ptr=ids.dest_ptr)"#}), +(TEMPORARY_ARRAY, indoc! {r#"ids.temporary_array = segments.add_temp_segment()"#}), +(VERIFY_ECDSA_SIGNATURE, indoc! {r#"ecdsa_builtin.add_signature(ids.ecdsa_ptr.address_, (ids.signature_r, ids.signature_s))"#}), +(SPLIT_OUTPUT_0, indoc! {r#"ids.output0_low = ids.output0 & ((1 << 128) - 1) +ids.output0_high = ids.output0 >> 128"#}), +(SPLIT_OUTPUT_1, indoc! {r#"ids.output1_low = ids.output1 & ((1 << 128) - 1) +ids.output1_high = ids.output1 >> 128"#}), +(SPLIT_INPUT_3, indoc! {r#"ids.high3, ids.low3 = divmod(memory[ids.inputs + 3], 256)"#}), +(SPLIT_INPUT_6, indoc! {r#"ids.high6, ids.low6 = divmod(memory[ids.inputs + 6], 256 ** 2)"#}), +(SPLIT_INPUT_9, indoc! {r#"ids.high9, ids.low9 = divmod(memory[ids.inputs + 9], 256 ** 3)"#}), +(SPLIT_INPUT_12, indoc! {r#"ids.high12, ids.low12 = divmod(memory[ids.inputs + 12], 256 ** 4)"#}), +(SPLIT_INPUT_15, indoc! {r#"ids.high15, ids.low15 = divmod(memory[ids.inputs + 15], 256 ** 5)"#}), +(SPLIT_N_BYTES, indoc! {r#"ids.n_words_to_copy, ids.n_bytes_left = divmod(ids.n_bytes, ids.BYTES_IN_WORD)"#}), +(SPLIT_OUTPUT_MID_LOW_HIGH, indoc! {r#"tmp, ids.output1_low = divmod(ids.output1, 256 ** 7) +ids.output1_high, ids.output1_mid = divmod(tmp, 2 ** 128)"#}), +(NONDET_N_GREATER_THAN_10, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.n >= 10)"#}), +(NONDET_N_GREATER_THAN_2, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.n >= 2)"#}), +(RANDOM_EC_POINT, indoc! {r#"from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME from starkware.python.math_utils import random_ec_point from starkware.python.utils import to_bytes @@ -962,8 +824,8 @@ from starkware.python.utils import to_bytes # (1) The added point s is deterministic. # (2) It's hard to choose inputs for which the builtin will fail. seed = b"".join(map(to_bytes, [ids.p.x, ids.p.y, ids.m, ids.q.x, ids.q.y])) -ids.s.x, ids.s.y = random_ec_point(FIELD_PRIME, ALPHA, BETA, seed)"#; -pub const CHAINED_EC_OP_RANDOM_EC_POINT: &str = r#"from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME +ids.s.x, ids.s.y = random_ec_point(FIELD_PRIME, ALPHA, BETA, seed)"#}), +(CHAINED_EC_OP_RANDOM_EC_POINT, indoc! {r#"from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME from starkware.python.math_utils import random_ec_point from starkware.python.utils import to_bytes @@ -989,24 +851,22 @@ seed = b"".join( ], ) ) -ids.s.x, ids.s.y = random_ec_point(FIELD_PRIME, ALPHA, BETA, seed)"#; -pub const RECOVER_Y: &str = - "from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME +ids.s.x, ids.s.y = random_ec_point(FIELD_PRIME, ALPHA, BETA, seed)"#}), +(RECOVER_Y, indoc! {r#"from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME from starkware.python.math_utils import recover_y ids.p.x = ids.x # This raises an exception if `x` is not on the curve. -ids.p.y = recover_y(ids.x, ALPHA, BETA, FIELD_PRIME)"; -pub const PACK_MODN_DIV_MODN: &str = "from starkware.cairo.common.cairo_secp.secp_utils import pack +ids.p.y = recover_y(ids.x, ALPHA, BETA, FIELD_PRIME)"#}), +(PACK_MODN_DIV_MODN, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack from starkware.python.math_utils import div_mod, safe_div N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141 x = pack(ids.x, PRIME) % N s = pack(ids.s, PRIME) % N -value = res = div_mod(x, s, N)"; -pub const XS_SAFE_DIV: &str = "value = k = safe_div(res * s - x, N)"; - +value = res = div_mod(x, s, N)"#}), +(XS_SAFE_DIV, indoc! {r#"value = k = safe_div(res * s - x, N)"#}), // The following hints support the lib https://github.com/NethermindEth/research-basic-Cairo-operations-big-integers/blob/main/lib -pub const UINT384_UNSIGNED_DIV_REM: &str = "def split(num: int, num_bits_shift: int, length: int): +(UINT384_UNSIGNED_DIV_REM, indoc! {r#"def split(num: int, num_bits_shift: int, length: int): a = [] for _ in range(length): a.append( num & ((1 << num_bits_shift) - 1) ) @@ -1031,16 +891,16 @@ ids.quotient.d2 = quotient_split[2] remainder_split = split(remainder, num_bits_shift=128, length=3) ids.remainder.d0 = remainder_split[0] ids.remainder.d1 = remainder_split[1] -ids.remainder.d2 = remainder_split[2]"; -pub const UINT384_SPLIT_128: &str = "ids.low = ids.a & ((1<<128) - 1) -ids.high = ids.a >> 128"; -pub const ADD_NO_UINT384_CHECK: &str = "sum_d0 = ids.a.d0 + ids.b.d0 +ids.remainder.d2 = remainder_split[2]"#}), +(UINT384_SPLIT_128, indoc! {r#"ids.low = ids.a & ((1<<128) - 1) +ids.high = ids.a >> 128"#}), +(ADD_NO_UINT384_CHECK, indoc! {r#"sum_d0 = ids.a.d0 + ids.b.d0 ids.carry_d0 = 1 if sum_d0 >= ids.SHIFT else 0 sum_d1 = ids.a.d1 + ids.b.d1 + ids.carry_d0 ids.carry_d1 = 1 if sum_d1 >= ids.SHIFT else 0 sum_d2 = ids.a.d2 + ids.b.d2 + ids.carry_d1 -ids.carry_d2 = 1 if sum_d2 >= ids.SHIFT else 0"; -pub const UINT384_SQRT: &str = "from starkware.python.math_utils import isqrt +ids.carry_d2 = 1 if sum_d2 >= ids.SHIFT else 0"#}), +(UINT384_SQRT, indoc! {r#"from starkware.python.math_utils import isqrt def split(num: int, num_bits_shift: int, length: int): a = [] @@ -1059,10 +919,8 @@ assert 0 <= root < 2 ** 192 root_split = split(root, num_bits_shift=128, length=3) ids.root.d0 = root_split[0] ids.root.d1 = root_split[1] -ids.root.d2 = root_split[2]"; - -pub const SUB_REDUCED_A_AND_REDUCED_B: &str = - "def split(num: int, num_bits_shift: int, length: int): +ids.root.d2 = root_split[2]"#}), +(SUB_REDUCED_A_AND_REDUCED_B, indoc! {r#"def split(num: int, num_bits_shift: int, length: int): a = [] for _ in range(length): a.append( num & ((1 << num_bits_shift) - 1) ) @@ -1084,10 +942,8 @@ res_split = split(res, num_bits_shift=128, length=3) ids.res.d0 = res_split[0] ids.res.d1 = res_split[1] -ids.res.d2 = res_split[2]"; - -pub const UNSIGNED_DIV_REM_UINT768_BY_UINT384: &str = - "def split(num: int, num_bits_shift: int, length: int): +ids.res.d2 = res_split[2]"#}), +(UNSIGNED_DIV_REM_UINT768_BY_UINT384, indoc! {r#"def split(num: int, num_bits_shift: int, length: int): a = [] for _ in range(length): a.append( num & ((1 << num_bits_shift) - 1) ) @@ -1119,11 +975,10 @@ ids.quotient.d5 = quotient_split[5] remainder_split = split(remainder, num_bits_shift=128, length=3) ids.remainder.d0 = remainder_split[0] ids.remainder.d1 = remainder_split[1] -ids.remainder.d2 = remainder_split[2]"; - +ids.remainder.d2 = remainder_split[2]"#}), // equal to UNSIGNED_DIV_REM_UINT768_BY_UINT384 but with some whitespace removed // in the `num = num >> num_bits_shift` and between `pack` and `pack_extended` -pub const UNSIGNED_DIV_REM_UINT768_BY_UINT384_STRIPPED: &str = r#"def split(num: int, num_bits_shift: int, length: int): +(UNSIGNED_DIV_REM_UINT768_BY_UINT384_STRIPPED, indoc! {r#"def split(num: int, num_bits_shift: int, length: int): a = [] for _ in range(length): a.append( num & ((1 << num_bits_shift) - 1) ) @@ -1155,18 +1010,11 @@ ids.quotient.d5 = quotient_split[5] remainder_split = split(remainder, num_bits_shift=128, length=3) ids.remainder.d0 = remainder_split[0] ids.remainder.d1 = remainder_split[1] -ids.remainder.d2 = remainder_split[2]"#; - -pub const UINT384_SIGNED_NN: &str = "memory[ap] = 1 if 0 <= (ids.a.d2 % PRIME) < 2 ** 127 else 0"; - -pub const IMPORT_SECP256R1_ALPHA: &str = - "from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_ALPHA as ALPHA"; - -pub const IMPORT_SECP256R1_N: &str = - "from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_N as N"; - -pub const UINT384_GET_SQUARE_ROOT: &str = - "from starkware.python.math_utils import is_quad_residue, sqrt +ids.remainder.d2 = remainder_split[2]"#}), +(UINT384_SIGNED_NN, indoc! {r#"memory[ap] = 1 if 0 <= (ids.a.d2 % PRIME) < 2 ** 127 else 0"#}), +(IMPORT_SECP256R1_ALPHA, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_ALPHA as ALPHA"#}), +(IMPORT_SECP256R1_N, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_N as N"#}), +(UINT384_GET_SQUARE_ROOT, indoc! {r#"from starkware.python.math_utils import is_quad_residue, sqrt def split(num: int, num_bits_shift: int = 128, length: int = 3): a = [] @@ -1208,9 +1056,8 @@ ids.sqrt_x.d1 = split_root_x[1] ids.sqrt_x.d2 = split_root_x[2] ids.sqrt_gx.d0 = split_root_gx[0] ids.sqrt_gx.d1 = split_root_gx[1] -ids.sqrt_gx.d2 = split_root_gx[2]"; - -pub const UINT256_GET_SQUARE_ROOT: &str = r#"from starkware.python.math_utils import is_quad_residue, sqrt +ids.sqrt_gx.d2 = split_root_gx[2]"#}), +(UINT256_GET_SQUARE_ROOT, indoc! {r#"from starkware.python.math_utils import is_quad_residue, sqrt def split(a: int): return (a & ((1 << 128) - 1), a >> 128) @@ -1244,9 +1091,8 @@ split_root_gx = split(root_gx) ids.sqrt_x.low = split_root_x[0] ids.sqrt_x.high = split_root_x[1] ids.sqrt_gx.low = split_root_gx[0] -ids.sqrt_gx.high = split_root_gx[1]"#; - -pub const UINT384_DIV: &str = "from starkware.python.math_utils import div_mod +ids.sqrt_gx.high = split_root_gx[1]"#}), +(UINT384_DIV, indoc! {r#"from starkware.python.math_utils import div_mod def split(num: int, num_bits_shift: int, length: int): a = [] @@ -1272,9 +1118,8 @@ b_inverse_mod_p_split = split(b_inverse_mod_p, num_bits_shift=128, length=3) ids.b_inverse_mod_p.d0 = b_inverse_mod_p_split[0] ids.b_inverse_mod_p.d1 = b_inverse_mod_p_split[1] -ids.b_inverse_mod_p.d2 = b_inverse_mod_p_split[2]"; - -pub const INV_MOD_P_UINT256: &str = r#"from starkware.python.math_utils import div_mod +ids.b_inverse_mod_p.d2 = b_inverse_mod_p_split[2]"#}), +(INV_MOD_P_UINT256, indoc! {r#"from starkware.python.math_utils import div_mod def split(a: int): return (a & ((1 << 128) - 1), a >> 128) @@ -1294,19 +1139,15 @@ b_inverse_mod_p = div_mod(1, b, p) b_inverse_mod_p_split = split(b_inverse_mod_p) ids.b_inverse_mod_p.low = b_inverse_mod_p_split[0] -ids.b_inverse_mod_p.high = b_inverse_mod_p_split[1]"#; - -pub const HI_MAX_BITLEN: &str = - "ids.len_hi = max(ids.scalar_u.d2.bit_length(), ids.scalar_v.d2.bit_length())-1"; - -pub const QUAD_BIT: &str = r#"ids.quad_bit = ( +ids.b_inverse_mod_p.high = b_inverse_mod_p_split[1]"#}), +(HI_MAX_BITLEN, indoc! {r#"ids.len_hi = max(ids.scalar_u.d2.bit_length(), ids.scalar_v.d2.bit_length())-1"#}), +(QUAD_BIT, indoc! {r#"ids.quad_bit = ( 8 * ((ids.scalar_v >> ids.m) & 1) + 4 * ((ids.scalar_u >> ids.m) & 1) + 2 * ((ids.scalar_v >> (ids.m - 1)) & 1) + ((ids.scalar_u >> (ids.m - 1)) & 1) -)"#; - -pub const INV_MOD_P_UINT512: &str = "def pack_512(u, num_bits_shift: int) -> int: +)"#}), +(INV_MOD_P_UINT512, indoc! {r#"def pack_512(u, num_bits_shift: int) -> int: limbs = (u.d0, u.d1, u.d2, u.d3) return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs)) @@ -1317,20 +1158,16 @@ x_inverse_mod_p = pow(x,-1, p) x_inverse_mod_p_split = (x_inverse_mod_p & ((1 << 128) - 1), x_inverse_mod_p >> 128) ids.x_inverse_mod_p.low = x_inverse_mod_p_split[0] -ids.x_inverse_mod_p.high = x_inverse_mod_p_split[1]"; - -pub const DI_BIT: &str = - r#"ids.dibit = ((ids.scalar_u >> ids.m) & 1) + 2 * ((ids.scalar_v >> ids.m) & 1)"#; - -pub const EC_RECOVER_DIV_MOD_N_PACKED: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +ids.x_inverse_mod_p.high = x_inverse_mod_p_split[1]"#}), +(DI_BIT, indoc! {r#"ids.dibit = ((ids.scalar_u >> ids.m) & 1) + 2 * ((ids.scalar_v >> ids.m) & 1)"#}), +(EC_RECOVER_DIV_MOD_N_PACKED, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack from starkware.python.math_utils import div_mod, safe_div N = pack(ids.n, PRIME) x = pack(ids.x, PRIME) % N s = pack(ids.s, PRIME) % N -value = res = div_mod(x, s, N)"#; - -pub const UINT512_UNSIGNED_DIV_REM: &str = r#"def split(num: int, num_bits_shift: int, length: int): +value = res = div_mod(x, s, N)"#}), +(UINT512_UNSIGNED_DIV_REM, indoc! {r#"def split(num: int, num_bits_shift: int, length: int): a = [] for _ in range(length): a.append( num & ((1 << num_bits_shift) - 1) ) @@ -1359,20 +1196,17 @@ ids.quotient.d3 = quotient_split[3] remainder_split = split(remainder, num_bits_shift=128, length=2) ids.remainder.low = remainder_split[0] -ids.remainder.high = remainder_split[1]"#; - -pub const EC_RECOVER_SUB_A_B: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +ids.remainder.high = remainder_split[1]"#}), +(EC_RECOVER_SUB_A_B, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack from starkware.python.math_utils import div_mod, safe_div a = pack(ids.a, PRIME) b = pack(ids.b, PRIME) -value = res = a - b"#; - -pub const A_B_BITAND_1: &str = "ids.a_lsb = ids.a & 1 -ids.b_lsb = ids.b & 1"; - -pub const EC_RECOVER_PRODUCT_MOD: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import pack +value = res = a - b"#}), +(A_B_BITAND_1, indoc! {r#"ids.a_lsb = ids.a & 1 +ids.b_lsb = ids.b & 1"#}), +(EC_RECOVER_PRODUCT_MOD, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack from starkware.python.math_utils import div_mod, safe_div a = pack(ids.a, PRIME) @@ -1380,9 +1214,8 @@ b = pack(ids.b, PRIME) product = a * b m = pack(ids.m, PRIME) -value = res = product % m"#; - -pub const UINT256_MUL_INV_MOD_P: &str = r#"from starkware.python.math_utils import div_mod +value = res = product % m"#}), +(UINT256_MUL_INV_MOD_P, indoc! {r#"from starkware.python.math_utils import div_mod def split(a: int): return (a & ((1 << 128) - 1), a >> 128) @@ -1402,21 +1235,17 @@ b_inverse_mod_p = div_mod(1, b, p) b_inverse_mod_p_split = split(b_inverse_mod_p) ids.b_inverse_mod_p.low = b_inverse_mod_p_split[0] -ids.b_inverse_mod_p.high = b_inverse_mod_p_split[1]"#; - -pub const EC_RECOVER_PRODUCT_DIV_M: &str = "value = k = product // m"; - -pub const SQUARE_SLOPE_X_MOD_P: &str = - "from starkware.cairo.common.cairo_secp.secp_utils import pack +ids.b_inverse_mod_p.high = b_inverse_mod_p_split[1]"#}), +(EC_RECOVER_PRODUCT_DIV_M, indoc! {r#"value = k = product // m"#}), +(SQUARE_SLOPE_X_MOD_P, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack slope = pack(ids.slope, PRIME) x0 = pack(ids.point0.x, PRIME) x1 = pack(ids.point1.x, PRIME) y0 = pack(ids.point0.y, PRIME) -value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"; - -pub const SPLIT_XX: &str = "PRIME = 2**255 - 19 +value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#}), +(SPLIT_XX, indoc! {r#"PRIME = 2**255 - 19 II = pow(2, (PRIME - 1) // 4, PRIME) xx = ids.xx.low + (ids.xx.high<<128) @@ -1426,39 +1255,27 @@ if (x * x - xx) % PRIME != 0: if x % 2 != 0: x = PRIME - x ids.x.low = x & ((1<<128)-1) -ids.x.high = x >> 128"; -#[cfg(feature = "test_utils")] -pub const SKIP_NEXT_INSTRUCTION: &str = "skip_next_instruction()"; - -#[cfg(feature = "test_utils")] -pub const PRINT_FELT: &str = "print(ids.x)"; - -#[cfg(feature = "test_utils")] -pub const PRINT_ARR: &str = r#"print(bytes.fromhex(f"{ids.name:062x}").decode().replace('\x00','')) +ids.x.high = x >> 128"#}), +(SKIP_NEXT_INSTRUCTION, indoc! {r#"skip_next_instruction()"#}, "test_utils"), +(PRINT_FELT, indoc! {r#"print(ids.x)"#}, "test_utils"), +(PRINT_ARR, indoc! {r#"print(bytes.fromhex(f"{ids.name:062x}").decode().replace('\x00','')) arr = [memory[ids.arr + i] for i in range(ids.arr_len)] -print(arr)"#; - -#[cfg(feature = "test_utils")] -pub const PRINT_DICT: &str = r#"print(bytes.fromhex(f"{ids.name:062x}").decode().replace('\x00','')) +print(arr)"#}, "test_utils"), +(PRINT_DICT, indoc! {r#"print(bytes.fromhex(f"{ids.name:062x}").decode().replace('\x00','')) data = __dict_manager.get_dict(ids.dict_ptr) print( {k: v if isinstance(v, int) else [memory[v + i] for i in range(ids.pointer_size)] for k, v in data.items()} -)"#; - -pub const RUN_P_CIRCUIT: &str = "from starkware.cairo.lang.builtins.modulo.mod_builtin_runner import ModBuiltinRunner\nassert builtin_runners[\"add_mod_builtin\"].instance_def.batch_size == 1\nassert builtin_runners[\"mul_mod_builtin\"].instance_def.batch_size == 1\n\nModBuiltinRunner.fill_memory(\n memory=memory,\n add_mod=(ids.add_mod_ptr.address_, builtin_runners[\"add_mod_builtin\"], ids.add_mod_n),\n mul_mod=(ids.mul_mod_ptr.address_, builtin_runners[\"mul_mod_builtin\"], ids.mul_mod_n),\n)"; - -pub const RUN_P_CIRCUIT_WITH_LARGE_BATCH_SIZE: &str = "from starkware.cairo.lang.builtins.modulo.mod_builtin_runner import ModBuiltinRunner\nassert builtin_runners[\"add_mod_builtin\"].instance_def.batch_size == ids.BATCH_SIZE\nassert builtin_runners[\"mul_mod_builtin\"].instance_def.batch_size == ids.BATCH_SIZE\n\nModBuiltinRunner.fill_memory(\n memory=memory,\n add_mod=(ids.add_mod_ptr.address_, builtin_runners[\"add_mod_builtin\"], ids.add_mod_n),\n mul_mod=(ids.mul_mod_ptr.address_, builtin_runners[\"mul_mod_builtin\"], ids.mul_mod_n),\n)"; - -pub const NONDET_ELEMENTS_OVER_TEN: &str = - "memory[ap] = to_felt_or_relocatable(ids.elements_end - ids.elements >= 10)"; -pub const NONDET_ELEMENTS_OVER_TWO: &str = - "memory[ap] = to_felt_or_relocatable(ids.elements_end - ids.elements >= 2)"; - -pub const EXCESS_BALANCE: &str = r#"from excess_balance import excess_balance_func +)"#}, "test_utils"), +(RUN_P_CIRCUIT, "from starkware.cairo.lang.builtins.modulo.mod_builtin_runner import ModBuiltinRunner\nassert builtin_runners[\"add_mod_builtin\"].instance_def.batch_size == 1\nassert builtin_runners[\"mul_mod_builtin\"].instance_def.batch_size == 1\n\nModBuiltinRunner.fill_memory(\n memory=memory,\n add_mod=(ids.add_mod_ptr.address_, builtin_runners[\"add_mod_builtin\"], ids.add_mod_n),\n mul_mod=(ids.mul_mod_ptr.address_, builtin_runners[\"mul_mod_builtin\"], ids.mul_mod_n),\n)"), +(RUN_P_CIRCUIT_WITH_LARGE_BATCH_SIZE, "from starkware.cairo.lang.builtins.modulo.mod_builtin_runner import ModBuiltinRunner\nassert builtin_runners[\"add_mod_builtin\"].instance_def.batch_size == ids.BATCH_SIZE\nassert builtin_runners[\"mul_mod_builtin\"].instance_def.batch_size == ids.BATCH_SIZE\n\nModBuiltinRunner.fill_memory(\n memory=memory,\n add_mod=(ids.add_mod_ptr.address_, builtin_runners[\"add_mod_builtin\"], ids.add_mod_n),\n mul_mod=(ids.mul_mod_ptr.address_, builtin_runners[\"mul_mod_builtin\"], ids.mul_mod_n),\n)"), +(NONDET_ELEMENTS_OVER_TEN, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.elements_end - ids.elements >= 10)"#}), +(NONDET_ELEMENTS_OVER_TWO, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.elements_end - ids.elements >= 2)"#}), +(EXCESS_BALANCE, indoc! {r#"from excess_balance import excess_balance_func res = excess_balance_func(ids, memory, __dict_manager) ids.check_account_value = res["account_value"] ids.check_excess_balance = res["excess_balance"] ids.check_margin_requirement_d = res["margin_requirement"] -ids.check_unrealized_pnl_d = res["unrealized_pnl"]"#; +ids.check_unrealized_pnl_d = res["unrealized_pnl"]"#}) +} diff --git a/vm/src/hint_processor/builtin_hint_processor/hint_utils.rs b/vm/src/hint_processor/builtin_hint_processor/hint_utils.rs index e104cb7e86..1da3905e02 100644 --- a/vm/src/hint_processor/builtin_hint_processor/hint_utils.rs +++ b/vm/src/hint_processor/builtin_hint_processor/hint_utils.rs @@ -15,6 +15,61 @@ use crate::types::relocatable::Relocatable; use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; +/// Generates a const string for each hint, and a lazy_static HashMap that maps the const name to +/// the hint string. +/// Allows gating specific hints behind feature gates. +/// +/// # Examples +/// +/// ``` +/// # #[macro_use] extern crate cairo_vm; +/// # use cairo_vm::stdlib::collections::HashMap; +/// cairo_vm::define_hint_string_map!( +/// FOO_HINTS, +/// (FOO_HINT_ADD_X_Y, "x + y"), +/// (FOO_HINT_PRINT_X, "print(x)", "test_utils") +/// ); +/// ``` +/// +/// This will generate the following code: +/// +/// ``` +/// # use cairo_vm::stdlib::collections::HashMap; +/// pub const FOO_HINT_ADD_X_Y: &str = "x + y"; +/// #[cfg(feature = "test_utils")] +/// pub const FOO_HINT_PRINT_X: &str = "print(x)"; +/// +/// lazy_static::lazy_static! { +/// pub static ref FOO_HINTS: HashMap<&'static str, &'static str> = { +/// let mut map = HashMap::new(); +/// map.insert("FOO_HINT_ADD_X_Y", FOO_HINT_ADD_X_Y); +/// #[cfg(feature = "test_utils")] +/// map.insert("FOO_HINT_PRINT_X", FOO_HINT_PRINT_X); +/// map +/// }; +/// } +/// ``` +#[macro_export] +macro_rules! define_hint_string_map { + ($hint_set_name:ident, $(($hint_name:ident, $hint_str:expr $(, $feature_gate:expr)?)),+) => { + $( + $(#[cfg(feature = $feature_gate)])? + pub const $hint_name: &str = $hint_str; + )+ + + lazy_static::lazy_static! { + pub static ref $hint_set_name: HashMap<&'static str, &'static str> = { + let mut map = HashMap::new(); + $( + $(#[cfg(feature = $feature_gate)])? + map.insert(stringify!($hint_name), $hint_name); + )+ + map + }; + } + } +} + //Inserts value into the address of the given ids variable pub fn insert_value_from_var_name( var_name: &str, diff --git a/vm/src/hint_processor/builtin_hint_processor/secp/cairo0_hints.rs b/vm/src/hint_processor/builtin_hint_processor/secp/cairo0_hints.rs index 5e894588da..f3ffeac78f 100644 --- a/vm/src/hint_processor/builtin_hint_processor/secp/cairo0_hints.rs +++ b/vm/src/hint_processor/builtin_hint_processor/secp/cairo0_hints.rs @@ -5,6 +5,7 @@ use crate::stdlib::{ prelude::*, }; +use crate::define_hint_string_map; use crate::hint_processor::builtin_hint_processor::hint_utils::{ get_constant_from_var_name, get_integer_from_var_name, insert_value_from_var_name, }; @@ -17,6 +18,7 @@ use crate::types::exec_scope::ExecutionScopes; use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use crate::Felt252; +use indoc::indoc; use num_bigint::{BigInt, BigUint}; use num_integer::Integer; use num_traits::One; @@ -26,9 +28,70 @@ use super::bigint_utils::{BigInt3, Uint384}; use super::ec_utils::EcPoint; use super::secp_utils::{SECP256R1_ALPHA, SECP256R1_B, SECP256R1_P}; -pub const SECP_REDUCE: &str = r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P +define_hint_string_map! { + CAIRO0_HINT_CODES, +(SECP_REDUCE, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P from starkware.cairo.common.cairo_secp.secp_utils import pack -value = pack(ids.x, PRIME) % SECP256R1_P"#; +value = pack(ids.x, PRIME) % SECP256R1_P"#}), +(SECP_REDUCE_X, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P +from starkware.cairo.common.cairo_secp.secp_utils import pack + +x = pack(ids.x, PRIME) % SECP256R1_P"#}), +(COMPUTE_Q_MOD_PRIME, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P +from starkware.cairo.common.cairo_secp.secp_utils import pack + +q, r = divmod(pack(ids.val, PRIME), SECP256R1_P) +assert r == 0, f"verify_zero: Invalid input {ids.val.d0, ids.val.d1, ids.val.d2}." +ids.q = q % PRIME"#}), +(COMPUTE_IDS_HIGH_LOW, indoc! {r#"from starkware.cairo.common.math_utils import as_int + +# Correctness check. +value = as_int(ids.value, PRIME) % PRIME +assert value < ids.UPPER_BOUND, f'{value} is outside of the range [0, 2**165).' + +# Calculation for the assertion. +ids.high, ids.low = divmod(ids.value, ids.SHIFT)"#}), +(SECP_R1_GET_POINT_FROM_X, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP256R1, pack +from starkware.python.math_utils import y_squared_from_x + +y_square_int = y_squared_from_x( + x=pack(ids.x, SECP256R1.prime), + alpha=SECP256R1.alpha, + beta=SECP256R1.beta, + field_prime=SECP256R1.prime, +) + +# Note that (y_square_int ** ((SECP256R1.prime + 1) / 4)) ** 2 = +# = y_square_int ** ((SECP256R1.prime + 1) / 2) = +# = y_square_int ** ((SECP256R1.prime - 1) / 2 + 1) = +# = y_square_int * y_square_int ** ((SECP256R1.prime - 1) / 2) = y_square_int * {+/-}1. +y = pow(y_square_int, (SECP256R1.prime + 1) // 4, SECP256R1.prime) + +# We need to decide whether to take y or prime - y. +if ids.v % 2 == y % 2: + value = y +else: + value = (-y) % SECP256R1.prime"#}), +(IS_ON_CURVE_2, indoc! {r#"ids.is_on_curve = (y * y) % SECP256R1.prime == y_square_int"#}), +(SECP_DOUBLE_ASSIGN_NEW_X, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P +from starkware.cairo.common.cairo_secp.secp_utils import pack + +slope = pack(ids.slope, SECP256R1_P) +x = pack(ids.point.x, SECP256R1_P) +y = pack(ids.point.y, SECP256R1_P) + +value = new_x = (pow(slope, 2, SECP256R1_P) - 2 * x) % SECP256R1_P"#}), +(GENERATE_NIBBLES, indoc! {r#"num = (ids.scalar.high << 128) + ids.scalar.low +nibbles = [(num >> i) & 0xf for i in range(0, 256, 4)] +ids.first_nibble = nibbles.pop() +ids.last_nibble = nibbles[0]"#}), +(FAST_SECP_ADD_ASSIGN_NEW_Y, indoc! {r#"value = new_y = (slope * (x - new_x) - y) % SECP256R1_P"#}), +(WRITE_NIBBLES_TO_MEM, indoc! {r#"memory[fp + 0] = to_felt_or_relocatable(nibbles.pop())"#}), +(COMPUTE_VALUE_DIV_MOD, indoc! {r#"from starkware.python.math_utils import div_mod + +value = div_mod(1, x, SECP256R1_P)"#}) +} + pub fn reduce_value( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, @@ -41,10 +104,6 @@ pub fn reduce_value( Ok(()) } -pub const SECP_REDUCE_X: &str = r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P -from starkware.cairo.common.cairo_secp.secp_utils import pack - -x = pack(ids.x, PRIME) % SECP256R1_P"#; pub fn reduce_x( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, @@ -57,12 +116,6 @@ pub fn reduce_x( Ok(()) } -pub const COMPUTE_Q_MOD_PRIME: &str = r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P -from starkware.cairo.common.cairo_secp.secp_utils import pack - -q, r = divmod(pack(ids.val, PRIME), SECP256R1_P) -assert r == 0, f"verify_zero: Invalid input {ids.val.d0, ids.val.d1, ids.val.d2}." -ids.q = q % PRIME"#; pub fn compute_q_mod_prime( vm: &mut VirtualMachine, _exec_scopes: &mut ExecutionScopes, @@ -79,14 +132,6 @@ pub fn compute_q_mod_prime( Ok(()) } -pub const COMPUTE_IDS_HIGH_LOW: &str = r#"from starkware.cairo.common.math_utils import as_int - -# Correctness check. -value = as_int(ids.value, PRIME) % PRIME -assert value < ids.UPPER_BOUND, f'{value} is outside of the range [0, 2**165).' - -# Calculation for the assertion. -ids.high, ids.low = divmod(ids.value, ids.SHIFT)"#; pub fn compute_ids_high_low( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, @@ -121,28 +166,6 @@ pub fn compute_ids_high_low( Ok(()) } -pub const SECP_R1_GET_POINT_FROM_X: &str = r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP256R1, pack -from starkware.python.math_utils import y_squared_from_x - -y_square_int = y_squared_from_x( - x=pack(ids.x, SECP256R1.prime), - alpha=SECP256R1.alpha, - beta=SECP256R1.beta, - field_prime=SECP256R1.prime, -) - -# Note that (y_square_int ** ((SECP256R1.prime + 1) / 4)) ** 2 = -# = y_square_int ** ((SECP256R1.prime + 1) / 2) = -# = y_square_int ** ((SECP256R1.prime - 1) / 2 + 1) = -# = y_square_int * y_square_int ** ((SECP256R1.prime - 1) / 2) = y_square_int * {+/-}1. -y = pow(y_square_int, (SECP256R1.prime + 1) // 4, SECP256R1.prime) - -# We need to decide whether to take y or prime - y. -if ids.v % 2 == y % 2: - value = y -else: - value = (-y) % SECP256R1.prime"#; - pub fn r1_get_point_from_x( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, @@ -204,8 +227,6 @@ pub fn r1_get_point_from_x( Ok(()) } -pub const IS_ON_CURVE_2: &str = r#"ids.is_on_curve = (y * y) % SECP256R1.prime == y_square_int"#; - pub fn is_on_curve_2( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, @@ -228,15 +249,6 @@ pub fn is_on_curve_2( Ok(()) } -pub const SECP_DOUBLE_ASSIGN_NEW_X: &str = r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P -from starkware.cairo.common.cairo_secp.secp_utils import pack - -slope = pack(ids.slope, SECP256R1_P) -x = pack(ids.point.x, SECP256R1_P) -y = pack(ids.point.y, SECP256R1_P) - -value = new_x = (pow(slope, 2, SECP256R1_P) - 2 * x) % SECP256R1_P"#; - pub fn secp_double_assign_new_x( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, @@ -266,10 +278,6 @@ pub fn secp_double_assign_new_x( Ok(()) } -pub const GENERATE_NIBBLES: &str = r#"num = (ids.scalar.high << 128) + ids.scalar.low -nibbles = [(num >> i) & 0xf for i in range(0, 256, 4)] -ids.first_nibble = nibbles.pop() -ids.last_nibble = nibbles[0]"#; pub fn generate_nibbles( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, @@ -298,8 +306,6 @@ pub fn generate_nibbles( Ok(()) } -pub const FAST_SECP_ADD_ASSIGN_NEW_Y: &str = - r#"value = new_y = (slope * (x - new_x) - y) % SECP256R1_P"#; pub fn fast_secp_add_assign_new_y( _vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, @@ -322,8 +328,6 @@ pub fn fast_secp_add_assign_new_y( Ok(()) } -pub const WRITE_NIBBLES_TO_MEM: &str = r#"memory[fp + 0] = to_felt_or_relocatable(nibbles.pop())"#; - pub fn write_nibbles_to_mem( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, @@ -338,9 +342,6 @@ pub fn write_nibbles_to_mem( Ok(()) } -pub const COMPUTE_VALUE_DIV_MOD: &str = r#"from starkware.python.math_utils import div_mod - -value = div_mod(1, x, SECP256R1_P)"#; pub fn compute_value_div_mod( _vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes,