Why does range_check_ptr chek for [0, 2^128) instead of [0, P/2)

254 Views Asked by At

According to the doc a felt is a field element, ie any integer between in the range [0, P) with P = 2^251 + 17 * 2^192 + 1.

On the other hand, the range_check_ptr checks that a felt is within [0, 2^128).

I don't understand this limitation : why not [0, 2^250) such that a felt is somehow a int250?

MWE:

%lang starknet

from starkware.cairo.common.math import assert_nn

@view
func foo{range_check_ptr}() -> ():
    alloc_locals
    local x
    %{ ids.x = PRIME - 10 %}
    assert_nn(a=x)
    return ()
end

this fails because of how the assert_nn and range_check_ptr are defined but I can't understand why it's design so:

Error at pc=0:0:
Got an exception while executing a hint.
    %{
        ^^
Cairo traceback (most recent call last):
contracts/main.cairo:6:6: (pc=0:13)
func foo{range_check_ptr}() -> ():
     ^**^
contracts/tmp.cairo:10:5: (pc=0:8)
    assert_nn(a=x)
    ^************^

Traceback (most recent call last):
  File "/Users/clementwalter/.pyenv/versions/3.9.13/envs/starksheet/lib/python3.9/site-packages/starkware/cairo/common/math.cairo", line 43, in <module>
    assert 0 <= ids.a % PRIME < range_check_builtin.bound, f\'a = {ids.a} is out of range.\'
AssertionError: a = 3618502788666131213697322783095070105623107215331596699973092056135872020471 is out of range.'})
1

There are 1 best solutions below

3
On

Both are valid options. You can use 2 250-range checks to simulate a 128-range check, or 3-128 range checks to simulate a 250-range check. It boils down to performance (less is better) and what is a more common use.