Giter Club home page Giter Club logo

cairo-lang's Introduction

Introduction

Cairo is a programming language for writing provable programs.

Documentation

The Cairo documentation consists of two parts: "Hello Cairo" and "How Cairo Works?". Both parts can be found in https://cairo-lang.org/docs/.

We recommend starting from Setting up the environment.

Installation instructions

You should be able to download the python package zip file directly from github and install it using pip. See Setting up the environment.

However, if you want to build it yourself, you can build it from the git repository. It is recommended to run the build inside a docker (as explained below), since it guarantees that all the dependencies are installed. Alternatively, you can try following the commands in the docker file.

Building using the dockerfile

Note: This section is relevant only if you wish to build the Cairo python-package yourself, rather than downloading it.

The root directory holds a dedicated Dockerfile, which automatically builds the package and runs the unit tests on a simulated Ubuntu 18.04 environment. You should have docker installed (see https://docs.docker.com/get-docker/).

Clone the repository and initialize the git submodules using:

> git clone [email protected]:starkware-libs/cairo-lang.git
> cd cairo-lang

Build the docker image:

> docker build --tag cairo .

If everything works, you should see

Successfully tagged cairo:latest

Once the docker image is built, you can fetch the python package zip file using:

> container_id=$(docker create cairo)
> docker cp ${container_id}:/app/cairo-lang-0.13.1.zip .
> docker rm -v ${container_id}

cairo-lang's People

Contributors

danielkroeni avatar kobigurk avatar liorgold2 avatar raitobezarius avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cairo-lang's Issues

Missing test_utils.py file

There is an import
from starkware.cairo.common.test_utils import create_memory_struct
In src/starkware/cairo/builtin_selection/select_input_builtins_test.py and in src/starkware/cairo/builtin_selection/validate_builtins_test.py

But no such function create_memory_struct exists anywhere. It was forgotten to commit the file I suppose.

How to Convert Trace to Proof?

  1. How can I make trace from cairo program? Do I need to run with --proof_mode ?

  2. How can I convert trace to STARK proof without SHARP? Is prover released now? Or Can you give some reference for conversion?

Command specific CLI --help

Hi Cairo team,

It would be nice if the CLI --help flag displayed help for an individual command. Example

starknet get_block --help
usage: starknet [-h] [-v] [--network NETWORK] [--network_id NETWORK_ID] [--chain_id CHAIN_ID] [--wallet WALLET] [--no_wallet] [--account ACCOUNT]
                [--account_dir ACCOUNT_DIR] [--flavor {Debug,Release,RelWithDebInfo}] [--gateway_url GATEWAY_URL] [--feeder_gateway_url FEEDER_GATEWAY_URL]
                {call,deploy,deploy_account,estimate_fee,get_block,get_state_update,get_code,get_contract_addresses,get_full_contract,get_storage_at,get_transaction,get_transaction_receipt,get_transaction_trace,invoke,tx_status}

A tool to communicate with StarkNet.

positional arguments:
  {call,deploy,deploy_account,estimate_fee,get_block,get_state_update,get_code,get_contract_addresses,get_full_contract,get_storage_at,get_transaction,get_transaction_receipt,get_transaction_trace,invoke,tx_status}

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show program's version number and exit
  --network NETWORK     The name of the StarkNet network.
  --network_id NETWORK_ID
                        A textual identifier of the network. Used for account management.
  --chain_id CHAIN_ID   The chain id (either as a hex number or as a string).
  --wallet WALLET       The name of the wallet, including the python module and wallet class.
  --no_wallet           Perform a direct contract call without an account contract.
  --account ACCOUNT     The name of the account. If not given, the default account (as defined by the wallet) is used.
  --account_dir ACCOUNT_DIR
                        The directory containing the account files (default: '~/.starknet_accounts').
  --flavor {Debug,Release,RelWithDebInfo}
                        Build flavor.
  --gateway_url GATEWAY_URL
                        The URL of a StarkNet gateway.
  --feeder_gateway_url FEEDER_GATEWAY_URL
                        The URL of a StarkNet feeder gateway.

shows the generic starknet help information rather than the specific flags for get_block

Use the conventional equality operator in assert statements

Cairo should be optimized for readability and that’s why the statement assert <expr0> = <expr1> bugs me a bit.
Simply using the conventional equality operator == instead would feel cleaner than overwriting the assignment operator = because this unconventional syntax reads like a classic typo or bad code style until you’ve internalized that assert overwrites =.

I guess the design rationale was to prevent this common typo? If so, I think it would benefit Cairo’s readability if instead the equality operator stays consistently == and the assignment operator = becomes illegal after an assert. This prevents that typo while using the most simple syntax.

Unable to build on mac

It fails in one of two places:

[ 24%] Generating ../../python_libs/gen_solidity_venv.info
....
File "/usr/local/Cellar/[email protected]/3.7.13_1/bin/../Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 812, in fsencode
    filename = fspath(filename)  # Does type-checking of `filename`.
TypeError: expected str, bytes or os.PathLike object, not NoneType
src/cmake_utils/CMakeFiles/gen_solidity_venv.dir/build.make:73: *** [python_libs/gen_solidity_venv.info] error 1

or

[ 80%] Generating ../../../../python_libs/cairo_lang_venv.info
...
File "/usr/local/Cellar/[email protected]/3.7.13_1/bin/../Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 812, in fsencode
    filename = fspath(filename)  # Does type-checking of `filename`.
TypeError: expected str, bytes or os.PathLike object, not NoneType
src/starkware/cairo/lang/CMakeFiles/cairo_lang_venv.dir/build.make:78: *** [python_libs/cairo_lang_venv.info] error 1

Which one is unpredictable.

python --version
Python 3.7.13

Library call not working as expected

I'm working through the documentation at the moment and can't get library calls to work: https://www.cairo-lang.org/docs/hello_starknet/calling_contracts.html.

The docs say: "To perform a library call, use the contract interface as above, but prepend library_call_ to the function name and pass a class hash instead of a contract address."

However when I run starknet-compile I get the following error:

Unknown identifier '__main__.IBalanceContract.library_call_increase_balance'.

Full response below - I'm running cairo-lang 0.8.0 btw - any ideas why?

(cairo_venv) parkyeung@Parks-MacBook-Pro cairo-tutorial % starknet-compile contracts/proxy_contract_library_call.cairo --output proxy_contract_library_call_compiled.json --abi proxy_contract_library_call_abi.json
contracts/proxy_contract_library_call.cairo:43:5: Unknown identifier '__main__.IBalanceContract.library_call_increase_balance'.
    IBalanceContract.library_call_increase_balance(
    ^********************************************^

Error on proof generation

Hi I have some issues when I use cairo-run --proof_mode

Here is my error

Traceback (most recent call last):
  File "/home/hephai/cairo_venv/bin/cairo-run", line 10, in <module>
    sys.exit(main())
  File "/home/hephai/cairo_venv/lib/python3.7/site-packages/starkware/cairo/lang/vm/cairo_run.py", line 179, in main
    res = cairo_run(args)
  File "/home/hephai/cairo_venv/lib/python3.7/site-packages/starkware/cairo/lang/vm/cairo_run.py", line 253, in cairo_run
    end = runner.initialize_main_entrypoint()
  File "/home/hephai/cairo_venv/lib/python3.7/site-packages/starkware/cairo/lang/vm/cairo_runner.py", line 207, in initialize_main_entrypoint
    return self.program_base + self.program.get_label("__end__")
  File "/home/hephai/cairo_venv/lib/python3.7/site-packages/starkware/cairo/lang/compiler/program.py", line 124, in get_label
    name=name, expected_type=LabelDefinition, full_name_lookup=full_name_lookup
  File "/home/hephai/cairo_venv/lib/python3.7/site-packages/starkware/cairo/lang/compiler/program.py", line 113, in get_identifier
    result = self.identifiers.search(accessible_scopes=[self.main_scope], name=scoped_name)
  File "/home/hephai/cairo_venv/lib/python3.7/site-packages/starkware/cairo/lang/compiler/identifier_manager.py", line 220, in search
    res = self._search(accessible_scopes=accessible_scopes, name=name, get_scope=False)
  File "/home/hephai/cairo_venv/lib/python3.7/site-packages/starkware/cairo/lang/compiler/identifier_manager.py", line 212, in _search
    raise MissingIdentifierError(name[:1])
starkware.cairo.lang.compiler.identifier_manager.MissingIdentifierError: Unknown identifier '__end__'.

Why this problem happens? and how can I fix it?

Unable to deploy contract to mainnet

When attempting to deploy a contract to mainnet via this command:
starknet deploy --contract artifacts/Things.json --inputs 0x6d6567612067616d6572206c6561677565 <some_address> --account alpha-mainnet --network alpha-mainnet --account_dir ~/.starknet_accounts

I'm getting the following error:

Got BadRequest while trying to access https://alpha-mainnet.starknet.io/gateway/add_transaction. Status code: 500; text: {"code": "StarknetErrorCode.NON_PERMITTED_CONTRACT", "message": "The contract class attempted to be deployed is not permitted."}.
Traceback (most recent call last):
  File "/Users/<user>/code/cairo-sandbox/env/lib/python3.8/site-packages/services/external_api/client.py", line 121, in _send_request
    raise BadRequest(status_code=response.status, text=text)
services.external_api.client.BadRequest: HTTP error ocurred. Status: 500. Text: {"code": "StarknetErrorCode.NON_PERMITTED_CONTRACT", "message": "The contract class attempted to be deployed is not permitted."}
Error: BadRequest: HTTP error ocurred. Status: 500. Text: {"code": "StarknetErrorCode.NON_PERMITTED_CONTRACT", "message": "The contract class attempted to be deployed is not permitted."}

The contract was successfully declared using starknet declare --contract artifacts/Things.json . I was also able to successfully deploy this contract to goerli.

Could not build docker image.

Hit to RUN

docker build --tag cairo .

After a period of operation, it show lots of error to prompt build fail.

PLEASE see the below:

`
=> ERROR [15/22] RUN ctest -V -j8 807.6ss

[15/22] RUN ctest -V -j8:
#20 0.867 UpdateCTestConfiguration from :/app/build/Release/DartConfiguration.tcl
#20 0.868 Parse Config file:/app/build/Release/DartConfiguration.tcl
#20 0.888 UpdateCTestConfiguration from :/app/build/Release/DartConfiguration.tcl
#20 0.888 Parse Config file:/app/build/Release/DartConfiguration.tcl
#20 0.890 Test project /app/build/Release
#20 0.892 Constructing a list of tests
#20 0.972 Done constructing a list of tests
#20 0.973 Updating test list for fixtures
#20 0.973 Added 0 tests to meet fixture requirements
#20 0.979 Checking test dependency graph...
#20 0.980 Checking test dependency graph end
#20 0.983 test 1
#20 0.984 Start 1: cairo_common_test
#20 0.986
#20 0.986 1: Test command: /app/build/Release/src/starkware/cairo/common/cairo_common_test
#20 0.987 1: Test timeout computed to be: 1500
#20 0.994 test 2
#20 0.994 Start 2: cairo_run_builtins_test
#20 0.995
#20 0.995 2: Test command: /app/build/Release/src/starkware/cairo/lang/builtins/cairo_run_builtins_test
#20 0.995 2: Test timeout computed to be: 1500
#20 0.998 test 3
#20 0.998 Start 3: cairo_compile_test
#20 0.999
#20 0.999 3: Test command: /app/build/Release/src/starkware/cairo/lang/compiler/cairo_compile_test
#20 0.999 3: Test timeout computed to be: 1500
#20 1.002 test 4
#20 1.003 Start 4: cairo_tracer_test
#20 1.003
#20 1.003 4: Test command: /app/build/Release/src/starkware/cairo/lang/tracer/cairo_tracer_test
#20 1.003 4: Test timeout computed to be: 1500
#20 1.007 test 5
#20 1.008 Start 5: cairo_vm_test
#20 1.008
#20 1.008 5: Test command: /app/build/Release/src/starkware/cairo/lang/vm/cairo_vm_test
#20 1.008 5: Test timeout computed to be: 1500
#20 1.025 test 6
#20 1.025 Start 6: fact_checker_test
#20 1.026
#20 1.026 6: Test command: /app/build/Release/src/starkware/cairo/sharp/fact_checker_test
#20 1.026 6: Test timeout computed to be: 1500
#20 1.060 test 7
#20 1.060 Start 7: sharp_client_lib_test
#20 1.060
#20 1.060 7: Test command: /app/build/Release/src/starkware/cairo/sharp/sharp_client_lib_test
#20 1.060 7: Test timeout computed to be: 1500
#20 1.077 test 8
#20 1.078 Start 8: starkware_python_utils_test
#20 1.078
#20 1.078 8: Test command: /app/build/Release/src/starkware/python/starkware_python_utils_test
#20 1.078 8: Test timeout computed to be: 1500
#20 7.881 8: ============================= test session starts ==============================
#20 7.882 8: platform linux -- Python 3.7.13, pytest-7.0.0, pluggy-1.0.0
#20 7.946 8: rootdir: /app/build/Release
#20 7.946 8: plugins: asyncio-0.18.0
#20 7.946 8: asyncio: mode=legacy
#20 16.59 8: collected 33 items
#20 16.59 8:
#20 16.62 8: src/starkware/python/starkware_python_utils_test_venv-site/starkware/python/expression_string_test.py . [ 3%]
#20 16.64 8: [ 3%]
#20 16.65 8: src/starkware/python/starkware_python_utils_test_venv-site/starkware/python/math_utils_test.py . [ 6%]
.......
.......
.......
#20 805.9 18: DeprecationWarning,
#20 805.9 18:
#20 805.9 18: python_pip/python3.7/pip_pytest_asyncio/pytest_asyncio/plugin.py:228
#20 805.9 18: /app/build/Release/python_pip/python3.7/pip_pytest_asyncio/pytest_asyncio/plugin.py:228: DeprecationWarning: '@pytest.fixture' is applied to <fixture starknet, file=/app/build/Release/src/starkware/starknet/testing/starknet_testing_test_venv-site/starkware/starknet/testing/starknet_test.py, line=13> in 'legacy' mode, please replace it with '@pytest_asyncio.fixture' as a preparation for switching to 'strict' mode (or use 'auto' mode to seamlessly handle all these fixtures as asyncio-driven).
#20 805.9 18: DeprecationWarning,
#20 805.9 18:
#20 805.9 18: python_pip/python3.7/pip_pytest_asyncio/pytest_asyncio/plugin.py:228
#20 805.9 18: /app/build/Release/python_pip/python3.7/pip_pytest_asyncio/pytest_asyncio/plugin.py:228: DeprecationWarning: '@pytest.fixture' is applied to <fixture contract, file=/app/build/Release/src/starkware/starknet/testing/starknet_testing_test_venv-site/starkware/starknet/testing/starknet_test.py, line=18> in 'legacy' mode, please replace it with '@pytest_asyncio.fixture' as a preparation for switching to 'strict' mode (or use 'auto' mode to seamlessly handle all these fixtures as asyncio-driven).
#20 805.9 18: DeprecationWarning,
#20 805.9 18:
#20 805.9 18: -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
#20 805.9 18: =========================== short test summary info ============================
#20 805.9 18: ERROR src/starkware/starknet/testing/starknet_testing_test_venv-site/starkware/starknet/testing/mock_starknet_messaging_test.py::test_mock_send_message_from_l2
#20 805.9 18: ERROR src/starkware/starknet/testing/starknet_testing_test_venv-site/starkware/starknet/testing/mock_starknet_messaging_test.py::test_mock_consume_message_to_l2
#20 805.9 18: ERROR src/starkware/starknet/testing/starknet_testing_test_venv-site/starkware/starknet/testing/postman_test.py::test_postman_l1_to_l2_positive_flow
#20 805.9 18: ERROR src/starkware/starknet/testing/starknet_testing_test_venv-site/starkware/starknet/testing/postman_test.py::test_postman_l1_to_l2_another_mock_starknet_messaging_contract
#20 805.9 18: ERROR src/starkware/starknet/testing/starknet_testing_test_venv-site/starkware/starknet/testing/postman_test.py::test_postman_l2_to_l1_positive_flow
#20 805.9 18: ============= 9 passed, 11 warnings, 5 errors in 667.18s (0:11:07) =============
#20 806.2 18: Exception ignored in: <function Ganache.del at 0x400e795200>
#20 806.2 18: Traceback (most recent call last):
#20 806.2 18: File "/app/build/Release/src/starkware/starknet/testing/starknet_testing_test_venv-site/starkware/eth/eth_test_utils.py", line 96, in del
#20 806.2 18: self.stop()
#20 806.2 18: File "/app/build/Release/src/starkware/starknet/testing/starknet_testing_test_venv-site/starkware/eth/eth_test_utils.py", line 99, in stop
#20 806.2 18: if not self.is_alive:
#20 806.2 18: AttributeError: 'Ganache' object has no attribute 'is_alive'
#20 807.4 20/20 Test #18: starknet_testing_test ..................***Failed 686.31 sec
#20 807.4
#20 807.4 95% tests passed, 1 tests failed out of 20
#20 807.4
#20 807.4 Total Test time (real) = 806.49 sec
#20 807.4
#20 807.4 The following tests FAILED:
#20 807.4 18 - starknet_testing_test (Failed)
#20 807.4 Errors while running CTest
#20 807.4 Output from these tests are in: /app/build/Release/Testing/Temporary/LastTest.log
#20 807.4 Use "--rerun-failed --output-on-failure" to re-run the failed cases verbosely.


executor failed running [/bin/sh -c ctest -V -j8]: exit code: 8`

Use strings for numbers in `pedersen_params.json`

Using strings in place of the large numbers in that JSON file would allow sharing and maintaining it more easily in other languages that don't have great support for big numbers in JSON parsing.

request: support eth-hash >= 0.3.2

Feature Request

Issue

Right now, eth-hash is pinned to 0.2.0. Other dependencies in my project require eth-hash >= 0.3.2. I am wondering if there is anything we can do?

Possible Solution

Either upgrading eth-hash to >= 0.3.2 or relaxing the pin constraints

How to verify a proof?

The documentation is light on this, but it looks like a proof of computation can be generated with cairo-run ... --proof_mode --trace-file=output.trace. How do I verify this proof?

Valid signature rejection not that negligible and possibly exploitable

crypto.signature.signature.verify() rejects signatures with an r, inverse s, or message (hash) greater than 2**251 < EC_ORDER:

assert 1 <= r < 2 ** N_ELEMENT_BITS_ECDSA, "r = %s" % r
assert 1 <= w < 2 ** N_ELEMENT_BITS_ECDSA, "w = %s" % w
assert 0 <= msg_hash < 2 ** N_ELEMENT_BITS_ECDSA, "msg_hash = %s" % msg_hash

There's a gap of ~2^196 values, thus a probability to hit an invalid r or s that is of the order of 2^(196-251)/2 = 2^-54, when generating an ECDSA sig for some fixed message using a standard algorithm (rather than Cairo's sign(), which enforces these constraints).

I can't think of a specific attack scenario at the moment, but I would expect to find applications where either

  1. that accidental failure rate would be unacceptably high, or
  2. adversaries could bruteforce invalid sigs to do some kind of DoS, or worse (with plausible deniability)

I probably miss some of the context, and you may have a good reason to verify sigs that way.

cairo-lang doesn't support the current solidity version

I am trying to create a FreeBSD port for cairo-lang, but the solidity package is at the latest version, and binary isn't available for FreeBSD.

Could you please support the latest solidity version. Or otherwise how to make it work on FreeBSD?

Thanks,
Yuri

Curve25519 support

There are known concerns about the older ECDSA algorithm that is implemented in the common library. More relevantly for my practical considerations libsodium does only implement Curve25519.

It may be a good idea if cairo could also support the Curve25519 (and by consequence Ed25519)?

Cannot run demo for AMM

I wanted to compile and run the demo for automated market maker in cairo-lang/src/demo/amm_demo/amm.cairo but I could not run the compiled program. When calling cairo-run --program=test_compiled.json --print_output I get this error:

Error: Builtins {'output', 'pedersen', 'range_check'} are not present in layout "plain"

I am running inside the python virtual environment. Is there something I am missing here?

Python doesn't properly handle large negative numbers

I have the number -1024168008553002790667416331076178940052697074220694435907157227142754829457, the result of a Pedersen hashing. When I try to access it using Python (i.e. as a hint), I get 2594334780113128423029906452018891165570410141110902264065934828993117191024, although running serialize_word on the value confirms that it's the -1024... one.

I assume this is either some kind of overflow in Python, or an issue with negative numbers? I need to access the hash value inside a hint , so this is tricky behavior to work with.

Does `pip3 install cairo-lang` fail depending on Python version?

I tried this page
https://www.cairo-lang.org/docs/quickstart.html

but I failed pip3 install cairo-lang

environment

Python 3.7.13
Mac OS Montery(v12.3)
Applle Silicon

error message

❯ pip3 install cairo-lang

Collecting cairo-lang
  Using cached cairo-lang-0.8.0.zip (882 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [1 lines of output]
      ERROR: Can not execute `setup.py` since setuptools is not available in the build environment.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

what I did
upgrade setuptools by this

pip3 install --upgrade setuptools
-> did't work well

next, I try to downgrade python version, but it can't work any versions...
(Ignore this issue as I don't think it is directly related to cairo.)

If you were able to install cairo-lang on another Python 3.7 series, I would appreciate it if you could tell me the version.

for example v 3.7.5

❯ pyenv install 3.7.5
python-build: use [email protected] from homebrew
python-build: use readline from homebrew
Downloading Python-3.7.5.tar.xz...
-> https://www.python.org/ftp/python/3.7.5/Python-3.7.5.tar.xz
Installing Python-3.7.5...
python-build: use readline from homebrew
python-build: use zlib from xcode sdk

BUILD FAILED (OS X 12.3 using python-build 20180424)

Inspect or clean up the working tree at /var/folders/x1/jhqvlmx964z9_x4mqg7g_l040000gn/T/python-build.20220324143851.18869
Results logged to /var/folders/x1/jhqvlmx964z9_x4mqg7g_l040000gn/T/python-build.20220324143851.18869.log

Last 10 log lines:
checking for --with-cxx-main=<compiler>... no
checking for clang++... no
configure:

  By default, distutils will build C++ extension modules with "clang++".
  If this is not intended, then set CXX on the configure command line.

checking for the platform triplet based on compiler characteristics... darwin
configure: error: internal configure error for the platform triplet, please file a bug report
make: *** No targets specified and no makefile found.  Stop.

~/cairo_practice main* 14s

sha256 in cairo-lang

overtime, I guess we will see sha256 and some other hash function to have open source implementation in cairo-lang.

and these should be very. easily by reverse engineering from published contract.

so cairo-lang reverse engineering will also appear.

jack

cairo-mode for emacs

figured there should be an implementation for emacs's LSP or extend GenericMode
I can see if this could be implemented in emacs lisp

How the conversion from EcPoint to felt works?

Im using the fastecdsa library to generate a key pair, the public key is in the format of an x and y point, (x,y), I send this value to a function expecting public_key: felt, and the operation works fine, but then I want to make sure the value stored is correct and I don't see how it automatically transforms the point into a felt, therefore I cannot assert the test result.

Something like this:
Cairo code:
func set_public_key{ syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr }(new_public_key: felt): Account_set_public_key(new_public_key) return () end
test:

private_key = 123456789987654321
public_key = keys.get_public_key(private_key, curve.secp256k1)
#public key : X: 0x3595819058943de6b847791de355b3591738dd5055eac0d9839e27149da4491e
#Y: 0x6fb37ec164564d3467d7923c84a2c3cc2b4e68f5ee8254abc0ac3c571f906bc7
await signer.send_transactions(account, [(account.contract_address, 'set_public_key', [public_key])])
execution_info = await account.get_public_key().call()
#result=1813293060336465068570802339647185657676088914728234993269889516456358561835
assert execution_info.result == (public_key,)

So how can I transform my key to then assert the test?

Restriction on the prime used not matching the paper

The Cairo paper stipulates that the prime to be used needs to be greater than 2^63 (i.e. be of 64 bits at least), for proper instruction decoding. This check is done in src/starkware/cairo/lang/compiler/program.py, line 68.

However I came accross this additional check in src/starkware/cairo/lang/compiler/encode.py, line 38 that prevents the use of any prime below 2^64. The last bit, called RESERVED_BIT, is commented out, and I couldn't find where this discrepancy with the Cairo paper was actually being leveraged. Couldn't this check be relaxed to match the paper? Or are there modifications I missed requiring this?

Are mainstream symmetric cryptographic algorithms practical in Cairo?

I believe the ZKCP pay-to-sudoku demo assembled a symmetric stream cipher from a hash function, but I'm wondering whether the advances in Cairo have made it possible to implement more "mainstream" symmetric encryption algorithms nowadays?

Has someone already done this? If not, is it worthwhile trying to implement a standardized cryptographic algorithm in Cairo, or would the proofs still get impractically large at this point? Or are there other barriers that would make it unpleasant right now?

Provide hints for implementing a backend for a minimized version of Solidity

I'm trying to understand what it means to compile a smart contract language to/through Cairo and still have it execute.

To get the ball rolling, here is a minimized variant of Solidity:

contract Puzzle {
    function puzzle(int a, int b, ERC20 coin) public {
        if (a^2 + b^2 == 458) {
            coin.transfer(caller, 1);
        }
    }
}

If I were to just compile this into EVM, I'd eventually have a CALL opcode that is triggered by some logic.

Questions:

  1. What could this example be extended with to provide a useful off-chain proving-of-something?
  2. If we don't target EVM, how do we eventually achieve something comparable to an on-chain CALL?

Is it only a portion of the code that gets compiled to Cairo? Or is EVM eventually produced by Cairo?

[Python 3.9] `_field_types` attribute of the `typing.NamedTuple` class has been removed

Name Version
Python 3.9.9
cairo-lang 0.8.0

Cairo-lang 0.8.0 throws the following error when used with Python 3.9.

args = contract_hash_full_args(hash_ptr=RelocatableValue(segment_index=8, offset=0), contract_definition=ContractDefinition(a...62507520, 5188850464614744064, 5193354042767540224, 5189976364521848832, 0, 5193354038472572928, 23451087663173[140](https://github.com/software-mansion/protostar/runs/5631001118?check_suite_focus=true#step:8:140)46]))

    def gen_typed_args(self, args: NamedTuple) -> List[MaybeRelocatable]:
        """
        Takes a Cairo typed NamedTuple generated with CairoStructFactory and
        returns a Cairo-friendly argument list.
        """
        cairo_args = []
>       for value, field_type in zip(args, args._field_types.values()):
E       AttributeError: 'contract_hash_full_args' object has no attribute '_field_types'

../lib/python3.9/site-packages/starkware/cairo/lang/vm/memory_segments.py:169: AttributeError

https://github.com/software-mansion/protostar/runs/5631001118?check_suite_focus=true


The _field_types attribute of the typing.NamedTuple class has been removed. It was deprecated since Python 3.8. Use the annotations attribute instead. (Contributed by Serhiy Storchaka in bpo-40182.)

https://docs.python.org/3/whatsnew/3.9.html

Use poetry for dependencies management

Looking at the codebase, it seems like a manual non-standard dependencies management solution has been used for the project.

Current python best practices instead advocate for more advanced tools than plain requirements.txt file, for example, poetry.

Is the team open to a PR in this direction?

Vscode Cairo formatter extension not working

I'm trying to get the vscode extension (https://www.cairo-lang.org/docs/quickstart.html#visual-studio-code-setup) working. I'm on a Windows machine, using WSL2, vscode launched from the venv.

Using cairo-format contract.cairo works from the command line. But using the plugin by "Command Palette -> Format document" gives:

Formatting failed: No terminal matches '
' in the current parser context, at line 1 col 15

%lang starknet
              ^
Expected one of: 
	* LSQB
	* DOT
	* LBRACE
	* BUILTINS
	* RPAR
	* HEXINT
	* INT
	* _ARROW
	* "+="
	* EQUAL
	* LPAR
	* STAR
	* _DBL_STAR
	* IDENTIFIER
	* HINT
	* SLASH
	* PLUS
	* _AT
	* STRING
	* LANG
	* RBRACE
	* MINUS
	* COMMENT
	* _NEQ
	* SHORT_STRING
	* COMMA
	* COLON
	* _DBL_PLUS
	* _NEWLINE
	* SEMICOLON
	* AMPERSAND
	* RSQB
	* _DBL_EQ

Previous tokens: Token('IDENTIFIER', 'starknet')

The first three lines of my contract are:

%lang starknet

from starkware.cairo.common.alloc import alloc

Unpacking error not clear/actionable (0.6.2)

Hi There,

I thought I'd ask for help but also flag as a potential improvement to the compiler in the spirit of https://elm-lang.org/news/compiler-errors-for-humans.

  1. Do you know how to fix the below code? What is the unpacking error here?
  2. Do you think there are ways to make unpacking errors more clearly actionable for users?
%lang starknet
%builtins pedersen range_check

from starkware.cairo.common.cairo_builtins import HashBuiltin
from starkware.cairo.common.bitwise import bitwise_and
from starkware.cairo.common.math import assert_nn_le

const WORD = 2 ** 16
const MASK = WORD - 1
const MASK2 = MASK * WORD

@view
func pack2{range_check_ptr}(x : felt, y : felt) -> (res : felt):
    assert_nn_le(x, WORD)  # Could be removed as an optimization
    assert_nn_le(y, WORD)  # Could be removed as an optimization
    return (x * WORD + y)
end

@view
func unpack1(packed : felt) -> (res : felt):
    tempvar masked = bitwise_and(packed, MASK2)
    let (res) = (masked / WORD)
    return (res=res)
end

@view
func unpack2(packed : felt) -> (res : felt):
    let (res) = (bitwise_and(packed, MASK))
    return (res=res)
end

The following code errors with:

Cannot unpack (masked / WORD)

FYI this is the test I used:

import os
import pytest

from starkware.starknet.testing.starknet import Starknet

CONTRACT_FILE = os.path.join(os.path.dirname(__file__), "packing.cairo")


@pytest.mark.asyncio
async def test_can_call_external_contract():
    starknet = await Starknet.empty()

    contract = await starknet.deploy(
        source=CONTRACT_FILE,
    )

    a = 2 ** 13 + 1
    b = 7

    packed = (await contract.pack2(a, b).call()).result

    assert (await contract.unpack1(packed).call()).result == a
    assert (await contract.unpack2(packed).call()).result == b

RecursionError: maximum recursion depth exceeded in comparison

Following the steps here: https://www.cairo-lang.org/docs/quickstart.html

I get this error when trying to compile the example program

// LOT OF TEXT
  File "/Users/davidwong/cairo_venv/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py", line 686, in field_for_schema
    generic_field = _field_for_generic_type(typ, base_schema, typ_frame, **metadata)
  File "/Users/davidwong/cairo_venv/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py", line 528, in _field_for_generic_type
    children = tuple(
  File "/Users/davidwong/cairo_venv/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py", line 529, in <genexpr>
    field_for_schema(arg, base_schema=base_schema, typ_frame=typ_frame)
  File "/Users/davidwong/cairo_venv/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py", line 718, in field_for_schema
    or _internal_class_schema(typ, base_schema, typ_frame)
  File "/Users/davidwong/cairo_venv/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py", line 393, in _internal_class_schema
    attributes.update(
  File "/Users/davidwong/cairo_venv/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py", line 396, in <genexpr>
    field_for_schema(
  File "/Users/davidwong/cairo_venv/lib/python3.9/site-packages/marshmallow_dataclass/__init__.py", line 721, in field_for_schema
    return marshmallow.fields.Nested(nested, **metadata)
  File "/Users/davidwong/cairo_venv/lib/python3.9/site-packages/marshmallow/fields.py", line 544, in __init__
    if not is_collection(exclude):
  File "/Users/davidwong/cairo_venv/lib/python3.9/site-packages/marshmallow/utils.py", line 57, in is_collection
    return is_iterable_but_not_string(obj) and not isinstance(obj, Mapping)
  File "/Users/davidwong/.pyenv/versions/3.9.5/lib/python3.9/abc.py", line 98, in __instancecheck__
    return _abc_instancecheck(cls, instance)
RecursionError: maximum recursion depth exceeded in comparison

running

➜  cairo_program pyenv local
3.7.8

on MacOS

Error running starknet-compile using python 3.10

Hi,

As far as I can tell cairo-lang is not explicitly built/tested for python 3.10, but I just wanted to log this issue:

Running starknet-compile using python 3.10 yields:

Traceback (most recent call last):
  File "/usr/local/bin/starknet-compile", line 7, in <module>
    from starkware.starknet.compiler.compile import main  # noqa
  File "/usr/local/lib/python3.10/site-packages/starkware/starknet/compiler/compile.py", line 7, in <module>
    from starkware.cairo.lang.compiler.assembler import assemble
  File "/usr/local/lib/python3.10/site-packages/starkware/cairo/lang/compiler/assembler.py", line 7, in <module>
    from starkware.cairo.lang.compiler.program import CairoHint, Program
  File "/usr/local/lib/python3.10/site-packages/starkware/cairo/lang/compiler/program.py", line 25, in <module>
    from starkware.starkware_utils.marshmallow_dataclass_fields import IntAsHex
  File "/usr/local/lib/python3.10/site-packages/starkware/starkware_utils/marshmallow_dataclass_fields.py", line 6, in <module>
    from frozendict import frozendict
  File "/usr/local/lib/python3.10/site-packages/frozendict/__init__.py", line 16, in <module>
    class frozendict(collections.Mapping):
AttributeError: module 'collections' has no attribute 'Mapping'

frozendict is pinned to version 1.2, released in 2016. In python 3.10 importing abstract base classes from collections directly has been disabled.

Can't Build Repo

Can't seem to build the repo with the latest version - there may be a bug - either running pip3 install or running from docker:

CMake Error at CMakeLists.txt:15 (include):
include could not find load file:

repos/starkware-public/cmake_utils/exe_rules.cmake

CMake Error at CMakeLists.txt:16 (include):
include could not find load file:

repos/starkware-public/cmake_utils/python_rules.cmake

CMake Error at CMakeLists.txt:17 (include):
include could not find load file:

repos/starkware-public/cmake_utils/pip_rules.cmake

CMake Error at CMakeLists.txt:18 (python_get_pip_deps):
Unknown CMake command "python_get_pip_deps".

Mac M1 setup does not work without correct flags due to fastecdsa dependency

Hi! This has been discussed in the nile GH, it might be good to state that a command which adequately uses gmp and clang assuming gmp is installed via brew and clang through pip is:

CFLAGS=-I`brew --prefix gmp`/include LDFLAGS=-L`brew --prefix gmp`/lib pip install ecdsa fastecdsa sympy

Because otherwise the error is rather non-descriptive.

Error when trying to use verify_eth_signature

Using the 0.8.2.1 version of Cairo-lang I attempt to use the verify_eth_signature located inside starkware.cairo.common.cairo_secp.signature I get the following error:

 /com.docker.devenvironments.code/.tox/default/lib/python3.7/site-packages/starkware/cairo/common/cairo_secp/signature.cairo:209:44: Unknown identifier 'bitwise_ptr'.
E           func verify_eth_signature{range_check_ptr, bitwise_ptr : BitwiseBuiltin*, keccak_ptr : felt*}(
E                                                      ^***************************^

Screen Shot 2022-05-18 at 4 06 09 PM

[Unhandled exception] cairo-compile is crashing due to lark 'UnexpectedCharacters' exception

Hey,

During fuzzing, I found a case making the Cairo compiler crash. The crash occurs when compiling an invalid Cairo code that raises a lark lark.exceptions.UnexpectedCharacters exception (that is not catch internally).

Reproduction

from starkware.cairo.lang.compiler.cairo_compile import compile_cairo

code = "\x0b,\x0b,VV"

program = compile_cairo(code, 2 ** 251 + 17 * 2 ** 192 + 1, debug_info=True)

Traceback

python3 replay_crash.py 
Traceback (most recent call last):
  File "replay_crash.py", line 5, in <module>
    program = compile_cairo(code, 2 ** 251 + 17 * 2 ** 192 + 1, debug_info=True)
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/cairo_compile.py", line 259, in compile_cairo
    program, _ = compile_cairo_ex(
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/cairo_compile.py", line 228, in compile_cairo_ex
    preprocessed_program = preprocess_codes(
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/preprocessor/preprocess_codes.py", line 26, in preprocess_codes
    pass_manager.run(context)
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/preprocessor/pass_manager.py", line 55, in run
    stage.run(context)
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/preprocessor/default_pass_manager.py", line 154, in run
    self.collect_module(
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/preprocessor/default_pass_manager.py", line 124, in collect_module
    files = collect_imports(filename, read_file=read_file_fixed)
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/import_loader.py", line 30, in collect_imports
    collector.collect(curr_pkg_name)
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/import_loader.py", line 81, in collect
    parsed_file: CairoFile = parse_file(code, filename=filename)
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/parser.py", line 241, in parse_file
    return parse(filename, code, "cairo_file", CairoFile, parser_context=parser_context)
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/parser.py", line 209, in parse
    raise wrap_lark_error(err, input_file) from None
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/parser.py", line 161, in wrap_lark_error
    raise err
  File "/usr/cairo_venv/lib/python3.8/site-packages/starkware/cairo/lang/compiler/parser.py", line 195, in parse
    for token in parser.lexer_state.lex(parser_state):
  File "/usr/cairo_venv/lib/python3.8/site-packages/lark/lexer.py", line 388, in lex
    yield self.next_token(state, parser_state)
  File "/usr/cairo_venv/lib/python3.8/site-packages/lark/lexer.py", line 398, in next_token
    raise UnexpectedCharacters(lex_state.text, line_ctr.char_pos, line_ctr.line, line_ctr.column,
lark.exceptions.UnexpectedCharacters: No terminal matches '
                                                           ' in the current parser context, at line 1 col 1

,
 ,VV
^
Expected one of: 
	* COMMENT
	* SEMICOLON
	* COLON
	* RSQB
	* LANG
	* LPAR
	* SHORT_STRING
	* DOT
	* HEXINT
	* STRING
	* RPAR
	* SLASH
	* LBRACE
	* MINUS
	* _ARROW
	* _DBL_PLUS
	* IDENTIFIER
	* STAR
	* _NEWLINE
	* _AT
	* EQUAL
	* HINT
	* COMMA
	* PLUS
	* "+="
	* AMPERSAND
	* RBRACE
	* _DBL_EQ
	* _DBL_STAR
	* BUILTINS
	* INT
	* LSQB
	* _NEQ

cairo-compile command-line tool is also crashing when providing directly those bytes inside a file.

Happy to help if you have any questions ;)

Allow 'BadRequest' to be more import-able

Currently, when communicating with Starknet, an occasional BadRequest gets raised (for example, requesting a block number that is too high). I want to be able to catch and handle these exceptions accordingly. To do this, I have to import the class, which defined here: https://github.com/starkware-libs/cairo-lang/blob/master/src/services/external_api/base_client.py#L18

To import this, it looks like this:

from services.external_api.base_client import BadRequest

You can see starknet.py importing this class here: https://github.com/software-mansion/starknet.py/blob/development/starknet_py/net/client.py#L4
, along with RetryConfig.

This is a feature request to have these classes be more importable to downstream users of cairo-lang, such as starknet.py,

Benefits:

  1. It is more obvious what package this is coming from
  2. It is less likely to change
  3. Prevents potential naming collisions
  4. Makes IDEs happier

Thank you :)

Encountered error while trying to install package.

I run 'pip3 install cairo-lang', show error below.

 In file included from src/curveMath.c:1:
      src/curveMath.h:6:10: fatal error: 'gmp.h' file not found
      #include <gmp.h>
               ^~~~~~~
      1 error generated.
      error: command 'clang' failed with exit status 1
      [end of output]

I acctualy did 'brew install gmp', but show this message.
does anyone know about solution?

  • Mac OS Montery(v12.2.1)
  • Applle Silicon

InvalidURL when querying for blockNumber=pending

Hi StarkNet team!

I'm trying to run a local devnet node via https://github.com/Shard-Labs/starknet-devnet
However, I'm observing that requests to a basic endpoint like get_block are failing due to:

starknet get_block --number pending --gateway_url 127.0.0.1:5000 --feeder_gateway_url 127.0.0.1:5000
Got InvalidURL while trying to access /feeder_gateway/get_block?blockNumber=pending.
Traceback (most recent call last):
  File "/opt/homebrew/lib/python3.9/site-packages/services/external_api/base_client.py", line 115, in _send_request
    async with session.request(
  File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/client.py", line 1138, in __aenter__
    self._resp = await self._coro
  File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/client.py", line 507, in _request
    req = self._request_class(
  File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/client_reqrep.py", line 305, in __init__
    self.update_host(url)
  File "/opt/homebrew/lib/python3.9/site-packages/aiohttp/client_reqrep.py", line 366, in update_host
    raise InvalidURL(url)
aiohttp.client_exceptions.InvalidURL: /feeder_gateway/get_block?blockNumber=pending
Error: InvalidURL: /feeder_gateway/get_block?blockNumber=pending

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.