cairo_vm/hint_processor/builtin_hint_processor/
hint_code.rs

1use indoc::indoc;
2
3use crate::define_hint_string_map;
4use crate::stdlib::collections::HashMap;
5
6define_hint_string_map! {
7    HINT_CODES,
8(ADD_SEGMENT, indoc! {r#"memory[ap] = segments.add()"#}),
9(VM_ENTER_SCOPE, indoc! {r#"vm_enter_scope()"#}),
10(VM_EXIT_SCOPE, indoc! {r#"vm_exit_scope()"#}),
11(MEMCPY_ENTER_SCOPE, indoc! {r#"vm_enter_scope({'n': ids.len})"#}),
12(MEMCPY_CONTINUE_COPYING, indoc! {r#"n -= 1
13ids.continue_copying = 1 if n > 0 else 0"#}),
14(MEMSET_ENTER_SCOPE, indoc! {r#"vm_enter_scope({'n': ids.n})"#}),
15(MEMSET_CONTINUE_LOOP, indoc! {r#"n -= 1
16ids.continue_loop = 1 if n > 0 else 0"#}),
17(POW, indoc! {r#"ids.locs.bit = (ids.prev_locs.exp % PRIME) & 1"#}),
18(IS_NN, indoc! {r#"memory[ap] = 0 if 0 <= (ids.a % PRIME) < range_check_builtin.bound else 1"#}),
19(IS_NN_OUT_OF_RANGE, indoc! {r#"memory[ap] = 0 if 0 <= ((-ids.a - 1) % PRIME) < range_check_builtin.bound else 1"#}),
20(IS_LE_FELT, indoc! {r#"memory[ap] = 0 if (ids.a % PRIME) <= (ids.b % PRIME) else 1"#}),
21(IS_POSITIVE, indoc! {r#"from starkware.cairo.common.math_utils import is_positive
22ids.is_positive = 1 if is_positive(
23    value=ids.value, prime=PRIME, rc_bound=range_check_builtin.bound) else 0"#}),
24(ASSERT_NN, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer
25assert_integer(ids.a)
26assert 0 <= ids.a % PRIME < range_check_builtin.bound, f'a = {ids.a} is out of range.'"#}),
27(ASSERT_NOT_ZERO, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer
28assert_integer(ids.value)
29assert ids.value % PRIME != 0, f'assert_not_zero failed: {ids.value} = 0.'"#}),
30(ASSERT_NOT_EQUAL, indoc! {r#"from starkware.cairo.lang.vm.relocatable import RelocatableValue
31both_ints = isinstance(ids.a, int) and isinstance(ids.b, int)
32both_relocatable = (
33    isinstance(ids.a, RelocatableValue) and isinstance(ids.b, RelocatableValue) and
34    ids.a.segment_index == ids.b.segment_index)
35assert both_ints or both_relocatable, \
36    f'assert_not_equal failed: non-comparable values: {ids.a}, {ids.b}.'
37assert (ids.a - ids.b) % PRIME != 0, f'assert_not_equal failed: {ids.a} = {ids.b}.'"#}),
38(ASSERT_LE_FELT, indoc! {r#"import itertools
39
40from starkware.cairo.common.math_utils import assert_integer
41assert_integer(ids.a)
42assert_integer(ids.b)
43a = ids.a % PRIME
44b = ids.b % PRIME
45assert a <= b, f'a = {a} is not less than or equal to b = {b}.'
46
47# Find an arc less than PRIME / 3, and another less than PRIME / 2.
48lengths_and_indices = [(a, 0), (b - a, 1), (PRIME - 1 - b, 2)]
49lengths_and_indices.sort()
50assert lengths_and_indices[0][0] <= PRIME // 3 and lengths_and_indices[1][0] <= PRIME // 2
51excluded = lengths_and_indices[2][1]
52
53memory[ids.range_check_ptr + 1], memory[ids.range_check_ptr + 0] = (
54    divmod(lengths_and_indices[0][0], ids.PRIME_OVER_3_HIGH))
55memory[ids.range_check_ptr + 3], memory[ids.range_check_ptr + 2] = (
56    divmod(lengths_and_indices[1][0], ids.PRIME_OVER_2_HIGH))"#}),
57(ASSERT_LE_FELT_V_0_6, "from starkware.cairo.common.math_utils import assert_integer
58assert_integer(ids.a)
59assert_integer(ids.b)
60assert (ids.a % PRIME) <= (ids.b % PRIME), \\
61    f'a = {ids.a % PRIME} is not less than or equal to b = {ids.b % PRIME}.'"),
62(ASSERT_LE_FELT_V_0_8, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer
63assert_integer(ids.a)
64assert_integer(ids.b)
65a = ids.a % PRIME
66b = ids.b % PRIME
67assert a <= b, f'a = {a} is not less than or equal to b = {b}.'
68
69ids.small_inputs = int(
70    a < range_check_builtin.bound and (b - a) < range_check_builtin.bound)"#}),
71(ASSERT_LE_FELT_EXCLUDED_0, indoc! {r#"memory[ap] = 1 if excluded != 0 else 0"#}),
72(ASSERT_LE_FELT_EXCLUDED_1, indoc! {r#"memory[ap] = 1 if excluded != 1 else 0"#}),
73(ASSERT_LE_FELT_EXCLUDED_2, indoc! {r#"assert excluded == 2"#}),
74(ASSERT_LT_FELT, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer
75assert_integer(ids.a)
76assert_integer(ids.b)
77assert (ids.a % PRIME) < (ids.b % PRIME), \
78    f'a = {ids.a % PRIME} is not less than b = {ids.b % PRIME}.'"#}),
79(SPLIT_INT_ASSERT_RANGE, indoc! {r#"assert ids.value == 0, 'split_int(): value is out of range.'"#}),
80(ASSERT_250_BITS, indoc! {r#"from starkware.cairo.common.math_utils import as_int
81
82# Correctness check.
83value = as_int(ids.value, PRIME) % PRIME
84assert value < ids.UPPER_BOUND, f'{value} is outside of the range [0, 2**250).'
85
86# Calculation for the assertion.
87ids.high, ids.low = divmod(ids.value, ids.SHIFT)"#}),
88(IS_250_BITS, indoc! {r#"ids.is_250 = 1 if ids.addr < 2**250 else 0"#}),
89(IS_ADDR_BOUNDED, indoc! {r#"# Verify the assumptions on the relationship between 2**250, ADDR_BOUND and PRIME.
90ADDR_BOUND = ids.ADDR_BOUND % PRIME
91assert (2**250 < ADDR_BOUND <= 2**251) and (2 * 2**250 < PRIME) and (
92        ADDR_BOUND * 2 > PRIME), \
93    'normalize_address() cannot be used with the current constants.'
94ids.is_small = 1 if ids.addr < ADDR_BOUND else 0"#}),
95(SPLIT_INT, indoc! {r#"memory[ids.output] = res = (int(ids.value) % PRIME) % ids.base
96assert res < ids.bound, f'split_int(): Limb {res} is out of range.'"#}),
97(SPLIT_64, indoc! {r#"ids.low = ids.a & ((1<<64) - 1)
98ids.high = ids.a >> 64"#}),
99(SPLIT_FELT, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer
100assert ids.MAX_HIGH < 2**128 and ids.MAX_LOW < 2**128
101assert PRIME - 1 == ids.MAX_HIGH * 2**128 + ids.MAX_LOW
102assert_integer(ids.value)
103ids.low = ids.value & ((1 << 128) - 1)
104ids.high = ids.value >> 128"#}),
105(SQRT, indoc! {r#"from starkware.python.math_utils import isqrt
106value = ids.value % PRIME
107assert value < 2 ** 250, f"value={value} is outside of the range [0, 2**250)."
108assert 2 ** 250 < PRIME
109ids.root = isqrt(value)"#}),
110(UNSIGNED_DIV_REM, indoc! {r#"from starkware.cairo.common.math_utils import assert_integer
111assert_integer(ids.div)
112assert 0 < ids.div <= PRIME // range_check_builtin.bound, \
113    f'div={hex(ids.div)} is out of the valid range.'
114ids.q, ids.r = divmod(ids.value, ids.div)"#}),
115(SIGNED_DIV_REM, indoc! {r#"from starkware.cairo.common.math_utils import as_int, assert_integer
116
117assert_integer(ids.div)
118assert 0 < ids.div <= PRIME // range_check_builtin.bound, \
119    f'div={hex(ids.div)} is out of the valid range.'
120
121assert_integer(ids.bound)
122assert ids.bound <= range_check_builtin.bound // 2, \
123    f'bound={hex(ids.bound)} is out of the valid range.'
124
125int_value = as_int(ids.value, PRIME)
126q, ids.r = divmod(int_value, ids.div)
127
128assert -ids.bound <= q < ids.bound, \
129    f'{int_value} / {ids.div} = {q} is out of the range [{-ids.bound}, {ids.bound}).'
130
131ids.biased_q = q + ids.bound"#}),
132(IS_QUAD_RESIDUE, indoc! {r#"from starkware.crypto.signature.signature import FIELD_PRIME
133from starkware.python.math_utils import div_mod, is_quad_residue, sqrt
134
135x = ids.x
136if is_quad_residue(x, FIELD_PRIME):
137    ids.y = sqrt(x, FIELD_PRIME)
138else:
139    ids.y = sqrt(div_mod(x, 3, FIELD_PRIME), FIELD_PRIME)"#}),
140(FIND_ELEMENT, indoc! {r#"array_ptr = ids.array_ptr
141elm_size = ids.elm_size
142assert isinstance(elm_size, int) and elm_size > 0, \
143    f'Invalid value for elm_size. Got: {elm_size}.'
144key = ids.key
145
146if '__find_element_index' in globals():
147    ids.index = __find_element_index
148    found_key = memory[array_ptr + elm_size * __find_element_index]
149    assert found_key == key, \
150        f'Invalid index found in __find_element_index. index: {__find_element_index}, ' \
151        f'expected key {key}, found key: {found_key}.'
152    # Delete __find_element_index to make sure it's not used for the next calls.
153    del __find_element_index
154else:
155    n_elms = ids.n_elms
156    assert isinstance(n_elms, int) and n_elms >= 0, \
157        f'Invalid value for n_elms. Got: {n_elms}.'
158    if '__find_element_max_size' in globals():
159        assert n_elms <= __find_element_max_size, \
160            f'find_element() can only be used with n_elms<={__find_element_max_size}. ' \
161            f'Got: n_elms={n_elms}.'
162
163    for i in range(n_elms):
164        if memory[array_ptr + elm_size * i] == key:
165            ids.index = i
166            break
167    else:
168        raise ValueError(f'Key {key} was not found.')"#}),
169(SEARCH_SORTED_LOWER, indoc! {r#"array_ptr = ids.array_ptr
170elm_size = ids.elm_size
171assert isinstance(elm_size, int) and elm_size > 0, \
172    f'Invalid value for elm_size. Got: {elm_size}.'
173
174n_elms = ids.n_elms
175assert isinstance(n_elms, int) and n_elms >= 0, \
176    f'Invalid value for n_elms. Got: {n_elms}.'
177if '__find_element_max_size' in globals():
178    assert n_elms <= __find_element_max_size, \
179        f'find_element() can only be used with n_elms<={__find_element_max_size}. ' \
180        f'Got: n_elms={n_elms}.'
181
182for i in range(n_elms):
183    if memory[array_ptr + elm_size * i] >= ids.key:
184        ids.index = i
185        break
186else:
187    ids.index = n_elms"#}),
188(SET_ADD, indoc! {r#"assert ids.elm_size > 0
189assert ids.set_ptr <= ids.set_end_ptr
190elm_list = memory.get_range(ids.elm_ptr, ids.elm_size)
191for i in range(0, ids.set_end_ptr - ids.set_ptr, ids.elm_size):
192    if memory.get_range(ids.set_ptr + i, ids.elm_size) == elm_list:
193        ids.index = i // ids.elm_size
194        ids.is_elm_in_set = 1
195        break
196else:
197    ids.is_elm_in_set = 0"#}),
198(DEFAULT_DICT_NEW, indoc! {r#"if '__dict_manager' not in globals():
199    from starkware.cairo.common.dict import DictManager
200    __dict_manager = DictManager()
201
202memory[ap] = __dict_manager.new_default_dict(segments, ids.default_value)"#}),
203(DICT_NEW, indoc! {r#"if '__dict_manager' not in globals():
204    from starkware.cairo.common.dict import DictManager
205    __dict_manager = DictManager()
206
207memory[ap] = __dict_manager.new_dict(segments, initial_dict)
208del initial_dict"#}),
209(DICT_READ, indoc! {r#"dict_tracker = __dict_manager.get_tracker(ids.dict_ptr)
210dict_tracker.current_ptr += ids.DictAccess.SIZE
211ids.value = dict_tracker.data[ids.key]"#}),
212(DICT_WRITE, indoc! {r#"dict_tracker = __dict_manager.get_tracker(ids.dict_ptr)
213dict_tracker.current_ptr += ids.DictAccess.SIZE
214ids.dict_ptr.prev_value = dict_tracker.data[ids.key]
215dict_tracker.data[ids.key] = ids.new_value"#}),
216(DICT_UPDATE, indoc! {r#"# Verify dict pointer and prev value.
217dict_tracker = __dict_manager.get_tracker(ids.dict_ptr)
218current_value = dict_tracker.data[ids.key]
219assert current_value == ids.prev_value, \
220    f'Wrong previous value in dict. Got {ids.prev_value}, expected {current_value}.'
221
222# Update value.
223dict_tracker.data[ids.key] = ids.new_value
224dict_tracker.current_ptr += ids.DictAccess.SIZE"#}),
225(SQUASH_DICT, indoc! {r#"dict_access_size = ids.DictAccess.SIZE
226address = ids.dict_accesses.address_
227assert ids.ptr_diff % dict_access_size == 0, \
228    'Accesses array size must be divisible by DictAccess.SIZE'
229n_accesses = ids.n_accesses
230if '__squash_dict_max_size' in globals():
231    assert n_accesses <= __squash_dict_max_size, \
232        f'squash_dict() can only be used with n_accesses<={__squash_dict_max_size}. ' \
233        f'Got: n_accesses={n_accesses}.'
234# A map from key to the list of indices accessing it.
235access_indices = {}
236for i in range(n_accesses):
237    key = memory[address + dict_access_size * i]
238    access_indices.setdefault(key, []).append(i)
239# Descending list of keys.
240keys = sorted(access_indices.keys(), reverse=True)
241# Are the keys used bigger than range_check bound.
242ids.big_keys = 1 if keys[0] >= range_check_builtin.bound else 0
243ids.first_key = key = keys.pop()"#}),
244(SQUASH_DICT_INNER_SKIP_LOOP, indoc! {r#"ids.should_skip_loop = 0 if current_access_indices else 1"#}),
245(SQUASH_DICT_INNER_FIRST_ITERATION, indoc! {r#"current_access_indices = sorted(access_indices[key])[::-1]
246current_access_index = current_access_indices.pop()
247memory[ids.range_check_ptr] = current_access_index"#}),
248(SQUASH_DICT_INNER_CHECK_ACCESS_INDEX, indoc! {r#"new_access_index = current_access_indices.pop()
249ids.loop_temps.index_delta_minus1 = new_access_index - current_access_index - 1
250current_access_index = new_access_index"#}),
251(SQUASH_DICT_INNER_CONTINUE_LOOP, indoc! {r#"ids.loop_temps.should_continue = 1 if current_access_indices else 0"#}),
252(SQUASH_DICT_INNER_ASSERT_LEN_KEYS, indoc! {r#"assert len(keys) == 0"#}),
253(SQUASH_DICT_INNER_LEN_ASSERT, indoc! {r#"assert len(current_access_indices) == 0"#}),
254(SQUASH_DICT_INNER_USED_ACCESSES_ASSERT, indoc! {r#"assert ids.n_used_accesses == len(access_indices[key])"#}),
255(SQUASH_DICT_INNER_NEXT_KEY, indoc! {r#"assert len(keys) > 0, 'No keys left but remaining_accesses > 0.'
256ids.next_key = key = keys.pop()"#}),
257(DICT_SQUASH_COPY_DICT, indoc! {r#"# Prepare arguments for dict_new. In particular, the same dictionary values should be copied
258# to the new (squashed) dictionary.
259vm_enter_scope({
260    # Make __dict_manager accessible.
261    '__dict_manager': __dict_manager,
262    # Create a copy of the dict, in case it changes in the future.
263    'initial_dict': dict(__dict_manager.get_dict(ids.dict_accesses_end)),
264})"#}),
265(DICT_SQUASH_UPDATE_PTR, indoc! {r#"# Update the DictTracker's current_ptr to point to the end of the squashed dict.
266__dict_manager.get_tracker(ids.squashed_dict_start).current_ptr = \
267    ids.squashed_dict_end.address_"#}),
268(BIGINT_TO_UINT256, indoc! {r#"ids.low = (ids.x.d0 + ids.x.d1 * ids.BASE) & ((1 << 128) - 1)"#}),
269(UINT256_ADD, indoc! {r#"sum_low = ids.a.low + ids.b.low
270ids.carry_low = 1 if sum_low >= ids.SHIFT else 0
271sum_high = ids.a.high + ids.b.high + ids.carry_low
272ids.carry_high = 1 if sum_high >= ids.SHIFT else 0"#}),
273(UINT256_ADD_LOW, indoc! {r#"sum_low = ids.a.low + ids.b.low
274ids.carry_low = 1 if sum_low >= ids.SHIFT else 0"#}),
275(UINT128_ADD, indoc! {r#"res = ids.a + ids.b
276ids.carry = 1 if res >= ids.SHIFT else 0"#}),
277(UINT256_SUB, indoc! {r#"def split(num: int, num_bits_shift: int = 128, length: int = 2):
278    a = []
279    for _ in range(length):
280        a.append( num & ((1 << num_bits_shift) - 1) )
281        num = num >> num_bits_shift
282    return tuple(a)
283
284def pack(z, num_bits_shift: int = 128) -> int:
285    limbs = (z.low, z.high)
286    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
287
288a = pack(ids.a)
289b = pack(ids.b)
290res = (a - b)%2**256
291res_split = split(res)
292ids.res.low = res_split[0]
293ids.res.high = res_split[1]"#}),
294(UINT256_SQRT, indoc! {r#"from starkware.python.math_utils import isqrt
295n = (ids.n.high << 128) + ids.n.low
296root = isqrt(n)
297assert 0 <= root < 2 ** 128
298ids.root.low = root
299ids.root.high = 0"#}),
300(UINT256_SQRT_FELT, indoc! {r#"from starkware.python.math_utils import isqrt
301n = (ids.n.high << 128) + ids.n.low
302root = isqrt(n)
303assert 0 <= root < 2 ** 128
304ids.root = root"#}),
305(UINT256_SIGNED_NN, indoc! {r#"memory[ap] = 1 if 0 <= (ids.a.high % PRIME) < 2 ** 127 else 0"#}),
306(UINT256_UNSIGNED_DIV_REM, indoc! {r#"a = (ids.a.high << 128) + ids.a.low
307div = (ids.div.high << 128) + ids.div.low
308quotient, remainder = divmod(a, div)
309
310ids.quotient.low = quotient & ((1 << 128) - 1)
311ids.quotient.high = quotient >> 128
312ids.remainder.low = remainder & ((1 << 128) - 1)
313ids.remainder.high = remainder >> 128"#}),
314(UINT256_EXPANDED_UNSIGNED_DIV_REM, indoc! {r#"a = (ids.a.high << 128) + ids.a.low
315div = (ids.div.b23 << 128) + ids.div.b01
316quotient, remainder = divmod(a, div)
317
318ids.quotient.low = quotient & ((1 << 128) - 1)
319ids.quotient.high = quotient >> 128
320ids.remainder.low = remainder & ((1 << 128) - 1)
321ids.remainder.high = remainder >> 128"#}),
322(UINT256_MUL_DIV_MOD, indoc! {r#"a = (ids.a.high << 128) + ids.a.low
323b = (ids.b.high << 128) + ids.b.low
324div = (ids.div.high << 128) + ids.div.low
325quotient, remainder = divmod(a * b, div)
326
327ids.quotient_low.low = quotient & ((1 << 128) - 1)
328ids.quotient_low.high = (quotient >> 128) & ((1 << 128) - 1)
329ids.quotient_high.low = (quotient >> 256) & ((1 << 128) - 1)
330ids.quotient_high.high = quotient >> 384
331ids.remainder.low = remainder & ((1 << 128) - 1)
332ids.remainder.high = remainder >> 128"#}),
333(USORT_ENTER_SCOPE, indoc! {r#"vm_enter_scope(dict(__usort_max_size = globals().get('__usort_max_size')))"#}),
334(USORT_BODY, indoc! {r#"from collections import defaultdict
335
336input_ptr = ids.input
337input_len = int(ids.input_len)
338if __usort_max_size is not None:
339    assert input_len <= __usort_max_size, (
340        f"usort() can only be used with input_len<={__usort_max_size}. "
341        f"Got: input_len={input_len}."
342    )
343
344positions_dict = defaultdict(list)
345for i in range(input_len):
346    val = memory[input_ptr + i]
347    positions_dict[val].append(i)
348
349output = sorted(positions_dict.keys())
350ids.output_len = len(output)
351ids.output = segments.gen_arg(output)
352ids.multiplicities = segments.gen_arg([len(positions_dict[k]) for k in output])"#}),
353(USORT_VERIFY, indoc! {r#"last_pos = 0
354positions = positions_dict[ids.value][::-1]"#}),
355(USORT_VERIFY_MULTIPLICITY_ASSERT, indoc! {r#"assert len(positions) == 0"#}),
356(USORT_VERIFY_MULTIPLICITY_BODY, indoc! {r#"current_pos = positions.pop()
357ids.next_item_index = current_pos - last_pos
358last_pos = current_pos + 1"#}),
359(BLAKE2S_COMPUTE, indoc! {r#"from starkware.cairo.common.cairo_blake2s.blake2s_utils import compute_blake2s_func
360compute_blake2s_func(segments=segments, output_ptr=ids.output)"#}),
361(BLAKE2S_FINALIZE, indoc! {r#"# Add dummy pairs of input and output.
362from starkware.cairo.common.cairo_blake2s.blake2s_utils import IV, blake2s_compress
363
364_n_packed_instances = int(ids.N_PACKED_INSTANCES)
365assert 0 <= _n_packed_instances < 20
366_blake2s_input_chunk_size_felts = int(ids.INPUT_BLOCK_FELTS)
367assert 0 <= _blake2s_input_chunk_size_felts < 100
368
369message = [0] * _blake2s_input_chunk_size_felts
370modified_iv = [IV[0] ^ 0x01010020] + IV[1:]
371output = blake2s_compress(
372    message=message,
373    h=modified_iv,
374    t0=0,
375    t1=0,
376    f0=0xffffffff,
377    f1=0,
378)
379padding = (modified_iv + message + [0, 0xffffffff] + output) * (_n_packed_instances - 1)
380segments.write_arg(ids.blake2s_ptr_end, padding)"#}),
381(BLAKE2S_FINALIZE_V2, indoc! {r#"# Add dummy pairs of input and output.
382from starkware.cairo.common.cairo_blake2s.blake2s_utils import IV, blake2s_compress
383
384_n_packed_instances = int(ids.N_PACKED_INSTANCES)
385assert 0 <= _n_packed_instances < 20
386_blake2s_input_chunk_size_felts = int(ids.BLAKE2S_INPUT_CHUNK_SIZE_FELTS)
387assert 0 <= _blake2s_input_chunk_size_felts < 100
388
389message = [0] * _blake2s_input_chunk_size_felts
390modified_iv = [IV[0] ^ 0x01010020] + IV[1:]
391output = blake2s_compress(
392    message=message,
393    h=modified_iv,
394    t0=0,
395    t1=0,
396    f0=0xffffffff,
397    f1=0,
398)
399padding = (modified_iv + message + [0, 0xffffffff] + output) * (_n_packed_instances - 1)
400segments.write_arg(ids.blake2s_ptr_end, padding)"#}),
401(BLAKE2S_FINALIZE_V3, indoc! {r#"# Add dummy pairs of input and output.
402from starkware.cairo.common.cairo_blake2s.blake2s_utils import IV, blake2s_compress
403
404_n_packed_instances = int(ids.N_PACKED_INSTANCES)
405assert 0 <= _n_packed_instances < 20
406_blake2s_input_chunk_size_felts = int(ids.BLAKE2S_INPUT_CHUNK_SIZE_FELTS)
407assert 0 <= _blake2s_input_chunk_size_felts < 100
408
409message = [0] * _blake2s_input_chunk_size_felts
410modified_iv = [IV[0] ^ 0x01010020] + IV[1:]
411output = blake2s_compress(
412    message=message,
413    h=modified_iv,
414    t0=0,
415    t1=0,
416    f0=0xffffffff,
417    f1=0,
418)
419padding = (message + modified_iv + [0, 0xffffffff] + output) * (_n_packed_instances - 1)
420segments.write_arg(ids.blake2s_ptr_end, padding)"#}),
421(BLAKE2S_ADD_UINT256, indoc! {r#"B = 32
422MASK = 2 ** 32 - 1
423segments.write_arg(ids.data, [(ids.low >> (B * i)) & MASK for i in range(4)])
424segments.write_arg(ids.data + 4, [(ids.high >> (B * i)) & MASK for i in range(4)])"#}),
425(BLAKE2S_ADD_UINT256_BIGEND, indoc! {r#"B = 32
426MASK = 2 ** 32 - 1
427segments.write_arg(ids.data, [(ids.high >> (B * (3 - i))) & MASK for i in range(4)])
428segments.write_arg(ids.data + 4, [(ids.low >> (B * (3 - i))) & MASK for i in range(4)])"#}),
429(EXAMPLE_BLAKE2S_COMPRESS, indoc! {r#"from starkware.cairo.common.cairo_blake2s.blake2s_utils import IV, blake2s_compress
430
431_blake2s_input_chunk_size_felts = int(ids.BLAKE2S_INPUT_CHUNK_SIZE_FELTS)
432assert 0 <= _blake2s_input_chunk_size_felts < 100
433
434new_state = blake2s_compress(
435    message=memory.get_range(ids.blake2s_start, _blake2s_input_chunk_size_felts),
436    h=[IV[0] ^ 0x01010020] + IV[1:],
437    t0=ids.n_bytes,
438    t1=0,
439    f0=0xffffffff,
440    f1=0,
441)
442
443segments.write_arg(ids.output, new_state)"#}),
444(NONDET_BIGINT3_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import split
445
446segments.write_arg(ids.res.address_, split(value))"#}),
447(NONDET_BIGINT3_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import split
448segments.write_arg(ids.res.address_, split(value))"#}),
449(VERIFY_ZERO_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
450
451q, r = divmod(pack(ids.val, PRIME), SECP_P)
452assert r == 0, f"verify_zero: Invalid input {ids.val.d0, ids.val.d1, ids.val.d2}."
453ids.q = q % PRIME"#}),
454(VERIFY_ZERO_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P
455q, r = divmod(pack(ids.val, PRIME), SECP_P)
456assert r == 0, f"verify_zero: Invalid input {ids.val.d0, ids.val.d1, ids.val.d2}."
457ids.q = q % PRIME"#}),
458(VERIFY_ZERO_V3, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
459SECP_P = 2**255-19
460to_assert = pack(ids.val, PRIME)
461q, r = divmod(pack(ids.val, PRIME), SECP_P)
462assert r == 0, f"verify_zero: Invalid input {ids.val.d0, ids.val.d1, ids.val.d2}."
463ids.q = q % PRIME"#}),
464(VERIFY_ZERO_EXTERNAL_SECP, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
465
466q, r = divmod(pack(ids.val, PRIME), SECP_P)
467assert r == 0, f"verify_zero: Invalid input {ids.val.d0, ids.val.d1, ids.val.d2}."
468ids.q = q % PRIME"#}),
469(REDUCE_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
470
471value = pack(ids.x, PRIME) % SECP_P"#}),
472(REDUCE_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
473value = pack(ids.x, PRIME) % SECP_P"#}),
474(REDUCE_ED25519, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
475SECP_P=2**255-19
476
477value = pack(ids.x, PRIME) % SECP_P"#}),
478(UNSAFE_KECCAK, indoc! {r#"from eth_hash.auto import keccak
479
480data, length = ids.data, ids.length
481
482if '__keccak_max_size' in globals():
483    assert length <= __keccak_max_size, \
484        f'unsafe_keccak() can only be used with length<={__keccak_max_size}. ' \
485        f'Got: length={length}.'
486
487keccak_input = bytearray()
488for word_i, byte_i in enumerate(range(0, length, 16)):
489    word = memory[data + word_i]
490    n_bytes = min(16, length - byte_i)
491    assert 0 <= word < 2 ** (8 * n_bytes)
492    keccak_input += word.to_bytes(n_bytes, 'big')
493
494hashed = keccak(keccak_input)
495ids.high = int.from_bytes(hashed[:16], 'big')
496ids.low = int.from_bytes(hashed[16:32], 'big')"#}),
497(UNSAFE_KECCAK_FINALIZE, indoc! {r#"from eth_hash.auto import keccak
498keccak_input = bytearray()
499n_elms = ids.keccak_state.end_ptr - ids.keccak_state.start_ptr
500for word in memory.get_range(ids.keccak_state.start_ptr, n_elms):
501    keccak_input += word.to_bytes(16, 'big')
502hashed = keccak(keccak_input)
503ids.high = int.from_bytes(hashed[:16], 'big')
504ids.low = int.from_bytes(hashed[16:32], 'big')"#}),
505(IS_ZERO_NONDET, indoc! {r#"memory[ap] = to_felt_or_relocatable(x == 0)"#}),
506(IS_ZERO_INT, indoc! {r#"memory[ap] = int(x == 0)"#}),
507(IS_ZERO_PACK_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
508
509x = pack(ids.x, PRIME) % SECP_P"#}),
510(IS_ZERO_PACK_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
511x = pack(ids.x, PRIME) % SECP_P"#}),
512(IS_ZERO_PACK_EXTERNAL_SECP_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
513
514x = pack(ids.x, PRIME) % SECP_P"#}),
515(IS_ZERO_PACK_EXTERNAL_SECP_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
516x = pack(ids.x, PRIME) % SECP_P"#}),
517(IS_ZERO_PACK_ED25519, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
518SECP_P=2**255-19
519
520x = pack(ids.x, PRIME) % SECP_P"#}),
521(IS_ZERO_ASSIGN_SCOPE_VARS, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P
522from starkware.python.math_utils import div_mod
523
524value = x_inv = div_mod(1, x, SECP_P)"#}),
525(IS_ZERO_ASSIGN_SCOPE_VARS_EXTERNAL_SECP, indoc! {r#"from starkware.python.math_utils import div_mod
526
527value = x_inv = div_mod(1, x, SECP_P)"#}),
528(IS_ZERO_ASSIGN_SCOPE_VARS_ED25519, indoc! {r#"SECP_P=2**255-19
529from starkware.python.math_utils import div_mod
530
531value = x_inv = div_mod(1, x, SECP_P)"#}),
532(DIV_MOD_N_PACKED_DIVMOD_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import N, pack
533from starkware.python.math_utils import div_mod, safe_div
534
535a = pack(ids.a, PRIME)
536b = pack(ids.b, PRIME)
537value = res = div_mod(a, b, N)"#}),
538(DIV_MOD_N_PACKED_DIVMOD_EXTERNAL_N, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
539from starkware.python.math_utils import div_mod, safe_div
540
541a = pack(ids.a, PRIME)
542b = pack(ids.b, PRIME)
543value = res = div_mod(a, b, N)"#}),
544(DIV_MOD_N_SAFE_DIV, indoc! {r#"value = k = safe_div(res * b - a, N)"#}),
545(GET_FELT_BIT_LENGTH, indoc! {r#"x = ids.x
546ids.bit_length = x.bit_length()"#}),
547(BIGINT_PACK_DIV_MOD, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
548from starkware.cairo.common.math_utils import as_int
549from starkware.python.math_utils import div_mod, safe_div
550
551p = pack(ids.P, PRIME)
552x = pack(ids.x, PRIME) + as_int(ids.x.d3, PRIME) * ids.BASE ** 3 + as_int(ids.x.d4, PRIME) * ids.BASE ** 4
553y = pack(ids.y, PRIME)
554
555value = res = div_mod(x, y, p)"#}),
556(BIGINT_SAFE_DIV, indoc! {r#"k = safe_div(res * y - x, p)
557value = k if k > 0 else 0 - k
558ids.flag = 1 if k > 0 else 0"#}),
559(DIV_MOD_N_SAFE_DIV_PLUS_ONE, indoc! {r#"value = k_plus_one = safe_div(res * b - a, N) + 1"#}),
560(GET_POINT_FROM_X, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
561
562x_cube_int = pack(ids.x_cube, PRIME) % SECP_P
563y_square_int = (x_cube_int + ids.BETA) % SECP_P
564y = pow(y_square_int, (SECP_P + 1) // 4, SECP_P)
565
566# We need to decide whether to take y or SECP_P - y.
567if ids.v % 2 == y % 2:
568    value = y
569else:
570    value = (-y) % SECP_P"#}),
571(EC_NEGATE, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
572
573y = pack(ids.point.y, PRIME) % SECP_P
574# The modulo operation in python always returns a nonnegative number.
575value = (-y) % SECP_P"#}),
576(EC_NEGATE_EMBEDDED_SECP, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
577SECP_P = 2**255-19
578
579y = pack(ids.point.y, PRIME) % SECP_P
580# The modulo operation in python always returns a nonnegative number.
581value = (-y) % SECP_P"#}),
582(EC_DOUBLE_SLOPE_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
583from starkware.python.math_utils import ec_double_slope
584
585# Compute the slope.
586x = pack(ids.point.x, PRIME)
587y = pack(ids.point.y, PRIME)
588value = slope = ec_double_slope(point=(x, y), alpha=0, p=SECP_P)"#}),
589(EC_DOUBLE_SLOPE_V2, indoc! {r#"from starkware.python.math_utils import ec_double_slope
590from starkware.cairo.common.cairo_secp.secp_utils import pack
591SECP_P = 2**255-19
592
593# Compute the slope.
594x = pack(ids.point.x, PRIME)
595y = pack(ids.point.y, PRIME)
596value = slope = ec_double_slope(point=(x, y), alpha=42204101795669822316448953119945047945709099015225996174933988943478124189485, p=SECP_P)"#}),
597(EC_DOUBLE_SLOPE_V3, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
598from starkware.python.math_utils import div_mod
599
600# Compute the slope.
601x = pack(ids.pt.x, PRIME)
602y = pack(ids.pt.y, PRIME)
603value = slope = div_mod(3 * x ** 2, 2 * y, SECP_P)"#}),
604(EC_DOUBLE_SLOPE_V4, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_ALPHA, SECP256R1_P
605from starkware.cairo.common.cairo_secp.secp_utils import pack
606from starkware.python.math_utils import ec_double_slope
607
608# Compute the slope.
609x = pack(ids.point.x, SECP256R1_P)
610y = pack(ids.point.y, SECP256R1_P)
611value = slope = ec_double_slope(point=(x, y), alpha=SECP256R1_ALPHA, p=SECP256R1_P)"#}),
612(EC_DOUBLE_SLOPE_EXTERNAL_CONSTS, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
613from starkware.python.math_utils import ec_double_slope
614
615# Compute the slope.
616x = pack(ids.point.x, PRIME)
617y = pack(ids.point.y, PRIME)
618value = slope = ec_double_slope(point=(x, y), alpha=ALPHA, p=SECP_P)"#}),
619(COMPUTE_SLOPE_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
620from starkware.python.math_utils import line_slope
621
622# Compute the slope.
623x0 = pack(ids.point0.x, PRIME)
624y0 = pack(ids.point0.y, PRIME)
625x1 = pack(ids.point1.x, PRIME)
626y1 = pack(ids.point1.y, PRIME)
627value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP_P)"#}),
628(COMPUTE_SLOPE_V2, indoc! {r#"from starkware.python.math_utils import line_slope
629from starkware.cairo.common.cairo_secp.secp_utils import pack
630SECP_P = 2**255-19
631# Compute the slope.
632x0 = pack(ids.point0.x, PRIME)
633y0 = pack(ids.point0.y, PRIME)
634x1 = pack(ids.point1.x, PRIME)
635y1 = pack(ids.point1.y, PRIME)
636value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP_P)"#}),
637(COMPUTE_SLOPE_SECP256R1_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
638from starkware.python.math_utils import line_slope
639
640# Compute the slope.
641x0 = pack(ids.point0.x, PRIME)
642y0 = pack(ids.point0.y, PRIME)
643x1 = pack(ids.point1.x, PRIME)
644y1 = pack(ids.point1.y, PRIME)
645value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP_P)"#}),
646(COMPUTE_SLOPE_SECP256R1_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P
647from starkware.cairo.common.cairo_secp.secp_utils import pack
648from starkware.python.math_utils import line_slope
649
650# Compute the slope.
651x0 = pack(ids.point0.x, PRIME)
652y0 = pack(ids.point0.y, PRIME)
653x1 = pack(ids.point1.x, PRIME)
654y1 = pack(ids.point1.y, PRIME)
655value = slope = line_slope(point1=(x0, y0), point2=(x1, y1), p=SECP256R1_P)"#}),
656(IMPORT_SECP256R1_P, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_P as SECP_P"#}),
657(COMPUTE_SLOPE_WHITELIST, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
658from starkware.python.math_utils import div_mod
659
660# Compute the slope.
661x0 = pack(ids.pt0.x, PRIME)
662y0 = pack(ids.pt0.y, PRIME)
663x1 = pack(ids.pt1.x, PRIME)
664y1 = pack(ids.pt1.y, PRIME)
665value = slope = div_mod(y0 - y1, x0 - x1, SECP_P)"#}),
666(EC_DOUBLE_ASSIGN_NEW_X_V1, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
667
668slope = pack(ids.slope, PRIME)
669x = pack(ids.point.x, PRIME)
670y = pack(ids.point.y, PRIME)
671
672value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#}),
673(EC_DOUBLE_ASSIGN_NEW_X_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
674
675slope = pack(ids.slope, PRIME)
676x = pack(ids.point.x, PRIME)
677y = pack(ids.point.y, PRIME)
678
679value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#}),
680(EC_DOUBLE_ASSIGN_NEW_X_V3, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
681SECP_P = 2**255-19
682
683slope = pack(ids.slope, PRIME)
684x = pack(ids.point.x, PRIME)
685y = pack(ids.point.y, PRIME)
686
687value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#}),
688(EC_DOUBLE_ASSIGN_NEW_X_V4, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
689
690slope = pack(ids.slope, PRIME)
691x = pack(ids.pt.x, PRIME)
692y = pack(ids.pt.y, PRIME)
693
694value = new_x = (pow(slope, 2, SECP_P) - 2 * x) % SECP_P"#}),
695(EC_DOUBLE_ASSIGN_NEW_Y, indoc! {r#"value = new_y = (slope * (x - new_x) - y) % SECP_P"#}),
696(SHA256_INPUT, indoc! {r#"ids.full_word = int(ids.n_bytes >= 4)"#}),
697(SHA256_MAIN_CONSTANT_INPUT_LENGTH, indoc! {r#"from starkware.cairo.common.cairo_sha256.sha256_utils import (
698    IV, compute_message_schedule, sha2_compress_function)
699
700_sha256_input_chunk_size_felts = int(ids.SHA256_INPUT_CHUNK_SIZE_FELTS)
701assert 0 <= _sha256_input_chunk_size_felts < 100
702
703w = compute_message_schedule(memory.get_range(
704    ids.sha256_start, _sha256_input_chunk_size_felts))
705new_state = sha2_compress_function(IV, w)
706segments.write_arg(ids.output, new_state)"#}),
707(SHA256_MAIN_ARBITRARY_INPUT_LENGTH, indoc! {r#"from starkware.cairo.common.cairo_sha256.sha256_utils import (
708    compute_message_schedule, sha2_compress_function)
709
710_sha256_input_chunk_size_felts = int(ids.SHA256_INPUT_CHUNK_SIZE_FELTS)
711assert 0 <= _sha256_input_chunk_size_felts < 100
712_sha256_state_size_felts = int(ids.SHA256_STATE_SIZE_FELTS)
713assert 0 <= _sha256_state_size_felts < 100
714w = compute_message_schedule(memory.get_range(
715    ids.sha256_start, _sha256_input_chunk_size_felts))
716new_state = sha2_compress_function(memory.get_range(ids.state, _sha256_state_size_felts), w)
717segments.write_arg(ids.output, new_state)"#}),
718(SHA256_FINALIZE, indoc! {r#"# Add dummy pairs of input and output.
719from starkware.cairo.common.cairo_sha256.sha256_utils import (
720    IV, compute_message_schedule, sha2_compress_function)
721
722_block_size = int(ids.BLOCK_SIZE)
723assert 0 <= _block_size < 20
724_sha256_input_chunk_size_felts = int(ids.SHA256_INPUT_CHUNK_SIZE_FELTS)
725assert 0 <= _sha256_input_chunk_size_felts < 100
726
727message = [0] * _sha256_input_chunk_size_felts
728w = compute_message_schedule(message)
729output = sha2_compress_function(IV, w)
730padding = (message + IV + output) * (_block_size - 1)
731segments.write_arg(ids.sha256_ptr_end, padding)"#}),
732(KECCAK_WRITE_ARGS, indoc! {r#"segments.write_arg(ids.inputs, [ids.low % 2 ** 64, ids.low // 2 ** 64])
733segments.write_arg(ids.inputs + 2, [ids.high % 2 ** 64, ids.high // 2 ** 64])"#}),
734(COMPARE_BYTES_IN_WORD_NONDET, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.n_bytes < ids.BYTES_IN_WORD)"#}),
735(COMPARE_KECCAK_FULL_RATE_IN_BYTES_NONDET, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.n_bytes >= ids.KECCAK_FULL_RATE_IN_BYTES)"#}),
736(BLOCK_PERMUTATION, indoc! {r#"from starkware.cairo.common.keccak_utils.keccak_utils import keccak_func
737_keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS)
738assert 0 <= _keccak_state_size_felts < 100
739
740output_values = keccak_func(memory.get_range(
741    ids.keccak_ptr - _keccak_state_size_felts, _keccak_state_size_felts))
742segments.write_arg(ids.keccak_ptr, output_values)"#}),
743// The 0.10.3 whitelist uses this variant (instead of the one used by the common library), but both hints have the same behaviour
744// We should check for future refactors that may discard one of the variants
745(BLOCK_PERMUTATION_WHITELIST_V1, indoc! {r#"from starkware.cairo.common.cairo_keccak.keccak_utils import keccak_func
746_keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS)
747assert 0 <= _keccak_state_size_felts < 100
748
749output_values = keccak_func(memory.get_range(
750    ids.keccak_ptr - _keccak_state_size_felts, _keccak_state_size_felts))
751segments.write_arg(ids.keccak_ptr, output_values)"#}),
752(BLOCK_PERMUTATION_WHITELIST_V2, indoc! {r#"from starkware.cairo.common.cairo_keccak.keccak_utils import keccak_func
753_keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS)
754assert 0 <= _keccak_state_size_felts < 100
755output_values = keccak_func(memory.get_range(
756    ids.keccak_ptr_start, _keccak_state_size_felts))
757segments.write_arg(ids.output, output_values)"#}),
758(CAIRO_KECCAK_INPUT_IS_FULL_WORD, indoc! {r#"ids.full_word = int(ids.n_bytes >= 8)"#}),
759(CAIRO_KECCAK_FINALIZE_V1, indoc! {r#"# Add dummy pairs of input and output.
760_keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS)
761_block_size = int(ids.BLOCK_SIZE)
762assert 0 <= _keccak_state_size_felts < 100
763assert 0 <= _block_size < 10
764inp = [0] * _keccak_state_size_felts
765padding = (inp + keccak_func(inp)) * _block_size
766segments.write_arg(ids.keccak_ptr_end, padding)"#}),
767(CAIRO_KECCAK_FINALIZE_V2, indoc! {r#"# Add dummy pairs of input and output.
768_keccak_state_size_felts = int(ids.KECCAK_STATE_SIZE_FELTS)
769_block_size = int(ids.BLOCK_SIZE)
770assert 0 <= _keccak_state_size_felts < 100
771assert 0 <= _block_size < 1000
772inp = [0] * _keccak_state_size_felts
773padding = (inp + keccak_func(inp)) * _block_size
774segments.write_arg(ids.keccak_ptr_end, padding)"#}),
775(FAST_EC_ADD_ASSIGN_NEW_X, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
776
777slope = pack(ids.slope, PRIME)
778x0 = pack(ids.point0.x, PRIME)
779x1 = pack(ids.point1.x, PRIME)
780y0 = pack(ids.point0.y, PRIME)
781
782value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#}),
783(FAST_EC_ADD_ASSIGN_NEW_X_V2, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
784SECP_P = 2**255-19
785
786slope = pack(ids.slope, PRIME)
787x0 = pack(ids.point0.x, PRIME)
788x1 = pack(ids.point1.x, PRIME)
789y0 = pack(ids.point0.y, PRIME)
790
791value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#}),
792(FAST_EC_ADD_ASSIGN_NEW_X_V3, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import SECP_P, pack
793
794slope = pack(ids.slope, PRIME)
795x0 = pack(ids.pt0.x, PRIME)
796x1 = pack(ids.pt1.x, PRIME)
797y0 = pack(ids.pt0.y, PRIME)
798
799value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#}),
800(FAST_EC_ADD_ASSIGN_NEW_Y, indoc! {r#"value = new_y = (slope * (x0 - new_x) - y0) % SECP_P"#}),
801(EC_MUL_INNER, indoc! {r#"memory[ap] = (ids.scalar % PRIME) % 2"#}),
802(RELOCATE_SEGMENT, indoc! {r#"memory.add_relocation_rule(src_ptr=ids.src_ptr, dest_ptr=ids.dest_ptr)"#}),
803(TEMPORARY_ARRAY, indoc! {r#"ids.temporary_array = segments.add_temp_segment()"#}),
804(VERIFY_ECDSA_SIGNATURE, indoc! {r#"ecdsa_builtin.add_signature(ids.ecdsa_ptr.address_, (ids.signature_r, ids.signature_s))"#}),
805(SPLIT_OUTPUT_0, indoc! {r#"ids.output0_low = ids.output0 & ((1 << 128) - 1)
806ids.output0_high = ids.output0 >> 128"#}),
807(SPLIT_OUTPUT_1, indoc! {r#"ids.output1_low = ids.output1 & ((1 << 128) - 1)
808ids.output1_high = ids.output1 >> 128"#}),
809(SPLIT_INPUT_3, indoc! {r#"ids.high3, ids.low3 = divmod(memory[ids.inputs + 3], 256)"#}),
810(SPLIT_INPUT_6, indoc! {r#"ids.high6, ids.low6 = divmod(memory[ids.inputs + 6], 256 ** 2)"#}),
811(SPLIT_INPUT_9, indoc! {r#"ids.high9, ids.low9 = divmod(memory[ids.inputs + 9], 256 ** 3)"#}),
812(SPLIT_INPUT_12, indoc! {r#"ids.high12, ids.low12 = divmod(memory[ids.inputs + 12], 256 ** 4)"#}),
813(SPLIT_INPUT_15, indoc! {r#"ids.high15, ids.low15 = divmod(memory[ids.inputs + 15], 256 ** 5)"#}),
814(SPLIT_N_BYTES, indoc! {r#"ids.n_words_to_copy, ids.n_bytes_left = divmod(ids.n_bytes, ids.BYTES_IN_WORD)"#}),
815(SPLIT_OUTPUT_MID_LOW_HIGH, indoc! {r#"tmp, ids.output1_low = divmod(ids.output1, 256 ** 7)
816ids.output1_high, ids.output1_mid = divmod(tmp, 2 ** 128)"#}),
817(NONDET_N_GREATER_THAN_10, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.n >= 10)"#}),
818(NONDET_N_GREATER_THAN_2, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.n >= 2)"#}),
819(RANDOM_EC_POINT, indoc! {r#"from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME
820from starkware.python.math_utils import random_ec_point
821from starkware.python.utils import to_bytes
822
823# Define a seed for random_ec_point that's dependent on all the input, so that:
824#   (1) The added point s is deterministic.
825#   (2) It's hard to choose inputs for which the builtin will fail.
826seed = b"".join(map(to_bytes, [ids.p.x, ids.p.y, ids.m, ids.q.x, ids.q.y]))
827ids.s.x, ids.s.y = random_ec_point(FIELD_PRIME, ALPHA, BETA, seed)"#}),
828(CHAINED_EC_OP_RANDOM_EC_POINT, indoc! {r#"from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME
829from starkware.python.math_utils import random_ec_point
830from starkware.python.utils import to_bytes
831
832n_elms = ids.len
833assert isinstance(n_elms, int) and n_elms >= 0, \
834    f'Invalid value for len. Got: {n_elms}.'
835if '__chained_ec_op_max_len' in globals():
836    assert n_elms <= __chained_ec_op_max_len, \
837        f'chained_ec_op() can only be used with len<={__chained_ec_op_max_len}. ' \
838        f'Got: n_elms={n_elms}.'
839
840# Define a seed for random_ec_point that's dependent on all the input, so that:
841#   (1) The added point s is deterministic.
842#   (2) It's hard to choose inputs for which the builtin will fail.
843seed = b"".join(
844    map(
845        to_bytes,
846        [
847            ids.p.x,
848            ids.p.y,
849            *memory.get_range(ids.m, n_elms),
850            *memory.get_range(ids.q.address_, 2 * n_elms),
851        ],
852    )
853)
854ids.s.x, ids.s.y = random_ec_point(FIELD_PRIME, ALPHA, BETA, seed)"#}),
855(RECOVER_Y, indoc! {r#"from starkware.crypto.signature.signature import ALPHA, BETA, FIELD_PRIME
856from starkware.python.math_utils import recover_y
857ids.p.x = ids.x
858# This raises an exception if `x` is not on the curve.
859ids.p.y = recover_y(ids.x, ALPHA, BETA, FIELD_PRIME)"#}),
860(PACK_MODN_DIV_MODN, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
861from starkware.python.math_utils import div_mod, safe_div
862
863N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
864x = pack(ids.x, PRIME) % N
865s = pack(ids.s, PRIME) % N
866value = res = div_mod(x, s, N)"#}),
867(XS_SAFE_DIV, indoc! {r#"value = k = safe_div(res * s - x, N)"#}),
868// The following hints support the lib https://github.com/NethermindEth/research-basic-Cairo-operations-big-integers/blob/main/lib
869(UINT384_UNSIGNED_DIV_REM, indoc! {r#"def split(num: int, num_bits_shift: int, length: int):
870    a = []
871    for _ in range(length):
872        a.append( num & ((1 << num_bits_shift) - 1) )
873        num = num >> num_bits_shift
874    return tuple(a)
875
876def pack(z, num_bits_shift: int) -> int:
877    limbs = (z.d0, z.d1, z.d2)
878    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
879
880a = pack(ids.a, num_bits_shift = 128)
881div = pack(ids.div, num_bits_shift = 128)
882quotient, remainder = divmod(a, div)
883
884quotient_split = split(quotient, num_bits_shift=128, length=3)
885assert len(quotient_split) == 3
886
887ids.quotient.d0 = quotient_split[0]
888ids.quotient.d1 = quotient_split[1]
889ids.quotient.d2 = quotient_split[2]
890
891remainder_split = split(remainder, num_bits_shift=128, length=3)
892ids.remainder.d0 = remainder_split[0]
893ids.remainder.d1 = remainder_split[1]
894ids.remainder.d2 = remainder_split[2]"#}),
895(UINT384_SPLIT_128, indoc! {r#"ids.low = ids.a & ((1<<128) - 1)
896ids.high = ids.a >> 128"#}),
897(ADD_NO_UINT384_CHECK, indoc! {r#"sum_d0 = ids.a.d0 + ids.b.d0
898ids.carry_d0 = 1 if sum_d0 >= ids.SHIFT else 0
899sum_d1 = ids.a.d1 + ids.b.d1 + ids.carry_d0
900ids.carry_d1 = 1 if sum_d1 >= ids.SHIFT else 0
901sum_d2 = ids.a.d2 + ids.b.d2 + ids.carry_d1
902ids.carry_d2 = 1 if sum_d2 >= ids.SHIFT else 0"#}),
903(UINT384_SQRT, indoc! {r#"from starkware.python.math_utils import isqrt
904
905def split(num: int, num_bits_shift: int, length: int):
906    a = []
907    for _ in range(length):
908        a.append( num & ((1 << num_bits_shift) - 1) )
909        num = num >> num_bits_shift
910    return tuple(a)
911
912def pack(z, num_bits_shift: int) -> int:
913    limbs = (z.d0, z.d1, z.d2)
914    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
915
916a = pack(ids.a, num_bits_shift=128)
917root = isqrt(a)
918assert 0 <= root < 2 ** 192
919root_split = split(root, num_bits_shift=128, length=3)
920ids.root.d0 = root_split[0]
921ids.root.d1 = root_split[1]
922ids.root.d2 = root_split[2]"#}),
923(SUB_REDUCED_A_AND_REDUCED_B, indoc! {r#"def split(num: int, num_bits_shift: int, length: int):
924    a = []
925    for _ in range(length):
926        a.append( num & ((1 << num_bits_shift) - 1) )
927        num = num >> num_bits_shift
928    return tuple(a)
929
930def pack(z, num_bits_shift: int) -> int:
931    limbs = (z.d0, z.d1, z.d2)
932    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
933
934a = pack(ids.a, num_bits_shift = 128)
935b = pack(ids.b, num_bits_shift = 128)
936p = pack(ids.p, num_bits_shift = 128)
937
938res = (a - b) % p
939
940
941res_split = split(res, num_bits_shift=128, length=3)
942
943ids.res.d0 = res_split[0]
944ids.res.d1 = res_split[1]
945ids.res.d2 = res_split[2]"#}),
946(UNSIGNED_DIV_REM_UINT768_BY_UINT384, indoc! {r#"def split(num: int, num_bits_shift: int, length: int):
947    a = []
948    for _ in range(length):
949        a.append( num & ((1 << num_bits_shift) - 1) )
950        num = num >> num_bits_shift 
951    return tuple(a)
952
953def pack(z, num_bits_shift: int) -> int:
954    limbs = (z.d0, z.d1, z.d2)
955    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
956    
957def pack_extended(z, num_bits_shift: int) -> int:
958    limbs = (z.d0, z.d1, z.d2, z.d3, z.d4, z.d5)
959    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
960
961a = pack_extended(ids.a, num_bits_shift = 128)
962div = pack(ids.div, num_bits_shift = 128)
963
964quotient, remainder = divmod(a, div)
965
966quotient_split = split(quotient, num_bits_shift=128, length=6)
967
968ids.quotient.d0 = quotient_split[0]
969ids.quotient.d1 = quotient_split[1]
970ids.quotient.d2 = quotient_split[2]
971ids.quotient.d3 = quotient_split[3]
972ids.quotient.d4 = quotient_split[4]
973ids.quotient.d5 = quotient_split[5]
974
975remainder_split = split(remainder, num_bits_shift=128, length=3)
976ids.remainder.d0 = remainder_split[0]
977ids.remainder.d1 = remainder_split[1]
978ids.remainder.d2 = remainder_split[2]"#}),
979// equal to UNSIGNED_DIV_REM_UINT768_BY_UINT384 but with some whitespace removed
980// in the `num = num >> num_bits_shift` and between `pack` and `pack_extended`
981(UNSIGNED_DIV_REM_UINT768_BY_UINT384_STRIPPED, indoc! {r#"def split(num: int, num_bits_shift: int, length: int):
982    a = []
983    for _ in range(length):
984        a.append( num & ((1 << num_bits_shift) - 1) )
985        num = num >> num_bits_shift
986    return tuple(a)
987
988def pack(z, num_bits_shift: int) -> int:
989    limbs = (z.d0, z.d1, z.d2)
990    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
991
992def pack_extended(z, num_bits_shift: int) -> int:
993    limbs = (z.d0, z.d1, z.d2, z.d3, z.d4, z.d5)
994    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
995
996a = pack_extended(ids.a, num_bits_shift = 128)
997div = pack(ids.div, num_bits_shift = 128)
998
999quotient, remainder = divmod(a, div)
1000
1001quotient_split = split(quotient, num_bits_shift=128, length=6)
1002
1003ids.quotient.d0 = quotient_split[0]
1004ids.quotient.d1 = quotient_split[1]
1005ids.quotient.d2 = quotient_split[2]
1006ids.quotient.d3 = quotient_split[3]
1007ids.quotient.d4 = quotient_split[4]
1008ids.quotient.d5 = quotient_split[5]
1009
1010remainder_split = split(remainder, num_bits_shift=128, length=3)
1011ids.remainder.d0 = remainder_split[0]
1012ids.remainder.d1 = remainder_split[1]
1013ids.remainder.d2 = remainder_split[2]"#}),
1014(UINT384_SIGNED_NN, indoc! {r#"memory[ap] = 1 if 0 <= (ids.a.d2 % PRIME) < 2 ** 127 else 0"#}),
1015(IMPORT_SECP256R1_ALPHA, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_ALPHA as ALPHA"#}),
1016(IMPORT_SECP256R1_N, indoc! {r#"from starkware.cairo.common.cairo_secp.secp256r1_utils import SECP256R1_N as N"#}),
1017(UINT384_GET_SQUARE_ROOT, indoc! {r#"from starkware.python.math_utils import is_quad_residue, sqrt
1018
1019def split(num: int, num_bits_shift: int = 128, length: int = 3):
1020    a = []
1021    for _ in range(length):
1022        a.append( num & ((1 << num_bits_shift) - 1) )
1023        num = num >> num_bits_shift
1024    return tuple(a)
1025
1026def pack(z, num_bits_shift: int = 128) -> int:
1027    limbs = (z.d0, z.d1, z.d2)
1028    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
1029
1030
1031generator = pack(ids.generator)
1032x = pack(ids.x)
1033p = pack(ids.p)
1034
1035success_x = is_quad_residue(x, p)
1036root_x = sqrt(x, p) if success_x else None
1037
1038success_gx = is_quad_residue(generator*x, p)
1039root_gx = sqrt(generator*x, p) if success_gx else None
1040
1041# Check that one is 0 and the other is 1
1042if x != 0:
1043    assert success_x + success_gx ==1
1044
1045# `None` means that no root was found, but we need to transform these into a felt no matter what
1046if root_x == None:
1047    root_x = 0
1048if root_gx == None:
1049    root_gx = 0
1050ids.success_x = int(success_x)
1051ids.success_gx = int(success_gx)
1052split_root_x = split(root_x)
1053split_root_gx = split(root_gx)
1054ids.sqrt_x.d0 = split_root_x[0]
1055ids.sqrt_x.d1 = split_root_x[1]
1056ids.sqrt_x.d2 = split_root_x[2]
1057ids.sqrt_gx.d0 = split_root_gx[0]
1058ids.sqrt_gx.d1 = split_root_gx[1]
1059ids.sqrt_gx.d2 = split_root_gx[2]"#}),
1060(UINT256_GET_SQUARE_ROOT, indoc! {r#"from starkware.python.math_utils import is_quad_residue, sqrt
1061
1062def split(a: int):
1063    return (a & ((1 << 128) - 1), a >> 128)
1064
1065def pack(z) -> int:
1066    return z.low + (z.high << 128)
1067
1068generator = pack(ids.generator)
1069x = pack(ids.x)
1070p = pack(ids.p)
1071
1072success_x = is_quad_residue(x, p)
1073root_x = sqrt(x, p) if success_x else None
1074success_gx = is_quad_residue(generator*x, p)
1075root_gx = sqrt(generator*x, p) if success_gx else None
1076
1077# Check that one is 0 and the other is 1
1078if x != 0:
1079    assert success_x + success_gx == 1
1080
1081# `None` means that no root was found, but we need to transform these into a felt no matter what
1082if root_x == None:
1083    root_x = 0
1084if root_gx == None:
1085    root_gx = 0
1086ids.success_x = int(success_x)
1087ids.success_gx = int(success_gx)
1088split_root_x = split(root_x)
1089# print('split root x', split_root_x)
1090split_root_gx = split(root_gx)
1091ids.sqrt_x.low = split_root_x[0]
1092ids.sqrt_x.high = split_root_x[1]
1093ids.sqrt_gx.low = split_root_gx[0]
1094ids.sqrt_gx.high = split_root_gx[1]"#}),
1095(UINT384_DIV, indoc! {r#"from starkware.python.math_utils import div_mod
1096
1097def split(num: int, num_bits_shift: int, length: int):
1098    a = []
1099    for _ in range(length):
1100        a.append( num & ((1 << num_bits_shift) - 1) )
1101        num = num >> num_bits_shift
1102    return tuple(a)
1103
1104def pack(z, num_bits_shift: int) -> int:
1105    limbs = (z.d0, z.d1, z.d2)
1106    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
1107
1108a = pack(ids.a, num_bits_shift = 128)
1109b = pack(ids.b, num_bits_shift = 128)
1110p = pack(ids.p, num_bits_shift = 128)
1111# For python3.8 and above the modular inverse can be computed as follows:
1112# b_inverse_mod_p = pow(b, -1, p)
1113# Instead we use the python3.7-friendly function div_mod from starkware.python.math_utils
1114b_inverse_mod_p = div_mod(1, b, p)
1115
1116
1117b_inverse_mod_p_split = split(b_inverse_mod_p, num_bits_shift=128, length=3)
1118
1119ids.b_inverse_mod_p.d0 = b_inverse_mod_p_split[0]
1120ids.b_inverse_mod_p.d1 = b_inverse_mod_p_split[1]
1121ids.b_inverse_mod_p.d2 = b_inverse_mod_p_split[2]"#}),
1122(INV_MOD_P_UINT256, indoc! {r#"from starkware.python.math_utils import div_mod
1123
1124def split(a: int):
1125    return (a & ((1 << 128) - 1), a >> 128)
1126
1127def pack(z, num_bits_shift: int) -> int:
1128    limbs = (z.low, z.high)
1129    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
1130
1131a = pack(ids.a, 128)
1132b = pack(ids.b, 128)
1133p = pack(ids.p, 128)
1134# For python3.8 and above the modular inverse can be computed as follows:
1135# b_inverse_mod_p = pow(b, -1, p)
1136# Instead we use the python3.7-friendly function div_mod from starkware.python.math_utils
1137b_inverse_mod_p = div_mod(1, b, p)
1138
1139b_inverse_mod_p_split = split(b_inverse_mod_p)
1140
1141ids.b_inverse_mod_p.low = b_inverse_mod_p_split[0]
1142ids.b_inverse_mod_p.high = b_inverse_mod_p_split[1]"#}),
1143(HI_MAX_BITLEN, indoc! {r#"ids.len_hi = max(ids.scalar_u.d2.bit_length(), ids.scalar_v.d2.bit_length())-1"#}),
1144(QUAD_BIT, indoc! {r#"ids.quad_bit = (
1145    8 * ((ids.scalar_v >> ids.m) & 1)
1146    + 4 * ((ids.scalar_u >> ids.m) & 1)
1147    + 2 * ((ids.scalar_v >> (ids.m - 1)) & 1)
1148    + ((ids.scalar_u >> (ids.m - 1)) & 1)
1149)"#}),
1150(INV_MOD_P_UINT512, indoc! {r#"def pack_512(u, num_bits_shift: int) -> int:
1151    limbs = (u.d0, u.d1, u.d2, u.d3)
1152    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
1153
1154x = pack_512(ids.x, num_bits_shift = 128)
1155p = ids.p.low + (ids.p.high << 128)
1156x_inverse_mod_p = pow(x,-1, p)
1157
1158x_inverse_mod_p_split = (x_inverse_mod_p & ((1 << 128) - 1), x_inverse_mod_p >> 128)
1159
1160ids.x_inverse_mod_p.low = x_inverse_mod_p_split[0]
1161ids.x_inverse_mod_p.high = x_inverse_mod_p_split[1]"#}),
1162(DI_BIT, indoc! {r#"ids.dibit = ((ids.scalar_u >> ids.m) & 1) + 2 * ((ids.scalar_v >> ids.m) & 1)"#}),
1163(EC_RECOVER_DIV_MOD_N_PACKED, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
1164from starkware.python.math_utils import div_mod, safe_div
1165
1166N = pack(ids.n, PRIME)
1167x = pack(ids.x, PRIME) % N
1168s = pack(ids.s, PRIME) % N
1169value = res = div_mod(x, s, N)"#}),
1170(UINT512_UNSIGNED_DIV_REM, indoc! {r#"def split(num: int, num_bits_shift: int, length: int):
1171    a = []
1172    for _ in range(length):
1173        a.append( num & ((1 << num_bits_shift) - 1) )
1174        num = num >> num_bits_shift
1175    return tuple(a)
1176
1177def pack(z, num_bits_shift: int) -> int:
1178    limbs = (z.low, z.high)
1179    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
1180
1181def pack_extended(z, num_bits_shift: int) -> int:
1182    limbs = (z.d0, z.d1, z.d2, z.d3)
1183    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
1184
1185x = pack_extended(ids.x, num_bits_shift = 128)
1186div = pack(ids.div, num_bits_shift = 128)
1187
1188quotient, remainder = divmod(x, div)
1189
1190quotient_split = split(quotient, num_bits_shift=128, length=4)
1191
1192ids.quotient.d0 = quotient_split[0]
1193ids.quotient.d1 = quotient_split[1]
1194ids.quotient.d2 = quotient_split[2]
1195ids.quotient.d3 = quotient_split[3]
1196
1197remainder_split = split(remainder, num_bits_shift=128, length=2)
1198ids.remainder.low = remainder_split[0]
1199ids.remainder.high = remainder_split[1]"#}),
1200(EC_RECOVER_SUB_A_B, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
1201from starkware.python.math_utils import div_mod, safe_div
1202
1203a = pack(ids.a, PRIME)
1204b = pack(ids.b, PRIME)
1205
1206value = res = a - b"#}),
1207(A_B_BITAND_1, indoc! {r#"ids.a_lsb = ids.a & 1
1208ids.b_lsb = ids.b & 1"#}),
1209(EC_RECOVER_PRODUCT_MOD, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
1210from starkware.python.math_utils import div_mod, safe_div
1211
1212a = pack(ids.a, PRIME)
1213b = pack(ids.b, PRIME)
1214product = a * b
1215m = pack(ids.m, PRIME)
1216
1217value = res = product % m"#}),
1218(UINT256_MUL_INV_MOD_P, indoc! {r#"from starkware.python.math_utils import div_mod
1219
1220def split(a: int):
1221    return (a & ((1 << 128) - 1), a >> 128)
1222
1223def pack(z, num_bits_shift: int) -> int:
1224    limbs = (z.low, z.high)
1225    return sum(limb << (num_bits_shift * i) for i, limb in enumerate(limbs))
1226
1227a = pack(ids.a, 128)
1228b = pack(ids.b, 128)
1229p = pack(ids.p, 128)
1230# For python3.8 and above the modular inverse can be computed as follows:
1231# b_inverse_mod_p = pow(b, -1, p)
1232# Instead we use the python3.7-friendly function div_mod from starkware.python.math_utils
1233b_inverse_mod_p = div_mod(1, b, p)
1234
1235b_inverse_mod_p_split = split(b_inverse_mod_p)
1236
1237ids.b_inverse_mod_p.low = b_inverse_mod_p_split[0]
1238ids.b_inverse_mod_p.high = b_inverse_mod_p_split[1]"#}),
1239(EC_RECOVER_PRODUCT_DIV_M, indoc! {r#"value = k = product // m"#}),
1240(SQUARE_SLOPE_X_MOD_P, indoc! {r#"from starkware.cairo.common.cairo_secp.secp_utils import pack
1241
1242slope = pack(ids.slope, PRIME)
1243x0 = pack(ids.point0.x, PRIME)
1244x1 = pack(ids.point1.x, PRIME)
1245y0 = pack(ids.point0.y, PRIME)
1246
1247value = new_x = (pow(slope, 2, SECP_P) - x0 - x1) % SECP_P"#}),
1248(SPLIT_XX, indoc! {r#"PRIME = 2**255 - 19
1249II = pow(2, (PRIME - 1) // 4, PRIME)
1250
1251xx = ids.xx.low + (ids.xx.high<<128)
1252x = pow(xx, (PRIME + 3) // 8, PRIME)
1253if (x * x - xx) % PRIME != 0:
1254    x = (x * II) % PRIME
1255if x % 2 != 0:
1256    x = PRIME - x
1257ids.x.low = x & ((1<<128)-1)
1258ids.x.high = x >> 128"#}),
1259(SKIP_NEXT_INSTRUCTION, indoc! {r#"skip_next_instruction()"#}, "test_utils"),
1260(PRINT_FELT, indoc! {r#"print(ids.x)"#}, "test_utils"),
1261(PRINT_ARR, indoc! {r#"print(bytes.fromhex(f"{ids.name:062x}").decode().replace('\x00',''))
1262arr = [memory[ids.arr + i] for i in range(ids.arr_len)]
1263print(arr)"#}, "test_utils"),
1264(PRINT_DICT, indoc! {r#"print(bytes.fromhex(f"{ids.name:062x}").decode().replace('\x00',''))
1265data = __dict_manager.get_dict(ids.dict_ptr)
1266print(
1267    {k: v if isinstance(v, int) else [memory[v + i] for i in range(ids.pointer_size)] for k, v in data.items()}
1268)"#}, "test_utils"),
1269(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)"),
1270(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)"),
1271(NONDET_ELEMENTS_OVER_TEN, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.elements_end - ids.elements >= 10)"#}),
1272(NONDET_ELEMENTS_OVER_TWO, indoc! {r#"memory[ap] = to_felt_or_relocatable(ids.elements_end - ids.elements >= 2)"#}),
1273(EXCESS_BALANCE, indoc! {r#"from excess_balance import excess_balance_func
1274
1275res = excess_balance_func(ids, memory, __dict_manager)
1276
1277ids.check_account_value = res["account_value"]
1278ids.check_excess_balance = res["excess_balance"]
1279ids.check_margin_requirement_d = res["margin_requirement"]
1280ids.check_unrealized_pnl_d = res["unrealized_pnl"]"#})
1281}