├── .bazelrc ├── .gitattributes ├── .gitignore ├── BUILD ├── Dockerfile ├── LICENSE.txt ├── README.md ├── WORKSPACE ├── bazel_utils ├── BUILD ├── __init__.py ├── extract_artifacts.py ├── gen_python_exe.py ├── get_from_cairo_lang.bzl ├── patches │ ├── BUILD │ └── rules_python.patch ├── pytest_wrapper.py ├── python.bzl ├── python │ ├── BUILD │ ├── defs.bzl │ └── stub.sh ├── solc_wrapper.py └── solidity.bzl ├── docker_common_deps.sh ├── load_cairo_lang.bzl ├── package.json ├── pypy3.9_archive_build_file.bzl ├── scripts ├── BUILD ├── pypy-requirements-deps.json ├── pypy-requirements-gen.txt ├── pypy-requirements.txt ├── requirements-deps.json ├── requirements-gen.txt └── requirements.txt ├── src ├── demo │ └── amm_demo │ │ ├── amm.cairo │ │ ├── amm_contract.sol │ │ ├── demo.py │ │ └── prove_batch.py ├── services │ ├── config │ │ ├── BUILD │ │ └── general_config.py │ ├── everest │ │ ├── api │ │ │ ├── feeder_gateway │ │ │ │ ├── BUILD │ │ │ │ ├── docs.py │ │ │ │ ├── feeder_gateway_client.py │ │ │ │ └── response_objects.py │ │ │ └── gateway │ │ │ │ ├── BUILD │ │ │ │ ├── gateway_client.py │ │ │ │ ├── set_config_request.py │ │ │ │ ├── transaction.py │ │ │ │ └── transaction_type.py │ │ ├── business_logic │ │ │ ├── BUILD │ │ │ ├── internal_transaction.py │ │ │ ├── state.py │ │ │ ├── state_api.py │ │ │ └── transaction_execution_objects.py │ │ └── definitions │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── constants.py │ │ │ ├── fields.py │ │ │ └── general_config.py │ ├── external_api │ │ ├── BUILD │ │ ├── client.py │ │ ├── eth_gas_constants.py │ │ ├── has_uri_prefix.py │ │ ├── utils.py │ │ └── vars.bzl │ └── utils │ │ └── http_status_code.py ├── starkware │ ├── cairo │ │ ├── BUILD │ │ ├── bootloaders │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── aggregator_utils.py │ │ │ ├── aggregator_utils_test.py │ │ │ ├── applicative_bootloader │ │ │ │ ├── BUILD │ │ │ │ └── applicative_bootloader.cairo │ │ │ ├── bootloader │ │ │ │ ├── BUILD │ │ │ │ ├── bootloader.cairo │ │ │ │ ├── constants.cairo │ │ │ │ ├── run_bootloader.cairo │ │ │ │ └── supported_verifier_hashes.json │ │ │ ├── compute_fact.py │ │ │ ├── fact_topology.py │ │ │ ├── generate_fact.py │ │ │ ├── hash_program.py │ │ │ ├── program_hash_test_utils.py │ │ │ └── simple_bootloader │ │ │ │ ├── BUILD │ │ │ │ ├── execute_task.cairo │ │ │ │ ├── run_simple_bootloader.cairo │ │ │ │ ├── simple_bootloader.cairo │ │ │ │ └── verify_builtins.cairo │ │ ├── builtin_selection │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── inner_select_builtins.cairo │ │ │ ├── select_builtins.cairo │ │ │ ├── select_input_builtins.cairo │ │ │ ├── select_input_builtins_test.py │ │ │ ├── validate_builtins.cairo │ │ │ └── validate_builtins_test.py │ │ ├── cairo_verifier │ │ │ ├── BUILD │ │ │ ├── cairo_verifier_layout_program.bzl │ │ │ ├── cairo_verifier_layouts.bzl │ │ │ ├── layouts │ │ │ │ └── all_cairo │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── cairo_verifier.cairo │ │ │ │ │ ├── program_hash.json │ │ │ │ │ └── program_hash_test.py │ │ │ └── objects.cairo │ │ ├── common │ │ │ ├── BUILD │ │ │ ├── alloc.cairo │ │ │ ├── bitwise.cairo │ │ │ ├── bool.cairo │ │ │ ├── builtin_keccak │ │ │ │ ├── BUILD │ │ │ │ └── keccak.cairo │ │ │ ├── builtin_poseidon │ │ │ │ ├── BUILD │ │ │ │ └── poseidon.cairo │ │ │ ├── cairo_blake2s │ │ │ │ ├── BUILD │ │ │ │ ├── blake2s.cairo │ │ │ │ ├── blake2s_test.cairo │ │ │ │ ├── blake2s_test.py │ │ │ │ ├── blake2s_utils.py │ │ │ │ └── packed_blake2s.cairo │ │ │ ├── cairo_builtins.cairo │ │ │ ├── cairo_ec_op │ │ │ │ ├── BUILD │ │ │ │ └── ec_op.cairo │ │ │ ├── cairo_ecdsa │ │ │ │ ├── BUILD │ │ │ │ └── ecdsa.cairo │ │ │ ├── cairo_function_runner.py │ │ │ ├── cairo_keccak │ │ │ │ ├── BUILD │ │ │ │ ├── keccak.cairo │ │ │ │ ├── keccak_utils.py │ │ │ │ └── packed_keccak.cairo │ │ │ ├── cairo_secp │ │ │ │ ├── BUILD │ │ │ │ ├── bigint.cairo │ │ │ │ ├── bigint3.cairo │ │ │ │ ├── constants.cairo │ │ │ │ ├── ec.cairo │ │ │ │ ├── ec_point.cairo │ │ │ │ ├── field.cairo │ │ │ │ ├── secp256r1_utils.py │ │ │ │ ├── secp_utils.py │ │ │ │ └── signature.cairo │ │ │ ├── cairo_sha256 │ │ │ │ ├── BUILD │ │ │ │ ├── sha256_utils.cairo │ │ │ │ └── sha256_utils.py │ │ │ ├── copy_indices.cairo │ │ │ ├── default_dict.cairo │ │ │ ├── dict.cairo │ │ │ ├── dict.py │ │ │ ├── dict_access.cairo │ │ │ ├── ec.cairo │ │ │ ├── ec_point.cairo │ │ │ ├── find_element.cairo │ │ │ ├── hash.cairo │ │ │ ├── hash_chain.cairo │ │ │ ├── hash_chain.py │ │ │ ├── hash_chain_test.py │ │ │ ├── hash_state.cairo │ │ │ ├── hash_state.py │ │ │ ├── hash_state_poseidon.cairo │ │ │ ├── invoke.cairo │ │ │ ├── keccak.cairo │ │ │ ├── keccak_state.cairo │ │ │ ├── keccak_utils │ │ │ │ ├── BUILD │ │ │ │ ├── keccak_utils.cairo │ │ │ │ └── keccak_utils.py │ │ │ ├── log2_ceil.cairo │ │ │ ├── math.cairo │ │ │ ├── math_cmp.cairo │ │ │ ├── math_utils.py │ │ │ ├── memcpy.cairo │ │ │ ├── memset.cairo │ │ │ ├── merkle_multi_update.cairo │ │ │ ├── merkle_update.cairo │ │ │ ├── modulo.cairo │ │ │ ├── patricia.cairo │ │ │ ├── patricia_utils.cairo │ │ │ ├── patricia_utils.py │ │ │ ├── patricia_with_poseidon.cairo │ │ │ ├── patricia_with_sponge.cairo │ │ │ ├── poseidon_hash.py │ │ │ ├── poseidon_state.cairo │ │ │ ├── poseidon_utils.py │ │ │ ├── pow.cairo │ │ │ ├── registers.cairo │ │ │ ├── secp256r1 │ │ │ │ ├── BUILD │ │ │ │ ├── bigint.cairo │ │ │ │ ├── constants.cairo │ │ │ │ ├── ec.cairo │ │ │ │ └── field.cairo │ │ │ ├── segments.cairo │ │ │ ├── serialize.cairo │ │ │ ├── set.cairo │ │ │ ├── sha256_state.cairo │ │ │ ├── signature.cairo │ │ │ ├── simulate_builtin_keccak_with_cairo │ │ │ │ ├── BUILD │ │ │ │ └── simulate_keccak.cairo │ │ │ ├── small_merkle_tree.cairo │ │ │ ├── small_merkle_tree.py │ │ │ ├── sponge_as_hash.cairo │ │ │ ├── squash_dict.cairo │ │ │ ├── structs.py │ │ │ ├── uint256.cairo │ │ │ ├── usort.cairo │ │ │ └── validate_utils.py │ │ ├── lang │ │ │ ├── BUILD │ │ │ ├── MANIFEST.in │ │ │ ├── VERSION │ │ │ ├── __init__.py │ │ │ ├── builtins │ │ │ │ ├── BUILD │ │ │ │ ├── __init__.py │ │ │ │ ├── all_builtins.py │ │ │ │ ├── bitwise │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── bitwise_builtin_runner.py │ │ │ │ │ └── instance_def.py │ │ │ │ ├── builtin_runner_test_utils.py │ │ │ │ ├── ec │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── ec_op_builtin_runner.py │ │ │ │ │ ├── ec_op_builtin_runner_test.py │ │ │ │ │ └── instance_def.py │ │ │ │ ├── hash │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── hash_builtin_runner.py │ │ │ │ │ └── instance_def.py │ │ │ │ ├── instance_def.py │ │ │ │ ├── keccak │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── instance_def.py │ │ │ │ │ └── keccak_builtin_runner.py │ │ │ │ ├── modulo │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── instance_def.py │ │ │ │ │ ├── mod_builtin_runner.py │ │ │ │ │ ├── mod_builtin_runner_test.py │ │ │ │ │ └── modulo_test.cairo │ │ │ │ ├── poseidon │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── instance_def.py │ │ │ │ │ └── poseidon_builtin_runner.py │ │ │ │ ├── range_check │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── instance_def.py │ │ │ │ │ ├── range_check_builtin_runner.py │ │ │ │ │ └── range_check_builtin_runner_test.py │ │ │ │ └── signature │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── instance_def.py │ │ │ │ │ ├── signature_builtin_runner.py │ │ │ │ │ └── signature_builtin_runner_test.py │ │ │ ├── cairo_constants.py │ │ │ ├── cairo_rules.bzl │ │ │ ├── compiler │ │ │ │ ├── BUILD │ │ │ │ ├── __init__.py │ │ │ │ ├── assembler.py │ │ │ │ ├── assembler_test.py │ │ │ │ ├── ast │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── aliased_identifier.py │ │ │ │ │ ├── arguments.py │ │ │ │ │ ├── ast_objects_test_utils.py │ │ │ │ │ ├── bool_expr.py │ │ │ │ │ ├── cairo_types.py │ │ │ │ │ ├── code_elements.py │ │ │ │ │ ├── expr.py │ │ │ │ │ ├── expr_func_call.py │ │ │ │ │ ├── formatting_utils.py │ │ │ │ │ ├── instructions.py │ │ │ │ │ ├── module.py │ │ │ │ │ ├── node.py │ │ │ │ │ ├── notes.py │ │ │ │ │ ├── parentheses_expr_wrapper.py │ │ │ │ │ ├── parentheses_expr_wrapper_test.py │ │ │ │ │ ├── particle.py │ │ │ │ │ ├── particle_test.py │ │ │ │ │ ├── rvalue.py │ │ │ │ │ ├── types.py │ │ │ │ │ └── visitor.py │ │ │ │ ├── ast_objects_test.py │ │ │ │ ├── cairo.ebnf │ │ │ │ ├── cairo_compile.py │ │ │ │ ├── cairo_compile_test.py │ │ │ │ ├── cairo_format.py │ │ │ │ ├── conftest.py │ │ │ │ ├── const_expr_checker.py │ │ │ │ ├── constants.py │ │ │ │ ├── debug_info.py │ │ │ │ ├── debug_info_test.py │ │ │ │ ├── encode.py │ │ │ │ ├── encode_test.py │ │ │ │ ├── error_handling.py │ │ │ │ ├── error_handling_test.py │ │ │ │ ├── expression_evaluator.py │ │ │ │ ├── expression_evaluator_test.py │ │ │ │ ├── expression_simplifier.py │ │ │ │ ├── expression_simplifier_test.py │ │ │ │ ├── expression_transformer.py │ │ │ │ ├── fields.py │ │ │ │ ├── filter_unused_identifiers.py │ │ │ │ ├── filter_unused_identifiers_test.py │ │ │ │ ├── identifier_definition.py │ │ │ │ ├── identifier_definition_test.py │ │ │ │ ├── identifier_manager.py │ │ │ │ ├── identifier_manager_field.py │ │ │ │ ├── identifier_manager_field_test.py │ │ │ │ ├── identifier_manager_test.py │ │ │ │ ├── identifier_utils.py │ │ │ │ ├── identifier_utils_test.py │ │ │ │ ├── import_loader.py │ │ │ │ ├── import_loader_test.py │ │ │ │ ├── injector.py │ │ │ │ ├── injector_test.py │ │ │ │ ├── instruction.py │ │ │ │ ├── instruction_builder.py │ │ │ │ ├── instruction_builder_test.py │ │ │ │ ├── instruction_test.py │ │ │ │ ├── lib │ │ │ │ │ ├── BUILD │ │ │ │ │ └── registers.cairo │ │ │ │ ├── location_utils.py │ │ │ │ ├── module_reader.py │ │ │ │ ├── module_reader_test.py │ │ │ │ ├── offset_reference.py │ │ │ │ ├── offset_reference_test.py │ │ │ │ ├── parser.py │ │ │ │ ├── parser_errors_test.py │ │ │ │ ├── parser_test.py │ │ │ │ ├── parser_test_utils.py │ │ │ │ ├── parser_transformer.py │ │ │ │ ├── preprocessor │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── auxiliary_info_collector.py │ │ │ │ │ ├── bool_expr │ │ │ │ │ │ ├── BUILD │ │ │ │ │ │ ├── __init__.py │ │ │ │ │ │ ├── errors.py │ │ │ │ │ │ ├── lowering.py │ │ │ │ │ │ ├── lowering_test.py │ │ │ │ │ │ └── lowering_test_utils.py │ │ │ │ │ ├── compound_expressions.py │ │ │ │ │ ├── compound_expressions_test.py │ │ │ │ │ ├── conftest.py │ │ │ │ │ ├── default_pass_manager.py │ │ │ │ │ ├── dependency_graph.py │ │ │ │ │ ├── dependency_graph_test.py │ │ │ │ │ ├── directives.py │ │ │ │ │ ├── flow.py │ │ │ │ │ ├── flow_test.py │ │ │ │ │ ├── identifier_aware_visitor.py │ │ │ │ │ ├── identifier_aware_visitor_test.py │ │ │ │ │ ├── identifier_collector.py │ │ │ │ │ ├── identifier_collector_test.py │ │ │ │ │ ├── if_labels.py │ │ │ │ │ ├── if_labels_test.py │ │ │ │ │ ├── local_variables.py │ │ │ │ │ ├── local_variables_test.py │ │ │ │ │ ├── memento.py │ │ │ │ │ ├── memento_test.py │ │ │ │ │ ├── pass_manager.py │ │ │ │ │ ├── preprocess_codes.py │ │ │ │ │ ├── preprocessor.py │ │ │ │ │ ├── preprocessor_error.py │ │ │ │ │ ├── preprocessor_test.py │ │ │ │ │ ├── preprocessor_test_utils.py │ │ │ │ │ ├── preprocessor_utils.py │ │ │ │ │ ├── reg_tracking.py │ │ │ │ │ ├── reg_tracking_test.py │ │ │ │ │ ├── struct_collector.py │ │ │ │ │ └── struct_collector_test.py │ │ │ │ ├── program.py │ │ │ │ ├── proxy_identifier_manager.py │ │ │ │ ├── proxy_identifier_manager_test.py │ │ │ │ ├── references.py │ │ │ │ ├── references_test.py │ │ │ │ ├── resolve_search_result.py │ │ │ │ ├── resolve_search_result_test.py │ │ │ │ ├── scoped_name.py │ │ │ │ ├── scoped_name_test.py │ │ │ │ ├── substitute_identifiers.py │ │ │ │ ├── test_utils.py │ │ │ │ ├── type_casts.py │ │ │ │ ├── type_casts_test.py │ │ │ │ ├── type_system.py │ │ │ │ ├── type_system_visitor.py │ │ │ │ ├── type_system_visitor_test.py │ │ │ │ ├── type_utils.py │ │ │ │ ├── type_utils_test.py │ │ │ │ ├── unique_name_provider.py │ │ │ │ ├── unique_name_provider_test.py │ │ │ │ └── vars.bzl │ │ │ ├── create_cairo_lang_zip.py │ │ │ ├── dynamic_layout_params.py │ │ │ ├── ide │ │ │ │ ├── __init__.py │ │ │ │ ├── vim │ │ │ │ │ ├── ftdetect │ │ │ │ │ │ └── cairo.vim │ │ │ │ │ ├── ftplugin │ │ │ │ │ │ └── cairo.vim │ │ │ │ │ └── syntax │ │ │ │ │ │ └── cairo.vim │ │ │ │ └── vscode-cairo │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── README.md │ │ │ │ │ ├── icon.png │ │ │ │ │ ├── language-configuration.json │ │ │ │ │ ├── package.json │ │ │ │ │ ├── snippets.json │ │ │ │ │ ├── src │ │ │ │ │ └── extension.ts │ │ │ │ │ ├── syntaxes │ │ │ │ │ └── cairo.tmLanguage.json │ │ │ │ │ └── tsconfig.json │ │ │ ├── instances.py │ │ │ ├── migrators │ │ │ │ ├── BUILD │ │ │ │ ├── __init__.py │ │ │ │ ├── migrator.py │ │ │ │ ├── migrator_grammar.ebnf │ │ │ │ └── migrator_test.py │ │ │ ├── package_test │ │ │ │ ├── main.cairo │ │ │ │ └── run_test.sh │ │ │ ├── scripts │ │ │ │ ├── BUILD │ │ │ │ ├── cairo-compile │ │ │ │ ├── cairo-format │ │ │ │ ├── cairo-hash-program │ │ │ │ ├── cairo-migrate │ │ │ │ ├── cairo-reconstruct-traceback │ │ │ │ ├── cairo-run │ │ │ │ └── cairo-sharp │ │ │ ├── setup.py │ │ │ ├── tracer │ │ │ │ ├── BUILD │ │ │ │ ├── favicon.png │ │ │ │ ├── index.html │ │ │ │ ├── profile.py │ │ │ │ ├── profiler.py │ │ │ │ ├── third_party │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── profile.proto │ │ │ │ │ └── profile_pb2.py │ │ │ │ ├── tracer.css │ │ │ │ ├── tracer.js │ │ │ │ ├── tracer.py │ │ │ │ ├── tracer_data.py │ │ │ │ └── tracer_data_test.py │ │ │ ├── version.py │ │ │ └── vm │ │ │ │ ├── BUILD │ │ │ │ ├── __init__.py │ │ │ │ ├── air_public_input.py │ │ │ │ ├── builtin_runner.py │ │ │ │ ├── cairo_pie.py │ │ │ │ ├── cairo_pie_test.py │ │ │ │ ├── cairo_run.py │ │ │ │ ├── cairo_runner.py │ │ │ │ ├── cairo_runner_test.py │ │ │ │ ├── crypto.py │ │ │ │ ├── memory_dict.py │ │ │ │ ├── memory_dict_backend.py │ │ │ │ ├── memory_dict_test.py │ │ │ │ ├── memory_segments.py │ │ │ │ ├── memory_segments_test.py │ │ │ │ ├── output_builtin_runner.py │ │ │ │ ├── output_builtin_runner_test.py │ │ │ │ ├── reconstruct_traceback.py │ │ │ │ ├── reconstruct_traceback_test.py │ │ │ │ ├── relocatable.py │ │ │ │ ├── relocatable_fields.py │ │ │ │ ├── relocatable_fields_test.py │ │ │ │ ├── relocatable_test.py │ │ │ │ ├── security.py │ │ │ │ ├── security_test.py │ │ │ │ ├── test.cairo │ │ │ │ ├── test_utils.py │ │ │ │ ├── trace_entry.py │ │ │ │ ├── trace_entry_test.py │ │ │ │ ├── utils.py │ │ │ │ ├── validated_memory_dict.py │ │ │ │ ├── validated_memory_dict_test.py │ │ │ │ ├── virtual_machine_base.py │ │ │ │ ├── vm.py │ │ │ │ ├── vm_consts.py │ │ │ │ ├── vm_consts_test.py │ │ │ │ ├── vm_core.py │ │ │ │ ├── vm_exceptions.py │ │ │ │ └── vm_test.py │ │ ├── sharp │ │ │ ├── BUILD │ │ │ ├── client_lib.py │ │ │ ├── client_lib_test.py │ │ │ ├── config.json │ │ │ ├── fact_checker.py │ │ │ ├── fact_checker_test.py │ │ │ ├── sharp_client.py │ │ │ └── sharp_client_test.py │ │ ├── stark_verifier │ │ │ ├── __init__.py │ │ │ ├── air │ │ │ │ ├── BUILD │ │ │ │ ├── __init__.py │ │ │ │ ├── config_instances.cairo │ │ │ │ ├── config_interface.cairo │ │ │ │ ├── diluted.cairo │ │ │ │ ├── dynamic_layout_proof.json │ │ │ │ ├── example_expected.json │ │ │ │ ├── example_proof.json │ │ │ │ ├── layout.cairo │ │ │ │ ├── layouts │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── all_cairo │ │ │ │ │ │ ├── BUILD │ │ │ │ │ │ ├── autogenerated.cairo │ │ │ │ │ │ ├── composition.cairo │ │ │ │ │ │ ├── global_values.cairo │ │ │ │ │ │ ├── periodic_columns.cairo │ │ │ │ │ │ ├── public_verify.cairo │ │ │ │ │ │ └── verify.cairo │ │ │ │ │ ├── dex │ │ │ │ │ │ ├── BUILD │ │ │ │ │ │ ├── autogenerated.cairo │ │ │ │ │ │ ├── composition.cairo │ │ │ │ │ │ ├── global_values.cairo │ │ │ │ │ │ ├── periodic_columns.cairo │ │ │ │ │ │ ├── public_verify.cairo │ │ │ │ │ │ └── verify.cairo │ │ │ │ │ ├── dynamic │ │ │ │ │ │ ├── BUILD │ │ │ │ │ │ ├── autogenerated.cairo │ │ │ │ │ │ ├── composition.cairo │ │ │ │ │ │ ├── global_values.cairo │ │ │ │ │ │ ├── periodic_columns.cairo │ │ │ │ │ │ ├── public_verify.cairo │ │ │ │ │ │ └── verify.cairo │ │ │ │ │ ├── layouts_gen.bzl │ │ │ │ │ ├── recursive │ │ │ │ │ │ ├── BUILD │ │ │ │ │ │ ├── autogenerated.cairo │ │ │ │ │ │ ├── composition.cairo │ │ │ │ │ │ ├── global_values.cairo │ │ │ │ │ │ ├── periodic_columns.cairo │ │ │ │ │ │ ├── public_verify.cairo │ │ │ │ │ │ └── verify.cairo │ │ │ │ │ ├── recursive_with_poseidon │ │ │ │ │ │ ├── BUILD │ │ │ │ │ │ ├── autogenerated.cairo │ │ │ │ │ │ ├── composition.cairo │ │ │ │ │ │ ├── global_values.cairo │ │ │ │ │ │ ├── periodic_columns.cairo │ │ │ │ │ │ ├── public_verify.cairo │ │ │ │ │ │ └── verify.cairo │ │ │ │ │ ├── small │ │ │ │ │ │ ├── BUILD │ │ │ │ │ │ ├── autogenerated.cairo │ │ │ │ │ │ ├── composition.cairo │ │ │ │ │ │ ├── global_values.cairo │ │ │ │ │ │ ├── periodic_columns.cairo │ │ │ │ │ │ ├── public_verify.cairo │ │ │ │ │ │ └── verify.cairo │ │ │ │ │ ├── starknet │ │ │ │ │ │ ├── BUILD │ │ │ │ │ │ ├── autogenerated.cairo │ │ │ │ │ │ ├── composition.cairo │ │ │ │ │ │ ├── global_values.cairo │ │ │ │ │ │ ├── periodic_columns.cairo │ │ │ │ │ │ ├── public_verify.cairo │ │ │ │ │ │ └── verify.cairo │ │ │ │ │ └── starknet_with_keccak │ │ │ │ │ │ ├── BUILD │ │ │ │ │ │ ├── autogenerated.cairo │ │ │ │ │ │ ├── composition.cairo │ │ │ │ │ │ ├── global_values.cairo │ │ │ │ │ │ ├── periodic_columns.cairo │ │ │ │ │ │ ├── public_verify.cairo │ │ │ │ │ │ └── verify.cairo │ │ │ │ ├── oods.cairo │ │ │ │ ├── params.cairo │ │ │ │ ├── parser.py │ │ │ │ ├── public_input.cairo │ │ │ │ ├── public_input_test.py │ │ │ │ ├── public_memory.cairo │ │ │ │ ├── stark_test.py │ │ │ │ ├── stark_test_utils.py │ │ │ │ ├── traces.cairo │ │ │ │ └── utils.py │ │ │ └── core │ │ │ │ ├── BUILD │ │ │ │ ├── __init__.py │ │ │ │ ├── air_instances.cairo │ │ │ │ ├── air_interface.cairo │ │ │ │ ├── channel.cairo │ │ │ │ ├── channel_test.cairo │ │ │ │ ├── channel_test.py │ │ │ │ ├── config.cairo │ │ │ │ ├── config_instances.cairo │ │ │ │ ├── domains.cairo │ │ │ │ ├── fri │ │ │ │ ├── BUILD │ │ │ │ ├── __init__.py │ │ │ │ ├── config.cairo │ │ │ │ ├── fri.cairo │ │ │ │ ├── fri_formula.cairo │ │ │ │ ├── fri_formula_test.py │ │ │ │ ├── fri_layer.cairo │ │ │ │ ├── fri_layer_test.py │ │ │ │ ├── fri_test.py │ │ │ │ └── test_utils.py │ │ │ │ ├── merkle_test_data.json │ │ │ │ ├── proof_of_work.cairo │ │ │ │ ├── proof_of_work_test.py │ │ │ │ ├── queries.cairo │ │ │ │ ├── serialize_utils.cairo │ │ │ │ ├── stark.cairo │ │ │ │ ├── supported_proof_params.py │ │ │ │ ├── table_commitment.cairo │ │ │ │ ├── table_commitment_test.py │ │ │ │ ├── utils.cairo │ │ │ │ ├── utils_test.py │ │ │ │ ├── vector_commitment.cairo │ │ │ │ └── vector_commitment_test.py │ │ ├── vars.bzl │ │ └── vars_cairo_compiler.bzl │ ├── crypto │ │ ├── BUILD │ │ ├── __init__.py │ │ └── signature │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── fast_pedersen_hash.py │ │ │ ├── math_utils.py │ │ │ ├── nothing_up_my_sleeve_gen.py │ │ │ ├── pedersen_params.json │ │ │ └── signature.py │ ├── eth │ │ ├── BUILD │ │ ├── eth_test_utils.py │ │ └── web3_wrapper.py │ ├── python │ │ ├── BUILD │ │ ├── __init__.py │ │ ├── async_subprocess.py │ │ ├── expression_string.py │ │ ├── expression_string_test.py │ │ ├── fixed_point.py │ │ ├── json_rpc │ │ │ ├── BUILD │ │ │ ├── client.py │ │ │ └── client_test.py │ │ ├── math_utils.py │ │ ├── math_utils_test.py │ │ ├── merkle_tree.py │ │ ├── object_utils.py │ │ ├── python_dependencies.py │ │ ├── random_test_utils.py │ │ ├── test_utils.py │ │ ├── test_utils_test.py │ │ ├── utils.py │ │ ├── utils_stub_module.py │ │ ├── utils_stub_module.pyi │ │ └── utils_test.py │ ├── solidity │ │ ├── BUILD │ │ ├── components │ │ │ ├── BUILD │ │ │ ├── FactRegistry.sol │ │ │ ├── GenericGovernance.sol │ │ │ ├── Governance.sol │ │ │ ├── GovernanceStorage.sol │ │ │ ├── GovernedFinalizable.sol │ │ │ ├── OnchainDataFactTreeEncoder.sol │ │ │ └── Operator.sol │ │ ├── interfaces │ │ │ ├── BUILD │ │ │ ├── BlockDirectCall.sol │ │ │ ├── ContractInitializer.sol │ │ │ ├── ExternalInitializer.sol │ │ │ ├── IFactRegistry.sol │ │ │ ├── IQueryableFactRegistry.sol │ │ │ ├── Identity.sol │ │ │ ├── MGovernance.sol │ │ │ ├── MOperator.sol │ │ │ └── ProxySupport.sol │ │ ├── libraries │ │ │ ├── Addresses.sol │ │ │ ├── BUILD │ │ │ ├── NamedStorage.sol │ │ │ └── NamedStorage8.sol │ │ ├── third_party │ │ │ └── BUILD │ │ ├── tokens │ │ │ ├── BUILD │ │ │ ├── ERC1155 │ │ │ │ ├── BUILD │ │ │ │ ├── ERC1155.sol │ │ │ │ ├── IERC1155.sol │ │ │ │ └── IERC1155Receiver.sol │ │ │ ├── ERC165.sol │ │ │ ├── ERC20 │ │ │ │ └── BUILD │ │ │ ├── ERC721 │ │ │ │ ├── BUILD │ │ │ │ ├── ERC721.sol │ │ │ │ ├── IERC721.sol │ │ │ │ └── IERC721Receiver.sol │ │ │ └── IERC165.sol │ │ ├── upgrade │ │ │ └── BUILD │ │ └── utils.py │ ├── starknet │ │ ├── BUILD │ │ ├── apps │ │ │ └── amm_sample │ │ │ │ └── amm_sample.cairo │ │ ├── builtins │ │ │ └── segment_arena │ │ │ │ ├── BUILD │ │ │ │ ├── segment_arena.cairo │ │ │ │ ├── segment_arena_builtin_runner.py │ │ │ │ ├── segment_arena_test.cairo │ │ │ │ └── segment_arena_test.py │ │ ├── business_logic │ │ │ ├── BUILD │ │ │ ├── execution │ │ │ │ ├── BUILD │ │ │ │ ├── deprecated_objects.py │ │ │ │ ├── execute_entry_point.py │ │ │ │ ├── execute_entry_point_base.py │ │ │ │ ├── gas_usage.py │ │ │ │ ├── objects.py │ │ │ │ └── os_usage.py │ │ │ ├── fact_state │ │ │ │ ├── BUILD │ │ │ │ ├── contract_class_objects.py │ │ │ │ ├── contract_state_objects.py │ │ │ │ ├── patricia_state.py │ │ │ │ ├── state.py │ │ │ │ └── utils.py │ │ │ ├── state │ │ │ │ ├── BUILD │ │ │ │ ├── state.py │ │ │ │ ├── state_api.py │ │ │ │ ├── state_api_objects.py │ │ │ │ └── test_utils.py │ │ │ ├── transaction │ │ │ │ ├── BUILD │ │ │ │ ├── deprecated_objects.py │ │ │ │ ├── fee.py │ │ │ │ ├── internal_account_transaction.py │ │ │ │ ├── internal_transaction_schema.py │ │ │ │ ├── objects.py │ │ │ │ └── state_objects.py │ │ │ └── utils.py │ │ ├── cli │ │ │ ├── BUILD │ │ │ ├── class_hash.py │ │ │ ├── compiled_class_hash.py │ │ │ ├── reconstruct_starknet_traceback.py │ │ │ ├── reconstruct_starknet_traceback_test.py │ │ │ ├── starknet_cli.py │ │ │ └── starknet_cli_utils.py │ │ ├── common │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── constants.cairo │ │ │ ├── eth_utils.cairo │ │ │ ├── eth_utils_test.py │ │ │ ├── messages.cairo │ │ │ ├── new_syscalls.cairo │ │ │ ├── storage.cairo │ │ │ ├── storage_test.py │ │ │ └── syscalls.cairo │ │ ├── compiler │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── compile.py │ │ │ ├── conftest.py │ │ │ ├── contract_interface.py │ │ │ ├── contract_interface_test.py │ │ │ ├── data_encoder.py │ │ │ ├── data_encoder_test.py │ │ │ ├── event.py │ │ │ ├── event_test.py │ │ │ ├── external_wrapper.py │ │ │ ├── external_wrapper_test.py │ │ │ ├── starknet_pass_manager.py │ │ │ ├── starknet_preprocessor.py │ │ │ ├── starknet_preprocessor_test.py │ │ │ ├── storage_var.py │ │ │ ├── storage_var_test.py │ │ │ ├── test_utils.py │ │ │ ├── v1 │ │ │ │ ├── BUILD │ │ │ │ ├── BUILD.sierra-compiler-major-1 │ │ │ │ ├── compile.py │ │ │ │ ├── compiler_exe_paths.py │ │ │ │ ├── experimental_libfuncs.json │ │ │ │ └── mainnet_libfuncs.json │ │ │ ├── validation_utils.py │ │ │ └── validation_utils_test.py │ │ ├── core │ │ │ ├── aggregator │ │ │ │ ├── BUILD │ │ │ │ ├── aggregator_program.py │ │ │ │ ├── aggregator_test.py │ │ │ │ ├── combine_blocks.cairo │ │ │ │ ├── main.cairo │ │ │ │ ├── output_parser.py │ │ │ │ ├── program_hash.json │ │ │ │ ├── program_hash_test.py │ │ │ │ └── utils.py │ │ │ ├── os │ │ │ │ ├── BUILD │ │ │ │ ├── __init__.py │ │ │ │ ├── bl_syscall_handler.py │ │ │ │ ├── block_context.cairo │ │ │ │ ├── block_hash │ │ │ │ │ ├── BUILD │ │ │ │ │ └── block_hash.py │ │ │ │ ├── builtins.cairo │ │ │ │ ├── constants.cairo │ │ │ │ ├── contract_address │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── contract_address.cairo │ │ │ │ │ ├── contract_address.py │ │ │ │ │ └── contract_address_cairo_test.py │ │ │ │ ├── contract_class │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── class_hash.py │ │ │ │ │ ├── class_hash_utils.py │ │ │ │ │ ├── compiled_class.cairo │ │ │ │ │ ├── compiled_class_hash.py │ │ │ │ │ ├── compiled_class_hash_objects.py │ │ │ │ │ ├── compiled_class_hash_test.py │ │ │ │ │ ├── compiled_class_hash_utils.py │ │ │ │ │ ├── contract_class.cairo │ │ │ │ │ ├── deprecated_class_hash.py │ │ │ │ │ ├── deprecated_compiled_class.cairo │ │ │ │ │ └── utils.py │ │ │ │ ├── data_availability │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── bls_field.cairo │ │ │ │ │ ├── bls_field_test.py │ │ │ │ │ ├── bls_utils.py │ │ │ │ │ ├── commitment.cairo │ │ │ │ │ ├── compression.cairo │ │ │ │ │ └── compression.py │ │ │ │ ├── deprecated_bl_syscall_handler.py │ │ │ │ ├── deprecated_os_syscall_handler.py │ │ │ │ ├── deprecated_syscall_handler.py │ │ │ │ ├── execution │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── account_backward_compatibility.cairo │ │ │ │ │ ├── account_backward_compatibility.py │ │ │ │ │ ├── deprecated_execute_entry_point.cairo │ │ │ │ │ ├── deprecated_execute_syscalls.cairo │ │ │ │ │ ├── execute_entry_point.cairo │ │ │ │ │ ├── execute_syscalls.cairo │ │ │ │ │ ├── execute_transaction_utils.cairo │ │ │ │ │ ├── execute_transactions.cairo │ │ │ │ │ └── revert.cairo │ │ │ │ ├── execution_helper.py │ │ │ │ ├── kzg_manager.py │ │ │ │ ├── os.cairo │ │ │ │ ├── os_config │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── os_config.cairo │ │ │ │ │ ├── os_config_hash.json │ │ │ │ │ ├── os_config_hash.py │ │ │ │ │ ├── os_config_hash_test.py │ │ │ │ │ ├── private_os_config_hash.json │ │ │ │ │ └── test_utils.py │ │ │ │ ├── os_hints.py │ │ │ │ ├── os_input.py │ │ │ │ ├── os_logger.py │ │ │ │ ├── os_program.py │ │ │ │ ├── os_syscall_handler.py │ │ │ │ ├── os_utils.py │ │ │ │ ├── output.cairo │ │ │ │ ├── program_hash.json │ │ │ │ ├── program_hash_test.py │ │ │ │ ├── segment_utils.py │ │ │ │ ├── state │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── aliases.cairo │ │ │ │ │ ├── commitment.cairo │ │ │ │ │ ├── output.cairo │ │ │ │ │ ├── squash.cairo │ │ │ │ │ └── state.cairo │ │ │ │ ├── syscall_handler.py │ │ │ │ ├── syscall_utils.py │ │ │ │ └── transaction_hash │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── deprecated_transaction_hash.py │ │ │ │ │ ├── deprecated_transaction_hash_test.py │ │ │ │ │ ├── transaction_hash.cairo │ │ │ │ │ ├── transaction_hash.py │ │ │ │ │ ├── transaction_hash_test.py │ │ │ │ │ └── transaction_hash_test_utils.py │ │ │ └── test_contract │ │ │ │ ├── BUILD │ │ │ │ ├── delegate_proxy.cairo │ │ │ │ ├── dummy_account.cairo │ │ │ │ └── test_utils.py │ │ ├── definitions │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── blockifier_types.py │ │ │ ├── chain_ids.py │ │ │ ├── constants.py │ │ │ ├── data_availability_mode.py │ │ │ ├── error_codes.py │ │ │ ├── execution_mode.py │ │ │ ├── fields.py │ │ │ ├── general_config.py │ │ │ ├── general_config.yml │ │ │ ├── l1_da_mode.py │ │ │ ├── overridable_versioned_constants.py │ │ │ ├── transaction_type.py │ │ │ └── versioned_constants.json │ │ ├── public │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── abi.py │ │ │ ├── abi_structs.py │ │ │ ├── abi_structs_test.py │ │ │ └── abi_test.py │ │ ├── scripts │ │ │ ├── BUILD │ │ │ ├── starknet │ │ │ ├── starknet-class-hash │ │ │ ├── starknet-compile-deprecated │ │ │ └── starknet-compiled-class-hash │ │ ├── security │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── hints_whitelist.py │ │ │ ├── latest_whitelist_test.py │ │ │ ├── secure_hints.py │ │ │ ├── secure_hints_test.py │ │ │ ├── simple_references.py │ │ │ ├── simple_references_test.py │ │ │ ├── starknet_common.cairo │ │ │ └── whitelists │ │ │ │ ├── 0.10.3.json │ │ │ │ ├── 0.6.0.json │ │ │ │ ├── 0.8.2.json │ │ │ │ ├── 384_bit_prime_field.json │ │ │ │ ├── BUILD │ │ │ │ ├── cairo_blake2s.json │ │ │ │ ├── cairo_keccak.json │ │ │ │ ├── cairo_secp.json │ │ │ │ ├── cairo_sha256.json │ │ │ │ ├── cairo_sha256_arbitrary_input_length.json │ │ │ │ ├── ec_bigint.json │ │ │ │ ├── ec_recover.json │ │ │ │ ├── encode_packed.json │ │ │ │ ├── latest.json │ │ │ │ ├── uint256_improvements.json │ │ │ │ └── vrf.json │ │ ├── services │ │ │ ├── api │ │ │ │ ├── BUILD │ │ │ │ ├── __init__.py │ │ │ │ ├── contract_class │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── contract_class.py │ │ │ │ │ └── contract_class_utils.py │ │ │ │ ├── feeder_gateway │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── account_transaction_specific_info.py │ │ │ │ │ ├── block_signature.py │ │ │ │ │ ├── deprecated_transaction_specific_info.py │ │ │ │ │ ├── feeder_gateway_client.py │ │ │ │ │ ├── request_objects.py │ │ │ │ │ ├── response_objects.py │ │ │ │ │ ├── transaction_specific_info.py │ │ │ │ │ └── transaction_specific_info_schema.py │ │ │ │ ├── gateway │ │ │ │ │ ├── BUILD │ │ │ │ │ ├── account_transaction.py │ │ │ │ │ ├── deprecated_transaction.py │ │ │ │ │ ├── gateway_client.py │ │ │ │ │ ├── transaction.py │ │ │ │ │ ├── transaction_schema.py │ │ │ │ │ └── transaction_utils.py │ │ │ │ └── messages.py │ │ │ └── utils │ │ │ │ └── BUILD │ │ ├── solidity │ │ │ ├── BUILD │ │ │ ├── IStarknetMessaging.sol │ │ │ ├── IStarknetMessagingEvents.sol │ │ │ ├── Output.sol │ │ │ ├── Starknet.sol │ │ │ ├── StarknetGovernance.sol │ │ │ ├── StarknetMessaging.sol │ │ │ ├── StarknetOperator.sol │ │ │ ├── StarknetState.sol │ │ │ └── __init__.py │ │ ├── starknet_rules.bzl │ │ ├── starknet_rules_v0.bzl │ │ ├── storage │ │ │ ├── BUILD │ │ │ └── starknet_storage.py │ │ ├── testing │ │ │ ├── BUILD │ │ │ ├── MockStarknetMessaging.sol │ │ │ ├── contracts.py │ │ │ └── test_utils.py │ │ ├── third_party │ │ │ ├── __init__.py │ │ │ └── open_zeppelin │ │ │ │ ├── Account.cairo │ │ │ │ ├── BUILD │ │ │ │ ├── LICENSE │ │ │ │ ├── __init__.py │ │ │ │ ├── starknet_contracts.py │ │ │ │ └── utils │ │ │ │ ├── BUILD │ │ │ │ └── constants.cairo │ │ ├── utils │ │ │ ├── BUILD │ │ │ └── api_utils.py │ │ └── wallets │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── account.py │ │ │ ├── open_zeppelin.py │ │ │ ├── signer.py │ │ │ └── starknet_context.py │ ├── starkware_utils │ │ ├── BUILD │ │ ├── commitment_tree │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── binary_fact_tree.py │ │ │ ├── binary_fact_tree_da_utils.py │ │ │ ├── binary_fact_tree_node.py │ │ │ ├── calculation.py │ │ │ ├── inner_node_fact.py │ │ │ ├── leaf_fact.py │ │ │ ├── leaf_fact_utils.py │ │ │ ├── merkle_tree │ │ │ │ ├── BUILD │ │ │ │ └── traverse_tree.py │ │ │ ├── patricia_tree │ │ │ │ ├── BUILD │ │ │ │ ├── __init__.py │ │ │ │ ├── fast_patricia_update.py │ │ │ │ ├── nodes.py │ │ │ │ ├── nodes_test.py │ │ │ │ ├── patricia_tree.py │ │ │ │ ├── patricia_tree_test.py │ │ │ │ ├── virtual_calculation_node.py │ │ │ │ ├── virtual_calculation_node_test.py │ │ │ │ ├── virtual_patricia_node.py │ │ │ │ └── virtual_patricia_node_test.py │ │ │ └── update_tree.py │ │ ├── config_base.py │ │ ├── custom_raising_dict.py │ │ ├── error_handling.py │ │ ├── executor.py │ │ ├── field_validators.py │ │ ├── marshmallow_dataclass_fields.py │ │ ├── marshmallow_fields_metadata.py │ │ ├── one_of_schema_tracker.py │ │ ├── serializable.py │ │ ├── serializable_dataclass.py │ │ ├── subsequence.py │ │ ├── time │ │ │ ├── BUILD │ │ │ ├── __init__.py │ │ │ ├── fastforward.py │ │ │ ├── synchronous_executor.py │ │ │ ├── time.py │ │ │ └── time_test.py │ │ ├── validated_dataclass.py │ │ ├── validated_fields.py │ │ └── vars.bzl │ └── storage │ │ ├── BUILD │ │ ├── __init__.py │ │ ├── dict_storage.py │ │ ├── gated_storage.py │ │ ├── gated_storage_test.py │ │ ├── imm_storage.py │ │ ├── metrics.py │ │ ├── names.py │ │ ├── storage.py │ │ ├── storage_test.py │ │ ├── storage_utils.py │ │ └── test_utils.py └── third_party │ └── pip │ └── BUILD ├── vars.bzl └── yarn_ganache.lock /.bazelrc: -------------------------------------------------------------------------------- 1 | # Put all output in build directory. 2 | build --symlink_prefix=build/bazel 3 | 4 | # Don't inherit the user environment as that trashes the cache. 5 | build --incompatible_strict_action_env 6 | build --profile=bazel_build.profile 7 | 8 | # Prevent Bazel from adding empty __init__.py files. Those files prevent the packages from becoming 9 | # a namespace package and can cause an import collision. 10 | build --incompatible_default_to_explicit_init_py 11 | 12 | build --test_output=errors 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.cairo linguist-language=python linguist-detectable=false 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | __pycache__/ 3 | cairo-lang-*.zip 4 | /.vscode/ 5 | -------------------------------------------------------------------------------- /BUILD: -------------------------------------------------------------------------------- 1 | load("vars.bzl", "ADDITIONAL_IMPORTS") 2 | 3 | exports_files( 4 | [ 5 | ".clang-format", 6 | "package.json", 7 | "yarn_ganache.lock", 8 | ] + glob( 9 | [ 10 | "*.py", 11 | ], 12 | ), 13 | ) 14 | 15 | # The 'starkware' library adds 'src' to PYTHONPATH. 16 | # The library on its own does not add any dependencies. 17 | # This library is needed to allow us to use "import starkware.foo" instead of 18 | # "import src.starkware.foo". 19 | py_library( 20 | name = "starkware", 21 | srcs = [], 22 | imports = [ 23 | "src", 24 | ] + ADDITIONAL_IMPORTS, 25 | visibility = ["//visibility:public"], 26 | ) 27 | -------------------------------------------------------------------------------- /bazel_utils/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "py_exe") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files(["pytest_wrapper.py"]) 6 | 7 | py_binary( 8 | name = "gen_python_exe", 9 | srcs = ["gen_python_exe.py"], 10 | main = "gen_python_exe.py", 11 | ) 12 | 13 | py_binary( 14 | name = "solc_wrapper", 15 | srcs = ["solc_wrapper.py"], 16 | ) 17 | 18 | sh_binary( 19 | name = "solc-0.6.12", 20 | srcs = ["@solc-0.6.12//file"], 21 | ) 22 | 23 | sh_binary( 24 | name = "solc-0.8.24", 25 | srcs = ["@solc-0.8.24//file"], 26 | ) 27 | 28 | py_library( 29 | name = "default_extract_artifacts_lib", 30 | srcs = [ 31 | "__init__.py", 32 | "extract_artifacts.py", 33 | ], 34 | visibility = ["//visibility:public"], 35 | deps = [], 36 | ) 37 | 38 | py_exe( 39 | name = "default_extract_artifacts_exe", 40 | module = "bazel_utils.extract_artifacts", 41 | deps = ["default_extract_artifacts_lib"], 42 | ) 43 | -------------------------------------------------------------------------------- /bazel_utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/bazel_utils/__init__.py -------------------------------------------------------------------------------- /bazel_utils/get_from_cairo_lang.bzl: -------------------------------------------------------------------------------- 1 | def get_from_cairo_lang(label): 2 | return label 3 | -------------------------------------------------------------------------------- /bazel_utils/patches/BUILD: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/bazel_utils/patches/BUILD -------------------------------------------------------------------------------- /bazel_utils/patches/rules_python.patch: -------------------------------------------------------------------------------- 1 | diff --git a/python/pip_install/repositories.bzl b/python/pip_install/repositories.bzl 2 | index b322a70..14f2e30 100644 3 | --- a/python/pip_install/repositories.bzl 4 | +++ b/python/pip_install/repositories.bzl 5 | @@ -116,6 +116,7 @@ py_library( 6 | "**/*.pyc.*", # During pyc creation, temp files named *.pyc.NNN are created 7 | "**/* *", 8 | "**/*.dist-info/RECORD", 9 | + "**/__pycache__/**", 10 | "BUILD", 11 | "WORKSPACE", 12 | ]), 13 | -------------------------------------------------------------------------------- /bazel_utils/pytest_wrapper.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import pytest 4 | 5 | if __name__ == "__main__": 6 | sys.exit(pytest.main(sys.argv[1:])) 7 | -------------------------------------------------------------------------------- /bazel_utils/python/BUILD: -------------------------------------------------------------------------------- 1 | load("@rules_python//python:defs.bzl", "py_runtime", "py_runtime_pair") 2 | load( 3 | ":defs.bzl", 4 | "python_version_info", 5 | ) 6 | 7 | python_version_info( 8 | name = "python_version", 9 | build_setting_default = "", 10 | visibility = ["//visibility:public"], 11 | ) 12 | 13 | config_setting( 14 | name = "pypy", 15 | flag_values = {":python_version": "pypy"}, 16 | ) 17 | 18 | config_setting( 19 | name = "cpython", 20 | flag_values = {":python_version": "cpython"}, 21 | ) 22 | 23 | py_runtime( 24 | name = "python_stub_runtime", 25 | files = [ 26 | "@bazel_tools//tools/bash/runfiles", 27 | "@python3//:files", 28 | ], 29 | interpreter = "//bazel_utils/python:stub.sh", 30 | python_version = "PY3", 31 | visibility = ["//visibility:public"], 32 | ) 33 | 34 | py_runtime_pair( 35 | name = "py_stub_runtime_pair", 36 | py2_runtime = None, 37 | py3_runtime = ":python_stub_runtime", 38 | ) 39 | 40 | toolchain( 41 | name = "py_stub_toolchain", 42 | toolchain = ":py_stub_runtime_pair", 43 | toolchain_type = "@bazel_tools//tools/python:toolchain_type", 44 | ) 45 | -------------------------------------------------------------------------------- /docker_common_deps.sh: -------------------------------------------------------------------------------- 1 | curl -L -o /tmp/bazel_install.sh https://github.com/bazelbuild/bazel/releases/download/5.4.0/bazel-5.4.0-installer-linux-x86_64.sh 2 | chmod +x /tmp/bazel_install.sh 3 | /tmp/bazel_install.sh 4 | 5 | groupadd -g 1234 starkware && useradd -m starkware -u 1234 -g 1234 6 | -------------------------------------------------------------------------------- /load_cairo_lang.bzl: -------------------------------------------------------------------------------- 1 | def load_cairo_lang(): 2 | pass 3 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "workspace", 3 | "version": "1.0.0", 4 | "private": true, 5 | "description": "", 6 | "dependencies": { 7 | "ganache": "7.9.0" 8 | }, 9 | "devDependencies": {}, 10 | "author": "", 11 | "license": "ISC" 12 | } 13 | -------------------------------------------------------------------------------- /pypy3.9_archive_build_file.bzl: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | EXCLUDE_PATTERN = [ 4 | "**/__pycache__/**", 5 | "**/*.pyc", 6 | "**/*.pyc.*", # During pyc creation, temp files named *.pyc.NNN are created. 7 | "**/*.dist-info/RECORD", 8 | ] 9 | -------------------------------------------------------------------------------- /scripts/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "pypy-requirements.txt", 5 | "requirements.txt", 6 | ]) 7 | -------------------------------------------------------------------------------- /scripts/pypy-requirements-deps.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/scripts/pypy-requirements-deps.json -------------------------------------------------------------------------------- /scripts/pypy-requirements-gen.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/scripts/pypy-requirements-gen.txt -------------------------------------------------------------------------------- /scripts/pypy-requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/scripts/pypy-requirements.txt -------------------------------------------------------------------------------- /scripts/requirements-gen.txt: -------------------------------------------------------------------------------- 1 | aiohttp 2 | cachetools 3 | ecdsa 4 | eth-hash[pycryptodome] 5 | execnet 6 | fastecdsa 7 | frozendict 8 | gprof2dot 9 | lark 10 | marshmallow-dataclass==8.6.1 11 | marshmallow-enum 12 | marshmallow-oneofschema 13 | marshmallow>=3.13.0,<4.0 14 | mpmath 15 | numpy 16 | pipdeptree 17 | prometheus-client 18 | pytest 19 | pytest-asyncio 20 | pytest-profiling 21 | pytest-xdist 22 | PyYAML 23 | sympy 24 | typeguard<3.0.0 25 | web3 26 | -------------------------------------------------------------------------------- /src/services/config/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | py_library( 6 | name = "base_general_config_lib", 7 | srcs = [ 8 | "general_config.py", 9 | ], 10 | visibility = ["//visibility:public"], 11 | deps = [ 12 | "//src/starkware/starkware_utils:starkware_config_utils_lib", 13 | requirement("marshmallow_dataclass"), 14 | ], 15 | ) 16 | -------------------------------------------------------------------------------- /src/services/config/general_config.py: -------------------------------------------------------------------------------- 1 | import marshmallow_dataclass 2 | 3 | from starkware.starkware_utils.config_base import Config 4 | 5 | 6 | @marshmallow_dataclass.dataclass 7 | class GeneralConfigBase(Config): 8 | pass 9 | -------------------------------------------------------------------------------- /src/services/everest/api/feeder_gateway/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | py_library( 6 | name = "everest_feeder_gateway_client_lib", 7 | srcs = [ 8 | "feeder_gateway_client.py", 9 | ], 10 | visibility = ["//visibility:public"], 11 | deps = [ 12 | "//src/services/external_api:services_external_api_lib", 13 | ], 14 | ) 15 | 16 | py_library( 17 | name = "everest_external_api_feeder_gateway_lib", 18 | srcs = [ 19 | "docs.py", 20 | ], 21 | visibility = ["//visibility:public"], 22 | deps = [ 23 | ], 24 | ) 25 | 26 | py_library( 27 | name = "everest_feeder_gateway_response_objects_lib", 28 | srcs = [ 29 | "response_objects.py", 30 | ], 31 | visibility = ["//visibility:public"], 32 | deps = [ 33 | "//src/starkware/starkware_utils:starkware_dataclasses_field_utils_lib", 34 | requirement("marshmallow"), 35 | ], 36 | ) 37 | -------------------------------------------------------------------------------- /src/services/everest/api/feeder_gateway/docs.py: -------------------------------------------------------------------------------- 1 | def get_prev_batch_id_docstring(uri_prefix: str, port: int, batch_term: str) -> str: 2 | return f""" 3 | Get the previous {batch_term} ID for the input batch_id. 4 | 5 | :param batch_id: {batch_term.title()} ID to query. 6 | :type batch_id: int 7 | :return: The previous {batch_term} ID. 8 | :rtype: int 9 | 10 | :example: 11 | 12 | .. http:example:: curl wget httpie python-requests 13 | 14 | GET {uri_prefix}/get_prev_batch_id HTTP/1.1 15 | Host: localhost:{port} 16 | Accept: application/json 17 | 18 | :query batch_id: 5678 19 | 20 | 21 | HTTP/1.1 200 OK 22 | Content-Type: application/json 23 | 24 | 5676 25 | """ 26 | -------------------------------------------------------------------------------- /src/services/everest/api/feeder_gateway/feeder_gateway_client.py: -------------------------------------------------------------------------------- 1 | import json 2 | from typing import ClassVar 3 | 4 | from services.external_api.client import BaseRestClient 5 | 6 | 7 | class EverestFeederGatewayClient(BaseRestClient): 8 | """ 9 | Base class to FeederGatewayClient classes. 10 | """ 11 | 12 | prefix: ClassVar[str] = "/feeder_gateway" 13 | 14 | async def get_last_batch_id(self) -> int: 15 | raw_response = await self._send_request(send_method="GET", uri="/get_last_batch_id") 16 | return json.loads(raw_response) 17 | 18 | async def get_l1_blockchain_id(self) -> int: 19 | raw_response = await self._send_request(send_method="GET", uri="/get_l1_blockchain_id") 20 | return json.loads(raw_response) 21 | 22 | async def get_previous_batch_id(self, batch_id: int) -> int: 23 | raw_response = await self._send_request( 24 | send_method="GET", uri=f"/get_prev_batch_id?batch_id={batch_id}" 25 | ) 26 | return json.loads(raw_response) 27 | -------------------------------------------------------------------------------- /src/services/everest/api/feeder_gateway/response_objects.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Dict 2 | 3 | import marshmallow 4 | 5 | from starkware.starkware_utils.validated_dataclass import ValidatedMarshmallowDataclass 6 | 7 | 8 | class BaseResponseObject: 9 | """ 10 | Contains common functionality to response objects from the FeederGateway. 11 | """ 12 | 13 | @marshmallow.post_dump 14 | def remove_none_values(self, data: Dict[Any, Any], many: bool = False) -> Dict[Any, Any]: 15 | return {key: value for key, value in data.items() if value is not None} 16 | 17 | 18 | class ValidatedResponseObject(BaseResponseObject, ValidatedMarshmallowDataclass): 19 | """ 20 | Validated version of BaseResponseObject. 21 | This class must not contain a marshmallow schema and should not be directly (de)serialized. 22 | """ 23 | -------------------------------------------------------------------------------- /src/services/everest/api/gateway/gateway_client.py: -------------------------------------------------------------------------------- 1 | import json 2 | from typing import ClassVar, Dict 3 | 4 | from services.everest.api.gateway.transaction import EverestAddTransactionRequest 5 | from services.external_api.client import BaseRestClient 6 | 7 | 8 | class EverestGatewayClient(BaseRestClient): 9 | """ 10 | Base class to GatewayClient classes. 11 | """ 12 | 13 | prefix: ClassVar[str] = "/gateway" 14 | 15 | async def add_transaction_request( 16 | self, add_tx_request: EverestAddTransactionRequest 17 | ) -> Dict[str, str]: 18 | raw_response = await self._send_request( 19 | send_method="POST", uri="/add_transaction", data=add_tx_request.dumps() 20 | ) 21 | return json.loads(raw_response) 22 | 23 | async def get_first_unused_tx_id(self) -> int: 24 | response = await self._send_request(send_method="GET", uri="/get_first_unused_tx_id") 25 | return json.loads(response) 26 | -------------------------------------------------------------------------------- /src/services/everest/api/gateway/transaction_type.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class TransactionTypeBase(Enum): 5 | """ 6 | Base class of all transaction type enums. 7 | Do not add enum members to this class, only functionality. 8 | See: https://docs.python.org/3/library/enum.html#restricted-enum-subclassing. 9 | """ 10 | -------------------------------------------------------------------------------- /src/services/everest/business_logic/state_api.py: -------------------------------------------------------------------------------- 1 | from abc import ABC 2 | 3 | 4 | class StateProxy(ABC): 5 | """ 6 | A proxy to the state, exposing the sufficient functionallity to run a transaction. 7 | """ 8 | -------------------------------------------------------------------------------- /src/services/everest/definitions/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | py_library( 6 | name = "everest_definitions_lib", 7 | srcs = [ 8 | "constants.py", 9 | "fields.py", 10 | ], 11 | visibility = ["//visibility:public"], 12 | deps = [ 13 | "//src/starkware/crypto:starkware_crypto_lib", 14 | "//src/starkware/eth:web3_wrapper_lib", 15 | "//src/starkware/python:starkware_python_utils_lib", 16 | "//src/starkware/starkware_utils:starkware_dataclasses_field_utils_lib", 17 | "//src/starkware/starkware_utils:starkware_dataclasses_utils_lib", 18 | "//src/starkware/starkware_utils:starkware_error_handling_lib", 19 | requirement("marshmallow"), 20 | requirement("web3"), 21 | ], 22 | ) 23 | 24 | py_library( 25 | name = "everest_general_config_lib", 26 | srcs = [ 27 | "general_config.py", 28 | ], 29 | visibility = ["//visibility:public"], 30 | deps = [ 31 | "//src/services/config:base_general_config_lib", 32 | requirement("marshmallow_dataclass"), 33 | ], 34 | ) 35 | -------------------------------------------------------------------------------- /src/services/everest/definitions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/services/everest/definitions/__init__.py -------------------------------------------------------------------------------- /src/services/everest/definitions/constants.py: -------------------------------------------------------------------------------- 1 | ETH_ADDRESS_BITS = 160 2 | ETH_ADDRESS_LOWER_BOUND = 0 3 | ETH_ADDRESS_UPPER_BOUND = 1 << ETH_ADDRESS_BITS 4 | -------------------------------------------------------------------------------- /src/services/everest/definitions/general_config.py: -------------------------------------------------------------------------------- 1 | import marshmallow_dataclass 2 | 3 | from services.config.general_config import GeneralConfigBase 4 | 5 | 6 | @marshmallow_dataclass.dataclass 7 | class EverestGeneralConfig(GeneralConfigBase): 8 | pass 9 | -------------------------------------------------------------------------------- /src/services/external_api/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | load( 3 | "//src/services/external_api:vars.bzl", 4 | "SERVICES_EXTERNAL_API_LIB_ADDITIONAL_FILES", 5 | "SERVICES_EXTERNAL_API_LIB_ADDITIONAL_LIBS", 6 | ) 7 | 8 | package(default_visibility = ["//visibility:public"]) 9 | 10 | py_library( 11 | name = "services_external_api_utils_lib", 12 | srcs = [ 13 | "utils.py", 14 | ], 15 | visibility = ["//visibility:public"], 16 | ) 17 | 18 | py_library( 19 | name = "services_external_api_lib", 20 | srcs = [ 21 | "client.py", 22 | "has_uri_prefix.py", 23 | ] + SERVICES_EXTERNAL_API_LIB_ADDITIONAL_FILES, 24 | visibility = ["//visibility:public"], 25 | deps = [ 26 | ":services_external_api_utils_lib", 27 | "//src/starkware/python:starkware_python_utils_lib", 28 | "//src/starkware/starkware_utils:starkware_dataclasses_field_utils_lib", 29 | requirement("aiohttp"), 30 | ] + SERVICES_EXTERNAL_API_LIB_ADDITIONAL_LIBS, 31 | ) 32 | 33 | py_library( 34 | name = "services_eth_gas_constants_lib", 35 | srcs = [ 36 | "eth_gas_constants.py", 37 | ], 38 | visibility = ["//visibility:public"], 39 | deps = [], 40 | ) 41 | -------------------------------------------------------------------------------- /src/services/external_api/eth_gas_constants.py: -------------------------------------------------------------------------------- 1 | # Ethereum gas usage constants; for more details, see 2 | # page 27 in https://ethereum.github.io/yellowpaper/paper.pdf. 3 | GAS_PER_MEMORY_BYTE = 16 4 | WORD_WIDTH = 32 5 | GAS_PER_MEMORY_WORD = GAS_PER_MEMORY_BYTE * WORD_WIDTH 6 | SHARP_ADDITIONAL_GAS_PER_MEMORY_WORD = 100 # This value is not accurate. 7 | SHARP_GAS_PER_MEMORY_WORD = GAS_PER_MEMORY_WORD + SHARP_ADDITIONAL_GAS_PER_MEMORY_WORD 8 | GAS_PER_ZERO_TO_NONZERO_STORAGE_SET = 20000 9 | GAS_PER_COLD_STORAGE_ACCESS = 2100 10 | GAS_PER_NONZERO_TO_INT_STORAGE_SET = 2900 11 | GAS_PER_COUNTER_DECREASE = GAS_PER_COLD_STORAGE_ACCESS + GAS_PER_NONZERO_TO_INT_STORAGE_SET 12 | GAS_PER_LOG = 375 13 | GAS_PER_LOG_TOPIC = 375 14 | GAS_PER_LOG_DATA_BYTE = 8 15 | GAS_PER_LOG_DATA_WORD = GAS_PER_LOG_DATA_BYTE * WORD_WIDTH 16 | -------------------------------------------------------------------------------- /src/services/external_api/has_uri_prefix.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | from typing import ClassVar, Optional, cast 3 | 4 | from services.external_api.utils import join_routes 5 | 6 | 7 | class HasUriPrefix(ABC): 8 | """ 9 | A base class of HTTP Gateway services. 10 | """ 11 | 12 | _version: ClassVar[str] = "" 13 | 14 | @property 15 | @classmethod 16 | @abstractmethod 17 | def prefix(cls) -> str: 18 | """ 19 | Returns the prefix of the gateway URIs. 20 | Subclasses should define it as a class variable. 21 | """ 22 | 23 | @classmethod 24 | def format_uri(cls, name: str, version: Optional[str] = None) -> str: 25 | """ 26 | Concatenates version/cls.prefix with given URI. 27 | If version is not specified, cls._version is used. 28 | """ 29 | version = version if version is not None else cls._version 30 | prefix = cast(str, cls.prefix) # Mypy sees the property as a callable. 31 | route_list = [s for s in [prefix, version, name] if s is not None and len(s) != 0] 32 | return join_routes(route_list=route_list) 33 | -------------------------------------------------------------------------------- /src/services/external_api/utils.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def join_routes(route_list: List[str]) -> str: 5 | """ 6 | Joins a list of routes where the result will start with '/' and between every two routes there 7 | will be exactly one '/'. The reason why it is implemented and the builtin urljoin isn't being 8 | used, is that urljoin ignores preceding strings in the path if a leading slash is encountered. 9 | """ 10 | assert None not in route_list and "" not in route_list 11 | return "" if len(route_list) == 0 else "/" + "/".join(s.strip("/") for s in route_list) 12 | -------------------------------------------------------------------------------- /src/services/external_api/vars.bzl: -------------------------------------------------------------------------------- 1 | SERVICES_EXTERNAL_API_LIB_ADDITIONAL_FILES = [] 2 | SERVICES_EXTERNAL_API_LIB_ADDITIONAL_LIBS = [] 3 | -------------------------------------------------------------------------------- /src/services/utils/http_status_code.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class HttpStatusCode(Enum): 5 | """ 6 | See HTTP status codes in Wikipedia: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes. 7 | """ 8 | 9 | # Success. 10 | OK = 200 11 | 12 | # Client Errors. 13 | BAD_REQUEST = 400 14 | 15 | # Server Errors. 16 | INTERNAL_SERVER_ERROR = 500 17 | -------------------------------------------------------------------------------- /src/starkware/cairo/BUILD: -------------------------------------------------------------------------------- 1 | exports_files([".isort.cfg"]) 2 | -------------------------------------------------------------------------------- /src/starkware/cairo/bootloaders/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/bootloaders/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/bootloaders/aggregator_utils.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | from starkware.cairo.lang.vm.crypto import pedersen_hash 4 | from starkware.python.utils import from_bytes 5 | 6 | 7 | def get_aggregator_input_size(program_output: List[int]) -> int: 8 | """ 9 | Returns the size of the input to an aggregator program. 10 | """ 11 | assert len(program_output) > 0, "Invalid program output for an aggregator program." 12 | n_tasks = program_output[0] 13 | 14 | offset = 1 15 | for _ in range(n_tasks): 16 | assert len(program_output) > offset, "Invalid program output for an aggregator program." 17 | task_size = program_output[offset] 18 | offset += task_size 19 | 20 | return offset 21 | 22 | 23 | def add_aggregator_prefix(program_hash: int) -> int: 24 | """ 25 | Computes H("AGGREGATOR", program_hash) which indicates that the program was treated by the 26 | bootloader as an aggregator program. 27 | """ 28 | return pedersen_hash(from_bytes(b"AGGREGATOR"), program_hash) 29 | -------------------------------------------------------------------------------- /src/starkware/cairo/bootloaders/aggregator_utils_test.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.bootloaders.aggregator_utils import get_aggregator_input_size 2 | 3 | 4 | def test_get_aggregator_input_size(): 5 | # Create an aggregator input (bootloader output) with 2 tasks with output sizes 4 and 3. 6 | aggregator_input = [2] + [4, 100, 100, 100] + [3, 100, 100] 7 | aggregator_output = [100, 100, 100, 100] 8 | assert get_aggregator_input_size(program_output=aggregator_input + aggregator_output) == len( 9 | aggregator_input 10 | ) 11 | -------------------------------------------------------------------------------- /src/starkware/cairo/bootloaders/applicative_bootloader/BUILD: -------------------------------------------------------------------------------- 1 | load("//src/starkware/cairo/lang:cairo_rules.bzl", "cairo_binary", "cairo_library") 2 | 3 | cairo_library( 4 | name = "applicative_bootloader_lib", 5 | srcs = [ 6 | "applicative_bootloader.cairo", 7 | ], 8 | deps = ["//src/starkware/cairo/bootloaders/bootloader:bootloader_lib"], 9 | ) 10 | 11 | cairo_binary( 12 | name = "applicative_bootloader_program", 13 | cairoopts = [ 14 | "--debug_info_with_source", 15 | "--proof_mode", 16 | ], 17 | compiled_program_name = "applicative_bootloader_compiled.json", 18 | main = "applicative_bootloader.cairo", 19 | deps = [":applicative_bootloader_lib"], 20 | ) 21 | 22 | package(default_visibility = ["//visibility:public"]) 23 | -------------------------------------------------------------------------------- /src/starkware/cairo/bootloaders/bootloader/constants.cairo: -------------------------------------------------------------------------------- 1 | const BOOTLOADER_CONFIG_SIZE = 3; 2 | -------------------------------------------------------------------------------- /src/starkware/cairo/bootloaders/bootloader/supported_verifier_hashes.json: -------------------------------------------------------------------------------- 1 | [ 2 | "0x1000a7b3fbe5305ae59f9298ce57619cf9914d810ba876a2c30fc6145904ce2", 3 | "0x32daa3bd81bfc6aba263401761e78ae4a21b63161d6fc74bd4482b11fbdac6", 4 | "0x268e762c9153438f6a9203036739502104708b2f100987927fae7d563e027fb", 5 | "0x7c37f4bb5e5f73b62939127cf3669f3cc5a96eb0fd0f30d5642bce1ce1c9895", 6 | "0x29fa47f641f1d0112ca6c42bc10f31b3539d688a7f8008e750eae1c6dd7e7a", 7 | "0x193641eb151b0f41674641089952e60bc3aded26e3cf42793655c562b8c3aa0", 8 | "0x14c11937eeaf285502dec0e2db494708679fa51c4229f4cad2682344eae6935", 9 | "0x10d4339b5fb9134112e8c8d21b2b800414f2aebbf595dc2a1e1db0ad7c1f11d", 10 | "0x4d817d698a34fa79d97cccf5ba2707861a94b766d749b0dd47203018a43a112", 11 | "0x2a258bceea610b1008bd183365df7809688034a927fabcaff85ff63bb956f09", 12 | "0x672ad4caa2ed1d0c3b4954b32eaf51d867203a66920d8ee6b7455b3989f6a86", 13 | "0x2824b7ddb10287dd935d6e67fb846f32fec9bacb34fea4d2246dce395d4b580", 14 | "0x4f25ecc7f3184b4b5fe3bb34e6d553c1e477ff07c3efa64c433815fbdfb51a8", 15 | "0x7fb130c1bf059a1fa742f84877872ced1b0cb2c0f3b5d1fd63435946c4b11fd", 16 | "0x341c4d45c1a5829573dd21ca08d34648ef7925eae713ee01c54f4c9cf0ce2ed", 17 | "0x114bc6a9064baa4aaa9d953497ebe48887842c68ae70769e91702e866ba60b3" 18 | ] 19 | -------------------------------------------------------------------------------- /src/starkware/cairo/builtin_selection/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/builtin_selection/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/builtin_selection/select_builtins.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.builtin_selection.inner_select_builtins import inner_select_builtins 2 | 3 | // A wrapper for 'inner_select_builtins' function (see its documentation). 4 | func select_builtins( 5 | n_builtins, 6 | all_encodings: felt*, 7 | all_ptrs: felt*, 8 | n_selected_builtins, 9 | selected_encodings: felt*, 10 | selected_ptrs: felt*, 11 | ) { 12 | %{ vm_enter_scope({'n_selected_builtins': ids.n_selected_builtins}) %} 13 | let (selected_encodings_end) = inner_select_builtins( 14 | all_encodings=all_encodings, 15 | all_ptrs=all_ptrs, 16 | selected_encodings=selected_encodings, 17 | selected_ptrs=selected_ptrs, 18 | n_builtins=n_builtins, 19 | ); 20 | %{ vm_exit_scope() %} 21 | // Assert that the correct number of builtins was selected. 22 | assert n_selected_builtins = selected_encodings_end - selected_encodings; 23 | 24 | return (); 25 | } 26 | -------------------------------------------------------------------------------- /src/starkware/cairo/cairo_verifier/BUILD: -------------------------------------------------------------------------------- 1 | load("//src/starkware/cairo/lang:cairo_rules.bzl", "cairo_library") 2 | load( 3 | "//src/starkware/cairo/cairo_verifier:cairo_verifier_layout_program.bzl", 4 | "cairo_verifier_program", 5 | ) 6 | load("cairo_verifier_layouts.bzl", "CAIRO_LAYOUTS") 7 | 8 | cairo_library( 9 | name = "cairo_verifier", 10 | srcs = [ 11 | "objects.cairo", 12 | "//src/starkware/cairo/lang/compiler/lib:registers.cairo", 13 | ], 14 | deps = [ 15 | "//src/starkware/cairo/common:cairo_common_cairo_lib", 16 | "//src/starkware/cairo/stark_verifier/core:stark", 17 | "//src/starkware/cairo/stark_verifier/core/fri", 18 | ], 19 | ) 20 | 21 | CAIRO_VERIFIER_LAYOUT_PROGRAM_OUTPUTS = [ 22 | cairo_verifier_program(layout_name = layout_name) 23 | for layout_name in CAIRO_LAYOUTS 24 | ] 25 | 26 | CAIRO_VERIFIER_PROGRAM_ARTIFACTS_ALL_LAYOUTS = [ 27 | output.compiled_program_name 28 | for output in CAIRO_VERIFIER_LAYOUT_PROGRAM_OUTPUTS 29 | ] 30 | 31 | package(default_visibility = ["//visibility:public"]) 32 | 33 | exports_files([ 34 | "example_fact_topologies.json", 35 | "example_single_fact_topologies.json", 36 | "example_proof.json", 37 | "objects.cairo", 38 | ]) 39 | -------------------------------------------------------------------------------- /src/starkware/cairo/cairo_verifier/cairo_verifier_layouts.bzl: -------------------------------------------------------------------------------- 1 | CAIRO_LAYOUTS = [ 2 | "all_cairo", 3 | ] 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/cairo_verifier/layouts/all_cairo/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "pytest_test") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files(["cairo_verifier.cairo"]) 6 | 7 | pytest_test( 8 | name = "cairo_verifier_program_hash_all_cairo_test", 9 | srcs = [ 10 | "program_hash_test.py", 11 | ], 12 | data = [ 13 | "program_hash.json", 14 | "//src/starkware/cairo/cairo_verifier:cairo_verifier_compiled_all_cairo.json", 15 | ], 16 | visibility = ["//visibility:public"], 17 | deps = [ 18 | "//src/starkware/cairo/bootloaders:cairo_hash_program_lib", 19 | "//src/starkware/cairo/bootloaders:program_hash_test_utils_lib", 20 | ], 21 | ) 22 | -------------------------------------------------------------------------------- /src/starkware/cairo/cairo_verifier/layouts/all_cairo/program_hash.json: -------------------------------------------------------------------------------- 1 | { 2 | "program_hash": "0x2dc3398dda59a9abd48a67c6cdf7f73f685f242bc320f6ca0c1b68eac925df0" 3 | } 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/cairo_verifier/layouts/all_cairo/program_hash_test.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.bootloaders.program_hash_test_utils import ( 2 | program_hash_test_main, 3 | run_generate_hash_test, 4 | ) 5 | from starkware.python.utils import get_build_dir_path, get_source_dir_path 6 | 7 | PROGRAM_PATH = get_build_dir_path( 8 | "src/starkware/cairo/cairo_verifier/cairo_verifier_compiled_all_cairo.json" 9 | ) 10 | HASH_PATH = get_source_dir_path( 11 | rel_path="src/starkware/cairo/cairo_verifier/layouts/all_cairo/program_hash.json", 12 | default_value=get_build_dir_path( 13 | "src/starkware/cairo/cairo_verifier/layouts/all_cairo/program_hash.json" 14 | ), 15 | ) 16 | 17 | COMMAND = "generate_cairo_verifier_program_hash_all_cairo" 18 | 19 | 20 | def test_program_hash(): 21 | run_generate_hash_test( 22 | fix=False, program_path=PROGRAM_PATH, hash_path=HASH_PATH, command=COMMAND 23 | ) 24 | 25 | 26 | if __name__ == "__main__": 27 | program_hash_test_main(program_path=PROGRAM_PATH, hash_path=HASH_PATH, command=COMMAND) 28 | -------------------------------------------------------------------------------- /src/starkware/cairo/cairo_verifier/objects.cairo: -------------------------------------------------------------------------------- 1 | struct CairoVerifierOutput { 2 | program_hash: felt, 3 | output_hash: felt, 4 | } 5 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/alloc.cairo: -------------------------------------------------------------------------------- 1 | // Allocates a new memory segment. 2 | func alloc() -> (ptr: felt*) { 3 | %{ memory[ap] = segments.add() %} 4 | ap += 1; 5 | return (ptr=cast([ap - 1], felt*)); 6 | } 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/bool.cairo: -------------------------------------------------------------------------------- 1 | // Represents boolean values in Cairo. 2 | const FALSE = 0; 3 | const TRUE = 1; 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/builtin_keccak/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(["keccak.cairo"]) 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/builtin_poseidon/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(["poseidon.cairo"]) 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_blake2s/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "pytest_test") 2 | 3 | pytest_test( 4 | name = "cairo_blake2s_test", 5 | srcs = [ 6 | "blake2s_test.py", 7 | ], 8 | data = [ 9 | "blake2s_test.cairo", 10 | ], 11 | visibility = ["//visibility:public"], 12 | deps = [ 13 | "//src/starkware/cairo/common:cairo_common_lib", 14 | "//src/starkware/cairo/common:cairo_function_runner_lib", 15 | "//src/starkware/cairo/lang:cairo_constants_lib", 16 | "//src/starkware/cairo/lang/builtins:cairo_run_builtins_lib", 17 | "//src/starkware/cairo/lang/compiler:cairo_compile_lib", 18 | "//src/starkware/python:starkware_python_utils_lib", 19 | ], 20 | ) 21 | 22 | exports_files([ 23 | "blake2s.cairo", 24 | "blake2s_utils.py", 25 | "packed_blake2s.cairo", 26 | ]) 27 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_blake2s/blake2s_test.cairo: -------------------------------------------------------------------------------- 1 | %builtins range_check bitwise 2 | 3 | from starkware.cairo.common.alloc import alloc 4 | from starkware.cairo.common.cairo_blake2s.blake2s import ( 5 | INSTANCE_SIZE, 6 | blake2s, 7 | blake2s_add_felts, 8 | blake2s_add_uint256, 9 | blake2s_add_uint256_bigend, 10 | blake2s_as_words, 11 | blake2s_bigend, 12 | blake2s_felts, 13 | encode_felt252_to_u32s, 14 | finalize_blake2s, 15 | ) 16 | from starkware.cairo.common.cairo_builtins import BitwiseBuiltin 17 | 18 | func run_blake2s{range_check_ptr, blake2s_ptr: felt*}(inputs: felt**, lengths: felt*, n: felt) { 19 | if (n == 0) { 20 | return (); 21 | } 22 | 23 | blake2s(inputs[0], lengths[0]); 24 | return run_blake2s(inputs + 1, lengths + 1, n - 1); 25 | } 26 | 27 | func run_blake2s_and_finalize{range_check_ptr, bitwise_ptr: BitwiseBuiltin*}( 28 | inputs: felt**, lengths: felt*, n: felt 29 | ) { 30 | alloc_locals; 31 | let (local blake2s_ptr_start) = alloc(); 32 | let blake2s_ptr = blake2s_ptr_start; 33 | 34 | run_blake2s{blake2s_ptr=blake2s_ptr}(inputs, lengths, n); 35 | finalize_blake2s(blake2s_ptr_start=blake2s_ptr_start, blake2s_ptr_end=blake2s_ptr); 36 | return (); 37 | } 38 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_ec_op/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "ec_op.cairo", 5 | ]) 6 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_ecdsa/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "ecdsa.cairo", 5 | ]) 6 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_keccak/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "keccak.cairo", 5 | "keccak_utils.py", 6 | "packed_keccak.cairo", 7 | ]) 8 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_keccak/keccak_utils.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.common.keccak_utils.keccak_utils import * # noqa 2 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_secp/BUILD: -------------------------------------------------------------------------------- 1 | load("//src/starkware/cairo/lang:cairo_rules.bzl", "cairo_library") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files(glob([ 6 | "*.cairo", 7 | "*.py", 8 | ])) 9 | 10 | py_library( 11 | name = "utils", 12 | srcs = ["secp_utils.py"], 13 | deps = ["//src/starkware/cairo/common:cairo_common_lib"], 14 | ) 15 | 16 | cairo_library( 17 | name = "cairo_secp256k1", 18 | srcs = [ 19 | "bigint.cairo", 20 | "bigint3.cairo", 21 | "constants.cairo", 22 | "ec.cairo", 23 | "ec_point.cairo", 24 | "field.cairo", 25 | "signature.cairo", 26 | ], 27 | ) 28 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_secp/bigint3.cairo: -------------------------------------------------------------------------------- 1 | // Represents a big integer defined by: 2 | // d0 + BASE * d1 + BASE**2 * d2. 3 | // Note that the limbs (d_i) are NOT restricted to the range [0, BASE) and in particular they 4 | // can be negative. 5 | // In most cases this is used to represent a Secp256k1 or Secp256r1 field element. 6 | struct UnreducedBigInt3 { 7 | d0: felt, 8 | d1: felt, 9 | d2: felt, 10 | } 11 | 12 | // Same as UnreducedBigInt3, except that d0, d1 and d2 satisfy the bounds of 13 | // nondet_bigint3 or are the difference of two values satisfying those bounds. 14 | // In most cases this is used to represent a Secp256k1 or Secp256r1 field element. 15 | struct BigInt3 { 16 | d0: felt, 17 | d1: felt, 18 | d2: felt, 19 | } 20 | 21 | // Same as BigInt3, except the bounds on d0, d1 and d2 are twice as large. 22 | struct SumBigInt3 { 23 | d0: felt, 24 | d1: felt, 25 | d2: felt, 26 | } 27 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_secp/ec_point.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.common.cairo_secp.bigint3 import BigInt3 2 | 3 | // Represents a point on the secp256k1 elliptic curve. 4 | // The zero point is represented as a point with x = 0 (there is no point on the curve with a zero 5 | // x value). 6 | // x and y satisfy the bounds of nondet_bigint3 for the relevant curve. 7 | struct EcPoint { 8 | x: BigInt3, 9 | y: BigInt3, 10 | } 11 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_secp/secp256r1_utils.py: -------------------------------------------------------------------------------- 1 | SECP256R1_P = 2**256 - 2**224 + 2**192 + 2**96 - 1 2 | SECP256R1_N = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 3 | SECP256R1_ALPHA = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC 4 | SECP256R1_BETA = 0x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B 5 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/cairo_sha256/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "sha256_utils.cairo", 5 | "sha256_utils.py", 6 | ]) 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/copy_indices.cairo: -------------------------------------------------------------------------------- 1 | // Copies len field elements from src to dst at the given indices. 2 | // I.e., dst = [src[i] for i in indices]. 3 | func copy_indices(dst: felt*, src: felt*, indices: felt*, len: felt) { 4 | struct LoopFrame { 5 | dst: felt*, 6 | indices: felt*, 7 | } 8 | 9 | if (len == 0) { 10 | return (); 11 | } 12 | 13 | %{ vm_enter_scope({'n': ids.len}) %} 14 | tempvar frame = LoopFrame(dst=dst, indices=indices); 15 | 16 | loop: 17 | let frame = [cast(ap - LoopFrame.SIZE, LoopFrame*)]; 18 | assert [frame.dst] = src[[frame.indices]]; 19 | 20 | let continue_copying = [ap]; 21 | // Reserve space for continue_copying. 22 | let next_frame = cast(ap + 1, LoopFrame*); 23 | next_frame.dst = frame.dst + 1, ap++; 24 | next_frame.indices = frame.indices + 1, ap++; 25 | %{ 26 | n -= 1 27 | ids.continue_copying = 1 if n > 0 else 0 28 | %} 29 | static_assert next_frame + LoopFrame.SIZE == ap + 1; 30 | jmp loop if continue_copying != 0, ap++; 31 | // Assert that the loop executed len times. 32 | len = cast(next_frame.indices, felt) - cast(indices, felt); 33 | 34 | %{ vm_exit_scope() %} 35 | return (); 36 | } 37 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/dict_access.cairo: -------------------------------------------------------------------------------- 1 | // Represents an access (read, write or modify) to the dictionary. The dictionary is represented as 2 | // a chronological list of such accesses. The "current" value of a key is the new_value of the last 3 | // access with that key. 4 | // In a valid dictionary, the prev_value of each access is equal to the new_value of the previous 5 | // access to the same key. 6 | struct DictAccess { 7 | key: felt, 8 | prev_value: felt, 9 | new_value: felt, 10 | } 11 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/ec_point.cairo: -------------------------------------------------------------------------------- 1 | // Represents a point on an elliptic curve. 2 | struct EcPoint { 3 | x: felt, 4 | y: felt, 5 | } 6 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/hash.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.common.cairo_builtins import HashBuiltin 2 | 3 | // Computes the hash of two given field elements. 4 | // The hash function is defined by the hash_ptr used. 5 | // For example, pass the pedersen builtin pointer to compute Pedersen hash. 6 | // 7 | // Arguments: 8 | // hash_ptr - the hash builtin pointer. 9 | // x, y - the two field elements to be hashed, in this order. 10 | // 11 | // Returns: 12 | // result - the field element result of the hash. 13 | func hash2{hash_ptr: HashBuiltin*}(x, y) -> (result: felt) { 14 | hash_ptr.x = x; 15 | hash_ptr.y = y; 16 | let result = hash_ptr.result; 17 | let hash_ptr = hash_ptr + HashBuiltin.SIZE; 18 | return (result=result); 19 | } 20 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/hash_chain.py: -------------------------------------------------------------------------------- 1 | import functools 2 | 3 | from starkware.cairo.lang.vm.crypto import pedersen_hash 4 | 5 | 6 | def compute_hash_chain(data, hash_func=pedersen_hash): 7 | """ 8 | Computes a hash chain over the data, in the following order: 9 | h(data[0], h(data[1], h(..., h(data[n-2], data[n-1])))). 10 | """ 11 | assert len(data) >= 1, f"len(data) for hash chain computation must be >= 1; got: {len(data)}." 12 | return functools.reduce(lambda x, y: hash_func(y, x), data[::-1]) 13 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/hash_chain_test.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.common.hash_chain import compute_hash_chain 2 | from starkware.cairo.lang.vm.crypto import pedersen_hash 3 | 4 | 5 | def test_compute_hash_chain(): 6 | data = [1, 2, 3] 7 | assert compute_hash_chain(data) == pedersen_hash(1, pedersen_hash(2, 3)) 8 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/hash_state.py: -------------------------------------------------------------------------------- 1 | import functools 2 | 3 | from starkware.cairo.lang.vm.crypto import pedersen_hash 4 | 5 | 6 | def compute_hash_on_elements(data, hash_func=pedersen_hash): 7 | """ 8 | Computes a hash chain over the data, in the following order: 9 | h(h(h(h(0, data[0]), data[1]), ...), data[n-1]), n). 10 | 11 | The hash is initialized with 0 and ends with the data length appended. 12 | The length is appended in order to avoid collisions of the following kind: 13 | H([x,y,z]) = h(h(x,y),z) = H([w, z]) where w = h(x,y). 14 | """ 15 | return functools.reduce(lambda x, y: hash_func(x, y), [*data, len(data)], 0) 16 | 17 | 18 | def compute_hash_on_elements_without_length(data, hash_func=pedersen_hash): 19 | """ 20 | Similar to `compute_hash_on_elements` but without appending the length. 21 | May be used for hashing a prefix of a hash chain. 22 | """ 23 | return functools.reduce(lambda x, y: hash_func(x, y), data, 0) 24 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/invoke.cairo: -------------------------------------------------------------------------------- 1 | // Calls func_ptr(args[0], args[1], ..., args[n_args - 1]) and forwards its return value. 2 | // In order to convert a label to pc and use it as a value for the func_ptr argument, 3 | // use get_label_location(). 4 | func invoke(func_ptr: felt*, n_args: felt, args: felt*) { 5 | invoke_prepare_args(args_end=args + n_args, n_args=n_args); 6 | call abs func_ptr; 7 | ret; 8 | } 9 | 10 | // Helper function for invoke(). 11 | // Copies the memory range [args_end - n_args, args_end) to the memory range 12 | // [final_ap - n_args, final_ap) where final_ap is the value of ap when the function returns. 13 | func invoke_prepare_args(args_end: felt*, n_args: felt) { 14 | if (n_args == 0) { 15 | return (); 16 | } 17 | 18 | invoke_prepare_args(args_end=args_end - 1, n_args=n_args - 1); 19 | [ap] = [args_end - 1], ap++; 20 | return (); 21 | } 22 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/keccak_state.cairo: -------------------------------------------------------------------------------- 1 | // Represents 1600 bits of a Keccak state (8 felts each containing 200 bits). 2 | struct KeccakBuiltinState { 3 | s0: felt, 4 | s1: felt, 5 | s2: felt, 6 | s3: felt, 7 | s4: felt, 8 | s5: felt, 9 | s6: felt, 10 | s7: felt, 11 | } 12 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/keccak_utils/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "keccak_utils.cairo", 5 | "keccak_utils.py", 6 | ]) 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/log2_ceil.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.common.math import assert_in_range, assert_not_zero 2 | from starkware.cairo.common.pow import pow 3 | 4 | // Returns the ceil value of the log2 of the given value. 5 | // Enforces that 1 <= value <= RANGE_CHECK_BOUND. 6 | func log2_ceil{range_check_ptr}(value: felt) -> felt { 7 | alloc_locals; 8 | assert_not_zero(value); 9 | if (value == 1) { 10 | return 0; 11 | } 12 | 13 | local res; 14 | %{ 15 | from starkware.python.math_utils import log2_ceil 16 | ids.res = log2_ceil(ids.value) 17 | %} 18 | 19 | // Verify that 1 <= 2**(res - 1) < value <= 2**res <= RANGE_CHECK_BOUND. 20 | // The RANGE_CHECK_BOUND bound is required by the `assert_in_range` function. 21 | assert_in_range(res, 1, 128 + 1); 22 | let (lower_bound) = pow(2, res - 1); 23 | let min = lower_bound + 1; 24 | let max = 2 * lower_bound; 25 | assert_in_range(value, min, max + 1); 26 | 27 | return res; 28 | } 29 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/math_utils.py: -------------------------------------------------------------------------------- 1 | def assert_integer(val): 2 | """ 3 | Asserts that the input is an integer (and not relocatable value). 4 | """ 5 | assert isinstance(val, int), f"Expected integer, found: {val}." 6 | 7 | 8 | def as_int(val, prime): 9 | """ 10 | Returns the lift of the given field element, val, as an integer in the range 11 | (-prime/2, prime/2). 12 | """ 13 | assert_integer(val) 14 | return val if val < prime // 2 else val - prime 15 | 16 | 17 | def is_positive(value, prime, rc_bound): 18 | """ 19 | Returns True if the lift of the given field element, as an integer in the range 20 | (-rc_bound, rc_bound), is positive. 21 | Raises an exception if the element is not within that range. 22 | """ 23 | val = as_int(value, prime) 24 | assert abs(val) < rc_bound, f"value={val} is out of the valid range." 25 | return val > 0 26 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/memcpy.cairo: -------------------------------------------------------------------------------- 1 | // Copies len field elements from src to dst. 2 | func memcpy(dst: felt*, src: felt*, len) { 3 | struct LoopFrame { 4 | dst: felt*, 5 | src: felt*, 6 | } 7 | 8 | if (len == 0) { 9 | return (); 10 | } 11 | 12 | %{ vm_enter_scope({'n': ids.len}) %} 13 | tempvar frame = LoopFrame(dst=dst, src=src); 14 | 15 | loop: 16 | let frame = [cast(ap - LoopFrame.SIZE, LoopFrame*)]; 17 | assert [frame.dst] = [frame.src]; 18 | 19 | let continue_copying = [ap]; 20 | // Reserve space for continue_copying. 21 | let next_frame = cast(ap + 1, LoopFrame*); 22 | next_frame.dst = frame.dst + 1, ap++; 23 | next_frame.src = frame.src + 1, ap++; 24 | %{ 25 | n -= 1 26 | ids.continue_copying = 1 if n > 0 else 0 27 | %} 28 | static_assert next_frame + LoopFrame.SIZE == ap + 1; 29 | jmp loop if continue_copying != 0, ap++; 30 | // Assert that the loop executed len times. 31 | len = cast(next_frame.src, felt) - cast(src, felt); 32 | 33 | %{ vm_exit_scope() %} 34 | return (); 35 | } 36 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/memset.cairo: -------------------------------------------------------------------------------- 1 | // Writes value into [dst + 0], ..., [dst + n - 1]. 2 | func memset(dst: felt*, value: felt, n) { 3 | struct LoopFrame { 4 | dst: felt*, 5 | } 6 | 7 | if (n == 0) { 8 | return (); 9 | } 10 | 11 | %{ vm_enter_scope({'n': ids.n}) %} 12 | tempvar frame = LoopFrame(dst=dst); 13 | 14 | loop: 15 | let frame = [cast(ap - LoopFrame.SIZE, LoopFrame*)]; 16 | assert [frame.dst] = value; 17 | 18 | let continue_loop = [ap]; 19 | // Reserve space for continue_loop. 20 | let next_frame = cast(ap + 1, LoopFrame*); 21 | next_frame.dst = frame.dst + 1, ap++; 22 | %{ 23 | n -= 1 24 | ids.continue_loop = 1 if n > 0 else 0 25 | %} 26 | static_assert next_frame + LoopFrame.SIZE == ap + 1; 27 | jmp loop if continue_loop != 0, ap++; 28 | // Assert that the loop executed n times. 29 | n = cast(next_frame.dst, felt) - cast(dst, felt); 30 | 31 | %{ vm_exit_scope() %} 32 | return (); 33 | } 34 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/patricia_utils.cairo: -------------------------------------------------------------------------------- 1 | // Maximum length of an edge. 2 | const MAX_LENGTH = 251; 3 | 4 | // A struct of globals that are passed throughout the algorithm. 5 | struct ParticiaGlobals { 6 | // An array of size MAX_LENGTH, where pow2[i] = 2**i. 7 | pow2: felt*, 8 | // Offset of the relevant value field in DictAccess. 9 | // 1 if the previous tree is traversed and 2 if the new tree is traversed. 10 | access_offset: felt, 11 | } 12 | 13 | // Represents an edge node: a subtree with a path, s.t. all leaves not under that path are 0. 14 | struct NodeEdge { 15 | length: felt, 16 | path: felt, 17 | bottom: felt, 18 | } 19 | 20 | // Holds the constants needed for Patricia updates. 21 | struct PatriciaUpdateConstants { 22 | globals_pow2: felt*, 23 | } 24 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/patricia_with_poseidon.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.common.cairo_builtins import PoseidonBuiltin 2 | from starkware.cairo.common.dict import DictAccess 3 | from starkware.cairo.common.patricia_utils import PatriciaUpdateConstants 4 | from starkware.cairo.common.patricia_with_sponge import ( 5 | patricia_update_using_update_constants as patricia_update_using_update_constants_with_sponge, 6 | ) 7 | from starkware.cairo.common.sponge_as_hash import SpongeHashBuiltin 8 | 9 | func patricia_update_using_update_constants{poseidon_ptr: PoseidonBuiltin*, range_check_ptr}( 10 | patricia_update_constants: PatriciaUpdateConstants*, 11 | update_ptr: DictAccess*, 12 | n_updates: felt, 13 | height: felt, 14 | prev_root: felt, 15 | new_root: felt, 16 | ) { 17 | let hash_ptr = cast(poseidon_ptr, SpongeHashBuiltin*); 18 | 19 | with hash_ptr { 20 | patricia_update_using_update_constants_with_sponge( 21 | patricia_update_constants=patricia_update_constants, 22 | update_ptr=update_ptr, 23 | n_updates=n_updates, 24 | height=height, 25 | prev_root=prev_root, 26 | new_root=new_root, 27 | ); 28 | } 29 | 30 | // Update poseidon_ptr. 31 | let poseidon_ptr = cast(hash_ptr, PoseidonBuiltin*); 32 | 33 | return (); 34 | } 35 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/poseidon_state.cairo: -------------------------------------------------------------------------------- 1 | // Represents a Poseidon state. 2 | struct PoseidonBuiltinState { 3 | s0: felt, 4 | s1: felt, 5 | s2: felt, 6 | } 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/registers.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.compiler.lib.registers import get_ap, get_fp_and_pc 2 | 3 | // Takes the value of a label (relative to program base) and returns the actual runtime address of 4 | // that label in the memory. 5 | // 6 | // Usage example: 7 | // 8 | // func do_callback(...) { 9 | // ... 10 | // } 11 | // 12 | // func do_thing_then_callback(callback) { 13 | // ... 14 | // call abs callback; 15 | // } 16 | // 17 | // func main() { 18 | // let (callback_address) = get_label_location(do_callback); 19 | // do_thing_then_callback(callback=callback_address); 20 | // } 21 | func get_label_location(label_value: codeoffset) -> (res: felt*) { 22 | let (_, pc_val) = get_fp_and_pc(); 23 | 24 | ret_pc_label: 25 | return (res=pc_val + (label_value - ret_pc_label)); 26 | } 27 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/secp256r1/BUILD: -------------------------------------------------------------------------------- 1 | load("//src/starkware/cairo/lang:cairo_rules.bzl", "cairo_library") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | cairo_library( 6 | name = "cairo_secp256r1", 7 | srcs = [ 8 | "bigint.cairo", 9 | "constants.cairo", 10 | "ec.cairo", 11 | "field.cairo", 12 | ], 13 | visibility = ["//visibility:public"], 14 | ) 15 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/segments.cairo: -------------------------------------------------------------------------------- 1 | // Relocates src_ptr to dest_ptr. 2 | // 'src_ptr' must point to the start of a temporary segment. 3 | // 4 | // See add_relocation_rule() in src/starkware/cairo/lang/vm/memory_dict.py for more details. 5 | func relocate_segment(src_ptr: felt*, dest_ptr: felt*) { 6 | %{ memory.add_relocation_rule(src_ptr=ids.src_ptr, dest_ptr=ids.dest_ptr) %} 7 | 8 | // Add a verifier side assert that src_ptr and dest_ptr are indeed equal. 9 | assert src_ptr = dest_ptr; 10 | return (); 11 | } 12 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/sha256_state.cairo: -------------------------------------------------------------------------------- 1 | // Represents 256 bits of a SHA256 state (8 felts each containing 32 bits). 2 | struct Sha256State { 3 | s0: felt, 4 | s1: felt, 5 | s2: felt, 6 | s3: felt, 7 | s4: felt, 8 | s5: felt, 9 | s6: felt, 10 | s7: felt, 11 | } 12 | 13 | // Represents 512 bits of a SHA256 input (16 felts each containing 32 bits). 14 | struct Sha256Input { 15 | s0: felt, 16 | s1: felt, 17 | s2: felt, 18 | s3: felt, 19 | s4: felt, 20 | s5: felt, 21 | s6: felt, 22 | s7: felt, 23 | s8: felt, 24 | s9: felt, 25 | s10: felt, 26 | s11: felt, 27 | s12: felt, 28 | s13: felt, 29 | s14: felt, 30 | s15: felt, 31 | } 32 | 33 | struct Sha256ProcessBlock { 34 | input: Sha256Input, 35 | in_state: Sha256State, 36 | out_state: Sha256State, 37 | } 38 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/simulate_builtin_keccak_with_cairo/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "simulate_keccak.cairo", 5 | ]) 6 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/sponge_as_hash.cairo: -------------------------------------------------------------------------------- 1 | // Specifies a sponge builtin (e.g., Poseidon builtin) as a 2-to-1 hash function. 2 | // x, y - inputs to the hash function. 3 | // c_in - the capacity part of the input (must be initialized to a constant, we use 2). 4 | // result - the output of the hash function. 5 | // result1 - can be used as another output element if a longer output is needed. 6 | // c_out - the capacity part of the output (it is unsafe to use it as an output). 7 | struct SpongeHashBuiltin { 8 | x: felt, 9 | y: felt, 10 | c_in: felt, 11 | result: felt, 12 | result1: felt, 13 | c_out: felt, 14 | } 15 | 16 | // Computes the hash of two given field elements. 17 | // The hash function is defined by the hash_ptr used. 18 | // For example, pass the poseidon builtin pointer to compute Poseidon hash. 19 | // 20 | // Arguments: 21 | // hash_ptr - the sponge hash builtin pointer. 22 | // x, y - the two field elements to be hashed, in this order. 23 | // 24 | // Returns: 25 | // result - the field element result of the hash. 26 | func sponge_hash2{hash_ptr: SpongeHashBuiltin*}(x: felt, y: felt) -> (result: felt) { 27 | hash_ptr.x = x; 28 | hash_ptr.y = y; 29 | assert hash_ptr.c_in = 2; 30 | let result = hash_ptr.result; 31 | let hash_ptr = hash_ptr + SpongeHashBuiltin.SIZE; 32 | return (result=result); 33 | } 34 | -------------------------------------------------------------------------------- /src/starkware/cairo/common/validate_utils.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.vm.builtin_runner import SimpleBuiltinRunner 2 | from starkware.cairo.lang.vm.relocatable import RelocatableValue 3 | 4 | 5 | def validate_builtin_usage(builtin_runner: SimpleBuiltinRunner, end_ptr: RelocatableValue): 6 | assert builtin_runner.base is not None 7 | usage = end_ptr - builtin_runner.base 8 | assert usage % builtin_runner.cells_per_instance == 0, ( 9 | f"usage = {usage} is not a multiple of cells_per_instance = " 10 | f"{builtin_runner.cells_per_instance}." 11 | ) 12 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/MANIFEST.in: -------------------------------------------------------------------------------- 1 | include requirements.txt 2 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/VERSION: -------------------------------------------------------------------------------- 1 | 0.14.0a1 2 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/builtins/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/bitwise/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "bitwise_builtin_runner.py", 5 | "instance_def.py", 6 | ]) 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/bitwise/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/builtins/bitwise/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/builtin_runner_test_utils.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | from starkware.cairo.lang.compiler.cairo_compile import compile_cairo 4 | from starkware.cairo.lang.instances import CairoLayout 5 | from starkware.cairo.lang.vm.cairo_runner import CairoRunner 6 | from starkware.cairo.lang.vm.security import verify_secure_runner 7 | 8 | PRIME = 2**251 + 17 * 2**192 + 1 9 | 10 | 11 | def compile_and_run( 12 | code: str, layout: Union[str, CairoLayout] = "small", secure_run: bool = False 13 | ) -> CairoRunner: 14 | """ 15 | Compiles the given code and runs it in the VM. 16 | """ 17 | program = compile_cairo(code, PRIME) 18 | runner = CairoRunner(program, layout=layout, proof_mode=False) 19 | runner.initialize_segments() 20 | end = runner.initialize_main_entrypoint() 21 | runner.initialize_zero_segment() 22 | runner.initialize_vm({}) 23 | runner.run_until_pc(end) 24 | runner.end_run() 25 | if secure_run: 26 | runner.read_return_values() 27 | verify_secure_runner(runner) 28 | pie = runner.get_cairo_pie() 29 | pie.run_validity_checks() 30 | 31 | return runner 32 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/ec/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "pytest_test") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files([ 6 | "ec_op_builtin_runner.py", 7 | "instance_def.py", 8 | ]) 9 | 10 | pytest_test( 11 | name = "cairo_run_builtins_ec_op_test", 12 | srcs = [ 13 | "ec_op_builtin_runner_test.py", 14 | ], 15 | visibility = ["//visibility:public"], 16 | deps = [ 17 | "//src/starkware/cairo/lang/builtins:cairo_run_builtins_test_utils_lib", 18 | "//src/starkware/cairo/lang/vm:cairo_vm_lib", 19 | "//src/starkware/crypto:starkware_crypto_lib", 20 | "//src/starkware/python:starkware_python_utils_lib", 21 | ], 22 | ) 23 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/ec/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/builtins/ec/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/ec/instance_def.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | from typing import Optional 3 | 4 | from starkware.cairo.lang.builtins.instance_def import BuiltinInstanceDef 5 | 6 | # Each EC operation P + m * Q = R contains 7 cells: P_x, P_y, Q_x, Q_y, m, R_x, R_y. 7 | CELLS_PER_EC_OP = 7 8 | INPUT_CELLS_PER_EC_OP = 5 9 | 10 | 11 | @dataclasses.dataclass 12 | class EcOpInstanceDef(BuiltinInstanceDef): 13 | # Size of coefficient. 14 | scalar_height: int 15 | scalar_bits: int 16 | # The upper bound on the multiplication scalar, m. If None, the upper bound is 2^scalar_bits. 17 | scalar_limit: Optional[int] = None 18 | 19 | @property 20 | def memory_cells_per_instance(self) -> int: 21 | return CELLS_PER_EC_OP 22 | 23 | @property 24 | def range_check_units_per_builtin(self) -> int: 25 | return 0 26 | 27 | @property 28 | def invocation_height(self) -> int: 29 | return self.scalar_height 30 | 31 | def get_diluted_units_per_builtin(self, diluted_spacing: int, diluted_n_bits: int) -> int: 32 | return 0 33 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/hash/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "hash_builtin_runner.py", 5 | "instance_def.py", 6 | ]) 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/hash/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/builtins/hash/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/hash/instance_def.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | from typing import Optional 3 | 4 | from starkware.cairo.lang.builtins.instance_def import BuiltinInstanceDef 5 | 6 | # Each hash consists of 3 cells (two inputs and one output). 7 | CELLS_PER_HASH = 3 8 | INPUT_CELLS_PER_HASH = 2 9 | 10 | 11 | @dataclasses.dataclass 12 | class PedersenInstanceDef(BuiltinInstanceDef): 13 | # Split to this many different components - for optimization. 14 | repetitions: int 15 | 16 | # Size of hash. 17 | element_height: int 18 | element_bits: int 19 | # Number of inputs for hash. 20 | n_inputs: int 21 | # The upper bound on the hash inputs. If None, the upper bound is 2^element_bits. 22 | hash_limit: Optional[int] = None 23 | 24 | @property 25 | def memory_cells_per_instance(self) -> int: 26 | return CELLS_PER_HASH 27 | 28 | @property 29 | def range_check_units_per_builtin(self) -> int: 30 | return 0 31 | 32 | @property 33 | def invocation_height(self) -> int: 34 | return self.element_height * self.n_inputs 35 | 36 | def get_diluted_units_per_builtin(self, diluted_spacing: int, diluted_n_bits: int) -> int: 37 | return 0 38 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/keccak/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "instance_def.py", 5 | "keccak_builtin_runner.py", 6 | ]) 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/keccak/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/builtins/keccak/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/modulo/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "pytest_test") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files([ 6 | "instance_def.py", 7 | "mod_builtin_runner.py", 8 | ]) 9 | 10 | pytest_test( 11 | name = "cairo_run_builtins_mod_test", 12 | srcs = [ 13 | "mod_builtin_runner_test.py", 14 | ], 15 | data = [ 16 | "modulo_test.cairo", 17 | ], 18 | visibility = ["//visibility:public"], 19 | deps = [ 20 | "//src/starkware/cairo/lang:cairo_instances_lib", 21 | "//src/starkware/cairo/lang/builtins:cairo_run_builtins_lib", 22 | "//src/starkware/cairo/lang/builtins:cairo_run_builtins_test_utils_lib", 23 | "//src/starkware/cairo/lang/vm:cairo_relocatable_lib", 24 | "//src/starkware/cairo/lang/vm:cairo_run_lib", 25 | "//src/starkware/cairo/lang/vm:cairo_vm_lib", 26 | ], 27 | ) 28 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/modulo/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/builtins/modulo/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/poseidon/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "instance_def.py", 5 | "poseidon_builtin_runner.py", 6 | ]) 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/poseidon/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/builtins/poseidon/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/poseidon/instance_def.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | from typing import List 3 | 4 | from starkware.cairo.lang.builtins.instance_def import BuiltinInstanceDef 5 | from starkware.python.math_utils import next_power_of_2 6 | 7 | POSEIDON_M = 3 8 | 9 | 10 | @dataclasses.dataclass 11 | class PoseidonInstanceDef(BuiltinInstanceDef): 12 | # Defines the partition of the partial rounds to virtual columns. 13 | partial_rounds_partition: List[int] 14 | 15 | @property 16 | def memory_cells_per_instance(self) -> int: 17 | return 2 * POSEIDON_M 18 | 19 | @property 20 | def range_check_units_per_builtin(self) -> int: 21 | return 0 22 | 23 | @property 24 | def invocation_height(self) -> int: 25 | # The virtual columns of poseidon hash are: 26 | # 1. full_rounds_state{i} - whose height is Rf = number of full rounds = 8. 27 | # 2. partial_rounds_state{part} - whose height is self.partial_rounds_partition[part]. 28 | # 3. The squares of the above, which have the same sizes. 29 | # The total height is defined by the maximum of all sizes. 30 | return next_power_of_2(max([8] + self.partial_rounds_partition)) 31 | 32 | def get_diluted_units_per_builtin(self, diluted_spacing: int, diluted_n_bits: int) -> int: 33 | return 0 34 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/range_check/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "pytest_test") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files([ 6 | "instance_def.py", 7 | "range_check_builtin_runner.py", 8 | ]) 9 | 10 | pytest_test( 11 | name = "cairo_run_builtins_range_check_test", 12 | srcs = [ 13 | "range_check_builtin_runner_test.py", 14 | ], 15 | visibility = ["//visibility:public"], 16 | deps = [ 17 | "//src/starkware/cairo/lang/builtins:cairo_run_builtins_test_utils_lib", 18 | "//src/starkware/cairo/lang/vm:cairo_vm_lib", 19 | ], 20 | ) 21 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/range_check/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/builtins/range_check/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/range_check/instance_def.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | 3 | from starkware.cairo.lang.builtins.instance_def import BuiltinInstanceDefWithLowRatio 4 | 5 | CELLS_PER_RANGE_CHECK = 1 6 | 7 | 8 | @dataclasses.dataclass 9 | class RangeCheckInstanceDef(BuiltinInstanceDefWithLowRatio): 10 | # Number of 16-bit range checks that will be used for each instance of the builtin. 11 | # For example, n_parts=8 defines the range [0, 2^128). 12 | n_parts: int 13 | 14 | @property 15 | def memory_cells_per_instance(self) -> int: 16 | return CELLS_PER_RANGE_CHECK 17 | 18 | @property 19 | def range_check_units_per_builtin(self) -> int: 20 | return self.n_parts 21 | 22 | @property 23 | def invocation_height(self) -> int: 24 | return self.n_parts 25 | 26 | def get_diluted_units_per_builtin(self, diluted_spacing: int, diluted_n_bits: int) -> int: 27 | return 0 28 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/range_check/range_check_builtin_runner_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from starkware.cairo.lang.builtins.builtin_runner_test_utils import PRIME, compile_and_run 4 | from starkware.cairo.lang.vm.vm_exceptions import VmException 5 | 6 | 7 | def test_validation_rules(): 8 | CODE_FORMAT = """ 9 | %builtins range_check 10 | 11 | func main(range_check_ptr: felt) -> (range_check_ptr: felt) {{ 12 | assert [range_check_ptr] = {value}; 13 | return (range_check_ptr=range_check_ptr + 1); 14 | }} 15 | """ 16 | 17 | # Test valid values. 18 | compile_and_run(CODE_FORMAT.format(value=0)) 19 | compile_and_run(CODE_FORMAT.format(value=1)) 20 | 21 | with pytest.raises( 22 | VmException, 23 | match=f"Value {PRIME - 1}, in range check builtin 0, is out of range " 24 | r"\[0, {bound}\)".format(bound=2**128), 25 | ): 26 | compile_and_run(CODE_FORMAT.format(value=-1)) 27 | 28 | with pytest.raises( 29 | VmException, 30 | match=f"Range-check builtin: Expected value at address 2:0 to be an integer. Got: 2:0", 31 | ): 32 | compile_and_run(CODE_FORMAT.format(value="range_check_ptr")) 33 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/signature/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "pytest_test") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files([ 6 | "instance_def.py", 7 | "signature_builtin_runner.py", 8 | ]) 9 | 10 | pytest_test( 11 | name = "cairo_run_builtins_signature_test", 12 | srcs = [ 13 | "signature_builtin_runner_test.py", 14 | ], 15 | visibility = ["//visibility:public"], 16 | deps = [ 17 | "//src/starkware/cairo/lang/builtins:cairo_run_builtins_test_utils_lib", 18 | "//src/starkware/cairo/lang/vm:cairo_vm_lib", 19 | "//src/starkware/python:starkware_python_test_utils_lib", 20 | ], 21 | ) 22 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/signature/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/builtins/signature/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/builtins/signature/instance_def.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | 3 | from starkware.cairo.lang.builtins.instance_def import BuiltinInstanceDef 4 | 5 | # Each signature consists of 2 cells (a public key and a message). 6 | CELLS_PER_SIGNATURE = INPUT_CELLS_PER_SIGNATURE = 2 7 | 8 | 9 | @dataclasses.dataclass 10 | class EcdsaInstanceDef(BuiltinInstanceDef): 11 | # Split to this many different components - for optimization. 12 | repetitions: int 13 | 14 | # Size of hash. 15 | height: int 16 | n_hash_bits: int 17 | 18 | @property 19 | def memory_cells_per_instance(self) -> int: 20 | return CELLS_PER_SIGNATURE 21 | 22 | @property 23 | def range_check_units_per_builtin(self) -> int: 24 | return 0 25 | 26 | @property 27 | def invocation_height(self) -> int: 28 | return 2 * self.height 29 | 30 | def get_diluted_units_per_builtin(self, diluted_spacing: int, diluted_n_bits: int) -> int: 31 | return 0 32 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/cairo_constants.py: -------------------------------------------------------------------------------- 1 | DEFAULT_PRIME = 2**251 + 17 * 2**192 + 1 2 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/compiler/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/ast/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "pytest_test") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files(glob(["*.py"])) 6 | 7 | pytest_test( 8 | name = "cairo_compile_formatting_test", 9 | srcs = [ 10 | "parentheses_expr_wrapper_test.py", 11 | "particle_test.py", 12 | ], 13 | visibility = ["//visibility:public"], 14 | deps = [ 15 | "//src/starkware/cairo/lang/compiler:cairo_compile_lib", 16 | "//src/starkware/cairo/lang/compiler:cairo_compile_test_utils_lib", 17 | ], 18 | ) 19 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/ast/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/compiler/ast/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/ast/aliased_identifier.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | from typing import Optional, Sequence 3 | 4 | from starkware.cairo.lang.compiler.ast.expr import ExprIdentifier 5 | from starkware.cairo.lang.compiler.ast.formatting_utils import LocationField 6 | from starkware.cairo.lang.compiler.ast.node import AstNode 7 | from starkware.cairo.lang.compiler.error_handling import Location 8 | 9 | 10 | @dataclasses.dataclass 11 | class AliasedIdentifier(AstNode): 12 | orig_identifier: ExprIdentifier 13 | local_name: Optional[ExprIdentifier] 14 | location: Optional[Location] = LocationField 15 | 16 | def format(self): 17 | return f"{self.orig_identifier.format()}" + ( 18 | f" as {self.local_name.format()}" if self.local_name else "" 19 | ) 20 | 21 | @property 22 | def identifier(self): 23 | return self.local_name if self.local_name is not None else self.orig_identifier 24 | 25 | def get_children(self) -> Sequence[Optional[AstNode]]: 26 | return [self.orig_identifier, self.local_name] 27 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/ast/expr_func_call.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | from typing import Optional, Sequence 3 | 4 | from starkware.cairo.lang.compiler.ast.expr import Expression 5 | from starkware.cairo.lang.compiler.ast.formatting_utils import LocationField 6 | from starkware.cairo.lang.compiler.ast.node import AstNode 7 | from starkware.cairo.lang.compiler.ast.particle import ParticleList 8 | from starkware.cairo.lang.compiler.ast.rvalue import RvalueFuncCall 9 | from starkware.cairo.lang.compiler.error_handling import Location 10 | from starkware.python.expression_string import ExpressionString, OperatorPrecedence 11 | 12 | 13 | @dataclasses.dataclass 14 | class ExprFuncCall(Expression): 15 | """ 16 | Represents an expression of the form "()". For example, "foo(1, 2, z=3)". 17 | """ 18 | 19 | rvalue: RvalueFuncCall 20 | location: Optional[Location] = LocationField 21 | 22 | def to_expr_str(self): 23 | return ExpressionString.highest(self.rvalue.format_for_expr()) 24 | 25 | def get_particles(self) -> ParticleList: 26 | return self.rvalue.get_particles() 27 | 28 | def get_outmost_operator_precedence(self) -> OperatorPrecedence: 29 | return OperatorPrecedence.HIGHEST 30 | 31 | def get_children(self) -> Sequence[Optional[AstNode]]: 32 | return [self.rvalue] 33 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/ast/module.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | from typing import Optional, Sequence 3 | 4 | from starkware.cairo.lang.compiler.ast.code_elements import CodeBlock 5 | from starkware.cairo.lang.compiler.ast.formatting_utils import get_max_line_length 6 | from starkware.cairo.lang.compiler.ast.node import AstNode 7 | from starkware.cairo.lang.compiler.scoped_name import ScopedName 8 | 9 | 10 | @dataclasses.dataclass 11 | class CairoFile(AstNode): 12 | code_block: CodeBlock 13 | 14 | def format(self, allowed_line_length=None): 15 | if allowed_line_length is None: 16 | allowed_line_length = get_max_line_length() 17 | return self.code_block.format(allowed_line_length=allowed_line_length) 18 | 19 | def get_children(self) -> Sequence[Optional[AstNode]]: 20 | return [self.code_block] 21 | 22 | 23 | @dataclasses.dataclass 24 | class CairoModule(AstNode): 25 | cairo_file: CairoFile 26 | module_name: ScopedName 27 | 28 | def format(self, allowed_line_length=None): 29 | if allowed_line_length is None: 30 | allowed_line_length = get_max_line_length() 31 | return self.cairo_file.format(allowed_line_length=allowed_line_length) 32 | 33 | def get_children(self) -> Sequence[Optional[AstNode]]: 34 | return [self.cairo_file] 35 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/ast/node.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | from typing import Iterator, Optional, Sequence 3 | 4 | 5 | class AstNode(ABC): 6 | @abstractmethod 7 | def get_children(self) -> Sequence[Optional["AstNode"]]: 8 | """ 9 | Returns a list of the node's children (notes are not included). 10 | """ 11 | 12 | def get_subtree(self) -> Iterator["AstNode"]: 13 | """ 14 | Returns an iterator of all non-None nodes in the subtree rooted at this node, preorder 15 | (visit each node before its children). 16 | """ 17 | yield self 18 | for child in filter(None, self.get_children()): 19 | yield from child.get_subtree() 20 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | # Instruct pytest to print full information (e.g., the values on both sides of the equality) 4 | # about asserts that failed in the module below. 5 | # Normally, pytest prints full information only for test files (according to their name). 6 | pytest.register_assert_rewrite("starkware.cairo.lang.compiler.parser_test_utils") 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/constants.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.compiler.scoped_name import ScopedName 2 | 3 | LIBS_DIR_ENVVAR = "CAIRO_PATH" 4 | MAIN_SCOPE = ScopedName.from_string("__main__") 5 | START_FILE_NAME = "" 6 | SIZE_CONSTANT = ScopedName.from_string("SIZE") 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/expression_evaluator_test.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.compiler.expression_evaluator import ExpressionEvaluator 2 | from starkware.cairo.lang.compiler.parser import parse_expr 3 | 4 | 5 | def test_eval_registers(): 6 | ap = 5 7 | fp = 10 8 | prime = 13 9 | 10 | evaluator = ExpressionEvaluator[int](prime=prime, ap=ap, fp=fp, memory={}) 11 | assert evaluator.eval(parse_expr("2 * ap + 3 * fp - 5")) == (2 * ap + 3 * fp - 5) % prime 12 | 13 | 14 | def test_eval_with_types(): 15 | ap = 5 16 | fp = 10 17 | prime = 13 18 | 19 | evaluator = ExpressionEvaluator[int](prime=prime, ap=ap, fp=fp, memory={}) 20 | assert evaluator.eval(parse_expr("cast(ap, T*)")) == ap 21 | 22 | 23 | def test_eval_registers_and_memory(): 24 | ap = 5 25 | fp = 10 26 | prime = 13 27 | memory = {(2 * ap + 3 * fp - 5) % prime: 7, 7: 5, 6: 0} 28 | 29 | evaluator = ExpressionEvaluator[int](prime=prime, ap=ap, fp=fp, memory=memory) 30 | assert evaluator.eval(parse_expr("[2 * ap + 3 * fp - 5]")) == 7 31 | assert ( 32 | evaluator.eval(parse_expr("[[2 * ap + 3 * fp - 5]] + 3 * ap")) 33 | == (memory[7] + 3 * ap) % prime 34 | ) 35 | assert evaluator.eval(parse_expr("[[[2 * ap + 3 * fp - 5]]+1]")) == 0 36 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/identifier_definition_test.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.compiler.ast.cairo_types import TypeFelt 2 | from starkware.cairo.lang.compiler.identifier_definition import ( 3 | IdentifierDefinitionSchema, 4 | MemberDefinition, 5 | StructDefinition, 6 | ) 7 | from starkware.cairo.lang.compiler.scoped_name import ScopedName 8 | 9 | scope = ScopedName.from_string 10 | 11 | 12 | def test_struct_sorting(): 13 | orig = StructDefinition( 14 | full_name=ScopedName.from_string("T"), 15 | members={ 16 | "b": MemberDefinition(offset=1, cairo_type=TypeFelt()), 17 | "a": MemberDefinition(offset=0, cairo_type=TypeFelt()), 18 | }, 19 | size=2, 20 | ) 21 | members = orig.members 22 | 23 | assert list(members.items()) != sorted( 24 | members.items(), key=lambda key_value: key_value[1].offset 25 | ) 26 | 27 | schema = IdentifierDefinitionSchema() 28 | loaded = schema.load(schema.dump(orig)) 29 | members = loaded.members 30 | assert list(members.items()) == sorted( 31 | members.items(), key=lambda key_value: key_value[1].offset 32 | ) 33 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/identifier_manager_field_test.py: -------------------------------------------------------------------------------- 1 | from dataclasses import field 2 | 3 | import marshmallow_dataclass 4 | 5 | from starkware.cairo.lang.compiler.identifier_definition import LabelDefinition 6 | from starkware.cairo.lang.compiler.identifier_manager import IdentifierManager 7 | from starkware.cairo.lang.compiler.identifier_manager_field import IdentifierManagerField 8 | from starkware.cairo.lang.compiler.scoped_name import ScopedName 9 | from starkware.starkware_utils.marshmallow_dataclass_fields import additional_metadata 10 | 11 | scope = ScopedName.from_string 12 | 13 | 14 | def test_identifier_manager_field_serialization(): 15 | @marshmallow_dataclass.dataclass 16 | class Foo: 17 | identifiers: IdentifierManager = field( 18 | metadata=additional_metadata(marshmallow_field=IdentifierManagerField()) 19 | ) 20 | 21 | Schema = marshmallow_dataclass.class_schema(Foo) 22 | 23 | foo = Foo( 24 | identifiers=IdentifierManager.from_dict( 25 | { 26 | scope("aa.b"): LabelDefinition(pc=1000), 27 | } 28 | ) 29 | ) 30 | serialized = Schema().dump(foo) 31 | assert serialized == {"identifiers": {"aa.b": {"pc": 1000, "type": "label"}}} 32 | 33 | assert Schema().load(serialized) == foo 34 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/instruction_test.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | import pytest 4 | 5 | from starkware.cairo.lang.compiler.instruction import ( 6 | N_FLAGS, 7 | OFFSET_BITS, 8 | decode_instruction_values, 9 | ) 10 | 11 | 12 | def test_decode(): 13 | offsets = [randrange(0, 2**OFFSET_BITS) for _ in range(3)] 14 | flags = randrange(0, 2**N_FLAGS) 15 | instruction = 0 16 | for part in [flags] + offsets[::-1]: 17 | instruction = (instruction << OFFSET_BITS) | part 18 | assert [flags] + offsets == list(decode_instruction_values(instruction)) 19 | 20 | 21 | def test_unsupported_instruction(): 22 | with pytest.raises(AssertionError, match="Unsupported instruction: 0x8000000000000000."): 23 | decode_instruction_values(1 << (3 * OFFSET_BITS + N_FLAGS)) 24 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/lib/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(["registers.cairo"]) 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/lib/registers.cairo: -------------------------------------------------------------------------------- 1 | // Returns the contents of the fp and pc registers of the calling function. 2 | // The pc register's value is the address of the instruction that follows directly after the 3 | // invocation of get_fp_and_pc(). 4 | func get_fp_and_pc() -> (fp_val: felt*, pc_val: felt*) { 5 | // The call instruction itself already places the old fp and the return pc at 6 | // [ap - 2], [ap - 1]. 7 | return (fp_val=cast([ap - 2], felt*), pc_val=cast([ap - 1], felt*)); 8 | } 9 | 10 | // Returns the content of the ap register just before this function was invoked. 11 | @known_ap_change 12 | func get_ap() -> (ap_val: felt*) { 13 | // Once get_ap() is invoked, fp points to ap + 2 (since the call instruction placed the old fp 14 | // and pc in memory, advancing ap accordingly). 15 | // Hence, the desired ap value is fp - 2. 16 | let (fp_val, pc_val) = get_fp_and_pc(); 17 | return (ap_val=fp_val - 2); 18 | } 19 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/location_utils.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from starkware.cairo.lang.compiler.ast.expr import Expression 4 | from starkware.cairo.lang.compiler.error_handling import Location 5 | from starkware.cairo.lang.compiler.expression_transformer import ExpressionTransformer 6 | 7 | 8 | def add_parent_location( 9 | expr: Expression, new_parent_location: Optional[Location], message: str 10 | ) -> Expression: 11 | if new_parent_location is None: 12 | return expr 13 | 14 | class AddParentLocationTransformer(ExpressionTransformer): 15 | def location_modifier(self, location: Optional[Location]) -> Optional[Location]: 16 | if location is None: 17 | return new_parent_location 18 | return location.with_parent_location( 19 | new_parent_location=new_parent_location, message=message # type: ignore 20 | ) 21 | 22 | return AddParentLocationTransformer().visit(expr) 23 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/module_reader_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from starkware.cairo.lang.compiler.module_reader import ModuleNotFoundException, ModuleReader 4 | 5 | 6 | def test_file_path_extractor(): 7 | isfile = lambda _: True 8 | reader = ModuleReader(paths=["/usr/include"], cairo_suffix=".f~o") 9 | assert reader.module_to_file_path("foo.bar", isfile) == "/usr/include/foo/bar.f~o" 10 | 11 | reader = ModuleReader(paths=["rel//path"], cairo_suffix=".txt") 12 | assert reader.module_to_file_path("hello.world", isfile) == "rel//path/hello/world.txt" 13 | 14 | 15 | def test_search_file(): 16 | reader = ModuleReader(paths=["a", "b", "c"], cairo_suffix=".c") 17 | assert reader.module_to_file_path("f", isfile=lambda x: x in ["b/f.c", "c/f.c"]) == "b/f.c" 18 | 19 | with pytest.raises( 20 | ModuleNotFoundException, 21 | match="""\ 22 | Could not find module 'x.y.z'. Searched in the following paths: 23 | a/x/y/z.c 24 | b/x/y/z.c 25 | c/x/y/z.c""", 26 | ): 27 | reader.module_to_file_path("x.y.z", isfile=lambda _: False) 28 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/parser_test_utils.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | import pytest 4 | 5 | from starkware.cairo.lang.compiler.parser import ParserError, parse_file 6 | 7 | 8 | def verify_exception(code: str, error: str): 9 | """ 10 | Verifies that parsing the code results in the given error. 11 | """ 12 | with pytest.raises(ParserError) as e: 13 | parse_file(code, "") 14 | # Remove line and column information from the error using a regular expression. 15 | assert re.sub(":[0-9]+:[0-9]+: ", "file:?:?: ", str(e.value)) == error.strip() 16 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/preprocessor/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "pytest_test") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files(glob(["*.py"])) 6 | 7 | pytest_test( 8 | name = "cairo_compile_preprocessor_test", 9 | srcs = [ 10 | "compound_expressions_test.py", 11 | "conftest.py", 12 | "dependency_graph_test.py", 13 | "flow_test.py", 14 | "identifier_aware_visitor_test.py", 15 | "identifier_collector_test.py", 16 | "if_labels_test.py", 17 | "local_variables_test.py", 18 | "memento_test.py", 19 | "preprocessor_test.py", 20 | "reg_tracking_test.py", 21 | "struct_collector_test.py", 22 | ], 23 | visibility = ["//visibility:public"], 24 | deps = [ 25 | "//src/starkware/cairo/lang:cairo_constants_lib", 26 | "//src/starkware/cairo/lang/compiler:cairo_compile_lib", 27 | "//src/starkware/cairo/lang/compiler:cairo_compile_test_utils_lib", 28 | ], 29 | ) 30 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/preprocessor/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/compiler/preprocessor/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/preprocessor/bool_expr/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "pytest_test") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files([ 6 | "__init__.py", 7 | "errors.py", 8 | "lowering.py", 9 | "lowering_test_utils.py", 10 | ]) 11 | 12 | pytest_test( 13 | name = "cairo_compile_preprocessor_bool_expr_test", 14 | srcs = [ 15 | "lowering_test.py", 16 | "lowering_test_utils.py", 17 | ], 18 | visibility = ["//visibility:public"], 19 | deps = [ 20 | "//src/starkware/cairo/lang/compiler:cairo_compile_lib", 21 | "//src/starkware/cairo/lang/compiler:cairo_compile_test_utils_lib", 22 | ], 23 | ) 24 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/preprocessor/bool_expr/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/compiler/preprocessor/bool_expr/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/preprocessor/bool_expr/errors.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.compiler.error_handling import LocationError 2 | 3 | 4 | class BoolExprLoweringError(LocationError): 5 | pass 6 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/preprocessor/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | # Instruct pytest to print full information (e.g., the values on both sides of the equality) 4 | # about asserts that failed in the module below. 5 | # Normally, pytest prints full information only for test files (according to their name). 6 | pytest.register_assert_rewrite("starkware.cairo.lang.compiler.preprocessor.preprocessor_test_utils") 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/preprocessor/identifier_aware_visitor_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from starkware.cairo.lang.compiler.identifier_definition import ConstDefinition 4 | from starkware.cairo.lang.compiler.preprocessor.identifier_aware_visitor import ( 5 | IdentifierAwareVisitor, 6 | ) 7 | from starkware.cairo.lang.compiler.preprocessor.preprocessor_error import PreprocessorError 8 | from starkware.cairo.lang.compiler.scoped_name import ScopedName 9 | 10 | 11 | def test_add_name_definition_no_future(): 12 | visitor = IdentifierAwareVisitor() 13 | 14 | test_id = ScopedName.from_string("test_id") 15 | location = None 16 | 17 | visitor.add_name_definition( 18 | name=test_id, 19 | identifier_definition=ConstDefinition(value=1), 20 | location=location, 21 | require_future_definition=False, 22 | ) 23 | 24 | with pytest.raises(PreprocessorError, match=f"Redefinition of 'test_id'."): 25 | visitor.add_name_definition( 26 | name=test_id, 27 | identifier_definition=ConstDefinition(value=1), 28 | location=location, 29 | require_future_definition=False, 30 | ) 31 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/preprocessor/if_labels_test.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.compiler.preprocessor.preprocessor_test_utils import PRIME, preprocess_str 2 | 3 | 4 | def test_if_labels_are_set(): 5 | program = preprocess_str( 6 | code=""" 7 | namespace B { 8 | func foo(x, y) -> (res: felt) { 9 | if (x == 0) { 10 | if (y == 0) { 11 | return (res=0); 12 | } else { 13 | return (res=1); 14 | } 15 | } else { 16 | if (y == 0) { 17 | return (res=2); 18 | } else { 19 | return (res=3); 20 | } 21 | } 22 | } 23 | } 24 | func main() { 25 | B.foo(1, 2); 26 | ret; 27 | } 28 | """, 29 | prime=PRIME, 30 | ) 31 | assert ( 32 | program.format() 33 | == """\ 34 | jmp rel 10 if [fp + (-4)] != 0; 35 | jmp rel 5 if [fp + (-3)] != 0; 36 | [ap] = 0, ap++; 37 | ret; 38 | [ap] = 1, ap++; 39 | ret; 40 | jmp rel 5 if [fp + (-3)] != 0; 41 | [ap] = 2, ap++; 42 | ret; 43 | [ap] = 3, ap++; 44 | ret; 45 | [ap] = 1, ap++; 46 | [ap] = 2, ap++; 47 | call rel -22; 48 | ret; 49 | """ 50 | ) 51 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/preprocessor/preprocess_codes.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional, Sequence, Tuple 2 | 3 | from starkware.cairo.lang.compiler.identifier_manager import IdentifierManager 4 | from starkware.cairo.lang.compiler.preprocessor.pass_manager import PassManager, PassManagerContext 5 | from starkware.cairo.lang.compiler.preprocessor.preprocessor import PreprocessedProgram 6 | from starkware.cairo.lang.compiler.scoped_name import ScopedName 7 | 8 | 9 | def preprocess_codes( 10 | codes: Sequence[Tuple[str, str]], 11 | pass_manager: PassManager, 12 | main_scope: ScopedName = ScopedName(), 13 | start_codes: Optional[List[Tuple[str, str]]] = None, 14 | ) -> PreprocessedProgram: 15 | """ 16 | Preprocesses a list of Cairo files and returns a PreprocessedProgram instance. 17 | codes is a list of pairs (code_string, file_name). 18 | """ 19 | context = PassManagerContext( 20 | codes=list(codes), 21 | main_scope=main_scope, 22 | identifiers=IdentifierManager(), 23 | start_codes=[] if start_codes is None else start_codes, 24 | ) 25 | 26 | pass_manager.run(context) 27 | 28 | assert context.preprocessed_program is not None 29 | return context.preprocessed_program 30 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/preprocessor/preprocessor_error.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.compiler.error_handling import LocationError 2 | 3 | 4 | class PreprocessorError(LocationError): 5 | pass 6 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/references_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from starkware.cairo.lang.compiler.parser import parse_expr 4 | from starkware.cairo.lang.compiler.preprocessor.reg_tracking import RegTrackingData 5 | from starkware.cairo.lang.compiler.references import FlowTrackingError, Reference 6 | 7 | 8 | def test_eval_reference(): 9 | x = Reference( 10 | pc=0, 11 | value=parse_expr("2 * ap + 3 * fp - 5"), 12 | ap_tracking_data=RegTrackingData(group=1, offset=5), 13 | ) 14 | with pytest.raises(FlowTrackingError): 15 | x.eval(RegTrackingData(group=2, offset=5)) 16 | assert x.eval(RegTrackingData(group=1, offset=8)).format() == "2 * (ap - 3) + 3 * fp - 5" 17 | 18 | 19 | def test_eval_reference_fp_only(): 20 | x = Reference( 21 | pc=0, 22 | value=parse_expr("3 * fp - 5 + fp * fp"), 23 | ap_tracking_data=RegTrackingData(group=1, offset=5), 24 | ) 25 | assert x.eval(RegTrackingData(group=2, offset=7)) == parse_expr("3 * fp - 5 + fp * fp") 26 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/unique_name_provider_test.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.compiler.unique_name_provider import UniqueNameKind, UniqueNameProvider 2 | 3 | 4 | def test_unique_name_provider_next(): 5 | provider = UniqueNameProvider() 6 | assert provider.next(UniqueNameKind.Label) == "$lbl0" 7 | assert provider.next(UniqueNameKind.Var) == "$var1" 8 | assert provider.next(UniqueNameKind.Var) == "$var2" 9 | 10 | 11 | def test_is_name_unique(): 12 | assert UniqueNameProvider.is_name_unique("$lbl1") 13 | assert not UniqueNameProvider.is_name_unique("x") 14 | 15 | # This is an (acceptable) false positive. 16 | assert UniqueNameProvider.is_name_unique("$Hello") 17 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/compiler/vars.bzl: -------------------------------------------------------------------------------- 1 | IS_COMPILER_PYPY = False 2 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/ide/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/ide/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/ide/vim/ftdetect/cairo.vim: -------------------------------------------------------------------------------- 1 | augroup cairoFileType 2 | autocmd BufRead,BufNewFile *.cairo set filetype=cairo 3 | augroup END 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/ide/vim/ftplugin/cairo.vim: -------------------------------------------------------------------------------- 1 | " Show existing tab with 4 spaces width. 2 | setlocal tabstop=4 3 | " When indenting with '>', use 4 spaces width. 4 | setlocal shiftwidth=4 5 | 6 | command -buffer Format !.tox/dev/bin/python cairo-format -i % 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/ide/vim/syntax/cairo.vim: -------------------------------------------------------------------------------- 1 | " Vim syntax file 2 | " 3 | " Language: CAIRO 4 | 5 | if exists("b:current_syntax") 6 | finish 7 | endif 8 | 9 | syntax include @python syntax/python.vim 10 | 11 | let b:current_syntax = "cairo" 12 | 13 | hi def link statement Statement 14 | hi def link register Identifier 15 | hi def link comment Comment 16 | hi def link funcDef Statement 17 | hi def link funcName Function 18 | hi def link num Constant 19 | hi def link specialIdentifier Special 20 | 21 | syn keyword statement call jmp ret abs rel if const let from import static_assert local tempvar 22 | \ felt return assert cast else alloc_locals as with with_attr nondet dw codeoffset new 23 | \ using and 24 | syn keyword register ap fp 25 | syn keyword specialIdentifier SIZEOF_LOCALS SIZE 26 | syn match comment '//[^\n]*\n' 27 | syn keyword funcDef func namespace struct nextgroup=funcName skipwhite 28 | syn match funcName '[a-zA-Z_][a-zA-Z0-9_]*' display contained 29 | syn match num '[+-]\?\d\+' 30 | syn region cairoHint matchgroup=SpecialComment start="%{" keepend end="%}" contains=@python 31 | syn region pythonLiteral matchgroup=SpecialComment start="%\[" keepend end="%\]" contains=@python 32 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/ide/vscode-cairo/.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /out 3 | /package-lock.json 4 | /*.vsix 5 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/ide/vscode-cairo/README.md: -------------------------------------------------------------------------------- 1 | # CairoZero for Visual Studio Code 2 | 3 | This extension provides support for the older version of Cairo, known as CairoZero. For the new language, install the [Cairo 1.0](https://marketplace.visualstudio.com/items?itemName=starkware.cairo1) extension. 4 | Note that the CairoZero compiler and extension are no longer maintained. This extension should only be used by projects that still rely on CairoZero code. 5 | 6 | ## Installation 7 | 8 | From the directory of this file, run: 9 | ``` 10 | sudo npm install -g vsce 11 | npm install 12 | vsce package 13 | code --install-extension cairo*.vsix 14 | ``` 15 | 16 | ## Configuration 17 | 18 | If you have `cairo-format` installed globally (available in PATH), the value of 19 | `cairo.cairoFormatPath` should be `cairo-format` (the default). 20 | 21 | If you're working inside a StarkWare repository, and want the most up-to-date version, 22 | set the value of `cairo.cairoFormatPath` to 23 | ``` 24 | ${workspaceFolder}/src/starkware/cairo/lang/scripts/cairo-format 25 | ``` 26 | 27 | ## Run the extension (for development) 28 | 29 | 1. Open VSCode in the directory of the extension. 30 | 2. Run: 31 | ``` 32 | npm install 33 | npm run compile 34 | ``` 35 | 3. Reload VSCode. 36 | 4. Press F5. 37 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/ide/vscode-cairo/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/ide/vscode-cairo/icon.png -------------------------------------------------------------------------------- /src/starkware/cairo/lang/ide/vscode-cairo/language-configuration.json: -------------------------------------------------------------------------------- 1 | { 2 | "comments": { 3 | // Symbol used for single line comment. 4 | "lineComment": "//", 5 | }, 6 | // Symbols used as brackets. 7 | "brackets": [ 8 | ["[", "]"] 9 | ], 10 | // Symbols that are auto closed when typing. 11 | "autoClosingPairs": [ 12 | ["[", "]"], 13 | ["%{", "%}"] 14 | ], 15 | // Symbols that that can be used to surround a selection. 16 | "surroundingPairs": [ 17 | ["%{", "%}"] 18 | ] 19 | } 20 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/ide/vscode-cairo/snippets.json: -------------------------------------------------------------------------------- 1 | { 2 | "Storage variable": { 3 | "prefix": [ 4 | "@storage_var" 5 | ], 6 | "body": [ 7 | "@storage_var", 8 | "func ${1:name}() -> (${2:res: felt}) {", 9 | "}", 10 | "$0" 11 | ], 12 | "description": "A StarkNet storage variable." 13 | }, 14 | "External function": { 15 | "prefix": [ 16 | "@external" 17 | ], 18 | "body": [ 19 | "@external", 20 | "func ${1:name}{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr}(", 21 | "\t${2:arguments}", 22 | ") {", 23 | "\t$0", 24 | "}" 25 | ], 26 | "description": "A StarkNet contract external function." 27 | }, 28 | "StarkNet contract interface": { 29 | "prefix": [ 30 | "@contract_interface" 31 | ], 32 | "body": [ 33 | "@contract_interface", 34 | "namespace ${1:name} {", 35 | "\t$0", 36 | "}" 37 | ], 38 | "description": "A contract interface for another contract." 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/ide/vscode-cairo/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "outDir": "out", 6 | "lib": [ 7 | "es6" 8 | ], 9 | "sourceMap": true, 10 | "rootDir": "src", 11 | // Enable all strict type-checking options. 12 | "strict": true, 13 | // Additional checks. 14 | "noUnusedLocals": true, 15 | "noImplicitReturns": true, 16 | "noFallthroughCasesInSwitch": true, 17 | "noUnusedParameters": false 18 | }, 19 | "exclude": [ 20 | "node_modules", 21 | ".vscode-test" 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/migrators/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:python.bzl", "py_exe", "pytest_test") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | py_library( 6 | name = "cairo_migrator_lib", 7 | srcs = [ 8 | "migrator.py", 9 | ], 10 | data = [ 11 | "migrator_grammar.ebnf", 12 | ], 13 | visibility = ["//visibility:public"], 14 | deps = [ 15 | "//src/starkware/cairo/lang/compiler:cairo_compile_lib", 16 | ], 17 | ) 18 | 19 | pytest_test( 20 | name = "cairo_migrator_test", 21 | srcs = [ 22 | "migrator_test.py", 23 | ], 24 | visibility = ["//visibility:public"], 25 | deps = [ 26 | "cairo_migrator_lib", 27 | "//src/starkware/cairo/lang/compiler:cairo_compile_lib", 28 | ], 29 | ) 30 | 31 | py_exe( 32 | name = "cairo_migrator", 33 | module = "starkware.cairo.lang.migrators.migrator", 34 | deps = [ 35 | "cairo_migrator_lib", 36 | ], 37 | ) 38 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/migrators/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/migrators/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/package_test/main.cairo: -------------------------------------------------------------------------------- 1 | %builtins output pedersen 2 | 3 | from starkware.cairo.common.cairo_builtins import HashBuiltin 4 | from starkware.cairo.common.hash import hash2 5 | from starkware.cairo.common.serialize import serialize_word 6 | 7 | func main{output_ptr: felt*, pedersen_ptr: HashBuiltin*}() { 8 | let (hash) = hash2{hash_ptr=pedersen_ptr}(1, 2); 9 | serialize_word(hash); 10 | return (); 11 | } 12 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/scripts/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | py_library( 4 | name = "cairo_script_lib", 5 | srcs = [ 6 | ], 7 | data = [ 8 | "cairo-compile", 9 | "cairo-format", 10 | "cairo-hash-program", 11 | "cairo-migrate", 12 | "cairo-reconstruct-traceback", 13 | "cairo-run", 14 | "cairo-sharp", 15 | ], 16 | visibility = ["//visibility:public"], 17 | deps = [ 18 | "//src/starkware/cairo/bootloaders:cairo_hash_program_lib", 19 | "//src/starkware/cairo/lang/compiler:cairo_compile_lib", 20 | "//src/starkware/cairo/lang/migrators:cairo_migrator_lib", 21 | "//src/starkware/cairo/lang/vm:cairo_run_lib", 22 | "//src/starkware/cairo/lang/vm:cairo_vm_utils_lib", 23 | "//src/starkware/cairo/sharp:sharp_client_lib", 24 | ], 25 | ) 26 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/scripts/cairo-compile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../../..")) 7 | from starkware.cairo.lang.compiler.cairo_compile import main # noqa 8 | 9 | if __name__ == "__main__": 10 | sys.exit(main()) 11 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/scripts/cairo-format: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3.9 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../../..")) 7 | from starkware.cairo.lang.compiler.cairo_format import main # noqa 8 | 9 | if __name__ == "__main__": 10 | sys.exit(main()) 11 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/scripts/cairo-hash-program: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../../..")) 7 | from starkware.cairo.bootloaders.hash_program import main # noqa 8 | 9 | if __name__ == "__main__": 10 | sys.exit(main()) 11 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/scripts/cairo-migrate: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../../..")) 7 | from starkware.cairo.lang.migrators.migrator import main # noqa 8 | 9 | if __name__ == "__main__": 10 | sys.exit(main()) 11 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/scripts/cairo-reconstruct-traceback: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../../..")) 7 | from starkware.cairo.lang.vm.reconstruct_traceback import main # noqa 8 | 9 | if __name__ == "__main__": 10 | sys.exit(main()) 11 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/scripts/cairo-run: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../../..")) 7 | from starkware.cairo.lang.vm.cairo_run import main # noqa 8 | 9 | if __name__ == "__main__": 10 | sys.exit(main()) 11 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/scripts/cairo-sharp: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../../..")) 7 | from starkware.cairo.sharp.sharp_client import main # noqa 8 | 9 | if __name__ == "__main__": 10 | sys.exit(main()) 11 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/tracer/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | load("//bazel_utils:python.bzl", "pytest_test") 3 | 4 | package(default_visibility = ["//visibility:public"]) 5 | 6 | py_library( 7 | name = "cairo_tracer_lib", 8 | srcs = [ 9 | "profile.py", 10 | "profiler.py", 11 | "tracer.py", 12 | "tracer_data.py", 13 | "//src/starkware/cairo/lang/tracer/third_party:profile_pb2.py", 14 | ], 15 | data = [ 16 | "favicon.png", 17 | "index.html", 18 | "tracer.css", 19 | "tracer.js", 20 | ], 21 | visibility = ["//visibility:public"], 22 | deps = [ 23 | "//src/starkware/cairo/lang/compiler:cairo_compile_lib", 24 | "//src/starkware/cairo/lang/vm:cairo_vm_lib", 25 | requirement("protobuf"), 26 | ], 27 | ) 28 | 29 | pytest_test( 30 | name = "cairo_tracer_test", 31 | srcs = [ 32 | "tracer_data_test.py", 33 | ], 34 | visibility = ["//visibility:public"], 35 | deps = [ 36 | "cairo_tracer_lib", 37 | "//src/starkware/cairo/lang/vm:cairo_run_lib", 38 | ], 39 | ) 40 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/tracer/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/tracer/favicon.png -------------------------------------------------------------------------------- /src/starkware/cairo/lang/tracer/third_party/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(["profile_pb2.py"]) 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/version.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | __version__ = open(os.path.join(os.path.dirname(__file__), "VERSION")).read().strip() 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/vm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/lang/vm/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/lang/vm/crypto.py: -------------------------------------------------------------------------------- 1 | import contextlib 2 | 3 | from starkware.cairo.common.poseidon_hash import ( # noqa 4 | poseidon_hash, 5 | poseidon_hash_func, 6 | poseidon_hash_many, 7 | poseidon_hash_single, 8 | poseidon_perm, 9 | ) 10 | from starkware.crypto.signature.fast_pedersen_hash import pedersen_hash # noqa 11 | from starkware.crypto.signature.fast_pedersen_hash import pedersen_hash_func # noqa 12 | from starkware.crypto.signature.signature import verify as verify_ecdsa # noqa 13 | 14 | 15 | def get_crypto_lib_context_manager(flavor): 16 | return contextlib.suppress() 17 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/vm/memory_dict_backend.py: -------------------------------------------------------------------------------- 1 | MemoryDictBackend = dict 2 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/vm/test.cairo: -------------------------------------------------------------------------------- 1 | [ap - 1] = [ap - 1]; 2 | [ap - 1] = [ap - 1]; 3 | [ap - 1] = [ap - 1]; 4 | [ap - 1] = [ap - 1]; 5 | [ap - 1] = [ap - 1]; 6 | 7 | label0: 8 | [ap - 1] = [ap - 1]; 9 | 10 | label1: 11 | [ap - 1] = [ap - 1]; 12 | 13 | label2: 14 | [ap - 1] = [ap - 1]; 15 | 16 | __end__: 17 | jmp rel 0; 18 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/vm/test_utils.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.compiler.program import Program 2 | from starkware.cairo.lang.vm.memory_dict import MemoryDict 3 | from starkware.cairo.lang.vm.relocatable import MaybeRelocatableDict, RelocatableValue 4 | from starkware.cairo.lang.vm.vm import RunContext, VirtualMachine 5 | 6 | PRIME = 2**64 + 13 7 | 8 | 9 | def run_program_in_vm( 10 | program: Program, 11 | steps: int, 12 | *, 13 | pc=RelocatableValue(0, 10), 14 | ap=100, 15 | fp=100, 16 | extra_mem={}, 17 | prime=PRIME, 18 | ): 19 | # Set memory[fp - 1] to an arbitrary value, since [fp - 1] is assumed to be set. 20 | memory: MaybeRelocatableDict = { 21 | **{pc + i: v for i, v in enumerate(program.data)}, 22 | fp - 1: 1234, 23 | **extra_mem, 24 | } 25 | context = RunContext( 26 | pc=pc, 27 | ap=ap, 28 | fp=fp, 29 | memory=MemoryDict(memory), 30 | prime=prime, 31 | ) 32 | 33 | vm = VirtualMachine(program, context, {}) 34 | for _ in range(steps): 35 | vm.step() 36 | return vm 37 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/vm/trace_entry_test.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.vm.trace_entry import TraceEntry 2 | 3 | 4 | def test_trace_entry_serialization(): 5 | # Test serialization of a TraceEntry (values taken from the instruction 6 | # "[ap] = [ap - 1] + 2, ap++;"). 7 | entry = TraceEntry(ap=0x66, fp=0x64, pc=0xA) 8 | serialized = entry.serialize() 9 | assert len(serialized) == TraceEntry.serialization_size() 10 | assert ( 11 | serialized.hex() 12 | == """ 13 | 66 00 00 00 00 00 00 00 14 | 64 00 00 00 00 00 00 00 15 | 0a 00 00 00 00 00 00 00 16 | """.replace( 17 | " ", "" 18 | ).replace( 19 | "\n", "" 20 | ) 21 | ) 22 | 23 | # Test deserialization. 24 | assert TraceEntry.deserialize(serialized).serialize() == serialized 25 | -------------------------------------------------------------------------------- /src/starkware/cairo/lang/vm/vm.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.lang.vm.virtual_machine_base import get_perm_range_check_limits # noqa 2 | from starkware.cairo.lang.vm.vm_core import RunContext, VirtualMachine # noqa 3 | -------------------------------------------------------------------------------- /src/starkware/cairo/sharp/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "url": "https://testnet.provingservice.io/", 3 | "verifier_address": "0x07ec0D28e50322Eb0C159B9090ecF3aeA8346DFe", 4 | "steps_limit": 1000000 5 | } 6 | -------------------------------------------------------------------------------- /src/starkware/cairo/sharp/fact_checker_test.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.sharp.fact_checker import FactChecker 2 | 3 | 4 | def test_init(): 5 | """ 6 | Initializes the FactChecker. 7 | This test is a basic sanity check. 8 | """ 9 | FactChecker(fact_registry_address="", node_rpc_url="") 10 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/stark_verifier/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/stark_verifier/air/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/config_instances.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.stark_verifier.core.table_commitment import TableCommitmentConfig 2 | 3 | const MAX_N_COLUMNS = 128; 4 | 5 | // Configuration for the Traces component. 6 | struct TracesConfig { 7 | original: TableCommitmentConfig*, 8 | interaction: TableCommitmentConfig*, 9 | } 10 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/example_expected.json: -------------------------------------------------------------------------------- 1 | { 2 | "public_input_test": { 3 | "initial_hash_chain_seed": "0x061cfc784cb110654555232311f164478b4a29e5266897e2b20c22448958a687" 4 | }, 5 | "dynamic_layout_public_input_test": { 6 | "initial_hash_chain_seed": "0x0000fd8ef6333532160fcee791217d95f99e3d97bd1507104396f8683b2e6b2b" 7 | }, 8 | "diluted_test": { 9 | "spacing": 4, 10 | "n_bits": 16, 11 | "z": "0x12345678", 12 | "alpha": "0x87654321", 13 | "res": "0x3f070f6a2364e6900cc19fa78f05596c776f474786d6769a7b91410352ba644" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layout.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.stark_verifier.core.air_interface import AirInstance 2 | 3 | struct Layout { 4 | // Virtual functions. 5 | // Each should be a pointer to a function with the same interface as the function in this file. 6 | eval_oods_polynomial: felt*, 7 | // Constants. 8 | n_original_columns: felt, 9 | n_interaction_columns: felt, 10 | n_interaction_elements: felt, 11 | } 12 | 13 | struct DynamicLayout { 14 | layout: Layout, 15 | // A struct of felts (defined in autogenerated.cairo) containing all parameters of the dynamic 16 | // layout. Here represented as an array. 17 | dynamic_params: felt*, 18 | } 19 | 20 | struct AirWithLayout { 21 | air: AirInstance, 22 | layout: Layout, 23 | } 24 | 25 | struct AirWithDynamicLayout { 26 | air: AirInstance, 27 | layout: DynamicLayout, 28 | } 29 | 30 | func eval_oods_polynomial{range_check_ptr}( 31 | layout: Layout*, 32 | column_values: felt*, 33 | oods_values: felt*, 34 | constraint_coefficients: felt*, 35 | point: felt, 36 | oods_point: felt, 37 | trace_generator: felt, 38 | ) -> (res: felt) { 39 | jmp abs layout.eval_oods_polynomial; 40 | } 41 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layouts/BUILD: -------------------------------------------------------------------------------- 1 | load(":layouts_gen.bzl", "generate_layouts_libs") 2 | 3 | layouts = [ 4 | "all_cairo", 5 | "dex", 6 | "dynamic", 7 | "recursive", 8 | "small", 9 | "starknet", 10 | "starknet_with_keccak", 11 | "recursive_with_poseidon", 12 | ] 13 | 14 | generate_layouts_libs(layouts) 15 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layouts/all_cairo/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(glob(["*.cairo"])) 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layouts/dex/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(glob(["*.cairo"])) 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layouts/dynamic/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(glob(["*.cairo"])) 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layouts/layouts_gen.bzl: -------------------------------------------------------------------------------- 1 | def generate_layouts_libs(layouts): 2 | for layout in layouts: 3 | native.py_library( 4 | name = "starkware_cairo_stark_verifier_air_{}_lib".format(layout), 5 | srcs = [ 6 | ], 7 | data = [ 8 | "//src/starkware/cairo/stark_verifier/air/layouts/{}:autogenerated.cairo".format(layout), 9 | "//src/starkware/cairo/stark_verifier/air/layouts/{}:composition.cairo".format(layout), 10 | "//src/starkware/cairo/stark_verifier/air/layouts/{}:global_values.cairo".format(layout), 11 | "//src/starkware/cairo/stark_verifier/air/layouts/{}:periodic_columns.cairo".format(layout), 12 | "//src/starkware/cairo/stark_verifier/air/layouts/{}:public_verify.cairo".format(layout), 13 | "//src/starkware/cairo/stark_verifier/air/layouts/{}:verify.cairo".format(layout), 14 | "//src/starkware/cairo/stark_verifier/core:stark", 15 | ], 16 | tags = [ 17 | "external_cairo", 18 | "external_cairo-docs", 19 | ], 20 | visibility = ["//visibility:public"], 21 | ) 22 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layouts/recursive/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(glob(["*.cairo"])) 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layouts/recursive_with_poseidon/BUILD: -------------------------------------------------------------------------------- 1 | load("//src/starkware/cairo/lang:cairo_rules.bzl", "cairo_library") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files(glob(["*.cairo"])) 6 | 7 | cairo_library( 8 | name = "recursive_with_poseidon", 9 | srcs = [ 10 | "autogenerated.cairo", 11 | "composition.cairo", 12 | "global_values.cairo", 13 | "periodic_columns.cairo", 14 | "public_verify.cairo", 15 | "verify.cairo", 16 | ], 17 | visibility = ["//visibility:public"], 18 | deps = [ 19 | "//src/starkware/cairo/common:cairo_common_cairo_lib", 20 | "//src/starkware/cairo/stark_verifier/air:cairo", 21 | "//src/starkware/cairo/stark_verifier/core:stark", 22 | ], 23 | ) 24 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layouts/small/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(glob(["*.cairo"])) 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layouts/starknet/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(glob(["*.cairo"])) 4 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/layouts/starknet_with_keccak/BUILD: -------------------------------------------------------------------------------- 1 | load("//src/starkware/cairo/lang:cairo_rules.bzl", "cairo_library") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | exports_files(glob(["*.cairo"])) 6 | 7 | cairo_library( 8 | name = "starknet_with_keccak", 9 | srcs = [ 10 | "autogenerated.cairo", 11 | "composition.cairo", 12 | "global_values.cairo", 13 | "periodic_columns.cairo", 14 | "public_verify.cairo", 15 | "verify.cairo", 16 | ], 17 | visibility = ["//visibility:public"], 18 | deps = [ 19 | "//src/starkware/cairo/common:cairo_common_cairo_lib", 20 | "//src/starkware/cairo/stark_verifier/air:cairo", 21 | "//src/starkware/cairo/stark_verifier/core:stark", 22 | ], 23 | ) 24 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/params.cairo: -------------------------------------------------------------------------------- 1 | const CONSTRAINT_DEGREE = 2; 2 | const N_COMPOSITION_COLUMNS = CONSTRAINT_DEGREE; 3 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/air/stark_test.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.stark_verifier.air.stark_test_utils import PROOF_FILE, run_test 2 | 3 | 4 | def test_stark(): 5 | run_test(proof_file=PROOF_FILE, layout="starknet_with_keccak") 6 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/core/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/stark_verifier/core/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/core/air_instances.cairo: -------------------------------------------------------------------------------- 1 | struct PublicInput { 2 | } 3 | 4 | struct TracesConfig { 5 | } 6 | 7 | struct TracesUnsentCommitment { 8 | } 9 | 10 | struct TracesCommitment { 11 | } 12 | 13 | struct TracesDecommitment { 14 | } 15 | 16 | struct TracesWitness { 17 | } 18 | 19 | struct OodsEvaluationInfo { 20 | oods_values: felt*, 21 | oods_point: felt, 22 | trace_generator: felt, 23 | constraint_coefficients: felt*, 24 | } 25 | 26 | struct AirInstance { 27 | // Virtual functions. 28 | // Each should be a pointer to a function with the same interface as the function in this file. 29 | public_input_hash: felt*, 30 | public_input_validate: felt*, 31 | traces_config_validate: felt*, 32 | traces_commit: felt*, 33 | traces_decommit: felt*, 34 | traces_eval_composition_polynomial: felt*, 35 | eval_oods_boundary_poly_at_points: felt*, 36 | // Constants. 37 | n_dynamic_params: felt, 38 | n_constraints: felt, 39 | constraint_degree: felt, 40 | mask_size: felt, 41 | } 42 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/core/config_instances.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.stark_verifier.air.config_instances import TracesConfig 2 | from starkware.cairo.stark_verifier.core.fri.config import FriConfig 3 | from starkware.cairo.stark_verifier.core.proof_of_work import ProofOfWorkConfig 4 | from starkware.cairo.stark_verifier.core.table_commitment import TableCommitmentConfig 5 | 6 | const MAX_LOG_TRACE = 64; 7 | const MAX_LOG_BLOWUP_FACTOR = 16; 8 | const MAX_N_QUERIES = 48; 9 | 10 | struct StarkConfig { 11 | traces: TracesConfig*, 12 | composition: TableCommitmentConfig*, 13 | fri: FriConfig*, 14 | proof_of_work: ProofOfWorkConfig*, 15 | 16 | // Log2 of the trace domain size. 17 | log_trace_domain_size: felt, 18 | // Number of queries to the last component, FRI. 19 | n_queries: felt, 20 | // Log2 of the number of cosets composing the evaluation domain, where the coset size is the 21 | // trace length. 22 | log_n_cosets: felt, 23 | // Number of layers that use a verifier friendly hash in each commitment. 24 | n_verifier_friendly_commitment_layers: felt, 25 | } 26 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/core/domains.cairo: -------------------------------------------------------------------------------- 1 | // Information about the domains that are used in the stark proof. 2 | struct StarkDomains { 3 | // Log2 of the evaluation domain size. 4 | log_eval_domain_size: felt, 5 | // The evaluation domain size. 6 | eval_domain_size: felt, 7 | // The generator of the evaluation domain (a primitive root of unity of order eval_domain_size). 8 | eval_generator: felt, 9 | // Log2 of the trace domain size. 10 | log_trace_domain_size: felt, 11 | // The trace domain size. 12 | trace_domain_size: felt, 13 | // The generator of the trace domain (a primitive root of unity of order trace_domain_size). 14 | trace_generator: felt, 15 | } 16 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/core/fri/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/cairo/stark_verifier/core/fri/__init__.py -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/core/serialize_utils.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.common.memcpy import memcpy 2 | from starkware.cairo.common.uint256 import Uint256 3 | 4 | // Appends the given felt to the array pointed by the `data` (implicit) argument. 5 | func append_felt{data: felt*}(elem: felt) { 6 | assert data[0] = elem; 7 | let data = data + 1; 8 | return (); 9 | } 10 | 11 | // Concats the given array of felts to the array pointed by the `data` (implicit) argument. 12 | // Note that the array len is not added to `data`. 13 | func append_felts{data: felt*}(len: felt, arr: felt*) { 14 | memcpy(dst=data, src=arr, len=len); 15 | let data = data + len; 16 | return (); 17 | } 18 | 19 | // Appends the given Uint256 to the array pointed by the `data` (implicit) argument. 20 | func append_uint256{data: felt*}(elem: Uint256) { 21 | assert data[0] = elem.high; 22 | assert data[1] = elem.low; 23 | let data = data + 2; 24 | return (); 25 | } 26 | -------------------------------------------------------------------------------- /src/starkware/cairo/stark_verifier/core/supported_proof_params.py: -------------------------------------------------------------------------------- 1 | def are_parameters_supported(proof_parameters: dict): 2 | """ 3 | The stark verifier implemented in Cairo expects a specific set of hash functions and a 4 | specific field to be used by the prover. Check if proof_parameters match these requirements. 5 | """ 6 | if proof_parameters["channel_hash"] != "poseidon3": 7 | return False 8 | 9 | if proof_parameters["commitment_hash"] != "blake256_masked248_lsb": 10 | return False 11 | 12 | if proof_parameters["field"] != "PrimeField0": 13 | return False 14 | 15 | if proof_parameters["pow_hash"] != "blake256": 16 | return False 17 | 18 | if proof_parameters["statement"]["page_hash"] != "pedersen": 19 | return False 20 | 21 | if proof_parameters["verifier_friendly_commitment_hash"] != "poseidon3": 22 | return False 23 | 24 | return True 25 | -------------------------------------------------------------------------------- /src/starkware/cairo/vars.bzl: -------------------------------------------------------------------------------- 1 | CAIRO_LANG_VENV_ADDITIONAL_LIBS = [] 2 | CAIRO_VM_CRYPTO_ADDITIONAL_LIBS = [] 3 | CAIRO_COMMON_LIB_ADDITIONAL_FILES = [] 4 | CAIRO_COMMON_LIB_ADDITIONAL_LIBS = [] 5 | CAIRO_INSTANCES_LIB_ADDITIONAL_FILES = [] 6 | CAIRO_COMPILER_ARCHIVE = "sierra-compiler-major-1" 7 | -------------------------------------------------------------------------------- /src/starkware/cairo/vars_cairo_compiler.bzl: -------------------------------------------------------------------------------- 1 | CAIRO_COMPILER_ARCHIVE = "sierra-compiler-major-1" 2 | -------------------------------------------------------------------------------- /src/starkware/crypto/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | 3 | py_library( 4 | name = "starkware_crypto_lib", 5 | srcs = [ 6 | "//src/starkware/crypto/signature:fast_pedersen_hash.py", 7 | "//src/starkware/crypto/signature:math_utils.py", 8 | "//src/starkware/crypto/signature:nothing_up_my_sleeve_gen.py", 9 | "//src/starkware/crypto/signature:signature.py", 10 | ], 11 | data = [ 12 | "//src/starkware/crypto/signature:pedersen_params.json", 13 | ], 14 | visibility = ["//visibility:public"], 15 | deps = [ 16 | "//src/starkware/python:starkware_python_utils_lib", 17 | requirement("ecdsa"), 18 | requirement("fastecdsa"), 19 | requirement("mpmath"), 20 | requirement("sympy"), 21 | ], 22 | ) 23 | 24 | package(default_visibility = ["//visibility:public"]) 25 | -------------------------------------------------------------------------------- /src/starkware/crypto/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/crypto/__init__.py -------------------------------------------------------------------------------- /src/starkware/crypto/signature/BUILD: -------------------------------------------------------------------------------- 1 | exports_files(glob([ 2 | "*.json", 3 | "*.py", 4 | ])) 5 | 6 | package(default_visibility = ["//visibility:public"]) 7 | -------------------------------------------------------------------------------- /src/starkware/crypto/signature/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/crypto/signature/__init__.py -------------------------------------------------------------------------------- /src/starkware/eth/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | py_library( 6 | name = "starkware_eth_test_utils_lib", 7 | srcs = [ 8 | "eth_test_utils.py", 9 | ], 10 | data = ["@npm_ganache//ganache/bin:ganache"], 11 | visibility = ["//visibility:public"], 12 | deps = [ 13 | ":web3_wrapper_lib", 14 | requirement("pytest"), 15 | requirement("web3"), 16 | ], 17 | ) 18 | 19 | py_library( 20 | name = "web3_wrapper_lib", 21 | srcs = [ 22 | "web3_wrapper.py", 23 | ], 24 | visibility = ["//visibility:public"], 25 | deps = [requirement("web3")], 26 | ) 27 | -------------------------------------------------------------------------------- /src/starkware/eth/web3_wrapper.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | from web3 import Web3, eth # Noqa. 4 | 5 | web3_api_new_to_old: Dict[str, str] = { 6 | "to_checksum_address": "toChecksumAddress", 7 | "is_checksum_address": "isChecksumAddress", 8 | "is_connected": "isConnected", 9 | "solidity_keccak": "solidityKeccak", 10 | "client_version": "clientVersion", 11 | "toJSON": "to_json", 12 | "toWei": "to_wei", 13 | } 14 | 15 | 16 | def web3_type_fix(): 17 | web3_type_fix_over_version6_generic() 18 | 19 | 20 | def web3_type_fix_over_version6_generic(): 21 | for api in web3_api_new_to_old.keys(): 22 | if not hasattr(Web3, api): 23 | setattr(Web3, api, getattr(Web3, web3_api_new_to_old[api])) 24 | 25 | 26 | def web3_contract_event_fix(event): 27 | if not hasattr(event, "create_filter"): 28 | event.create_filter = event.createFilter 29 | if not hasattr(event, "process_receipt"): 30 | event.process_receipt = event.processReceipt 31 | 32 | 33 | web3_type_fix() 34 | -------------------------------------------------------------------------------- /src/starkware/python/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/python/__init__.py -------------------------------------------------------------------------------- /src/starkware/python/json_rpc/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | load("//bazel_utils:python.bzl", "pytest_test") 3 | 4 | package(default_visibility = ["//visibility:public"]) 5 | 6 | exports_files([ 7 | "client.py", 8 | "common.py", 9 | "server.py", 10 | ]) 11 | 12 | pytest_test( 13 | name = "json_rpc_client_test", 14 | srcs = [ 15 | "client_test.py", 16 | ], 17 | visibility = ["//visibility:public"], 18 | deps = [ 19 | "//src/starkware/python:starkware_expression_string_lib", 20 | "//src/starkware/python:starkware_json_rpc_lib", 21 | "//src/starkware/python:starkware_python_test_utils_lib", 22 | "//src/starkware/python:starkware_python_utils_lib", 23 | requirement("pytest_asyncio"), 24 | ], 25 | ) 26 | -------------------------------------------------------------------------------- /src/starkware/python/json_rpc/client.py: -------------------------------------------------------------------------------- 1 | """ 2 | JSON-RPC client implementation. 3 | """ 4 | 5 | import json 6 | from typing import Any, Dict 7 | 8 | 9 | class JsonRpcMethod: 10 | """ 11 | Represents a JSON-RPC method that can be called to generate a JSON-RPC request. 12 | """ 13 | 14 | def __init__(self, name: str): 15 | self.name = name 16 | 17 | def call(self, *args, **kwargs) -> str: 18 | """ 19 | Returns a JSON-RPC call. 20 | """ 21 | assert len(args) == 0, "JSON-RPC call can only contain named arguments." 22 | 23 | call_dict: Dict[str, Any] = {"jsonrpc": "2.0", "method": self.name, "id": None} 24 | if len(kwargs) != 0: 25 | call_dict["params"] = kwargs 26 | 27 | return json.dumps(call_dict) 28 | 29 | 30 | class JsonRpcEncoder: 31 | """ 32 | Generates JsonRpcMethods. 33 | """ 34 | 35 | def __getattr__(self, name: str) -> JsonRpcMethod: 36 | return JsonRpcMethod(name=name) 37 | -------------------------------------------------------------------------------- /src/starkware/python/json_rpc/client_test.py: -------------------------------------------------------------------------------- 1 | """ 2 | JSON-RPC client test. 3 | """ 4 | 5 | import json 6 | 7 | import pytest 8 | 9 | from starkware.python.json_rpc.client import JsonRpcEncoder 10 | 11 | 12 | def test_json_rpc_encoder(): 13 | """ 14 | Tests the JSON RPC encoder. 15 | """ 16 | encoder = JsonRpcEncoder() 17 | 18 | assert json.loads(encoder.bar.call(x=1, y="abc", z={"a": 3, "b": "c"})) == { 19 | "jsonrpc": "2.0", 20 | "method": "bar", 21 | "params": { 22 | "x": 1, 23 | "y": "abc", 24 | "z": { 25 | "a": 3, 26 | "b": "c", 27 | }, 28 | }, 29 | "id": None, 30 | } 31 | 32 | with pytest.raises(AssertionError, match="JSON-RPC call can only contain named arguments."): 33 | encoder.foo.call(1, 2, x=3) 34 | -------------------------------------------------------------------------------- /src/starkware/python/utils_stub_module.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | from typing import Any, Iterable 3 | 4 | # This file contains functions of utils.py, for which stubs exist in the corresponding *.pyi file. 5 | # It is needed since mypy looks for all definitions in *.pyi files, without falling back to the 6 | # *.py. 7 | 8 | 9 | def safe_zip(*iterables: Iterable[Any]) -> Iterable: 10 | """ 11 | Zips iterables. Makes sure the lengths of all iterables are equal. 12 | """ 13 | sentinel = object() 14 | for combo in itertools.zip_longest(*iterables, fillvalue=sentinel): 15 | assert sentinel not in combo, "Iterables to safe_zip are not equal in length." 16 | yield combo 17 | -------------------------------------------------------------------------------- /src/starkware/solidity/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | py_library( 4 | name = "starkware_contracts_utils_lib", 5 | srcs = [ 6 | "utils.py", 7 | ], 8 | visibility = ["//visibility:public"], 9 | ) 10 | -------------------------------------------------------------------------------- /src/starkware/solidity/components/GovernanceStorage.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity >=0.6.0 <0.9.0; 3 | import {GovernanceInfoStruct} from "starkware/solidity/components/Governance.sol"; 4 | 5 | /* 6 | Holds the governance slots for ALL entities, including proxy and the main contract. 7 | */ 8 | contract GovernanceStorage { 9 | // A map from a Governor tag to its own GovernanceInfoStruct. 10 | mapping(string => GovernanceInfoStruct) internal governanceInfo; //NOLINT uninitialized-state. 11 | } 12 | -------------------------------------------------------------------------------- /src/starkware/solidity/components/GovernedFinalizable.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.8.0; 3 | 4 | import "starkware/solidity/interfaces/MGovernance.sol"; 5 | import "starkware/solidity/libraries/NamedStorage8.sol"; 6 | 7 | /** 8 | A Governor controlled finalizable contract. 9 | The inherited contract (the one that is GovernedFinalizable) implements the Governance. 10 | */ 11 | abstract contract GovernedFinalizable is MGovernance { 12 | event Finalized(); 13 | 14 | string constant STORAGE_TAG = "STARKWARE_CONTRACTS_GOVERENED_FINALIZABLE_1.0_TAG"; 15 | 16 | function isFinalized() public view returns (bool) { 17 | return NamedStorage.getBoolValue(STORAGE_TAG); 18 | } 19 | 20 | modifier notFinalized() { 21 | require(!isFinalized(), "FINALIZED"); 22 | _; 23 | } 24 | 25 | function finalize() external onlyGovernance notFinalized { 26 | NamedStorage.setBoolValue(STORAGE_TAG, true); 27 | emit Finalized(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/starkware/solidity/interfaces/BlockDirectCall.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity >=0.6.0 <0.9.0; 3 | 4 | /* 5 | This contract provides means to block direct call of an external function. 6 | A derived contract (e.g. MainDispatcherBase) should decorate sensitive functions with the 7 | notCalledDirectly modifier, thereby preventing it from being called directly, and allowing only 8 | calling using delegate_call. 9 | */ 10 | abstract contract BlockDirectCall { 11 | address immutable this_; 12 | 13 | constructor() internal { 14 | this_ = address(this); 15 | } 16 | 17 | modifier notCalledDirectly() { 18 | require(this_ != address(this), "DIRECT_CALL_DISALLOWED"); 19 | _; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/starkware/solidity/interfaces/ExternalInitializer.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity >=0.6.0 <0.9.0; 3 | 4 | interface ExternalInitializer { 5 | event LogExternalInitialize(bytes data); 6 | 7 | function initialize(bytes calldata data) external; 8 | } 9 | -------------------------------------------------------------------------------- /src/starkware/solidity/interfaces/IFactRegistry.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity >=0.6.0 <0.9.0; 3 | 4 | /* 5 | The Fact Registry design pattern is a way to separate cryptographic verification from the 6 | business logic of the contract flow. 7 | 8 | A fact registry holds a hash table of verified "facts" which are represented by a hash of claims 9 | that the registry hash check and found valid. This table may be queried by accessing the 10 | isValid() function of the registry with a given hash. 11 | 12 | In addition, each fact registry exposes a registry specific function for submitting new claims 13 | together with their proofs. The information submitted varies from one registry to the other 14 | depending of the type of fact requiring verification. 15 | 16 | For further reading on the Fact Registry design pattern see this 17 | `StarkWare blog post `_. 18 | */ 19 | interface IFactRegistry { 20 | /* 21 | Returns true if the given fact was previously registered in the contract. 22 | */ 23 | function isValid(bytes32 fact) external view returns (bool); 24 | } 25 | -------------------------------------------------------------------------------- /src/starkware/solidity/interfaces/IQueryableFactRegistry.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity >=0.6.0 <0.9.0; 3 | 4 | import "starkware/solidity/interfaces/IFactRegistry.sol"; 5 | 6 | /* 7 | Extends the IFactRegistry interface with a query method that indicates 8 | whether the fact registry has successfully registered any fact or is still empty of such facts. 9 | */ 10 | interface IQueryableFactRegistry is IFactRegistry { 11 | /* 12 | Returns true if at least one fact has been registered. 13 | */ 14 | function hasRegisteredFact() external view returns (bool); 15 | } 16 | -------------------------------------------------------------------------------- /src/starkware/solidity/interfaces/Identity.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity >=0.6.0 <0.9.0; 3 | 4 | interface Identity { 5 | /* 6 | Allows a caller to ensure that the provided address is of the expected type and version. 7 | */ 8 | function identify() external pure returns (string memory); 9 | } 10 | -------------------------------------------------------------------------------- /src/starkware/solidity/interfaces/MGovernance.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity >=0.6.0 <0.9.0; 3 | 4 | abstract contract MGovernance { 5 | function _isGovernor(address user) internal view virtual returns (bool); 6 | 7 | /* 8 | Allows calling the function only by a Governor. 9 | */ 10 | modifier onlyGovernance() { 11 | require(_isGovernor(msg.sender), "ONLY_GOVERNANCE"); 12 | _; 13 | } 14 | 15 | function initGovernance() internal virtual; 16 | } 17 | -------------------------------------------------------------------------------- /src/starkware/solidity/interfaces/MOperator.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity >=0.6.0 <0.9.0; 3 | 4 | import "starkware/solidity/interfaces/MGovernance.sol"; 5 | 6 | abstract contract MOperator { 7 | event LogOperatorAdded(address operator); 8 | event LogOperatorRemoved(address operator); 9 | 10 | function isOperator(address user) public view virtual returns (bool); 11 | 12 | modifier onlyOperator() { 13 | require(isOperator(msg.sender), "ONLY_OPERATOR"); 14 | _; 15 | } 16 | 17 | function registerOperator(address newOperator) external virtual; 18 | 19 | function unregisterOperator(address removedOperator) external virtual; 20 | 21 | function getOperators() internal view virtual returns (mapping(address => bool) storage); 22 | } 23 | -------------------------------------------------------------------------------- /src/starkware/solidity/third_party/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(glob(["*.sol"])) 4 | -------------------------------------------------------------------------------- /src/starkware/solidity/tokens/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:solidity.bzl", "sol_library") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | sol_library( 6 | name = "erc20_sol", 7 | srcs = [ 8 | "//src/starkware/solidity/tokens/ERC20:ERC20.sol", 9 | "//src/starkware/solidity/tokens/ERC20:IERC20.sol", 10 | "//src/starkware/solidity/tokens/ERC20:IERC20Metadata.sol", 11 | ], 12 | deps = [], 13 | ) 14 | 15 | sol_library( 16 | name = "token_interfaces_sol", 17 | srcs = [ 18 | "//src/starkware/solidity/tokens/ERC1155:IERC1155.sol", 19 | "//src/starkware/solidity/tokens/ERC20:IERC20.sol", 20 | "//src/starkware/solidity/tokens/ERC721:IERC721.sol", 21 | ], 22 | deps = [], 23 | ) 24 | -------------------------------------------------------------------------------- /src/starkware/solidity/tokens/ERC1155/BUILD: -------------------------------------------------------------------------------- 1 | exports_files(glob(["*.sol"])) 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | -------------------------------------------------------------------------------- /src/starkware/solidity/tokens/ERC165.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | import "starkware/solidity/tokens/IERC165.sol"; 5 | 6 | /** 7 | Implementation of the {IERC165} interface. 8 | 9 | Contracts may inherit from this and call {registerInterface} to declare 10 | their support of an interface. 11 | */ 12 | abstract contract ERC165 is IERC165 { 13 | /* 14 | INTERFACE_ID_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7. 15 | */ 16 | bytes4 private constant INTERFACE_ID_ERC165 = 0x01ffc9a7; 17 | 18 | mapping(bytes4 => bool) private supportedInterfaces; 19 | 20 | constructor() public { 21 | // Derived contracts need only register support for their own interfaces, 22 | // Support for ERC165 itself here. 23 | registerInterface(INTERFACE_ID_ERC165); 24 | } 25 | 26 | function supportsInterface(bytes4 interfaceId) public view override returns (bool) { 27 | return supportedInterfaces[interfaceId]; 28 | } 29 | 30 | function registerInterface(bytes4 interfaceId) internal { 31 | require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); 32 | supportedInterfaces[interfaceId] = true; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/starkware/solidity/tokens/ERC20/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "ERC20.sol", 5 | "IERC20.sol", 6 | "IERC20Metadata.sol", 7 | ]) 8 | -------------------------------------------------------------------------------- /src/starkware/solidity/tokens/ERC721/BUILD: -------------------------------------------------------------------------------- 1 | exports_files(glob(["*.sol"])) 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | -------------------------------------------------------------------------------- /src/starkware/solidity/tokens/ERC721/IERC721Receiver.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | interface IERC721Receiver { 5 | function onERC721Received( 6 | address operator, 7 | address from, 8 | uint256 tokenId, 9 | bytes calldata data 10 | ) external returns (bytes4); 11 | } 12 | -------------------------------------------------------------------------------- /src/starkware/solidity/tokens/IERC165.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.6.12; 3 | 4 | /** 5 | Interface of the ERC165 standard, as defined in the 6 | https://eips.ethereum.org/EIPS/eip-165[EIP]. 7 | 8 | 9 | */ 10 | interface IERC165 { 11 | function supportsInterface(bytes4 interfaceId) external view returns (bool); 12 | } 13 | -------------------------------------------------------------------------------- /src/starkware/solidity/upgrade/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils:solidity.bzl", "sol_library") 2 | 3 | sol_library( 4 | name = "proxy_storage_sol", 5 | srcs = [ 6 | "ProxyStorage.sol", 7 | ], 8 | visibility = ["//visibility:public"], 9 | deps = [ 10 | "//src/starkware/solidity/components:governance_storage_sol", 11 | ], 12 | ) 13 | -------------------------------------------------------------------------------- /src/starkware/solidity/utils.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | import json 3 | from pathlib import Path 4 | 5 | 6 | def load_nearby_contract(name: str, no_throw=False) -> dict: 7 | """ 8 | Loads a contract json from the directory of the caller module. 9 | """ 10 | frame = inspect.stack()[1] 11 | module = inspect.getmodule(frame[0]) 12 | assert module is not None 13 | filename = module.__file__ 14 | assert filename is not None 15 | try: 16 | path = Path(filename).parent / f"{name}.json" 17 | return json.load(path.open()) 18 | except Exception as ex: 19 | if no_throw: 20 | return {} 21 | else: 22 | raise ex 23 | -------------------------------------------------------------------------------- /src/starkware/starknet/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | -------------------------------------------------------------------------------- /src/starkware/starknet/business_logic/state/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | py_library( 6 | name = "starknet_business_logic_state_lib", 7 | srcs = [ 8 | "state.py", 9 | "state_api.py", 10 | "state_api_objects.py", 11 | ], 12 | visibility = ["//visibility:public"], 13 | deps = [ 14 | "//src/services/everest/business_logic:everest_business_logic_state_api_lib", 15 | "//src/starkware/cairo/lang:cairo_version_lib", 16 | "//src/starkware/python:starkware_python_utils_lib", 17 | "//src/starkware/starknet/definitions:starknet_definitions_lib", 18 | "//src/starkware/starknet/definitions:starknet_general_config_lib", 19 | "//src/starkware/starknet/public:starknet_abi_lib", 20 | "//src/starkware/starknet/services/api/contract_class:starknet_contract_class_lib", 21 | "//src/starkware/starkware_utils:starkware_dataclasses_utils_lib", 22 | "//src/starkware/starkware_utils:starkware_error_handling_lib", 23 | requirement("marshmallow"), 24 | requirement("marshmallow_dataclass"), 25 | ], 26 | ) 27 | -------------------------------------------------------------------------------- /src/starkware/starknet/common/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/common/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/common/constants.cairo: -------------------------------------------------------------------------------- 1 | // The dummy caller address of an externally originated transaction. 2 | const ORIGIN_ADDRESS = 0; 3 | -------------------------------------------------------------------------------- /src/starkware/starknet/common/eth_utils.cairo: -------------------------------------------------------------------------------- 1 | from starkware.cairo.common.math import assert_lt_felt, assert_not_zero 2 | 3 | const ETH_ADDRESS_BOUND = 2 ** 160; 4 | 5 | func assert_eth_address_range{range_check_ptr}(address: felt) { 6 | with_attr error_message("Invalid Ethereum address - value is more than 160 bits") { 7 | assert_lt_felt(address, ETH_ADDRESS_BOUND); 8 | } 9 | 10 | with_attr error_message("Invalid Ethereum address - value is zero") { 11 | assert_not_zero(address); 12 | } 13 | return (); 14 | } 15 | -------------------------------------------------------------------------------- /src/starkware/starknet/common/messages.cairo: -------------------------------------------------------------------------------- 1 | from starkware.starknet.common.syscalls import SEND_MESSAGE_TO_L1_SELECTOR, SendMessageToL1SysCall 2 | 3 | // Sends a message to an L1 contract at 'l1_address' with given payload. 4 | func send_message_to_l1{syscall_ptr: felt*}(to_address: felt, payload_size: felt, payload: felt*) { 5 | assert [cast(syscall_ptr, SendMessageToL1SysCall*)] = SendMessageToL1SysCall( 6 | selector=SEND_MESSAGE_TO_L1_SELECTOR, 7 | to_address=to_address, 8 | payload_size=payload_size, 9 | payload_ptr=payload, 10 | ); 11 | %{ syscall_handler.send_message_to_l1(segments=segments, syscall_ptr=ids.syscall_ptr) %} 12 | let syscall_ptr = syscall_ptr + SendMessageToL1SysCall.SIZE; 13 | return (); 14 | } 15 | -------------------------------------------------------------------------------- /src/starkware/starknet/compiler/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/compiler/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/compiler/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | pytest.register_assert_rewrite("starkware.cairo.lang.compiler.preprocessor.preprocessor_test_utils") 4 | -------------------------------------------------------------------------------- /src/starkware/starknet/compiler/v1/BUILD: -------------------------------------------------------------------------------- 1 | load("//src/starkware/cairo:vars_cairo_compiler.bzl", "CAIRO_COMPILER_ARCHIVE") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | py_library( 6 | name = "starknet_compile_v1_lib", 7 | srcs = [ 8 | "compile.py", 9 | ], 10 | data = [ 11 | "@" + CAIRO_COMPILER_ARCHIVE, 12 | "experimental_libfuncs.json", 13 | "mainnet_libfuncs.json", 14 | ], 15 | visibility = ["//visibility:public"], 16 | deps = [ 17 | ":exe_paths", 18 | "//src/starkware/starknet/definitions:starknet_definitions_lib", 19 | "//src/starkware/starkware_utils:starkware_error_handling_lib", 20 | ], 21 | ) 22 | 23 | py_library( 24 | name = "exe_paths", 25 | srcs = [ 26 | "compiler_exe_paths.py", 27 | ], 28 | visibility = ["//visibility:public"], 29 | deps = ["@bazel_tools//tools/python/runfiles"], 30 | ) 31 | -------------------------------------------------------------------------------- /src/starkware/starknet/compiler/v1/BUILD.sierra-compiler-major-1: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | filegroup( 4 | name = "sierra-compiler-major-1", 5 | srcs = glob(["**/*"]), 6 | visibility = ["//visibility:public"], 7 | ) 8 | -------------------------------------------------------------------------------- /src/starkware/starknet/compiler/v1/compiler_exe_paths.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | COMPILER_DIR_NAME = "sierra-compiler-major-1/bin" 4 | 5 | # This path might be invalid and shouldn't be used outside the following `if`. 6 | _COMPILER_DIR = os.path.join(os.path.dirname(__file__), COMPILER_DIR_NAME) 7 | 8 | STARKNET_COMPILE_EXE = os.path.join(_COMPILER_DIR, "starknet-compile") 9 | STARKNET_SIERRA_COMPILE_EXE = os.path.join(_COMPILER_DIR, "starknet-sierra-compile") 10 | 11 | 12 | if not os.path.exists(_COMPILER_DIR): 13 | # Bazel flow. 14 | from bazel_tools.tools.python.runfiles import runfiles 15 | 16 | r = runfiles.Create() 17 | STARKNET_COMPILE_EXE = r.Rlocation(os.path.join(COMPILER_DIR_NAME, "starknet-compile")) 18 | STARKNET_SIERRA_COMPILE_EXE = r.Rlocation( 19 | os.path.join(COMPILER_DIR_NAME, "starknet-sierra-compile") 20 | ) 21 | 22 | assert os.path.exists( 23 | STARKNET_COMPILE_EXE 24 | ), f"starknet-compile exe doesn't exist at: {STARKNET_COMPILE_EXE}." 25 | assert os.path.exists( 26 | STARKNET_SIERRA_COMPILE_EXE 27 | ), f"starknet-sierra-compile exe doesn't exist at: {STARKNET_SIERRA_COMPILE_EXE}." 28 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/aggregator/aggregator_program.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | 4 | import cachetools 5 | 6 | from starkware.cairo.lang.compiler.program import Program 7 | from starkware.python.utils import get_build_dir_path 8 | 9 | PROGRAM_PATH = os.path.join(os.path.dirname(__file__), "program_hash.json") 10 | AGGREGATOR_COMPILED_PATH = get_build_dir_path( 11 | "src/starkware/starknet/core/aggregator/aggregator.json" 12 | ) 13 | 14 | 15 | @cachetools.cached(cache={}) 16 | def get_aggregator_program_hash_with_prefix() -> int: 17 | return int(json.load(open(PROGRAM_PATH, "rb"))["program_hash_with_aggregator_prefix"], 16) 18 | 19 | 20 | @cachetools.cached(cache={}) 21 | def get_aggregator_program() -> Program: 22 | return Program.loads(data=open(AGGREGATOR_COMPILED_PATH).read()) 23 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/aggregator/program_hash.json: -------------------------------------------------------------------------------- 1 | { 2 | "program_hash": "0x181986bfe23bbfdac56c40522bd5c2b1b64c824c74bd6722a3ccacc8cc888e2", 3 | "program_hash_with_aggregator_prefix": "0x1ae51bd7157e0754f1e1729806ad5579a7ac6926cd0c8dd342ad1e7a3758c2e" 4 | } 5 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/aggregator/program_hash_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from starkware.cairo.bootloaders.aggregator_utils import add_aggregator_prefix 4 | from starkware.cairo.bootloaders.program_hash_test_utils import ( 5 | program_hash_test_main, 6 | run_generate_hash_test, 7 | ) 8 | from starkware.python.utils import get_source_dir_path 9 | 10 | PROGRAM_PATH = os.path.join(os.path.dirname(__file__), "aggregator.json") 11 | HASH_PATH = get_source_dir_path( 12 | "src/starkware/starknet/core/aggregator/program_hash.json", 13 | default_value=os.path.join(os.path.dirname(__file__), "program_hash.json"), 14 | ) 15 | 16 | COMMAND = "aggregator_program_hash_test_fix" 17 | 18 | 19 | def post_process(data): 20 | data["program_hash_with_aggregator_prefix"] = hex( 21 | add_aggregator_prefix(int(data["program_hash"], 16)) 22 | ) 23 | return data 24 | 25 | 26 | def test_aggregator_program_hash(): 27 | run_generate_hash_test( 28 | fix=False, 29 | program_path=PROGRAM_PATH, 30 | hash_path=HASH_PATH, 31 | command=COMMAND, 32 | post_process=post_process, 33 | ) 34 | 35 | 36 | if __name__ == "__main__": 37 | program_hash_test_main( 38 | program_path=PROGRAM_PATH, hash_path=HASH_PATH, command=COMMAND, post_process=post_process 39 | ) 40 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/core/os/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/block_hash/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | py_library( 4 | name = "starknet_block_hash_lib", 5 | srcs = [ 6 | "block_hash.py", 7 | ], 8 | visibility = ["//visibility:public"], 9 | deps = [ 10 | "//src/starkware/cairo/common:cairo_common_lib", 11 | "//src/starkware/cairo/lang/vm:cairo_vm_crypto_lib", 12 | "//src/starkware/python:starkware_python_utils_lib", 13 | "//src/starkware/starknet/definitions:starknet_definitions_lib", 14 | "//src/starkware/starkware_utils:starkware_utils_lib", 15 | "//src/starkware/storage:starkware_abstract_storage_lib", 16 | "//src/starkware/storage:starkware_dict_storage_lib", 17 | "//src/starkware/storage:starkware_storage_utils_lib", 18 | ], 19 | ) 20 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/contract_class/utils.py: -------------------------------------------------------------------------------- 1 | import contextlib 2 | from contextvars import ContextVar 3 | from enum import Enum, auto 4 | from typing import Any, Optional, Tuple 5 | 6 | import cachetools 7 | 8 | 9 | class ClassHashType(Enum): 10 | CONTRACT_CLASS = 0 11 | COMPILED_CLASS = auto() 12 | DEPRECATED_COMPILED_CLASS = auto() 13 | 14 | 15 | ClassHashCacheKeyType = Tuple[ClassHashType, Any] 16 | 17 | class_hash_cache_ctx_var: ContextVar[ 18 | Optional[cachetools.LRUCache[ClassHashCacheKeyType, int]] 19 | ] = ContextVar("class_hash_cache", default=None) 20 | 21 | 22 | @contextlib.contextmanager 23 | def set_class_hash_cache(cache: cachetools.LRUCache[ClassHashCacheKeyType, int]): 24 | """ 25 | Sets a cache to be used by compute_class_hash(). 26 | """ 27 | assert class_hash_cache_ctx_var.get() is None, "Cannot replace an existing class_hash_cache." 28 | 29 | token = class_hash_cache_ctx_var.set(cache) 30 | try: 31 | yield 32 | finally: 33 | class_hash_cache_ctx_var.reset(token) 34 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/execution/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "deprecated_execute_entry_point.cairo", 5 | "deprecated_execute_syscalls.cairo", 6 | "execute_entry_point.cairo", 7 | "execute_syscalls.cairo", 8 | "execute_transaction_utils.cairo", 9 | "execute_transactions.cairo", 10 | "revert.cairo", 11 | "account_backward_compatibility.cairo", 12 | ]) 13 | 14 | py_library( 15 | name = "account_backward_compatibility_lib", 16 | srcs = [ 17 | "account_backward_compatibility.py", 18 | ], 19 | deps = ["//src/starkware/starknet/definitions:starknet_definitions_lib"], 20 | ) 21 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/execution/account_backward_compatibility.py: -------------------------------------------------------------------------------- 1 | import functools 2 | from typing import FrozenSet 3 | 4 | from starkware.starknet.definitions.constants import get_versioned_constants_json 5 | 6 | 7 | @functools.lru_cache() 8 | def get_v1_bound_accounts_cairo0() -> FrozenSet[int]: 9 | hex_list = get_versioned_constants_json()["os_constants"]["v1_bound_accounts_cairo0"] 10 | return frozenset(int(x, 16) for x in hex_list) 11 | 12 | 13 | @functools.lru_cache() 14 | def get_v1_bound_accounts_cairo1() -> FrozenSet[int]: 15 | hex_list = get_versioned_constants_json()["os_constants"]["v1_bound_accounts_cairo1"] 16 | return frozenset(int(x, 16) for x in hex_list) 17 | 18 | 19 | @functools.lru_cache() 20 | def get_v1_bound_accounts_max_tip() -> int: 21 | hex_val = get_versioned_constants_json()["os_constants"]["v1_bound_accounts_max_tip"] 22 | assert hex_val.startswith("0x") 23 | return int(hex_val, 16) 24 | 25 | 26 | @functools.lru_cache() 27 | def get_data_gas_accounts() -> FrozenSet[int]: 28 | hex_list = get_versioned_constants_json()["os_constants"]["data_gas_accounts"] 29 | return frozenset(int(x, 16) for x in hex_list) 30 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/os_config/os_config_hash.json: -------------------------------------------------------------------------------- 1 | { 2 | "MAINNET": "0x70c7b342f93155315d1cb2da7a4e13a3c2430f51fb5696c1b224c3da5508dfb", 3 | "TESTNET": "0x53a8e6a1184eaf1d76ff707b20dcd7ca40e57cb6673a662a7357a7010671cff", 4 | "TESTNET_SEPOLIA": "0x1b9900f77ff5923183a7795fcfbb54ed76917bc1ddd4160cc77fa96e36cf8c5", 5 | "INTEGRATION_SEPOLIA": "0x5fa1ee0f3971ddd03b1ba861f16503eb1d8e3b3889e20e905f3d1da9c30f3da", 6 | "PREINTEGRATION_SEPOLIA": "0x775ee1a1d2a41ac164cb52ad34fd29dda875d6522174a6788208adf39e121c4", 7 | "TESTNET2": "0x73912d2ae738412252acc3135ecfb08d1f8bb05b3b7696f6f890f3cab63f931" 8 | } 9 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/os_config/os_config_hash.py: -------------------------------------------------------------------------------- 1 | from starkware.cairo.common.hash_state import compute_hash_on_elements 2 | from starkware.starknet.definitions.general_config import StarknetOsConfig 3 | 4 | # A constant representing the StarkNet OS config version. 5 | STARKNET_OS_CONFIG_HASH_VERSION = int.from_bytes(b"StarknetOsConfig3", "big") 6 | 7 | 8 | def calculate_starknet_config_hash(starknet_os_config: StarknetOsConfig) -> int: 9 | """ 10 | Calculates the hash of StarkNet config. 11 | """ 12 | return compute_hash_on_elements( 13 | data=[ 14 | STARKNET_OS_CONFIG_HASH_VERSION, 15 | starknet_os_config.chain_id, 16 | starknet_os_config.fee_token_address, 17 | ] 18 | ) 19 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/os_config/private_os_config_hash.json: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/os_program.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import cachetools 4 | 5 | from starkware.cairo.bootloaders.hash_program import HashFunction, compute_program_hash_chain 6 | from starkware.cairo.lang.compiler.program import Program 7 | 8 | STARKNET_OS_COMPILED_PATH = os.path.join(os.path.dirname(__file__), "starknet_os_compiled.json") 9 | 10 | 11 | @cachetools.cached(cache={}) 12 | def get_os_casm() -> str: 13 | with open(STARKNET_OS_COMPILED_PATH, "r") as file: 14 | return file.read() 15 | 16 | 17 | @cachetools.cached(cache={}) 18 | def get_os_program() -> Program: 19 | return Program.loads(get_os_casm()) 20 | 21 | 22 | @cachetools.cached(cache={}) 23 | def get_os_program_hash() -> int: 24 | program = get_os_program() 25 | return compute_program_hash_chain(program=program, program_hash_function=HashFunction.PEDERSEN) 26 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/program_hash.json: -------------------------------------------------------------------------------- 1 | { 2 | "program_hash": "0x517048691015ccab844c0b238096817831b730afd0657bb4fc470513a49ced1" 3 | } 4 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/program_hash_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from starkware.cairo.bootloaders.program_hash_test_utils import ( 4 | program_hash_test_main, 5 | run_generate_hash_test, 6 | ) 7 | from starkware.python.utils import get_source_dir_path 8 | 9 | PROGRAM_PATH = os.path.join(os.path.dirname(__file__), "starknet_os_compiled.json") 10 | HASH_PATH = get_source_dir_path( 11 | "src/starkware/starknet/core/os/program_hash.json", 12 | default_value=os.path.join(os.path.dirname(__file__), "program_hash.json"), 13 | ) 14 | COMMAND = "starknet_os_program_hash_test_fix" 15 | 16 | 17 | def test_starknet_program_hash(): 18 | run_generate_hash_test( 19 | fix=False, program_path=PROGRAM_PATH, hash_path=HASH_PATH, command=COMMAND 20 | ) 21 | 22 | 23 | if __name__ == "__main__": 24 | program_hash_test_main(program_path=PROGRAM_PATH, hash_path=HASH_PATH, command=COMMAND) 25 | -------------------------------------------------------------------------------- /src/starkware/starknet/core/os/state/BUILD: -------------------------------------------------------------------------------- 1 | load("//src/starkware/cairo/lang:cairo_rules.bzl", "cairo_library") 2 | 3 | cairo_library( 4 | name = "starknet_os_state_lib", 5 | srcs = [ 6 | "aliases.cairo", 7 | "commitment.cairo", 8 | "output.cairo", 9 | "squash.cairo", 10 | "state.cairo", 11 | "//src/starkware/starknet/core/os:constants.cairo", 12 | ], 13 | visibility = ["//visibility:public"], 14 | deps = [ 15 | "//src/starkware/cairo/common:cairo_common_cairo_lib", 16 | ], 17 | ) 18 | -------------------------------------------------------------------------------- /src/starkware/starknet/definitions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/definitions/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/definitions/blockifier_types.py: -------------------------------------------------------------------------------- 1 | # Modules should not be named `types`, as this may cause errors: 2 | # https://stackoverflow.com/questions/43453414 . 3 | from typing import Dict, Tuple 4 | 5 | # Blockifier typedefs: 6 | 7 | RawClass = str 8 | # Class hash to raw class. Where raw class is a JSON dictionary representing the class. 9 | # We use a plain JSON instead of a Python object to save loading time. 10 | RawDeprecatedDeclaredClassMapping = Dict[int, RawClass] 11 | # Class hash to (contract class, (compiled hash, compiled class)). 12 | RawDeclaredClassMapping = Dict[int, Tuple[RawClass, Tuple[int, RawClass]]] 13 | -------------------------------------------------------------------------------- /src/starkware/starknet/definitions/chain_ids.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from typing import Dict, Set 3 | 4 | from starkware.python.utils import from_bytes 5 | from starkware.starknet.definitions.overridable_versioned_constants import ( 6 | OverridableVersionedConstants, 7 | ) 8 | 9 | FEE_TOKEN_ADDRESS = 0x04718F5A0FC34CC1AF16A1CDEE98FFB20C31F5CD61D6AB07201858F4287C938D 10 | DEPRECATED_FEE_TOKEN_ADDRESS = 0x49D36570D4E46F48E99674BD3FCC84644DDD6B96F7C741B1562B82F9E004DC7 11 | 12 | 13 | class StarknetChainId(Enum): 14 | MAINNET = from_bytes(b"SN_MAIN") 15 | TESTNET = from_bytes(b"SN_GOERLI") 16 | TESTNET2 = from_bytes(b"SN_GOERLI2") 17 | TESTNET_SEPOLIA = from_bytes(b"SN_SEPOLIA") 18 | INTEGRATION_SEPOLIA = from_bytes(b"SN_INTEGRATION_SEPOLIA") 19 | PREINTEGRATION_SEPOLIA = from_bytes(b"SN_PREINTEGRATION_SEPOLIA") 20 | 21 | def is_private(self) -> bool: 22 | return self.name in PRIVATE_CHAIN_IDS 23 | 24 | 25 | PRIVATE_CHAIN_IDS: Set[str] = set() 26 | 27 | 28 | CHAIN_ID_TO_FEE_TOKEN_ADDRESS = {chain_enum: FEE_TOKEN_ADDRESS for chain_enum in StarknetChainId} 29 | CHAIN_ID_TO_DEPRECATED_FEE_TOKEN_ADDRESS = { 30 | chain_enum: DEPRECATED_FEE_TOKEN_ADDRESS for chain_enum in StarknetChainId 31 | } 32 | 33 | CHAIN_ID_TO_PRIVATE_VERSIONED_CONSTANTS: Dict[StarknetChainId, OverridableVersionedConstants] = {} 34 | -------------------------------------------------------------------------------- /src/starkware/starknet/definitions/data_availability_mode.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class DataAvailabilityMode(Enum): 5 | L1 = 0 6 | L2 = 1 7 | 8 | def assert_l1(self): 9 | assert self is DataAvailabilityMode.L1, "Only L1 storage is currently supported." 10 | -------------------------------------------------------------------------------- /src/starkware/starknet/definitions/execution_mode.py: -------------------------------------------------------------------------------- 1 | from enum import Enum, auto 2 | 3 | 4 | class ExecutionMode(Enum): 5 | """ 6 | The execution mode of a given entry point. 7 | Used by the syscall handler. 8 | """ 9 | 10 | EXECUTE = 0 11 | # Runs the entry point in validate mode. In validate mode the run changes as follows: 12 | # 1. A contract is not allowed to call another contract. 13 | # 2. The following deprecated syscalls are blocked: 14 | # - get_block_number. 15 | # - get_sequence_address. 16 | # - get_block_timestamp. 17 | # 3. The following syscalls are changed. 18 | # - get_block_hash is blocked. 19 | # - In get_execution_info the block info is replaced with all-zeros. 20 | VALIDATE = auto() 21 | -------------------------------------------------------------------------------- /src/starkware/starknet/definitions/general_config.yml: -------------------------------------------------------------------------------- 1 | deprecated_fee_token_address: '0x497d1c054cec40f64454b45deecdc83e0c7f7b961c63531eae03748abd95350' 2 | enforce_l1_handler_fee: true 3 | sequencer_address: '0x295548396b1c6cb8a9e420773c28f1531492f73bc45c35e2f499e3d3a6605b2' 4 | starknet_os_config: 5 | chain_id: 1536727068981429685321 6 | fee_token_address: '0x4fa9355c504fa2de263bd7920644b5e48794fe1450ec2a6526518ad77d6a567' 7 | validate_max_n_steps_override: 1000000 8 | -------------------------------------------------------------------------------- /src/starkware/starknet/definitions/l1_da_mode.py: -------------------------------------------------------------------------------- 1 | from enum import Enum, auto 2 | 3 | 4 | class L1DaMode(Enum): 5 | CALLDATA = 0 6 | BLOB = auto() 7 | 8 | @classmethod 9 | def from_boolean(cls, use_kzg_da: bool) -> "L1DaMode": 10 | return cls.BLOB if use_kzg_da else cls.CALLDATA 11 | -------------------------------------------------------------------------------- /src/starkware/starknet/definitions/overridable_versioned_constants.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | from typing import Optional 3 | 4 | 5 | # Should only include versioned constants which are both overridable AND have a need for an 6 | # override. 7 | @dataclasses.dataclass(frozen=True) 8 | class OverridableVersionedConstants: 9 | max_calldata_length: Optional[int] = None 10 | invoke_tx_max_n_steps: Optional[int] = None 11 | validate_max_n_steps: Optional[int] = None 12 | max_n_events: Optional[int] = None 13 | -------------------------------------------------------------------------------- /src/starkware/starknet/definitions/transaction_type.py: -------------------------------------------------------------------------------- 1 | from enum import auto 2 | 3 | from services.everest.api.gateway.transaction_type import TransactionTypeBase 4 | 5 | # The name of the schema for deprecated transactions. Must be of the form: 6 | # "DEPRECATED_" + TransactionType.name. 7 | DEPRECATED_DECLARE_SCHEMA_NAME = "DEPRECATED_DECLARE" 8 | DEPRECATED_DEPLOY_ACCOUNT_SCHEMA_NAME = "DEPRECATED_DEPLOY_ACCOUNT" 9 | DEPRECATED_INVOKE_FUNCTION_SCHEMA_NAME = "DEPRECATED_INVOKE_FUNCTION" 10 | DEPRECATED_OLD_DECLARE_SCHEMA_NAME = "DEPRECATED_OLD_DECLARE" 11 | 12 | 13 | class TransactionType(TransactionTypeBase): 14 | DECLARE = 0 15 | DEPLOY = auto() 16 | DEPLOY_ACCOUNT = auto() 17 | INITIALIZE_BLOCK_INFO = auto() 18 | INVOKE_FUNCTION = auto() 19 | L1_HANDLER = auto() 20 | -------------------------------------------------------------------------------- /src/starkware/starknet/public/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | load("//bazel_utils:python.bzl", "pytest_test") 3 | 4 | package(default_visibility = ["//visibility:public"]) 5 | 6 | py_library( 7 | name = "starknet_abi_lib", 8 | srcs = [ 9 | "abi.py", 10 | "abi_structs.py", 11 | ], 12 | visibility = ["//visibility:public"], 13 | deps = [ 14 | "//src/starkware/cairo/lang/compiler:cairo_compile_lib", 15 | "//src/starkware/cairo/lang/vm:cairo_vm_crypto_lib", 16 | "//src/starkware/python:starkware_python_utils_lib", 17 | requirement("eth_hash"), 18 | requirement("pycryptodome"), 19 | ], 20 | ) 21 | 22 | pytest_test( 23 | name = "starknet_abi_lib_test", 24 | srcs = [ 25 | "abi_structs_test.py", 26 | "abi_test.py", 27 | ], 28 | visibility = ["//visibility:public"], 29 | deps = [ 30 | "starknet_abi_lib", 31 | ], 32 | ) 33 | -------------------------------------------------------------------------------- /src/starkware/starknet/public/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/public/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/public/abi_test.py: -------------------------------------------------------------------------------- 1 | from starkware.starknet.public.abi import starknet_keccak 2 | 3 | 4 | def test_starknet_keccak(): 5 | value = starknet_keccak(b"hello") 6 | assert value == 0x8AFF950685C2ED4BC3174F3472287B56D9517B9C948127319A09A7A36DEAC8 7 | assert value < 2**250 8 | -------------------------------------------------------------------------------- /src/starkware/starknet/scripts/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | py_library( 4 | name = "starknet_script_lib", 5 | data = [ 6 | "starknet", 7 | "starknet-class-hash", 8 | "starknet-compile-deprecated", 9 | "starknet-compiled-class-hash", 10 | ], 11 | visibility = ["//visibility:public"], 12 | deps = [ 13 | "//src/starkware/starknet/cli:starknet_cli_lib", 14 | "//src/starkware/starknet/compiler:starknet_compile_lib", 15 | ], 16 | ) 17 | -------------------------------------------------------------------------------- /src/starkware/starknet/scripts/starknet: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import asyncio 4 | import os 5 | import sys 6 | 7 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../..")) 8 | from starkware.starknet.cli.starknet_cli import main # noqa 9 | 10 | if __name__ == "__main__": 11 | sys.exit(asyncio.run(main())) 12 | -------------------------------------------------------------------------------- /src/starkware/starknet/scripts/starknet-class-hash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../..")) 7 | from starkware.starknet.cli.class_hash import main # noqa 8 | 9 | if __name__ == "__main__": 10 | sys.exit(main()) 11 | -------------------------------------------------------------------------------- /src/starkware/starknet/scripts/starknet-compile-deprecated: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../..")) 7 | from starkware.starknet.compiler.compile import main # noqa 8 | 9 | if __name__ == "__main__": 10 | sys.exit(main()) 11 | -------------------------------------------------------------------------------- /src/starkware/starknet/scripts/starknet-compiled-class-hash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../../..")) 7 | from starkware.starknet.cli.compiled_class_hash import main # noqa 8 | 9 | if __name__ == "__main__": 10 | sys.exit(main()) 11 | -------------------------------------------------------------------------------- /src/starkware/starknet/security/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/security/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/security/hints_whitelist.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from starkware.starknet.security.secure_hints import HintsWhitelist 4 | 5 | WHILTELIST_DIR = os.path.join(os.path.dirname(__file__), "whitelists") 6 | 7 | 8 | def get_hints_whitelist() -> HintsWhitelist: 9 | return HintsWhitelist.from_dir(dirname=WHILTELIST_DIR) 10 | -------------------------------------------------------------------------------- /src/starkware/starknet/security/simple_references_test.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | import pytest 4 | 5 | from starkware.cairo.lang.compiler.parser import parse_expr 6 | from starkware.starknet.security.simple_references import is_simple_reference 7 | 8 | 9 | @pytest.mark.parametrize( 10 | "expr_str, simplicity", 11 | [ 12 | ["ap", 1], 13 | ["1234", 1], 14 | ["(ap * (-3) + 4) - 5", 10], 15 | ["[[[ap] + [fp]]]", 7], 16 | ["cast(ap, x)", 2], 17 | ["[cast(ap, x)]", 3], 18 | ["cast(ap, x) + 1", None], 19 | ["cast(cast(ap, x), x)", None], 20 | ["x", None], 21 | ["&ap", None], 22 | ["3 ** 2", None], 23 | ["3 / 2", None], 24 | ["nondet %{ 5 %}", None], 25 | ], 26 | ) 27 | def test_is_simple_reference(expr_str: str, simplicity: Optional[int]): 28 | expr = parse_expr(expr_str) 29 | if simplicity is not None: 30 | assert is_simple_reference(expr, simplicity_bound=simplicity) is False 31 | assert is_simple_reference(expr, simplicity_bound=simplicity + 1) is True 32 | else: 33 | assert is_simple_reference(expr, simplicity_bound=0) is False 34 | assert is_simple_reference(expr, simplicity_bound=1000) is False 35 | -------------------------------------------------------------------------------- /src/starkware/starknet/security/whitelists/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(glob(["*.json"])) 4 | -------------------------------------------------------------------------------- /src/starkware/starknet/security/whitelists/cairo_sha256_arbitrary_input_length.json: -------------------------------------------------------------------------------- 1 | { 2 | "allowed_reference_expressions_for_hint": [ 3 | { 4 | "allowed_expressions": [], 5 | "hint_lines": [ 6 | "from starkware.cairo.common.cairo_sha256.sha256_utils import (", 7 | " compute_message_schedule, sha2_compress_function)", 8 | "", 9 | "_sha256_input_chunk_size_felts = int(ids.SHA256_INPUT_CHUNK_SIZE_FELTS)", 10 | "assert 0 <= _sha256_input_chunk_size_felts < 100", 11 | "_sha256_state_size_felts = int(ids.SHA256_STATE_SIZE_FELTS)", 12 | "assert 0 <= _sha256_state_size_felts < 100", 13 | "w = compute_message_schedule(memory.get_range(", 14 | " ids.sha256_start, _sha256_input_chunk_size_felts))", 15 | "new_state = sha2_compress_function(memory.get_range(ids.state, _sha256_state_size_felts), w)", 16 | "segments.write_arg(ids.output, new_state)" 17 | ] 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/starkware/starknet/security/whitelists/encode_packed.json: -------------------------------------------------------------------------------- 1 | { 2 | "allowed_reference_expressions_for_hint": [ 3 | { 4 | "allowed_expressions": [], 5 | "hint_lines": [ 6 | "x = ids.x", 7 | "ids.bit_length = x.bit_length()" 8 | ] 9 | } 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/starkware/starknet/services/api/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | py_library( 4 | name = "starknet_messages_lib", 5 | srcs = [ 6 | "messages.py", 7 | ], 8 | visibility = ["//visibility:public"], 9 | deps = [ 10 | "//src/services/everest/definitions:everest_definitions_lib", 11 | "//src/starkware/cairo/bootloaders:cairo_bootloader_generate_fact_lib", 12 | "//src/starkware/python:starkware_python_utils_lib", 13 | "//src/starkware/starknet/business_logic/transaction:starknet_transaction_deprecated_objects_lib", 14 | "//src/starkware/starknet/definitions:starknet_definitions_lib", 15 | "//src/starkware/starkware_utils:starkware_dataclasses_utils_lib", 16 | ], 17 | ) 18 | -------------------------------------------------------------------------------- /src/starkware/starknet/services/api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/services/api/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/services/api/contract_class/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/services/api/contract_class/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/services/api/feeder_gateway/block_signature.py: -------------------------------------------------------------------------------- 1 | from typing import Callable, List, Optional 2 | 3 | from starkware.crypto.signature.signature import ECSignature, sign 4 | from starkware.starknet.services.api.feeder_gateway.response_objects import BlockSignature 5 | 6 | HashManyFunction = Callable[[List[int]], int] 7 | 8 | 9 | def sign_block(private_key: int, block_hash: int) -> ECSignature: 10 | """ 11 | Signs on the block hash. 12 | """ 13 | return sign(block_hash, priv_key=private_key) 14 | 15 | 16 | def get_signature( 17 | block_hash: int, private_key: int, hash_func: Optional[HashManyFunction] = None 18 | ) -> BlockSignature: 19 | return BlockSignature( 20 | block_hash=block_hash, signature=sign_block(private_key=private_key, block_hash=block_hash) 21 | ) 22 | -------------------------------------------------------------------------------- /src/starkware/starknet/services/api/feeder_gateway/transaction_specific_info.py: -------------------------------------------------------------------------------- 1 | from dataclasses import field 2 | from typing import ClassVar 3 | 4 | import marshmallow_dataclass 5 | 6 | from services.everest.api.feeder_gateway.response_objects import ValidatedResponseObject 7 | from starkware.starknet.definitions import fields 8 | from starkware.starknet.definitions.transaction_type import TransactionType 9 | 10 | 11 | @marshmallow_dataclass.dataclass(frozen=True) 12 | class TransactionSpecificInfo(ValidatedResponseObject): 13 | transaction_hash: int = field(metadata=fields.transaction_hash_metadata) 14 | tx_type: ClassVar[TransactionType] 15 | version: int = field(metadata=fields.tx_version_metadata) 16 | -------------------------------------------------------------------------------- /src/starkware/starknet/services/api/gateway/gateway_client.py: -------------------------------------------------------------------------------- 1 | import json 2 | from typing import Dict, Optional 3 | 4 | from services.everest.api.gateway.gateway_client import EverestGatewayClient 5 | from starkware.starknet.services.api.gateway.transaction import Transaction 6 | from starkware.starknet.services.api.gateway.transaction_schema import TransactionSchema 7 | 8 | 9 | class GatewayClient(EverestGatewayClient): 10 | """ 11 | A client class for the StarkNet Gateway. 12 | """ 13 | 14 | async def add_transaction(self, tx: Transaction, token: Optional[str] = None) -> Dict[str, str]: 15 | uri_suffix = "" if token is None else f"?token={token}" 16 | 17 | raw_response = await self._send_request( 18 | send_method="POST", 19 | uri=f"/add_transaction{uri_suffix}", 20 | data=TransactionSchema().dumps(obj=tx), 21 | ) 22 | return json.loads(raw_response) 23 | -------------------------------------------------------------------------------- /src/starkware/starknet/services/utils/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | -------------------------------------------------------------------------------- /src/starkware/starknet/solidity/StarknetGovernance.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.8.0; 3 | 4 | import "starkware/solidity/components/Governance.sol"; 5 | 6 | contract StarknetGovernance is Governance { 7 | string constant STARKNET_GOVERNANCE_INFO_TAG = "STARKNET_1.0_GOVERNANCE_INFO"; 8 | 9 | /* 10 | Returns the GovernanceInfoStruct associated with the governance tag. 11 | */ 12 | function getGovernanceInfo() internal pure override returns (GovernanceInfoStruct storage gub) { 13 | bytes32 location = keccak256(abi.encodePacked(STARKNET_GOVERNANCE_INFO_TAG)); 14 | assembly { 15 | gub.slot := location 16 | } 17 | } 18 | 19 | function starknetIsGovernor(address user) external view returns (bool) { 20 | return _isGovernor(user); 21 | } 22 | 23 | function starknetNominateNewGovernor(address newGovernor) external { 24 | _nominateNewGovernor(newGovernor); 25 | } 26 | 27 | function starknetRemoveGovernor(address governorForRemoval) external { 28 | _removeGovernor(governorForRemoval); 29 | } 30 | 31 | function starknetAcceptGovernance() external { 32 | _acceptGovernance(); 33 | } 34 | 35 | function starknetCancelNomination() external { 36 | _cancelNomination(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/starkware/starknet/solidity/StarknetOperator.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0. 2 | pragma solidity ^0.8.0; 3 | 4 | import "starkware/solidity/components/Operator.sol"; 5 | import "starkware/solidity/libraries/NamedStorage8.sol"; 6 | 7 | abstract contract StarknetOperator is Operator { 8 | string constant OPERATORS_MAPPING_TAG = "STARKNET_1.0_ROLES_OPERATORS_MAPPING_TAG"; 9 | 10 | function getOperators() internal pure override returns (mapping(address => bool) storage) { 11 | return NamedStorage.addressToBoolMapping(OPERATORS_MAPPING_TAG); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/starkware/starknet/solidity/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/solidity/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/starknet_rules_v0.bzl: -------------------------------------------------------------------------------- 1 | load("//src/starkware/cairo/lang:cairo_rules.bzl", "cairo_binary") 2 | 3 | def starknet_contract_v0( 4 | name, 5 | compiled_program_name, 6 | cairo_compile_exe = "//src/starkware/starknet/compiler:starknet_compile_exe", 7 | **kwargs): 8 | cairo_binary( 9 | name = name, 10 | abi = "%s_abi.json" % name, 11 | compiled_program_name = compiled_program_name, 12 | cairo_compile_exe = cairo_compile_exe, 13 | **kwargs 14 | ) 15 | 16 | def starknet_contract_v0_for_testing( 17 | name, 18 | main, 19 | srcs, 20 | **kwargs): 21 | new_main = main[:-6] + "_for_testing.cairo" 22 | native.genrule( 23 | name = "generate_" + name, 24 | srcs = [main], 25 | outs = [new_main], 26 | tools = ["//src/starkware/starknet:make_contract_for_testing"], 27 | cmd = "$(execpath //src/starkware/starknet:make_contract_for_testing) " + 28 | "--input_path $(execpath %s) " % main + 29 | "--output_path $(execpath %s)" % new_main, 30 | ) 31 | starknet_contract_v0( 32 | name = name, 33 | main = new_main, 34 | srcs = srcs + [new_main], 35 | **kwargs 36 | ) 37 | -------------------------------------------------------------------------------- /src/starkware/starknet/storage/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | py_library( 6 | name = "starknet_storage_lib", 7 | srcs = [ 8 | "starknet_storage.py", 9 | ], 10 | visibility = ["//visibility:public"], 11 | deps = [ 12 | "//src/starkware/python:starkware_python_utils_lib", 13 | "//src/starkware/starknet/definitions:starknet_definitions_lib", 14 | "//src/starkware/starkware_utils:starkware_commitment_tree_facts_lib", 15 | "//src/starkware/starkware_utils:starkware_commitment_tree_leaf_fact_utils_lib", 16 | "//src/starkware/starkware_utils:starkware_dataclasses_utils_lib", 17 | "//src/starkware/starkware_utils:starkware_utils_lib", 18 | "//src/starkware/storage:starkware_abstract_storage_lib", 19 | requirement("marshmallow_dataclass"), 20 | ], 21 | ) 22 | -------------------------------------------------------------------------------- /src/starkware/starknet/testing/contracts.py: -------------------------------------------------------------------------------- 1 | from starkware.solidity.utils import load_nearby_contract 2 | 3 | MockStarknetMessaging = load_nearby_contract("MockStarknetMessaging") 4 | -------------------------------------------------------------------------------- /src/starkware/starknet/third_party/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/third_party/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/third_party/open_zeppelin/BUILD: -------------------------------------------------------------------------------- 1 | load("//src/starkware/starknet:starknet_rules_v0.bzl", "starknet_contract_v0") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | starknet_contract_v0( 6 | name = "account", 7 | srcs = [ 8 | "Account.cairo", 9 | ], 10 | cairoopts = ["--account_contract"], 11 | compiled_program_name = "account.json", 12 | main = "Account.cairo", 13 | deps = [ 14 | "//src/starkware/starknet/third_party/open_zeppelin/utils:constants", 15 | ], 16 | ) 17 | 18 | py_library( 19 | name = "open_zeppelin_contracts_lib", 20 | srcs = [ 21 | "starknet_contracts.py", 22 | ], 23 | data = [ 24 | "account.json", 25 | "//src/starkware/starknet/common:starknet_common_cairo_lib", 26 | ], 27 | visibility = ["//visibility:public"], 28 | deps = [ 29 | "//src/starkware/cairo/common:cairo_common_lib", 30 | "//src/starkware/starknet/services/api/contract_class:starknet_contract_class_lib", 31 | ], 32 | ) 33 | -------------------------------------------------------------------------------- /src/starkware/starknet/third_party/open_zeppelin/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/third_party/open_zeppelin/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/third_party/open_zeppelin/starknet_contracts.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | 3 | from starkware.starknet.services.api.contract_class.contract_class import DeprecatedCompiledClass 4 | 5 | DIR = os.path.dirname(__file__) 6 | 7 | account_contract = DeprecatedCompiledClass.loads( 8 | data=open(os.path.join(DIR, "account.json")).read() 9 | ) 10 | -------------------------------------------------------------------------------- /src/starkware/starknet/third_party/open_zeppelin/utils/BUILD: -------------------------------------------------------------------------------- 1 | load("//src/starkware/cairo/lang:cairo_rules.bzl", "cairo_library") 2 | 3 | package(default_visibility = ["//visibility:public"]) 4 | 5 | cairo_library( 6 | name = "constants", 7 | srcs = [ 8 | "constants.cairo", 9 | ], 10 | ) 11 | -------------------------------------------------------------------------------- /src/starkware/starknet/third_party/open_zeppelin/utils/constants.cairo: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | // OpenZeppelin Cairo Contracts v0.1.0 (utils/constants.cairo) 3 | 4 | %lang starknet 5 | 6 | // 7 | // Booleans 8 | // 9 | 10 | const TRUE = 1; 11 | const FALSE = 0; 12 | 13 | // 14 | // Hashing Transactions 15 | // 16 | 17 | const PREFIX_TRANSACTION = 'StarkNet Transaction'; 18 | 19 | // 20 | // Numbers 21 | // 22 | 23 | const UINT8_MAX = 256; 24 | -------------------------------------------------------------------------------- /src/starkware/starknet/utils/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | py_library( 4 | name = "starknet_api_utils_lib", 5 | srcs = [ 6 | "api_utils.py", 7 | ], 8 | visibility = ["//visibility:public"], 9 | deps = [ 10 | "//src/starkware/cairo/lang:cairo_constants_lib", 11 | ], 12 | ) 13 | -------------------------------------------------------------------------------- /src/starkware/starknet/utils/api_utils.py: -------------------------------------------------------------------------------- 1 | from typing import List, Sequence, Union 2 | 3 | from starkware.cairo.lang.cairo_constants import DEFAULT_PRIME as PRIME 4 | 5 | 6 | def cast_to_felts(values: Sequence[Union[str, int]]) -> List[int]: 7 | lower_bound = -(PRIME // 2) 8 | upper_bound = PRIME 9 | result = [] 10 | for value in values: 11 | if isinstance(value, int): 12 | value_int = value 13 | else: 14 | try: 15 | value_int = int(value, 16) if value.startswith("0x") else int(value) 16 | except ValueError: 17 | raise ValueError( 18 | f"Invalid input value: '{value}'. Expected a decimal or hexadecimal integer." 19 | ) from None 20 | 21 | if not lower_bound <= value_int < upper_bound: 22 | raise ValueError( 23 | f"Input value '{value}' is out of bounds. " 24 | f"Expected a value in the range [{lower_bound}, {upper_bound})." 25 | ) 26 | 27 | result.append(value_int % PRIME) 28 | 29 | return result 30 | -------------------------------------------------------------------------------- /src/starkware/starknet/wallets/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starknet/wallets/__init__.py -------------------------------------------------------------------------------- /src/starkware/starknet/wallets/starknet_context.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | 3 | 4 | @dataclasses.dataclass 5 | class StarknetContext: 6 | # A textual identifier used to distinguish between different Starknet networks. 7 | network_id: str 8 | # The directory which contains the account information files. 9 | account_dir: str 10 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/commitment_tree/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files(glob(["*.py"])) 4 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/commitment_tree/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starkware_utils/commitment_tree/__init__.py -------------------------------------------------------------------------------- /src/starkware/starkware_utils/commitment_tree/inner_node_fact.py: -------------------------------------------------------------------------------- 1 | from abc import abstractmethod 2 | from typing import Tuple 3 | 4 | from starkware.storage.storage import Fact 5 | 6 | 7 | class InnerNodeFact(Fact): 8 | """ 9 | Represents the fact of an inner node in a binary fact tree. 10 | """ 11 | 12 | @abstractmethod 13 | def to_tuple(self) -> Tuple[int, ...]: 14 | """ 15 | Returns a representation of the fact's preimage as a tuple. 16 | """ 17 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/commitment_tree/leaf_fact.py: -------------------------------------------------------------------------------- 1 | from abc import abstractmethod 2 | from typing import TypeVar 3 | 4 | from starkware.storage.storage import Fact 5 | 6 | 7 | class LeafFact(Fact): 8 | """ 9 | A fact that represents a leaf in a commitment tree. 10 | """ 11 | 12 | @property 13 | @abstractmethod 14 | def is_empty(self) -> bool: 15 | """ 16 | Returns true iff the fact represents a leaf that has no value or was deleted. 17 | """ 18 | 19 | 20 | TLeafFact = TypeVar("TLeafFact", bound=LeafFact) 21 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/commitment_tree/merkle_tree/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | exports_files([ 4 | "merkle_calculation_node.py", 5 | "merkle_tree.py", 6 | "merkle_tree_node.py", 7 | "traverse_tree.py", 8 | ]) 9 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/commitment_tree/patricia_tree/BUILD: -------------------------------------------------------------------------------- 1 | load("//bazel_utils/python:defs.bzl", "requirement") 2 | load("//bazel_utils:python.bzl", "pytest_test") 3 | 4 | package(default_visibility = ["//visibility:public"]) 5 | 6 | exports_files([ 7 | "fast_patricia_update.py", 8 | "nodes.py", 9 | "patricia_tree.py", 10 | "test_utils.py", 11 | "virtual_calculation_node.py", 12 | "virtual_patricia_node.py", 13 | ]) 14 | 15 | pytest_test( 16 | name = "patricia_tree_test", 17 | srcs = [ 18 | "nodes_test.py", 19 | "patricia_tree_test.py", 20 | "virtual_calculation_node_test.py", 21 | "virtual_patricia_node_test.py", 22 | ], 23 | visibility = ["//visibility:public"], 24 | deps = [ 25 | "//src/starkware/cairo/common:cairo_common_lib", 26 | "//src/starkware/crypto:starkware_crypto_lib", 27 | "//src/starkware/python:starkware_python_test_utils_lib", 28 | "//src/starkware/python:starkware_python_utils_lib", 29 | "//src/starkware/starkware_utils:starkware_utils_lib", 30 | "//src/starkware/storage:starkware_storage_lib", 31 | "//src/starkware/storage:starkware_storage_test_utils_lib", 32 | "//src/starkware/storage:starkware_storage_utils_lib", 33 | requirement("pytest_asyncio"), 34 | ], 35 | ) 36 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/commitment_tree/patricia_tree/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starkware_utils/commitment_tree/patricia_tree/__init__.py -------------------------------------------------------------------------------- /src/starkware/starkware_utils/executor.py: -------------------------------------------------------------------------------- 1 | from concurrent.futures import Executor 2 | from contextlib import contextmanager 3 | from contextvars import ContextVar 4 | from typing import Optional 5 | 6 | executor_ctx_var: ContextVar[Optional[Executor]] = ContextVar("executor", default=None) 7 | 8 | 9 | @contextmanager 10 | def service_executor(executor: Executor): 11 | """ 12 | Context manager that sets executor_ctx_var context variable. 13 | """ 14 | try: 15 | prev = executor_ctx_var.get() 16 | executor_ctx_var.set(executor) 17 | yield 18 | finally: 19 | executor_ctx_var.set(prev) 20 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/subsequence.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | 4 | def is_subsequence(subsequence: List, sequence: List) -> bool: 5 | """ 6 | Checks whether 'subsequence' is a subsequence of 'sequence'. 7 | """ 8 | 9 | offset = 0 10 | for item in sequence: 11 | if offset == len(subsequence): 12 | return True 13 | 14 | if item == subsequence[offset]: 15 | offset = offset + 1 16 | 17 | return offset == len(subsequence) 18 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/time/BUILD: -------------------------------------------------------------------------------- 1 | exports_files(["__init__.py"]) 2 | 3 | py_library( 4 | name = "starkware_utils_time_lib", 5 | srcs = [ 6 | "fastforward.py", 7 | "synchronous_executor.py", 8 | "time.py", 9 | ], 10 | visibility = ["//visibility:public"], 11 | ) 12 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/time/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/starkware_utils/time/__init__.py -------------------------------------------------------------------------------- /src/starkware/starkware_utils/time/synchronous_executor.py: -------------------------------------------------------------------------------- 1 | from concurrent.futures import Executor, Future 2 | from threading import Lock 3 | 4 | 5 | class SynchronousExecutor(Executor): 6 | """ 7 | Mock executor for tests. Executes all calls synchronously. 8 | """ 9 | 10 | def __init__(self): 11 | self._shutdown = False 12 | self._shutdownLock = Lock() 13 | 14 | def submit(self, fn, *args, **kwargs): 15 | with self._shutdownLock: 16 | if self._shutdown: 17 | raise RuntimeError("cannot schedule new futures after shutdown") 18 | 19 | f: Future = Future() 20 | try: 21 | result = fn(*args, **kwargs) 22 | except BaseException as e: 23 | f.set_exception(e) 24 | else: 25 | f.set_result(result) 26 | 27 | return f 28 | 29 | def shutdown(self, wait=True): 30 | with self._shutdownLock: 31 | self._shutdown = True 32 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/time/time.py: -------------------------------------------------------------------------------- 1 | from contextlib import contextmanager 2 | from contextvars import ContextVar 3 | from time import time as def_time_func 4 | from typing import Callable 5 | 6 | """ 7 | Provides an overridable time() function. 8 | Tests can mock this time function mock_time_func. 9 | 10 | Example: 11 | with mock_time_func(lambda: 1000): 12 | assert time() == 1000 13 | """ 14 | 15 | 16 | mocked_time_func: ContextVar[Callable[[], float]] = ContextVar( 17 | "mocked_time_func", default=def_time_func 18 | ) 19 | 20 | 21 | def time(): 22 | time_func = mocked_time_func.get() 23 | return time_func() 24 | 25 | 26 | def elapsed_time(timestamp: float) -> float: 27 | return time() - timestamp 28 | 29 | 30 | @contextmanager 31 | def mock_time_func(time_func: Callable[[], float]): 32 | last_val = mocked_time_func.get() 33 | try: 34 | mocked_time_func.set(time_func) 35 | yield 36 | finally: 37 | mocked_time_func.set(last_val) 38 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/time/time_test.py: -------------------------------------------------------------------------------- 1 | from time import time as real_time 2 | 3 | from starkware.starkware_utils.time.time import mock_time_func, time 4 | 5 | 6 | def test_time(): 7 | assert abs(real_time() - time()) < 1 8 | with mock_time_func(lambda: 1000): 9 | assert time() == 1000 10 | with mock_time_func(lambda: 2000): 11 | assert time() == 2000 12 | assert time() == 1000 13 | -------------------------------------------------------------------------------- /src/starkware/starkware_utils/vars.bzl: -------------------------------------------------------------------------------- 1 | STARKWARE_UTILS_LIBS_ADDITIONAL_FILES = [] 2 | STARKWARE_UTILS_LIBS_ADDITIONAL_LIBS = [] 3 | -------------------------------------------------------------------------------- /src/starkware/storage/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/starkware-libs/cairo-lang/ab8be40403a7634ba296c467b26b8bd945ba5cfa/src/starkware/storage/__init__.py -------------------------------------------------------------------------------- /src/starkware/storage/metrics.py: -------------------------------------------------------------------------------- 1 | import prometheus_client 2 | 3 | CACHED_STORAGE_GET_TOTAL = prometheus_client.Counter( 4 | name="starkware_cached_storage_get_total_count", 5 | documentation="Count of total get_value() calls to CachedStorage", 6 | labelnames=(), 7 | ) 8 | 9 | CACHED_STORAGE_GET_CACHE = prometheus_client.Counter( 10 | name="starkware_cached_storage_get_cache_count", 11 | documentation="Count of get_value() calls to CachedStorage that got the value from the cache", 12 | labelnames=(), 13 | ) 14 | 15 | # Metric names may diverge on client argument. 16 | CACHED_STORAGE_GET_TOTAL_NAME = getattr(CACHED_STORAGE_GET_TOTAL, "_name") 17 | CACHED_STORAGE_GET_CACHE_NAME = getattr(CACHED_STORAGE_GET_CACHE, "_name") 18 | -------------------------------------------------------------------------------- /src/starkware/storage/names.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | from datetime import datetime 4 | from typing import Dict 5 | 6 | from starkware.starkware_utils.time.time import time 7 | 8 | 9 | def generate_unique_key(item_type: str, props: Dict[str, str] = {}) -> bytes: 10 | """ 11 | Generates a unique S3 storage key. 12 | """ 13 | suffix = datetime.utcfromtimestamp(time()).strftime("%H%M%S") 14 | t = datetime.fromtimestamp(time()) 15 | suffix += "_" + "".join(random.choices(string.ascii_lowercase + string.digits, k=8)) 16 | key = f"{t:year=%04Y/month=%02m/day=%02d}/type={item_type}" 17 | for prop, val in props.items(): 18 | key = f"{key}/{prop}={val}" 19 | key = f"{key}/{suffix}" 20 | return key.encode("ascii") 21 | -------------------------------------------------------------------------------- /src/starkware/storage/storage_utils.py: -------------------------------------------------------------------------------- 1 | import dataclasses 2 | 3 | from starkware.python.utils import from_bytes, to_bytes 4 | from starkware.starkware_utils.commitment_tree.leaf_fact import LeafFact 5 | from starkware.storage.storage import HashFunctionType 6 | 7 | 8 | @dataclasses.dataclass(frozen=True) 9 | class SimpleLeafFact(LeafFact): 10 | value: int 11 | 12 | @classmethod 13 | def prefix(cls) -> bytes: 14 | return b"leaf" 15 | 16 | def serialize(self) -> bytes: 17 | return to_bytes(self.value) 18 | 19 | def _hash(self, hash_func: HashFunctionType) -> bytes: 20 | return self.serialize() 21 | 22 | @classmethod 23 | def deserialize(cls, data: bytes) -> "SimpleLeafFact": 24 | return cls(from_bytes(data)) 25 | 26 | @classmethod 27 | def empty(cls) -> "SimpleLeafFact": 28 | return cls(value=0) 29 | 30 | @property 31 | def is_empty(self) -> bool: 32 | return self.value == 0 33 | -------------------------------------------------------------------------------- /src/third_party/pip/BUILD: -------------------------------------------------------------------------------- 1 | load("@cpython_reqs//:requirements.bzl", "all_requirements") 2 | load("@pypy_reqs//:requirements.bzl", pypy_all_requirements = "all_requirements") 3 | load("//bazel_utils/python:defs.bzl", "unify_requirements") 4 | 5 | [ 6 | alias( 7 | name = requirement, 8 | actual = select({ 9 | "//bazel_utils/python:pypy": "@pypy_reqs_" + requirement + "//:pkg", 10 | "//conditions:default": "@cpython_reqs_" + requirement + "//:pkg", 11 | }), 12 | visibility = ["//visibility:public"], 13 | ) 14 | for requirement in unify_requirements({ 15 | "cpython_reqs": all_requirements, 16 | "pypy_reqs": pypy_all_requirements, 17 | }) if requirement != "greenlet" 18 | ] 19 | -------------------------------------------------------------------------------- /vars.bzl: -------------------------------------------------------------------------------- 1 | ADDITIONAL_IMPORTS = [] 2 | --------------------------------------------------------------------------------