From 2e24b6a15704e038f4a15dfdb89c13ab14cba569 Mon Sep 17 00:00:00 2001 From: fmoletta <99273364+fmoletta@users.noreply.github.com> Date: Thu, 25 Apr 2024 17:44:58 -0300 Subject: [PATCH] Bump to 2.6.3 + Remove gas checks (#1709) * bumping compiler version and removing gas * Update cairo-lang dependencies to 2.6.3 * Update CasmContractClass import * Bump corelib * Un-comment additional_initialization * Allow return_type_id to be None * Compile with skip_auto_withdraw_gas * Use custom impl of poseidon_hash_many * Yeet create_metadata * Remove unused imports * Add missing imports * Remove additional initialization * Update lock * fix * Add instructions to add Scarb.toml setting in README * Add temp fix for nullable_box_vec * Ignore GasBuiltin when deserializng outputs * Add Known bugs & issues section * Fix run_dict_with_struct * Fix compilation for tests * Add changelog entry * Fix non-optional dependency --------- Co-authored-by: Ariel Elperin Co-authored-by: Pedro Fontana Co-authored-by: Pedro Fontana --- CHANGELOG.md | 5 + Cargo.lock | 121 ++++++++++------- Cargo.toml | 15 ++- cairo1-run/Cargo.toml | 7 +- cairo1-run/Makefile | 2 +- cairo1-run/README.md | 31 ++++- cairo1-run/src/cairo_run.rs | 126 +++++++----------- cairo1-run/src/main.rs | 13 +- .../cairo-1-programs/dict_with_struct.cairo | 10 +- .../cairo-1-programs/nullable_box_vec.cairo | 10 +- .../cairo-1-programs/poseidon.cairo | 27 +++- .../cairo-1-programs/poseidon_pedersen.cairo | 26 +++- vm/Cargo.toml | 2 + vm/src/tests/mod.rs | 2 +- vm/src/types/program.rs | 2 +- 15 files changed, 245 insertions(+), 154 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index be40ac5ccc..d0ee2b01da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,11 @@ * feat: Implement `CairoPie::read_zip_file`[#1729](https://github.com/lambdaclass/cairo-vm/pull/1729) +* feat: Bump to 2.6.3 + Remove gas checks[#1709](https://github.com/lambdaclass/cairo-vm/pull/1709) + * Bump cairo_lang crates & corelib to v2.6.3 + * Disable gas checks when compiling to sierra & casm + * Add `Known bugs & issues` segment to README, poining out issues derived from the removal of gas checks and cairo v2.6.3 + * feat: Implement running from `CairoPie`[#1720](https://github.com/lambdaclass/cairo-vm/pull/1720) * Add function `cairo_run_pie` * Add `CairoPie` methods `run_validity_checks` & `check_pie_compatibility` diff --git a/Cargo.lock b/Cargo.lock index 0625fe15a5..9ec6a683ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -482,9 +482,9 @@ dependencies = [ [[package]] name = "cairo-lang-casm" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ceb71a4cbf5b474bd671c79b2c05e8168a97199bfea1c01ef63b1bdaac3db03" +checksum = "10d9c31baeb6b52586b5adc88f01e90f86389d63d94363c562de5c79352e545b" dependencies = [ "cairo-lang-utils", "indoc", @@ -496,9 +496,9 @@ dependencies = [ [[package]] name = "cairo-lang-compiler" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95c1aab3213462c5b7c21508f1a4330bdf0766c90e6dd4ed79b0002c2b96a715" +checksum = "7148cb2d72a3db24a6d2ef2b2602102cc5099cb9f6b913e5047fb009cb3a22a1" dependencies = [ "anyhow", "cairo-lang-defs", @@ -513,23 +513,24 @@ dependencies = [ "cairo-lang-syntax", "cairo-lang-utils", "salsa", + "smol_str", "thiserror", ] [[package]] name = "cairo-lang-debug" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03623ba892200c6b3c55fab260d4aa0bff833d6bcecdb1fb022565ac00d5a683" +checksum = "5a761eb8e31ea65a2dd45f729c74f1770315f97124dad93d1f6853a10d460c6b" dependencies = [ "cairo-lang-utils", ] [[package]] name = "cairo-lang-defs" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09131755b08a485322656e061ad05602215a198dd4a2daf3897e64dc76e7544e" +checksum = "f6d60bc5d72fe7a95ba34e041dcbdf1cf3bfccb87008a515514b74913fa8ff05" dependencies = [ "cairo-lang-debug", "cairo-lang-diagnostics", @@ -544,9 +545,9 @@ dependencies = [ [[package]] name = "cairo-lang-diagnostics" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b8185cc9472c648ac9db970ce558595c71259eebd55d25a502fe569cb871448" +checksum = "356089e1b0a0ba9e115566191745613b3806a20259ad76764df82ab534d5412a" dependencies = [ "cairo-lang-debug", "cairo-lang-filesystem", @@ -556,9 +557,9 @@ dependencies = [ [[package]] name = "cairo-lang-eq-solver" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ae71750096b64d4dd54dd2c39ef50651bb4aff4bc829e3d07549a5035620e0a" +checksum = "fc43246cc2e5afd5a028bcdd63876ac3f8b1f4fb3ff785daaa0f0fbb51c9d906" dependencies = [ "cairo-lang-utils", "good_lp", @@ -566,9 +567,9 @@ dependencies = [ [[package]] name = "cairo-lang-filesystem" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1819ef5a5396df695dcec993500c46bc44c309590b503da26965c873dfe8a84a" +checksum = "6bcb9a4a40e53fa099774bd08bbcc3430f51213cc7fb1b50c2e9d01155731798" dependencies = [ "cairo-lang-debug", "cairo-lang-utils", @@ -580,9 +581,9 @@ dependencies = [ [[package]] name = "cairo-lang-lowering" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0968f0da6117dca1a70d6ac7d2e252d8b1710f333458c54ce08dbef1c0323881" +checksum = "1ba60e1e2477aa0f610ccf29189097d580464607c94b51741e1c18e64d6cee5f" dependencies = [ "cairo-lang-debug", "cairo-lang-defs", @@ -605,9 +606,9 @@ dependencies = [ [[package]] name = "cairo-lang-parser" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae556e49c0a90d30e52f068b0fb5ed4d419766661d3713a1644f3894a9255a5a" +checksum = "7f16ba1535e0cc5e79c2eff6592859bbdac03dc53d4dcdd26dbdbc04a77c3f5c" dependencies = [ "cairo-lang-diagnostics", "cairo-lang-filesystem", @@ -625,9 +626,9 @@ dependencies = [ [[package]] name = "cairo-lang-plugins" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8d319f3e84ff679159f97e3baa1d918d369ba9e3ade5ad490e0a9e4eca19591" +checksum = "81c8cf6e0ee3d6b19429cc1663738b22f1ecea7d51bf7452e8e1086f08798baf" dependencies = [ "cairo-lang-defs", "cairo-lang-diagnostics", @@ -644,9 +645,9 @@ dependencies = [ [[package]] name = "cairo-lang-proc-macros" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fef002aac874d76492eb9577dab663f9a84fe4584b4215c7ebfda7d025fcadae" +checksum = "67f9da66325ce7ed6c002360f26106fe79deb9f8a2fca30abdbb8d388da7bb46" dependencies = [ "cairo-lang-debug", "quote", @@ -655,9 +656,9 @@ dependencies = [ [[package]] name = "cairo-lang-project" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f384c26e6907de9c94b44051e386498159e8c9e1567b9b1eae9c22e16ff17e5" +checksum = "e198af1ab3d05c7fb8b6a9a7a2e9bce245a6c855df5f770b751d29874a23b152" dependencies = [ "cairo-lang-filesystem", "cairo-lang-utils", @@ -669,9 +670,9 @@ dependencies = [ [[package]] name = "cairo-lang-semantic" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "311434caae9542b7c442ac69a04e3c8eaa477654f215abe0bd7dfd3c0de70669" +checksum = "6d7df81521c2125e3e95b683cc99374db1aebd7ddb317c5ca3dd92a235a9eb13" dependencies = [ "cairo-lang-debug", "cairo-lang-defs", @@ -694,9 +695,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52c00c34fcaf97bbc4111d1631af8c65838841a38b3502b5bbc04355b7d46982" +checksum = "07da3ca1434c62a7cc7cd77d2941ef47a1c23b37325781b59407b78d8c61d863" dependencies = [ "anyhow", "cairo-felt", @@ -720,9 +721,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra-ap-change" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c99a0be021b359c51383cce4372cb1061f7d53438d80f208c56af2154583c98e" +checksum = "122c9055eb609a511178e3dce577de061819fd4c4c6b7452804557f76ca43bbf" dependencies = [ "cairo-lang-eq-solver", "cairo-lang-sierra", @@ -735,9 +736,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra-gas" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f273d4de9d30e556e72ebe2751f9ed6bf3d84a70f6c76f52b178c24cddb12e43" +checksum = "cf049d9aea65c6e38da219a3700c72f78795d11449d9adcec28047ef8d63bd23" dependencies = [ "cairo-lang-eq-solver", "cairo-lang-sierra", @@ -750,9 +751,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra-generator" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "734f72e9e8b1ec7a96208aa8dfba87ca1614188e3646ae67c519afe707569490" +checksum = "3e1d75e0830279ca1bd0189e3326720d6e081225f7d81ed060bbd22c6b37e980" dependencies = [ "cairo-lang-debug", "cairo-lang-defs", @@ -765,7 +766,7 @@ dependencies = [ "cairo-lang-syntax", "cairo-lang-utils", "itertools 0.11.0", - "num-bigint", + "num-traits 0.2.18", "once_cell", "salsa", "smol_str", @@ -773,9 +774,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra-to-casm" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "842ae37ee3f1cd06b926aceb480fd70b84300aae82e9606b876678d30c21649a" +checksum = "6a3c3be88c8562fbf93b0803c186e7282f6daad93576c07f61b04a591fde468f" dependencies = [ "assert_matches", "cairo-felt", @@ -794,9 +795,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra-type-size" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f969cbaf81f3beb1dc693674fc792a815bf8fc13471227020a5faf309d5faf80" +checksum = "a38da6f98c6b16945c89d2ae351c82d636ed38d3e6eb02f7c8679e3e03a63988" dependencies = [ "cairo-lang-sierra", "cairo-lang-utils", @@ -804,13 +805,12 @@ dependencies = [ [[package]] name = "cairo-lang-starknet" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67cd2d120f39369c7bd7d124dee638c250495054030d01d4e1d1b88f0063bd80" +checksum = "2c9ffa8b3b8c47138c36b1907cebb5047dfc4de29ec10ece5bd6d6853243ec50" dependencies = [ "anyhow", "cairo-felt", - "cairo-lang-casm", "cairo-lang-compiler", "cairo-lang-defs", "cairo-lang-diagnostics", @@ -820,14 +820,33 @@ dependencies = [ "cairo-lang-semantic", "cairo-lang-sierra", "cairo-lang-sierra-generator", - "cairo-lang-sierra-to-casm", + "cairo-lang-starknet-classes", "cairo-lang-syntax", "cairo-lang-utils", "const_format", - "convert_case", "indent", "indoc", "itertools 0.11.0", + "once_cell", + "serde", + "serde_json", + "smol_str", + "thiserror", +] + +[[package]] +name = "cairo-lang-starknet-classes" +version = "2.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47c64ae2bb00173e3a88760128bf72de356fa80eb19fa47602479063648b4003" +dependencies = [ + "cairo-felt", + "cairo-lang-casm", + "cairo-lang-sierra", + "cairo-lang-sierra-to-casm", + "cairo-lang-utils", + "convert_case", + "itertools 0.11.0", "num-bigint", "num-integer", "num-traits 0.2.18", @@ -842,9 +861,9 @@ dependencies = [ [[package]] name = "cairo-lang-syntax" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "552d3438fec55832976bc7c7d7490100e8ce7385d3f3f1539f9a46fffa2197c6" +checksum = "8262c426a57e1e5ec297db24278464841500613445e2cb1c43d5f71ad91ee8d6" dependencies = [ "cairo-lang-debug", "cairo-lang-filesystem", @@ -858,9 +877,9 @@ dependencies = [ [[package]] name = "cairo-lang-syntax-codegen" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dab4d07bd78658f0fdc3fd20f1236bc3e6ebdd8a8fc72ece95a5dd03b7a09da" +checksum = "70e2d692eae4bb4179a4a1148fd5eb738a91653d86750c813658ffad4a99fa97" dependencies = [ "genco", "xshell", @@ -868,9 +887,9 @@ dependencies = [ [[package]] name = "cairo-lang-utils" -version = "2.5.4" +version = "2.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12d0939f42d40fb1d975cae073d7d4f82d83de4ba2149293115525245425f909" +checksum = "bf733a7cdc4166d0baf0ed8a98d9ada827daee6653b37d9326e334e53481c6d3" dependencies = [ "hashbrown 0.14.3", "indexmap 2.2.3", @@ -894,6 +913,7 @@ dependencies = [ "bitvec", "cairo-lang-casm", "cairo-lang-starknet", + "cairo-lang-starknet-classes", "clap", "criterion", "generic-array", @@ -969,6 +989,7 @@ dependencies = [ "cairo-lang-sierra-gas", "cairo-lang-sierra-to-casm", "cairo-lang-sierra-type-size", + "cairo-lang-starknet-classes", "cairo-lang-utils", "cairo-vm", "clap", diff --git a/Cargo.toml b/Cargo.toml index f3825f5efa..d9d516a08c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,14 +66,15 @@ thiserror-no-std = { version = "2.0.2", default-features = false } bitvec = { version = "1", default-features = false, features = ["alloc"] } # Dependencies for cairo-1-hints feature -cairo-lang-starknet = { version = "2.5.4", default-features = false } -cairo-lang-casm = { version = "2.5.4", default-features = false } +cairo-lang-starknet = { version = "2.6.3", default-features = false } +cairo-lang-casm = { version = "2.6.3", default-features = false } -cairo-lang-compiler = { version = "2.5.4", default-features = false } -cairo-lang-sierra-to-casm = { version = "2.5.4", default-features = false } -cairo-lang-sierra = { version = "2.5.4", default-features = false } -cairo-lang-runner = { version = "2.5.4", default-features = false } -cairo-lang-utils = { version = "2.5.4", default-features = false } +cairo-lang-starknet-classes = { version = "2.6.3", default-features = false } +cairo-lang-compiler = { version = "2.6.3", default-features = false } +cairo-lang-sierra-to-casm = { version = "2.6.3", default-features = false } +cairo-lang-sierra = { version = "2.6.3", default-features = false } +cairo-lang-runner = { version = "2.6.3", default-features = false } +cairo-lang-utils = { version = "2.6.3", default-features = false } # TODO: check these dependencies for wasm compatibility ark-ff = { version = "0.4.2", default-features = false } diff --git a/cairo1-run/Cargo.toml b/cairo1-run/Cargo.toml index ff1d0eb9fe..43bc52d019 100644 --- a/cairo1-run/Cargo.toml +++ b/cairo1-run/Cargo.toml @@ -12,9 +12,10 @@ keywords.workspace = true cairo-vm = {workspace = true, features = ["std", "cairo-1-hints", "clap"]} serde_json = { workspace = true } -cairo-lang-sierra-type-size = { version = "2.5.4", default-features = false } -cairo-lang-sierra-ap-change = { version = "2.5.4", default-features = false } -cairo-lang-sierra-gas = { version = "2.5.4", default-features = false } +cairo-lang-sierra-type-size = { version = "2.6.3", default-features = false } +cairo-lang-sierra-ap-change = { version = "2.6.3", default-features = false } +cairo-lang-sierra-gas = { version = "2.6.3", default-features = false } +cairo-lang-starknet-classes.workspace = true cairo-lang-sierra-to-casm.workspace = true cairo-lang-compiler.workspace = true cairo-lang-sierra.workspace = true diff --git a/cairo1-run/Makefile b/cairo1-run/Makefile index c2869d9972..c6d1d58484 100644 --- a/cairo1-run/Makefile +++ b/cairo1-run/Makefile @@ -15,7 +15,7 @@ MEMORY:=$(patsubst $(CAIRO_1_FOLDER)/%.cairo, $(CAIRO_1_FOLDER)/%.memory, $(CAIR deps: git clone https://github.com/starkware-libs/cairo.git \ && cd cairo \ - && git checkout v2.5.4 \ + && git checkout v2.6.3 \ && cd .. \ && mv cairo/corelib/ . \ && rm -rf cairo/ diff --git a/cairo1-run/README.md b/cairo1-run/README.md index e4aafd4f6b..1ec32d61b8 100644 --- a/cairo1-run/README.md +++ b/cairo1-run/README.md @@ -71,8 +71,14 @@ The cairo1-run cli supports the following optional arguments: # Running scarb projects -First compile your project running `scarb build` +As cairo1-run skips gas checks when running, you will need to add the following to your Scarb.toml to ensure that compilation is done without adding gas checks: + +```toml +[cairo] +enable-gas = false +``` +First compile your project running `scarb build` Then run the compiled project's sierra file located at `project_name/target/project_name.sierra.json` @@ -80,3 +86,26 @@ Example: ```bash cargo run path-to-project/target/project_name.sierra.json ``` + +# Known bugs & issues + +## Libfunc `get_builtin_costs` & function `poseidon_hash_many` +Compiling without gas checks removes libfuncs associated with gas checks that are generated during compilation but it cannot remove those in the cairo code itself. Therefore code using the external functions on the `gas` corelib moudle (`withdraw_gas`, `withdraw_gas_all` & `get_builtin_costs`) will fail to compile. +One notable case of this issue is the `poseidon_hash_span` function, which uses `get_builtin_costs` in its implementation. We advise using the `HashStateTrait` impl instead. The `poseidon_hash_span` function can also be modified so that it no longer relies on gas, an example of this can be found on the test file `poseidon.cairo` under the `cairo_porgrams/cairo-1-programs` folder. + +## Nullable> +There is currently a bug in cairo 2.6.3 affecting `Nullable>` types. +Tracking issue: https://github.com/starkware-libs/cairo/issues/5411 + +Proposed solution: + +Add the helper function: +``` +#[inline(never)] +fn identity(t: T) -> T { t } +``` + +And use it when creating the `Nullable>`: +``` +NullableTrait::::new(BoxTrait::new(identity(value))) +``` diff --git a/cairo1-run/src/cairo_run.rs b/cairo1-run/src/cairo_run.rs index d4f46d4bac..97700bbc91 100644 --- a/cairo1-run/src/cairo_run.rs +++ b/cairo1-run/src/cairo_run.rs @@ -13,7 +13,7 @@ use cairo_lang_sierra::{ bitwise::BitwiseType, core::{CoreLibfunc, CoreType}, ec::EcOpType, - gas::{CostTokenType, GasBuiltinType}, + gas::GasBuiltinType, pedersen::PedersenType, poseidon::PoseidonType, range_check::RangeCheckType, @@ -25,11 +25,10 @@ use cairo_lang_sierra::{ program::{Function, GenericArg, Program as SierraProgram}, program_registry::ProgramRegistry, }; -use cairo_lang_sierra_ap_change::calc_ap_changes; -use cairo_lang_sierra_gas::{gas_info::GasInfo, objects::CostInfoProvider}; +use cairo_lang_sierra_gas::objects::CostInfoProvider; use cairo_lang_sierra_to_casm::{ - compiler::CairoProgram, - metadata::{calc_metadata, Metadata, MetadataComputationConfig, MetadataError}, + compiler::{CairoProgram, SierraToCasmConfig}, + metadata::calc_metadata_ap_change_only, }; use cairo_lang_sierra_type_size::get_type_size_map; use cairo_lang_utils::{casts::IntoOrPanic, unordered_hash_map::UnorderedHashMap}; @@ -123,12 +122,17 @@ pub fn cairo_run_program( ), Error, > { - let metadata = create_metadata(sierra_program, Some(Default::default()))?; + let metadata = calc_metadata_ap_change_only(sierra_program) + .map_err(|_| VirtualMachineError::Unexpected)?; let sierra_program_registry = ProgramRegistry::::new(sierra_program)?; let type_sizes = get_type_size_map(sierra_program, &sierra_program_registry).unwrap_or_default(); + let config = SierraToCasmConfig { + gas_usage_check: false, + max_bytecode_size: usize::MAX, + }; let casm_program = - cairo_lang_sierra_to_casm::compiler::compile(sierra_program, &metadata, true)?; + cairo_lang_sierra_to_casm::compiler::compile(sierra_program, &metadata, config)?; let main_func = find_function(sierra_program, "::main")?; @@ -146,15 +150,11 @@ pub fn cairo_run_program( )?; // Fetch return type data - let return_type_id = main_func - .signature - .ret_types - .last() - .ok_or(Error::NoRetTypesInSignature)?; - let return_type_size = type_sizes - .get(return_type_id) - .cloned() - .ok_or_else(|| Error::NoTypeSizeForId(return_type_id.clone()))?; + + let return_type_id = main_func.signature.ret_types.last(); + let return_type_size = return_type_id + .and_then(|id| type_sizes.get(id).cloned()) + .unwrap_or_default(); // This footer is used by lib funcs let libfunc_footer = create_code_footer(); @@ -178,8 +178,6 @@ pub fn cairo_run_program( .map(MaybeRelocatable::from) .collect(); - let data_len = data.len(); - let program = if cairo_run_config.proof_mode { Program::new_for_proof( builtins.clone(), @@ -221,8 +219,6 @@ pub fn cairo_run_program( let mut vm = VirtualMachine::new(cairo_run_config.trace_enabled); let end = runner.initialize(&mut vm, cairo_run_config.proof_mode)?; - additional_initialization(&mut vm, data_len)?; - // Run it until the end / infinite loop in proof_mode runner.run_until_pc(end, &mut vm, &mut hint_processor)?; if cairo_run_config.proof_mode { @@ -287,26 +283,6 @@ pub fn cairo_run_program( Ok((runner, vm, return_values, serialized_output)) } -fn additional_initialization(vm: &mut VirtualMachine, data_len: usize) -> Result<(), Error> { - // Create the builtin cost segment - let builtin_cost_segment = vm.add_memory_segment(); - for token_type in CostTokenType::iter_precost() { - vm.insert_value( - (builtin_cost_segment + (token_type.offset_in_builtin_costs() as usize)) - .map_err(VirtualMachineError::Math)?, - Felt252::default(), - )? - } - // Put a pointer to the builtin cost segment at the end of the program (after the - // additional `ret` statement). - vm.insert_value( - (vm.get_pc() + data_len).map_err(VirtualMachineError::Math)?, - builtin_cost_segment, - )?; - - Ok(()) -} - #[allow(clippy::type_complexity)] fn build_hints_vec<'b>( instructions: impl Iterator, @@ -518,14 +494,10 @@ fn create_entry_code( casm_build_extend!(ctx, let () = call FUNCTION;); - let return_type_id = signature - .ret_types - .last() - .ok_or(Error::NoRetTypesInSignature)?; - let return_type_size = type_sizes - .get(return_type_id) - .cloned() - .ok_or_else(|| Error::NoTypeSizeForId(return_type_id.clone()))?; + let return_type_id = signature.ret_types.last(); + let return_type_size = return_type_id + .and_then(|id| type_sizes.get(id).cloned()) + .unwrap_or_default(); let mut offset: i16 = 0; for ty in signature.ret_types.iter().rev() { let info = get_info(sierra_program_registry, ty) @@ -660,28 +632,6 @@ fn get_info<'a>( .map(|ctc| ctc.info()) } -/// Creates the metadata required for a Sierra program lowering to casm. -fn create_metadata( - sierra_program: &cairo_lang_sierra::program::Program, - metadata_config: Option, -) -> Result { - if let Some(metadata_config) = metadata_config { - calc_metadata(sierra_program, metadata_config).map_err(|err| match err { - MetadataError::ApChangeError(_) => VirtualMachineError::Unexpected, - MetadataError::CostError(_) => VirtualMachineError::Unexpected, - }) - } else { - Ok(Metadata { - ap_change_info: calc_ap_changes(sierra_program, |_, _| 0) - .map_err(|_| VirtualMachineError::Unexpected)?, - gas_info: GasInfo { - variable_values: Default::default(), - function_costs: Default::default(), - }, - }) - } -} - fn get_function_builtins( params: &[cairo_lang_sierra::ids::ConcreteTypeId], append_output: bool, @@ -718,7 +668,7 @@ fn get_function_builtins( fn fetch_return_values( return_type_size: i16, - return_type_id: &ConcreteTypeId, + return_type_id: Option<&ConcreteTypeId>, vm: &VirtualMachine, builtin_count: i16, fetch_from_output: bool, @@ -737,10 +687,12 @@ fn fetch_return_values( }; // Check if this result is a Panic result if return_type_id - .debug_name - .as_ref() - .ok_or_else(|| Error::TypeIdNoDebugName(return_type_id.clone()))? - .starts_with("core::panics::PanicResult::") + .and_then(|id| { + id.debug_name + .as_ref() + .map(|name| name.starts_with("core::panics::PanicResult::")) + }) + .unwrap_or_default() { // Check the failure flag (aka first return value) if return_values.first() != Some(&MaybeRelocatable::from(0)) { @@ -822,11 +774,16 @@ fn finalize_builtins( fn serialize_output( return_values: &[MaybeRelocatable], vm: &mut VirtualMachine, - return_type_id: &ConcreteTypeId, + return_type_id: Option<&ConcreteTypeId>, sierra_program_registry: &ProgramRegistry, type_sizes: &UnorderedHashMap, ) -> String { let mut output_string = String::new(); + let return_type_id = if let Some(id) = return_type_id { + id + } else { + return output_string; + }; let mut return_values_iter = return_values.iter().peekable(); serialize_output_inner( &mut return_values_iter, @@ -1174,6 +1131,10 @@ fn serialize_output_inner<'a>( type_sizes, ) } + cairo_lang_sierra::extensions::core::CoreTypeConcrete::GasBuiltin(_info) => { + // Ignore it + let _ = return_values_iter.next(); + }, _ => panic!("Unexpected return type") } } @@ -1189,7 +1150,9 @@ mod tests { use std::path::Path; use super::*; - use cairo_lang_compiler::{compile_cairo_project_at_path, CompilerConfig}; + use cairo_lang_compiler::{ + compile_prepared_db, db::RootDatabase, project::setup_project, CompilerConfig, + }; use cairo_vm::types::relocatable::Relocatable; use rstest::rstest; @@ -1198,8 +1161,13 @@ mod tests { replace_ids: true, ..CompilerConfig::default() }; - - compile_cairo_project_at_path(Path::new(filename), compiler_config).unwrap() + let mut db = RootDatabase::builder() + .detect_corelib() + .skip_auto_withdraw_gas() + .build() + .unwrap(); + let main_crate_ids = setup_project(&mut db, Path::new(filename)).unwrap(); + compile_prepared_db(&mut db, main_crate_ids, compiler_config).unwrap() } fn main_hash_panic_result(sierra_program: &SierraProgram) -> bool { diff --git a/cairo1-run/src/main.rs b/cairo1-run/src/main.rs index 310e8d490d..a5045b8642 100644 --- a/cairo1-run/src/main.rs +++ b/cairo1-run/src/main.rs @@ -1,7 +1,9 @@ use bincode::enc::write::Writer; use cairo1_run::error::Error; use cairo1_run::{cairo_run_program, Cairo1RunConfig, FuncArg}; -use cairo_lang_compiler::{compile_cairo_project_at_path, CompilerConfig}; +use cairo_lang_compiler::{ + compile_prepared_db, db::RootDatabase, project::setup_project, CompilerConfig, +}; use cairo_vm::{ air_public_input::PublicInputError, types::layout_name::LayoutName, vm::errors::trace_errors::TraceError, Felt252, @@ -150,8 +152,13 @@ fn run(args: impl Iterator) -> Result, Error> { replace_ids: true, ..CompilerConfig::default() }; - compile_cairo_project_at_path(&args.filename, compiler_config) - .map_err(|err| Error::SierraCompilation(err.to_string()))? + let mut db = RootDatabase::builder() + .detect_corelib() + .skip_auto_withdraw_gas() + .build() + .unwrap(); + let main_crate_ids = setup_project(&mut db, &args.filename).unwrap(); + compile_prepared_db(&mut db, main_crate_ids, compiler_config).unwrap() } }; diff --git a/cairo_programs/cairo-1-programs/dict_with_struct.cairo b/cairo_programs/cairo-1-programs/dict_with_struct.cairo index 9f24aade67..c085198888 100644 --- a/cairo_programs/cairo-1-programs/dict_with_struct.cairo +++ b/cairo_programs/cairo-1-programs/dict_with_struct.cairo @@ -11,9 +11,9 @@ fn main() -> SquashedFelt252Dict> { // Create the dictionary let mut d: Felt252Dict> = Default::default(); - let box_a = BoxTrait::new(FP16x16 { mag: 1, sign: false }); - let box_b = BoxTrait::new(FP16x16 { mag: 1, sign: true }); - let box_c = BoxTrait::new(FP16x16 { mag: 1, sign: true }); + let box_a = BoxTrait::new(identity(FP16x16 { mag: 1, sign: false })); + let box_b = BoxTrait::new(identity(FP16x16 { mag: 1, sign: true })); + let box_c = BoxTrait::new(identity(FP16x16 { mag: 1, sign: true })); // Insert it as a `Span` d.insert(0, nullable_from_box(box_c)); @@ -22,3 +22,7 @@ fn main() -> SquashedFelt252Dict> { d.squash() } + +// TODO: remove this temporary fixed once fixed in cairo +#[inline(never)] +fn identity(t: T) -> T { t } diff --git a/cairo_programs/cairo-1-programs/nullable_box_vec.cairo b/cairo_programs/cairo-1-programs/nullable_box_vec.cairo index f051270e2d..a26704bfd3 100644 --- a/cairo_programs/cairo-1-programs/nullable_box_vec.cairo +++ b/cairo_programs/cairo-1-programs/nullable_box_vec.cairo @@ -7,9 +7,9 @@ fn main() -> NullableVec { let mut d: Felt252Dict>> = Default::default(); // Populate the dictionary - d.insert(0, nullable_from_box(BoxTrait::new(BoxTrait::new(10)))); - d.insert(1, nullable_from_box(BoxTrait::new(BoxTrait::new(20)))); - d.insert(2, nullable_from_box(BoxTrait::new(BoxTrait::new(30)))); + d.insert(0, nullable_from_box(BoxTrait::new(BoxTrait::new(identity(10))))); + d.insert(1, nullable_from_box(BoxTrait::new(BoxTrait::new(identity(20))))); + d.insert(2, nullable_from_box(BoxTrait::new(BoxTrait::new(identity(30))))); // Return NullableVec NullableVec { @@ -17,3 +17,7 @@ fn main() -> NullableVec { len: 3, } } + +// TODO: remove this temporary fixed once fixed in cairo +#[inline(never)] +fn identity(t: T) -> T { t } diff --git a/cairo_programs/cairo-1-programs/poseidon.cairo b/cairo_programs/cairo-1-programs/poseidon.cairo index 96a3c8beef..857f28ee73 100644 --- a/cairo_programs/cairo-1-programs/poseidon.cairo +++ b/cairo_programs/cairo-1-programs/poseidon.cairo @@ -1,7 +1,9 @@ use core::felt252; -use core::poseidon::poseidon_hash_span; use array::ArrayTrait; use array::SpanTrait; +use core::hash::HashStateTrait; +use core::poseidon::{hades_permutation, HashState}; + fn main() -> felt252 { let mut data: Array = ArrayTrait::new(); @@ -12,3 +14,26 @@ fn main() -> felt252 { poseidon_hash_span(data.span()) } + +// Modified version of poseidon_hash_span that doesn't require builtin gas costs +pub fn poseidon_hash_span(mut span: Span) -> felt252 { + _poseidon_hash_span_inner((0, 0, 0), ref span) +} + +/// Helper function for poseidon_hash_span. +fn _poseidon_hash_span_inner( + state: (felt252, felt252, felt252), + ref span: Span +) -> felt252 { + let (s0, s1, s2) = state; + let x = *match span.pop_front() { + Option::Some(x) => x, + Option::None => { return HashState { s0, s1, s2, odd: false }.finalize(); }, + }; + let y = *match span.pop_front() { + Option::Some(y) => y, + Option::None => { return HashState { s0: s0 + x, s1, s2, odd: true }.finalize(); }, + }; + let next_state = hades_permutation(s0 + x, s1 + y, s2); + _poseidon_hash_span_inner(next_state, ref span) +} diff --git a/cairo_programs/cairo-1-programs/poseidon_pedersen.cairo b/cairo_programs/cairo-1-programs/poseidon_pedersen.cairo index c78820c63a..c7b6210cf5 100644 --- a/cairo_programs/cairo-1-programs/poseidon_pedersen.cairo +++ b/cairo_programs/cairo-1-programs/poseidon_pedersen.cairo @@ -1,8 +1,9 @@ use core::felt252; -use core::poseidon::poseidon_hash_span; use array::ArrayTrait; use array::SpanTrait; use core::pedersen::pedersen; +use core::hash::HashStateTrait; +use core::poseidon::{hades_permutation, HashState}; fn main() -> felt252 { let mut data: Array = ArrayTrait::new(); @@ -14,3 +15,26 @@ fn main() -> felt252 { let res = poseidon_hash_span(data.span()); pedersen(res, 0) } + +// Modified version of poseidon_hash_span that doesn't require builtin gas costs +pub fn poseidon_hash_span(mut span: Span) -> felt252 { + _poseidon_hash_span_inner((0, 0, 0), ref span) +} + +/// Helper function for poseidon_hash_span. +fn _poseidon_hash_span_inner( + state: (felt252, felt252, felt252), + ref span: Span +) -> felt252 { + let (s0, s1, s2) = state; + let x = *match span.pop_front() { + Option::Some(x) => x, + Option::None => { return HashState { s0, s1, s2, odd: false }.finalize(); }, + }; + let y = *match span.pop_front() { + Option::Some(y) => y, + Option::None => { return HashState { s0: s0 + x, s1, s2, odd: true }.finalize(); }, + }; + let next_state = hades_permutation(s0 + x, s1 + y, s2); + _poseidon_hash_span_inner(next_state, ref span) +} diff --git a/vm/Cargo.toml b/vm/Cargo.toml index 579f5c0298..a6bc143d75 100644 --- a/vm/Cargo.toml +++ b/vm/Cargo.toml @@ -23,6 +23,7 @@ std = [ cairo-1-hints = [ "dep:cairo-lang-starknet", "dep:cairo-lang-casm", + "dep:cairo-lang-starknet-classes", "dep:ark-ff", "dep:ark-std", ] @@ -71,6 +72,7 @@ bitvec = { workspace = true } # Dependencies for cairo-1-hints feature cairo-lang-starknet = { workspace = true, optional = true } +cairo-lang-starknet-classes = { workspace = true, optional = true } cairo-lang-casm = { workspace = true, optional = true } # TODO: check these dependencies for wasm compatibility diff --git a/vm/src/tests/mod.rs b/vm/src/tests/mod.rs index b2d95c3df6..4d1e37bde1 100644 --- a/vm/src/tests/mod.rs +++ b/vm/src/tests/mod.rs @@ -16,7 +16,7 @@ use crate::{ }, }; #[cfg(feature = "cairo-1-hints")] -use cairo_lang_starknet::casm_contract_class::CasmContractClass; +use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use crate::stdlib::prelude::*; diff --git a/vm/src/types/program.rs b/vm/src/types/program.rs index 34e332afe9..e8b14fd877 100644 --- a/vm/src/types/program.rs +++ b/vm/src/types/program.rs @@ -26,7 +26,7 @@ use crate::{ }, }; #[cfg(feature = "cairo-1-hints")] -use cairo_lang_starknet::casm_contract_class::CasmContractClass; +use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use core::num::NonZeroUsize; #[cfg(feature = "std")]