diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2a5060004a..2849d6e24b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -148,31 +148,11 @@ jobs: path: "target/release/native_blockifier.pypy39-pp73-x86_64-linux-gnu.so" destination: "native_blockifier_artifacts/${{ env.SHORT_HASH }}/release/" + # Keep the name 'udeps' to match original action name, so we don't need to define specific branch + # rules on Github for specific version branches. udeps: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@master - name: "Rust Toolchain Setup" - with: - toolchain: nightly-2024-01-12 - - # Setup pypy and link to the location expected by .cargo/config.toml. - - uses: actions/setup-python@v5 - id: setup-pypy - with: - python-version: 'pypy3.9' - - run: ln -s '${{ steps.setup-pypy.outputs.python-path }}' /usr/local/bin/pypy3.9 - - env: - LD_LIBRARY_PATH: ${{ steps.setup-pypy.outputs.pythonLocation }}/bin - run: echo "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}" >> $GITHUB_ENV - - - uses: Swatinem/rust-cache@v2 - id: "cache-cargo" - - if: ${{ steps.cache-cargo.outputs.cache-hit != 'true' }} - name: "Download and run cargo-udeps" - run: | - wget -O - -c https://github.com/est31/cargo-udeps/releases/download/v0.1.45/cargo-udeps-v0.1.45-x86_64-unknown-linux-gnu.tar.gz | tar -xz - cargo-udeps-*/cargo-udeps udeps - env: - RUSTUP_TOOLCHAIN: nightly-2024-01-12 + - name: Run Machete (detect unused dependencies) + uses: bnjbvr/cargo-machete@main diff --git a/Cargo.lock b/Cargo.lock index a858a9513d..afb622cb0b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,17 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + [[package]] name = "ahash" version = "0.7.7" @@ -57,47 +68,48 @@ checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" [[package]] name = "anstream" -version = "0.6.5" +version = "0.6.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d664a92ecae85fd0a7392615844904654d1d5f5514837f471ddef4a057aba1b6" +checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", + "is_terminal_polyfill", "utf8parse", ] [[package]] name = "anstyle" -version = "1.0.4" +version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" +checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b" [[package]] name = "anstyle-parse" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" +checksum = "c03a11a9034d92058ceb6ee011ce58af4a9bf61491aa7e1e59ecd24bd40d22d4" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.0.2" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" +checksum = "ad186efb764318d35165f1758e7dcef3b10628e26d41a44bc5550652e6804391" dependencies = [ "windows-sys 0.52.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.2" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" +checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" dependencies = [ "anstyle", "windows-sys 0.52.0", @@ -105,15 +117,15 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.79" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "080e9890a082662b09c1ad45f567faeeb47f22b5fb23895fbe1e651e718e25ca" +checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" [[package]] name = "arc-swap" -version = "1.6.0" +version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6" +checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457" [[package]] name = "ark-ec" @@ -128,7 +140,7 @@ dependencies = [ "derivative", "hashbrown 0.13.2", "itertools 0.10.5", - "num-traits 0.2.17", + "num-traits 0.2.19", "zeroize", ] @@ -145,8 +157,8 @@ dependencies = [ "derivative", "digest", "itertools 0.10.5", - "num-bigint 0.4.4", - "num-traits 0.2.17", + "num-bigint", + "num-traits 0.2.19", "paste", "rustc_version", "zeroize", @@ -168,8 +180,8 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7abe79b0e4288889c4574159ab790824d0033b9fdcb2a112a3182fac2e514565" dependencies = [ - "num-bigint 0.4.4", - "num-traits 0.2.17", + "num-bigint", + "num-traits 0.2.19", "proc-macro2", "quote", "syn 1.0.109", @@ -219,7 +231,7 @@ dependencies = [ "ark-serialize-derive", "ark-std", "digest", - "num-bigint 0.4.4", + "num-bigint", ] [[package]] @@ -239,8 +251,8 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94893f1e0c6eeab764ade8dc4c0db24caf4fe7cbbaafc0eba0a9030f447b5185" dependencies = [ - "num-traits 0.2.17", - "rand 0.8.5", + "num-traits 0.2.19", + "rand", ] [[package]] @@ -272,7 +284,7 @@ checksum = "c980ee35e870bd1a4d2c8294d4c04d0499e67bca1e4b5cefcc693c2fa00caea9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] @@ -286,15 +298,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "autocfg" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dde43e75fd43e8a1bf86103336bc699aa8d17ad1be60c76c0bdfd4828e19b78" -dependencies = [ - "autocfg 1.1.0", -] - [[package]] name = "autocfg" version = "1.1.0" @@ -316,6 +319,12 @@ dependencies = [ "rustc-demangle", ] +[[package]] +name = "base64ct" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" + [[package]] name = "bincode" version = "2.0.0-rc.3" @@ -342,7 +351,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] @@ -395,7 +404,7 @@ dependencies = [ [[package]] name = "blockifier" -version = "0.7.0-dev.1" +version = "0.8.0-dev.1" dependencies = [ "anyhow", "ark-ec", @@ -404,7 +413,6 @@ dependencies = [ "ark-secp256r1", "assert_matches", "cached", - "cairo-felt", "cairo-lang-casm", "cairo-lang-runner", "cairo-lang-starknet-classes", @@ -413,25 +421,25 @@ dependencies = [ "criterion", "derive_more", "glob", - "indexmap 2.1.0", + "indexmap 2.2.6", "itertools 0.10.5", "keccak", "log", - "num-bigint 0.4.4", + "num-bigint", "num-integer", - "num-rational 0.4.1", - "num-traits 0.2.17", + "num-rational", + "num-traits 0.2.19", "once_cell", "phf", "pretty_assertions", - "rand 0.8.5", + "rand", "regex", "rstest", "serde", "serde_json", "sha2", "sha3", - "starknet-crypto 0.5.2", + "starknet-types-core", "starknet_api", "strum", "strum_macros 0.24.3", @@ -440,6 +448,16 @@ dependencies = [ "tikv-jemallocator", ] +[[package]] +name = "bstr" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05efc5cfd9110c8416e471df0e96702d58690178e206e61b7173706673c93706" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "bumpalo" version = "3.14.0" @@ -460,9 +478,30 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.5.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" +checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" + +[[package]] +name = "bzip2" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8" +dependencies = [ + "bzip2-sys", + "libc", +] + +[[package]] +name = "bzip2-sys" +version = "0.1.11+1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "736a955f3fa7875102d57c82b8cac37ec45224a07fd32d58f9f7a186b6cd4cdc" +dependencies = [ + "cc", + "libc", + "pkg-config", +] [[package]] name = "cached" @@ -500,38 +539,25 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a4f925191b4367301851c6d99b09890311d74b0d43f274c0b34c86d308a3663" -[[package]] -name = "cairo-felt" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae932292b9ba497a4e892b56aa4e0c6f329a455180fdbdc132700dfe68d9b153" -dependencies = [ - "lazy_static", - "num-bigint 0.4.4", - "num-integer", - "num-traits 0.2.17", - "serde", -] - [[package]] name = "cairo-lang-casm" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed99c41d458d27dd6d42eed29c57c09e8e6d7c70e546b61cb4bfdb9842d0a279" +checksum = "c2faefea599ed16d71262ad60b66c8b8e081b83e08d141ae9f8da98240a3dabd" dependencies = [ "cairo-lang-utils", - "indoc 2.0.4", - "num-bigint 0.4.4", - "num-traits 0.2.17", + "indoc 2.0.5", + "num-bigint", + "num-traits 0.2.19", "parity-scale-codec", "serde", ] [[package]] name = "cairo-lang-compiler" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "064f1515038f0496a52a3def9c11879491f76b72cb064d28b9fb6d5e4557ba8a" +checksum = "4cf77e43ec3e249676db8d10de69c0013a01b5bd898b003e53b7477fe4a257f4" dependencies = [ "anyhow", "cairo-lang-defs", @@ -545,6 +571,7 @@ dependencies = [ "cairo-lang-sierra-generator", "cairo-lang-syntax", "cairo-lang-utils", + "indoc 2.0.5", "salsa", "smol_str", "thiserror", @@ -552,18 +579,18 @@ dependencies = [ [[package]] name = "cairo-lang-debug" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d3179c07c03cb5d9a36f3ed7e7402bdfe16b9d0de5a960a9fd598a356032be0" +checksum = "69a2ccc456d6d6be5c45b94d7f0da5da573e888adf4dece38fe5768910d4c4fd" dependencies = [ "cairo-lang-utils", ] [[package]] name = "cairo-lang-defs" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a52a7e66818a41ad4332f07fbd7aba09522c2f05e0436dc7ceb2c989067a5e41" +checksum = "70270a8df40452784d2b9943f09bb17e0241f0d2d5b51e80e43bbab0f09d43fe" dependencies = [ "cairo-lang-debug", "cairo-lang-diagnostics", @@ -571,28 +598,28 @@ dependencies = [ "cairo-lang-parser", "cairo-lang-syntax", "cairo-lang-utils", - "itertools 0.11.0", + "itertools 0.12.1", "salsa", "smol_str", ] [[package]] name = "cairo-lang-diagnostics" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dfe5fc09df15dd815f09257ac7fe2cbfce775ea992b699f4d76f475538d402d" +checksum = "cf54b7d11b9c4be3f7b9fa15ae6912c2b830a404983b21dbfea7503cc7a0a96d" dependencies = [ "cairo-lang-debug", "cairo-lang-filesystem", "cairo-lang-utils", - "itertools 0.11.0", + "itertools 0.12.1", ] [[package]] name = "cairo-lang-eq-solver" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae770ae2d5ae2f4b6202137dc3a4053f89ad635ae0328a8f4807a3c5856f2ae9" +checksum = "83adfb83ff9c2f2b2df81f80ac0c4c0ee4f23a3ee2898e186bddf838f0d76896" dependencies = [ "cairo-lang-utils", "good_lp", @@ -600,9 +627,9 @@ dependencies = [ [[package]] name = "cairo-lang-filesystem" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fee331de8d8dfddcdb015e86be282819d9c93ee2925f3f188d9af41455dda30d" +checksum = "56daeeed88b6d8358701a3d47b33374fd2a019596bb9a0864d0278cd41004fc8" dependencies = [ "cairo-lang-debug", "cairo-lang-utils", @@ -612,11 +639,32 @@ dependencies = [ "smol_str", ] +[[package]] +name = "cairo-lang-formatter" +version = "2.7.0-dev.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "402ff59d648ad1cf57d654c9ec3fed1e98f409b0f3d1474679dec6ee84f46457" +dependencies = [ + "anyhow", + "cairo-lang-diagnostics", + "cairo-lang-filesystem", + "cairo-lang-parser", + "cairo-lang-syntax", + "cairo-lang-utils", + "diffy", + "ignore", + "itertools 0.12.1", + "salsa", + "serde", + "smol_str", + "thiserror", +] + [[package]] name = "cairo-lang-lowering" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c81afe28160958fb6ca0dd0c7fc40972d3664f390a29b63190b2441ef67d59df" +checksum = "e1913e4071758d226f6592db1f12f515d74616b8b5259f59523801c3481d9c3b" dependencies = [ "cairo-lang-debug", "cairo-lang-defs", @@ -628,10 +676,10 @@ dependencies = [ "cairo-lang-syntax", "cairo-lang-utils", "id-arena", - "itertools 0.11.0", + "itertools 0.12.1", "log", - "num-bigint 0.4.4", - "num-traits 0.2.17", + "num-bigint", + "num-traits 0.2.19", "once_cell", "salsa", "smol_str", @@ -639,9 +687,9 @@ dependencies = [ [[package]] name = "cairo-lang-parser" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1ce7492bbd227138fad2687094af0d1fe0e7ce33f561ab11d6fb0c53bccf01d" +checksum = "f7f06b6c7da1ba98371ec39f0928ea4a190e24e783c5f0b429e1fbe64ee672ee" dependencies = [ "cairo-lang-diagnostics", "cairo-lang-filesystem", @@ -649,9 +697,9 @@ dependencies = [ "cairo-lang-syntax-codegen", "cairo-lang-utils", "colored", - "itertools 0.11.0", - "num-bigint 0.4.4", - "num-traits 0.2.17", + "itertools 0.12.1", + "num-bigint", + "num-traits 0.2.19", "salsa", "smol_str", "unescaper", @@ -659,9 +707,9 @@ dependencies = [ [[package]] name = "cairo-lang-plugins" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41dbe519ef698fe0f295b49031cb35ccb919610338a6a5136e8968e13791864d" +checksum = "36fce40856d2c6415dc597cdc4e2f92885f9aab7288f4cdf95e15cb25274c820" dependencies = [ "cairo-lang-defs", "cairo-lang-diagnostics", @@ -670,28 +718,28 @@ dependencies = [ "cairo-lang-syntax", "cairo-lang-utils", "indent", - "indoc 2.0.4", - "itertools 0.11.0", + "indoc 2.0.5", + "itertools 0.12.1", "salsa", "smol_str", ] [[package]] name = "cairo-lang-proc-macros" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd65bf4d71ebc1efb0181b6c4d27c93e7e01fe5d521a15f2a5695cd7b5d79f36" +checksum = "2bf12b18566bbca35cd36750c4d15bed56c998ff5367eb649975334256983053" dependencies = [ "cairo-lang-debug", "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] name = "cairo-lang-project" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81ecab619e54abf610eefa4918d03831e50e54738b1973e37419734cefd73a77" +checksum = "74a9759131a1d59a58c775a980ad514e243addb334b95556cd23266d774587a2" dependencies = [ "cairo-lang-filesystem", "cairo-lang-utils", @@ -703,15 +751,13 @@ dependencies = [ [[package]] name = "cairo-lang-runner" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be60564ec98572096428145342047dddc1bec5c84992f20d38353bd7fbb6c2c4" +checksum = "dbe20f518b01a596b1dab5cecc611dc556771fad60e88b32e84cc9d8044a4023" dependencies = [ "ark-ff", "ark-secp256k1", "ark-secp256r1", - "ark-std", - "cairo-felt", "cairo-lang-casm", "cairo-lang-lowering", "cairo-lang-sierra", @@ -722,21 +768,24 @@ dependencies = [ "cairo-lang-starknet", "cairo-lang-utils", "cairo-vm", - "itertools 0.11.0", + "itertools 0.12.1", "keccak", - "num-bigint 0.4.4", + "num-bigint", "num-integer", - "num-traits 0.2.17", + "num-traits 0.2.19", + "rand", + "sha2", "smol_str", - "starknet-crypto 0.6.1", + "starknet-crypto 0.6.2", + "starknet-types-core", "thiserror", ] [[package]] name = "cairo-lang-semantic" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d2a528f1c547e67631dcea299b6864f96792052e3a7ce27e5cbc23d6fce0fcf" +checksum = "ffd46d20af4285271fdda6c815831ea95c2dfa0fbfb07b65633f3ef84c1bbe23" dependencies = [ "cairo-lang-debug", "cairo-lang-defs", @@ -746,78 +795,82 @@ dependencies = [ "cairo-lang-plugins", "cairo-lang-proc-macros", "cairo-lang-syntax", + "cairo-lang-test-utils", "cairo-lang-utils", "id-arena", - "indoc 2.0.4", - "itertools 0.11.0", - "num-bigint 0.4.4", - "num-traits 0.2.17", + "indoc 2.0.5", + "itertools 0.12.1", + "num-bigint", + "num-traits 0.2.19", "once_cell", "salsa", "smol_str", + "toml", ] [[package]] name = "cairo-lang-sierra" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5774a2d5725d9cd96cfead69ea070ddfc87f912c36ab91086df66efe90e89e7c" +checksum = "5022f62ac3a430e4d52d55b62080cbd88e8587b43a7e5c0569feb02c5eb63443" dependencies = [ "anyhow", - "cairo-felt", "cairo-lang-utils", "const-fnv1a-hash", "convert_case 0.6.0", "derivative", - "itertools 0.11.0", + "itertools 0.12.1", "lalrpop", "lalrpop-util", - "num-bigint 0.4.4", - "num-traits 0.2.17", + "num-bigint", + "num-traits 0.2.19", "regex", "salsa", "serde", "serde_json", "sha3", "smol_str", + "starknet-types-core", "thiserror", ] [[package]] name = "cairo-lang-sierra-ap-change" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "237de08219efe89406ce1cd6db8c2c1b8b062b090156ea82fb4f6eb8899d47f0" +checksum = "4f5cd352c120ffc20eecfbd7691652ca4a6ca7231567377939d6fac3dc35da99" dependencies = [ "cairo-lang-eq-solver", "cairo-lang-sierra", "cairo-lang-sierra-type-size", "cairo-lang-utils", - "itertools 0.11.0", - "num-traits 0.2.17", + "itertools 0.12.1", + "num-bigint", + "num-traits 0.2.19", "thiserror", ] [[package]] name = "cairo-lang-sierra-gas" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7b6fcdb1894da323e17c0f8388aab0622d25ace481c8d71eccafb764a2651fe" +checksum = "59aa1123fc8a6d08f80c2f12d1f72807597c32f2d75ca19696013824af263cb8" dependencies = [ "cairo-lang-eq-solver", "cairo-lang-sierra", "cairo-lang-sierra-type-size", "cairo-lang-utils", - "itertools 0.11.0", - "num-traits 0.2.17", + "itertools 0.12.1", + "num-bigint", + "num-traits 0.2.19", "thiserror", ] [[package]] name = "cairo-lang-sierra-generator" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9507e0de57e9e3bd973c6b1e341910283d9283649f9c003fe1ed62c94270a447" +checksum = "2bad0c6e76d2097e93129c19c5602ddfd4300173c240cf336bc50f1f0b85df8c" dependencies = [ "cairo-lang-debug", "cairo-lang-defs", @@ -829,39 +882,41 @@ dependencies = [ "cairo-lang-sierra", "cairo-lang-syntax", "cairo-lang-utils", - "itertools 0.11.0", - "num-traits 0.2.17", + "itertools 0.12.1", + "num-traits 0.2.19", "once_cell", "salsa", + "serde", + "serde_json", "smol_str", ] [[package]] name = "cairo-lang-sierra-to-casm" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "042ca9969b62580fbd9f257e60c9e441715335a2fe7c79826aa9664ef4e21187" +checksum = "8f51aab0d040f6c2c49eba5bbebd1ac7d66e87db24c5587ac8c759247c295a11" dependencies = [ "assert_matches", - "cairo-felt", "cairo-lang-casm", "cairo-lang-sierra", "cairo-lang-sierra-ap-change", "cairo-lang-sierra-gas", "cairo-lang-sierra-type-size", "cairo-lang-utils", - "indoc 2.0.4", - "itertools 0.11.0", - "num-bigint 0.4.4", - "num-traits 0.2.17", + "indoc 2.0.5", + "itertools 0.12.1", + "num-bigint", + "num-traits 0.2.19", + "starknet-types-core", "thiserror", ] [[package]] name = "cairo-lang-sierra-type-size" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859e83d8ceeec98b72119c89281468ad08b6a60c9f2d99ddce407df0c6b8377c" +checksum = "9eab42a1cda2bae4adf612985080e7ecb88ceb83c9c069f1bfef9ae76c408eec" dependencies = [ "cairo-lang-sierra", "cairo-lang-utils", @@ -869,12 +924,11 @@ dependencies = [ [[package]] name = "cairo-lang-starknet" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a22e15a9c91f26fe9b8638bddcb8b08282b7a27d1435c8390f5fa6abdef768" +checksum = "02a4284dad726fdcb601be5ada83486eed53b46988dbdeef90bc2e5630570c2f" dependencies = [ "anyhow", - "cairo-felt", "cairo-lang-compiler", "cairo-lang-defs", "cairo-lang-diagnostics", @@ -889,51 +943,52 @@ dependencies = [ "cairo-lang-utils", "const_format", "indent", - "indoc 2.0.4", - "itertools 0.11.0", + "indoc 2.0.5", + "itertools 0.12.1", "once_cell", "serde", "serde_json", "smol_str", + "starknet-types-core", "thiserror", ] [[package]] name = "cairo-lang-starknet-classes" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39d9d31715b12f46963373bf0c4eeaa66c1839ee44fb176e39fe49d364aea0cf" +checksum = "dc7fdcbbba52cf3daedd2a2b3dde6403bc4c0bf679e5fbfd330a73d693fc9158" dependencies = [ - "cairo-felt", "cairo-lang-casm", "cairo-lang-sierra", "cairo-lang-sierra-to-casm", "cairo-lang-utils", "convert_case 0.6.0", - "itertools 0.11.0", - "num-bigint 0.4.4", + "itertools 0.12.1", + "num-bigint", "num-integer", - "num-traits 0.2.17", + "num-traits 0.2.19", "once_cell", "serde", "serde_json", "sha3", "smol_str", - "starknet-crypto 0.6.1", + "starknet-crypto 0.6.2", + "starknet-types-core", "thiserror", ] [[package]] name = "cairo-lang-syntax" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03bca67a21f85098d3185a2c016ef335ffc0b815a8305aad4a117876379c2cb3" +checksum = "9a794b8c7b14cb8134f5c710c35014f087ea27d981618d26441e3b07830120de" dependencies = [ "cairo-lang-debug", "cairo-lang-filesystem", "cairo-lang-utils", - "num-bigint 0.4.4", - "num-traits 0.2.17", + "num-bigint", + "num-traits 0.2.19", "salsa", "smol_str", "unescaper", @@ -941,25 +996,38 @@ dependencies = [ [[package]] name = "cairo-lang-syntax-codegen" -version = "2.6.3" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e2d692eae4bb4179a4a1148fd5eb738a91653d86750c813658ffad4a99fa97" +checksum = "a84a680a70dbb0ed98cd4e10e461cb989bf0f92c9d79ad6e311cb08f7a0a91ec" dependencies = [ "genco", "xshell", ] +[[package]] +name = "cairo-lang-test-utils" +version = "2.7.0-dev.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b49fd5ec4786f5a088219ac672db55e1ffad03603c95069626d93f9391ab2cc" +dependencies = [ + "cairo-lang-formatter", + "cairo-lang-utils", + "colored", + "log", + "pretty_assertions", +] + [[package]] name = "cairo-lang-utils" -version = "2.6.0" +version = "2.7.0-dev.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15222608b6afc529e86554f5f8722cb37de9d73f28384ad33d86e6749ab6d13f" +checksum = "81ce0c5fd767c01cba2abcb7d46428d31c92ca4d006fa42d442ee7884bc20764" dependencies = [ - "hashbrown 0.14.3", - "indexmap 2.1.0", - "itertools 0.11.0", - "num-bigint 0.4.4", - "num-traits 0.2.17", + "hashbrown 0.14.5", + "indexmap 2.2.6", + "itertools 0.12.1", + "num-bigint", + "num-traits 0.2.19", "parity-scale-codec", "schemars", "serde", @@ -967,33 +1035,32 @@ dependencies = [ [[package]] name = "cairo-vm" -version = "0.9.2" +version = "1.0.0-rc3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd569684da80d747273613d5c809e4f81bf6f6b1b64d0301b12bac8f2fb8ffb1" +checksum = "a0fa4c74b86c0f17b58ced4fdab5c1da0a41fb12725ad7601e12bb27d8d90435" dependencies = [ "anyhow", "bincode", "bitvec", - "cairo-felt", "generic-array", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "hex", "keccak", "lazy_static", - "mimalloc", "nom", - "num-bigint 0.4.4", + "num-bigint", "num-integer", "num-prime", - "num-traits 0.2.17", - "rand 0.8.5", + "num-traits 0.2.19", + "rand", "serde", "serde_json", "sha2", "sha3", - "starknet-crypto 0.6.1", - "starknet-curve 0.4.0", + "starknet-crypto 0.6.2", + "starknet-types-core", "thiserror-no-std", + "zip", ] [[package]] @@ -1008,6 +1075,7 @@ version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" dependencies = [ + "jobserver", "libc", ] @@ -1026,11 +1094,21 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + [[package]] name = "clang-sys" -version = "1.7.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67523a3b4be3ce1989d607a828d036249522dd9c1c8de7f4dd2dae43a37369d1" +checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" dependencies = [ "glob", "libc", @@ -1050,45 +1128,36 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.13" +version = "4.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52bdc885e4cacc7f7c9eedc1ef6da641603180c783c41a15c264944deeaab642" +checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" -version = "4.4.12" +version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb7fb5e4e979aec3be7791562fcba452f94ad85e954da024396433e0e25a79e9" +checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" dependencies = [ "anstream", "anstyle", "clap_lex", - "strsim", + "strsim 0.11.1", ] [[package]] name = "clap_lex" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" - -[[package]] -name = "cloudabi" -version = "0.0.3" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddfc5b9aa5d4507acaf872de71051dfd0e309860e88966e1051e462a077aac4f" -dependencies = [ - "bitflags 1.3.2", -] +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" [[package]] name = "colorchoice" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" +checksum = "0b6a852b24ab71dffc585bcb46eaf7959d175cb865a7152e35b348d1b2960422" [[package]] name = "colored" @@ -1126,6 +1195,12 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "constant_time_eq" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" + [[package]] name = "convert_case" version = "0.4.0" @@ -1172,7 +1247,7 @@ dependencies = [ "csv", "itertools 0.10.5", "lazy_static", - "num-traits 0.2.17", + "num-traits 0.2.19", "oorandom", "plotters", "rayon", @@ -1291,7 +1366,7 @@ dependencies = [ "ident_case", "proc-macro2", "quote", - "strsim", + "strsim 0.10.0", "syn 1.0.109", ] @@ -1306,6 +1381,15 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", +] + [[package]] name = "derivative" version = "2.2.0" @@ -1336,6 +1420,15 @@ version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" +[[package]] +name = "diffy" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e616e59155c92257e84970156f506287853355f58cd4a6eb167385722c32b790" +dependencies = [ + "nu-ansi-term", +] + [[package]] name = "digest" version = "0.10.7" @@ -1407,9 +1500,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "fixed-hash" @@ -1418,7 +1511,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "835c052cb0c08c1acf6ffd71c022172e18723949c8282f2b9f27efbc51e64534" dependencies = [ "byteorder", - "rand 0.8.5", + "rand", "rustc-hex", "static_assertions", ] @@ -1454,12 +1547,6 @@ dependencies = [ "percent-encoding", ] -[[package]] -name = "fuchsia-cprng" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" - [[package]] name = "funty" version = "2.0.0" @@ -1522,7 +1609,7 @@ checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] @@ -1580,7 +1667,7 @@ checksum = "d4cf186fea4af17825116f72932fe52cce9a13bae39ff63b4dc0cfdb3fb4bde1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] @@ -1618,11 +1705,24 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" +[[package]] +name = "globset" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57da3b9b5b85bd66f31093f8c408b90a74431672542466497dcbdfdc02034be1" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax 0.8.2", +] + [[package]] name = "good_lp" -version = "1.7.0" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa124423ded10046a849fa0ae9747c541895557f1af177e0890b09879e7e9e7d" +checksum = "3198bd13dea84c76a64621d6ee8ee26a4960a9a0d538eca95ca8f1320a469ac9" dependencies = [ "fnv", "minilp", @@ -1654,9 +1754,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.14.3" +version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" dependencies = [ "ahash 0.8.7", "allocator-api2", @@ -1753,6 +1853,22 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" +[[package]] +name = "ignore" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b46810df39e66e925525d6e38ce1e7f6e1d208f72dc39757880fcb66e2c58af1" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata", + "same-file", + "walkdir", + "winapi-util", +] + [[package]] name = "impl-codec" version = "0.6.0" @@ -1794,19 +1910,19 @@ version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" dependencies = [ - "autocfg 1.1.0", + "autocfg", "hashbrown 0.12.3", "serde", ] [[package]] name = "indexmap" -version = "2.1.0" +version = "2.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f" +checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" dependencies = [ "equivalent", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "serde", ] @@ -1818,9 +1934,18 @@ checksum = "bfa799dd5ed20a7e349f3b4639aa80d74549c81716d9ec4f994c9b5815598306" [[package]] name = "indoc" -version = "2.0.4" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5" + +[[package]] +name = "inout" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e186cfbae8084e513daff4240b4797e342f988cecda4fb6c939150f96315fd8" +checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +dependencies = [ + "generic-array", +] [[package]] name = "instant" @@ -1848,6 +1973,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" + [[package]] name = "itertools" version = "0.10.5" @@ -1859,9 +1990,9 @@ dependencies = [ [[package]] name = "itertools" -version = "0.11.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" dependencies = [ "either", ] @@ -1872,6 +2003,15 @@ version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" +[[package]] +name = "jobserver" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2b099aaa34a9751c5bf0878add70444e1ed2dd73f347be99003d4577277de6e" +dependencies = [ + "libc", +] + [[package]] name = "js-sys" version = "0.3.69" @@ -1883,9 +2023,9 @@ dependencies = [ [[package]] name = "keccak" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f6d5ed8676d904364de097082f4e7d240b571b67989ced0240f08b7f966f940" +checksum = "ecc2af9a1119c51f12a14607e783cb977bde58bc069ff0c3da1095e635d70654" dependencies = [ "cpufeatures", ] @@ -1915,18 +2055,18 @@ dependencies = [ [[package]] name = "lalrpop-util" -version = "0.20.0" +version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f35c735096c0293d313e8f2a641627472b83d01b937177fe76e5e2708d31e0d" +checksum = "507460a910eb7b32ee961886ff48539633b788a36b65692b95f225b844c82553" dependencies = [ - "regex", + "regex-automata", ] [[package]] name = "lambdaworks-crypto" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "458fee521f12d0aa97a2e06eaf134398a5d2ae7b2074af77eb402b0d93138c47" +checksum = "7fb5d4f22241504f7c7b8d2c3a7d7835d7c07117f10bff2a7d96a9ef6ef217c3" dependencies = [ "lambdaworks-math", "serde", @@ -1936,9 +2076,9 @@ dependencies = [ [[package]] name = "lambdaworks-math" -version = "0.6.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c74ce6f0d9cb672330b6ca59e85a6c3607a3329e0372ab0d3fe38c2d38e50f9" +checksum = "358e172628e713b80a530a59654154bfc45783a6ed70ea284839800cebdf8f97" dependencies = [ "serde", "serde_json", @@ -1961,18 +2101,18 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" [[package]] name = "libc" -version = "0.2.151" +version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "libloading" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c571b676ddfc9a8c12f1f3d3085a7b163966a8fd8098a90640953ce5f6170161" +checksum = "0c2a198fb6b0eada2a8df47933734e6d35d350665a33a3593d7164fa52c75c19" dependencies = [ "cfg-if", - "windows-sys 0.48.0", + "windows-targets 0.52.0", ] [[package]] @@ -1992,16 +2132,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "libmimalloc-sys" -version = "0.1.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3979b5c37ece694f1f5e51e7ecc871fdb0f517ed04ee45f88d15d6d553cb9664" -dependencies = [ - "cc", - "libc", -] - [[package]] name = "libredox" version = "0.0.1" @@ -2034,15 +2164,15 @@ version = "0.4.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" dependencies = [ - "autocfg 1.1.0", + "autocfg", "scopeguard", ] [[package]] name = "log" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "lru" @@ -2096,11 +2226,11 @@ dependencies = [ [[package]] name = "memoffset" -version = "0.9.0" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" dependencies = [ - "autocfg 1.1.0", + "autocfg", ] [[package]] @@ -2122,16 +2252,7 @@ checksum = "38b4faf00617defe497754acde3024865bc143d44a86799b24e191ecff91354f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", -] - -[[package]] -name = "mimalloc" -version = "0.1.39" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa01922b5ea280a911e323e4d2fd24b7fe5cc4042e0d2cda3c40775cdc4bdc9c" -dependencies = [ - "libmimalloc-sys", + "syn 2.0.66", ] [[package]] @@ -2161,21 +2282,22 @@ dependencies = [ [[package]] name = "native_blockifier" -version = "0.7.0-dev.1" +version = "0.8.0-dev.1" dependencies = [ "blockifier", "cached", "cairo-lang-starknet-classes", "cairo-vm", - "indexmap 2.1.0", + "indexmap 2.2.6", "log", - "num-bigint 0.4.4", + "num-bigint", "papyrus_storage", "pretty_assertions", "pyo3", "pyo3-log", "serde", "serde_json", + "starknet-types-core", "starknet_api", "tempfile", "thiserror", @@ -2190,7 +2312,7 @@ dependencies = [ "matrixmultiply", "num-complex", "num-integer", - "num-traits 0.2.17", + "num-traits 0.2.19", "rawpointer", ] @@ -2211,40 +2333,24 @@ dependencies = [ ] [[package]] -name = "num" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8536030f9fea7127f841b45bb6243b27255787fb4eb83958aa1ef9d2fdc0c36" -dependencies = [ - "num-bigint 0.2.6", - "num-complex", - "num-integer", - "num-iter", - "num-rational 0.2.4", - "num-traits 0.2.17", -] - -[[package]] -name = "num-bigint" -version = "0.2.6" +name = "nu-ansi-term" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "090c7f9998ee0ff65aa5b723e4009f7b217707f1fb5ea551329cc4d6231fb304" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" dependencies = [ - "autocfg 1.1.0", - "num-integer", - "num-traits 0.2.17", + "overload", + "winapi", ] [[package]] name = "num-bigint" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0" +checksum = "c165a9ab64cf766f73521c0dd2cfdff64f488b8f0b3e621face3462d3db536d7" dependencies = [ - "autocfg 1.1.0", "num-integer", - "num-traits 0.2.17", - "rand 0.8.5", + "num-traits 0.2.19", + "rand", "serde", ] @@ -2254,29 +2360,23 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6b19411a9719e753aff12e5187b74d60d3dc449ec3f4dc21e3989c3f554bc95" dependencies = [ - "autocfg 1.1.0", - "num-traits 0.2.17", + "autocfg", + "num-traits 0.2.19", ] [[package]] -name = "num-integer" -version = "0.1.45" +name = "num-conv" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" -dependencies = [ - "autocfg 1.1.0", - "num-traits 0.2.17", -] +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" [[package]] -name = "num-iter" -version = "0.1.44" +name = "num-integer" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d869c01cc0c455284163fd0092f1f93835385ccab5a98a0dcc497b2f8bf055a9" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" dependencies = [ - "autocfg 1.1.0", - "num-integer", - "num-traits 0.2.17", + "num-traits 0.2.19", ] [[package]] @@ -2285,9 +2385,9 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "64a5fe11d4135c3bcdf3a95b18b194afa9608a5f6ff034f5d857bc9a27fb0119" dependencies = [ - "num-bigint 0.4.4", + "num-bigint", "num-integer", - "num-traits 0.2.17", + "num-traits 0.2.19", ] [[package]] @@ -2299,23 +2399,11 @@ dependencies = [ "bitvec", "either", "lru", - "num-bigint 0.4.4", + "num-bigint", "num-integer", "num-modular", - "num-traits 0.2.17", - "rand 0.8.5", -] - -[[package]] -name = "num-rational" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c000134b5dbf44adc5cb772486d335293351644b801551abe8f75c84cfa4aef" -dependencies = [ - "autocfg 1.1.0", - "num-bigint 0.2.6", - "num-integer", - "num-traits 0.2.17", + "num-traits 0.2.19", + "rand", ] [[package]] @@ -2324,10 +2412,10 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" dependencies = [ - "autocfg 1.1.0", - "num-bigint 0.4.4", + "autocfg", + "num-bigint", "num-integer", - "num-traits 0.2.17", + "num-traits 0.2.19", "serde", ] @@ -2337,16 +2425,16 @@ version = "0.1.43" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92e5113e9fd4cc14ded8e499429f396a20f98c772a47cc8622a736e1ec843c31" dependencies = [ - "num-traits 0.2.17", + "num-traits 0.2.19", ] [[package]] name = "num-traits" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ - "autocfg 1.1.0", + "autocfg", ] [[package]] @@ -2370,6 +2458,12 @@ version = "11.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + [[package]] name = "page_size" version = "0.6.0" @@ -2382,29 +2476,33 @@ dependencies = [ [[package]] name = "papyrus_common" -version = "0.4.0-dev.1" +version = "0.4.0-dev.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9540af3cf503356a4a0b85b7088625ddce4aadff52ff2b6c735206cc9a51ad85" +checksum = "253c374b2174d98425fdd5e2e0a1bfd9b9f880a37c45149926ff02548ca6fa56" dependencies = [ "bitvec", "cairo-lang-starknet-classes", "hex", + "indexmap 2.2.6", + "itertools 0.10.5", "lazy_static", + "rand", "serde", "serde_json", "sha3", "starknet-crypto 0.5.2", + "starknet-types-core", "starknet_api", "thiserror", ] [[package]] name = "papyrus_config" -version = "0.4.0-dev.1" +version = "0.4.0-dev.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20c0679905ebf1579de3a0153f278027b5f6ca8429a4b13b522ce133cae1bb55" +checksum = "681c77c3036aa865206d874c5fbaa264713f22bfd0ef518c7881a1954fc3a045" dependencies = [ - "clap 4.4.13", + "clap 4.5.4", "itertools 0.10.5", "serde", "serde_json", @@ -2415,33 +2513,31 @@ dependencies = [ [[package]] name = "papyrus_proc_macros" -version = "0.4.0-dev.1" +version = "0.4.0-dev.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fdb2133ed4651fe27ae2d9bbe430eafe2b6a6b8f5545a9447e6ffb60d8a583e" +checksum = "80ae7c26b3754c405b911a45d9304c10feebf237b6b91b3c3c0fc31cbad9692f" dependencies = [ "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] name = "papyrus_storage" -version = "0.4.0-dev.1" +version = "0.4.0-dev.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d258b86ec0cd4b546f4bb39495a5ff7e89de793feedcb7320864c104d67972ca" +checksum = "92bd277d8c0f980cb9da4584b01cd43213309ed0d5dc73a627b24080fab89845" dependencies = [ "byteorder", "cairo-lang-casm", "cairo-lang-starknet-classes", "cairo-lang-utils", - "clap 4.4.13", - "flate2", "human_bytes", - "indexmap 2.1.0", + "indexmap 2.2.6", "integer-encoding", "libmdbx", "memmap2", "metrics", - "num-bigint 0.4.4", + "num-bigint", "page_size", "papyrus_common", "papyrus_config", @@ -2450,19 +2546,20 @@ dependencies = [ "primitive-types", "serde", "serde_json", + "starknet-types-core", "starknet_api", - "statistical", "tempfile", "thiserror", "tracing", "validator", + "zstd 0.13.1", ] [[package]] name = "parity-scale-codec" -version = "3.6.5" +version = "3.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dec8a8073036902368c2cdc0387e85ff9a37054d7e7c98e592145e0c92cd4fb" +checksum = "306800abfa29c7f16596b5970a588435e3d5b3149683d00c12b699cc19f895ee" dependencies = [ "arrayvec", "bitvec", @@ -2474,9 +2571,9 @@ dependencies = [ [[package]] name = "parity-scale-codec-derive" -version = "3.6.5" +version = "3.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "312270ee71e1cd70289dacf597cab7b207aa107d2f28191c2ae45b2ece18a260" +checksum = "d830939c76d294956402033aee57a6da7b438f2294eb94864c37b0569053a42c" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -2532,6 +2629,17 @@ dependencies = [ "windows-targets 0.48.5", ] +[[package]] +name = "password-hash" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700" +dependencies = [ + "base64ct", + "rand_core", + "subtle", +] + [[package]] name = "paste" version = "1.0.14" @@ -2544,6 +2652,18 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17359afc20d7ab31fdb42bb844c8b3bb1dabd7dcf7e68428492da7f16966fcef" +[[package]] +name = "pbkdf2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917" +dependencies = [ + "digest", + "hmac", + "password-hash", + "sha2", +] + [[package]] name = "peeking_take_while" version = "0.1.2" @@ -2563,7 +2683,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d3afd2628e69da2be385eb6f2fd57c8ac7977ceeff6dc166ff1657b0e386a9" dependencies = [ "fixedbitset", - "indexmap 2.1.0", + "indexmap 2.2.6", ] [[package]] @@ -2583,7 +2703,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" dependencies = [ "phf_shared 0.11.2", - "rand 0.8.5", + "rand", ] [[package]] @@ -2596,7 +2716,7 @@ dependencies = [ "phf_shared 0.11.2", "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] @@ -2635,13 +2755,19 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "pkg-config" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" + [[package]] name = "plotters" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2c224ba00d7cadd4d5c660deaf2098e5e80e07846537c51f9cfa4be50c1fd45" dependencies = [ - "num-traits 0.2.17", + "num-traits 0.2.19", "plotters-backend", "plotters-svg", "wasm-bindgen", @@ -2669,6 +2795,12 @@ version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7170ef9988bc169ba16dd36a7fa041e5c4cbeb6a35b76d4c03daded371eae7c0" +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.17" @@ -2705,12 +2837,11 @@ dependencies = [ [[package]] name = "proc-macro-crate" -version = "1.3.1" +version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +checksum = "6d37c51ca738a55da99dc0c4a34860fd675453b8b36209178c2249bb13651284" dependencies = [ - "once_cell", - "toml_edit 0.19.15", + "toml_edit 0.21.0", ] [[package]] @@ -2739,9 +2870,9 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.74" +version = "1.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2de98502f212cfcea8d0bb305bd0f49d7ebdd75b64ba0a68f937d888f4e0d6db" +checksum = "22244ce15aa966053a896d1accb3a6e68469b97c7f33f284b99f0d576879fc23" dependencies = [ "unicode-ident", ] @@ -2753,11 +2884,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e681a6cfdc4adcc93b4d3cf993749a4552018ee0a9b65fc0ccfad74352c72a38" dependencies = [ "cfg-if", - "hashbrown 0.14.3", + "hashbrown 0.14.5", "indoc 1.0.9", "libc", "memoffset", - "num-bigint 0.4.4", + "num-bigint", "parking_lot 0.12.1", "pyo3-build-config", "pyo3-ffi", @@ -2821,9 +2952,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.35" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] @@ -2834,25 +2965,6 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" -[[package]] -name = "rand" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d71dacdc3c88c1fde3885a3be3fbab9f35724e6ce99467f7d9c5026132184ca" -dependencies = [ - "autocfg 0.1.8", - "libc", - "rand_chacha 0.1.1", - "rand_core 0.4.2", - "rand_hc", - "rand_isaac", - "rand_jitter", - "rand_os", - "rand_pcg", - "rand_xorshift", - "winapi", -] - [[package]] name = "rand" version = "0.8.5" @@ -2860,18 +2972,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "556d3a1ca6600bfcbab7c7c91ccb085ac7fbbcd70e008a98742e7847f4f7bcef" -dependencies = [ - "autocfg 0.1.8", - "rand_core 0.3.1", + "rand_chacha", + "rand_core", ] [[package]] @@ -2881,24 +2983,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core 0.6.4", + "rand_core", ] -[[package]] -name = "rand_core" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" -dependencies = [ - "rand_core 0.4.2", -] - -[[package]] -name = "rand_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" - [[package]] name = "rand_core" version = "0.6.4" @@ -2908,68 +2995,6 @@ dependencies = [ "getrandom", ] -[[package]] -name = "rand_hc" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b40677c7be09ae76218dc623efbf7b18e34bced3f38883af07bb75630a21bc4" -dependencies = [ - "rand_core 0.3.1", -] - -[[package]] -name = "rand_isaac" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ded997c9d5f13925be2a6fd7e66bf1872597f759fd9dd93513dd7e92e5a5ee08" -dependencies = [ - "rand_core 0.3.1", -] - -[[package]] -name = "rand_jitter" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1166d5c91dc97b88d1decc3285bb0a99ed84b05cfd0bc2341bdf2d43fc41e39b" -dependencies = [ - "libc", - "rand_core 0.4.2", - "winapi", -] - -[[package]] -name = "rand_os" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b75f676a1e053fc562eafbb47838d67c84801e38fc1ba459e8f180deabd5071" -dependencies = [ - "cloudabi", - "fuchsia-cprng", - "libc", - "rand_core 0.4.2", - "rdrand", - "winapi", -] - -[[package]] -name = "rand_pcg" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abf9b09b01790cfe0364f52bf32995ea3c39f4d2dd011eac241d2914146d0b44" -dependencies = [ - "autocfg 0.1.8", - "rand_core 0.4.2", -] - -[[package]] -name = "rand_xorshift" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbf7e9e623549b0e21f6e97cf8ecf247c1a8fd2e8a992ae265314300b2455d5c" -dependencies = [ - "rand_core 0.3.1", -] - [[package]] name = "rawpointer" version = "0.2.1" @@ -2996,15 +3021,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "rdrand" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" -dependencies = [ - "rand_core 0.3.1", -] - [[package]] name = "redox_syscall" version = "0.2.16" @@ -3140,9 +3156,9 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.28" +version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72e572a5e8ca657d7366229cdde4bd14c4eb5499a9573d4d366fe1b599daa316" +checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ "bitflags 2.4.1", "errno", @@ -3203,9 +3219,9 @@ dependencies = [ [[package]] name = "schemars" -version = "0.8.16" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45a28f4c49489add4ce10783f7911893516f15afe45d015608d41faca6bc4d29" +checksum = "09c024468a378b7e36765cd36702b7a90cc3cba11654f6685c8f233408e89e92" dependencies = [ "dyn-clone", "indexmap 1.9.3", @@ -3216,14 +3232,14 @@ dependencies = [ [[package]] name = "schemars_derive" -version = "0.8.16" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c767fd6fa65d9ccf9cf026122c1b555f2ef9a4f0cea69da4d7dbc3e258d30967" +checksum = "b1eee588578aff73f856ab961cd2f79e36bc45d7ded33a7562adba4667aecc0e" dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 1.0.109", + "syn 2.0.66", ] [[package]] @@ -3240,9 +3256,9 @@ checksum = "b97ed7a9823b74f99c7742f5336af7be5ecd3eeafcb1507d1fa93347b1d589b0" [[package]] name = "serde" -version = "1.0.194" +version = "1.0.203" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b114498256798c94a0689e1a15fec6005dee8ac1f41de56404b67afc2a4b773" +checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094" dependencies = [ "serde_derive", ] @@ -3259,31 +3275,31 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.194" +version = "1.0.203" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3385e45322e8f9931410f01b3031ec534c3947d0e94c18049af4d9f9907d4e0" +checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] name = "serde_derive_internals" -version = "0.26.0" +version = "0.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85bf8229e7920a9f636479437026331ce11aa132b4dde37d121944a44d6e5f3c" +checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.66", ] [[package]] name = "serde_json" -version = "1.0.113" +version = "1.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69801b70b1c3dac963ecb03a364ba0ceda9cf60c71cfe475e99864759c8b8a79" +checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3" dependencies = [ "itoa", "ryu", @@ -3292,13 +3308,24 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" +checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0" dependencies = [ "serde", ] +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "sha2" version = "0.10.8" @@ -3322,9 +3349,9 @@ dependencies = [ [[package]] name = "shlex" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "siphasher" @@ -3338,7 +3365,7 @@ version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" dependencies = [ - "autocfg 1.1.0", + "autocfg", ] [[package]] @@ -3382,9 +3409,9 @@ dependencies = [ "crypto-bigint", "hex", "hmac", - "num-bigint 0.4.4", + "num-bigint", "num-integer", - "num-traits 0.2.17", + "num-traits 0.2.19", "rfc6979", "sha2", "starknet-crypto-codegen", @@ -3395,33 +3422,33 @@ dependencies = [ [[package]] name = "starknet-crypto" -version = "0.6.1" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33c03f5ac70f9b067f48db7d2d70bdf18ee0f731e8192b6cfa679136becfcdb0" +checksum = "2e2c30c01e8eb0fc913c4ee3cf676389fffc1d1182bfe5bb9670e4e72e968064" dependencies = [ "crypto-bigint", "hex", "hmac", - "num-bigint 0.4.4", + "num-bigint", "num-integer", - "num-traits 0.2.17", + "num-traits 0.2.19", "rfc6979", "sha2", "starknet-crypto-codegen", - "starknet-curve 0.4.0", + "starknet-curve 0.4.2", "starknet-ff", "zeroize", ] [[package]] name = "starknet-crypto-codegen" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af6527b845423542c8a16e060ea1bc43f67229848e7cd4c4d80be994a84220ce" +checksum = "bbc159a1934c7be9761c237333a57febe060ace2bc9e3b337a59a37af206d19f" dependencies = [ - "starknet-curve 0.4.0", + "starknet-curve 0.4.2", "starknet-ff", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] @@ -3435,18 +3462,18 @@ dependencies = [ [[package]] name = "starknet-curve" -version = "0.4.0" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68a0d87ae56572abf83ddbfd44259a7c90dbeeee1629a1ffe223e7f9a8f3052" +checksum = "d1c383518bb312751e4be80f53e8644034aa99a0afb29d7ac41b89a997db875b" dependencies = [ "starknet-ff", ] [[package]] name = "starknet-ff" -version = "0.3.6" +version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "067419451efdea1ee968df8438369960c167e0e905c05b84afd074f50e1d6f3d" +checksum = "7abf1b44ec5b18d87c1ae5f54590ca9d0699ef4dd5b2ffa66fc97f24613ec585" dependencies = [ "ark-ff", "crypto-bigint", @@ -3456,34 +3483,36 @@ dependencies = [ [[package]] name = "starknet-types-core" -version = "0.0.11" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1e16522c1c9aa7fc149a46816cd18aa12a5fc2b2b75a018089022db473a9237" +checksum = "ce6bacf0ba19bc721e518bc4bf389ff13daa8a7c5db5fd320600473b8aa9fcbd" dependencies = [ - "bitvec", "lambdaworks-crypto", "lambdaworks-math", "lazy_static", - "num-bigint 0.4.4", + "num-bigint", "num-integer", - "num-traits 0.2.17", + "num-traits 0.2.19", "serde", ] [[package]] name = "starknet_api" -version = "0.12.0-dev.0" +version = "0.13.0-dev.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83d0987fc20eb9d39e39ce768534718174c30bc6532fa5c6e493a611b5f4303" +checksum = "66a6dc6b4f77fff0f28894cc36d5a691784550054d06c6850e901278aed2c7e6" dependencies = [ + "bitvec", "cairo-lang-starknet-classes", "derive_more", "hex", - "indexmap 2.1.0", + "indexmap 2.2.6", + "itertools 0.12.1", "once_cell", "primitive-types", "serde", "serde_json", + "sha3", "starknet-crypto 0.5.2", "starknet-types-core", "strum", @@ -3497,16 +3526,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" -[[package]] -name = "statistical" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49d57902bb128e5e38b5218d3681215ae3e322d99f65d5420e9849730d2ea372" -dependencies = [ - "num", - "rand 0.6.5", -] - [[package]] name = "string_cache" version = "0.8.7" @@ -3526,6 +3545,12 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "strum" version = "0.24.1" @@ -3555,7 +3580,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] @@ -3577,9 +3602,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.46" +version = "2.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89456b690ff72fddcecf231caedbe615c59480c93358a93dfae7fc29e3ebbf0e" +checksum = "c42f3f41a2de00b01c0aaad383c5a45241efc8b2d1eda5661812fda5f3cdcff5" dependencies = [ "proc-macro2", "quote", @@ -3594,19 +3619,18 @@ checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" [[package]] name = "target-lexicon" -version = "0.12.13" +version = "0.12.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69758bda2e78f098e4ccb393021a0963bb3442eac05f135c30f61b7370bbafae" +checksum = "e1fc403891a21bcfb7c37834ba66a547a8f402146eba7265b5a6d88059c9ff2f" [[package]] name = "tempfile" -version = "3.9.0" +version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", - "redox_syscall 0.4.1", "rustix", "windows-sys 0.52.0", ] @@ -3655,22 +3679,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.56" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d54378c645627613241d077a3a79db965db602882668f9136ac42af9ecb730ad" +checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.56" +version = "1.0.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa0faa943b50f3db30a20aa7e265dbc66076993efed8463e8de414e5d06d3471" +checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] @@ -3713,6 +3737,25 @@ dependencies = [ "tikv-jemalloc-sys", ] +[[package]] +name = "time" +version = "0.3.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" + [[package]] name = "tiny-keccak" version = "2.0.2" @@ -3767,52 +3810,52 @@ checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] name = "toml" -version = "0.8.8" +version = "0.8.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1a195ec8c9da26928f773888e0742ca3ca1040c6cd859c919c9f59c1954ab35" +checksum = "a4e43f8cc456c9704c851ae29c67e17ef65d2c30017c17a9765b89c382dc8bba" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.21.0", + "toml_edit 0.22.13", ] [[package]] name = "toml_datetime" -version = "0.6.5" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" +checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.19.15" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +checksum = "d34d383cd00a163b4a5b85053df514d45bc330f6de7737edfe0a93311d1eaa03" dependencies = [ - "indexmap 2.1.0", + "indexmap 2.2.6", "toml_datetime", - "winnow", + "winnow 0.5.31", ] [[package]] name = "toml_edit" -version = "0.21.0" +version = "0.22.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34d383cd00a163b4a5b85053df514d45bc330f6de7737edfe0a93311d1eaa03" +checksum = "c127785850e8c20836d49732ae6abfa47616e60bf9d9f57c43c250361a9db96c" dependencies = [ - "indexmap 2.1.0", + "indexmap 2.2.6", "serde", "serde_spanned", "toml_datetime", - "winnow", + "winnow 0.6.9", ] [[package]] @@ -3835,7 +3878,7 @@ checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] @@ -3876,9 +3919,9 @@ dependencies = [ [[package]] name = "unicode-bidi" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f2528f27a9eb2b21e69c95319b30bd0efd85d09c379741b0f78ea1d86be2416" +checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" [[package]] name = "unicode-ident" @@ -3888,9 +3931,9 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-normalization" -version = "0.1.22" +version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" dependencies = [ "tinyvec", ] @@ -4018,7 +4061,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", "wasm-bindgen-shared", ] @@ -4040,7 +4083,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -4233,6 +4276,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "winnow" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86c949fede1d13936a99f14fafd3e76fd642b556dd2ce96287fbe2e0151bfac6" +dependencies = [ + "memchr", +] + [[package]] name = "wyz" version = "0.5.1" @@ -4244,18 +4296,18 @@ dependencies = [ [[package]] name = "xshell" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce2107fe03e558353b4c71ad7626d58ed82efaf56c54134228608893c77023ad" +checksum = "6db0ab86eae739efd1b054a8d3d16041914030ac4e01cd1dca0cf252fd8b6437" dependencies = [ "xshell-macros", ] [[package]] name = "xshell-macros" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e2c411759b501fb9501aac2b1b2d287a6e93e5bdcf13c25306b23e1b716dd0e" +checksum = "9d422e8e38ec76e2f06ee439ccc765e9c6a9638b9e7c9f2e8255e4d41e8bd852" [[package]] name = "yansi" @@ -4280,7 +4332,7 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", ] [[package]] @@ -4300,5 +4352,72 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.46", + "syn 2.0.66", +] + +[[package]] +name = "zip" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261" +dependencies = [ + "aes", + "byteorder", + "bzip2", + "constant_time_eq", + "crc32fast", + "crossbeam-utils", + "flate2", + "hmac", + "pbkdf2", + "sha1", + "time", + "zstd 0.11.2+zstd.1.5.2", +] + +[[package]] +name = "zstd" +version = "0.11.2+zstd.1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4" +dependencies = [ + "zstd-safe 5.0.2+zstd.1.5.2", +] + +[[package]] +name = "zstd" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d789b1514203a1120ad2429eae43a7bd32b90976a7bb8a05f7ec02fa88cc23a" +dependencies = [ + "zstd-safe 7.1.0", +] + +[[package]] +name = "zstd-safe" +version = "5.0.2+zstd.1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d2a5585e04f9eea4b2a3d1eca508c4dee9592a89ef6f450c11719da0726f4db" +dependencies = [ + "libc", + "zstd-sys", +] + +[[package]] +name = "zstd-safe" +version = "7.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cd99b45c6bc03a018c8b8a86025678c87e55526064e38f9df301989dce7ec0a" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.10+zstd.1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa" +dependencies = [ + "cc", + "pkg-config", ] diff --git a/Cargo.toml b/Cargo.toml index 2387d84c80..81fe6644ae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ resolver = "2" members = ["crates/blockifier", "crates/native_blockifier"] [workspace.package] -version = "0.7.0-dev.1" +version = "0.8.0-dev.1" edition = "2021" repository = "https://github.com/starkware-libs/blockifier/" license = "Apache-2.0" @@ -20,12 +20,11 @@ ark-secp256k1 = "0.4.0" ark-secp256r1 = "0.4.0" assert_matches = "1.5.0" cached = "0.44.0" -cairo-felt = "0.9.1" -cairo-lang-casm = "2.6.0" -cairo-lang-runner = "2.6.0" -cairo-lang-starknet-classes = "2.6.0" -cairo-lang-utils = "2.6.0" -cairo-vm = "0.9.2" +cairo-lang-casm = "2.7.0-dev.0" +cairo-lang-runner = "2.7.0-dev.0" +cairo-lang-starknet-classes = "2.7.0-dev.0" +cairo-lang-utils = "2.7.0-dev.0" +cairo-vm = "1.0.0-rc3" criterion = "0.3" derive_more = "0.99.17" glob = "0.3.1" @@ -38,7 +37,7 @@ num-integer = "0.1.45" num-rational = { version = "0.4", features = ["serde"] } num-traits = "0.2" once_cell = "1.19.0" -papyrus_storage = "0.4.0-dev.1" +papyrus_storage = "0.4.0-dev.4" phf = { version = "0.11", features = ["macros"] } pretty_assertions = "1.2.1" pyo3 = "0.19.1" @@ -50,8 +49,8 @@ serde = "1.0.184" serde_json = "1.0.81" sha2 = "0.10.8" sha3 = "0.10.6" -starknet-crypto = "0.5.1" -starknet_api = "0.12.0-dev.0" +starknet-types-core = { version = "0.1.5", features = ["hash", "prime-bigint"] } +starknet_api = "0.13.0-dev.9" strum = "0.24.1" strum_macros = "0.24.3" tempfile = "3.7.0" diff --git a/crates/blockifier/Cargo.toml b/crates/blockifier/Cargo.toml index 498c0438c8..bf35900c7f 100644 --- a/crates/blockifier/Cargo.toml +++ b/crates/blockifier/Cargo.toml @@ -23,7 +23,6 @@ ark-ff.workspace = true ark-secp256k1.workspace = true ark-secp256r1.workspace = true cached.workspace = true -cairo-felt.workspace = true cairo-lang-casm = { workspace = true, features = ["parity-scale-codec"] } cairo-lang-runner.workspace = true cairo-lang-starknet-classes.workspace = true @@ -46,7 +45,7 @@ serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = ["arbitrary_precision"] } sha2.workspace = true sha3.workspace = true -starknet-crypto.workspace = true +starknet-types-core.workspace = true starknet_api = { workspace = true, features = ["testing"] } strum.workspace = true strum_macros.workspace = true diff --git a/crates/blockifier/src/abi/abi_utils.rs b/crates/blockifier/src/abi/abi_utils.rs index 1a89ca54e4..ba2f00175c 100644 --- a/crates/blockifier/src/abi/abi_utils.rs +++ b/crates/blockifier/src/abi/abi_utils.rs @@ -1,26 +1,26 @@ -use cairo_felt::Felt252; -use num_integer::Integer; use sha3::{Digest, Keccak256}; -use starknet_api::core::{ContractAddress, EntryPointSelector, L2_ADDRESS_UPPER_BOUND}; -use starknet_api::hash::{pedersen_hash, StarkFelt, StarkHash}; +use starknet_api::core::{ + ContractAddress, EntryPointSelector, PatriciaKey, L2_ADDRESS_UPPER_BOUND, +}; use starknet_api::state::StorageKey; +use starknet_types_core::felt::{Felt, NonZeroFelt}; +use starknet_types_core::hash::{Pedersen, StarkHash}; use crate::abi::constants; -use crate::execution::execution_utils::{felt_to_stark_felt, stark_felt_to_felt}; #[cfg(test)] #[path = "abi_utils_test.rs"] mod test; /// A variant of eth-keccak that computes a value that fits in a Starknet field element. -pub fn starknet_keccak(data: &[u8]) -> Felt252 { +pub fn starknet_keccak(data: &[u8]) -> Felt { let mut hasher = Keccak256::new(); hasher.update(data); - let mut result = hasher.finalize(); + let mut result: [u8; 32] = hasher.finalize().into(); // Truncate result to 250 bits. *result.first_mut().unwrap() &= 3; - Felt252::from_bytes_be(&result) + Felt::from_bytes_be(&result) } /// Returns an entry point selector, given its name. @@ -31,25 +31,26 @@ pub fn selector_from_name(entry_point_name: &str) -> EntryPointSelector { // The default entry points selector is not being mapped in the usual way in order to save // computations in the OS, and to avoid encoding the default entry point names there. if DEFAULT_ENTRY_POINTS.contains(&entry_point_name) { - EntryPointSelector(StarkHash::from(constants::DEFAULT_ENTRY_POINT_SELECTOR)) + EntryPointSelector(Felt::from(constants::DEFAULT_ENTRY_POINT_SELECTOR)) } else { - EntryPointSelector(felt_to_stark_felt(&starknet_keccak(entry_point_name.as_bytes()))) + EntryPointSelector(starknet_keccak(entry_point_name.as_bytes())) } } /// Returns the storage address of a Starknet storage variable given its name and arguments. -pub fn get_storage_var_address(storage_var_name: &str, args: &[StarkFelt]) -> StorageKey { +pub fn get_storage_var_address(storage_var_name: &str, args: &[Felt]) -> StorageKey { let storage_var_name_hash = starknet_keccak(storage_var_name.as_bytes()); - let storage_var_name_hash = felt_to_stark_felt(&storage_var_name_hash); let storage_key_hash = - args.iter().fold(storage_var_name_hash, |res, arg| pedersen_hash(&res, arg)); + args.iter().fold(storage_var_name_hash, |res, arg| Pedersen::hash(&res, arg)); - let storage_key = stark_felt_to_felt(storage_key_hash) - .mod_floor(&Felt252::from_bytes_be(&L2_ADDRESS_UPPER_BOUND.to_bytes_be())); + let storage_key = storage_key_hash + .mod_floor(&NonZeroFelt::from_raw(Felt::from(*L2_ADDRESS_UPPER_BOUND).to_raw())); - StorageKey::try_from(felt_to_stark_felt(&storage_key)) - .expect("Should be within bounds as retrieved mod L2_ADDRESS_UPPER_BOUND.") + StorageKey( + PatriciaKey::try_from(storage_key) + .expect("Should be within bounds as retrieved mod L2_ADDRESS_UPPER_BOUND."), + ) } /// Returns the storage key inside the fee token corresponding to the first storage cell where the diff --git a/crates/blockifier/src/abi/abi_utils_test.rs b/crates/blockifier/src/abi/abi_utils_test.rs index c2d02108a0..05ed2eb3c0 100644 --- a/crates/blockifier/src/abi/abi_utils_test.rs +++ b/crates/blockifier/src/abi/abi_utils_test.rs @@ -1,8 +1,7 @@ -use cairo_felt::Felt252; use num_bigint::BigUint; use starknet_api::core::EntryPointSelector; -use starknet_api::hash::StarkFelt; -use starknet_api::stark_felt; +use starknet_api::felt; +use starknet_types_core::felt::Felt; use crate::abi::abi_utils::selector_from_name; use crate::abi::constants as abi_constants; @@ -13,7 +12,7 @@ use crate::transaction::constants as transaction_constants; fn test_selector_from_name() { // Test default EP. let expected_default_selector = - EntryPointSelector(stark_felt!(abi_constants::DEFAULT_ENTRY_POINT_SELECTOR)); + EntryPointSelector(felt!(abi_constants::DEFAULT_ENTRY_POINT_SELECTOR)); assert_eq!( selector_from_name(abi_constants::DEFAULT_ENTRY_POINT_NAME), expected_default_selector @@ -26,7 +25,7 @@ fn test_selector_from_name() { // Test execute EP. let expected_execute_selector = "0x15d40a3d6ca2ac30f4031e42be28da9b056fef9bb7357ac5e85627ee876e5ad"; - let expected_execute_selector = EntryPointSelector(stark_felt!(expected_execute_selector)); + let expected_execute_selector = EntryPointSelector(felt!(expected_execute_selector)); assert_eq!( selector_from_name(transaction_constants::EXECUTE_ENTRY_POINT_NAME), expected_execute_selector @@ -35,7 +34,7 @@ fn test_selector_from_name() { // Test empty EP. let expected_empty_selector = "0x1d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"; - let expected_empty_selector = EntryPointSelector(stark_felt!(expected_empty_selector)); + let expected_empty_selector = EntryPointSelector(felt!(expected_empty_selector)); assert_eq!(selector_from_name(""), expected_empty_selector); } @@ -43,12 +42,12 @@ fn test_selector_from_name() { fn test_value_too_large_for_type() { // Happy flow. let n = 1991_u128; - let n_as_felt = Felt252::from(n); + let n_as_felt = Felt::from(n); felt_to_u128(&n_as_felt).unwrap(); // Value too large for type. let overflowed_u128: BigUint = BigUint::from(1_u8) << 128; - let overflowed_u128_as_felt = Felt252::from(overflowed_u128); + let overflowed_u128_as_felt = Felt::from(overflowed_u128); let error = felt_to_u128(&overflowed_u128_as_felt).unwrap_err(); assert_eq!( format!("{error}"), diff --git a/crates/blockifier/src/abi/constants.rs b/crates/blockifier/src/abi/constants.rs index 7a52b06db7..9b4818fd77 100644 --- a/crates/blockifier/src/abi/constants.rs +++ b/crates/blockifier/src/abi/constants.rs @@ -1,5 +1,5 @@ -use starknet_api::hash::StarkFelt; use starknet_api::transaction::TransactionVersion; +use starknet_types_core::felt::Felt; pub const CONSTRUCTOR_ENTRY_POINT_NAME: &str = "constructor"; pub const DEFAULT_ENTRY_POINT_NAME: &str = "__default__"; @@ -7,7 +7,7 @@ pub const DEFAULT_ENTRY_POINT_SELECTOR: u64 = 0; pub const DEFAULT_L1_ENTRY_POINT_NAME: &str = "__l1_default__"; // The version is considered 0 for L1-Handler transaction hash calculation purposes. -pub const L1_HANDLER_VERSION: TransactionVersion = TransactionVersion(StarkFelt::ZERO); +pub const L1_HANDLER_VERSION: TransactionVersion = TransactionVersion(Felt::ZERO); // OS-related constants. pub const L1_TO_L2_MSG_HEADER_SIZE: usize = 5; diff --git a/crates/blockifier/src/abi/sierra_types.rs b/crates/blockifier/src/abi/sierra_types.rs index 8e48744a16..1def7724f1 100644 --- a/crates/blockifier/src/abi/sierra_types.rs +++ b/crates/blockifier/src/abi/sierra_types.rs @@ -1,4 +1,3 @@ -use cairo_felt::Felt252; use cairo_vm::types::errors::math_errors::MathError; use cairo_vm::types::relocatable::Relocatable; use cairo_vm::vm::errors::memory_errors::MemoryError; @@ -6,13 +5,11 @@ use cairo_vm::vm::vm_core::VirtualMachine; use num_bigint::{BigUint, ToBigUint}; use num_traits::ToPrimitive; use starknet_api::core::{ContractAddress, PatriciaKey}; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; use starknet_api::StarknetApiError; -use starknet_crypto::FieldElement; +use starknet_types_core::felt::Felt; use thiserror::Error; -use crate::execution::execution_utils::stark_felt_to_felt; use crate::state::errors::StateError; use crate::state::state_api::StateReader; @@ -21,7 +18,7 @@ pub type SierraTypeResult = Result; #[derive(Debug, Error)] pub enum SierraTypeError { #[error("Felt {val} is too big to convert to '{ty}'.")] - ValueTooLargeForType { val: Felt252, ty: &'static str }, + ValueTooLargeForType { val: Felt, ty: &'static str }, #[error(transparent)] MemoryError(#[from] MemoryError), #[error(transparent)] @@ -44,20 +41,13 @@ pub trait SierraType: Sized { // Utils. -pub fn felt_to_u128(felt: &Felt252) -> Result { - felt.to_u128() - .ok_or_else(|| SierraTypeError::ValueTooLargeForType { val: felt.clone(), ty: "u128" }) -} - -pub fn stark_felt_to_u128(stark_felt: &StarkFelt) -> Result { - felt_to_u128(&stark_felt_to_felt(*stark_felt)) +pub fn felt_to_u128(felt: &Felt) -> Result { + felt.to_u128().ok_or_else(|| SierraTypeError::ValueTooLargeForType { val: *felt, ty: "u128" }) } // TODO(barak, 01/10/2023): Move to starknet_api under StorageKey implementation. pub fn next_storage_key(key: &StorageKey) -> Result { - Ok(StorageKey(PatriciaKey::try_from(StarkFelt::from( - FieldElement::from(*key.0.key()) + FieldElement::ONE, - ))?)) + Ok(StorageKey(PatriciaKey::try_from(*key.0.key() + Felt::ONE)?)) } // Implementations. @@ -77,9 +67,9 @@ impl SierraU128 { impl SierraType for SierraU128 { fn from_memory(vm: &VirtualMachine, ptr: &mut Relocatable) -> SierraTypeResult { - let val_as_felt = vm.get_integer(*ptr)?; + let felt = vm.get_integer(*ptr)?; *ptr = (*ptr + 1)?; - Ok(Self { val: felt_to_u128(&val_as_felt)? }) + Ok(Self { val: felt_to_u128(&felt)? }) } fn from_storage( @@ -87,8 +77,8 @@ impl SierraType for SierraU128 { contract_address: &ContractAddress, key: &StorageKey, ) -> SierraTypeResult { - let val_as_felt = stark_felt_to_felt(state.get_storage_at(*contract_address, *key)?); - Ok(Self { val: felt_to_u128(&val_as_felt)? }) + let felt = state.get_storage_at(*contract_address, *key)?; + Ok(Self { val: felt_to_u128(&felt)? }) } } diff --git a/crates/blockifier/src/blockifier/block.rs b/crates/blockifier/src/blockifier/block.rs index d3bd40932d..83be85d1a6 100644 --- a/crates/blockifier/src/blockifier/block.rs +++ b/crates/blockifier/src/blockifier/block.rs @@ -2,8 +2,8 @@ use std::num::NonZeroU128; use starknet_api::block::{BlockHash, BlockNumber, BlockTimestamp}; use starknet_api::core::ContractAddress; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; +use starknet_types_core::felt::Felt; use crate::abi::constants; use crate::state::errors::StateError; @@ -85,7 +85,7 @@ pub struct BlockNumberHashPair { } impl BlockNumberHashPair { - pub fn new(block_number: u64, block_hash: StarkFelt) -> BlockNumberHashPair { + pub fn new(block_number: u64, block_hash: Felt) -> BlockNumberHashPair { BlockNumberHashPair { number: BlockNumber(block_number), hash: BlockHash(block_hash) } } } diff --git a/crates/blockifier/src/blockifier/block_test.rs b/crates/blockifier/src/blockifier/block_test.rs index 4b36ac9b00..1f2447f8aa 100644 --- a/crates/blockifier/src/blockifier/block_test.rs +++ b/crates/blockifier/src/blockifier/block_test.rs @@ -1,6 +1,6 @@ use starknet_api::block::BlockNumber; use starknet_api::core::ContractAddress; -use starknet_api::hash::StarkFelt; +use starknet_api::felt; use starknet_api::state::StorageKey; use crate::abi::constants; @@ -18,7 +18,7 @@ fn test_pre_process_block() { // Test the positive flow of pre_process_block inside the allowed block number interval let block_number = BlockNumber(constants::STORED_BLOCK_HASH_BUFFER); - let block_hash = StarkFelt::from(20_u8); + let block_hash = felt!(20_u8); pre_process_block( &mut state, Some(BlockNumberHashPair::new(block_number.0, block_hash)), diff --git a/crates/blockifier/src/blockifier/stateful_validator.rs b/crates/blockifier/src/blockifier/stateful_validator.rs index 5b7f6696ef..d4fa4b6466 100644 --- a/crates/blockifier/src/blockifier/stateful_validator.rs +++ b/crates/blockifier/src/blockifier/stateful_validator.rs @@ -2,8 +2,8 @@ use std::sync::Arc; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use starknet_api::core::Nonce; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::TransactionHash; +use starknet_types_core::felt::Felt; use thiserror::Error; use crate::blockifier::config::TransactionExecutorConfig; @@ -136,8 +136,8 @@ impl StatefulValidator { let tx_nonce = tx_info.nonce(); let deploy_account_not_processed = - deploy_account_tx_hash.is_some() && nonce == Nonce(StarkFelt::ZERO); - let is_post_deploy_nonce = Nonce(StarkFelt::ONE) <= tx_nonce; + deploy_account_tx_hash.is_some() && nonce == Nonce(Felt::ZERO); + let is_post_deploy_nonce = Nonce(Felt::ONE) <= tx_nonce; let nonce_small_enough_to_qualify_for_validation_skip = tx_nonce <= self.max_nonce_for_validation_skip; diff --git a/crates/blockifier/src/blockifier/transaction_executor_test.rs b/crates/blockifier/src/blockifier/transaction_executor_test.rs index 507b84cf8b..6ed4347164 100644 --- a/crates/blockifier/src/blockifier/transaction_executor_test.rs +++ b/crates/blockifier/src/blockifier/transaction_executor_test.rs @@ -1,9 +1,9 @@ use assert_matches::assert_matches; use pretty_assertions::assert_eq; use rstest::rstest; -use starknet_api::hash::StarkFelt; -use starknet_api::stark_felt; +use starknet_api::felt; use starknet_api::transaction::{Fee, TransactionVersion}; +use starknet_types_core::felt::Felt; use crate::blockifier::config::TransactionExecutorConfig; use crate::blockifier::transaction_executor::{ @@ -146,8 +146,8 @@ fn test_deploy_account( #[case::invoke_function_base_case( "assert_eq", vec![ - stark_felt!(3_u32), // x. - stark_felt!(3_u32) // y. + felt!(3_u32), // x. + felt!(3_u32) // y. ], BouncerWeights { state_diff_size: 2, @@ -159,9 +159,9 @@ fn test_deploy_account( #[case::emit_event_syscall( "test_emit_events", vec![ - stark_felt!(1_u32), // events_number. - stark_felt!(0_u32), // keys length. - stark_felt!(0_u32) // data length. + felt!(1_u32), // events_number. + felt!(0_u32), // keys length. + felt!(0_u32) // data length. ], BouncerWeights { state_diff_size: 2, @@ -185,7 +185,7 @@ fn test_invoke( #[values(TransactionVersion::ONE, TransactionVersion::THREE)] version: TransactionVersion, #[values(CairoVersion::Cairo0, CairoVersion::Cairo1)] cairo_version: CairoVersion, #[case] entry_point_name: &str, - #[case] entry_point_args: Vec, + #[case] entry_point_args: Vec, #[case] expected_bouncer_weights: BouncerWeights, ) { let test_contract = FeatureContract::TestContract(cairo_version); diff --git a/crates/blockifier/src/bouncer.rs b/crates/blockifier/src/bouncer.rs index 47a4b7ae8e..417b2ddc27 100644 --- a/crates/blockifier/src/bouncer.rs +++ b/crates/blockifier/src/bouncer.rs @@ -1,7 +1,6 @@ use std::collections::{HashMap, HashSet}; -use cairo_vm::serde::deserialize_program::BuiltinName; -use cairo_vm::vm::runners::builtin_runner::HASH_BUILTIN_NAME; +use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use serde::{Deserialize, Serialize}; use starknet_api::core::ClassHash; @@ -36,7 +35,7 @@ macro_rules! impl_checked_sub { }; } -pub type HashMapWrapper = HashMap; +pub type HashMapWrapper = HashMap; #[derive(Clone, Debug, Default, PartialEq)] pub struct BouncerConfig { @@ -160,13 +159,13 @@ impl From for BuiltinCount { // ExecutionResources contains all the builtins. // The keccak config we get from python is not always present. let builtin_count = Self { - bitwise: data.remove(BuiltinName::bitwise.name()).unwrap_or_default(), - ecdsa: data.remove(BuiltinName::ecdsa.name()).unwrap_or_default(), - ec_op: data.remove(BuiltinName::ec_op.name()).unwrap_or_default(), - keccak: data.remove(BuiltinName::keccak.name()).unwrap_or_default(), - pedersen: data.remove(BuiltinName::pedersen.name()).unwrap_or_default(), - poseidon: data.remove(BuiltinName::poseidon.name()).unwrap_or_default(), - range_check: data.remove(BuiltinName::range_check.name()).unwrap_or_default(), + bitwise: data.remove(&BuiltinName::bitwise).unwrap_or_default(), + ecdsa: data.remove(&BuiltinName::ecdsa).unwrap_or_default(), + ec_op: data.remove(&BuiltinName::ec_op).unwrap_or_default(), + keccak: data.remove(&BuiltinName::keccak).unwrap_or_default(), + pedersen: data.remove(&BuiltinName::pedersen).unwrap_or_default(), + poseidon: data.remove(&BuiltinName::poseidon).unwrap_or_default(), + range_check: data.remove(&BuiltinName::range_check).unwrap_or_default(), }; assert!( data.is_empty(), @@ -319,7 +318,7 @@ pub fn get_particia_update_resources(n_visited_storage_entries: usize) -> Execut // TODO(Yoni, 1/5/2024): re-estimate this. n_steps: 32 * n_updates, // For each Patricia update there are two hash calculations. - builtin_instance_counter: HashMap::from([(HASH_BUILTIN_NAME.to_string(), 2 * n_updates)]), + builtin_instance_counter: HashMap::from([(BuiltinName::pedersen, 2 * n_updates)]), n_memory_holes: 0, } } diff --git a/crates/blockifier/src/bouncer_test.rs b/crates/blockifier/src/bouncer_test.rs index 2b8188447b..1b0dbb9e98 100644 --- a/crates/blockifier/src/bouncer_test.rs +++ b/crates/blockifier/src/bouncer_test.rs @@ -1,10 +1,9 @@ use std::collections::{HashMap, HashSet}; -use cairo_vm::serde::deserialize_program::BuiltinName; +use cairo_vm::types::builtin_name::BuiltinName; use rstest::rstest; use starknet_api::core::{ClassHash, ContractAddress, PatriciaKey}; -use starknet_api::hash::StarkHash; -use starknet_api::{class_hash, contract_address, patricia_key}; +use starknet_api::{class_hash, contract_address, felt, patricia_key}; use super::BouncerConfig; use crate::blockifier::transaction_executor::{ @@ -241,13 +240,13 @@ fn test_bouncer_try_update( // Prepare the resources to be added to the bouncer. let execution_summary = ExecutionSummary { ..Default::default() }; let builtin_counter = HashMap::from([ - (BuiltinName::bitwise.name().to_string(), 1), - (BuiltinName::ecdsa.name().to_string(), added_ecdsa), - (BuiltinName::ec_op.name().to_string(), 1), - (BuiltinName::keccak.name().to_string(), added_keccak), - (BuiltinName::pedersen.name().to_string(), 1), - (BuiltinName::poseidon.name().to_string(), 1), - (BuiltinName::range_check.name().to_string(), 1), + (BuiltinName::bitwise, 1), + (BuiltinName::ecdsa, added_ecdsa), + (BuiltinName::ec_op, 1), + (BuiltinName::keccak, added_keccak), + (BuiltinName::pedersen, 1), + (BuiltinName::poseidon, 1), + (BuiltinName::range_check, 1), ]); let tx_resources = TransactionResources { vm_resources: ExecutionResources { diff --git a/crates/blockifier/src/concurrency/fee_utils.rs b/crates/blockifier/src/concurrency/fee_utils.rs index 00b45131cb..b839d8e97f 100644 --- a/crates/blockifier/src/concurrency/fee_utils.rs +++ b/crates/blockifier/src/concurrency/fee_utils.rs @@ -2,13 +2,11 @@ use std::collections::HashMap; use num_traits::ToPrimitive; use starknet_api::core::ContractAddress; -use starknet_api::hash::StarkFelt; -use starknet_api::stark_felt; use starknet_api::transaction::Fee; +use starknet_types_core::felt::Felt; use crate::context::{BlockContext, TransactionContext}; use crate::execution::call_info::CallInfo; -use crate::execution::execution_utils::stark_felt_to_felt; use crate::fee::fee_utils::get_sequencer_balance_keys; use crate::state::cached_state::{ContractClassMapping, StateMaps}; use crate::state::state_api::UpdatableState; @@ -70,14 +68,14 @@ pub fn complete_fee_transfer_flow( // fee transfer is executed with a false (constant) sequencer balance. This affects the call info. pub fn fill_sequencer_balance_reads( fee_transfer_call_info: &mut CallInfo, - sequencer_balance: (StarkFelt, StarkFelt), + sequencer_balance: (Felt, Felt), ) { let storage_read_values = &mut fee_transfer_call_info.storage_read_values; assert_eq!(storage_read_values.len(), 4, "Storage read values should have 4 elements"); let (low_index, high_index) = STORAGE_READ_SEQUENCER_BALANCE_INDICES; for index in [low_index, high_index] { - assert_eq!(storage_read_values[index], StarkFelt::ZERO, "Sequencer balance should be zero"); + assert_eq!(storage_read_values[index], Felt::ZERO, "Sequencer balance should be zero"); } let (low, high) = sequencer_balance; storage_read_values[low_index] = low; @@ -89,13 +87,13 @@ pub fn add_fee_to_sequencer_balance( state: &mut impl UpdatableState, actual_fee: Fee, block_context: &BlockContext, - sequencer_balance: (StarkFelt, StarkFelt), + sequencer_balance: (Felt, Felt), ) { let (low, high) = sequencer_balance; let sequencer_balance_low_as_u128 = - stark_felt_to_felt(low).to_u128().expect("sequencer balance low should be u128"); + low.to_u128().expect("sequencer balance low should be u128"); let sequencer_balance_high_as_u128 = - stark_felt_to_felt(high).to_u128().expect("sequencer balance high should be u128"); + high.to_u128().expect("sequencer balance high should be u128"); let (new_value_low, carry) = sequencer_balance_low_as_u128.overflowing_add(actual_fee.0); let (new_value_high, carry) = sequencer_balance_high_as_u128.overflowing_add(carry.into()); assert!( @@ -106,8 +104,8 @@ pub fn add_fee_to_sequencer_balance( get_sequencer_balance_keys(block_context); let writes = StateMaps { storage: HashMap::from([ - ((fee_token_address, sequencer_balance_key_low), stark_felt!(new_value_low)), - ((fee_token_address, sequencer_balance_key_high), stark_felt!(new_value_high)), + ((fee_token_address, sequencer_balance_key_low), Felt::from(new_value_low)), + ((fee_token_address, sequencer_balance_key_high), Felt::from(new_value_high)), ]), ..StateMaps::default() }; diff --git a/crates/blockifier/src/concurrency/fee_utils_test.rs b/crates/blockifier/src/concurrency/fee_utils_test.rs index f73ad7f8b0..99356f8671 100644 --- a/crates/blockifier/src/concurrency/fee_utils_test.rs +++ b/crates/blockifier/src/concurrency/fee_utils_test.rs @@ -1,14 +1,12 @@ -use cairo_felt::Felt252; use num_bigint::BigUint; use rstest::rstest; -use starknet_api::hash::StarkFelt; -use starknet_api::stark_felt; +use starknet_api::felt; use starknet_api::transaction::{Fee, ResourceBoundsMapping, TransactionVersion}; +use starknet_types_core::felt::Felt; use crate::concurrency::fee_utils::{add_fee_to_sequencer_balance, fill_sequencer_balance_reads}; use crate::concurrency::test_utils::create_fee_transfer_call_info; use crate::context::BlockContext; -use crate::execution::execution_utils::{felt_to_stark_felt, stark_felt_to_felt}; use crate::fee::fee_utils::get_sequencer_balance_keys; use crate::invoke_tx_args; use crate::state::state_api::StateReader; @@ -45,20 +43,20 @@ pub fn test_fill_sequencer_balance_reads( fill_sequencer_balance_reads( &mut concurrency_call_info, - (StarkFelt::from(sequencer_balance), StarkFelt::ZERO), + (Felt::from(sequencer_balance), Felt::ZERO), ); assert_eq!(concurrency_call_info, call_info); } #[rstest] -#[case::no_overflow(Fee(50_u128), stark_felt!(100_u128), StarkFelt::ZERO)] -#[case::overflow(Fee(150_u128), stark_felt!(u128::MAX), stark_felt!(5_u128))] -#[case::overflow_edge_case(Fee(500_u128), stark_felt!(u128::MAX), stark_felt!(u128::MAX-1))] +#[case::no_overflow(Fee(50_u128), felt!(100_u128), Felt::ZERO)] +#[case::overflow(Fee(150_u128), felt!(u128::MAX), felt!(5_u128))] +#[case::overflow_edge_case(Fee(500_u128), felt!(u128::MAX), felt!(u128::MAX-1))] pub fn test_add_fee_to_sequencer_balance( - #[case] actual_fee: Fee, - #[case] sequencer_balance_low: StarkFelt, - #[case] sequencer_balance_high: StarkFelt, + #[case] actual_fee: starknet_api::transaction::Fee, + #[case] sequencer_balance_low: Felt, + #[case] sequencer_balance_high: Felt, ) { let block_context = BlockContext::create_for_account_testing_with_concurrency_mode(true); let account = FeatureContract::Empty(CairoVersion::Cairo1); @@ -80,20 +78,13 @@ pub fn test_add_fee_to_sequencer_balance( state.get_storage_at(fee_token_address, sequencer_balance_key_low).unwrap(); let new_sequencer_balance_value_high = state.get_storage_at(fee_token_address, sequencer_balance_key_high).unwrap(); - let expected_balance = - (stark_felt_to_felt(sequencer_balance_low) + Felt252::from(actual_fee.0)).to_biguint(); + let expected_balance = (sequencer_balance_low + Felt::from(actual_fee.0)).to_biguint(); let mask_128_bit = (BigUint::from(1_u8) << 128) - 1_u8; - let expected_sequencer_balance_value_low = Felt252::from(&expected_balance & mask_128_bit); + let expected_sequencer_balance_value_low = Felt::from(&expected_balance & mask_128_bit); let expected_sequencer_balance_value_high = - stark_felt_to_felt(sequencer_balance_high) + Felt252::from(&expected_balance >> 128); + sequencer_balance_high + Felt::from(&expected_balance >> 128); - assert_eq!( - new_sequencer_balance_value_low, - felt_to_stark_felt(&expected_sequencer_balance_value_low) - ); - assert_eq!( - new_sequencer_balance_value_high, - felt_to_stark_felt(&expected_sequencer_balance_value_high) - ); + assert_eq!(new_sequencer_balance_value_low, expected_sequencer_balance_value_low); + assert_eq!(new_sequencer_balance_value_high, expected_sequencer_balance_value_high); } diff --git a/crates/blockifier/src/concurrency/flow_test.rs b/crates/blockifier/src/concurrency/flow_test.rs index 19989ae46f..c89644940b 100644 --- a/crates/blockifier/src/concurrency/flow_test.rs +++ b/crates/blockifier/src/concurrency/flow_test.rs @@ -4,8 +4,7 @@ use std::sync::Arc; use rstest::rstest; use starknet_api::core::{ContractAddress, PatriciaKey}; -use starknet_api::hash::{StarkFelt, StarkHash}; -use starknet_api::{contract_address, patricia_key, stark_felt}; +use starknet_api::{contract_address, felt, patricia_key}; use crate::abi::sierra_types::{SierraType, SierraU128}; use crate::concurrency::scheduler::{Scheduler, Task, TransactionStatus}; @@ -114,7 +113,7 @@ fn scheduler_flow_test( *storage_writes .get(&(contract_address!(CONTRACT_ADDRESS), storage_key!(STORAGE_KEY))) .unwrap(), - stark_felt!(format!("{:x}", tx_index + 1).as_str()) + felt!(format!("{:x}", tx_index + 1).as_str()) ); } } @@ -168,7 +167,7 @@ fn state_maps_with_single_storage_entry(value: u128) -> StateMaps { StateMaps { storage: HashMap::from([( (contract_address!(CONTRACT_ADDRESS), storage_key!(STORAGE_KEY)), - stark_felt!(value), + felt!(value), )]), ..Default::default() } diff --git a/crates/blockifier/src/concurrency/test_utils.rs b/crates/blockifier/src/concurrency/test_utils.rs index f8834334d6..237740212e 100644 --- a/crates/blockifier/src/concurrency/test_utils.rs +++ b/crates/blockifier/src/concurrency/test_utils.rs @@ -1,7 +1,6 @@ use rstest::fixture; use starknet_api::core::{ClassHash, ContractAddress, PatriciaKey}; -use starknet_api::hash::StarkHash; -use starknet_api::{class_hash, contract_address, patricia_key}; +use starknet_api::{class_hash, contract_address, felt, patricia_key}; use crate::concurrency::versioned_state::{ThreadSafeVersionedState, VersionedState}; use crate::context::BlockContext; diff --git a/crates/blockifier/src/concurrency/versioned_state.rs b/crates/blockifier/src/concurrency/versioned_state.rs index fd36781f74..b01355e6ef 100644 --- a/crates/blockifier/src/concurrency/versioned_state.rs +++ b/crates/blockifier/src/concurrency/versioned_state.rs @@ -2,8 +2,8 @@ use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex, MutexGuard}; use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; +use starknet_types_core::felt::Felt; use crate::concurrency::versioned_storage::VersionedStorage; use crate::concurrency::TxIndex; @@ -26,7 +26,7 @@ const READ_ERR: &str = "Error: read value missing in the versioned storage"; pub struct VersionedState { // TODO(barak, 01/08/2024): Change initial_state to state. initial_state: S, - storage: VersionedStorage<(ContractAddress, StorageKey), StarkFelt>, + storage: VersionedStorage<(ContractAddress, StorageKey), Felt>, nonces: VersionedStorage, class_hashes: VersionedStorage, compiled_class_hashes: VersionedStorage, @@ -288,7 +288,7 @@ impl StateReader for VersionedStateProxy { &self, contract_address: ContractAddress, key: StorageKey, - ) -> StateResult { + ) -> StateResult { let mut state = self.state(); match state.storage.read(self.tx_index, (contract_address, key)) { Some(value) => Ok(value), @@ -354,7 +354,7 @@ impl StateReader for VersionedStateProxy { // values. We artificially insert zero for undeclared contracts. state .compiled_class_hashes - .set_initial_value(class_hash, CompiledClassHash(StarkFelt::ZERO)); + .set_initial_value(class_hash, CompiledClassHash(Felt::ZERO)); Err(StateError::UndeclaredClassHash(class_hash))? } Err(error) => Err(error)?, diff --git a/crates/blockifier/src/concurrency/versioned_state_test.rs b/crates/blockifier/src/concurrency/versioned_state_test.rs index 467ccb9ba3..d50fac2f48 100644 --- a/crates/blockifier/src/concurrency/versioned_state_test.rs +++ b/crates/blockifier/src/concurrency/versioned_state_test.rs @@ -4,10 +4,11 @@ use std::thread; use assert_matches::assert_matches; use rstest::{fixture, rstest}; -use starknet_api::core::{calculate_contract_address, ClassHash, ContractAddress, PatriciaKey}; -use starknet_api::hash::{StarkFelt, StarkHash}; +use starknet_api::core::{ + calculate_contract_address, ClassHash, ContractAddress, Nonce, PatriciaKey, +}; use starknet_api::transaction::{Calldata, ContractAddressSalt, Fee, TransactionVersion}; -use starknet_api::{calldata, class_hash, contract_address, patricia_key, stark_felt}; +use starknet_api::{calldata, class_hash, contract_address, felt, patricia_key}; use crate::abi::abi_utils::{get_fee_token_var_address, get_storage_var_address}; use crate::concurrency::test_utils::{ @@ -51,8 +52,8 @@ fn test_versioned_state_proxy() { // Test data let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let contract_address = contract_address!("0x1"); - let key = storage_key!("0x10"); - let stark_felt = stark_felt!(13_u8); + let key = storage_key!(0x10_u8); + let felt = felt!(13_u8); let nonce = nonce!(2_u8); let class_hash = class_hash!(27_u8); let another_class_hash = class_hash!(28_u8); @@ -61,7 +62,7 @@ fn test_versioned_state_proxy() { // Create the versioned state let cached_state = CachedState::from(DictStateReader { - storage_view: HashMap::from([((contract_address, key), stark_felt)]), + storage_view: HashMap::from([((contract_address, key), felt)]), address_to_nonce: HashMap::from([(contract_address, nonce)]), address_to_class_hash: HashMap::from([(contract_address, class_hash)]), class_hash_to_compiled_class_hash: HashMap::from([(class_hash, compiled_class_hash)]), @@ -77,10 +78,7 @@ fn test_versioned_state_proxy() { // Read initial data assert_eq!(versioned_state_proxys[5].get_nonce_at(contract_address).unwrap(), nonce); assert_eq!(versioned_state_proxys[0].get_nonce_at(contract_address).unwrap(), nonce); - assert_eq!( - versioned_state_proxys[7].get_storage_at(contract_address, key).unwrap(), - stark_felt - ); + assert_eq!(versioned_state_proxys[7].get_storage_at(contract_address, key).unwrap(), felt); assert_eq!(versioned_state_proxys[2].get_class_hash_at(contract_address).unwrap(), class_hash); assert_eq!( versioned_state_proxys[5].get_compiled_class_hash(class_hash).unwrap(), @@ -100,8 +98,8 @@ fn test_versioned_state_proxy() { ); // Write to the state. - let new_key = storage_key!("0x11"); - let stark_felt_v3 = stark_felt!(14_u8); + let new_key = storage_key!(0x11_u8); + let felt_v3 = felt!(14_u8); let nonce_v4 = nonce!(3_u8); let class_hash_v7 = class_hash!(28_u8); let class_hash_v10 = class_hash!(29_u8); @@ -111,7 +109,7 @@ fn test_versioned_state_proxy() { versioned_state_proxys[3].state().apply_writes( 3, &StateMaps { - storage: HashMap::from([((contract_address, new_key), stark_felt_v3)]), + storage: HashMap::from([((contract_address, new_key), felt_v3)]), declared_contracts: HashMap::from([(another_class_hash, true)]), ..Default::default() }, @@ -155,13 +153,10 @@ fn test_versioned_state_proxy() { // Read the data assert_eq!(versioned_state_proxys[2].get_nonce_at(contract_address).unwrap(), nonce); assert_eq!(versioned_state_proxys[5].get_nonce_at(contract_address).unwrap(), nonce_v4); - assert_eq!( - versioned_state_proxys[5].get_storage_at(contract_address, key).unwrap(), - stark_felt - ); + assert_eq!(versioned_state_proxys[5].get_storage_at(contract_address, key).unwrap(), felt); assert_eq!( versioned_state_proxys[5].get_storage_at(contract_address, new_key).unwrap(), - stark_felt_v3 + felt_v3 ); assert_eq!(versioned_state_proxys[2].get_class_hash_at(contract_address).unwrap(), class_hash); assert_eq!( @@ -232,8 +227,8 @@ fn test_run_parallel_txs() { let enforce_fee = account_tx_1.create_tx_info().enforce_fee().unwrap(); let class_hash = grindy_account.get_class_hash(); - let ctor_storage_arg = stark_felt!(1_u8); - let ctor_grind_arg = stark_felt!(0_u8); // Do not grind in deploy phase. + let ctor_storage_arg = felt!(1_u8); + let ctor_grind_arg = felt!(0_u8); // Do not grind in deploy phase. let constructor_calldata = calldata![ctor_grind_arg, ctor_storage_arg]; let deploy_tx_args = deploy_account_tx_args! { class_hash, @@ -248,7 +243,7 @@ fn test_run_parallel_txs() { let deployed_account_balance_key = get_fee_token_var_address(account_address); let fee_token_address = chain_info.fee_token_address(&FeeType::Eth); state_2 - .set_storage_at(fee_token_address, deployed_account_balance_key, stark_felt!(BALANCE)) + .set_storage_at(fee_token_address, deployed_account_balance_key, felt!(BALANCE)) .unwrap(); let block_context_1 = block_context.clone(); @@ -284,7 +279,7 @@ fn test_validate_reads( class_hash: ClassHash, safe_versioned_state: ThreadSafeVersionedState>, ) { - let storage_key = storage_key!("0x10"); + let storage_key = storage_key!(0x10_u8); let mut version_state_proxy = safe_versioned_state.pin_version(1); let transactional_state = TransactionalState::create_transactional(&mut version_state_proxy); @@ -328,13 +323,13 @@ fn test_validate_reads( #[case::storage( StateMaps { storage: HashMap::from( - [((contract_address!("0x1"), storage_key!("0x1")), stark_felt!(1_u8))] + [((contract_address!("0x1"), storage_key!("0x1")), felt!(1_u8))] ), ..Default::default() }, StateMaps { storage: HashMap::from( - [((contract_address!("0x1"), storage_key!("0x1")), stark_felt!(2_u8))] + [((contract_address!("0x1"), storage_key!("0x1")), felt!(2_u8))] ), ..Default::default() } @@ -543,18 +538,15 @@ fn test_delete_writes_completeness( ) { let feature_contract = FeatureContract::TestContract(CairoVersion::Cairo1); let state_maps_writes = StateMaps { - nonces: HashMap::from([(contract_address!("0x1"), nonce!("0x1"))]), + nonces: HashMap::from([(contract_address!("0x1"), Nonce(felt!(1_u8)))]), class_hashes: HashMap::from([( contract_address!("0x1"), feature_contract.get_class_hash(), )]), - storage: HashMap::from([( - (contract_address!("0x1"), storage_key!("0x1")), - stark_felt!("0x1"), - )]), + storage: HashMap::from([((contract_address!("0x1"), storage_key!(1_u8)), felt!("0x1"))]), compiled_class_hashes: HashMap::from([( feature_contract.get_class_hash(), - compiled_class_hash!("0x1"), + compiled_class_hash!(0x1_u16), )]), declared_contracts: HashMap::from([(feature_contract.get_class_hash(), true)]), }; @@ -604,7 +596,7 @@ fn test_versioned_proxy_state_flow( safe_versioned_state: ThreadSafeVersionedState>, ) { let contract_address = contract_address!("0x1"); - let class_hash = ClassHash(stark_felt!(27_u8)); + let class_hash = ClassHash(felt!(27_u8)); let mut versioned_proxy_states: Vec>> = (0..4).map(|i| safe_versioned_state.pin_version(i)).collect(); @@ -615,8 +607,8 @@ fn test_versioned_proxy_state_flow( } // Clients class hash values. - let class_hash_1 = ClassHash(stark_felt!(76_u8)); - let class_hash_3 = ClassHash(stark_felt!(234_u8)); + let class_hash_1 = ClassHash(felt!(76_u8)); + let class_hash_3 = ClassHash(felt!(234_u8)); transactional_states[1].set_class_hash_at(contract_address, class_hash_1).unwrap(); transactional_states[3].set_class_hash_at(contract_address, class_hash_3).unwrap(); diff --git a/crates/blockifier/src/concurrency/worker_logic_test.rs b/crates/blockifier/src/concurrency/worker_logic_test.rs index d6270c5a84..1e258e95ba 100644 --- a/crates/blockifier/src/concurrency/worker_logic_test.rs +++ b/crates/blockifier/src/concurrency/worker_logic_test.rs @@ -3,9 +3,9 @@ use std::sync::Mutex; use rstest::rstest; use starknet_api::core::{ContractAddress, Nonce, PatriciaKey}; -use starknet_api::hash::{StarkFelt, StarkHash}; use starknet_api::transaction::{ContractAddressSalt, ResourceBoundsMapping, TransactionVersion}; -use starknet_api::{contract_address, patricia_key, stark_felt}; +use starknet_api::{contract_address, felt, patricia_key}; +use starknet_types_core::felt::Felt; use super::WorkerExecutor; use crate::abi::abi_utils::get_fee_token_var_address; @@ -62,8 +62,8 @@ fn verify_sequencer_balance_update( let (sequencer_balance_key_low, sequencer_balance_key_high) = get_sequencer_balance_keys(block_context); for (expected_balance, storage_key) in [ - (stark_felt!(expected_sequencer_balance_low), sequencer_balance_key_low), - (StarkFelt::ZERO, sequencer_balance_key_high), + (felt!(expected_sequencer_balance_low), sequencer_balance_key_low), + (Felt::ZERO, sequencer_balance_key_high), ] { let actual_balance = tx_version_state .get_storage_at( @@ -163,10 +163,7 @@ pub fn test_commit_tx() { .as_ref() .unwrap() .storage_read_values[read_storage_index]; - assert_eq!( - stark_felt!(expected_sequencer_storage_read), - actual_sequencer_storage_read, - ); + assert_eq!(felt!(expected_sequencer_storage_read), actual_sequencer_storage_read,); } } let tx_context = executor.block_context.to_tx_context(&txs[commit_idx]); @@ -268,7 +265,7 @@ fn test_worker_execute(max_resource_bounds: ResourceBoundsMapping) { let test_contract_address = test_contract.get_instance_address(0); let account_address = account_contract.get_instance_address(0); let nonce_manager = &mut NonceManager::default(); - let storage_value = stark_felt!(93_u8); + let storage_value = felt!(93_u8); let storage_key = storage_key!(1993_u16); let tx_success = account_invoke_tx(invoke_tx_args! { @@ -301,7 +298,7 @@ fn test_worker_execute(max_resource_bounds: ResourceBoundsMapping) { calldata: create_calldata( test_contract_address, "write_and_revert", - &[stark_felt!(1991_u16),storage_value ], // Calldata: address, value. + &[felt!(1991_u16),storage_value ], // Calldata: address, value. ), resource_bounds: max_resource_bounds, nonce: nonce_manager.next(account_address) @@ -356,8 +353,8 @@ fn test_worker_execute(max_resource_bounds: ResourceBoundsMapping) { nonces: HashMap::from([(account_address, nonce!(1_u8))]), storage: HashMap::from([ ((test_contract_address, storage_key), storage_value), - ((erc_contract_address, account_balance_key_low), stark_felt!(account_balance)), - ((erc_contract_address, account_balance_key_high), stark_felt!(0_u8)), + ((erc_contract_address, account_balance_key_low), felt!(account_balance)), + ((erc_contract_address, account_balance_key_high), felt!(0_u8)), ]), ..Default::default() }; @@ -370,9 +367,9 @@ fn test_worker_execute(max_resource_bounds: ResourceBoundsMapping) { (erc_contract_address, erc20.get_class_hash()), ]), storage: HashMap::from([ - ((test_contract_address, storage_key), stark_felt!(0_u8)), - ((erc_contract_address, account_balance_key_low), stark_felt!(BALANCE)), - ((erc_contract_address, account_balance_key_high), stark_felt!(0_u8)), + ((test_contract_address, storage_key), felt!(0_u8)), + ((erc_contract_address, account_balance_key_low), felt!(BALANCE)), + ((erc_contract_address, account_balance_key_high), felt!(0_u8)), ]), // When running an entry point, we load its contract class. declared_contracts: HashMap::from([ @@ -445,8 +442,8 @@ fn test_worker_validate(max_resource_bounds: ResourceBoundsMapping) { let test_contract_address = test_contract.get_instance_address(0); let account_address = account_contract.get_instance_address(0); let nonce_manager = &mut NonceManager::default(); - let storage_value0 = stark_felt!(93_u8); - let storage_value1 = stark_felt!(39_u8); + let storage_value0 = felt!(93_u8); + let storage_value1 = felt!(39_u8); let storage_key = storage_key!(1993_u16); // Both transactions change the same storage key. @@ -569,9 +566,9 @@ fn test_deploy_before_declare(max_resource_bounds: ResourceBoundsMapping) { &[ test_class_hash.0, // Class hash. ContractAddressSalt::default().0, // Salt. - stark_felt!(2_u8), // Constructor calldata length. - stark_felt!(1_u8), // Constructor calldata arg1. - stark_felt!(1_u8), // Constructor calldata arg2. + felt!(2_u8), // Constructor calldata length. + felt!(1_u8), // Constructor calldata arg1. + felt!(1_u8), // Constructor calldata arg2. ] ), resource_bounds: max_resource_bounds, @@ -639,7 +636,7 @@ fn test_worker_commit_phase(max_resource_bounds: ResourceBoundsMapping) { let test_contract_address = test_contract.get_instance_address(0); let sender_address = account_contract.get_instance_address(0); let nonce_manager = &mut NonceManager::default(); - let storage_value = stark_felt!(93_u8); + let storage_value = felt!(93_u8); let storage_key = storage_key!(1993_u16); let calldata = create_calldata( test_contract_address, diff --git a/crates/blockifier/src/context.rs b/crates/blockifier/src/context.rs index f755c47009..659406c31f 100644 --- a/crates/blockifier/src/context.rs +++ b/crates/blockifier/src/context.rs @@ -91,7 +91,7 @@ impl ChainInfo { impl Default for ChainInfo { fn default() -> Self { ChainInfo { - chain_id: ChainId("0x0".to_string()), + chain_id: ChainId::Other("0x0".to_string()), fee_token_addresses: FeeTokenAddresses::default(), } } diff --git a/crates/blockifier/src/execution/call_info.rs b/crates/blockifier/src/execution/call_info.rs index b73bce0828..1efef68115 100644 --- a/crates/blockifier/src/execution/call_info.rs +++ b/crates/blockifier/src/execution/call_info.rs @@ -1,21 +1,21 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::iter::Sum; use std::ops::Add; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; -use serde::{Deserialize, Serialize}; +use serde::Serialize; use starknet_api::core::{ClassHash, ContractAddress, EthAddress, PatriciaKey}; -use starknet_api::hash::{StarkFelt, StarkHash}; -use starknet_api::patricia_key; use starknet_api::state::StorageKey; use starknet_api::transaction::{EventContent, L2ToL1Payload}; +use starknet_api::{felt, patricia_key}; +use starknet_types_core::felt::Felt; use crate::execution::entry_point::CallEntryPoint; use crate::fee::gas_usage::get_message_segment_length; use crate::state::cached_state::StorageEntry; #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)] -pub struct Retdata(pub Vec); +pub struct Retdata(pub Vec); #[macro_export] macro_rules! retdata { @@ -83,15 +83,6 @@ pub struct CallExecution { pub gas_consumed: u64, } -// This struct is used to implement `serde` functionality in a remote `ExecutionResources` Struct. -#[derive(Debug, Default, Deserialize, derive_more::From, Eq, PartialEq, Serialize)] -#[serde(remote = "ExecutionResources")] -struct ExecutionResourcesDef { - n_steps: usize, - n_memory_holes: usize, - builtin_instance_counter: HashMap, -} - #[derive(Default)] pub struct ExecutionSummary { pub executed_class_hashes: HashSet, @@ -158,7 +149,7 @@ impl TestExecutionSummary { order: i, message: MessageToL1 { to_address: EthAddress::default(), - payload: L2ToL1Payload(vec![StarkFelt::default()]), + payload: L2ToL1Payload(vec![Felt::default()]), }, }) .collect(), @@ -175,12 +166,11 @@ impl TestExecutionSummary { pub struct CallInfo { pub call: CallEntryPoint, pub execution: CallExecution, - #[serde(with = "ExecutionResourcesDef")] pub resources: ExecutionResources, pub inner_calls: Vec, // Additional information gathered during execution. - pub storage_read_values: Vec, + pub storage_read_values: Vec, pub accessed_storage_keys: HashSet, } diff --git a/crates/blockifier/src/execution/common_hints.rs b/crates/blockifier/src/execution/common_hints.rs index 17d51b525c..962984c0c8 100644 --- a/crates/blockifier/src/execution/common_hints.rs +++ b/crates/blockifier/src/execution/common_hints.rs @@ -2,7 +2,6 @@ use std::collections::HashMap; use std::ops::Shl; use std::rc::Rc; -use cairo_felt::{Felt252, PRIME_STR}; use cairo_vm::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::{ BuiltinHintProcessor, HintFunc, }; @@ -13,11 +12,10 @@ use cairo_vm::hint_processor::hint_processor_definition::HintReference; use cairo_vm::serde::deserialize_program::ApTracking; use cairo_vm::types::exec_scope::ExecutionScopes; use cairo_vm::vm::errors::hint_errors::HintError; -use cairo_vm::vm::errors::vm_errors::VirtualMachineError; use cairo_vm::vm::runners::cairo_runner::RunResources; use cairo_vm::vm::vm_core::VirtualMachine; use num_bigint::BigUint; -use num_traits::{Num, One, Zero}; +use starknet_types_core::felt::Felt; use crate::execution::hint_code::{ NORMALIZE_ADDRESS_SET_IS_250_HINT, NORMALIZE_ADDRESS_SET_IS_SMALL_HINT, @@ -41,7 +39,7 @@ pub fn normalize_address_set_is_small( _execution_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, - constants: &HashMap, + constants: &HashMap, ) -> HintExecutionResult { const ADDR_BOUND: &str = "starkware.starknet.common.storage.ADDR_BOUND"; let addr_bound = &constants @@ -49,8 +47,7 @@ pub fn normalize_address_set_is_small( .ok_or_else(|| HintError::MissingConstant("ADDR_BOUND".into()))? .to_biguint(); let addr = get_integer_from_var_name("addr", vm, ids_data, ap_tracking)?.to_biguint(); - let prime = BigUint::from_str_radix(&PRIME_STR[2..], 16) - .map_err(|_| VirtualMachineError::CouldntParsePrime(PRIME_STR.into()))?; + let prime = Felt::prime(); if !(addr_bound > &BigUint::from(1u8).shl(250) && addr_bound <= &BigUint::from(1u8).shl(251) @@ -67,7 +64,7 @@ pub fn normalize_address_set_is_small( )); } - let is_small = if addr < *addr_bound { Felt252::one() } else { Felt252::zero() }; + let is_small = if addr < *addr_bound { Felt::ONE } else { Felt::ZERO }; insert_value_from_var_name("is_small", is_small, vm, ids_data, ap_tracking) } @@ -77,12 +74,11 @@ pub fn normalize_address_set_is_250( _execution_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, - _constants: &HashMap, + _constants: &HashMap, ) -> HintExecutionResult { let addr = get_integer_from_var_name("addr", vm, ids_data, ap_tracking)?; - let is_250 = - if *addr < (Felt252::one() << (250_u32)) { Felt252::one() } else { Felt252::zero() }; + let is_250 = if addr < (Felt::TWO.pow(250_u128)) { Felt::ONE } else { Felt::ZERO }; insert_value_from_var_name("is_250", is_250, vm, ids_data, ap_tracking) } diff --git a/crates/blockifier/src/execution/contract_address_test.rs b/crates/blockifier/src/execution/contract_address_test.rs index 86c74171a9..405360da1e 100644 --- a/crates/blockifier/src/execution/contract_address_test.rs +++ b/crates/blockifier/src/execution/contract_address_test.rs @@ -1,8 +1,7 @@ use rstest::rstest; use starknet_api::core::{calculate_contract_address, ClassHash, ContractAddress}; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::{Calldata, ContractAddressSalt}; -use starknet_api::{calldata, stark_felt}; +use starknet_api::{calldata, felt}; use crate::abi::abi_utils::selector_from_name; use crate::context::ChainInfo; @@ -56,19 +55,19 @@ fn test_calculate_contract_address() { let calldata_no_constructor = calldata![ salt.0, // Contract_address_salt. class_hash.0, // Class hash. - stark_felt!(0_u8), // Calldata length. + felt!(0_u8), // Calldata length. *deployer_address.0.key() // deployer_address. ]; run_test(salt, class_hash, &calldata![], calldata_no_constructor, deployer_address, &mut state); // With constructor. - let constructor_calldata = calldata![stark_felt!(1_u8), stark_felt!(1_u8)]; + let constructor_calldata = calldata![felt!(1_u8), felt!(1_u8)]; let calldata = calldata![ salt.0, // Contract_address_salt. class_hash.0, // Class hash. - stark_felt!(2_u8), // Calldata length. - stark_felt!(1_u8), // Calldata: address. - stark_felt!(1_u8), // Calldata: value. + felt!(2_u8), // Calldata length. + felt!(1_u8), // Calldata: address. + felt!(1_u8), // Calldata: value. *deployer_address.0.key() // deployer_address. ]; run_test(salt, class_hash, &constructor_calldata, calldata, deployer_address, &mut state); diff --git a/crates/blockifier/src/execution/contract_class.rs b/crates/blockifier/src/execution/contract_class.rs index f632afac69..36e1391a07 100644 --- a/crates/blockifier/src/execution/contract_class.rs +++ b/crates/blockifier/src/execution/contract_class.rs @@ -2,7 +2,6 @@ use std::collections::{HashMap, HashSet}; use std::ops::Deref; use std::sync::Arc; -use cairo_felt::Felt252; use cairo_lang_casm; use cairo_lang_casm::hints::Hint; use cairo_lang_starknet_classes::casm_contract_class::{CasmContractClass, CasmContractEntryPoint}; @@ -10,10 +9,10 @@ use cairo_lang_starknet_classes::NestedIntList; use cairo_vm::serde::deserialize_program::{ ApTracking, FlowTrackingData, HintParams, ReferenceManager, }; +use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::types::errors::program_errors::ProgramError; use cairo_vm::types::program::Program; use cairo_vm::types::relocatable::MaybeRelocatable; -use cairo_vm::vm::runners::builtin_runner::{HASH_BUILTIN_NAME, POSEIDON_BUILTIN_NAME}; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use itertools::Itertools; use serde::de::Error as DeserializationError; @@ -23,13 +22,14 @@ use starknet_api::deprecated_contract_class::{ ContractClass as DeprecatedContractClass, EntryPoint, EntryPointOffset, EntryPointType, Program as DeprecatedProgram, }; +use starknet_types_core::felt::Felt; use super::execution_utils::poseidon_hash_many_cost; use crate::abi::abi_utils::selector_from_name; use crate::abi::constants::{self, CONSTRUCTOR_ENTRY_POINT_NAME}; use crate::execution::entry_point::CallEntryPoint; use crate::execution::errors::{ContractClassError, PreExecutionError}; -use crate::execution::execution_utils::{felt_to_stark_felt, sn_api_to_cairo_vm_program}; +use crate::execution::execution_utils::sn_api_to_cairo_vm_program; use crate::fee::eth_gas_constants; use crate::transaction::errors::TransactionExecutionError; @@ -124,10 +124,7 @@ impl ContractClassV0 { ExecutionResources { n_steps, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([( - HASH_BUILTIN_NAME.to_string(), - hashed_data_size, - )]), + builtin_instance_counter: HashMap::from([(BuiltinName::pedersen, hashed_data_size)]), } } @@ -256,7 +253,7 @@ pub fn estimate_casm_hash_computation_resources( &ExecutionResources { n_steps: 474, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([(POSEIDON_BUILTIN_NAME.to_string(), 10)]), + builtin_instance_counter: HashMap::from([(BuiltinName::poseidon, 10)]), } + &poseidon_hash_many_cost(*length) } NestedIntList::Node(segments) => { @@ -264,12 +261,12 @@ pub fn estimate_casm_hash_computation_resources( let mut execution_resources = ExecutionResources { n_steps: 491, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([(POSEIDON_BUILTIN_NAME.to_string(), 11)]), + builtin_instance_counter: HashMap::from([(BuiltinName::poseidon, 11)]), }; let base_segment_cost = ExecutionResources { n_steps: 24, n_memory_holes: 1, - builtin_instance_counter: HashMap::from([(POSEIDON_BUILTIN_NAME.to_string(), 1)]), + builtin_instance_counter: HashMap::from([(BuiltinName::poseidon, 1)]), }; for segment in segments { let NestedIntList::Leaf(length) = segment else { @@ -360,7 +357,7 @@ impl TryFrom for ContractClassV1 { let data: Vec = class .bytecode .into_iter() - .map(|x| MaybeRelocatable::from(Felt252::from(x.value))) + .map(|x| MaybeRelocatable::from(Felt::from(x.value))) .collect(); let mut hints: HashMap> = HashMap::new(); @@ -456,7 +453,7 @@ fn convert_entry_points_v1( .into_iter() .map(|ep| -> Result<_, ProgramError> { Ok(EntryPointV1 { - selector: EntryPointSelector(felt_to_stark_felt(&Felt252::from(ep.selector))), + selector: EntryPointSelector(Felt::from(ep.selector)), offset: EntryPointOffset(ep.offset), builtins: ep.builtins.into_iter().map(|builtin| builtin + "_builtin").collect(), }) diff --git a/crates/blockifier/src/execution/deprecated_entry_point_execution.rs b/crates/blockifier/src/execution/deprecated_entry_point_execution.rs index 6908575ee4..73b2c7b855 100644 --- a/crates/blockifier/src/execution/deprecated_entry_point_execution.rs +++ b/crates/blockifier/src/execution/deprecated_entry_point_execution.rs @@ -1,7 +1,7 @@ +use cairo_vm::types::layout_name::LayoutName; use cairo_vm::types::relocatable::{MaybeRelocatable, Relocatable}; use cairo_vm::vm::errors::vm_errors::VirtualMachineError; use cairo_vm::vm::runners::cairo_runner::{CairoArg, CairoRunner, ExecutionResources}; -use cairo_vm::vm::vm_core::VirtualMachine; use starknet_api::core::EntryPointSelector; use starknet_api::deprecated_contract_class::EntryPointType; use starknet_api::hash::StarkHash; @@ -15,14 +15,11 @@ use crate::execution::entry_point::{ CallEntryPoint, EntryPointExecutionContext, EntryPointExecutionResult, }; use crate::execution::errors::{PostExecutionError, PreExecutionError}; -use crate::execution::execution_utils::{ - read_execution_retdata, stark_felt_to_felt, Args, ReadOnlySegments, -}; +use crate::execution::execution_utils::{read_execution_retdata, Args, ReadOnlySegments}; use crate::state::state_api::State; pub struct VmExecutionContext<'a> { pub runner: CairoRunner, - pub vm: VirtualMachine, pub syscall_handler: DeprecatedSyscallHintProcessor<'a>, pub initial_syscall_ptr: Relocatable, pub entry_point_pc: usize, @@ -36,17 +33,12 @@ pub fn execute_entry_point_call( resources: &mut ExecutionResources, context: &mut EntryPointExecutionContext, ) -> EntryPointExecutionResult { - let VmExecutionContext { - mut runner, - mut vm, - mut syscall_handler, - initial_syscall_ptr, - entry_point_pc, - } = initialize_execution_context(&call, contract_class, state, resources, context)?; + let VmExecutionContext { mut runner, mut syscall_handler, initial_syscall_ptr, entry_point_pc } = + initialize_execution_context(&call, contract_class, state, resources, context)?; let (implicit_args, args) = prepare_call_arguments( &call, - &mut vm, + &mut runner, initial_syscall_ptr, &mut syscall_handler.read_only_segments, )?; @@ -56,10 +48,9 @@ pub fn execute_entry_point_call( let previous_resources = syscall_handler.resources.clone(); // Execute. - run_entry_point(&mut vm, &mut runner, &mut syscall_handler, entry_point_pc, args)?; + run_entry_point(&mut runner, &mut syscall_handler, entry_point_pc, args)?; Ok(finalize_execution( - vm, runner, syscall_handler, call, @@ -81,16 +72,17 @@ pub fn initialize_execution_context<'a>( // Instantiate Cairo runner. let proof_mode = false; - let mut runner = CairoRunner::new(&contract_class.program, "starknet", proof_mode)?; - let trace_enabled = false; - let mut vm = VirtualMachine::new(trace_enabled); + let allow_missing_builtins = false; + let program_base = None; + let mut runner = + CairoRunner::new(&contract_class.program, LayoutName::starknet, proof_mode, trace_enabled)?; - runner.initialize_builtins(&mut vm)?; - runner.initialize_segments(&mut vm, None); + runner.initialize_builtins(allow_missing_builtins)?; + runner.initialize_segments(program_base); // Instantiate syscall handler. - let initial_syscall_ptr = vm.add_memory_segment(); + let initial_syscall_ptr = runner.vm.add_memory_segment(); let syscall_handler = DeprecatedSyscallHintProcessor::new( state, resources, @@ -100,7 +92,7 @@ pub fn initialize_execution_context<'a>( call.caller_address, ); - Ok(VmExecutionContext { runner, vm, syscall_handler, initial_syscall_ptr, entry_point_pc }) + Ok(VmExecutionContext { runner, syscall_handler, initial_syscall_ptr, entry_point_pc }) } pub fn resolve_entry_point_pc( @@ -153,40 +145,44 @@ pub fn resolve_entry_point_pc( pub fn prepare_call_arguments( call: &CallEntryPoint, - vm: &mut VirtualMachine, + runner: &mut CairoRunner, initial_syscall_ptr: Relocatable, read_only_segments: &mut ReadOnlySegments, ) -> Result<(Vec, Args), PreExecutionError> { let mut args: Args = vec![]; // Prepare called EP details. - let entry_point_selector = - MaybeRelocatable::from(stark_felt_to_felt(call.entry_point_selector.0)); + let entry_point_selector = MaybeRelocatable::from(call.entry_point_selector.0); args.push(CairoArg::from(entry_point_selector)); // Prepare implicit arguments. let mut implicit_args = vec![]; implicit_args.push(MaybeRelocatable::from(initial_syscall_ptr)); implicit_args.extend( - vm.get_builtin_runners().iter().flat_map(|builtin_runner| builtin_runner.initial_stack()), + runner + .vm + .get_builtin_runners() + .iter() + .flat_map(|builtin_runner| builtin_runner.initial_stack()), ); args.push(CairoArg::from(implicit_args.clone())); // Prepare calldata arguments. let calldata = &call.calldata.0; let calldata: Vec = - calldata.iter().map(|&arg| MaybeRelocatable::from(stark_felt_to_felt(arg))).collect(); + calldata.iter().map(|&arg| MaybeRelocatable::from(arg)).collect(); let calldata_length = MaybeRelocatable::from(calldata.len()); args.push(CairoArg::from(calldata_length)); - let calldata_start_ptr = MaybeRelocatable::from(read_only_segments.allocate(vm, &calldata)?); + let calldata_start_ptr = + MaybeRelocatable::from(read_only_segments.allocate(&mut runner.vm, &calldata)?); args.push(CairoArg::from(calldata_start_ptr)); Ok((implicit_args, args)) } + /// Runs the runner from the given PC. pub fn run_entry_point( - vm: &mut VirtualMachine, runner: &mut CairoRunner, hint_processor: &mut DeprecatedSyscallHintProcessor<'_>, entry_point_pc: usize, @@ -200,7 +196,6 @@ pub fn run_entry_point( &args, verify_secure, program_segment_size, - vm, hint_processor, ); @@ -208,8 +203,7 @@ pub fn run_entry_point( } pub fn finalize_execution( - mut vm: VirtualMachine, - runner: CairoRunner, + mut runner: CairoRunner, syscall_handler: DeprecatedSyscallHintProcessor<'_>, call: CallEntryPoint, previous_resources: ExecutionResources, @@ -222,19 +216,19 @@ pub fn finalize_execution( .expect("The initial_fp field should be initialized after running the entry point."); // When execution starts the stack holds the EP arguments + [ret_fp, ret_pc]. let args_ptr = (initial_fp - (n_total_args + 2))?; - vm.mark_address_range_as_accessed(args_ptr, n_total_args)?; - syscall_handler.read_only_segments.mark_as_accessed(&mut vm)?; + runner.vm.mark_address_range_as_accessed(args_ptr, n_total_args)?; + syscall_handler.read_only_segments.mark_as_accessed(&mut runner)?; // Validate run. let [retdata_size, retdata_ptr]: [MaybeRelocatable; 2] = - vm.get_return_values(2)?.try_into().expect("Return values must be of size 2."); - let implicit_args_end_ptr = (vm.get_ap() - 2)?; - validate_run(&mut vm, &runner, &syscall_handler, implicit_args, implicit_args_end_ptr)?; + runner.vm.get_return_values(2)?.try_into().expect("Return values must be of size 2."); + let implicit_args_end_ptr = (runner.vm.get_ap() - 2)?; + validate_run(&mut runner, &syscall_handler, implicit_args, implicit_args_end_ptr)?; // Take into account the VM execution resources of the current call, without inner calls. // Has to happen after marking holes in segments as accessed. let vm_resources_without_inner_calls = runner - .get_execution_resources(&vm) + .get_execution_resources() .map_err(VirtualMachineError::RunnerError)? .filter_unused_builtins(); *syscall_handler.resources += &vm_resources_without_inner_calls; @@ -247,7 +241,7 @@ pub fn finalize_execution( Ok(CallInfo { call, execution: CallExecution { - retdata: read_execution_retdata(&vm, retdata_size, &retdata_ptr)?, + retdata: read_execution_retdata(&runner, retdata_size, &retdata_ptr)?, events: syscall_handler.events, l2_to_l1_messages: syscall_handler.l2_to_l1_messages, failed: false, @@ -261,15 +255,14 @@ pub fn finalize_execution( } pub fn validate_run( - vm: &mut VirtualMachine, - runner: &CairoRunner, + runner: &mut CairoRunner, syscall_handler: &DeprecatedSyscallHintProcessor<'_>, implicit_args: Vec, implicit_args_end: Relocatable, ) -> Result<(), PostExecutionError> { // Validate builtins' final stack. let mut current_builtin_ptr = implicit_args_end; - current_builtin_ptr = runner.get_builtins_final_stack(vm, current_builtin_ptr)?; + current_builtin_ptr = runner.get_builtins_final_stack(current_builtin_ptr)?; // Validate implicit arguments segment length is unchanged. // Subtract one to get to the first implicit arg segment (the syscall pointer). @@ -290,8 +283,9 @@ pub fn validate_run( } // Validate syscall segment size. - let syscall_end_ptr = vm.get_relocatable(implicit_args_start)?; - let syscall_used_size = vm + let syscall_end_ptr = runner.vm.get_relocatable(implicit_args_start)?; + let syscall_used_size = runner + .vm .get_segment_used_size( syscall_start_ptr .segment_index @@ -310,5 +304,5 @@ pub fn validate_run( PostExecutionError::SecurityValidationError("Syscall segment end".to_string()) })?; - syscall_handler.read_only_segments.validate(vm) + syscall_handler.read_only_segments.validate(&runner.vm) } diff --git a/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs b/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs index 54d2242ecf..3106d562db 100644 --- a/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs +++ b/crates/blockifier/src/execution/deprecated_syscalls/deprecated_syscalls_test.rs @@ -1,19 +1,18 @@ use std::collections::{HashMap, HashSet}; -use cairo_felt::Felt252; -use cairo_vm::vm::runners::builtin_runner::RANGE_CHECK_BUILTIN_NAME; +use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use num_traits::Pow; use pretty_assertions::assert_eq; use rstest::rstest; use starknet_api::core::{calculate_contract_address, ChainId, PatriciaKey}; -use starknet_api::hash::{StarkFelt, StarkHash}; use starknet_api::state::StorageKey; use starknet_api::transaction::{ Calldata, ContractAddressSalt, EventContent, EventData, EventKey, Fee, TransactionHash, TransactionVersion, }; -use starknet_api::{calldata, stark_felt}; +use starknet_api::{calldata, felt}; +use starknet_types_core::felt::Felt; use test_case::test_case; use crate::abi::abi_utils::selector_from_name; @@ -23,7 +22,6 @@ use crate::execution::common_hints::ExecutionMode; use crate::execution::deprecated_syscalls::DeprecatedSyscallSelector; use crate::execution::entry_point::{CallEntryPoint, CallType}; use crate::execution::errors::EntryPointExecutionError; -use crate::execution::execution_utils::felt_to_stark_felt; use crate::execution::syscalls::hint_processor::EmitEventError; use crate::state::state_api::StateReader; use crate::test_utils::contracts::FeatureContract; @@ -45,8 +43,8 @@ fn test_storage_read_write() { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let mut state = test_state(&ChainInfo::create_for_testing(), 0, &[(test_contract, 1)]); - let key = stark_felt!(1234_u16); - let value = stark_felt!(18_u8); + let key = felt!(1234_u16); + let value = felt!(18_u8); let calldata = calldata![key, value]; let entry_point_call = CallEntryPoint { calldata, @@ -56,7 +54,7 @@ fn test_storage_read_write() { let storage_address = entry_point_call.storage_address; assert_eq!( entry_point_call.execute_directly(&mut state).unwrap().execution, - CallExecution::from_retdata(retdata![stark_felt!(value)]) + CallExecution::from_retdata(retdata![value]) ); // Verify that the state has changed. let value_from_state = @@ -70,11 +68,11 @@ fn test_library_call() { let mut state = test_state(&ChainInfo::create_for_testing(), 0, &[(test_contract, 1)]); let inner_entry_point_selector = selector_from_name("test_storage_read_write"); let calldata = calldata![ - stark_felt!(test_contract.get_class_hash().0), // Class hash. - inner_entry_point_selector.0, // Function selector. - stark_felt!(2_u8), // Calldata length. - stark_felt!(1234_u16), // Calldata: address. - stark_felt!(91_u16) // Calldata: value. + test_contract.get_class_hash().0, // Class hash. + inner_entry_point_selector.0, // Function selector. + felt!(2_u8), // Calldata length. + felt!(1234_u16), // Calldata: address. + felt!(91_u16) // Calldata: value. ]; let entry_point_call = CallEntryPoint { entry_point_selector: selector_from_name("test_library_call"), @@ -84,7 +82,7 @@ fn test_library_call() { }; assert_eq!( entry_point_call.execute_directly(&mut state).unwrap().execution, - CallExecution::from_retdata(retdata![stark_felt!(91_u16)]) + CallExecution::from_retdata(retdata![felt!(91_u16)]) ); } @@ -96,12 +94,12 @@ fn test_nested_library_call() { let outer_entry_point_selector = selector_from_name("test_library_call"); let inner_entry_point_selector = selector_from_name("test_storage_read_write"); let main_entry_point_calldata = calldata![ - stark_felt!(test_contract.get_class_hash().0), // Class hash. - outer_entry_point_selector.0, // Library call function selector. - inner_entry_point_selector.0, // Storage function selector. - stark_felt!(2_u8), // Calldata length. - stark_felt!(key), // Calldata: address. - stark_felt!(value) // Calldata: value. + test_contract.get_class_hash().0, // Class hash. + outer_entry_point_selector.0, // Library call function selector. + inner_entry_point_selector.0, // Storage function selector. + felt!(2_u8), // Calldata length. + felt!(key), // Calldata: address. + felt!(value) // Calldata: value. ]; // Create expected call info tree. @@ -113,7 +111,7 @@ fn test_nested_library_call() { }; let nested_storage_entry_point = CallEntryPoint { entry_point_selector: inner_entry_point_selector, - calldata: calldata![stark_felt!(key + 1), stark_felt!(value + 1)], + calldata: calldata![felt!(key + 1), felt!(value + 1)], class_hash: Some(test_contract.get_class_hash()), code_address: None, call_type: CallType::Delegate, @@ -122,11 +120,11 @@ fn test_nested_library_call() { let library_entry_point = CallEntryPoint { entry_point_selector: outer_entry_point_selector, calldata: calldata![ - stark_felt!(test_contract.get_class_hash().0), // Class hash. - inner_entry_point_selector.0, // Storage function selector. - stark_felt!(2_u8), // Calldata length. - stark_felt!(key + 1), // Calldata: address. - stark_felt!(value + 1) // Calldata: value. + test_contract.get_class_hash().0, // Class hash. + inner_entry_point_selector.0, // Storage function selector. + felt!(2_u8), // Calldata length. + felt!(key + 1), // Calldata: address. + felt!(value + 1) // Calldata: value. ], class_hash: Some(test_contract.get_class_hash()), code_address: None, @@ -134,19 +132,19 @@ fn test_nested_library_call() { ..trivial_external_entry_point_new(test_contract) }; let storage_entry_point = CallEntryPoint { - calldata: calldata![stark_felt!(key), stark_felt!(value)], + calldata: calldata![felt!(key), felt!(value)], ..nested_storage_entry_point }; let storage_entry_point_resources = ExecutionResources { n_steps: 218, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([(RANGE_CHECK_BUILTIN_NAME.to_string(), 2)]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, 2)]), }; let nested_storage_call_info = CallInfo { call: nested_storage_entry_point, - execution: CallExecution::from_retdata(retdata![stark_felt!(value + 1)]), + execution: CallExecution::from_retdata(retdata![felt!(value + 1)]), resources: storage_entry_point_resources.clone(), - storage_read_values: vec![stark_felt!(value + 1)], + storage_read_values: vec![felt!(value + 1)], accessed_storage_keys: HashSet::from([storage_key!(key + 1)]), ..Default::default() }; @@ -154,21 +152,21 @@ fn test_nested_library_call() { + &ExecutionResources { n_steps: 39, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([(RANGE_CHECK_BUILTIN_NAME.to_string(), 1)]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, 1)]), }; library_call_resources += &storage_entry_point_resources; let library_call_info = CallInfo { call: library_entry_point, - execution: CallExecution::from_retdata(retdata![stark_felt!(value + 1)]), + execution: CallExecution::from_retdata(retdata![felt!(value + 1)]), resources: library_call_resources.clone(), inner_calls: vec![nested_storage_call_info], ..Default::default() }; let storage_call_info = CallInfo { call: storage_entry_point, - execution: CallExecution::from_retdata(retdata![stark_felt!(value)]), + execution: CallExecution::from_retdata(retdata![felt!(value)]), resources: storage_entry_point_resources.clone(), - storage_read_values: vec![stark_felt!(value)], + storage_read_values: vec![felt!(value)], accessed_storage_keys: HashSet::from([storage_key!(key)]), ..Default::default() }; @@ -183,7 +181,7 @@ fn test_nested_library_call() { main_call_resources += &(&library_call_resources * 2); let expected_call_info = CallInfo { call: main_entry_point.clone(), - execution: CallExecution::from_retdata(retdata![stark_felt!(0_u8)]), + execution: CallExecution::from_retdata(retdata![felt!(0_u8)]), resources: main_call_resources, inner_calls: vec![library_call_info, storage_call_info], ..Default::default() @@ -202,12 +200,13 @@ fn test_call_contract() { let trivial_external_entry_point = trivial_external_entry_point_new(test_contract); let outer_entry_point_selector = selector_from_name("test_call_contract"); let inner_entry_point_selector = selector_from_name("test_storage_read_write"); - let (key, value) = (stark_felt!(405_u16), stark_felt!(48_u8)); + let (key_int, value_int) = (405_u16, 48_u8); + let (key, value) = (felt!(key_int), felt!(value_int)); let inner_calldata = calldata![key, value]; let calldata = calldata![ *test_address.0.key(), // Contract address. inner_entry_point_selector.0, // Function selector. - stark_felt!(2_u8), // Calldata length. + felt!(2_u8), // Calldata length. key, // Calldata: address. value // Calldata: value. ]; @@ -231,10 +230,10 @@ fn test_call_contract() { resources: ExecutionResources { n_steps: 218, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([(RANGE_CHECK_BUILTIN_NAME.to_string(), 2)]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, 2)]), }, - storage_read_values: vec![stark_felt!(value)], - accessed_storage_keys: HashSet::from([storage_key!(key)]), + storage_read_values: vec![value], + accessed_storage_keys: HashSet::from([storage_key!(key_int)]), ..Default::default() }; let expected_call_info = CallInfo { @@ -250,10 +249,7 @@ fn test_call_contract() { + &ExecutionResources { n_steps: 257, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([( - RANGE_CHECK_BUILTIN_NAME.to_string(), - 3, - )]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, 3)]), }, ..Default::default() }; @@ -270,7 +266,7 @@ fn test_replace_class() { let mut state = test_state(chain_info, 0, &[(test_contract, 1), (empty_contract, 1)]); let test_address = test_contract.get_instance_address(0); // Replace with undeclared class hash. - let calldata = calldata![stark_felt!(1234_u16)]; + let calldata = calldata![felt!(1234_u16)]; let entry_point_call = CallEntryPoint { calldata, entry_point_selector: selector_from_name("test_replace_class"), @@ -317,7 +313,7 @@ fn test_replace_class() { true, true, true, false, Some(format!( "Invalid syscall input: {:?}; {:}", - stark_felt!(2_u8), + felt!(2_u8), "The deploy_from_zero field in the deploy system call must be 0 or 1.", )) // With constructor, nontrivial calldata, address available, corrupt deploy from zero; @@ -342,8 +338,8 @@ fn test_deploy( }; let constructor_calldata = if supply_constructor_calldata { vec![ - stark_felt!(1_u8), // Calldata: address. - stark_felt!(1_u8), // Calldata: value. + felt!(1_u8), // Calldata: address. + felt!(1_u8), // Calldata: value. ] } else { vec![] @@ -385,22 +381,22 @@ fn test_deploy( } #[test_case( - ExecutionMode::Execute, "block_number", calldata![stark_felt!(CURRENT_BLOCK_NUMBER)]; + ExecutionMode::Execute, "block_number", calldata![felt!(CURRENT_BLOCK_NUMBER)]; "Test the syscall get_block_number in execution mode Execute")] #[test_case( - ExecutionMode::Validate, "block_number", calldata![stark_felt!(CURRENT_BLOCK_NUMBER_FOR_VALIDATE)]; + ExecutionMode::Validate, "block_number", calldata![felt!(CURRENT_BLOCK_NUMBER_FOR_VALIDATE)]; "Test the syscall get_block_number in execution mode Validate")] #[test_case( - ExecutionMode::Execute, "block_timestamp", calldata![stark_felt!(CURRENT_BLOCK_TIMESTAMP)]; + ExecutionMode::Execute, "block_timestamp", calldata![felt!(CURRENT_BLOCK_TIMESTAMP)]; "Test the syscall get_block_timestamp in execution mode Execute")] #[test_case( - ExecutionMode::Validate, "block_timestamp", calldata![stark_felt!(CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE)]; + ExecutionMode::Validate, "block_timestamp", calldata![felt!(CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE)]; "Test the syscall get_block_timestamp in execution mode Validate")] #[test_case( - ExecutionMode::Execute, "sequencer_address", calldata![stark_felt!(TEST_SEQUENCER_ADDRESS)]; + ExecutionMode::Execute, "sequencer_address", calldata![felt!(TEST_SEQUENCER_ADDRESS)]; "Test the syscall get_sequencer_address in execution mode Execute")] #[test_case( - ExecutionMode::Validate, "sequencer_address", calldata![stark_felt!(0_u64)]; + ExecutionMode::Validate, "sequencer_address", calldata![felt!(0_u64)]; "Test the syscall get_sequencer_address in execution mode Validate")] fn test_block_info_syscalls( execution_mode: ExecutionMode, @@ -444,22 +440,22 @@ fn test_block_info_syscalls( fn test_tx_info(#[values(false, true)] only_query: bool) { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let mut state = test_state(&ChainInfo::create_for_testing(), 0, &[(test_contract, 1)]); - let mut version = Felt252::from(1_u8); + let mut version = felt!(1_u8); if only_query { - let simulate_version_base = Pow::pow(Felt252::from(2_u8), QUERY_VERSION_BASE_BIT); + let simulate_version_base = Pow::pow(felt!(2_u8), QUERY_VERSION_BASE_BIT); version += simulate_version_base; } - let tx_hash = TransactionHash(stark_felt!(1991_u16)); + let tx_hash = TransactionHash(felt!(1991_u16)); let max_fee = Fee(0); let nonce = nonce!(3_u16); let sender_address = test_contract.get_instance_address(0); let expected_tx_info = calldata![ - felt_to_stark_felt(&version), // Transaction version. - *sender_address.0.key(), // Account address. - stark_felt!(max_fee.0), // Max fee. - tx_hash.0, // Transaction hash. - stark_felt!(&*ChainId(CHAIN_ID_NAME.to_string()).as_hex()), // Chain ID. - nonce.0 // Nonce. + version, // Transaction version. + *sender_address.0.key(), // Account address. + felt!(max_fee.0), // Max fee. + tx_hash.0, // Transaction hash. + felt!(&*ChainId::Other(CHAIN_ID_NAME.to_string()).as_hex()), // Chain ID. + nonce.0 // Nonce. ]; let entry_point_selector = selector_from_name("test_get_tx_info"); let entry_point_call = CallEntryPoint { @@ -490,9 +486,9 @@ fn test_tx_info(#[values(false, true)] only_query: bool) { fn test_emit_event() { let versioned_constants = VersionedConstants::create_for_testing(); // Positive flow. - let keys = vec![stark_felt!(2019_u16), stark_felt!(2020_u16)]; - let data = vec![stark_felt!(2021_u16), stark_felt!(2022_u16), stark_felt!(2023_u16)]; - let n_emitted_events = vec![stark_felt!(1_u16)]; + let keys = vec![felt!(2019_u16), felt!(2020_u16)]; + let data = vec![felt!(2021_u16), felt!(2022_u16), felt!(2023_u16)]; + let n_emitted_events = vec![felt!(1_u16)]; let call_info = emit_events(&n_emitted_events, &keys, &data).unwrap(); let event = EventContent { keys: keys.clone().into_iter().map(EventKey).collect(), @@ -509,7 +505,7 @@ fn test_emit_event() { // Negative flow, the data length exceeds the limit. let max_event_data_length = versioned_constants.tx_event_limits.max_data_length; - let data_too_long = vec![stark_felt!(2_u16); max_event_data_length + 1]; + let data_too_long = vec![felt!(2_u16); max_event_data_length + 1]; let error = emit_events(&n_emitted_events, &keys, &data_too_long).unwrap_err(); let expected_error = EmitEventError::ExceedsMaxDataLength { data_length: max_event_data_length + 1, @@ -519,7 +515,7 @@ fn test_emit_event() { // Negative flow, the keys length exceeds the limit. let max_event_keys_length = versioned_constants.tx_event_limits.max_keys_length; - let keys_too_long = vec![stark_felt!(1_u16); max_event_keys_length + 1]; + let keys_too_long = vec![felt!(1_u16); max_event_keys_length + 1]; let error = emit_events(&n_emitted_events, &keys_too_long, &data).unwrap_err(); let expected_error = EmitEventError::ExceedsMaxKeysLength { keys_length: max_event_keys_length + 1, @@ -529,7 +525,7 @@ fn test_emit_event() { // Negative flow, the number of events exceeds the limit. let max_n_emitted_events = versioned_constants.tx_event_limits.max_n_emitted_events; - let n_emitted_events_too_big = vec![stark_felt!( + let n_emitted_events_too_big = vec![felt!( u16::try_from(max_n_emitted_events + 1).expect("Failed to convert usize to u16.") )]; let error = emit_events(&n_emitted_events_too_big, &keys, &data).unwrap_err(); @@ -541,18 +537,18 @@ fn test_emit_event() { } fn emit_events( - n_emitted_events: &[StarkFelt], - keys: &[StarkFelt], - data: &[StarkFelt], + n_emitted_events: &[Felt], + keys: &[Felt], + data: &[Felt], ) -> Result { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let mut state = test_state(&ChainInfo::create_for_testing(), 0, &[(test_contract, 1)]); let calldata = Calldata( [ n_emitted_events.to_owned(), - vec![stark_felt!(u16::try_from(keys.len()).expect("Failed to convert usize to u16."))], + vec![felt!(u16::try_from(keys.len()).expect("Failed to convert usize to u16."))], keys.to_vec(), - vec![stark_felt!(u16::try_from(data.len()).expect("Failed to convert usize to u16."))], + vec![felt!(u16::try_from(data.len()).expect("Failed to convert usize to u16."))], data.to_vec(), ] .concat() diff --git a/crates/blockifier/src/execution/deprecated_syscalls/hint_processor.rs b/crates/blockifier/src/execution/deprecated_syscalls/hint_processor.rs index 1a78de1dc4..c73e914967 100644 --- a/crates/blockifier/src/execution/deprecated_syscalls/hint_processor.rs +++ b/crates/blockifier/src/execution/deprecated_syscalls/hint_processor.rs @@ -1,7 +1,6 @@ use std::any::Any; use std::collections::{HashMap, HashSet}; -use cairo_felt::Felt252; use cairo_vm::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::{ BuiltinHintProcessor, HintProcessorData, }; @@ -16,12 +15,13 @@ use cairo_vm::vm::errors::memory_errors::MemoryError; use cairo_vm::vm::errors::vm_errors::VirtualMachineError; use cairo_vm::vm::runners::cairo_runner::{ExecutionResources, ResourceTracker, RunResources}; use cairo_vm::vm::vm_core::VirtualMachine; +use num_bigint::{BigUint, TryFromBigIntError}; use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector}; use starknet_api::deprecated_contract_class::EntryPointType; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; use starknet_api::transaction::Calldata; use starknet_api::StarknetApiError; +use starknet_types_core::felt::{Felt, FromStrError}; use thiserror::Error; use crate::blockifier::block::BlockInfo; @@ -41,8 +41,8 @@ use crate::execution::deprecated_syscalls::{ use crate::execution::entry_point::{CallEntryPoint, CallType, EntryPointExecutionContext}; use crate::execution::errors::{ConstructorEntryPointExecutionError, EntryPointExecutionError}; use crate::execution::execution_utils::{ - felt_range_from_ptr, max_fee_for_execution_info, stark_felt_from_ptr, stark_felt_to_felt, - ReadOnlySegment, ReadOnlySegments, + felt_from_ptr, felt_range_from_ptr, max_fee_for_execution_info, ReadOnlySegment, + ReadOnlySegments, }; use crate::execution::hint_code; use crate::execution::syscalls::hint_processor::EmitEventError; @@ -68,6 +68,10 @@ pub enum DeprecatedSyscallExecutionError { }, #[error(transparent)] EmitEventError(#[from] EmitEventError), + #[error(transparent)] + FromBigUint(#[from] TryFromBigIntError), + #[error(transparent)] + FromStr(#[from] FromStrError), #[error("{error}")] LibraryCallExecutionError { class_hash: ClassHash, @@ -76,9 +80,9 @@ pub enum DeprecatedSyscallExecutionError { error: Box, }, #[error("Invalid syscall input: {input:?}; {info}")] - InvalidSyscallInput { input: StarkFelt, info: String }, + InvalidSyscallInput { input: Felt, info: String }, #[error("Invalid syscall selector: {0:?}.")] - InvalidDeprecatedSyscallSelector(StarkFelt), + InvalidDeprecatedSyscallSelector(Felt), #[error(transparent)] MathError(#[from] cairo_vm::types::errors::math_errors::MathError), #[error(transparent)] @@ -153,7 +157,7 @@ pub struct DeprecatedSyscallHintProcessor<'a> { pub syscall_ptr: Relocatable, // Additional information gathered during execution. - pub read_values: Vec, + pub read_values: Vec, pub accessed_keys: HashSet, // Additional fields. @@ -330,8 +334,8 @@ impl<'a> DeprecatedSyscallHintProcessor<'a> { fn read_next_syscall_selector( &mut self, vm: &mut VirtualMachine, - ) -> DeprecatedSyscallResult { - let selector = stark_felt_from_ptr(vm, &mut self.syscall_ptr)?; + ) -> DeprecatedSyscallResult { + let selector = felt_from_ptr(vm, &mut self.syscall_ptr)?; Ok(selector) } @@ -346,8 +350,7 @@ impl<'a> DeprecatedSyscallHintProcessor<'a> { vm: &mut VirtualMachine, ) -> DeprecatedSyscallResult { let signature = &self.context.tx_context.tx_info.signature().0; - let signature = - signature.iter().map(|&x| MaybeRelocatable::from(stark_felt_to_felt(x))).collect(); + let signature = signature.iter().map(|&x| MaybeRelocatable::from(x)).collect(); let signature_segment_start_ptr = self.read_only_segments.allocate(vm, &signature)?; Ok(signature_segment_start_ptr) @@ -361,14 +364,14 @@ impl<'a> DeprecatedSyscallHintProcessor<'a> { let TransactionContext { block_context, tx_info } = self.context.tx_context.as_ref(); let tx_signature_length = tx_info.signature().0.len(); let tx_info: Vec = vec![ - stark_felt_to_felt(tx_info.signed_version().0).into(), - stark_felt_to_felt(*tx_info.sender_address().0.key()).into(), + tx_info.signed_version().0.into(), + (*tx_info.sender_address().0.key()).into(), max_fee_for_execution_info(tx_info).into(), tx_signature_length.into(), tx_signature_start_ptr.into(), - stark_felt_to_felt(tx_info.transaction_hash().0).into(), - Felt252::from_bytes_be(block_context.chain_info.chain_id.0.as_bytes()).into(), - stark_felt_to_felt(tx_info.nonce().0).into(), + tx_info.transaction_hash().0.into(), + Felt::from_hex(block_context.chain_info.chain_id.as_hex().as_str())?.into(), + tx_info.nonce().0.into(), ]; let tx_info_start_ptr = self.read_only_segments.allocate(vm, &tx_info)?; @@ -389,7 +392,7 @@ impl<'a> DeprecatedSyscallHintProcessor<'a> { pub fn set_contract_storage_at( &mut self, key: StorageKey, - value: StarkFelt, + value: Felt, ) -> DeprecatedSyscallResult { self.accessed_keys.insert(key); self.state.set_storage_at(self.storage_address, key, value)?; @@ -426,7 +429,7 @@ impl HintProcessorLogic for DeprecatedSyscallHintProcessor<'_> { vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, hint_data: &Box, - constants: &HashMap, + constants: &HashMap, ) -> HintExecutionResult { let hint = hint_data.downcast_ref::().ok_or(HintError::WrongHintData)?; if hint_code::SYSCALL_HINTS.contains(hint.code.as_str()) { @@ -437,10 +440,10 @@ impl HintProcessorLogic for DeprecatedSyscallHintProcessor<'_> { } } -pub fn felt_to_bool(felt: StarkFelt) -> DeprecatedSyscallResult { - if felt == StarkFelt::from(0_u8) { +pub fn felt_to_bool(felt: Felt) -> DeprecatedSyscallResult { + if felt == Felt::from(0_u8) { Ok(false) - } else if felt == StarkFelt::from(1_u8) { + } else if felt == Felt::from(1_u8) { Ok(true) } else { Err(DeprecatedSyscallExecutionError::InvalidSyscallInput { @@ -463,7 +466,7 @@ pub fn read_call_params( vm: &VirtualMachine, ptr: &mut Relocatable, ) -> DeprecatedSyscallResult<(EntryPointSelector, Calldata)> { - let function_selector = EntryPointSelector(stark_felt_from_ptr(vm, ptr)?); + let function_selector = EntryPointSelector(felt_from_ptr(vm, ptr)?); let calldata = read_calldata(vm, ptr)?; Ok((function_selector, calldata)) @@ -478,7 +481,7 @@ pub fn execute_inner_call( call.execute(syscall_handler.state, syscall_handler.resources, syscall_handler.context)?; let retdata = &call_info.execution.retdata.0; let retdata: Vec = - retdata.iter().map(|&x| MaybeRelocatable::from(stark_felt_to_felt(x))).collect(); + retdata.iter().map(|&x| MaybeRelocatable::from(x)).collect(); let retdata_segment_start_ptr = syscall_handler.read_only_segments.allocate(vm, &retdata)?; syscall_handler.inner_calls.push(call_info); @@ -518,16 +521,17 @@ pub fn execute_library_call( }) } -pub fn read_felt_array( - vm: &VirtualMachine, - ptr: &mut Relocatable, -) -> Result, TErr> +pub fn read_felt_array(vm: &VirtualMachine, ptr: &mut Relocatable) -> Result, TErr> where - TErr: From + From + From + From, + TErr: From + + From + + From + + From + + From>, { - let array_size = stark_felt_from_ptr(vm, ptr)?; + let array_size = felt_from_ptr(vm, ptr)?; let array_data_start_ptr = vm.get_relocatable(*ptr)?; *ptr = (*ptr + 1)?; - Ok(felt_range_from_ptr(vm, array_data_start_ptr, usize::try_from(array_size)?)?) + Ok(felt_range_from_ptr(vm, array_data_start_ptr, usize::try_from(array_size.to_biguint())?)?) } diff --git a/crates/blockifier/src/execution/deprecated_syscalls/mod.rs b/crates/blockifier/src/execution/deprecated_syscalls/mod.rs index 1a3d8eb7a1..1f81cffb80 100644 --- a/crates/blockifier/src/execution/deprecated_syscalls/mod.rs +++ b/crates/blockifier/src/execution/deprecated_syscalls/mod.rs @@ -1,4 +1,3 @@ -use cairo_felt::Felt252; use cairo_vm::types::relocatable::Relocatable; use cairo_vm::vm::vm_core::VirtualMachine; use serde::Deserialize; @@ -7,11 +6,11 @@ use starknet_api::core::{ calculate_contract_address, ClassHash, ContractAddress, EntryPointSelector, EthAddress, }; use starknet_api::deprecated_contract_class::EntryPointType; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; use starknet_api::transaction::{ Calldata, ContractAddressSalt, EventContent, EventData, EventKey, L2ToL1Payload, }; +use starknet_types_core::felt::Felt; use strum_macros::EnumIter; use self::hint_processor::{ @@ -23,8 +22,7 @@ use crate::execution::call_info::{MessageToL1, OrderedEvent, OrderedL2ToL1Messag use crate::execution::common_hints::ExecutionMode; use crate::execution::entry_point::{CallEntryPoint, CallType, ConstructorContext}; use crate::execution::execution_utils::{ - execute_deployment, stark_felt_from_ptr, write_maybe_relocatable, write_stark_felt, - ReadOnlySegment, + execute_deployment, felt_from_ptr, write_felt, write_maybe_relocatable, ReadOnlySegment, }; #[cfg(test)] @@ -71,11 +69,11 @@ pub enum DeprecatedSyscallSelector { StorageWrite, } -impl TryFrom for DeprecatedSyscallSelector { +impl TryFrom for DeprecatedSyscallSelector { type Error = DeprecatedSyscallExecutionError; - fn try_from(raw_selector: StarkFelt) -> Result { + fn try_from(raw_selector: Felt) -> Result { // Remove leading zero bytes from selector. - let selector_bytes = raw_selector.bytes(); + let selector_bytes = raw_selector.to_bytes_be(); let first_non_zero = selector_bytes.iter().position(|&byte| byte != b'\0').unwrap_or(32); match &selector_bytes[first_non_zero..] { @@ -173,7 +171,7 @@ impl SyscallRequest for CallContractRequest { vm: &VirtualMachine, ptr: &mut Relocatable, ) -> DeprecatedSyscallResult { - let contract_address = ContractAddress::try_from(stark_felt_from_ptr(vm, ptr)?)?; + let contract_address = ContractAddress::try_from(felt_from_ptr(vm, ptr)?)?; let (function_selector, calldata) = read_call_params(vm, ptr)?; Ok(CallContractRequest { contract_address, function_selector, calldata }) @@ -277,10 +275,10 @@ pub struct DeployRequest { impl SyscallRequest for DeployRequest { fn read(vm: &VirtualMachine, ptr: &mut Relocatable) -> DeprecatedSyscallResult { - let class_hash = ClassHash(stark_felt_from_ptr(vm, ptr)?); - let contract_address_salt = ContractAddressSalt(stark_felt_from_ptr(vm, ptr)?); + let class_hash = ClassHash(felt_from_ptr(vm, ptr)?); + let contract_address_salt = ContractAddressSalt(felt_from_ptr(vm, ptr)?); let constructor_calldata = read_calldata(vm, ptr)?; - let deploy_from_zero = stark_felt_from_ptr(vm, ptr)?; + let deploy_from_zero = felt_from_ptr(vm, ptr)?; Ok(DeployRequest { class_hash, @@ -301,7 +299,7 @@ impl SyscallResponse for DeployResponse { // `constructor_retdata`. // Nonempty constructor retdata is currently not supported. fn write(self, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { - write_stark_felt(vm, ptr, *self.contract_address.0.key())?; + write_felt(vm, ptr, *self.contract_address.0.key())?; write_maybe_relocatable(vm, ptr, 0)?; write_maybe_relocatable(vm, ptr, 0)?; Ok(()) @@ -399,7 +397,7 @@ pub struct GetBlockNumberResponse { impl SyscallResponse for GetBlockNumberResponse { fn write(self, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { - write_maybe_relocatable(vm, ptr, Felt252::from(self.block_number.0))?; + write_maybe_relocatable(vm, ptr, Felt::from(self.block_number.0))?; Ok(()) } } @@ -435,7 +433,7 @@ pub struct GetBlockTimestampResponse { impl SyscallResponse for GetBlockTimestampResponse { fn write(self, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { - write_maybe_relocatable(vm, ptr, Felt252::from(self.block_timestamp.0))?; + write_maybe_relocatable(vm, ptr, Felt::from(self.block_timestamp.0))?; Ok(()) } } @@ -483,7 +481,7 @@ pub struct GetContractAddressResponse { impl SyscallResponse for GetContractAddressResponse { fn write(self, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { - write_stark_felt(vm, ptr, *self.address.0.key())?; + write_felt(vm, ptr, *self.address.0.key())?; Ok(()) } } @@ -565,7 +563,7 @@ impl SyscallRequest for LibraryCallRequest { vm: &VirtualMachine, ptr: &mut Relocatable, ) -> DeprecatedSyscallResult { - let class_hash = ClassHash(stark_felt_from_ptr(vm, ptr)?); + let class_hash = ClassHash(felt_from_ptr(vm, ptr)?); let (function_selector, calldata) = read_call_params(vm, ptr)?; Ok(LibraryCallRequest { class_hash, function_selector, calldata }) @@ -626,7 +624,7 @@ impl SyscallRequest for ReplaceClassRequest { vm: &VirtualMachine, ptr: &mut Relocatable, ) -> DeprecatedSyscallResult { - let class_hash = ClassHash(stark_felt_from_ptr(vm, ptr)?); + let class_hash = ClassHash(felt_from_ptr(vm, ptr)?); Ok(ReplaceClassRequest { class_hash }) } @@ -659,7 +657,7 @@ impl SyscallRequest for SendMessageToL1Request { vm: &VirtualMachine, ptr: &mut Relocatable, ) -> DeprecatedSyscallResult { - let to_address = EthAddress::try_from(stark_felt_from_ptr(vm, ptr)?)?; + let to_address = EthAddress::try_from(felt_from_ptr(vm, ptr)?)?; let payload = L2ToL1Payload(read_felt_array::(vm, ptr)?); Ok(SendMessageToL1Request { message: MessageToL1 { to_address, payload } }) @@ -696,19 +694,19 @@ impl SyscallRequest for StorageReadRequest { vm: &VirtualMachine, ptr: &mut Relocatable, ) -> DeprecatedSyscallResult { - let address = StorageKey::try_from(stark_felt_from_ptr(vm, ptr)?)?; + let address = StorageKey::try_from(felt_from_ptr(vm, ptr)?)?; Ok(StorageReadRequest { address }) } } #[derive(Debug, Eq, PartialEq)] pub struct StorageReadResponse { - pub value: StarkFelt, + pub value: Felt, } impl SyscallResponse for StorageReadResponse { fn write(self, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { - write_stark_felt(vm, ptr, self.value)?; + write_felt(vm, ptr, self.value)?; Ok(()) } } @@ -726,7 +724,7 @@ pub fn storage_read( #[derive(Debug, Eq, PartialEq)] pub struct StorageWriteRequest { pub address: StorageKey, - pub value: StarkFelt, + pub value: Felt, } impl SyscallRequest for StorageWriteRequest { @@ -734,8 +732,8 @@ impl SyscallRequest for StorageWriteRequest { vm: &VirtualMachine, ptr: &mut Relocatable, ) -> DeprecatedSyscallResult { - let address = StorageKey::try_from(stark_felt_from_ptr(vm, ptr)?)?; - let value = stark_felt_from_ptr(vm, ptr)?; + let address = StorageKey::try_from(felt_from_ptr(vm, ptr)?)?; + let value = felt_from_ptr(vm, ptr)?; Ok(StorageWriteRequest { address, value }) } } diff --git a/crates/blockifier/src/execution/entry_point.rs b/crates/blockifier/src/execution/entry_point.rs index 2e9ec07c1f..cb2c298529 100644 --- a/crates/blockifier/src/execution/entry_point.rs +++ b/crates/blockifier/src/execution/entry_point.rs @@ -7,8 +7,8 @@ use num_traits::{Inv, Zero}; use serde::Serialize; use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector}; use starknet_api::deprecated_contract_class::EntryPointType; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::{Calldata, TransactionVersion}; +use starknet_types_core::felt::Felt; use crate::abi::abi_utils::selector_from_name; use crate::abi::constants; @@ -89,7 +89,7 @@ impl CallEntryPoint { if tx_context.tx_info.version() == TransactionVersion::ZERO && class_hash == ClassHash( - StarkFelt::try_from(FAULTY_CLASS_HASH).expect("A class hash must be a felt."), + Felt::from_hex(FAULTY_CLASS_HASH).expect("A class hash must be a felt."), ) { return Err(PreExecutionError::FraudAttempt.into()); diff --git a/crates/blockifier/src/execution/entry_point_execution.rs b/crates/blockifier/src/execution/entry_point_execution.rs index dcfe16becb..d297c48ac2 100644 --- a/crates/blockifier/src/execution/entry_point_execution.rs +++ b/crates/blockifier/src/execution/entry_point_execution.rs @@ -1,15 +1,13 @@ use std::collections::HashSet; -use cairo_felt::Felt252; -use cairo_vm::serde::deserialize_program::BuiltinName; +use cairo_vm::types::builtin_name::BuiltinName; +use cairo_vm::types::layout_name::LayoutName; use cairo_vm::types::relocatable::{MaybeRelocatable, Relocatable}; use cairo_vm::vm::errors::vm_errors::VirtualMachineError; -use cairo_vm::vm::runners::builtin_runner::SEGMENT_ARENA_BUILTIN_NAME; use cairo_vm::vm::runners::cairo_runner::{CairoArg, CairoRunner, ExecutionResources}; -use cairo_vm::vm::vm_core::VirtualMachine; use num_traits::ToPrimitive; -use starknet_api::hash::StarkFelt; -use starknet_api::stark_felt; +use starknet_api::felt; +use starknet_types_core::felt::Felt; use crate::execution::call_info::{CallExecution, CallInfo, Retdata}; use crate::execution::contract_class::{ContractClassV1, EntryPointV1}; @@ -18,8 +16,7 @@ use crate::execution::entry_point::{ }; use crate::execution::errors::{EntryPointExecutionError, PostExecutionError, PreExecutionError}; use crate::execution::execution_utils::{ - read_execution_retdata, stark_felt_to_felt, write_maybe_relocatable, write_stark_felt, Args, - ReadOnlySegments, + read_execution_retdata, write_felt, write_maybe_relocatable, Args, ReadOnlySegments, }; use crate::execution::syscalls::hint_processor::SyscallHintProcessor; use crate::state::state_api::State; @@ -28,7 +25,6 @@ use crate::state::state_api::State; pub struct VmExecutionContext<'a> { pub runner: CairoRunner, - pub vm: VirtualMachine, pub syscall_handler: SyscallHintProcessor<'a>, pub initial_syscall_ptr: Relocatable, pub entry_point: EntryPointV1, @@ -57,7 +53,6 @@ pub fn execute_entry_point_call( let VmExecutionContext { mut runner, - mut vm, mut syscall_handler, initial_syscall_ptr, entry_point, @@ -66,7 +61,7 @@ pub fn execute_entry_point_call( let args = prepare_call_arguments( &syscall_handler.call, - &mut vm, + &mut runner, initial_syscall_ptr, &mut syscall_handler.read_only_segments, &entry_point, @@ -79,18 +74,11 @@ pub fn execute_entry_point_call( // Execute. let bytecode_length = contract_class.bytecode_length(); let program_segment_size = bytecode_length + program_extra_data_length; - run_entry_point( - &mut vm, - &mut runner, - &mut syscall_handler, - entry_point, - args, - program_segment_size, - )?; + run_entry_point(&mut runner, &mut syscall_handler, entry_point, args, program_segment_size)?; // Collect the set PC values that were visited during the entry point execution. register_visited_pcs( - &mut vm, + &mut runner, syscall_handler.state, class_hash, program_segment_size, @@ -98,7 +86,6 @@ pub fn execute_entry_point_call( )?; let call_info = finalize_execution( - vm, runner, syscall_handler, previous_resources, @@ -116,7 +103,7 @@ pub fn execute_entry_point_call( // Collects the set PC values that were visited during the entry point execution. fn register_visited_pcs( - vm: &mut VirtualMachine, + runner: &mut CairoRunner, state: &mut dyn State, class_hash: starknet_api::core::ClassHash, program_segment_size: usize, @@ -127,8 +114,8 @@ fn register_visited_pcs( // after it. // TODO(lior): Avoid unnecessary relocation once the VM has a non-relocated `get_trace()` // function. - vm.relocate_trace(&[1, 1 + program_segment_size])?; - for trace_entry in vm.get_relocated_trace()? { + runner.relocate_trace(&[1, 1 + program_segment_size].into())?; + for trace_entry in runner.relocated_trace.as_ref().expect("Relocated trace not found") { let pc = trace_entry.pc; if pc < 1 { return Err(EntryPointExecutionError::InternalError(format!( @@ -157,10 +144,13 @@ pub fn initialize_execution_context<'a>( // Instantiate Cairo runner. let proof_mode = false; - let mut runner = CairoRunner::new(&contract_class.0.program, "starknet", proof_mode)?; - let trace_enabled = true; - let mut vm = VirtualMachine::new(trace_enabled); + let mut runner = CairoRunner::new( + &contract_class.0.program, + LayoutName::starknet, + proof_mode, + trace_enabled, + )?; // Initialize program with all builtins. let program_builtins = [ @@ -173,13 +163,13 @@ pub fn initialize_execution_context<'a>( BuiltinName::range_check, BuiltinName::segment_arena, ]; - runner.initialize_function_runner_cairo_1(&mut vm, &program_builtins)?; + runner.initialize_function_runner_cairo_1(&program_builtins)?; let mut read_only_segments = ReadOnlySegments::default(); let program_extra_data_length = - prepare_program_extra_data(&mut vm, contract_class, &mut read_only_segments)?; + prepare_program_extra_data(&mut runner, contract_class, &mut read_only_segments)?; // Instantiate syscall handler. - let initial_syscall_ptr = vm.add_memory_segment(); + let initial_syscall_ptr = runner.vm.add_memory_segment(); let syscall_handler = SyscallHintProcessor::new( state, resources, @@ -192,7 +182,6 @@ pub fn initialize_execution_context<'a>( Ok(VmExecutionContext { runner, - vm, syscall_handler, initial_syscall_ptr, entry_point, @@ -201,7 +190,7 @@ pub fn initialize_execution_context<'a>( } fn prepare_program_extra_data( - vm: &mut VirtualMachine, + runner: &mut CairoRunner, contract_class: &ContractClassV1, read_only_segments: &mut ReadOnlySegments, ) -> Result { @@ -212,15 +201,15 @@ fn prepare_program_extra_data( for _i in 0..20 { data.push(MaybeRelocatable::from(0)); } - let builtin_cost_segment_start = read_only_segments.allocate(vm, &data)?; + let builtin_cost_segment_start = read_only_segments.allocate(&mut runner.vm, &data)?; // Put a pointer to the builtin cost segment at the end of the program (after the // additional `ret` statement). - let mut ptr = (vm.get_pc() + contract_class.bytecode_length())?; + let mut ptr = (runner.vm.get_pc() + contract_class.bytecode_length())?; // Push a `ret` opcode. - write_stark_felt(vm, &mut ptr, stark_felt!("0x208b7fff7fff7ffe"))?; + write_felt(&mut runner.vm, &mut ptr, felt!(0x208b7fff7fff7ffe_u128))?; // Push a pointer to the builtin cost segment. - write_maybe_relocatable(vm, &mut ptr, builtin_cost_segment_start)?; + write_maybe_relocatable(&mut runner.vm, &mut ptr, builtin_cost_segment_start)?; let program_extra_data_length = 2; Ok(program_extra_data_length) @@ -228,7 +217,7 @@ fn prepare_program_extra_data( pub fn prepare_call_arguments( call: &CallEntryPoint, - vm: &mut VirtualMachine, + runner: &mut CairoRunner, initial_syscall_ptr: Relocatable, read_only_segments: &mut ReadOnlySegments, entrypoint: &EntryPointV1, @@ -237,23 +226,26 @@ pub fn prepare_call_arguments( // Push builtins. for builtin_name in &entrypoint.builtins { - if let Some(builtin) = - vm.get_builtin_runners().iter().find(|builtin| builtin.name() == builtin_name) + if let Some(builtin) = runner + .vm + .get_builtin_runners() + .iter() + .find(|builtin| builtin.name().to_str_with_suffix() == builtin_name) { args.extend(builtin.initial_stack().into_iter().map(CairoArg::Single)); continue; } - if builtin_name == SEGMENT_ARENA_BUILTIN_NAME { - let segment_arena = vm.add_memory_segment(); + if builtin_name == BuiltinName::segment_arena.to_str_with_suffix() { + let segment_arena = runner.vm.add_memory_segment(); // Write into segment_arena. let mut ptr = segment_arena; - let info_segment = vm.add_memory_segment(); - let n_constructed = StarkFelt::default(); - let n_destructed = StarkFelt::default(); - write_maybe_relocatable(vm, &mut ptr, info_segment)?; - write_stark_felt(vm, &mut ptr, n_constructed)?; - write_stark_felt(vm, &mut ptr, n_destructed)?; + let info_segment = runner.vm.add_memory_segment(); + let n_constructed = Felt::default(); + let n_destructed = Felt::default(); + write_maybe_relocatable(&mut runner.vm, &mut ptr, info_segment)?; + write_felt(&mut runner.vm, &mut ptr, n_constructed)?; + write_felt(&mut runner.vm, &mut ptr, n_destructed)?; args.push(CairoArg::Single(MaybeRelocatable::from(ptr))); continue; @@ -261,16 +253,16 @@ pub fn prepare_call_arguments( return Err(PreExecutionError::InvalidBuiltin(builtin_name.clone())); } // Push gas counter. - args.push(CairoArg::Single(MaybeRelocatable::from(Felt252::from(call.initial_gas)))); + args.push(CairoArg::Single(MaybeRelocatable::from(Felt::from(call.initial_gas)))); // Push syscall ptr. args.push(CairoArg::Single(MaybeRelocatable::from(initial_syscall_ptr))); // Prepare calldata arguments. let calldata = &call.calldata.0; let calldata: Vec = - calldata.iter().map(|&arg| MaybeRelocatable::from(stark_felt_to_felt(arg))).collect(); + calldata.iter().map(|&arg| MaybeRelocatable::from(arg)).collect(); - let calldata_start_ptr = read_only_segments.allocate(vm, &calldata)?; + let calldata_start_ptr = read_only_segments.allocate(&mut runner.vm, &calldata)?; let calldata_end_ptr = MaybeRelocatable::from((calldata_start_ptr + calldata.len())?); args.push(CairoArg::Single(MaybeRelocatable::from(calldata_start_ptr))); args.push(CairoArg::Single(calldata_end_ptr)); @@ -279,7 +271,6 @@ pub fn prepare_call_arguments( } /// Runs the runner from the given PC. pub fn run_entry_point( - vm: &mut VirtualMachine, runner: &mut CairoRunner, hint_processor: &mut SyscallHintProcessor<'_>, entry_point: EntryPointV1, @@ -293,7 +284,6 @@ pub fn run_entry_point( &args, verify_secure, Some(program_segment_size), - vm, hint_processor, ); @@ -301,8 +291,7 @@ pub fn run_entry_point( } pub fn finalize_execution( - mut vm: VirtualMachine, - runner: CairoRunner, + mut runner: CairoRunner, syscall_handler: SyscallHintProcessor<'_>, previous_resources: ExecutionResources, n_total_args: usize, @@ -313,22 +302,22 @@ pub fn finalize_execution( .program_base .expect("The `program_base` field should be initialized after running the entry point."); let program_end_ptr = (program_start_ptr + runner.get_program().data_len())?; - vm.mark_address_range_as_accessed(program_end_ptr, program_extra_data_length)?; + runner.vm.mark_address_range_as_accessed(program_end_ptr, program_extra_data_length)?; let initial_fp = runner .get_initial_fp() .expect("The `initial_fp` field should be initialized after running the entry point."); // When execution starts the stack holds the EP arguments + [ret_fp, ret_pc]. let args_ptr = (initial_fp - (n_total_args + 2))?; - vm.mark_address_range_as_accessed(args_ptr, n_total_args)?; - syscall_handler.read_only_segments.mark_as_accessed(&mut vm)?; + runner.vm.mark_address_range_as_accessed(args_ptr, n_total_args)?; + syscall_handler.read_only_segments.mark_as_accessed(&mut runner)?; - let call_result = get_call_result(&vm, &syscall_handler)?; + let call_result = get_call_result(&runner, &syscall_handler)?; // Take into account the VM execution resources of the current call, without inner calls. // Has to happen after marking holes in segments as accessed. let vm_resources_without_inner_calls = runner - .get_execution_resources(&vm) + .get_execution_resources() .map_err(VirtualMachineError::RunnerError)? .filter_unused_builtins(); *syscall_handler.resources += &vm_resources_without_inner_calls; @@ -355,10 +344,10 @@ pub fn finalize_execution( } fn get_call_result( - vm: &VirtualMachine, + runner: &CairoRunner, syscall_handler: &SyscallHintProcessor<'_>, ) -> Result { - let return_result = vm.get_return_values(5)?; + let return_result = runner.vm.get_return_values(5)?; // Corresponds to the Cairo 1.0 enum: // enum PanicResult> { Ok: Array::, Err: Array::, }. let [failure_flag, retdata_start, retdata_end]: &[MaybeRelocatable; 3] = @@ -396,7 +385,7 @@ fn get_call_result( let gas_consumed = syscall_handler.call.initial_gas - gas; Ok(CallResult { failed, - retdata: read_execution_retdata(vm, retdata_size, retdata_start)?, + retdata: read_execution_retdata(runner, retdata_size, retdata_start)?, gas_consumed, }) } diff --git a/crates/blockifier/src/execution/entry_point_test.rs b/crates/blockifier/src/execution/entry_point_test.rs index 353e3ff936..55dfe57fe2 100644 --- a/crates/blockifier/src/execution/entry_point_test.rs +++ b/crates/blockifier/src/execution/entry_point_test.rs @@ -1,12 +1,11 @@ use std::collections::HashSet; -use cairo_vm::serde::deserialize_program::BuiltinName; +use cairo_vm::types::builtin_name::BuiltinName; use num_bigint::BigInt; use pretty_assertions::assert_eq; use starknet_api::core::{EntryPointSelector, PatriciaKey}; -use starknet_api::hash::{StarkFelt, StarkHash}; use starknet_api::transaction::Calldata; -use starknet_api::{calldata, stark_felt}; +use starknet_api::{calldata, felt}; use crate::abi::abi_utils::{get_storage_var_address, selector_from_name}; use crate::context::ChainInfo; @@ -30,20 +29,20 @@ fn test_call_info_iteration() { // | // left_leaf (2) let left_leaf = CallInfo { - call: CallEntryPoint { calldata: calldata![stark_felt!(2_u8)], ..Default::default() }, + call: CallEntryPoint { calldata: calldata![felt!(2_u8)], ..Default::default() }, ..Default::default() }; let right_leaf = CallInfo { - call: CallEntryPoint { calldata: calldata![stark_felt!(3_u8)], ..Default::default() }, + call: CallEntryPoint { calldata: calldata![felt!(3_u8)], ..Default::default() }, ..Default::default() }; let inner_node = CallInfo { - call: CallEntryPoint { calldata: calldata![stark_felt!(1_u8)], ..Default::default() }, + call: CallEntryPoint { calldata: calldata![felt!(1_u8)], ..Default::default() }, inner_calls: vec![left_leaf], ..Default::default() }; let root = CallInfo { - call: CallEntryPoint { calldata: calldata![stark_felt!(0_u8)], ..Default::default() }, + call: CallEntryPoint { calldata: calldata![felt!(0_u8)], ..Default::default() }, inner_calls: vec![inner_node, right_leaf], ..Default::default() }; @@ -53,7 +52,7 @@ fn test_call_info_iteration() { // works. assert_eq!( call_info.call.calldata, - calldata![stark_felt!(u64::try_from(i).expect("Failed to convert usize to u64."))] + calldata![felt!(u64::try_from(i).expect("Failed to convert usize to u64."))] ); } } @@ -76,7 +75,7 @@ fn test_entry_point_without_arg() { fn test_entry_point_with_arg() { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let mut state = test_state(&ChainInfo::create_for_testing(), 0, &[(test_contract, 1)]); - let calldata = calldata![stark_felt!(25_u8)]; + let calldata = calldata![felt!(25_u8)]; let entry_point_call = CallEntryPoint { calldata, entry_point_selector: selector_from_name("with_arg"), @@ -101,11 +100,11 @@ fn test_long_retdata() { assert_eq!( entry_point_call.execute_directly(&mut state).unwrap().execution, CallExecution::from_retdata(retdata![ - stark_felt!(0_u8), - stark_felt!(1_u8), - stark_felt!(2_u8), - stark_felt!(3_u8), - stark_felt!(4_u8) + felt!(0_u8), + felt!(1_u8), + felt!(2_u8), + felt!(3_u8), + felt!(4_u8) ]) ); } @@ -114,7 +113,7 @@ fn test_long_retdata() { fn test_entry_point_with_builtin() { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let mut state = test_state(&ChainInfo::create_for_testing(), 0, &[(test_contract, 1)]); - let calldata = calldata![stark_felt!(47_u8), stark_felt!(31_u8)]; + let calldata = calldata![felt!(47_u8), felt!(31_u8)]; let entry_point_call = CallEntryPoint { calldata, entry_point_selector: selector_from_name("bitwise_and"), @@ -130,7 +129,7 @@ fn test_entry_point_with_builtin() { fn test_entry_point_with_hint() { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let mut state = test_state(&ChainInfo::create_for_testing(), 0, &[(test_contract, 1)]); - let calldata = calldata![stark_felt!(81_u8)]; + let calldata = calldata![felt!(81_u8)]; let entry_point_call = CallEntryPoint { calldata, entry_point_selector: selector_from_name("sqrt"), @@ -146,7 +145,7 @@ fn test_entry_point_with_hint() { fn test_entry_point_with_return_value() { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let mut state = test_state(&ChainInfo::create_for_testing(), 0, &[(test_contract, 1)]); - let calldata = calldata![stark_felt!(23_u8)]; + let calldata = calldata![felt!(23_u8)]; let entry_point_call = CallEntryPoint { calldata, entry_point_selector: selector_from_name("return_result"), @@ -154,7 +153,7 @@ fn test_entry_point_with_return_value() { }; assert_eq!( entry_point_call.execute_directly(&mut state).unwrap().execution, - CallExecution::from_retdata(retdata![stark_felt!(23_u8)]) + CallExecution::from_retdata(retdata![felt!(23_u8)]) ); } @@ -162,7 +161,7 @@ fn test_entry_point_with_return_value() { fn test_entry_point_not_found_in_contract() { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let mut state = test_state(&ChainInfo::create_for_testing(), 0, &[(test_contract, 1)]); - let entry_point_selector = EntryPointSelector(stark_felt!(2_u8)); + let entry_point_selector = EntryPointSelector(felt!(2_u8)); let entry_point_call = CallEntryPoint { entry_point_selector, ..trivial_external_entry_point_new(test_contract) }; let error = entry_point_call.execute_directly(&mut state).unwrap_err(); @@ -307,7 +306,7 @@ fn test_builtin_execution_security_failures() { run_security_test( state, security_contract, - "Inconsistent auto-deduction for builtin pedersen", + "Inconsistent auto-deduction for pedersen_builtin", "test_bad_pedersen_values", calldata![], ); @@ -362,7 +361,7 @@ fn test_syscall_execution_security_failures() { for perform_inner_call_to_foo in 0..2 { // TODO(Ori, 1/2/2024): Write an indicative expect message explaining why the conversion // works. - let calldata = calldata![stark_felt!( + let calldata = calldata![felt!( u8::try_from(perform_inner_call_to_foo).expect("Failed to convert i32 to u8.") )]; run_security_test( @@ -386,8 +385,7 @@ fn test_syscall_execution_security_failures() { state, security_contract, "Requested contract address \ - ContractAddress(PatriciaKey(StarkFelt(\"\ - 0x0000000000000000000000000000000000000000000000000000000000000017\"))) is not deployed", + 0x0000000000000000000000000000000000000000000000000000000000000017 is not deployed", "test_bad_call_address", calldata![], ); @@ -401,10 +399,7 @@ fn test_syscall_execution_security_failures() { run_security_test( state, security_contract, - "Entry point \ - EntryPointSelector(StarkFelt(\"\ - 0x0000000000000000000000000000000000000000000000000000000000000019\")) not found in \ - contract", + "Entry point EntryPointSelector(0x19) not found in contract", "test_bad_call_selector", calldata![], ); @@ -426,14 +421,14 @@ fn test_post_run_validation_security_failure() { run_security_test( state, security_contract, - "Missing memory cells for builtin range_check", + "Missing memory cells for range_check_builtin", "test_builtin_hole", calldata![], ); run_security_test( state, security_contract, - "Missing memory cells for builtin pedersen", + "Missing memory cells for pedersen_builtin", "test_missing_pedersen_values", calldata![], ); @@ -479,7 +474,7 @@ fn test_post_run_validation_security_failure() { "test_write_to_call_contract_return_value", calldata![], ); - let calldata = calldata![stark_felt!(1_u8), stark_felt!(1_u8)]; + let calldata = calldata![felt!(1_u8), felt!(1_u8)]; run_security_test( state, security_contract, @@ -501,15 +496,16 @@ fn test_storage_related_members() { ..trivial_external_entry_point_new(test_contract) }; let actual_call_info = entry_point_call.execute_directly(&mut state).unwrap(); - assert_eq!(actual_call_info.storage_read_values, vec![stark_felt!(39_u8)]); + assert_eq!(actual_call_info.storage_read_values, vec![felt!(39_u8)]); assert_eq!( actual_call_info.accessed_storage_keys, - HashSet::from([get_storage_var_address("number_map", &[stark_felt!(1_u8)])]) + HashSet::from([get_storage_var_address("number_map", &[felt!(1_u8)])]) ); // Test raw storage read and write. - let key = stark_felt!(1234_u16); - let value = stark_felt!(18_u8); + let key_int = 1234_u16; + let key = felt!(key_int); + let value = felt!(18_u8); let calldata = calldata![key, value]; let entry_point_call = CallEntryPoint { calldata, @@ -518,7 +514,7 @@ fn test_storage_related_members() { }; let actual_call_info = entry_point_call.execute_directly(&mut state).unwrap(); assert_eq!(actual_call_info.storage_read_values, vec![value]); - assert_eq!(actual_call_info.accessed_storage_keys, HashSet::from([storage_key!(key)])); + assert_eq!(actual_call_info.accessed_storage_keys, HashSet::from([storage_key!(key_int)])); } #[test] @@ -539,6 +535,6 @@ fn test_cairo1_entry_point_segment_arena() { .unwrap() .resources .builtin_instance_counter - .contains_key(BuiltinName::segment_arena.name()) + .contains_key(&BuiltinName::segment_arena) ); } diff --git a/crates/blockifier/src/execution/errors.rs b/crates/blockifier/src/execution/errors.rs index b2cec45d2c..1fa6a1d5b2 100644 --- a/crates/blockifier/src/execution/errors.rs +++ b/crates/blockifier/src/execution/errors.rs @@ -7,7 +7,7 @@ use cairo_vm::vm::errors::vm_errors::VirtualMachineError; use num_bigint::{BigInt, TryFromBigIntError}; use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector}; use starknet_api::deprecated_contract_class::EntryPointType; -use starknet_api::hash::StarkFelt; +use starknet_types_core::felt::Felt; use thiserror::Error; use crate::execution::entry_point::ConstructorContext; @@ -18,7 +18,7 @@ use crate::state::errors::StateError; #[derive(Debug, Error)] pub enum PreExecutionError { - #[error("Entry point {selector:?} of type {typ:?} is not unique.")] + #[error("Entry point {:#064x} of type {typ:?} is not unique.", .selector.0)] DuplicatedEntryPointSelector { selector: EntryPointSelector, typ: EntryPointType }, #[error("Entry point {0:?} not found in contract.")] EntryPointNotFound(EntryPointSelector), @@ -40,7 +40,7 @@ pub enum PreExecutionError { RunnerError(Box), #[error(transparent)] StateError(#[from] StateError), - #[error("Requested contract address {0:?} is not deployed.")] + #[error("Requested contract address {:#064x} is not deployed.", .0.key())] UninitializedStorageAddress(ContractAddress), } @@ -77,7 +77,7 @@ pub enum EntryPointExecutionError { #[error(transparent)] CairoRunError(#[from] CairoRunError), #[error("Execution failed. Failure reason: {}.", format_panic_data(.error_data))] - ExecutionFailed { error_data: Vec }, + ExecutionFailed { error_data: Vec }, #[error("Internal error: {0}")] InternalError(String), #[error("Invalid input: {input_descriptor}; {info}")] diff --git a/crates/blockifier/src/execution/execution_utils.rs b/crates/blockifier/src/execution/execution_utils.rs index 3667b8ccd2..326e1a6337 100644 --- a/crates/blockifier/src/execution/execution_utils.rs +++ b/crates/blockifier/src/execution/execution_utils.rs @@ -1,23 +1,22 @@ use std::collections::HashMap; -use cairo_felt::Felt252; use cairo_lang_runner::casm_run::format_next_item; use cairo_vm::serde::deserialize_program::{ deserialize_array_of_bigint_hex, Attribute, HintParams, Identifier, ReferenceManager, }; +use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::types::errors::program_errors::ProgramError; use cairo_vm::types::program::Program; use cairo_vm::types::relocatable::{MaybeRelocatable, Relocatable}; use cairo_vm::vm::errors::memory_errors::MemoryError; use cairo_vm::vm::errors::vm_errors::VirtualMachineError; -use cairo_vm::vm::runners::builtin_runner::POSEIDON_BUILTIN_NAME; -use cairo_vm::vm::runners::cairo_runner::{CairoArg, ExecutionResources}; +use cairo_vm::vm::runners::cairo_runner::{CairoArg, CairoRunner, ExecutionResources}; use cairo_vm::vm::vm_core::VirtualMachine; use num_bigint::BigUint; use starknet_api::core::ClassHash; use starknet_api::deprecated_contract_class::Program as DeprecatedProgram; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::Calldata; +use starknet_types_core::felt::Felt; use super::entry_point::ConstructorEntryPointExecutionResult; use super::errors::ConstructorEntryPointExecutionError; @@ -35,19 +34,6 @@ use crate::transaction::objects::TransactionInfo; pub type Args = Vec; -#[cfg(test)] -#[path = "execution_utils_test.rs"] -pub mod test; - -pub fn stark_felt_to_felt(stark_felt: StarkFelt) -> Felt252 { - Felt252::from_bytes_be(stark_felt.bytes()) -} - -pub fn felt_to_stark_felt(felt: &Felt252) -> StarkFelt { - let biguint = format!("{:#x}", felt.to_biguint()); - StarkFelt::try_from(biguint.as_str()).expect("Felt252 must be in StarkFelt's range.") -} - /// Executes a specific call to a contract entry point and returns its output. pub fn execute_entry_point_call( call: CallEntryPoint, @@ -77,7 +63,7 @@ pub fn execute_entry_point_call( } pub fn read_execution_retdata( - vm: &VirtualMachine, + runner: &CairoRunner, retdata_size: MaybeRelocatable, retdata_ptr: &MaybeRelocatable, ) -> Result { @@ -89,20 +75,13 @@ pub fn read_execution_retdata( } }; - Ok(Retdata(felt_range_from_ptr(vm, Relocatable::try_from(retdata_ptr)?, retdata_size)?)) -} - -pub fn stark_felt_from_ptr( - vm: &VirtualMachine, - ptr: &mut Relocatable, -) -> Result { - Ok(felt_to_stark_felt(&felt_from_ptr(vm, ptr)?)) + Ok(Retdata(felt_range_from_ptr(&runner.vm, Relocatable::try_from(retdata_ptr)?, retdata_size)?)) } pub fn felt_from_ptr( vm: &VirtualMachine, ptr: &mut Relocatable, -) -> Result { +) -> Result { let felt = vm.get_integer(*ptr)?.into_owned(); *ptr = (*ptr + 1)?; Ok(felt) @@ -113,18 +92,18 @@ pub fn write_u256( ptr: &mut Relocatable, value: BigUint, ) -> Result<(), MemoryError> { - write_felt(vm, ptr, Felt252::from(&value & BigUint::from(u128::MAX)))?; - write_felt(vm, ptr, Felt252::from(value >> 128)) + write_felt(vm, ptr, Felt::from(&value & BigUint::from(u128::MAX)))?; + write_felt(vm, ptr, Felt::from(value >> 128)) } pub fn felt_range_from_ptr( vm: &VirtualMachine, ptr: Relocatable, size: usize, -) -> Result, VirtualMachineError> { +) -> Result, VirtualMachineError> { let values = vm.get_integer_range(ptr, size)?; - // Extract values as `StarkFelt`. - let values = values.into_iter().map(|felt| felt_to_stark_felt(felt.as_ref())).collect(); + // Extract values as `Felt`. + let values = values.into_iter().map(|felt| *felt).collect(); Ok(values) } @@ -205,9 +184,9 @@ impl ReadOnlySegments { Ok(()) } - pub fn mark_as_accessed(&self, vm: &mut VirtualMachine) -> Result<(), PostExecutionError> { + pub fn mark_as_accessed(&self, runner: &mut CairoRunner) -> Result<(), PostExecutionError> { for segment in &self.0 { - vm.mark_address_range_as_accessed(segment.start_ptr, segment.length)?; + runner.vm.mark_address_range_as_accessed(segment.start_ptr, segment.length)?; } Ok(()) @@ -253,18 +232,10 @@ pub fn execute_deployment( ) } -pub fn write_stark_felt( - vm: &mut VirtualMachine, - ptr: &mut Relocatable, - felt: StarkFelt, -) -> Result<(), MemoryError> { - write_felt(vm, ptr, stark_felt_to_felt(felt)) -} - pub fn write_felt( vm: &mut VirtualMachine, ptr: &mut Relocatable, - felt: Felt252, + felt: Felt, ) -> Result<(), MemoryError> { write_maybe_relocatable(vm, ptr, felt) } @@ -279,7 +250,7 @@ pub fn write_maybe_relocatable>( Ok(()) } -pub fn max_fee_for_execution_info(tx_info: &TransactionInfo) -> Felt252 { +pub fn max_fee_for_execution_info(tx_info: &TransactionInfo) -> Felt { match tx_info { TransactionInfo::Current(_) => 0, TransactionInfo::Deprecated(tx_info) => tx_info.max_fee.0, @@ -287,8 +258,8 @@ pub fn max_fee_for_execution_info(tx_info: &TransactionInfo) -> Felt252 { .into() } -pub fn format_panic_data(felts: &[StarkFelt]) -> String { - let mut felts = felts.iter().map(|felt| stark_felt_to_felt(*felt)); +pub fn format_panic_data(felts: &[Felt]) -> String { + let mut felts = felts.iter().copied(); let mut items = Vec::new(); while let Some(item) = format_next_item(&mut felts) { items.push(item.quote_if_string()); @@ -304,9 +275,6 @@ pub fn poseidon_hash_many_cost(data_length: usize) -> ExecutionResources { + (data_length % 2) * 3 + 21, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([( - POSEIDON_BUILTIN_NAME.to_string(), - data_length / 2 + 1, - )]), + builtin_instance_counter: HashMap::from([(BuiltinName::poseidon, data_length / 2 + 1)]), } } diff --git a/crates/blockifier/src/execution/execution_utils_test.rs b/crates/blockifier/src/execution/execution_utils_test.rs deleted file mode 100644 index 546f377672..0000000000 --- a/crates/blockifier/src/execution/execution_utils_test.rs +++ /dev/null @@ -1,47 +0,0 @@ -use std::iter::zip; - -use cairo_felt::Felt252; -use num_bigint::BigUint; -use num_traits::{One, Zero}; -use pretty_assertions::assert_eq; -use starknet_api::hash::StarkFelt; - -use crate::execution::execution_utils::{felt_to_stark_felt, stark_felt_to_felt}; - -fn starkfelt_to_felt_pairs() -> Vec<(StarkFelt, Felt252)> { - // The STARK prime is 2 ^ 251 + 17 * 2 ^ 192 + 1. - const STARK_PRIME_MINUS_ONE: &str = - "0x800000000000011000000000000000000000000000000000000000000000000"; - - let starkfelt_from_hex_error_message = "`StarkFelt` construction from hex has failed."; - let starkfelts = vec![ - StarkFelt::from(0_u8), - StarkFelt::from(1_u8), - StarkFelt::from(1234_u16), - StarkFelt::try_from(STARK_PRIME_MINUS_ONE).expect(starkfelt_from_hex_error_message), - ]; - let felts = vec![ - Felt252::zero(), - Felt252::one(), - Felt252::from(1234), - // Note: the BigUint digits are ordered least significant digit first. - // Prime - 1. - Felt252::from(BigUint::new(vec![0, 0, 0, 0, 0, 0, 17, 134217728])), - ]; - - zip(starkfelts, felts).collect() -} - -#[test] -fn test_stark_felt_to_felt() { - for (stark_felt, equivalent_felt) in starkfelt_to_felt_pairs() { - assert_eq!(stark_felt_to_felt(stark_felt), equivalent_felt); - } -} - -#[test] -fn test_felt_to_stark_felt() { - for (equivalent_stark_felt, felt) in starkfelt_to_felt_pairs() { - assert_eq!(felt_to_stark_felt(&felt), equivalent_stark_felt); - } -} diff --git a/crates/blockifier/src/execution/stack_trace.rs b/crates/blockifier/src/execution/stack_trace.rs index 709758131f..c6a15e6a68 100644 --- a/crates/blockifier/src/execution/stack_trace.rs +++ b/crates/blockifier/src/execution/stack_trace.rs @@ -1,3 +1,4 @@ +use cairo_vm::types::relocatable::Relocatable; use cairo_vm::vm::errors::cairo_run_errors::CairoRunError; use cairo_vm::vm::errors::hint_errors::HintError; use cairo_vm::vm::errors::vm_errors::VirtualMachineError; @@ -43,13 +44,13 @@ pub struct EntryPointErrorFrame { impl EntryPointErrorFrame { fn preamble_text(&self) -> String { format!( - "{}: {} (contract address: {}, class hash: {}, selector: {}):", + "{}: {} (contract address: {:#064x}, class hash: {:#064x}, selector: {}):", self.depth, self.preamble_type.text(), self.storage_address.0.key(), - self.class_hash, + self.class_hash.0, if let Some(selector) = self.selector { - format!("{}", selector.0) + format!("{:#064x}", selector.0) } else { "UNKNOWN".to_string() } @@ -64,13 +65,13 @@ impl From<&EntryPointErrorFrame> for String { } pub struct VmExceptionFrame { - pc: usize, + pc: Relocatable, traceback: Option, } impl From<&VmExceptionFrame> for String { fn from(value: &VmExceptionFrame) -> Self { - let vm_exception_preamble = format!("Error at pc=0:{}:", value.pc); + let vm_exception_preamble = format!("Error at pc={}:", value.pc); let vm_exception_traceback = if let Some(traceback) = &value.traceback { format!("\n{}", traceback) } else { diff --git a/crates/blockifier/src/execution/stack_trace_test.rs b/crates/blockifier/src/execution/stack_trace_test.rs index bbfc149c76..6243ec0b25 100644 --- a/crates/blockifier/src/execution/stack_trace_test.rs +++ b/crates/blockifier/src/execution/stack_trace_test.rs @@ -2,12 +2,11 @@ use pretty_assertions::assert_eq; use regex::Regex; use rstest::rstest; use starknet_api::core::{calculate_contract_address, Nonce}; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::{ Calldata, ContractAddressSalt, Fee, ResourceBoundsMapping, TransactionSignature, TransactionVersion, }; -use starknet_api::{calldata, stark_felt}; +use starknet_api::{calldata, felt}; use crate::abi::abi_utils::selector_from_name; use crate::abi::constants::CONSTRUCTOR_ENTRY_POINT_NAME; @@ -57,7 +56,7 @@ fn test_stack_trace( &[ test_contract_address_2_felt, // Contract address. inner_entry_point_selector_felt, // Function selector. - stark_felt!(0_u8), // Innermost calldata length. + felt!(0_u8), // Innermost calldata length. ], ); @@ -90,22 +89,22 @@ fn test_stack_trace( let expected_trace_cairo0 = format!( "Transaction execution has failed: -0: Error in the called contract (contract address: {account_address_felt}, class hash: \ - {account_contract_hash}, selector: {execute_selector_felt}): +0: Error in the called contract (contract address: {account_address_felt:#064x}, class hash: \ + {account_contract_hash:#064x}, selector: {execute_selector_felt:#064x}): Error at pc=0:7: Cairo traceback (most recent call last): Unknown location (pc=0:{account_call_location}) Unknown location (pc=0:{account_entry_point_location}) -1: Error in the called contract (contract address: {test_contract_address_felt}, class hash: \ - {test_contract_hash}, selector: {external_entry_point_selector_felt}): +1: Error in the called contract (contract address: {test_contract_address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {external_entry_point_selector_felt:#064x}): Error at pc=0:37: Cairo traceback (most recent call last): Unknown location (pc=0:{call_location}) Unknown location (pc=0:{entry_point_location}) -2: Error in the called contract (contract address: {test_contract_address_2_felt}, class hash: \ - {test_contract_hash}, selector: {inner_entry_point_selector_felt}): +2: Error in the called contract (contract address: {test_contract_address_2_felt:#064x}, class \ + hash: {test_contract_hash:#064x}, selector: {inner_entry_point_selector_felt:#064x}): Error at pc=0:1184: Cairo traceback (most recent call last): Unknown location (pc=0:1188) @@ -116,14 +115,14 @@ An ASSERT_EQ instruction failed: 1 != 0. let expected_trace_cairo1 = format!( "Transaction execution has failed: -0: Error in the called contract (contract address: {account_address_felt}, class hash: \ - {account_contract_hash}, selector: {execute_selector_felt}): +0: Error in the called contract (contract address: {account_address_felt:#064x}, class hash: \ + {account_contract_hash:#064x}, selector: {execute_selector_felt:#064x}): Error at pc=0:767: -1: Error in the called contract (contract address: {test_contract_address_felt}, class hash: \ - {test_contract_hash}, selector: {external_entry_point_selector_felt}): +1: Error in the called contract (contract address: {test_contract_address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {external_entry_point_selector_felt:#064x}): Error at pc=0:612: -2: Error in the called contract (contract address: {test_contract_address_2_felt}, class hash: \ - {test_contract_hash}, selector: {inner_entry_point_selector_felt}): +2: Error in the called contract (contract address: {test_contract_address_2_felt:#064x}, class \ + hash: {test_contract_hash:#064x}, selector: {inner_entry_point_selector_felt:#064x}): Execution failed. Failure reason: 0x6661696c ('fail'). " ); @@ -168,14 +167,14 @@ fn test_trace_callchain_ends_with_regular_call( test_contract_address, // contract_address "invoke_call_chain", &[ - stark_felt!(7_u8), // Calldata length + felt!(7_u8), // Calldata length contract_address_felt, // Contract address. invoke_call_chain_selector_felt, // Function selector. - stark_felt!(0_u8), // Call type: call_contract_syscall. - stark_felt!(3_u8), // Calldata length + felt!(0_u8), // Call type: call_contract_syscall. + felt!(3_u8), // Calldata length contract_address_felt, // Contract address. selector_from_name(last_func_name).0, // Function selector. - stark_felt!(2_u8), // Call type: regular call. + felt!(2_u8), // Call type: regular call. ], ); @@ -206,22 +205,22 @@ fn test_trace_callchain_ends_with_regular_call( let (expected_pc0, expected_pc1) = expected_pc_locations; format!( "Transaction execution has failed: -0: Error in the called contract (contract address: {account_address_felt}, class hash: \ - {account_contract_hash}, selector: {execute_selector_felt}): +0: Error in the called contract (contract address: {account_address_felt:#064x}, class hash: \ + {account_contract_hash:#064x}, selector: {execute_selector_felt:#064x}): Error at pc=0:7: Cairo traceback (most recent call last): Unknown location (pc=0:{account_call_location}) Unknown location (pc=0:{account_entry_point_location}) -1: Error in the called contract (contract address: {contract_address_felt}, class hash: \ - {test_contract_hash}, selector: {invoke_call_chain_selector_felt}): +1: Error in the called contract (contract address: {contract_address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {invoke_call_chain_selector_felt:#064x}): Error at pc=0:37: Cairo traceback (most recent call last): Unknown location (pc=0:{call_location}) Unknown location (pc=0:{entry_point_location}) -2: Error in the called contract (contract address: {contract_address_felt}, class hash: \ - {test_contract_hash}, selector: {invoke_call_chain_selector_felt}): +2: Error in the called contract (contract address: {contract_address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {invoke_call_chain_selector_felt:#064x}): Error at pc=0:{expected_pc0}: Cairo traceback (most recent call last): Unknown location (pc=0:{call_location}) @@ -235,17 +234,17 @@ Unknown location (pc=0:{expected_pc1}) let pc_location = entry_point_offset.0 + INNER_CALL_CONTRACT_IN_CALL_CHAIN_OFFSET; format!( "Transaction execution has failed: -0: Error in the called contract (contract address: {account_address_felt}, class hash: \ - {account_contract_hash}, selector: {execute_selector_felt}): +0: Error in the called contract (contract address: {account_address_felt:#064x}, class hash: \ + {account_contract_hash:#064x}, selector: {execute_selector_felt:#064x}): Error at pc=0:767: -1: Error in the called contract (contract address: {contract_address_felt}, class hash: \ - {test_contract_hash}, selector: {invoke_call_chain_selector_felt}): +1: Error in the called contract (contract address: {contract_address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {invoke_call_chain_selector_felt:#064x}): Error at pc=0:9381: Cairo traceback (most recent call last): Unknown location (pc=0:{pc_location}) -2: Error in the called contract (contract address: {contract_address_felt}, class hash: \ - {test_contract_hash}, selector: {invoke_call_chain_selector_felt}): +2: Error in the called contract (contract address: {contract_address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {invoke_call_chain_selector_felt:#064x}): Execution failed. Failure reason: {expected_error}. " ) @@ -294,19 +293,19 @@ fn test_trace_call_chain_with_syscalls( let last_func_selector_felt = selector_from_name(last_func_name).0; let mut raw_calldata = vec![ - stark_felt!(7_u8 + calldata_extra_length), // Calldata length - address_felt, // Contract address. - invoke_call_chain_selector_felt, // Function selector. - stark_felt!(0_u8), // Call type: call_contract_syscall. - stark_felt!(3_u8 + calldata_extra_length), // Calldata length - contract_id, // Contract address / class hash. - last_func_selector_felt, // Function selector. - stark_felt!(call_type), // Syscall type: library_call or call_contract. + felt!(7_u8 + calldata_extra_length), // Calldata length + address_felt, // Contract address. + invoke_call_chain_selector_felt, // Function selector. + felt!(0_u8), // Call type: call_contract_syscall. + felt!(3_u8 + calldata_extra_length), // Calldata length + contract_id, // Contract address / class hash. + last_func_selector_felt, // Function selector. + felt!(call_type), // Syscall type: library_call or call_contract. ]; // Need to send an empty array for the last call in `invoke_call_chain` variant. if last_func_name == "invoke_call_chain" { - raw_calldata.push(stark_felt!(0_u8)); + raw_calldata.push(felt!(0_u8)); } let calldata = create_calldata( @@ -333,13 +332,13 @@ fn test_trace_call_chain_with_syscalls( let last_call_preamble = if call_type == 0 { format!( - "Error in the called contract (contract address: {address_felt}, class hash: \ - {test_contract_hash}, selector: {last_func_selector_felt})" + "Error in the called contract (contract address: {address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {last_func_selector_felt:#064x})" ) } else { format!( - "Error in a library call (contract address: {address_felt}, class hash: \ - {test_contract_hash}, selector: {last_func_selector_felt})" + "Error in a library call (contract address: {address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {last_func_selector_felt:#064x})" ) }; @@ -353,22 +352,22 @@ fn test_trace_call_chain_with_syscalls( let (expected_pc0, expected_pc1, expected_pc2, expected_pc3) = expected_pcs; format!( "Transaction execution has failed: -0: Error in the called contract (contract address: {account_address_felt}, class hash: \ - {account_contract_hash}, selector: {execute_selector_felt}): +0: Error in the called contract (contract address: {account_address_felt:#064x}, class hash: \ + {account_contract_hash:#064x}, selector: {execute_selector_felt:#064x}): Error at pc=0:7: Cairo traceback (most recent call last): Unknown location (pc=0:{account_call_location}) Unknown location (pc=0:{account_entry_point_location}) -1: Error in the called contract (contract address: {address_felt}, class hash: \ - {test_contract_hash}, selector: {invoke_call_chain_selector_felt}): +1: Error in the called contract (contract address: {address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {invoke_call_chain_selector_felt:#064x}): Error at pc=0:37: Cairo traceback (most recent call last): Unknown location (pc=0:{call_location}) Unknown location (pc=0:{entry_point_location}) -2: Error in the called contract (contract address: {address_felt}, class hash: \ - {test_contract_hash}, selector: {invoke_call_chain_selector_felt}): +2: Error in the called contract (contract address: {address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {invoke_call_chain_selector_felt:#064x}): Error at pc=0:{expected_pc0}: Cairo traceback (most recent call last): Unknown location (pc=0:{call_location}) @@ -388,17 +387,17 @@ Unknown location (pc=0:{expected_pc3}) let (expected_pc0, expected_pc1, _, _) = expected_pcs; format!( "Transaction execution has failed: -0: Error in the called contract (contract address: {account_address_felt}, class hash: \ - {account_contract_hash}, selector: {execute_selector_felt}): +0: Error in the called contract (contract address: {account_address_felt:#064x}, class hash: \ + {account_contract_hash:#064x}, selector: {execute_selector_felt:#064x}): Error at pc=0:767: -1: Error in the called contract (contract address: {address_felt}, class hash: \ - {test_contract_hash}, selector: {invoke_call_chain_selector_felt}): +1: Error in the called contract (contract address: {address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {invoke_call_chain_selector_felt:#064x}): Error at pc=0:{expected_pc0}: Cairo traceback (most recent call last): Unknown location (pc=0:{pc_location}) -2: Error in the called contract (contract address: {address_felt}, class hash: \ - {test_contract_hash}, selector: {invoke_call_chain_selector_felt}): +2: Error in the called contract (contract address: {address_felt:#064x}, class hash: \ + {test_contract_hash:#064x}, selector: {invoke_call_chain_selector_felt:#064x}): Error at pc=0:{expected_pc1}: Cairo traceback (most recent call last): Unknown location (pc=0:{pc_location}) @@ -490,22 +489,24 @@ fn test_validate_trace( let expected_error = match cairo_version { CairoVersion::Cairo0 => format!( "Transaction validation has failed: -0: Error in the called contract (contract address: {contract_address}, class hash: {class_hash}, \ - selector: {selector}): +0: Error in the called contract (contract address: {contract_address:#064x}, class hash: {:#064x}, \ + selector: {selector:#064x}): Error at pc=0:0: Cairo traceback (most recent call last): Unknown location (pc=0:0) Unknown location (pc=0:0) An ASSERT_EQ instruction failed: 1 != 0. -" +", + class_hash.0 ), CairoVersion::Cairo1 => format!( "Transaction validation has failed: -0: Error in the called contract (contract address: {contract_address}, class hash: {class_hash}, \ - selector: {selector}): +0: Error in the called contract (contract address: {contract_address:#064x}, class hash: {:#064x}, \ + selector: {selector:#064x}): Execution failed. Failure reason: 0x496e76616c6964207363656e6172696f ('Invalid scenario'). -" +", + class_hash.0 ), }; @@ -553,9 +554,10 @@ fn test_account_ctor_frame_stack_trace( let expected_address = deploy_address.0.key(); let expected_error = format!( "Contract constructor execution has failed: -0: Error in the contract class constructor (contract address: {expected_address}, class hash: \ - {class_hash}, selector: {expected_selector}): -" +0: Error in the contract class constructor (contract address: {expected_address:#064x}, class \ + hash: {:#064x}, selector: {expected_selector:#064x}): +", + class_hash.0 ) + match cairo_version { CairoVersion::Cairo0 => { "Error at pc=0:223: @@ -596,10 +598,10 @@ fn test_contract_ctor_frame_stack_trace( let account_class_hash = account.get_class_hash(); let faulty_class_hash = faulty_ctor.get_class_hash(); - let salt = stark_felt!(7_u8); + let salt = felt!(7_u8); // Constructor arg: set to true to fail deployment. - let validate_constructor = stark_felt!(FELT_TRUE); - let signature = TransactionSignature(vec![stark_felt!(INVALID)]); + let validate_constructor = felt!(FELT_TRUE); + let signature = TransactionSignature(vec![felt!(INVALID)]); let expected_deployed_address = calculate_contract_address( ContractAddressSalt(salt), faulty_class_hash, @@ -617,12 +619,12 @@ fn test_contract_ctor_frame_stack_trace( &[ faulty_class_hash.0, salt, - stark_felt!(1_u8), // Calldata: ctor args length. + felt!(1_u8), // Calldata: ctor args length. validate_constructor, ] ), resource_bounds: max_resource_bounds, - nonce: Nonce(stark_felt!(0_u8)), + nonce: Nonce(felt!(0_u8)), }); // Construct expected output. @@ -636,19 +638,19 @@ fn test_contract_ctor_frame_stack_trace( let (frame_0, frame_1, frame_2) = ( format!( "Transaction execution has failed: -0: Error in the called contract (contract address: {account_address_felt}, class hash: \ - {account_class_hash}, selector: {}):", - execute_selector.0 +0: Error in the called contract (contract address: {account_address_felt:#064x}, class hash: \ + {:#064x}, selector: {:#064x}):", + account_class_hash.0, execute_selector.0 ), format!( - "1: Error in the called contract (contract address: {account_address_felt}, class \ - hash: {account_class_hash}, selector: {}):", - deploy_contract_selector.0 + "1: Error in the called contract (contract address: {account_address_felt:#064x}, \ + class hash: {:#064x}, selector: {:#064x}):", + account_class_hash.0, deploy_contract_selector.0 ), format!( - "2: Error in the contract class constructor (contract address: {expected_address}, \ - class hash: {faulty_class_hash}, selector: {}):", - ctor_selector.0 + "2: Error in the contract class constructor (contract address: \ + {expected_address:#064x}, class hash: {:#064x}, selector: {:#064x}):", + faulty_class_hash.0, ctor_selector.0 ), ); let (execute_offset, deploy_offset, ctor_offset) = ( diff --git a/crates/blockifier/src/execution/syscalls/hint_processor.rs b/crates/blockifier/src/execution/syscalls/hint_processor.rs index 34c9c5dca1..449cf3705c 100644 --- a/crates/blockifier/src/execution/syscalls/hint_processor.rs +++ b/crates/blockifier/src/execution/syscalls/hint_processor.rs @@ -1,7 +1,6 @@ use std::any::Any; use std::collections::{HashMap, HashSet}; -use cairo_felt::Felt252; use cairo_lang_casm::hints::{Hint, StarknetHint}; use cairo_lang_casm::operand::{BinOpOperand, DerefOrImmediate, Operation, Register, ResOperand}; use cairo_lang_runner::casm_run::execute_core_hint_base; @@ -15,13 +14,12 @@ use cairo_vm::vm::errors::memory_errors::MemoryError; use cairo_vm::vm::errors::vm_errors::VirtualMachineError; use cairo_vm::vm::runners::cairo_runner::{ExecutionResources, ResourceTracker, RunResources}; use cairo_vm::vm::vm_core::VirtualMachine; -use num_traits::Zero; use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector}; use starknet_api::deprecated_contract_class::EntryPointType; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; use starknet_api::transaction::{Calldata, Resource}; use starknet_api::StarknetApiError; +use starknet_types_core::felt::{Felt, FromStrError}; use thiserror::Error; use crate::abi::sierra_types::SierraTypeError; @@ -30,8 +28,8 @@ use crate::execution::common_hints::{ExecutionMode, HintExecutionResult}; use crate::execution::entry_point::{CallEntryPoint, CallType, EntryPointExecutionContext}; use crate::execution::errors::{ConstructorEntryPointExecutionError, EntryPointExecutionError}; use crate::execution::execution_utils::{ - felt_range_from_ptr, max_fee_for_execution_info, stark_felt_from_ptr, stark_felt_to_felt, - write_maybe_relocatable, ReadOnlySegment, ReadOnlySegments, + felt_from_ptr, felt_range_from_ptr, max_fee_for_execution_info, write_maybe_relocatable, + ReadOnlySegment, ReadOnlySegments, }; use crate::execution::syscalls::secp::{ secp256k1_add, secp256k1_get_point_from_x, secp256k1_get_xy, secp256k1_mul, secp256k1_new, @@ -59,8 +57,10 @@ pub enum SyscallExecutionError { EmitEventError(#[from] EmitEventError), #[error("Cannot replace V1 class hash with V0 class hash: {class_hash}.")] ForbiddenClassReplacement { class_hash: ClassHash }, + #[error(transparent)] + FromStr(#[from] FromStrError), #[error("Invalid address domain: {address_domain}.")] - InvalidAddressDomain { address_domain: StarkFelt }, + InvalidAddressDomain { address_domain: Felt }, #[error(transparent)] ConstructorEntryPointExecutionError(#[from] ConstructorEntryPointExecutionError), #[error(transparent)] @@ -80,9 +80,9 @@ pub enum SyscallExecutionError { error: Box, }, #[error("Invalid syscall input: {input:?}; {info}")] - InvalidSyscallInput { input: StarkFelt, info: String }, + InvalidSyscallInput { input: Felt, info: String }, #[error("Invalid syscall selector: {0:?}.")] - InvalidSyscallSelector(StarkFelt), + InvalidSyscallSelector(Felt), #[error("Unauthorized syscall {syscall_name} in execution mode {execution_mode}.")] InvalidSyscallInExecutionMode { syscall_name: String, execution_mode: ExecutionMode }, #[error(transparent)] @@ -98,7 +98,7 @@ pub enum SyscallExecutionError { #[error(transparent)] VirtualMachineError(#[from] VirtualMachineError), #[error("Syscall error.")] - SyscallError { error_data: Vec }, + SyscallError { error_data: Vec }, } #[derive(Debug, Error)] @@ -198,7 +198,7 @@ pub struct SyscallHintProcessor<'a> { pub syscall_ptr: Relocatable, // Additional information gathered during execution. - pub read_values: Vec, + pub read_values: Vec, pub accessed_keys: HashSet, // Secp hint processors. @@ -433,9 +433,9 @@ impl<'a> SyscallHintProcessor<'a> { vm: &mut VirtualMachine, tx_info: &CurrentTransactionInfo, ) -> SyscallResult<(Relocatable, Relocatable)> { - let l1_gas = StarkFelt::try_from(L1_GAS).map_err(SyscallExecutionError::from)?; - let l2_gas = StarkFelt::try_from(L2_GAS).map_err(SyscallExecutionError::from)?; - let flat_resource_bounds: Vec = tx_info + let l1_gas = Felt::from_hex(L1_GAS).map_err(SyscallExecutionError::from)?; + let l2_gas = Felt::from_hex(L2_GAS).map_err(SyscallExecutionError::from)?; + let flat_resource_bounds: Vec = tx_info .resource_bounds .0 .iter() @@ -447,8 +447,8 @@ impl<'a> SyscallHintProcessor<'a> { vec![ resource, - StarkFelt::from(resource_bounds.max_amount), - StarkFelt::from(resource_bounds.max_price_per_unit), + Felt::from(resource_bounds.max_amount), + Felt::from(resource_bounds.max_price_per_unit), ] }) .collect(); @@ -481,7 +481,7 @@ impl<'a> SyscallHintProcessor<'a> { if gas_counter < required_gas { // Out of gas failure. let out_of_gas_error = - StarkFelt::try_from(OUT_OF_GAS_ERROR).map_err(SyscallExecutionError::from)?; + Felt::from_hex(OUT_OF_GAS_ERROR).map_err(SyscallExecutionError::from)?; let response: SyscallResponseWrapper = SyscallResponseWrapper::Failure { gas_counter, error_data: vec![out_of_gas_error] }; response.write(vm, &mut self.syscall_ptr)?; @@ -507,8 +507,8 @@ impl<'a> SyscallHintProcessor<'a> { Ok(()) } - fn read_next_syscall_selector(&mut self, vm: &mut VirtualMachine) -> SyscallResult { - let selector = stark_felt_from_ptr(vm, &mut self.syscall_ptr)?; + fn read_next_syscall_selector(&mut self, vm: &mut VirtualMachine) -> SyscallResult { + let selector = felt_from_ptr(vm, &mut self.syscall_ptr)?; Ok(selector) } @@ -532,9 +532,9 @@ impl<'a> SyscallHintProcessor<'a> { let additional_info: Vec = vec![ block_info_ptr.into(), tx_info_ptr.into(), - stark_felt_to_felt(*self.caller_address().0.key()).into(), - stark_felt_to_felt(*self.storage_address().0.key()).into(), - stark_felt_to_felt(self.entry_point_selector().0).into(), + self.caller_address().0.key().into(), + self.storage_address().0.key().into(), + self.entry_point_selector().0.into(), ]; let execution_info_segment_start_ptr = self.read_only_segments.allocate(vm, &additional_info)?; @@ -550,7 +550,7 @@ impl<'a> SyscallHintProcessor<'a> { let block_timestamp = block_info.block_timestamp.0; let block_number = block_info.block_number.0; let versioned_constants = self.context.versioned_constants(); - let block_data: Vec = if self.is_validate_mode() { + let block_data: Vec = if self.is_validate_mode() { // Round down to the nearest multiple of validate_block_number_rounding. let validate_block_number_rounding = versioned_constants.get_validate_block_number_rounding(); @@ -561,15 +561,11 @@ impl<'a> SyscallHintProcessor<'a> { let rounded_timestamp = (block_timestamp / validate_timestamp_rounding) * validate_timestamp_rounding; - vec![ - StarkFelt::from(rounded_block_number), - StarkFelt::from(rounded_timestamp), - StarkFelt::ZERO, - ] + vec![Felt::from(rounded_block_number), Felt::from(rounded_timestamp), Felt::ZERO] } else { vec![ - StarkFelt::from(block_number), - StarkFelt::from(block_timestamp), + Felt::from(block_number), + Felt::from(block_timestamp), *block_info.sequencer_address.0.key(), ] }; @@ -581,9 +577,9 @@ impl<'a> SyscallHintProcessor<'a> { fn allocate_data_segment( &mut self, vm: &mut VirtualMachine, - data: &[StarkFelt], + data: &[Felt], ) -> SyscallResult<(Relocatable, Relocatable)> { - let data = data.iter().map(|&x| MaybeRelocatable::from(stark_felt_to_felt(x))).collect(); + let data = data.iter().map(|&x| MaybeRelocatable::from(x)).collect(); let data_segment_start_ptr = self.read_only_segments.allocate(vm, &data)?; let data_segment_end_ptr = (data_segment_start_ptr + data.len())?; Ok((data_segment_start_ptr, data_segment_end_ptr)) @@ -595,17 +591,17 @@ impl<'a> SyscallHintProcessor<'a> { &self.allocate_data_segment(vm, &tx_info.signature().0)?; let mut tx_data: Vec = vec![ - stark_felt_to_felt(tx_info.signed_version().0).into(), - stark_felt_to_felt(*tx_info.sender_address().0.key()).into(), + tx_info.signed_version().0.into(), + tx_info.sender_address().0.key().into(), max_fee_for_execution_info(tx_info).into(), tx_signature_start_ptr.into(), tx_signature_end_ptr.into(), - stark_felt_to_felt((tx_info).transaction_hash().0).into(), - Felt252::from_bytes_be( - self.context.tx_context.block_context.chain_info.chain_id.0.as_bytes(), - ) + (tx_info).transaction_hash().0.into(), + Felt::from_hex( + self.context.tx_context.block_context.chain_info.chain_id.as_hex().as_str(), + )? .into(), - stark_felt_to_felt((tx_info).nonce().0).into(), + (tx_info).nonce().0.into(), ]; match tx_info { @@ -622,17 +618,17 @@ impl<'a> SyscallHintProcessor<'a> { tx_data.extend_from_slice(&[ tx_resource_bounds_start_ptr.into(), tx_resource_bounds_end_ptr.into(), - Felt252::from(context.tip.0).into(), + Felt::from(context.tip.0).into(), tx_paymaster_data_start_ptr.into(), tx_paymaster_data_end_ptr.into(), - stark_felt_to_felt(context.nonce_data_availability_mode.into()).into(), - stark_felt_to_felt(context.fee_data_availability_mode.into()).into(), + Felt::from(context.nonce_data_availability_mode).into(), + Felt::from(context.fee_data_availability_mode).into(), tx_account_deployment_data_start_ptr.into(), tx_account_deployment_data_end_ptr.into(), ]); } TransactionInfo::Deprecated(_) => { - let zero_felt: MaybeRelocatable = Felt252::zero().into(); + let zero_felt: MaybeRelocatable = Felt::ZERO.into(); tx_data.extend_from_slice(&[ zero_felt.clone(), // Empty segment of resource bounds (start ptr). zero_felt.clone(), // Empty segment of resource bounds (end ptr). @@ -665,7 +661,7 @@ impl<'a> SyscallHintProcessor<'a> { pub fn set_contract_storage_at( &mut self, key: StorageKey, - value: StarkFelt, + value: Felt, ) -> SyscallResult { self.accessed_keys.insert(key); self.state.set_storage_at(self.storage_address(), key, value)?; @@ -678,12 +674,12 @@ impl<'a> SyscallHintProcessor<'a> { /// A [ResOperand] represents a CASM result expression, and is deserialized with the hint. fn get_ptr_from_res_operand_unchecked(vm: &mut VirtualMachine, res: &ResOperand) -> Relocatable { let (cell, base_offset) = match res { - ResOperand::Deref(cell) => (cell, Felt252::from(0)), + ResOperand::Deref(cell) => (cell, Felt::from(0)), ResOperand::BinOp(BinOpOperand { op: Operation::Add, a, b: DerefOrImmediate::Immediate(b), - }) => (a, Felt252::from(b.clone().value)), + }) => (a, Felt::from(b.clone().value)), _ => panic!("Illegal argument for a buffer."), }; let base = match cell.register { @@ -718,7 +714,7 @@ impl HintProcessorLogic for SyscallHintProcessor<'_> { vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, hint_data: &Box, - _constants: &HashMap, + _constants: &HashMap, ) -> HintExecutionResult { let hint = hint_data.downcast_ref::().ok_or(HintError::WrongHintData)?; match hint { @@ -739,10 +735,10 @@ impl HintProcessorLogic for SyscallHintProcessor<'_> { } } -pub fn felt_to_bool(felt: StarkFelt, error_info: &str) -> SyscallResult { - if felt == StarkFelt::from(0_u8) { +pub fn felt_to_bool(felt: Felt, error_info: &str) -> SyscallResult { + if felt == Felt::from(0_u8) { Ok(false) - } else if felt == StarkFelt::from(1_u8) { + } else if felt == Felt::from(1_u8) { Ok(true) } else { Err(SyscallExecutionError::InvalidSyscallInput { input: felt, info: error_info.into() }) @@ -757,7 +753,7 @@ pub fn read_call_params( vm: &VirtualMachine, ptr: &mut Relocatable, ) -> SyscallResult<(EntryPointSelector, Calldata)> { - let function_selector = EntryPointSelector(stark_felt_from_ptr(vm, ptr)?); + let function_selector = EntryPointSelector(felt_from_ptr(vm, ptr)?); let calldata = read_calldata(vm, ptr)?; Ok((function_selector, calldata)) @@ -790,7 +786,7 @@ pub fn execute_inner_call( pub fn create_retdata_segment( vm: &mut VirtualMachine, syscall_handler: &mut SyscallHintProcessor<'_>, - raw_retdata: &[StarkFelt], + raw_retdata: &[Felt], ) -> SyscallResult { let (retdata_segment_start_ptr, _) = syscall_handler.allocate_data_segment(vm, raw_retdata)?; @@ -830,10 +826,7 @@ pub fn execute_library_call( }) } -pub fn read_felt_array( - vm: &VirtualMachine, - ptr: &mut Relocatable, -) -> Result, TErr> +pub fn read_felt_array(vm: &VirtualMachine, ptr: &mut Relocatable) -> Result, TErr> where TErr: From + From + From + From, { diff --git a/crates/blockifier/src/execution/syscalls/mod.rs b/crates/blockifier/src/execution/syscalls/mod.rs index 67dfdc0c3d..ecb2fe611e 100644 --- a/crates/blockifier/src/execution/syscalls/mod.rs +++ b/crates/blockifier/src/execution/syscalls/mod.rs @@ -1,4 +1,3 @@ -use cairo_felt::Felt252; use cairo_vm::types::relocatable::{MaybeRelocatable, Relocatable}; use cairo_vm::vm::vm_core::VirtualMachine; use num_traits::ToPrimitive; @@ -7,11 +6,11 @@ use starknet_api::core::{ calculate_contract_address, ClassHash, ContractAddress, EntryPointSelector, EthAddress, }; use starknet_api::deprecated_contract_class::EntryPointType; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; use starknet_api::transaction::{ Calldata, ContractAddressSalt, EventContent, EventData, EventKey, L2ToL1Payload, }; +use starknet_types_core::felt::Felt; use self::hint_processor::{ create_retdata_segment, execute_inner_call, execute_library_call, felt_to_bool, @@ -24,8 +23,7 @@ use crate::execution::contract_class::ContractClass; use crate::execution::deprecated_syscalls::DeprecatedSyscallSelector; use crate::execution::entry_point::{CallEntryPoint, CallType, ConstructorContext}; use crate::execution::execution_utils::{ - execute_deployment, felt_from_ptr, felt_to_stark_felt, stark_felt_from_ptr, stark_felt_to_felt, - write_felt, write_maybe_relocatable, write_stark_felt, ReadOnlySegment, + execute_deployment, felt_from_ptr, write_felt, write_maybe_relocatable, ReadOnlySegment, }; use crate::execution::syscalls::hint_processor::{INVALID_INPUT_LENGTH_ERROR, OUT_OF_GAS_ERROR}; use crate::transaction::transaction_utils::update_remaining_gas; @@ -61,7 +59,7 @@ impl SyscallRequest for SyscallRequestWrapper { let gas_counter = felt_from_ptr(vm, ptr)?; let gas_counter = gas_counter.to_u64().ok_or_else(|| SyscallExecutionError::InvalidSyscallInput { - input: felt_to_stark_felt(&gas_counter), + input: gas_counter, info: String::from("Unexpected gas."), })?; Ok(Self { gas_counter, request: T::read(vm, ptr)? }) @@ -70,27 +68,27 @@ impl SyscallRequest for SyscallRequestWrapper { pub enum SyscallResponseWrapper { Success { gas_counter: u64, response: T }, - Failure { gas_counter: u64, error_data: Vec }, + Failure { gas_counter: u64, error_data: Vec }, } impl SyscallResponse for SyscallResponseWrapper { fn write(self, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { match self { Self::Success { gas_counter, response } => { - write_felt(vm, ptr, Felt252::from(gas_counter))?; + write_felt(vm, ptr, Felt::from(gas_counter))?; // 0 to indicate success. - write_stark_felt(vm, ptr, StarkFelt::from(0_u8))?; + write_felt(vm, ptr, Felt::from(0_u8))?; response.write(vm, ptr) } Self::Failure { gas_counter, error_data } => { - write_felt(vm, ptr, Felt252::from(gas_counter))?; + write_felt(vm, ptr, Felt::from(gas_counter))?; // 1 to indicate failure. - write_stark_felt(vm, ptr, StarkFelt::from(1_u8))?; + write_felt(vm, ptr, Felt::from(1_u8))?; // Write the error data to a new memory segment. let revert_reason_start = vm.add_memory_segment(); let revert_reason_end = vm.load_data( revert_reason_start, - &error_data.into_iter().map(stark_felt_to_felt).map(Into::into).collect(), + &error_data.into_iter().map(Into::into).collect(), )?; // Write the start and end pointers of the error data. @@ -144,7 +142,7 @@ pub struct CallContractRequest { impl SyscallRequest for CallContractRequest { fn read(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { - let contract_address = ContractAddress::try_from(stark_felt_from_ptr(vm, ptr)?)?; + let contract_address = ContractAddress::try_from(felt_from_ptr(vm, ptr)?)?; let (function_selector, calldata) = read_call_params(vm, ptr)?; Ok(CallContractRequest { contract_address, function_selector, calldata }) @@ -199,10 +197,10 @@ pub struct DeployRequest { impl SyscallRequest for DeployRequest { fn read(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { - let class_hash = ClassHash(stark_felt_from_ptr(vm, ptr)?); - let contract_address_salt = ContractAddressSalt(stark_felt_from_ptr(vm, ptr)?); + let class_hash = ClassHash(felt_from_ptr(vm, ptr)?); + let contract_address_salt = ContractAddressSalt(felt_from_ptr(vm, ptr)?); let constructor_calldata = read_calldata(vm, ptr)?; - let deploy_from_zero = stark_felt_from_ptr(vm, ptr)?; + let deploy_from_zero = felt_from_ptr(vm, ptr)?; Ok(DeployRequest { class_hash, @@ -224,7 +222,7 @@ pub struct DeployResponse { impl SyscallResponse for DeployResponse { fn write(self, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { - write_stark_felt(vm, ptr, *self.contract_address.0.key())?; + write_felt(vm, ptr, *self.contract_address.0.key())?; write_segment(vm, ptr, self.constructor_retdata) } } @@ -348,7 +346,7 @@ impl SyscallRequest for GetBlockHashRequest { let felt = felt_from_ptr(vm, ptr)?; let block_number = BlockNumber(felt.to_u64().ok_or_else(|| { SyscallExecutionError::InvalidSyscallInput { - input: felt_to_stark_felt(&felt), + input: felt, info: String::from("Block number must fit within 64 bits."), } })?); @@ -364,7 +362,7 @@ pub struct GetBlockHashResponse { impl SyscallResponse for GetBlockHashResponse { fn write(self, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { - write_stark_felt(vm, ptr, self.block_hash.0)?; + write_felt(vm, ptr, self.block_hash.0)?; Ok(()) } } @@ -393,14 +391,14 @@ pub fn get_block_hash( if current_block_number < constants::STORED_BLOCK_HASH_BUFFER || requested_block_number > current_block_number - constants::STORED_BLOCK_HASH_BUFFER { - let out_of_range_error = StarkFelt::try_from(BLOCK_NUMBER_OUT_OF_RANGE_ERROR) - .map_err(SyscallExecutionError::from)?; + let out_of_range_error = + Felt::from_hex(BLOCK_NUMBER_OUT_OF_RANGE_ERROR).map_err(SyscallExecutionError::from)?; return Err(SyscallExecutionError::SyscallError { error_data: vec![out_of_range_error] }); } - let key = StorageKey::try_from(StarkFelt::from(requested_block_number))?; + let key = StorageKey::try_from(Felt::from(requested_block_number))?; let block_hash_contract_address = - ContractAddress::try_from(StarkFelt::from(constants::BLOCK_HASH_CONTRACT_ADDRESS))?; + ContractAddress::try_from(Felt::from(constants::BLOCK_HASH_CONTRACT_ADDRESS))?; let block_hash = BlockHash(syscall_handler.state.get_storage_at(block_hash_contract_address, key)?); Ok(GetBlockHashResponse { block_hash }) @@ -443,7 +441,7 @@ pub struct LibraryCallRequest { impl SyscallRequest for LibraryCallRequest { fn read(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { - let class_hash = ClassHash(stark_felt_from_ptr(vm, ptr)?); + let class_hash = ClassHash(felt_from_ptr(vm, ptr)?); let (function_selector, calldata) = read_call_params(vm, ptr)?; Ok(LibraryCallRequest { class_hash, function_selector, calldata }) @@ -503,7 +501,7 @@ pub struct ReplaceClassRequest { impl SyscallRequest for ReplaceClassRequest { fn read(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { - let class_hash = ClassHash(stark_felt_from_ptr(vm, ptr)?); + let class_hash = ClassHash(felt_from_ptr(vm, ptr)?); Ok(ReplaceClassRequest { class_hash }) } @@ -544,7 +542,7 @@ pub struct SendMessageToL1Request { impl SyscallRequest for SendMessageToL1Request { // The Cairo struct contains: `to_address`, `payload_size`, `payload`. fn read(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { - let to_address = EthAddress::try_from(stark_felt_from_ptr(vm, ptr)?)?; + let to_address = EthAddress::try_from(felt_from_ptr(vm, ptr)?)?; let payload = L2ToL1Payload(read_felt_array::(vm, ptr)?); Ok(SendMessageToL1Request { message: MessageToL1 { to_address, payload } }) @@ -575,29 +573,29 @@ pub fn send_message_to_l1( #[derive(Debug, Eq, PartialEq)] pub struct StorageReadRequest { - pub address_domain: StarkFelt, + pub address_domain: Felt, pub address: StorageKey, } impl SyscallRequest for StorageReadRequest { fn read(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { - let address_domain = stark_felt_from_ptr(vm, ptr)?; - if address_domain != StarkFelt::from(0_u8) { + let address_domain = felt_from_ptr(vm, ptr)?; + if address_domain != Felt::from(0_u8) { return Err(SyscallExecutionError::InvalidAddressDomain { address_domain }); } - let address = StorageKey::try_from(stark_felt_from_ptr(vm, ptr)?)?; + let address = StorageKey::try_from(felt_from_ptr(vm, ptr)?)?; Ok(StorageReadRequest { address_domain, address }) } } #[derive(Debug, Eq, PartialEq)] pub struct StorageReadResponse { - pub value: StarkFelt, + pub value: Felt, } impl SyscallResponse for StorageReadResponse { fn write(self, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { - write_stark_felt(vm, ptr, self.value)?; + write_felt(vm, ptr, self.value)?; Ok(()) } } @@ -615,19 +613,19 @@ pub fn storage_read( #[derive(Debug, Eq, PartialEq)] pub struct StorageWriteRequest { - pub address_domain: StarkFelt, + pub address_domain: Felt, pub address: StorageKey, - pub value: StarkFelt, + pub value: Felt, } impl SyscallRequest for StorageWriteRequest { fn read(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { - let address_domain = stark_felt_from_ptr(vm, ptr)?; - if address_domain != StarkFelt::from(0_u8) { + let address_domain = felt_from_ptr(vm, ptr)?; + if address_domain != Felt::from(0_u8) { return Err(SyscallExecutionError::InvalidAddressDomain { address_domain }); } - let address = StorageKey::try_from(stark_felt_from_ptr(vm, ptr)?)?; - let value = stark_felt_from_ptr(vm, ptr)?; + let address = StorageKey::try_from(felt_from_ptr(vm, ptr)?)?; + let value = felt_from_ptr(vm, ptr)?; Ok(StorageWriteRequest { address_domain, address, value }) } } @@ -663,8 +661,8 @@ impl SyscallRequest for KeccakRequest { #[derive(Debug, Eq, PartialEq)] pub struct KeccakResponse { - pub result_low: Felt252, - pub result_high: Felt252, + pub result_low: Felt, + pub result_high: Felt, } impl SyscallResponse for KeccakResponse { @@ -689,8 +687,7 @@ pub fn keccak( if remainder != 0 { return Err(SyscallExecutionError::SyscallError { error_data: vec![ - StarkFelt::try_from(INVALID_INPUT_LENGTH_ERROR) - .map_err(SyscallExecutionError::from)?, + Felt::from_hex(INVALID_INPUT_LENGTH_ERROR).map_err(SyscallExecutionError::from)?, ], }); } @@ -700,7 +697,7 @@ pub fn keccak( let gas_cost = n_rounds_as_u64 * syscall_handler.context.gas_costs().keccak_round_cost_gas_cost; if gas_cost > *remaining_gas { let out_of_gas_error = - StarkFelt::try_from(OUT_OF_GAS_ERROR).map_err(SyscallExecutionError::from)?; + Felt::from_hex(OUT_OF_GAS_ERROR).map_err(SyscallExecutionError::from)?; return Err(SyscallExecutionError::SyscallError { error_data: vec![out_of_gas_error] }); } @@ -716,7 +713,7 @@ pub fn keccak( for chunk in data.chunks(KECCAK_FULL_RATE_IN_WORDS) { for (i, val) in chunk.iter().enumerate() { state[i] ^= val.to_u64().ok_or_else(|| SyscallExecutionError::InvalidSyscallInput { - input: felt_to_stark_felt(val), + input: **val, info: String::from("Invalid input for the keccak syscall."), })?; } @@ -724,8 +721,8 @@ pub fn keccak( } Ok(KeccakResponse { - result_low: (Felt252::from(state[1]) << 64u32) + Felt252::from(state[0]), - result_high: (Felt252::from(state[3]) << 64u32) + Felt252::from(state[2]), + result_low: (Felt::from(state[1]) * Felt::TWO.pow(64_u128)) + Felt::from(state[0]), + result_high: (Felt::from(state[3]) * Felt::TWO.pow(64_u128)) + Felt::from(state[2]), }) } @@ -796,7 +793,7 @@ pub fn sha_256_process_block( let response = segment; let data: Vec = - state_as_words.iter().map(|&arg| MaybeRelocatable::from(Felt252::from(arg))).collect(); + state_as_words.iter().map(|&arg| MaybeRelocatable::from(Felt::from(arg))).collect(); syscall_handler.sha256_segment_end_ptr = Some(vm.load_data(segment, &data)?); diff --git a/crates/blockifier/src/execution/syscalls/secp.rs b/crates/blockifier/src/execution/syscalls/secp.rs index f9804ddf47..60df6dc30d 100644 --- a/crates/blockifier/src/execution/syscalls/secp.rs +++ b/crates/blockifier/src/execution/syscalls/secp.rs @@ -1,23 +1,19 @@ use ark_ec::short_weierstrass; use ark_ec::short_weierstrass::SWCurveConfig; use ark_ff::{BigInteger, PrimeField}; -use cairo_felt::Felt252; use cairo_vm::types::relocatable::Relocatable; use cairo_vm::vm::vm_core::VirtualMachine; use num_bigint::BigUint; use num_traits::{ToPrimitive, Zero}; -use starknet_api::hash::StarkFelt; +use starknet_types_core::felt::Felt; use crate::abi::sierra_types::{SierraType, SierraU256}; -use crate::execution::execution_utils::{ - felt_from_ptr, stark_felt_from_ptr, write_maybe_relocatable, write_u256, -}; +use crate::execution::execution_utils::{felt_from_ptr, write_maybe_relocatable, write_u256}; use crate::execution::syscalls::hint_processor::{ felt_to_bool, SyscallHintProcessor, INVALID_ARGUMENT, }; use crate::execution::syscalls::{ - felt_to_stark_felt, SyscallExecutionError, SyscallRequest, SyscallResponse, SyscallResult, - WriteResponseResult, + SyscallExecutionError, SyscallRequest, SyscallResponse, SyscallResult, WriteResponseResult, }; #[derive(Debug, Default, Eq, PartialEq)] @@ -53,7 +49,7 @@ where if request.x >= modulos { return Err(SyscallExecutionError::SyscallError { error_data: vec![ - StarkFelt::try_from(INVALID_ARGUMENT).map_err(SyscallExecutionError::from)?, + Felt::from_hex(INVALID_ARGUMENT).map_err(SyscallExecutionError::from)?, ], }); } @@ -84,7 +80,7 @@ where if x >= modulos || y >= modulos { return Err(SyscallExecutionError::SyscallError { error_data: vec![ - StarkFelt::try_from(INVALID_ARGUMENT).map_err(SyscallExecutionError::from)?, + Felt::from_hex(INVALID_ARGUMENT).map_err(SyscallExecutionError::from)?, ], }); } @@ -111,11 +107,11 @@ where fn get_point_by_id( &self, - ec_point_id: Felt252, + ec_point_id: Felt, ) -> SyscallResult<&short_weierstrass::Affine> { ec_point_id.to_usize().and_then(|id| self.points.get(id)).ok_or_else(|| { SyscallExecutionError::InvalidSyscallInput { - input: felt_to_stark_felt(&ec_point_id), + input: ec_point_id, info: "Invalid Secp point ID".to_string(), } }) @@ -172,8 +168,8 @@ impl SyscallResponse for SecpOpRespone { #[derive(Debug, Eq, PartialEq)] pub struct SecpAddRequest { - pub lhs_id: Felt252, - pub rhs_id: Felt252, + pub lhs_id: Felt, + pub rhs_id: Felt, } impl SyscallRequest for SecpAddRequest { @@ -216,7 +212,7 @@ impl SyscallRequest for SecpGetPointFromXRequest { fn read(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { let x = SierraU256::from_memory(vm, ptr)?.to_biguint(); - let y_parity = felt_to_bool(stark_felt_from_ptr(vm, ptr)?, "Invalid y parity")?; + let y_parity = felt_to_bool(felt_from_ptr(vm, ptr)?, "Invalid y parity")?; Ok(SecpGetPointFromXRequest { x, y_parity }) } } @@ -245,7 +241,7 @@ pub fn secp256r1_get_point_from_x( #[derive(Debug, Eq, PartialEq)] pub struct SecpGetXyRequest { - pub ec_point_id: Felt252, + pub ec_point_id: Felt, } impl SyscallRequest for SecpGetXyRequest { @@ -286,7 +282,7 @@ pub fn secp256r1_get_xy( #[derive(Debug, Eq, PartialEq)] pub struct SecpMulRequest { - pub ec_point_id: Felt252, + pub ec_point_id: Felt, pub multiplier: BigUint, } diff --git a/crates/blockifier/src/execution/syscalls/syscalls_test.rs b/crates/blockifier/src/execution/syscalls/syscalls_test.rs index 6f2fa770d2..d3186713d8 100644 --- a/crates/blockifier/src/execution/syscalls/syscalls_test.rs +++ b/crates/blockifier/src/execution/syscalls/syscalls_test.rs @@ -1,9 +1,8 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use assert_matches::assert_matches; -use cairo_felt::Felt252; use cairo_lang_utils::byte_array::BYTE_ARRAY_MAGIC; -use cairo_vm::vm::runners::builtin_runner::RANGE_CHECK_BUILTIN_NAME; +use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use num_traits::Pow; use pretty_assertions::assert_eq; @@ -12,14 +11,14 @@ use starknet_api::core::{ calculate_contract_address, ChainId, ContractAddress, EthAddress, PatriciaKey, }; use starknet_api::data_availability::DataAvailabilityMode; -use starknet_api::hash::{StarkFelt, StarkHash}; use starknet_api::state::StorageKey; use starknet_api::transaction::{ AccountDeploymentData, Calldata, ContractAddressSalt, EventContent, EventData, EventKey, Fee, L2ToL1Payload, PaymasterData, Resource, ResourceBounds, ResourceBoundsMapping, Tip, TransactionHash, TransactionVersion, }; -use starknet_api::{calldata, stark_felt}; +use starknet_api::{calldata, felt}; +use starknet_types_core::felt::Felt; use test_case::test_case; use crate::abi::abi_utils::selector_from_name; @@ -31,7 +30,6 @@ use crate::execution::call_info::{ use crate::execution::common_hints::ExecutionMode; use crate::execution::entry_point::{CallEntryPoint, CallType}; use crate::execution::errors::EntryPointExecutionError; -use crate::execution::execution_utils::{felt_to_stark_felt, stark_felt_to_felt}; use crate::execution::syscalls::hint_processor::{ EmitEventError, BLOCK_NUMBER_OUT_OF_RANGE_ERROR, L1_GAS, L2_GAS, OUT_OF_GAS_ERROR, }; @@ -61,8 +59,8 @@ fn test_storage_read_write() { let chain_info = &ChainInfo::create_for_testing(); let mut state = test_state(chain_info, BALANCE, &[(test_contract, 1)]); - let key = stark_felt!(1234_u16); - let value = stark_felt!(18_u8); + let key = felt!(1234_u16); + let value = felt!(18_u8); let calldata = calldata![key, value]; let entry_point_call = CallEntryPoint { calldata, @@ -73,7 +71,7 @@ fn test_storage_read_write() { assert_eq!( entry_point_call.execute_directly(&mut state).unwrap().execution, CallExecution { - retdata: retdata![stark_felt!(value)], + retdata: retdata![value], gas_consumed: REQUIRED_GAS_STORAGE_READ_WRITE_TEST, ..CallExecution::default() } @@ -95,8 +93,8 @@ fn test_call_contract() { FeatureContract::TestContract(CairoVersion::Cairo1).get_instance_address(0), "test_storage_read_write", &[ - stark_felt!(405_u16), // Calldata: address. - stark_felt!(48_u8), // Calldata: value. + felt!(405_u16), // Calldata: address. + felt!(48_u8), // Calldata: value. ], ); let entry_point_call = CallEntryPoint { @@ -107,7 +105,7 @@ fn test_call_contract() { assert_eq!( entry_point_call.execute_directly(&mut state).unwrap().execution, CallExecution { - retdata: retdata![stark_felt!(48_u8)], + retdata: retdata![felt!(48_u8)], gas_consumed: REQUIRED_GAS_CALL_CONTRACT_TEST, ..CallExecution::default() } @@ -118,10 +116,10 @@ fn test_call_contract() { fn test_emit_event() { let versioned_constants = VersionedConstants::create_for_testing(); // Positive flow. - let keys = vec![stark_felt!(2019_u16), stark_felt!(2020_u16)]; - let data = vec![stark_felt!(2021_u16), stark_felt!(2022_u16), stark_felt!(2023_u16)]; + let keys = vec![felt!(2019_u16), felt!(2020_u16)]; + let data = vec![felt!(2021_u16), felt!(2022_u16), felt!(2023_u16)]; // TODO(Ori, 1/2/2024): Write an indicative expect message explaining why the conversion works. - let n_emitted_events = vec![stark_felt!(1_u16)]; + let n_emitted_events = vec![felt!(1_u16)]; let call_info = emit_events(&n_emitted_events, &keys, &data).unwrap(); let event = EventContent { keys: keys.clone().into_iter().map(EventKey).collect(), @@ -138,7 +136,7 @@ fn test_emit_event() { // Negative flow, the data length exceeds the limit. let max_event_data_length = versioned_constants.tx_event_limits.max_data_length; - let data_too_long = vec![stark_felt!(2_u16); max_event_data_length + 1]; + let data_too_long = vec![felt!(2_u16); max_event_data_length + 1]; let error = emit_events(&n_emitted_events, &keys, &data_too_long).unwrap_err(); let expected_error = EmitEventError::ExceedsMaxDataLength { data_length: max_event_data_length + 1, @@ -148,7 +146,7 @@ fn test_emit_event() { // Negative flow, the keys length exceeds the limit. let max_event_keys_length = versioned_constants.tx_event_limits.max_keys_length; - let keys_too_long = vec![stark_felt!(1_u16); max_event_keys_length + 1]; + let keys_too_long = vec![felt!(1_u16); max_event_keys_length + 1]; let error = emit_events(&n_emitted_events, &keys_too_long, &data).unwrap_err(); let expected_error = EmitEventError::ExceedsMaxKeysLength { keys_length: max_event_keys_length + 1, @@ -158,7 +156,7 @@ fn test_emit_event() { // Negative flow, the number of events exceeds the limit. let max_n_emitted_events = versioned_constants.tx_event_limits.max_n_emitted_events; - let n_emitted_events_too_big = vec![stark_felt!( + let n_emitted_events_too_big = vec![felt!( u16::try_from(max_n_emitted_events + 1).expect("Failed to convert usize to u16.") )]; let error = emit_events(&n_emitted_events_too_big, &keys, &data).unwrap_err(); @@ -170,9 +168,9 @@ fn test_emit_event() { } fn emit_events( - n_emitted_events: &[StarkFelt], - keys: &[StarkFelt], - data: &[StarkFelt], + n_emitted_events: &[Felt], + keys: &[Felt], + data: &[Felt], ) -> Result { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo1); let chain_info = &ChainInfo::create_for_testing(); @@ -180,9 +178,9 @@ fn emit_events( let calldata = Calldata( [ n_emitted_events.to_owned(), - vec![stark_felt!(u16::try_from(keys.len()).expect("Failed to convert usize to u16."))], + vec![felt!(u16::try_from(keys.len()).expect("Failed to convert usize to u16."))], keys.to_vec(), - vec![stark_felt!(u16::try_from(data.len()).expect("Failed to convert usize to u16."))], + vec![felt!(u16::try_from(data.len()).expect("Failed to convert usize to u16."))], data.to_vec(), ] .concat() @@ -206,11 +204,11 @@ fn test_get_block_hash() { // Initialize block number -> block hash entry. let upper_bound_block_number = CURRENT_BLOCK_NUMBER - constants::STORED_BLOCK_HASH_BUFFER; - let block_number = stark_felt!(upper_bound_block_number); - let block_hash = stark_felt!(66_u64); + let block_number = felt!(upper_bound_block_number); + let block_hash = felt!(66_u64); let key = StorageKey::try_from(block_number).unwrap(); let block_hash_contract_address = - ContractAddress::try_from(StarkFelt::from(constants::BLOCK_HASH_CONTRACT_ADDRESS)).unwrap(); + ContractAddress::try_from(Felt::from(constants::BLOCK_HASH_CONTRACT_ADDRESS)).unwrap(); state.set_storage_at(block_hash_contract_address, key, block_hash).unwrap(); // Positive flow. @@ -235,7 +233,7 @@ fn test_get_block_hash() { // Negative flow: Block number out of range. let requested_block_number = CURRENT_BLOCK_NUMBER - constants::STORED_BLOCK_HASH_BUFFER + 1; - let block_number = stark_felt!(requested_block_number); + let block_number = felt!(requested_block_number); let calldata = calldata![block_number]; let entry_point_call = CallEntryPoint { entry_point_selector: selector_from_name("test_get_block_hash"), @@ -244,7 +242,7 @@ fn test_get_block_hash() { }; let error = entry_point_call.execute_directly(&mut state).unwrap_err(); assert_matches!(error, EntryPointExecutionError::ExecutionFailed{ error_data } - if error_data == vec![stark_felt!(BLOCK_NUMBER_OUT_OF_RANGE_ERROR)]); + if error_data == vec![felt!(BLOCK_NUMBER_OUT_OF_RANGE_ERROR)]); } #[test] @@ -356,15 +354,15 @@ fn test_get_execution_info( let expected_block_info = match execution_mode { ExecutionMode::Validate => [ // Rounded block number. - stark_felt!(CURRENT_BLOCK_NUMBER_FOR_VALIDATE), + felt!(CURRENT_BLOCK_NUMBER_FOR_VALIDATE), // Rounded timestamp. - stark_felt!(CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE), - StarkFelt::ZERO, + felt!(CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE), + Felt::ZERO, ], ExecutionMode::Execute => [ - stark_felt!(CURRENT_BLOCK_NUMBER), // Block number. - stark_felt!(CURRENT_BLOCK_TIMESTAMP), // Block timestamp. - StarkFelt::try_from(TEST_SEQUENCER_ADDRESS).unwrap(), + felt!(CURRENT_BLOCK_NUMBER), // Block number. + felt!(CURRENT_BLOCK_TIMESTAMP), // Block timestamp. + Felt::from_hex(TEST_SEQUENCER_ADDRESS).unwrap(), ], }; @@ -375,42 +373,42 @@ fn test_get_execution_info( ( test_contract.get_instance_address(0), vec![ - StarkFelt::ZERO, // Tip. - StarkFelt::ZERO, // Paymaster data. - StarkFelt::ZERO, // Nonce DA. - StarkFelt::ZERO, // Fee DA. - StarkFelt::ZERO, // Account data. + Felt::ZERO, // Tip. + Felt::ZERO, // Paymaster data. + Felt::ZERO, // Nonce DA. + Felt::ZERO, // Fee DA. + Felt::ZERO, // Account data. ], ) }; if only_query { - let simulate_version_base = Pow::pow(Felt252::from(2_u8), QUERY_VERSION_BASE_BIT); - let query_version = simulate_version_base + stark_felt_to_felt(version.0); - version = TransactionVersion(felt_to_stark_felt(&query_version)); + let simulate_version_base = Pow::pow(Felt::from(2_u8), QUERY_VERSION_BASE_BIT); + let query_version = simulate_version_base + version.0; + version = TransactionVersion(query_version); } - let tx_hash = TransactionHash(stark_felt!(1991_u16)); + let tx_hash = TransactionHash(felt!(1991_u16)); let max_fee = Fee(42); let nonce = nonce!(3_u16); let sender_address = test_contract_address; - let expected_tx_info: Vec; - let mut expected_resource_bounds: Vec = vec![]; + let expected_tx_info: Vec; + let mut expected_resource_bounds: Vec = vec![]; let tx_info: TransactionInfo; if version == TransactionVersion::ONE { expected_tx_info = vec![ - version.0, // Transaction version. - *sender_address.0.key(), // Account address. - stark_felt!(max_fee.0), // Max fee. - StarkFelt::ZERO, // Signature. - tx_hash.0, // Transaction hash. - stark_felt!(&*ChainId(CHAIN_ID_NAME.to_string()).as_hex()), // Chain ID. - nonce.0, // Nonce. + version.0, // Transaction version. + *sender_address.0.key(), // Account address. + felt!(max_fee.0), // Max fee. + Felt::ZERO, // Signature. + tx_hash.0, // Transaction hash. + felt!(&*ChainId::Other(CHAIN_ID_NAME.to_string()).as_hex()), // Chain ID. + nonce.0, // Nonce. ]; if !is_legacy { expected_resource_bounds = vec![ - stark_felt!(0_u16), // Length of resource bounds array. + felt!(0_u16), // Length of resource bounds array. ]; } tx_info = TransactionInfo::Deprecated(DeprecatedTransactionInfo { @@ -428,23 +426,23 @@ fn test_get_execution_info( let max_amount = Fee(13); let max_price_per_unit = Fee(61); expected_tx_info = vec![ - version.0, // Transaction version. - *sender_address.0.key(), // Account address. - StarkFelt::ZERO, // Max fee. - StarkFelt::ZERO, // Signature. - tx_hash.0, // Transaction hash. - stark_felt!(&*ChainId(CHAIN_ID_NAME.to_string()).as_hex()), // Chain ID. - nonce.0, // Nonce. + version.0, // Transaction version. + *sender_address.0.key(), // Account address. + Felt::ZERO, // Max fee. + Felt::ZERO, // Signature. + tx_hash.0, // Transaction hash. + felt!(&*ChainId::Other(CHAIN_ID_NAME.to_string()).as_hex()), // Chain ID. + nonce.0, // Nonce. ]; if !is_legacy { expected_resource_bounds = vec![ - StarkFelt::from(2u32), // Length of ResourceBounds array. - stark_felt!(L1_GAS), // Resource. - stark_felt!(max_amount.0), // Max amount. - stark_felt!(max_price_per_unit.0), // Max price per unit. - stark_felt!(L2_GAS), // Resource. - StarkFelt::ZERO, // Max amount. - StarkFelt::ZERO, // Max price per unit. + Felt::from(2u32), // Length of ResourceBounds array. + felt!(L1_GAS), // Resource. + felt!(max_amount.0), // Max amount. + felt!(max_price_per_unit.0), // Max price per unit. + felt!(L2_GAS), // Resource. + Felt::ZERO, // Max amount. + Felt::ZERO, // Max price per unit. ]; } tx_info = TransactionInfo::Current(CurrentTransactionInfo { @@ -481,9 +479,9 @@ fn test_get_execution_info( let entry_point_selector = selector_from_name("test_get_execution_info"); let expected_call_info = vec![ - stark_felt!(0_u16), // Caller address. - *test_contract_address.0.key(), // Storage address. - stark_felt!(entry_point_selector.0), // Entry point selector. + felt!(0_u16), // Caller address. + *test_contract_address.0.key(), // Storage address. + entry_point_selector.0, // Entry point selector. ]; let entry_point_call = CallEntryPoint { entry_point_selector, @@ -525,9 +523,9 @@ fn test_library_call() { let calldata = calldata![ test_contract.get_class_hash().0, // Class hash. inner_entry_point_selector.0, // Function selector. - stark_felt!(2_u8), // Calldata length. - stark_felt!(1234_u16), // Calldata: address. - stark_felt!(91_u8) // Calldata: value. + felt!(2_u8), // Calldata length. + felt!(1234_u16), // Calldata: address. + felt!(91_u8) // Calldata: value. ]; let entry_point_call = CallEntryPoint { entry_point_selector: selector_from_name("test_library_call"), @@ -539,7 +537,7 @@ fn test_library_call() { assert_eq!( entry_point_call.execute_directly(&mut state).unwrap().execution, CallExecution { - retdata: retdata![stark_felt!(91_u16)], + retdata: retdata![felt!(91_u16)], gas_consumed: REQUIRED_GAS_LIBRARY_CALL_TEST, ..Default::default() } @@ -555,9 +553,9 @@ fn test_library_call_assert_fails() { let calldata = calldata![ test_contract.get_class_hash().0, // Class hash. inner_entry_point_selector.0, // Function selector. - stark_felt!(2_u8), // Calldata length. - stark_felt!(0_u8), // Calldata: first assert value. - stark_felt!(1_u8) // Calldata: second assert value. + felt!(2_u8), // Calldata length. + felt!(0_u8), // Calldata: first assert value. + felt!(1_u8) // Calldata: second assert value. ]; let entry_point_call = CallEntryPoint { entry_point_selector: selector_from_name("test_library_call"), @@ -585,8 +583,8 @@ fn test_nested_library_call() { test_class_hash.0, // Class hash. outer_entry_point_selector.0, // Library call function selector. inner_entry_point_selector.0, // Storage function selector. - stark_felt!(key), // Calldata: address. - stark_felt!(value) // Calldata: value. + felt!(key), // Calldata: address. + felt!(value) // Calldata: value. ]; // Create expected call info tree. @@ -599,7 +597,7 @@ fn test_nested_library_call() { }; let nested_storage_entry_point = CallEntryPoint { entry_point_selector: inner_entry_point_selector, - calldata: calldata![stark_felt!(key + 1), stark_felt!(value + 1)], + calldata: calldata![felt!(key + 1), felt!(value + 1)], class_hash: Some(test_class_hash), code_address: None, call_type: CallType::Delegate, @@ -611,9 +609,9 @@ fn test_nested_library_call() { calldata: calldata![ test_class_hash.0, // Class hash. inner_entry_point_selector.0, // Storage function selector. - stark_felt!(2_u8), // Calldata: address. - stark_felt!(key + 1), // Calldata: address. - stark_felt!(value + 1) // Calldata: value. + felt!(2_u8), // Calldata: address. + felt!(key + 1), // Calldata: address. + felt!(value + 1) // Calldata: value. ], class_hash: Some(test_class_hash), code_address: None, @@ -622,24 +620,24 @@ fn test_nested_library_call() { ..trivial_external_entry_point_new(test_contract) }; let storage_entry_point = CallEntryPoint { - calldata: calldata![stark_felt!(key), stark_felt!(value)], + calldata: calldata![felt!(key), felt!(value)], initial_gas: 9999656870, ..nested_storage_entry_point }; let storage_entry_point_resources = ExecutionResources { n_steps: 243, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([(RANGE_CHECK_BUILTIN_NAME.to_string(), 7)]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, 7)]), }; let nested_storage_call_info = CallInfo { call: nested_storage_entry_point, execution: CallExecution { - retdata: retdata![stark_felt!(value + 1)], + retdata: retdata![felt!(value + 1)], gas_consumed: REQUIRED_GAS_STORAGE_READ_WRITE_TEST, ..CallExecution::default() }, resources: storage_entry_point_resources.clone(), - storage_read_values: vec![stark_felt!(value + 1)], + storage_read_values: vec![felt!(value + 1)], accessed_storage_keys: HashSet::from([storage_key!(key + 1)]), ..Default::default() }; @@ -647,12 +645,12 @@ fn test_nested_library_call() { + &ExecutionResources { n_steps: 388, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([(RANGE_CHECK_BUILTIN_NAME.to_string(), 15)]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, 15)]), }; let library_call_info = CallInfo { call: library_entry_point, execution: CallExecution { - retdata: retdata![stark_felt!(value + 1)], + retdata: retdata![felt!(value + 1)], gas_consumed: REQUIRED_GAS_LIBRARY_CALL_TEST, ..CallExecution::default() }, @@ -663,12 +661,12 @@ fn test_nested_library_call() { let storage_call_info = CallInfo { call: storage_entry_point, execution: CallExecution { - retdata: retdata![stark_felt!(value)], + retdata: retdata![felt!(value)], gas_consumed: REQUIRED_GAS_STORAGE_READ_WRITE_TEST, ..CallExecution::default() }, resources: storage_entry_point_resources, - storage_read_values: vec![stark_felt!(value)], + storage_read_values: vec![felt!(value)], accessed_storage_keys: HashSet::from([storage_key!(key)]), ..Default::default() }; @@ -677,12 +675,12 @@ fn test_nested_library_call() { + &ExecutionResources { n_steps: 749, n_memory_holes: 2, - builtin_instance_counter: HashMap::from([(RANGE_CHECK_BUILTIN_NAME.to_string(), 27)]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, 27)]), }; let expected_call_info = CallInfo { call: main_entry_point.clone(), execution: CallExecution { - retdata: retdata![stark_felt!(value)], + retdata: retdata![felt!(value)], gas_consumed: 276880, ..CallExecution::default() }, @@ -710,7 +708,7 @@ fn test_replace_class() { // Replace with undeclared class hash. let entry_point_call = CallEntryPoint { - calldata: calldata![stark_felt!(1234_u16)], + calldata: calldata![felt!(1234_u16)], entry_point_selector: selector_from_name("test_replace_class"), ..trivial_external_entry_point_new(test_contract) }; @@ -788,15 +786,15 @@ fn test_send_message_to_l1() { let chain_info = &ChainInfo::create_for_testing(); let mut state = test_state(chain_info, BALANCE, &[(test_contract, 1)]); - let to_address = stark_felt!(1234_u16); - let payload = vec![stark_felt!(2019_u16), stark_felt!(2020_u16), stark_felt!(2021_u16)]; + let to_address = felt!(1234_u16); + let payload = vec![felt!(2019_u16), felt!(2020_u16), felt!(2021_u16)]; let calldata = Calldata( [ vec![ to_address, // TODO(Ori, 1/2/2024): Write an indicative expect message explaining why the // convertion works. - stark_felt!(u64::try_from(payload.len()).expect("Failed to convert usize to u64.")), + felt!(u64::try_from(payload.len()).expect("Failed to convert usize to u64.")), ], payload.clone(), ] @@ -861,8 +859,8 @@ fn test_deploy( }; let constructor_calldata = if supply_constructor_calldata { vec![ - stark_felt!(1_u8), // Calldata: address. - stark_felt!(1_u8), // Calldata: value. + felt!(1_u8), // Calldata: address. + felt!(1_u8), // Calldata: value. ] } else { vec![] @@ -917,8 +915,8 @@ fn test_out_of_gas() { let chain_info = &ChainInfo::create_for_testing(); let mut state = test_state(chain_info, BALANCE, &[(test_contract, 1)]); - let key = stark_felt!(1234_u16); - let value = stark_felt!(18_u8); + let key = felt!(1234_u16); + let value = felt!(18_u8); let calldata = calldata![key, value]; let entry_point_call = CallEntryPoint { calldata, @@ -928,7 +926,7 @@ fn test_out_of_gas() { }; let error = entry_point_call.execute_directly(&mut state).unwrap_err(); assert_matches!(error, EntryPointExecutionError::ExecutionFailed{ error_data } - if error_data == vec![stark_felt!(OUT_OF_GAS_ERROR)]); + if error_data == vec![felt!(OUT_OF_GAS_ERROR)]); } #[test] @@ -944,7 +942,7 @@ fn test_syscall_failure_format() { "0x11", ] .into_iter() - .map(|x| StarkFelt::try_from(x).unwrap()) + .map(|x| Felt::from_hex(x).unwrap()) .collect(); let error = EntryPointExecutionError::ExecutionFailed { error_data }; assert_eq!(error.to_string(), "Execution failed. Failure reason: \"Execution failure\"."); diff --git a/crates/blockifier/src/fee/actual_cost_test.rs b/crates/blockifier/src/fee/actual_cost_test.rs index 620dec9dad..1db2f14c56 100644 --- a/crates/blockifier/src/fee/actual_cost_test.rs +++ b/crates/blockifier/src/fee/actual_cost_test.rs @@ -1,7 +1,6 @@ use rstest::{fixture, rstest}; -use starknet_api::hash::StarkFelt; -use starknet_api::stark_felt; use starknet_api::transaction::{L2ToL1Payload, ResourceBoundsMapping}; +use starknet_types_core::felt::Felt; use crate::context::BlockContext; use crate::execution::call_info::{CallExecution, CallInfo, MessageToL1, OrderedL2ToL1Message}; @@ -141,7 +140,7 @@ fn test_calculate_tx_gas_usage_basic<'a>(#[values(false, true)] use_kzg_da: bool let mut call_infos = Vec::new(); for i in 0..4 { - let payload_vec = vec![stark_felt!(0_u16); i]; + let payload_vec = vec![Felt::ZERO; i]; let call_info = CallInfo { execution: CallExecution { l2_to_l1_messages: vec![OrderedL2ToL1Message { @@ -338,8 +337,8 @@ fn test_calculate_tx_gas_usage( constants::TRANSFER_ENTRY_POINT_NAME, &[ *some_other_account_address.0.key(), // Calldata: recipient. - stark_felt!(2_u8), // Calldata: lsb amount. - stark_felt!(0_u8), // Calldata: msb amount. + Felt::TWO, // Calldata: lsb amount. + Felt::ZERO, // Calldata: msb amount. ], ); diff --git a/crates/blockifier/src/fee/fee_checks.rs b/crates/blockifier/src/fee/fee_checks.rs index b097ea675b..f613ec9848 100644 --- a/crates/blockifier/src/fee/fee_checks.rs +++ b/crates/blockifier/src/fee/fee_checks.rs @@ -1,5 +1,5 @@ -use starknet_api::hash::StarkFelt; use starknet_api::transaction::Fee; +use starknet_types_core::felt::Felt; use thiserror::Error; use crate::context::TransactionContext; @@ -22,7 +22,7 @@ pub enum FeeCheckError { "Insufficient fee token balance. Fee: {}, balance: low/high \ {balance_low}/{balance_high}.", fee.0 )] - InsufficientFeeTokenBalance { fee: Fee, balance_low: StarkFelt, balance_high: StarkFelt }, + InsufficientFeeTokenBalance { fee: Fee, balance_low: Felt, balance_high: Felt }, } /// This struct holds the result of fee checks: recommended fee to charge (useful in post-execution diff --git a/crates/blockifier/src/fee/fee_test.rs b/crates/blockifier/src/fee/fee_test.rs index 138ac0a9b6..9fa32a18cc 100644 --- a/crates/blockifier/src/fee/fee_test.rs +++ b/crates/blockifier/src/fee/fee_test.rs @@ -1,11 +1,7 @@ use std::collections::HashMap; -use std::panic::catch_unwind; use assert_matches::assert_matches; -use cairo_vm::vm::runners::builtin_runner::{ - BITWISE_BUILTIN_NAME, HASH_BUILTIN_NAME, POSEIDON_BUILTIN_NAME, RANGE_CHECK_BUILTIN_NAME, - SIGNATURE_BUILTIN_NAME, -}; +use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use rstest::rstest; use starknet_api::transaction::Fee; @@ -29,11 +25,11 @@ fn get_vm_resource_usage() -> ExecutionResources { n_steps: 10000, n_memory_holes: 0, builtin_instance_counter: HashMap::from([ - (HASH_BUILTIN_NAME.to_string(), 10), - (RANGE_CHECK_BUILTIN_NAME.to_string(), 24), - (SIGNATURE_BUILTIN_NAME.to_string(), 1), - (BITWISE_BUILTIN_NAME.to_string(), 1), - (POSEIDON_BUILTIN_NAME.to_string(), 1), + (BuiltinName::pedersen, 10), + (BuiltinName::range_check, 24), + (BuiltinName::ecdsa, 1), + (BuiltinName::bitwise, 1), + (BuiltinName::poseidon, 1), ]), } } @@ -60,30 +56,14 @@ fn test_simple_calculate_l1_gas_by_vm_usage() { // Another positive flow, this time the heaviest resource is range_check_builtin. let n_reverted_steps = 0; vm_resource_usage.n_steps = - vm_resource_usage.builtin_instance_counter.get(RANGE_CHECK_BUILTIN_NAME).unwrap() - 1; + vm_resource_usage.builtin_instance_counter.get(&BuiltinName::range_check).unwrap() - 1; let l1_gas_by_vm_usage = - vm_resource_usage.builtin_instance_counter.get(RANGE_CHECK_BUILTIN_NAME).unwrap(); + vm_resource_usage.builtin_instance_counter.get(&BuiltinName::range_check).unwrap(); assert_eq!( GasVector::from_l1_gas(u128_from_usize(*l1_gas_by_vm_usage)), calculate_l1_gas_by_vm_usage(&versioned_constants, &vm_resource_usage, n_reverted_steps) .unwrap() ); - - // Negative flow. - // Pass dict with extra key. - let mut invalid_vm_resource_usage = vm_resource_usage.clone(); - invalid_vm_resource_usage - .builtin_instance_counter - .insert(String::from("bad_resource_name"), 17); - - let should_panic = catch_unwind(|| { - calculate_l1_gas_by_vm_usage( - &versioned_constants, - &invalid_vm_resource_usage, - n_reverted_steps, - ) - }); - assert!(should_panic.is_err()); } #[test] @@ -107,13 +87,15 @@ fn test_float_calculate_l1_gas_by_vm_usage() { // Another positive flow, this time the heaviest resource is ecdsa_builtin. vm_resource_usage.n_steps = 200; - let l1_gas_by_vm_usage = - ((*versioned_constants.vm_resource_fee_cost().get(SIGNATURE_BUILTIN_NAME).unwrap()) - * u128_from_usize( - *vm_resource_usage.builtin_instance_counter.get(SIGNATURE_BUILTIN_NAME).unwrap(), - )) - .ceil() - .to_integer(); + let l1_gas_by_vm_usage = ((*versioned_constants + .vm_resource_fee_cost() + .get(BuiltinName::ecdsa.to_str_with_suffix()) + .unwrap()) + * u128_from_usize( + *vm_resource_usage.builtin_instance_counter.get(&BuiltinName::ecdsa).unwrap(), + )) + .ceil() + .to_integer(); assert_eq!( GasVector::from_l1_gas(l1_gas_by_vm_usage), diff --git a/crates/blockifier/src/fee/fee_utils.rs b/crates/blockifier/src/fee/fee_utils.rs index c6b0dfdec8..5f526cbbd0 100644 --- a/crates/blockifier/src/fee/fee_utils.rs +++ b/crates/blockifier/src/fee/fee_utils.rs @@ -3,9 +3,9 @@ use std::collections::HashSet; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use num_bigint::BigUint; use starknet_api::core::ContractAddress; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; use starknet_api::transaction::Fee; +use starknet_types_core::felt::Felt; use crate::abi::abi_utils::get_fee_token_var_address; use crate::abi::constants; @@ -34,7 +34,7 @@ pub fn calculate_l1_gas_by_vm_usage( ) -> TransactionFeeResult { // TODO(Yoni, 1/7/2024): rename vm -> cairo. let vm_resource_fee_costs = versioned_constants.vm_resource_fee_cost(); - let mut vm_resource_usage_for_fee = vm_resource_usage.prover_builtins(); + let mut vm_resource_usage_for_fee = vm_resource_usage.prover_builtins_by_name(); vm_resource_usage_for_fee.insert( constants::N_STEPS_RESOURCE.to_string(), vm_resource_usage.total_n_steps() + n_reverted_steps, @@ -81,7 +81,7 @@ pub fn get_balance_and_if_covers_fee( state: &mut dyn StateReader, tx_context: &TransactionContext, fee: Fee, -) -> TransactionFeeResult<(StarkFelt, StarkFelt, bool)> { +) -> TransactionFeeResult<(Felt, Felt, bool)> { let tx_info = &tx_context.tx_info; let (balance_low, balance_high) = state.get_fee_token_balance(tx_info.sender_address(), tx_context.fee_token_address())?; @@ -90,7 +90,7 @@ pub fn get_balance_and_if_covers_fee( balance_high, // TODO(Dori,1/10/2023): If/when fees can be more than 128 bit integers, this should be // updated. - balance_high > StarkFelt::from(0_u8) || balance_low >= StarkFelt::from(fee.0), + balance_high > Felt::from(0_u8) || balance_low >= Felt::from(fee.0), )) } @@ -146,8 +146,8 @@ pub fn get_address_balance_keys(address: ContractAddress) -> (StorageKey, Storag (balance_key_low, balance_key_high) } -pub(crate) fn balance_to_big_uint(balance_low: &StarkFelt, balance_high: &StarkFelt) -> BigUint { - let low = BigUint::from_bytes_be(balance_low.bytes()); - let high = BigUint::from_bytes_be(balance_high.bytes()); +pub(crate) fn balance_to_big_uint(balance_low: &Felt, balance_high: &Felt) -> BigUint { + let low = BigUint::from_bytes_be(&balance_low.to_bytes_be()); + let high = BigUint::from_bytes_be(&balance_high.to_bytes_be()); (high << 128) + low } diff --git a/crates/blockifier/src/fee/gas_usage_test.rs b/crates/blockifier/src/fee/gas_usage_test.rs index 2411dfa102..1f145c09dc 100644 --- a/crates/blockifier/src/fee/gas_usage_test.rs +++ b/crates/blockifier/src/fee/gas_usage_test.rs @@ -2,8 +2,8 @@ use std::num::NonZeroU128; use pretty_assertions::assert_eq; use rstest::{fixture, rstest}; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::{EventContent, EventData, EventKey, Fee}; +use starknet_types_core::felt::Felt; use crate::abi::constants; use crate::context::BlockContext; @@ -45,8 +45,8 @@ fn test_get_event_gas_cost( let create_event = |keys_size: usize, data_size: usize| OrderedEvent { order: 0, event: EventContent { - keys: vec![EventKey(StarkFelt::ZERO); keys_size], - data: EventData(vec![StarkFelt::ZERO; data_size]), + keys: vec![EventKey(Felt::ZERO); keys_size], + data: EventData(vec![Felt::ZERO; data_size]), }, }; let call_info_1 = CallInfo { diff --git a/crates/blockifier/src/state/cached_state.rs b/crates/blockifier/src/state/cached_state.rs index 1f7089a329..cd84f728d6 100644 --- a/crates/blockifier/src/state/cached_state.rs +++ b/crates/blockifier/src/state/cached_state.rs @@ -4,8 +4,8 @@ use std::collections::{HashMap, HashSet}; use derive_more::IntoIterator; use indexmap::IndexMap; use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; +use starknet_types_core::felt::Felt; use crate::abi::abi_utils::get_fee_token_var_address; use crate::context::TransactionContext; @@ -132,7 +132,7 @@ impl StateReader for CachedState { &self, contract_address: ContractAddress, key: StorageKey, - ) -> StateResult { + ) -> StateResult { let mut cache = self.cache.borrow_mut(); if cache.get_storage_at(contract_address, key).is_none() { @@ -187,7 +187,7 @@ impl StateReader for CachedState { cache.set_declared_contract_initial_values(class_hash, false); cache.set_compiled_class_hash_initial_value( class_hash, - CompiledClassHash(StarkFelt::ZERO), + CompiledClassHash(Felt::ZERO), ); Err(StateError::UndeclaredClassHash(class_hash))?; } @@ -227,7 +227,7 @@ impl State for CachedState { &mut self, contract_address: ContractAddress, key: StorageKey, - value: StarkFelt, + value: Felt, ) -> StateResult<()> { self.cache.get_mut().set_storage_value(contract_address, key, value); @@ -236,12 +236,7 @@ impl State for CachedState { fn increment_nonce(&mut self, contract_address: ContractAddress) -> StateResult<()> { let current_nonce = self.get_nonce_at(contract_address)?; - // TODO(Ori, 1/2/2024): Write an indicative expect message explaining why the conversion - // works. - let current_nonce_as_u64: u64 = - usize::try_from(current_nonce.0)?.try_into().expect("Failed to convert usize to u64."); - let next_nonce_val = 1_u64 + current_nonce_as_u64; - let next_nonce = Nonce(StarkFelt::from(next_nonce_val)); + let next_nonce = Nonce(current_nonce.0 + Felt::ONE); self.cache.get_mut().set_nonce_value(contract_address, next_nonce); Ok(()) @@ -300,10 +295,10 @@ impl Default for CachedState); +pub struct StorageView(pub HashMap); /// Converts a `CachedState`'s storage mapping into a `StateDiff`'s storage mapping. -impl From for IndexMap> { +impl From for IndexMap> { fn from(storage_view: StorageView) -> Self { let mut storage_updates = Self::new(); for ((address, key), value) in storage_view.into_iter() { @@ -324,7 +319,7 @@ impl From for IndexMap, pub class_hashes: HashMap, - pub storage: HashMap, + pub storage: HashMap, pub compiled_class_hashes: HashMap, pub declared_contracts: HashMap, } @@ -386,11 +381,7 @@ impl StateCache { self.initial_reads.declared_contracts.insert(class_hash, is_declared); } - fn get_storage_at( - &self, - contract_address: ContractAddress, - key: StorageKey, - ) -> Option<&StarkFelt> { + fn get_storage_at(&self, contract_address: ContractAddress, key: StorageKey) -> Option<&Felt> { let contract_storage_key = (contract_address, key); self.writes .storage @@ -409,7 +400,7 @@ impl StateCache { &mut self, contract_address: ContractAddress, key: StorageKey, - value: StarkFelt, + value: Felt, ) { let contract_storage_key = (contract_address, key); self.initial_reads.storage.insert(contract_storage_key, value); @@ -419,7 +410,7 @@ impl StateCache { &mut self, contract_address: ContractAddress, key: StorageKey, - value: StarkFelt, + value: Felt, ) { let contract_storage_key = (contract_address, key); self.writes.storage.insert(contract_storage_key, value); @@ -492,7 +483,7 @@ impl<'a, S: StateReader + ?Sized> StateReader for MutRefState<'a, S> { &self, contract_address: ContractAddress, key: StorageKey, - ) -> StateResult { + ) -> StateResult { self.0.get_storage_at(contract_address, key) } @@ -542,7 +533,7 @@ impl<'a, U: UpdatableState> TransactionalState<'a, U> { } } -type StorageDiff = IndexMap>; +type StorageDiff = IndexMap>; /// Holds uncommitted changes induced on Starknet contracts. #[cfg_attr(any(feature = "testing", test), derive(Clone))] @@ -551,7 +542,7 @@ pub struct CommitmentStateDiff { // Contract instance attributes (per address). pub address_to_class_hash: IndexMap, pub address_to_nonce: IndexMap, - pub storage_updates: IndexMap>, + pub storage_updates: IndexMap>, // Global attributes. pub class_hash_to_compiled_class_hash: IndexMap, diff --git a/crates/blockifier/src/state/cached_state_test.rs b/crates/blockifier/src/state/cached_state_test.rs index 4fa45f204e..37c8e72ba5 100644 --- a/crates/blockifier/src/state/cached_state_test.rs +++ b/crates/blockifier/src/state/cached_state_test.rs @@ -5,8 +5,7 @@ use indexmap::indexmap; use pretty_assertions::assert_eq; use rstest::rstest; use starknet_api::core::PatriciaKey; -use starknet_api::hash::StarkHash; -use starknet_api::{class_hash, contract_address, patricia_key, stark_felt}; +use starknet_api::{class_hash, contract_address, felt, patricia_key}; use crate::context::{BlockContext, ChainInfo}; use crate::state::cached_state::*; @@ -22,7 +21,7 @@ fn set_initial_state_values( class_hash_to_class: ContractClassMapping, nonce_initial_values: HashMap, class_hash_initial_values: HashMap, - storage_initial_values: HashMap, + storage_initial_values: HashMap, ) { assert!(*state.cache.borrow() == StateCache::default(), "Cache already initialized."); @@ -36,19 +35,19 @@ fn set_initial_state_values( fn get_uninitialized_storage_value() { let state: CachedState = CachedState::default(); let contract_address = contract_address!("0x1"); - let key = storage_key!("0x10"); + let key = storage_key!(0x10_u16); - assert_eq!(state.get_storage_at(contract_address, key).unwrap(), StarkFelt::default()); + assert_eq!(state.get_storage_at(contract_address, key).unwrap(), Felt::default()); } #[test] fn get_and_set_storage_value() { let contract_address0 = contract_address!("0x100"); let contract_address1 = contract_address!("0x200"); - let key0 = storage_key!("0x10"); - let key1 = storage_key!("0x20"); - let storage_val0: StarkFelt = stark_felt!("0x1"); - let storage_val1: StarkFelt = stark_felt!("0x5"); + let key0 = storage_key!(0x10_u16); + let key1 = storage_key!(0x20_u16); + let storage_val0: Felt = felt!("0x1"); + let storage_val1: Felt = felt!("0x5"); let mut state = CachedState::from(DictStateReader { storage_view: HashMap::from([ @@ -60,12 +59,12 @@ fn get_and_set_storage_value() { assert_eq!(state.get_storage_at(contract_address0, key0).unwrap(), storage_val0); assert_eq!(state.get_storage_at(contract_address1, key1).unwrap(), storage_val1); - let modified_storage_value0 = stark_felt!("0xA"); + let modified_storage_value0 = felt!("0xA"); state.set_storage_at(contract_address0, key0, modified_storage_value0).unwrap(); assert_eq!(state.get_storage_at(contract_address0, key0).unwrap(), modified_storage_value0); assert_eq!(state.get_storage_at(contract_address1, key1).unwrap(), storage_val1); - let modified_storage_value1 = stark_felt!("0x7"); + let modified_storage_value1 = felt!("0x7"); state.set_storage_at(contract_address1, key1, modified_storage_value1).unwrap(); assert_eq!(state.get_storage_at(contract_address0, key0).unwrap(), modified_storage_value0); assert_eq!(state.get_storage_at(contract_address1, key1).unwrap(), modified_storage_value1); @@ -73,16 +72,16 @@ fn get_and_set_storage_value() { #[test] fn cast_between_storage_mapping_types() { - let empty_map: IndexMap> = IndexMap::default(); + let empty_map: IndexMap> = IndexMap::default(); assert_eq!(empty_map, IndexMap::from(StorageView::default())); let contract_address0 = contract_address!("0x100"); let contract_address1 = contract_address!("0x200"); - let key0 = storage_key!("0x10"); - let key1 = storage_key!("0x20"); - let storage_val0: StarkFelt = stark_felt!("0x1"); - let storage_val1: StarkFelt = stark_felt!("0x5"); - let storage_val2: StarkFelt = stark_felt!("0xa"); + let key0 = storage_key!(0x10_u16); + let key1 = storage_key!(0x20_u16); + let storage_val0: Felt = felt!("0x1"); + let storage_val1: Felt = felt!("0x5"); + let storage_val2: Felt = felt!("0xa"); let storage_map = StorageView(HashMap::from([ ((contract_address0, key0), storage_val0), @@ -134,7 +133,7 @@ fn declare_contract() { fn get_and_increment_nonce() { let contract_address1 = contract_address!("0x100"); let contract_address2 = contract_address!("0x200"); - let initial_nonce = nonce!("0x1"); + let initial_nonce = Nonce(felt!(1_u8)); let mut state = CachedState::from(DictStateReader { address_to_nonce: HashMap::from([ @@ -147,17 +146,17 @@ fn get_and_increment_nonce() { assert_eq!(state.get_nonce_at(contract_address2).unwrap(), initial_nonce); assert!(state.increment_nonce(contract_address1).is_ok()); - let nonce1_plus_one = nonce!("0x2"); + let nonce1_plus_one = Nonce(felt!(2_u8)); assert_eq!(state.get_nonce_at(contract_address1).unwrap(), nonce1_plus_one); assert_eq!(state.get_nonce_at(contract_address2).unwrap(), initial_nonce); assert!(state.increment_nonce(contract_address1).is_ok()); - let nonce1_plus_two = nonce!("0x3"); + let nonce1_plus_two = Nonce(felt!(3_u8)); assert_eq!(state.get_nonce_at(contract_address1).unwrap(), nonce1_plus_two); assert_eq!(state.get_nonce_at(contract_address2).unwrap(), initial_nonce); assert!(state.increment_nonce(contract_address2).is_ok()); - let nonce2_plus_one = nonce!("0x2"); + let nonce2_plus_one = Nonce(felt!(2_u8)); assert_eq!(state.get_nonce_at(contract_address1).unwrap(), nonce1_plus_two); assert_eq!(state.get_nonce_at(contract_address2).unwrap(), nonce2_plus_one); } @@ -232,11 +231,11 @@ fn cached_state_state_diff_conversion() { // key_x will not be changed. // key_y will be changed, but only with contract_address2 the value ends up being different, so // should only appear with contract_address2. - let key_x = storage_key!("0x10"); - let key_y = storage_key!("0x20"); - let storage_val0: StarkFelt = stark_felt!("0x1"); - let storage_val1: StarkFelt = stark_felt!("0x5"); - let storage_val2: StarkFelt = stark_felt!("0x6"); + let key_x = storage_key!(0x10_u16); + let key_y = storage_key!(0x20_u16); + let storage_val0: Felt = felt!("0x1"); + let storage_val1: Felt = felt!("0x5"); + let storage_val2: Felt = felt!("0x6"); let storage_initial_values = HashMap::from([ ((contract_address0, key_x), storage_val0), ((contract_address1, key_y), storage_val1), @@ -269,7 +268,7 @@ fn cached_state_state_diff_conversion() { state.set_storage_at(contract_address1, key_y, storage_val1).unwrap(); // Write new values using key contract_address2. - let new_value = stark_felt!("0x12345678"); + let new_value = felt!("0x12345678"); state.set_storage_at(contract_address2, key_y, new_value).unwrap(); assert!(state.increment_nonce(contract_address2).is_ok()); let new_class_hash = class_hash!("0x11111111"); @@ -298,9 +297,9 @@ fn create_state_changes_for_test( let contract_address = contract_address!(CONTRACT_ADDRESS); let contract_address2 = contract_address!("0x101"); let class_hash = class_hash!("0x10"); - let compiled_class_hash = compiled_class_hash!("0x11"); - let key = storage_key!("0x10"); - let storage_val: StarkFelt = stark_felt!("0x1"); + let compiled_class_hash = compiled_class_hash!(0x11_u16); + let key = storage_key!(0x10_u16); + let storage_val: Felt = felt!("0x1"); // Fill the initial read value, as in regular flow. state.get_class_hash_at(contract_address).unwrap(); @@ -315,14 +314,14 @@ fn create_state_changes_for_test( // Assign the existing value to the storage (this shouldn't be considered a change). // As the first access: - state.set_storage_at(contract_address2, key, StarkFelt::default()).unwrap(); + state.set_storage_at(contract_address2, key, Felt::default()).unwrap(); // As the second access: state.set_storage_at(contract_address, key, storage_val).unwrap(); if let Some(sender_address) = sender_address { // Charge fee from the sender. let sender_balance_key = get_fee_token_var_address(sender_address); - state.set_storage_at(fee_token_address, sender_balance_key, stark_felt!("0x1999")).unwrap(); + state.set_storage_at(fee_token_address, sender_balance_key, felt!("0x1999")).unwrap(); } state.get_actual_state_changes().unwrap() @@ -387,11 +386,9 @@ fn test_state_changes_merge( let new_contract_address = ContractAddress(patricia_key!("0x111")); // Overwrite existing and new storage values. + transactional_state.set_storage_at(contract_address, storage_key, felt!("0x1234")).unwrap(); transactional_state - .set_storage_at(contract_address, storage_key, stark_felt!("0x1234")) - .unwrap(); - transactional_state - .set_storage_at(new_contract_address, storage_key, stark_felt!("0x43210")) + .set_storage_at(new_contract_address, storage_key, felt!("0x43210")) .unwrap(); transactional_state.increment_nonce(contract_address).unwrap(); // Get the new state changes and then commit the transactional state. @@ -441,7 +438,7 @@ fn test_cache_get_write_keys() { assert_eq!(StateChanges::default().into_keys(), StateChangesKeys::default()); // Interesting case. - let some_felt = stark_felt!("0x1"); + let some_felt = felt!("0x1"); let some_class_hash = class_hash!("0x1"); let contract_address0 = contract_address!("0x200"); @@ -458,11 +455,11 @@ fn test_cache_get_write_keys() { (contract_address2, some_class_hash), ]), storage: HashMap::from([ - ((contract_address1, storage_key!("0x300")), some_felt), - ((contract_address1, storage_key!("0x600")), some_felt), - ((contract_address3, storage_key!("0x600")), some_felt), + ((contract_address1, storage_key!(0x300_u16)), some_felt), + ((contract_address1, storage_key!(0x600_u16)), some_felt), + ((contract_address3, storage_key!(0x600_u16)), some_felt), ]), - compiled_class_hashes: HashMap::from([(class_hash0, compiled_class_hash!("0x3"))]), + compiled_class_hashes: HashMap::from([(class_hash0, compiled_class_hash!(0x3_u16))]), declared_contracts: HashMap::default(), }); @@ -470,9 +467,9 @@ fn test_cache_get_write_keys() { nonce_keys: HashSet::from([contract_address0]), class_hash_keys: HashSet::from([contract_address1, contract_address2]), storage_keys: HashSet::from([ - (contract_address1, storage_key!("0x300")), - (contract_address1, storage_key!("0x600")), - (contract_address3, storage_key!("0x600")), + (contract_address1, storage_key!(0x300_u16)), + (contract_address1, storage_key!(0x600_u16)), + (contract_address3, storage_key!(0x600_u16)), ]), compiled_class_hash_keys: HashSet::from([class_hash0]), modified_contracts: HashSet::from([ @@ -501,8 +498,8 @@ fn test_state_changes_keys() { nonce_keys: HashSet::from([contract_address0]), class_hash_keys: HashSet::from([contract_address1]), storage_keys: HashSet::from([ - (contract_address2, storage_key!("0x300")), - (contract_address2, storage_key!("0x200")), + (contract_address2, storage_key!(0x300_u16)), + (contract_address2, storage_key!(0x200_u16)), ]), compiled_class_hash_keys: HashSet::from([class_hash0, class_hash1]), modified_contracts: HashSet::from([contract_address1, contract_address2]), @@ -535,7 +532,7 @@ fn test_state_changes_keys() { let mut keys1 = StateChangesKeys { nonce_keys: HashSet::from([contract_address1]), class_hash_keys: HashSet::from([contract_address1, contract_address2]), - storage_keys: HashSet::from([(contract_address2, storage_key!("0x300"))]), + storage_keys: HashSet::from([(contract_address2, storage_key!(0x300_u16))]), compiled_class_hash_keys: HashSet::from([class_hash0]), modified_contracts: HashSet::from([contract_address1, contract_address3]), }; @@ -545,7 +542,7 @@ fn test_state_changes_keys() { StateChangesKeys { nonce_keys: HashSet::from([contract_address0]), class_hash_keys: HashSet::new(), - storage_keys: HashSet::from([(contract_address2, storage_key!("0x200"),)]), + storage_keys: HashSet::from([(contract_address2, storage_key!(0x200_u16),)]), compiled_class_hash_keys: HashSet::from([class_hash1]), modified_contracts: HashSet::from([contract_address2]), } @@ -571,8 +568,8 @@ fn test_state_changes_keys() { nonce_keys: HashSet::from([contract_address0, contract_address1]), class_hash_keys: HashSet::from([contract_address1, contract_address2]), storage_keys: HashSet::from([ - (contract_address2, storage_key!("0x300")), - (contract_address2, storage_key!("0x200")), + (contract_address2, storage_key!(0x300_u16)), + (contract_address2, storage_key!(0x200_u16)), ]), compiled_class_hash_keys: HashSet::from([class_hash0, class_hash1]), modified_contracts: HashSet::from([ @@ -587,11 +584,11 @@ fn test_state_changes_keys() { #[rstest] fn test_state_maps() { let contract_address1 = contract_address!("0x101"); - let storage_key1 = storage_key!("0x102"); + let storage_key1 = storage_key!(0x102_u16); let class_hash1 = class_hash!("0x103"); - let nonce1 = nonce!("0x104"); - let compiled_class_hash1 = compiled_class_hash!("0x105"); - let some_felt1 = stark_felt!("0x106"); + let nonce1 = Nonce(felt!(0x104_u16)); + let compiled_class_hash1 = compiled_class_hash!(0x105_u16); + let some_felt1 = felt!("0x106"); let maps = StateMaps { nonces: HashMap::from([(contract_address1, nonce1)]), class_hashes: HashMap::from([(contract_address1, class_hash1)]), diff --git a/crates/blockifier/src/state/errors.rs b/crates/blockifier/src/state/errors.rs index 7a908f7381..c098c4edc6 100644 --- a/crates/blockifier/src/state/errors.rs +++ b/crates/blockifier/src/state/errors.rs @@ -1,4 +1,5 @@ use cairo_vm::types::errors::program_errors::ProgramError; +use num_bigint::{BigUint, TryFromBigIntError}; use starknet_api::core::{ClassHash, ContractAddress}; use starknet_api::StarknetApiError; use thiserror::Error; @@ -7,6 +8,8 @@ use crate::abi::constants; #[derive(Debug, Error)] pub enum StateError { + #[error(transparent)] + FromBigUint(#[from] TryFromBigIntError), #[error( "A block hash must be provided for block number > {}.", constants::STORED_BLOCK_HASH_BUFFER diff --git a/crates/blockifier/src/state/state_api.rs b/crates/blockifier/src/state/state_api.rs index 23e6ba8117..38096fdcd8 100644 --- a/crates/blockifier/src/state/state_api.rs +++ b/crates/blockifier/src/state/state_api.rs @@ -1,8 +1,8 @@ use std::collections::{HashMap, HashSet}; use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; +use starknet_types_core::felt::Felt; use super::cached_state::{ContractClassMapping, StateMaps}; use crate::abi::abi_utils::get_fee_token_var_address; @@ -30,7 +30,7 @@ pub trait StateReader { &self, contract_address: ContractAddress, key: StorageKey, - ) -> StateResult; + ) -> StateResult; /// Returns the nonce of the given contract instance. /// Default: 0 for an uninitialized contract address. @@ -55,7 +55,7 @@ pub trait StateReader { &mut self, contract_address: ContractAddress, fee_token_address: ContractAddress, - ) -> Result<(StarkFelt, StarkFelt), StateError> { + ) -> Result<(Felt, Felt), StateError> { let low_key = get_fee_token_var_address(contract_address); let high_key = next_storage_key(&low_key)?; let low = self.get_storage_at(fee_token_address, low_key)?; @@ -75,7 +75,7 @@ pub trait State: StateReader { &mut self, contract_address: ContractAddress, key: StorageKey, - value: StarkFelt, + value: Felt, ) -> StateResult<()>; /// Increments the nonce of the given contract instance. diff --git a/crates/blockifier/src/test_utils.rs b/crates/blockifier/src/test_utils.rs index bad3b34262..2c175af604 100644 --- a/crates/blockifier/src/test_utils.rs +++ b/crates/blockifier/src/test_utils.rs @@ -11,22 +11,19 @@ use std::collections::HashMap; use std::fs; use std::path::PathBuf; -use cairo_felt::Felt252; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; -use num_traits::{One, Zero}; use starknet_api::core::{ClassHash, ContractAddress, Nonce, PatriciaKey}; -use starknet_api::hash::{StarkFelt, StarkHash}; use starknet_api::state::StorageKey; use starknet_api::transaction::{ Calldata, ContractAddressSalt, Resource, ResourceBounds, ResourceBoundsMapping, TransactionVersion, }; -use starknet_api::{contract_address, patricia_key, stark_felt}; +use starknet_api::{contract_address, felt, patricia_key}; +use starknet_types_core::felt::Felt; use crate::abi::abi_utils::{get_fee_token_var_address, selector_from_name}; use crate::execution::deprecated_syscalls::hint_processor::SyscallCounter; use crate::execution::entry_point::CallEntryPoint; -use crate::execution::execution_utils::felt_to_stark_felt; use crate::execution::syscalls::SyscallSelector; use crate::state::cached_state::StateChangesCount; use crate::test_utils::contracts::FeatureContract; @@ -65,11 +62,14 @@ impl Default for CairoVersion { impl CairoVersion { // A declare transaction of the given version, can be used to declare contracts of the returned // cairo version. + // TODO: Make TransactionVersion an enum and use match here. pub fn from_declare_tx_version(tx_version: TransactionVersion) -> Self { - match tx_version { - TransactionVersion::ZERO | TransactionVersion::ONE => CairoVersion::Cairo0, - TransactionVersion::TWO | TransactionVersion::THREE => CairoVersion::Cairo1, - _ => panic!("Transaction version {:?} is not supported.", tx_version), + if tx_version == TransactionVersion::ZERO || tx_version == TransactionVersion::ONE { + CairoVersion::Cairo0 + } else if tx_version == TransactionVersion::TWO || tx_version == TransactionVersion::THREE { + CairoVersion::Cairo1 + } else { + panic!("Transaction version {:?} is not supported.", tx_version) } } @@ -115,23 +115,20 @@ pub const CHAIN_ID_NAME: &str = "SN_GOERLI"; #[derive(Default)] pub struct NonceManager { - next_nonce: HashMap, + next_nonce: HashMap, } impl NonceManager { pub fn next(&mut self, account_address: ContractAddress) -> Nonce { - let zero = Felt252::zero(); - let next_felt252 = self.next_nonce.get(&account_address).unwrap_or(&zero); - let next = Nonce(felt_to_stark_felt(next_felt252)); - self.next_nonce.insert(account_address, Felt252::one() + next_felt252); - next + let next = self.next_nonce.remove(&account_address).unwrap_or_default(); + self.next_nonce.insert(account_address, next + 1); + Nonce(next) } /// Decrements the nonce of the account, unless it is zero. pub fn rollback(&mut self, account_address: ContractAddress) { - let zero = Felt252::zero(); - let current = self.next_nonce.get(&account_address).unwrap_or(&zero); - if !current.is_zero() { + let current = *self.next_nonce.get(&account_address).unwrap_or(&Felt::default()); + if current != Felt::ZERO { self.next_nonce.insert(account_address, current - 1); } } @@ -142,7 +139,7 @@ impl NonceManager { #[macro_export] macro_rules! nonce { ($s:expr) => { - starknet_api::core::Nonce(starknet_api::hash::StarkHash::try_from($s).unwrap()) + starknet_api::core::Nonce(starknet_types_core::felt::Felt::from($s)) }; } @@ -161,7 +158,7 @@ macro_rules! storage_key { #[macro_export] macro_rules! compiled_class_hash { ($s:expr) => { - starknet_api::core::CompiledClassHash(starknet_api::hash::StarkHash::try_from($s).unwrap()) + starknet_api::core::CompiledClassHash(starknet_types_core::felt::Felt::from($s)) }; } @@ -172,7 +169,7 @@ pub struct SaltManager { impl SaltManager { pub fn next_salt(&mut self) -> ContractAddressSalt { - let next_contract_address_salt = ContractAddressSalt(stark_felt!(self.next_salt)); + let next_contract_address_salt = ContractAddressSalt(felt!(self.next_salt)); self.next_salt += 1; next_contract_address_salt } @@ -369,7 +366,7 @@ pub fn get_tx_resources(tx_type: TransactionType) -> ExecutionResources { /// ] pub fn calldata_for_deploy_test( class_hash: ClassHash, - constructor_calldata: &[StarkFelt], + constructor_calldata: &[Felt], valid_deploy_from_zero: bool, ) -> Calldata { Calldata( @@ -377,10 +374,10 @@ pub fn calldata_for_deploy_test( vec![ class_hash.0, ContractAddressSalt::default().0, - stark_felt!(u128_from_usize(constructor_calldata.len())), + felt!(u128_from_usize(constructor_calldata.len())), ], constructor_calldata.into(), - vec![stark_felt!(if valid_deploy_from_zero { 0_u8 } else { 2_u8 })], + vec![felt!(if valid_deploy_from_zero { 0_u8 } else { 2_u8 })], ] .concat() .into(), @@ -401,14 +398,14 @@ pub fn calldata_for_deploy_test( pub fn create_calldata( contract_address: ContractAddress, entry_point_name: &str, - entry_point_args: &[StarkFelt], + entry_point_args: &[Felt], ) -> Calldata { Calldata( [ vec![ *contract_address.0.key(), // Contract address. selector_from_name(entry_point_name).0, // EP selector name. - stark_felt!(u128_from_usize(entry_point_args.len())), + felt!(u128_from_usize(entry_point_args.len())), ], entry_point_args.into(), ] @@ -422,7 +419,7 @@ pub fn create_trivial_calldata(test_contract_address: ContractAddress) -> Callda create_calldata( test_contract_address, "return_result", - &[stark_felt!(2_u8)], // Calldata: num. + &[felt!(2_u8)], // Calldata: num. ) } diff --git a/crates/blockifier/src/test_utils/contracts.rs b/crates/blockifier/src/test_utils/contracts.rs index 5521c207bd..ae32cfdcf4 100644 --- a/crates/blockifier/src/test_utils/contracts.rs +++ b/crates/blockifier/src/test_utils/contracts.rs @@ -4,8 +4,8 @@ use starknet_api::core::{ use starknet_api::deprecated_contract_class::{ ContractClass as DeprecatedContractClass, EntryPointOffset, EntryPointType, }; -use starknet_api::hash::{StarkFelt, StarkHash}; -use starknet_api::{class_hash, contract_address, patricia_key, stark_felt}; +use starknet_api::{class_hash, contract_address, felt, patricia_key}; +use starknet_types_core::felt::Felt; use strum::IntoEnumIterator; use strum_macros::EnumIter; @@ -175,8 +175,8 @@ impl FeatureContract { pub fn get_compiled_class_hash(&self) -> CompiledClassHash { match self.cairo_version() { - CairoVersion::Cairo0 => CompiledClassHash(StarkFelt::ZERO), - CairoVersion::Cairo1 => CompiledClassHash(stark_felt!(self.get_integer_base())), + CairoVersion::Cairo0 => CompiledClassHash(Felt::ZERO), + CairoVersion::Cairo1 => CompiledClassHash(felt!(self.get_integer_base())), } } diff --git a/crates/blockifier/src/test_utils/declare.rs b/crates/blockifier/src/test_utils/declare.rs index 9d51db6319..11e73cbc2b 100644 --- a/crates/blockifier/src/test_utils/declare.rs +++ b/crates/blockifier/src/test_utils/declare.rs @@ -70,51 +70,48 @@ macro_rules! declare_tx_args { pub fn declare_tx(declare_tx_args: DeclareTxArgs, class_info: ClassInfo) -> AccountTransaction { AccountTransaction::Declare( DeclareTransaction::new( - match declare_tx_args.version { - TransactionVersion::ZERO => { - starknet_api::transaction::DeclareTransaction::V0(DeclareTransactionV0V1 { - max_fee: declare_tx_args.max_fee, - signature: declare_tx_args.signature, - sender_address: declare_tx_args.sender_address, - nonce: declare_tx_args.nonce, - class_hash: declare_tx_args.class_hash, - }) - } - TransactionVersion::ONE => { - starknet_api::transaction::DeclareTransaction::V1(DeclareTransactionV0V1 { - max_fee: declare_tx_args.max_fee, - signature: declare_tx_args.signature, - sender_address: declare_tx_args.sender_address, - nonce: declare_tx_args.nonce, - class_hash: declare_tx_args.class_hash, - }) - } - TransactionVersion::TWO => { - starknet_api::transaction::DeclareTransaction::V2(DeclareTransactionV2 { - max_fee: declare_tx_args.max_fee, - signature: declare_tx_args.signature, - sender_address: declare_tx_args.sender_address, - nonce: declare_tx_args.nonce, - class_hash: declare_tx_args.class_hash, - compiled_class_hash: declare_tx_args.compiled_class_hash, - }) - } - TransactionVersion::THREE => { - starknet_api::transaction::DeclareTransaction::V3(DeclareTransactionV3 { - signature: declare_tx_args.signature, - sender_address: declare_tx_args.sender_address, - resource_bounds: declare_tx_args.resource_bounds, - tip: declare_tx_args.tip, - nonce_data_availability_mode: declare_tx_args.nonce_data_availability_mode, - fee_data_availability_mode: declare_tx_args.fee_data_availability_mode, - paymaster_data: declare_tx_args.paymaster_data, - account_deployment_data: declare_tx_args.account_deployment_data, - nonce: declare_tx_args.nonce, - class_hash: declare_tx_args.class_hash, - compiled_class_hash: declare_tx_args.compiled_class_hash, - }) - } - version => panic!("Unsupported transaction version: {:?}.", version), + // TODO: Make TransactionVersion an enum and use match here. + if declare_tx_args.version == TransactionVersion::ZERO { + starknet_api::transaction::DeclareTransaction::V0(DeclareTransactionV0V1 { + max_fee: declare_tx_args.max_fee, + signature: declare_tx_args.signature, + sender_address: declare_tx_args.sender_address, + nonce: declare_tx_args.nonce, + class_hash: declare_tx_args.class_hash, + }) + } else if declare_tx_args.version == TransactionVersion::ONE { + starknet_api::transaction::DeclareTransaction::V1(DeclareTransactionV0V1 { + max_fee: declare_tx_args.max_fee, + signature: declare_tx_args.signature, + sender_address: declare_tx_args.sender_address, + nonce: declare_tx_args.nonce, + class_hash: declare_tx_args.class_hash, + }) + } else if declare_tx_args.version == TransactionVersion::TWO { + starknet_api::transaction::DeclareTransaction::V2(DeclareTransactionV2 { + max_fee: declare_tx_args.max_fee, + signature: declare_tx_args.signature, + sender_address: declare_tx_args.sender_address, + nonce: declare_tx_args.nonce, + class_hash: declare_tx_args.class_hash, + compiled_class_hash: declare_tx_args.compiled_class_hash, + }) + } else if declare_tx_args.version == TransactionVersion::THREE { + starknet_api::transaction::DeclareTransaction::V3(DeclareTransactionV3 { + signature: declare_tx_args.signature, + sender_address: declare_tx_args.sender_address, + resource_bounds: declare_tx_args.resource_bounds, + tip: declare_tx_args.tip, + nonce_data_availability_mode: declare_tx_args.nonce_data_availability_mode, + fee_data_availability_mode: declare_tx_args.fee_data_availability_mode, + paymaster_data: declare_tx_args.paymaster_data, + account_deployment_data: declare_tx_args.account_deployment_data, + nonce: declare_tx_args.nonce, + class_hash: declare_tx_args.class_hash, + compiled_class_hash: declare_tx_args.compiled_class_hash, + }) + } else { + panic!("Unsupported transaction version: {:?}.", declare_tx_args.version) }, declare_tx_args.tx_hash, class_info, diff --git a/crates/blockifier/src/test_utils/deploy_account.rs b/crates/blockifier/src/test_utils/deploy_account.rs index 391d233425..d6ce95195d 100644 --- a/crates/blockifier/src/test_utils/deploy_account.rs +++ b/crates/blockifier/src/test_utils/deploy_account.rs @@ -76,32 +76,31 @@ pub fn deploy_account_tx( ) .unwrap(); - let tx = match deploy_tx_args.version { - TransactionVersion::ONE => { - starknet_api::transaction::DeployAccountTransaction::V1(DeployAccountTransactionV1 { - max_fee: deploy_tx_args.max_fee, - signature: deploy_tx_args.signature, - nonce: nonce_manager.next(contract_address), - class_hash: deploy_tx_args.class_hash, - contract_address_salt: deploy_tx_args.contract_address_salt, - constructor_calldata: deploy_tx_args.constructor_calldata, - }) - } - TransactionVersion::THREE => { - starknet_api::transaction::DeployAccountTransaction::V3(DeployAccountTransactionV3 { - signature: deploy_tx_args.signature, - resource_bounds: deploy_tx_args.resource_bounds, - tip: deploy_tx_args.tip, - nonce_data_availability_mode: deploy_tx_args.nonce_data_availability_mode, - fee_data_availability_mode: deploy_tx_args.fee_data_availability_mode, - paymaster_data: deploy_tx_args.paymaster_data, - nonce: nonce_manager.next(contract_address), - class_hash: deploy_tx_args.class_hash, - contract_address_salt: deploy_tx_args.contract_address_salt, - constructor_calldata: deploy_tx_args.constructor_calldata, - }) - } - version => panic!("Unsupported transaction version: {:?}.", version), + // TODO: Make TransactionVersion an enum and use match here. + let tx = if deploy_tx_args.version == TransactionVersion::ONE { + starknet_api::transaction::DeployAccountTransaction::V1(DeployAccountTransactionV1 { + max_fee: deploy_tx_args.max_fee, + signature: deploy_tx_args.signature, + nonce: nonce_manager.next(contract_address), + class_hash: deploy_tx_args.class_hash, + contract_address_salt: deploy_tx_args.contract_address_salt, + constructor_calldata: deploy_tx_args.constructor_calldata, + }) + } else if deploy_tx_args.version == TransactionVersion::THREE { + starknet_api::transaction::DeployAccountTransaction::V3(DeployAccountTransactionV3 { + signature: deploy_tx_args.signature, + resource_bounds: deploy_tx_args.resource_bounds, + tip: deploy_tx_args.tip, + nonce_data_availability_mode: deploy_tx_args.nonce_data_availability_mode, + fee_data_availability_mode: deploy_tx_args.fee_data_availability_mode, + paymaster_data: deploy_tx_args.paymaster_data, + nonce: nonce_manager.next(contract_address), + class_hash: deploy_tx_args.class_hash, + contract_address_salt: deploy_tx_args.contract_address_salt, + constructor_calldata: deploy_tx_args.constructor_calldata, + }) + } else { + panic!("Unsupported transaction version: {:?}.", deploy_tx_args.version) }; DeployAccountTransaction::new(tx, TransactionHash::default(), contract_address) diff --git a/crates/blockifier/src/test_utils/dict_state_reader.rs b/crates/blockifier/src/test_utils/dict_state_reader.rs index 2f700da6da..54fcd890e2 100644 --- a/crates/blockifier/src/test_utils/dict_state_reader.rs +++ b/crates/blockifier/src/test_utils/dict_state_reader.rs @@ -1,8 +1,8 @@ use std::collections::HashMap; use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; +use starknet_types_core::felt::Felt; use crate::execution::contract_class::ContractClass; use crate::state::cached_state::StorageEntry; @@ -12,7 +12,7 @@ use crate::state::state_api::{StateReader, StateResult}; /// A simple implementation of `StateReader` using `HashMap`s as storage. #[derive(Clone, Debug, Default)] pub struct DictStateReader { - pub storage_view: HashMap, + pub storage_view: HashMap, pub address_to_nonce: HashMap, pub address_to_class_hash: HashMap, pub class_hash_to_class: HashMap, @@ -24,7 +24,7 @@ impl StateReader for DictStateReader { &self, contract_address: ContractAddress, key: StorageKey, - ) -> StateResult { + ) -> StateResult { let contract_storage_key = (contract_address, key); let value = self.storage_view.get(&contract_storage_key).copied().unwrap_or_default(); Ok(value) diff --git a/crates/blockifier/src/test_utils/initial_test_state.rs b/crates/blockifier/src/test_utils/initial_test_state.rs index 8d2aba3212..6e0268cb29 100644 --- a/crates/blockifier/src/test_utils/initial_test_state.rs +++ b/crates/blockifier/src/test_utils/initial_test_state.rs @@ -1,8 +1,7 @@ use std::collections::HashMap; use starknet_api::core::ContractAddress; -use starknet_api::hash::StarkFelt; -use starknet_api::stark_felt; +use starknet_api::felt; use strum::IntoEnumIterator; use crate::abi::abi_utils::get_fee_token_var_address; @@ -23,10 +22,8 @@ pub fn fund_account( let storage_view = &mut state_reader.storage_view; let balance_key = get_fee_token_var_address(account_address); for fee_type in FeeType::iter() { - storage_view.insert( - (chain_info.fee_token_address(&fee_type), balance_key), - stark_felt!(initial_balance), - ); + storage_view + .insert((chain_info.fee_token_address(&fee_type), balance_key), felt!(initial_balance)); } } diff --git a/crates/blockifier/src/test_utils/invoke.rs b/crates/blockifier/src/test_utils/invoke.rs index fd5f26537e..da2f790ece 100644 --- a/crates/blockifier/src/test_utils/invoke.rs +++ b/crates/blockifier/src/test_utils/invoke.rs @@ -67,41 +67,39 @@ macro_rules! invoke_tx_args { } pub fn invoke_tx(invoke_args: InvokeTxArgs) -> InvokeTransaction { - let invoke_tx = match invoke_args.version { - TransactionVersion::ZERO => { - starknet_api::transaction::InvokeTransaction::V0(InvokeTransactionV0 { - max_fee: invoke_args.max_fee, - calldata: invoke_args.calldata, - contract_address: invoke_args.sender_address, - signature: invoke_args.signature, - // V0 transactions should always select the `__execute__` entry point. - entry_point_selector: selector_from_name(EXECUTE_ENTRY_POINT_NAME), - }) - } - TransactionVersion::ONE => { - starknet_api::transaction::InvokeTransaction::V1(InvokeTransactionV1 { - max_fee: invoke_args.max_fee, - sender_address: invoke_args.sender_address, - nonce: invoke_args.nonce, - calldata: invoke_args.calldata, - signature: invoke_args.signature, - }) - } - TransactionVersion::THREE => { - starknet_api::transaction::InvokeTransaction::V3(InvokeTransactionV3 { - resource_bounds: invoke_args.resource_bounds, - calldata: invoke_args.calldata, - sender_address: invoke_args.sender_address, - nonce: invoke_args.nonce, - signature: invoke_args.signature, - tip: invoke_args.tip, - nonce_data_availability_mode: invoke_args.nonce_data_availability_mode, - fee_data_availability_mode: invoke_args.fee_data_availability_mode, - paymaster_data: invoke_args.paymaster_data, - account_deployment_data: invoke_args.account_deployment_data, - }) - } - _ => panic!("Unsupported transaction version: {:?}.", invoke_args.version), + // TODO: Make TransactionVersion an enum and use match here. + let invoke_tx = if invoke_args.version == TransactionVersion::ZERO { + starknet_api::transaction::InvokeTransaction::V0(InvokeTransactionV0 { + max_fee: invoke_args.max_fee, + calldata: invoke_args.calldata, + contract_address: invoke_args.sender_address, + signature: invoke_args.signature, + // V0 transactions should always select the `__execute__` entry point. + entry_point_selector: selector_from_name(EXECUTE_ENTRY_POINT_NAME), + }) + } else if invoke_args.version == TransactionVersion::ONE { + starknet_api::transaction::InvokeTransaction::V1(InvokeTransactionV1 { + max_fee: invoke_args.max_fee, + sender_address: invoke_args.sender_address, + nonce: invoke_args.nonce, + calldata: invoke_args.calldata, + signature: invoke_args.signature, + }) + } else if invoke_args.version == TransactionVersion::THREE { + starknet_api::transaction::InvokeTransaction::V3(InvokeTransactionV3 { + resource_bounds: invoke_args.resource_bounds, + calldata: invoke_args.calldata, + sender_address: invoke_args.sender_address, + nonce: invoke_args.nonce, + signature: invoke_args.signature, + tip: invoke_args.tip, + nonce_data_availability_mode: invoke_args.nonce_data_availability_mode, + fee_data_availability_mode: invoke_args.fee_data_availability_mode, + paymaster_data: invoke_args.paymaster_data, + account_deployment_data: invoke_args.account_deployment_data, + }) + } else { + panic!("Unsupported transaction version: {:?}.", invoke_args.version) }; let default_tx_hash = TransactionHash::default(); diff --git a/crates/blockifier/src/test_utils/prices.rs b/crates/blockifier/src/test_utils/prices.rs index 7cdda617f0..bc2592aade 100644 --- a/crates/blockifier/src/test_utils/prices.rs +++ b/crates/blockifier/src/test_utils/prices.rs @@ -3,9 +3,8 @@ use std::sync::Arc; use cached::proc_macro::cached; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use starknet_api::core::ContractAddress; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::Calldata; -use starknet_api::{calldata, stark_felt}; +use starknet_api::{calldata, felt}; use crate::abi::abi_utils::{get_fee_token_var_address, selector_from_name}; use crate::context::BlockContext; @@ -52,7 +51,7 @@ fn fee_transfer_resources( .set_storage_at( token_address, get_fee_token_var_address(account_contract_address), - stark_felt!(BALANCE), + felt!(BALANCE), ) .unwrap(); @@ -61,8 +60,8 @@ fn fee_transfer_resources( entry_point_selector: selector_from_name(constants::TRANSFER_ENTRY_POINT_NAME), calldata: calldata![ *block_context.block_info.sequencer_address.0.key(), // Recipient. - stark_felt!(7_u8), // LSB of Amount. - stark_felt!(0_u8) // MSB of Amount. + felt!(7_u8), // LSB of Amount. + felt!(0_u8) // MSB of Amount. ], storage_address: token_address, caller_address: account_contract_address, diff --git a/crates/blockifier/src/test_utils/struct_impls.rs b/crates/blockifier/src/test_utils/struct_impls.rs index 485230b14e..c44639d1bb 100644 --- a/crates/blockifier/src/test_utils/struct_impls.rs +++ b/crates/blockifier/src/test_utils/struct_impls.rs @@ -4,9 +4,8 @@ use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use serde_json::Value; use starknet_api::block::{BlockNumber, BlockTimestamp}; use starknet_api::core::{ChainId, ContractAddress, PatriciaKey}; -use starknet_api::hash::StarkHash; use starknet_api::transaction::Fee; -use starknet_api::{contract_address, patricia_key}; +use starknet_api::{contract_address, felt, patricia_key}; use super::update_json_value; use crate::blockifier::block::{BlockInfo, GasPrices}; @@ -124,7 +123,7 @@ impl GasCosts { impl ChainInfo { pub fn create_for_testing() -> Self { Self { - chain_id: ChainId(CHAIN_ID_NAME.to_string()), + chain_id: ChainId::Other(CHAIN_ID_NAME.to_string()), fee_token_addresses: FeeTokenAddresses { eth_fee_token_address: contract_address!(TEST_ERC20_CONTRACT_ADDRESS), strk_fee_token_address: contract_address!(TEST_ERC20_CONTRACT_ADDRESS2), diff --git a/crates/blockifier/src/test_utils/transfers_generator.rs b/crates/blockifier/src/test_utils/transfers_generator.rs index 400719886e..1164f58825 100644 --- a/crates/blockifier/src/test_utils/transfers_generator.rs +++ b/crates/blockifier/src/test_utils/transfers_generator.rs @@ -1,8 +1,8 @@ use rand::{Rng, SeedableRng}; use starknet_api::core::ContractAddress; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::{Calldata, Fee, TransactionVersion}; -use starknet_api::{calldata, stark_felt}; +use starknet_api::{calldata, felt}; +use starknet_types_core::felt::Felt; use crate::abi::abi_utils::selector_from_name; use crate::blockifier::config::TransactionExecutorConfig; @@ -21,7 +21,7 @@ use crate::transaction::transaction_execution::Transaction; const N_ACCOUNTS: u16 = 10000; const CHUNK_SIZE: usize = 10; const RANDOMIZATION_SEED: u64 = 0; -const TRANSACTION_VERSION: TransactionVersion = TransactionVersion(StarkFelt::ONE); +const TRANSACTION_VERSION: TransactionVersion = TransactionVersion(Felt::ONE); pub struct TransfersGenerator { account_addresses: Vec, @@ -86,23 +86,21 @@ impl TransfersGenerator { let nonce = self.nonce_manager.next(sender_address); let entry_point_selector = selector_from_name(TRANSFER_ENTRY_POINT_NAME); - let contract_address = match TRANSACTION_VERSION { - TransactionVersion::ONE => { - *self.chain_info.fee_token_addresses.eth_fee_token_address.0.key() - } - TransactionVersion::THREE => { - *self.chain_info.fee_token_addresses.strk_fee_token_address.0.key() - } - _ => panic!("Unsupported transaction version: {TRANSACTION_VERSION:?}"), + let contract_address = if TRANSACTION_VERSION == TransactionVersion::ONE { + *self.chain_info.fee_token_addresses.eth_fee_token_address.0.key() + } else if TRANSACTION_VERSION == TransactionVersion::THREE { + *self.chain_info.fee_token_addresses.strk_fee_token_address.0.key() + } else { + panic!("Unsupported transaction version: {TRANSACTION_VERSION:?}") }; let execute_calldata = calldata![ contract_address, // Contract address. entry_point_selector.0, // EP selector. - stark_felt!(3_u8), // Calldata length. + felt!(3_u8), // Calldata length. *recipient_address.0.key(), // Calldata: recipient. - stark_felt!(1_u8), // Calldata: lsb amount. - stark_felt!(0_u8) // Calldata: msb amount. + felt!(1_u8), // Calldata: lsb amount. + felt!(0_u8) // Calldata: msb amount. ]; let tx = invoke_tx(invoke_tx_args! { diff --git a/crates/blockifier/src/transaction/account_transaction.rs b/crates/blockifier/src/transaction/account_transaction.rs index a81d21aa9f..c4c396ebc2 100644 --- a/crates/blockifier/src/transaction/account_transaction.rs +++ b/crates/blockifier/src/transaction/account_transaction.rs @@ -4,8 +4,8 @@ use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use starknet_api::calldata; use starknet_api::core::{ContractAddress, EntryPointSelector}; use starknet_api::deprecated_contract_class::EntryPointType; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::{Calldata, Fee, ResourceBounds, TransactionVersion}; +use starknet_types_core::felt::Felt; use crate::abi::abi_utils::selector_from_name; use crate::context::{BlockContext, TransactionContext}; @@ -334,9 +334,9 @@ impl AccountTransaction { actual_fee: Fee, ) -> TransactionExecutionResult { // The least significant 128 bits of the amount transferred. - let lsb_amount = StarkFelt::from(actual_fee.0); + let lsb_amount = Felt::from(actual_fee.0); // The most significant 128 bits of the amount transferred. - let msb_amount = StarkFelt::from(0_u8); + let msb_amount = Felt::from(0_u8); let TransactionContext { block_context, tx_info } = tx_context.as_ref(); let storage_address = block_context.chain_info.fee_token_address(&tx_info.fee_type()); @@ -384,7 +384,7 @@ impl AccountTransaction { // Set the initial sequencer balance to avoid tarnishing the read-set of the transaction. let cache = transfer_state.cache.get_mut(); for key in [sequencer_balance_key_low, sequencer_balance_key_high] { - cache.set_storage_initial_value(fee_address, key, StarkFelt::ZERO); + cache.set_storage_initial_value(fee_address, key, Felt::ZERO); } let fee_transfer_call_info = @@ -771,7 +771,7 @@ impl ValidatableTransaction for AccountTransaction { if let ContractClass::V1(_) = contract_class { // The account contract class is a Cairo 1.0 contract; the `validate` entry point should // return `VALID`. - let expected_retdata = retdata![StarkFelt::try_from(constants::VALIDATE_RETDATA)?]; + let expected_retdata = retdata![Felt::from_hex(constants::VALIDATE_RETDATA)?]; if validate_call_info.execution.retdata != expected_retdata { return Err(TransactionExecutionError::InvalidValidateReturnData { actual: validate_call_info.execution.retdata, diff --git a/crates/blockifier/src/transaction/account_transactions_test.rs b/crates/blockifier/src/transaction/account_transactions_test.rs index 43208109d7..ffb9acb9a5 100644 --- a/crates/blockifier/src/transaction/account_transactions_test.rs +++ b/crates/blockifier/src/transaction/account_transactions_test.rs @@ -1,18 +1,18 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use cairo_felt::Felt252; use cairo_vm::vm::runners::cairo_runner::ResourceTracker; use pretty_assertions::assert_eq; use rstest::rstest; use starknet_api::core::{calculate_contract_address, ClassHash, ContractAddress, PatriciaKey}; -use starknet_api::hash::{StarkFelt, StarkHash}; +use starknet_api::hash::StarkHash; use starknet_api::state::StorageKey; use starknet_api::transaction::{ Calldata, ContractAddressSalt, DeclareTransactionV2, Fee, ResourceBoundsMapping, TransactionHash, TransactionVersion, }; -use starknet_api::{calldata, class_hash, contract_address, patricia_key, stark_felt}; +use starknet_api::{calldata, class_hash, contract_address, felt, patricia_key}; +use starknet_types_core::felt::Felt; use crate::abi::abi_utils::{ get_fee_token_var_address, get_storage_var_address, selector_from_name, @@ -20,7 +20,6 @@ use crate::abi::abi_utils::{ use crate::context::BlockContext; use crate::execution::contract_class::{ContractClass, ContractClassV1}; use crate::execution::entry_point::EntryPointExecutionContext; -use crate::execution::execution_utils::{felt_to_stark_felt, stark_felt_to_felt}; use crate::execution::syscalls::SyscallSelector; use crate::fee::fee_utils::{get_fee_by_gas_vector, get_sequencer_balance_keys}; use crate::fee::gas_usage::estimate_minimal_gas_vector; @@ -155,8 +154,8 @@ fn test_invoke_tx_from_non_deployed_account( calldata: calldata![ non_deployed_contract_address, // Contract address. entry_point_selector.0, // EP selector. - stark_felt!(1_u8), // Calldata length. - stark_felt!(2_u8) // Calldata: num. + felt!(1_u8), // Calldata length. + felt!(2_u8) // Calldata: num. ], resource_bounds: max_resource_bounds, version: tx_version, @@ -173,7 +172,7 @@ fn test_invoke_tx_from_non_deployed_account( // Make sure the error is because the account wasn't deployed. assert!(err.to_string().contains(expected_error)); // We expect to get an error only when tx_version is 0, on other versions to revert. - assert!(matches!(tx_version, TransactionVersion::ZERO)); + assert_eq!(tx_version, TransactionVersion::ZERO); } } } @@ -196,7 +195,7 @@ fn test_infinite_recursion( let recursion_depth = if success { 3_u32 } else { 1000_u32 }; let execute_calldata = if normal_recurse { - create_calldata(contract_address, "recurse", &[stark_felt!(recursion_depth)]) + create_calldata(contract_address, "recurse", &[felt!(recursion_depth)]) } else { create_calldata( contract_address, @@ -204,7 +203,7 @@ fn test_infinite_recursion( &[ *contract_address.0.key(), // Calldata: raw contract address. selector_from_name("recursive_syscall").0, // Calldata: raw selector - stark_felt!(recursion_depth), + felt!(recursion_depth), ], ) }; @@ -265,8 +264,8 @@ fn test_max_fee_limit_validate( // Deploy grindy account with a lot of grind in the constructor. // Expect this to fail without bumping nonce, so pass a temporary nonce manager. - let mut ctor_grind_arg = stark_felt!(1_u8); // Grind in deploy phase. - let ctor_storage_arg = stark_felt!(1_u8); // Not relevant for this test. + let mut ctor_grind_arg = felt!(1_u8); // Grind in deploy phase. + let ctor_storage_arg = felt!(1_u8); // Not relevant for this test. let (deploy_account_tx, _) = deploy_and_fund_account( &mut state, &mut NonceManager::default(), @@ -282,7 +281,7 @@ fn test_max_fee_limit_validate( assert!(error_trace.contains("no remaining steps")); // Deploy grindy account successfully this time. - ctor_grind_arg = stark_felt!(0_u8); // Do not grind in deploy phase. + ctor_grind_arg = felt!(0_u8); // Do not grind in deploy phase. let (deploy_account_tx, grindy_account_address) = deploy_and_fund_account( &mut state, &mut nonce_manager, @@ -371,7 +370,7 @@ fn test_recursion_depth_exceeded( &[ *contract_address.0.key(), // Calldata: raw contract address. selector_from_name(recursive_syscall_entry_point_name).0, // Calldata: raw selector. - stark_felt!(max_inner_recursion_depth), + felt!(max_inner_recursion_depth), ], ); let invoke_args = invoke_tx_args! { @@ -396,7 +395,7 @@ fn test_recursion_depth_exceeded( &[ *contract_address.0.key(), // Calldata: raw contract address. selector_from_name(recursive_syscall_entry_point_name).0, // Calldata: raw selector. - stark_felt!(exceeding_recursion_depth), + felt!(exceeding_recursion_depth), ], ); let invoke_args = crate::test_utils::invoke::InvokeTxArgs { @@ -429,7 +428,7 @@ fn test_revert_invoke( let mut nonce_manager = NonceManager::default(); // Invoke a function that changes the state and reverts. - let storage_key = stark_felt!(9_u8); + let storage_key = felt!(9_u8); let tx_execution_info = run_invoke_tx( state, &block_context, @@ -440,7 +439,7 @@ fn test_revert_invoke( test_contract_address, "write_and_revert", // Write some non-zero value. - &[storage_key, stark_felt!(99_u8)] + &[storage_key, felt!(99_u8)] ), version: transaction_version, nonce: nonce_manager.next(account_address), @@ -459,7 +458,7 @@ fn test_revert_invoke( state .get_fee_token_balance(account_address, chain_info.fee_token_address(&fee_type)) .unwrap(), - (stark_felt!(BALANCE - tx_execution_info.transaction_receipt.fee.0), stark_felt!(0_u8)) + (felt!(BALANCE - tx_execution_info.transaction_receipt.fee.0), felt!(0_u8)) ); assert_eq!(state.get_nonce_at(account_address).unwrap(), nonce_manager.next(account_address)); @@ -468,7 +467,7 @@ fn test_revert_invoke( // Check that execution state changes were reverted. assert_eq!( - stark_felt!(0_u8), + felt!(0_u8), state .get_storage_at(test_contract_address, StorageKey::try_from(storage_key).unwrap()) .unwrap() @@ -578,7 +577,7 @@ fn recursive_function_calldata( create_calldata( *contract_address, if failure_variant { "recursive_fail" } else { "recurse" }, - &[stark_felt!(depth)], // Calldata: recursion depth. + &[felt!(depth)], // Calldata: recursion depth. ) } @@ -817,7 +816,7 @@ fn test_max_fee_to_max_steps_conversion( let execute_calldata = create_calldata( contract_address, "with_arg", - &[stark_felt!(25_u8)], // Calldata: arg. + &[felt!(25_u8)], // Calldata: arg. ); // First invocation of `with_arg` gets the exact pre-calculated actual fee as max_fee. @@ -958,8 +957,8 @@ fn test_deploy_account_constructor_storage_write( let chain_info = &block_context.chain_info; let state = &mut test_state(chain_info, BALANCE, &[(grindy_account, 1)]); - let ctor_storage_arg = stark_felt!(1_u8); - let ctor_grind_arg = stark_felt!(0_u8); // Do not grind in deploy phase. + let ctor_storage_arg = felt!(1_u8); + let ctor_grind_arg = felt!(0_u8); // Do not grind in deploy phase. let constructor_calldata = calldata![ctor_grind_arg, ctor_storage_arg]; let (deploy_account_tx, _) = deploy_and_fund_account( state, @@ -1012,9 +1011,8 @@ fn test_count_actual_storage_changes( let mut nonce_manager = NonceManager::default(); let sequencer_address = block_context.block_info.sequencer_address; - let initial_sequencer_balance = stark_felt_to_felt( - state.get_fee_token_balance(sequencer_address, fee_token_address).unwrap().0, - ); + let initial_sequencer_balance = + state.get_fee_token_balance(sequencer_address, fee_token_address).unwrap().0; // Fee token var address. let sequencer_fee_token_var_address = get_fee_token_var_address(sequencer_address); @@ -1023,12 +1021,12 @@ fn test_count_actual_storage_changes( // Calldata types. let write_1_calldata = create_calldata(contract_address, "test_count_actual_storage_changes", &[]); - let recipient = stark_felt!(435_u16); - let transfer_amount: Felt252 = 1.into(); + let recipient = 435_u16; + let transfer_amount: Felt = 1.into(); let transfer_calldata = create_calldata( fee_token_address, TRANSFER_ENTRY_POINT_NAME, - &[recipient, felt_to_stark_felt(&transfer_amount), stark_felt!(0_u8)], + &[felt!(recipient), transfer_amount, felt!(0_u8)], ); // Run transactions; using transactional state to count only storage changes of the current @@ -1049,15 +1047,13 @@ fn test_count_actual_storage_changes( let fee_1 = execution_info.transaction_receipt.fee; let state_changes_1 = state.get_actual_state_changes().unwrap(); - let cell_write_storage_change = ((contract_address, storage_key!(15_u8)), stark_felt!(1_u8)); - let mut expected_sequencer_total_fee = initial_sequencer_balance + Felt252::from(fee_1.0); - let mut expected_sequencer_fee_update = ( - (fee_token_address, sequencer_fee_token_var_address), - felt_to_stark_felt(&expected_sequencer_total_fee), - ); + let cell_write_storage_change = ((contract_address, storage_key!(15_u8)), felt!(1_u8)); + let mut expected_sequencer_total_fee = initial_sequencer_balance + Felt::from(fee_1.0); + let mut expected_sequencer_fee_update = + ((fee_token_address, sequencer_fee_token_var_address), expected_sequencer_total_fee); let mut account_balance = BALANCE - fee_1.0; let account_balance_storage_change = - ((fee_token_address, account_fee_token_var_address), stark_felt!(account_balance)); + ((fee_token_address, account_fee_token_var_address), felt!(account_balance)); let expected_modified_contracts = HashSet::from([account_address, contract_address, fee_token_address]); @@ -1093,11 +1089,11 @@ fn test_count_actual_storage_changes( let fee_2 = execution_info.transaction_receipt.fee; let state_changes_2 = state.get_actual_state_changes().unwrap(); - expected_sequencer_total_fee += Felt252::from(fee_2.0); - expected_sequencer_fee_update.1 = felt_to_stark_felt(&expected_sequencer_total_fee); + expected_sequencer_total_fee += Felt::from(fee_2.0); + expected_sequencer_fee_update.1 = expected_sequencer_total_fee; account_balance -= fee_2.0; let account_balance_storage_change = - ((fee_token_address, account_fee_token_var_address), stark_felt!(account_balance)); + ((fee_token_address, account_fee_token_var_address), felt!(account_balance)); let expected_modified_contracts_2 = HashSet::from([account_address, fee_token_address]); let expected_storage_updates_2 = @@ -1131,14 +1127,14 @@ fn test_count_actual_storage_changes( let state_changes_transfer = state.get_actual_state_changes().unwrap(); let transfer_receipient_storage_change = ( (fee_token_address, get_fee_token_var_address(contract_address!(recipient))), - felt_to_stark_felt(&transfer_amount), + transfer_amount, ); - expected_sequencer_total_fee += Felt252::from(fee_transfer.0); - expected_sequencer_fee_update.1 = felt_to_stark_felt(&expected_sequencer_total_fee); + expected_sequencer_total_fee += Felt::from(fee_transfer.0); + expected_sequencer_fee_update.1 = expected_sequencer_total_fee; account_balance -= fee_transfer.0 + 1; // Reduce the fee and the transfered amount (1). let account_balance_storage_change = - ((fee_token_address, account_fee_token_var_address), stark_felt!(account_balance)); + ((fee_token_address, account_fee_token_var_address), felt!(account_balance)); let expected_modified_contracts_transfer = HashSet::from([account_address, fee_token_address]); let expected_storage_update_transfer = HashMap::from([ @@ -1221,11 +1217,7 @@ fn test_concurrency_execute_fee_transfer( let transfer_calldata = create_calldata( fee_token_address, TRANSFER_ENTRY_POINT_NAME, - &[ - *block_context.block_info.sequencer_address.0.key(), - stark_felt!(TRANSFER_AMOUNT), - stark_felt!(0_u8), - ], + &[*block_context.block_info.sequencer_address.0.key(), felt!(TRANSFER_AMOUNT), felt!(0_u8)], ); // Set the sequencer balance to a constant value to check that the read set did not changed. @@ -1256,17 +1248,14 @@ fn test_concurrency_execute_fee_transfer( ( storage_writes.get(&(fee_token_address, sequencer_balance_key_low)), // Balance after `execute` and without the fee transfer. - stark_felt!(SEQUENCER_BALANCE_LOW_INITIAL + TRANSFER_AMOUNT), + felt!(SEQUENCER_BALANCE_LOW_INITIAL + TRANSFER_AMOUNT), ), ( storage_initial_reads.get(&(fee_token_address, sequencer_balance_key_low)), - stark_felt!(SEQUENCER_BALANCE_LOW_INITIAL), - ), - (storage_writes.get(&(fee_token_address, sequencer_balance_key_high)), StarkFelt::ZERO), - ( - storage_initial_reads.get(&(fee_token_address, sequencer_balance_key_high)), - StarkFelt::ZERO, + felt!(SEQUENCER_BALANCE_LOW_INITIAL), ), + (storage_writes.get(&(fee_token_address, sequencer_balance_key_high)), Felt::ZERO), + (storage_initial_reads.get(&(fee_token_address, sequencer_balance_key_high)), Felt::ZERO), ] { assert_eq!(*seq_write_val.unwrap(), expexted_write_val); } @@ -1311,9 +1300,6 @@ fn test_concurrent_fee_transfer_when_sender_is_sequencer( for (seq_key, seq_value) in [(sequencer_balance_key_low, sender_balance), (sequencer_balance_key_high, 0_u128)] { - assert_eq!( - state.get_storage_at(fee_token_address, seq_key).unwrap(), - stark_felt!(seq_value) - ); + assert_eq!(state.get_storage_at(fee_token_address, seq_key).unwrap(), felt!(seq_value)); } } diff --git a/crates/blockifier/src/transaction/constants.rs b/crates/blockifier/src/transaction/constants.rs index 16b5d8cb6c..105bd24b4e 100644 --- a/crates/blockifier/src/transaction/constants.rs +++ b/crates/blockifier/src/transaction/constants.rs @@ -15,5 +15,5 @@ pub const FELT_TRUE: u64 = 1; pub const VALIDATE_RETDATA: &str = "0x56414c4944"; // TODO(Noa, 14/11/2023): Replace QUERY_VERSION_BASE_BIT with a lazy calculation. -// pub static QUERY_VERSION_BASE: Lazy = ... +// pub static QUERY_VERSION_BASE: Lazy = ... pub const QUERY_VERSION_BASE_BIT: u32 = 128; diff --git a/crates/blockifier/src/transaction/errors.rs b/crates/blockifier/src/transaction/errors.rs index 651eaddd6a..fc7c141e9f 100644 --- a/crates/blockifier/src/transaction/errors.rs +++ b/crates/blockifier/src/transaction/errors.rs @@ -2,6 +2,7 @@ use num_bigint::BigUint; use starknet_api::core::{ClassHash, ContractAddress, EntryPointSelector, Nonce}; use starknet_api::transaction::{Fee, TransactionVersion}; use starknet_api::StarknetApiError; +use starknet_types_core::felt::FromStrError; use thiserror::Error; use crate::execution::call_info::Retdata; @@ -72,6 +73,8 @@ pub enum TransactionExecutionError { }, #[error(transparent)] FeeCheckError(#[from] FeeCheckError), + #[error(transparent)] + FromStr(#[from] FromStrError), #[error("The `validate` entry point should return `VALID`. Got {actual:?}.")] InvalidValidateReturnData { actual: Retdata }, #[error( diff --git a/crates/blockifier/src/transaction/execution_flavors_test.rs b/crates/blockifier/src/transaction/execution_flavors_test.rs index a7ba09b45c..2264c5eaab 100644 --- a/crates/blockifier/src/transaction/execution_flavors_test.rs +++ b/crates/blockifier/src/transaction/execution_flavors_test.rs @@ -1,16 +1,14 @@ use assert_matches::assert_matches; -use cairo_felt::Felt252; use pretty_assertions::assert_eq; use rstest::rstest; use starknet_api::core::ContractAddress; -use starknet_api::hash::StarkFelt; -use starknet_api::stark_felt; +use starknet_api::felt; use starknet_api::transaction::{ Calldata, Fee, ResourceBoundsMapping, TransactionSignature, TransactionVersion, }; +use starknet_types_core::felt::Felt; use crate::context::{BlockContext, ChainInfo}; -use crate::execution::execution_utils::{felt_to_stark_felt, stark_felt_to_felt}; use crate::execution::syscalls::SyscallSelector; use crate::fee::fee_utils::get_fee_by_gas_vector; use crate::state::cached_state::CachedState; @@ -67,13 +65,13 @@ fn create_flavors_test_state( /// Checks that balance of the account decreased if and only if `charge_fee` is true. /// Returns the new balance. fn check_balance( - current_balance: StarkFelt, + current_balance: Felt, state: &mut CachedState, account_address: ContractAddress, chain_info: &ChainInfo, fee_type: &FeeType, charge_fee: bool, -) -> StarkFelt { +) -> Felt { let (new_balance, _) = state .get_fee_token_balance(account_address, chain_info.fee_token_address(fee_type)) .unwrap(); @@ -137,7 +135,7 @@ fn recurse_calldata(contract_address: ContractAddress, fail: bool, depth: u32) - create_calldata( contract_address, if fail { "recursive_fail" } else { "recurse" }, - &[stark_felt!(depth)], + &[felt!(depth)], ) } @@ -361,8 +359,8 @@ fn test_simulate_validate_charge_fee_fail_validate( max_fee, resource_bounds: max_resource_bounds, signature: TransactionSignature(vec![ - StarkFelt::from(INVALID), - StarkFelt::ZERO + Felt::from(INVALID), + Felt::ZERO ]), sender_address: faulty_account_address, calldata: create_calldata(faulty_account_address, "foo", &[]), @@ -662,16 +660,16 @@ fn test_simulate_validate_charge_fee_post_execution( validate, &fee_type, ); - assert!(stark_felt!(actual_fee) < current_balance); - let transfer_amount = stark_felt_to_felt(current_balance) - Felt252::from(actual_fee.0 / 2); - let recipient = stark_felt!(7_u8); + assert!(felt!(actual_fee.0) < current_balance); + let transfer_amount = current_balance - Felt::from(actual_fee.0 / 2); + let recipient = felt!(7_u8); let transfer_calldata = create_calldata( fee_token_address, "transfer", &[ recipient, // Calldata: to. - felt_to_stark_felt(&transfer_amount), - stark_felt!(0_u8), + transfer_amount, + felt!(0_u8), ], ); let tx_execution_info = account_invoke_tx(invoke_tx_args! { diff --git a/crates/blockifier/src/transaction/objects.rs b/crates/blockifier/src/transaction/objects.rs index d5b895dfbf..0ba4006a8d 100644 --- a/crates/blockifier/src/transaction/objects.rs +++ b/crates/blockifier/src/transaction/objects.rs @@ -1,7 +1,6 @@ use std::collections::HashMap; -use cairo_felt::Felt252; -use cairo_vm::vm::runners::builtin_runner::SEGMENT_ARENA_BUILTIN_NAME; +use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use num_traits::Pow; use serde::Serialize; @@ -11,12 +10,12 @@ use starknet_api::transaction::{ AccountDeploymentData, Fee, PaymasterData, Resource, ResourceBounds, ResourceBoundsMapping, Tip, TransactionHash, TransactionSignature, TransactionVersion, }; +use starknet_types_core::felt::Felt; use strum_macros::EnumIter; use crate::abi::constants as abi_constants; use crate::blockifier::block::BlockInfo; use crate::execution::call_info::{CallInfo, ExecutionSummary, MessageL1CostInfo, OrderedEvent}; -use crate::execution::execution_utils::{felt_to_stark_felt, stark_felt_to_felt}; use crate::fee::actual_cost::TransactionReceipt; use crate::fee::eth_gas_constants; use crate::fee::fee_utils::{calculate_l1_gas_by_vm_usage, get_fee_by_gas_vector}; @@ -84,9 +83,9 @@ impl TransactionInfo { return version; } - let query_version_base = Pow::pow(Felt252::from(2_u8), constants::QUERY_VERSION_BASE_BIT); - let query_version = query_version_base + stark_felt_to_felt(version.0); - TransactionVersion(felt_to_stark_felt(&query_version)) + let query_version_base = Felt::TWO.pow(constants::QUERY_VERSION_BASE_BIT); + let query_version = query_version_base + version.0; + TransactionVersion(query_version) } pub fn enforce_fee(&self) -> TransactionFeeResult { @@ -480,7 +479,8 @@ impl TransactionResources { pub trait ExecutionResourcesTraits { fn total_n_steps(&self) -> usize; fn to_resources_mapping(&self) -> ResourcesMapping; - fn prover_builtins(&self) -> HashMap; + fn prover_builtins(&self) -> HashMap; + fn prover_builtins_by_name(&self) -> HashMap; } impl ExecutionResourcesTraits for ExecutionResources { @@ -495,24 +495,31 @@ impl ExecutionResourcesTraits for ExecutionResources { + abi_constants::N_STEPS_PER_SEGMENT_ARENA_BUILTIN * self .builtin_instance_counter - .get(SEGMENT_ARENA_BUILTIN_NAME) + .get(&BuiltinName::segment_arena) .cloned() .unwrap_or_default() } - fn prover_builtins(&self) -> HashMap { + fn prover_builtins(&self) -> HashMap { let mut builtins = self.builtin_instance_counter.clone(); // See "total_n_steps" documentation. - builtins.remove(SEGMENT_ARENA_BUILTIN_NAME); + builtins.remove(&BuiltinName::segment_arena); builtins } + fn prover_builtins_by_name(&self) -> HashMap { + self.prover_builtins() + .iter() + .map(|(builtin, value)| (builtin.to_str_with_suffix().to_string(), *value)) + .collect() + } + // TODO(Nimrod, 1/5/2024): Delete this function when it's no longer in use. fn to_resources_mapping(&self) -> ResourcesMapping { let mut map = HashMap::from([(abi_constants::N_STEPS_RESOURCE.to_string(), self.total_n_steps())]); - map.extend(self.prover_builtins()); + map.extend(self.prover_builtins_by_name()); ResourcesMapping(map) } diff --git a/crates/blockifier/src/transaction/objects_test.rs b/crates/blockifier/src/transaction/objects_test.rs index 0e37a8994c..7d1ef479e1 100644 --- a/crates/blockifier/src/transaction/objects_test.rs +++ b/crates/blockifier/src/transaction/objects_test.rs @@ -1,7 +1,6 @@ use rstest::rstest; -use starknet_api::class_hash; use starknet_api::core::ClassHash; -use starknet_api::hash::StarkHash; +use starknet_api::{class_hash, felt}; use crate::execution::call_info::{ CallExecution, CallInfo, ExecutionSummary, OrderedEvent, TestExecutionSummary, diff --git a/crates/blockifier/src/transaction/post_execution_test.rs b/crates/blockifier/src/transaction/post_execution_test.rs index cc7f909629..a9b9e67321 100644 --- a/crates/blockifier/src/transaction/post_execution_test.rs +++ b/crates/blockifier/src/transaction/post_execution_test.rs @@ -1,11 +1,10 @@ use assert_matches::assert_matches; use rstest::rstest; use starknet_api::core::{ContractAddress, PatriciaKey}; -use starknet_api::hash::{StarkFelt, StarkHash}; use starknet_api::state::StorageKey; use starknet_api::transaction::{Calldata, Fee, ResourceBoundsMapping, TransactionVersion}; -use starknet_api::{patricia_key, stark_felt}; -use starknet_crypto::FieldElement; +use starknet_api::{felt, patricia_key}; +use starknet_types_core::felt::Felt; use crate::context::{BlockContext, ChainInfo}; use crate::fee::fee_checks::FeeCheckError; @@ -37,10 +36,10 @@ fn init_data_by_version(chain_info: &ChainInfo, cairo_version: CairoVersion) -> fn calldata_for_write_and_transfer( test_contract_address: ContractAddress, - storage_address: StarkFelt, - storage_value: StarkFelt, - recipient: StarkFelt, - transfer_amount: StarkFelt, + storage_address: Felt, + storage_value: Felt, + recipient: Felt, + transfer_amount: Felt, fee_token_address: ContractAddress, ) -> Calldata { create_calldata( @@ -72,21 +71,22 @@ fn test_revert_on_overdraft( let chain_info = &block_context.chain_info; let fee_token_address = chain_info.fee_token_addresses.get_by_fee_type(&fee_type); // An address to be written into to observe state changes. - let storage_address = stark_felt!(10_u8); + let storage_address = felt!(10_u8); let storage_key = StorageKey::try_from(storage_address).unwrap(); // Final storage value expected in the address at the end of this test. - let expected_final_value = stark_felt!(77_u8); + let expected_final_value = felt!(77_u8); // An address to be used as recipient of a transfer. - let recipient = stark_felt!(7_u8); - let recipient_address = ContractAddress(patricia_key!(recipient)); + let recipient_int = 7_u8; + let recipient = felt!(recipient_int); + let recipient_address = ContractAddress(patricia_key!(recipient_int)); // Amount expected to be transferred successfully. - let final_received_amount = stark_felt!(80_u8); + let final_received_amount = felt!(80_u8); let TestInitData { mut state, account_address, contract_address, mut nonce_manager } = init_data_by_version(chain_info, cairo_version); // Verify the contract's storage key initial value is empty. - assert_eq!(state.get_storage_at(contract_address, storage_key).unwrap(), stark_felt!(0_u8)); + assert_eq!(state.get_storage_at(contract_address, storage_key).unwrap(), felt!(0_u8)); // Approve the test contract to transfer funds. let approve_calldata = create_calldata( @@ -94,8 +94,8 @@ fn test_revert_on_overdraft( "approve", &[ *contract_address.0.key(), // Calldata: to. - stark_felt!(BALANCE), - stark_felt!(0_u8), + felt!(BALANCE), + felt!(0_u8), ], ); @@ -154,7 +154,7 @@ fn test_revert_on_overdraft( calldata: calldata_for_write_and_transfer( contract_address, storage_address, - stark_felt!(0_u8), + felt!(0_u8), recipient, balance, fee_token_address @@ -167,8 +167,7 @@ fn test_revert_on_overdraft( .unwrap(); // Compute the expected balance after the reverted write+transfer (tx fee should be charged). - let expected_new_balance: StarkFelt = - StarkFelt::from(FieldElement::from(balance) - FieldElement::from(transfer_tx_fee.0)); + let expected_new_balance = balance - Felt::from(transfer_tx_fee.0); // Verify the execution was reverted (including nonce bump) with the correct error. assert!(execution_info.is_reverted()); @@ -186,7 +185,7 @@ fn test_revert_on_overdraft( chain_info.fee_token_address(&tx_info.fee_type()), ) .unwrap(), - (expected_new_balance, stark_felt!(0_u8)) + (expected_new_balance, felt!(0_u8)) ); assert_eq!( state @@ -195,7 +194,7 @@ fn test_revert_on_overdraft( chain_info.fee_token_address(&tx_info.fee_type()) ) .unwrap(), - (final_received_amount, stark_felt!(0_u8)) + (final_received_amount, felt!(0_u8)) ); } @@ -226,11 +225,7 @@ fn test_revert_on_resource_overuse( let mut value_to_write = 1_u8; let mut write_a_lot_calldata = || { value_to_write += 1; - create_calldata( - contract_address, - "write_a_lot", - &[stark_felt!(n_writes), stark_felt!(value_to_write)], - ) + create_calldata(contract_address, "write_a_lot", &[felt!(n_writes), felt!(value_to_write)]) }; // Run a "heavy" transaction and measure the resources used. diff --git a/crates/blockifier/src/transaction/test_utils.rs b/crates/blockifier/src/transaction/test_utils.rs index 1468510b53..a5a353a056 100644 --- a/crates/blockifier/src/transaction/test_utils.rs +++ b/crates/blockifier/src/transaction/test_utils.rs @@ -1,12 +1,12 @@ use rstest::fixture; use starknet_api::core::{ClassHash, ContractAddress, Nonce}; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::{ Calldata, ContractAddressSalt, Fee, InvokeTransactionV0, InvokeTransactionV1, InvokeTransactionV3, Resource, ResourceBounds, ResourceBoundsMapping, TransactionHash, TransactionSignature, TransactionVersion, }; -use starknet_api::{calldata, stark_felt}; +use starknet_api::{calldata, felt}; +use starknet_types_core::felt::Felt; use strum::IntoEnumIterator; use crate::abi::abi_utils::get_fee_token_var_address; @@ -105,7 +105,7 @@ pub fn deploy_and_fund_account( for fee_type in FeeType::iter() { let fee_token_address = chain_info.fee_token_address(&fee_type); state - .set_storage_at(fee_token_address, deployed_account_balance_key, stark_felt!(BALANCE)) + .set_storage_at(fee_token_address, deployed_account_balance_key, felt!(BALANCE)) .unwrap(); } @@ -132,7 +132,7 @@ pub struct FaultyAccountTxCreatorArgs { pub scenario: u64, pub max_fee: Fee, // Should be None unless scenario is CALL_CONTRACT. - pub additional_data: Option>, + pub additional_data: Option>, // Should be use with tx_type Declare or InvokeFunction. pub sender_address: ContractAddress, // Should be used with tx_type DeployAccount. @@ -197,7 +197,7 @@ pub fn create_account_tx_for_validate_test( // The first felt of the signature is used to set the scenario. If the scenario is // `CALL_CONTRACT` the second felt is used to pass the contract address. - let mut signature_vector = vec![StarkFelt::from(scenario)]; + let mut signature_vector = vec![Felt::from(scenario)]; if let Some(additional_data) = additional_data { signature_vector.extend(additional_data); } @@ -230,7 +230,7 @@ pub fn create_account_tx_for_validate_test( TransactionType::DeployAccount => { // We do not use the sender address here because the transaction generates the actual // sender address. - let constructor_calldata = calldata![stark_felt!(match validate_constructor { + let constructor_calldata = calldata![felt!(match validate_constructor { true => constants::FELT_TRUE, false => constants::FELT_FALSE, })]; @@ -300,9 +300,9 @@ pub fn emit_n_events_tx( nonce: Nonce, ) -> AccountTransaction { let entry_point_args = vec![ - stark_felt!(u32::try_from(n).unwrap()), // events_number. - stark_felt!(0_u32), // keys length. - stark_felt!(0_u32), // data length. + felt!(u32::try_from(n).unwrap()), // events_number. + felt!(0_u32), // keys length. + felt!(0_u32), // data length. ]; let calldata = create_calldata(contract_address, "test_emit_events", &entry_point_args); account_invoke_tx(invoke_tx_args! { diff --git a/crates/blockifier/src/transaction/transaction_utils.rs b/crates/blockifier/src/transaction/transaction_utils.rs index 98922d5e93..1f4edc40c4 100644 --- a/crates/blockifier/src/transaction/transaction_utils.rs +++ b/crates/blockifier/src/transaction/transaction_utils.rs @@ -13,8 +13,11 @@ pub fn verify_contract_class_version( declare_version: TransactionVersion, ) -> Result<(), TransactionExecutionError> { match contract_class { + // TODO: Make TransactionVersion an enum and use match here. ContractClass::V0(_) => { - if let TransactionVersion::ZERO | TransactionVersion::ONE = declare_version { + if declare_version == TransactionVersion::ZERO + || declare_version == TransactionVersion::ONE + { return Ok(()); } Err(TransactionExecutionError::ContractClassVersionMismatch { @@ -23,7 +26,9 @@ pub fn verify_contract_class_version( }) } ContractClass::V1(_) => { - if let TransactionVersion::TWO | TransactionVersion::THREE = declare_version { + if declare_version == TransactionVersion::TWO + || declare_version == TransactionVersion::THREE + { return Ok(()); } Err(TransactionExecutionError::ContractClassVersionMismatch { diff --git a/crates/blockifier/src/transaction/transactions.rs b/crates/blockifier/src/transaction/transactions.rs index bf177a520d..0c064b78f3 100644 --- a/crates/blockifier/src/transaction/transactions.rs +++ b/crates/blockifier/src/transaction/transactions.rs @@ -4,11 +4,11 @@ use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use starknet_api::calldata; use starknet_api::core::{ClassHash, ContractAddress, Nonce}; use starknet_api::deprecated_contract_class::EntryPointType; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::{ AccountDeploymentData, Calldata, ContractAddressSalt, DeclareTransactionV2, DeclareTransactionV3, Fee, TransactionHash, TransactionSignature, TransactionVersion, }; +use starknet_types_core::felt::Felt; use crate::abi::abi_utils::selector_from_name; use crate::context::{BlockContext, TransactionContext}; @@ -473,9 +473,9 @@ impl L1HandlerTransaction { pub fn create_for_testing(l1_fee: Fee, contract_address: ContractAddress) -> Self { let calldata = calldata![ - StarkFelt::from_u128(0x123), // from_address. - StarkFelt::from_u128(0x876), // key. - StarkFelt::from_u128(0x44) // value. + Felt::from(0x123), // from_address. + Felt::from(0x876), // key. + Felt::from(0x44) // value. ]; let tx = starknet_api::transaction::L1HandlerTransaction { version: TransactionVersion::ZERO, diff --git a/crates/blockifier/src/transaction/transactions_test.rs b/crates/blockifier/src/transaction/transactions_test.rs index b6aa67fb8e..c8d982a87d 100644 --- a/crates/blockifier/src/transaction/transactions_test.rs +++ b/crates/blockifier/src/transaction/transactions_test.rs @@ -2,8 +2,7 @@ use std::collections::{HashMap, HashSet}; use std::sync::Arc; use assert_matches::assert_matches; -use cairo_felt::Felt252; -use cairo_vm::vm::runners::builtin_runner::{HASH_BUILTIN_NAME, RANGE_CHECK_BUILTIN_NAME}; +use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use num_bigint::BigUint; use num_traits::Pow; @@ -12,13 +11,13 @@ use pretty_assertions::assert_eq; use rstest::{fixture, rstest}; use starknet_api::core::{ChainId, ClassHash, ContractAddress, EthAddress, Nonce, PatriciaKey}; use starknet_api::deprecated_contract_class::EntryPointType; -use starknet_api::hash::{StarkFelt, StarkHash}; use starknet_api::state::StorageKey; use starknet_api::transaction::{ Calldata, EventContent, EventData, EventKey, Fee, L2ToL1Payload, ResourceBoundsMapping, TransactionSignature, TransactionVersion, }; -use starknet_api::{calldata, class_hash, contract_address, patricia_key, stark_felt}; +use starknet_api::{calldata, class_hash, contract_address, felt, patricia_key}; +use starknet_types_core::felt::Felt; use strum::IntoEnumIterator; use crate::abi::abi_utils::{ @@ -32,7 +31,6 @@ use crate::execution::call_info::{ }; use crate::execution::entry_point::{CallEntryPoint, CallType}; use crate::execution::errors::{ConstructorEntryPointExecutionError, EntryPointExecutionError}; -use crate::execution::execution_utils::{felt_to_stark_felt, stark_felt_to_felt}; use crate::execution::syscalls::hint_processor::{EmitEventError, L1_GAS, L2_GAS}; use crate::execution::syscalls::SyscallSelector; use crate::fee::actual_cost::TransactionReceipt; @@ -112,7 +110,7 @@ fn expected_validate_call_info( ) -> Option { let retdata = match cairo_version { CairoVersion::Cairo0 => Retdata::default(), - CairoVersion::Cairo1 => retdata!(stark_felt!(constants::VALIDATE_RETDATA)), + CairoVersion::Cairo1 => retdata!(felt!(constants::VALIDATE_RETDATA)), }; // Extra range check in regular (invoke) validate call, due to passing the calldata as an array. let n_range_checks = match cairo_version { @@ -135,10 +133,7 @@ fn expected_validate_call_info( let resources = ExecutionResources { n_steps, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([( - RANGE_CHECK_BUILTIN_NAME.to_string(), - n_range_checks, - )]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, n_range_checks)]), } .filter_unused_builtins(); @@ -172,9 +167,9 @@ fn expected_fee_transfer_call_info( let expected_sequencer_address = block_context.block_info.sequencer_address; let expected_sequencer_address_felt = *expected_sequencer_address.0.key(); // The least significant 128 bits of the expected amount transferred. - let lsb_expected_amount = stark_felt!(actual_fee.0); + let lsb_expected_amount = felt!(actual_fee.0); // The most significant 128 bits of the expected amount transferred. - let msb_expected_amount = stark_felt!(0_u8); + let msb_expected_amount = felt!(0_u8); let storage_address = block_context.chain_info.fee_token_address(fee_type); let expected_fee_transfer_call = CallEntryPoint { class_hash: Some(expected_fee_token_class_hash), @@ -214,18 +209,13 @@ fn expected_fee_transfer_call_info( Some(CallInfo { call: expected_fee_transfer_call, execution: CallExecution { - retdata: retdata![stark_felt!(constants::FELT_TRUE)], + retdata: retdata![felt!(constants::FELT_TRUE)], events: vec![expected_fee_transfer_event], ..Default::default() }, resources: Prices::FeeTransfer(account_address, *fee_type).into(), // We read sender and recipient balance - Uint256(BALANCE, 0) then Uint256(0, 0). - storage_read_values: vec![ - stark_felt!(BALANCE), - stark_felt!(0_u8), - stark_felt!(0_u8), - stark_felt!(0_u8), - ], + storage_read_values: vec![felt!(BALANCE), felt!(0_u8), felt!(0_u8), felt!(0_u8)], accessed_storage_keys: HashSet::from_iter(vec![ sender_balance_key_low, sender_balance_key_high, @@ -268,8 +258,8 @@ fn validate_final_balances( ) { // Expected balances of account and sequencer, per fee type. let (expected_sequencer_balance_eth, expected_sequencer_balance_strk) = match fee_type { - FeeType::Eth => (stark_felt!(expected_actual_fee.0), StarkFelt::ZERO), - FeeType::Strk => (StarkFelt::ZERO, stark_felt!(expected_actual_fee.0)), + FeeType::Eth => (felt!(expected_actual_fee.0), Felt::ZERO), + FeeType::Strk => (Felt::ZERO, felt!(expected_actual_fee.0)), }; let mut expected_account_balance_eth = initial_account_balance_eth; let mut expected_account_balance_strk = initial_account_balance_strk; @@ -287,10 +277,10 @@ fn validate_final_balances( (strk_fee_token_address, expected_account_balance_strk, expected_sequencer_balance_strk), ] { let account_balance = state.get_storage_at(fee_address, erc20_account_balance_key).unwrap(); - assert_eq!(account_balance, stark_felt!(expected_account_balance)); + assert_eq!(account_balance, felt!(expected_account_balance)); assert_eq!( state.get_storage_at(fee_address, test_erc20_sequencer_balance_key()).unwrap(), - stark_felt!(expected_sequencer_balance) + expected_sequencer_balance ); } } @@ -311,11 +301,7 @@ fn add_kzg_da_resources_to_resources_mapping( target.n_steps += os_kzg_da_resources.n_steps; os_kzg_da_resources.builtin_instance_counter.into_iter().for_each(|(key, value)| { - target - .builtin_instance_counter - .entry(key.to_string()) - .and_modify(|v| *v += value) - .or_insert(value); + target.builtin_instance_counter.entry(key).and_modify(|v| *v += value).or_insert(value); }); } @@ -325,7 +311,7 @@ fn add_kzg_da_resources_to_resources_mapping( resources: &get_syscall_resources(SyscallSelector::CallContract) + &ExecutionResources { n_steps: 62, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([(RANGE_CHECK_BUILTIN_NAME.to_string(), 1)]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, 1)]), }, validate_gas_consumed: 0, execute_gas_consumed: 0, @@ -337,7 +323,7 @@ fn add_kzg_da_resources_to_resources_mapping( resources: &get_syscall_resources(SyscallSelector::CallContract) + &ExecutionResources { n_steps: 219, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([(RANGE_CHECK_BUILTIN_NAME.to_string(), 8)]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, 8)]), }, validate_gas_consumed: 4740, // The gas consumption results from parsing the input // arguments. @@ -401,7 +387,7 @@ fn test_invoke_tx( ); // Build expected execute call info. - let expected_return_result_calldata = vec![stark_felt!(2_u8)]; + let expected_return_result_calldata = vec![felt!(2_u8)]; let expected_return_result_call = CallEntryPoint { entry_point_selector: selector_from_name("return_result"), class_hash: Some(test_contract.get_class_hash()), @@ -513,9 +499,9 @@ fn verify_storage_after_invoke_advanced_operations( state: &mut CachedState, contract_address: ContractAddress, account_address: ContractAddress, - index: StarkFelt, - expected_counters: [StarkFelt; 2], - expected_ec_point: [StarkFelt; 2], + index: Felt, + expected_counters: [Felt; 2], + expected_ec_point: [Felt; 2], expected_nonce: Nonce, ) { // Verify the two_counters values in storage. @@ -552,7 +538,7 @@ fn test_invoke_tx_advanced_operations( &mut test_state(&block_context.chain_info, BALANCE, &[(account, 1), (test_contract, 1)]); let account_address = account.get_instance_address(0); let contract_address = test_contract.get_instance_address(0); - let index = stark_felt!(123_u32); + let index = felt!(123_u32); let base_tx_args = invoke_tx_args! { resource_bounds: max_resource_bounds, sender_address: account_address, @@ -561,7 +547,7 @@ fn test_invoke_tx_advanced_operations( // Invoke advance_counter function. let mut nonce_manager = NonceManager::default(); let counter_diffs = [101_u32, 102_u32]; - let initial_counters = [stark_felt!(counter_diffs[0]), stark_felt!(counter_diffs[1])]; + let initial_counters = [felt!(counter_diffs[0]), felt!(counter_diffs[1])]; let calldata_args = vec![index, initial_counters[0], initial_counters[1]]; let account_tx = account_invoke_tx(invoke_tx_args! { @@ -573,7 +559,7 @@ fn test_invoke_tx_advanced_operations( account_tx.execute(state, block_context, true, true).unwrap(); let next_nonce = nonce_manager.next(account_address); - let initial_ec_point = [StarkFelt::ZERO, StarkFelt::ZERO]; + let initial_ec_point = [Felt::ZERO, Felt::ZERO]; verify_storage_after_invoke_advanced_operations( state, contract_address, @@ -586,12 +572,8 @@ fn test_invoke_tx_advanced_operations( // Invoke call_xor_counters function. let xor_values = [31_u32, 32_u32]; - let calldata_args = vec![ - *contract_address.0.key(), - index, - stark_felt!(xor_values[0]), - stark_felt!(xor_values[1]), - ]; + let calldata_args = + vec![*contract_address.0.key(), index, felt!(xor_values[0]), felt!(xor_values[1])]; let account_tx = account_invoke_tx(invoke_tx_args! { nonce: next_nonce, @@ -601,10 +583,8 @@ fn test_invoke_tx_advanced_operations( }); account_tx.execute(state, block_context, true, true).unwrap(); - let expected_counters = [ - stark_felt!(counter_diffs[0] ^ xor_values[0]), - stark_felt!(counter_diffs[1] ^ xor_values[1]), - ]; + let expected_counters = + [felt!(counter_diffs[0] ^ xor_values[0]), felt!(counter_diffs[1] ^ xor_values[1])]; let next_nonce = nonce_manager.next(account_address); verify_storage_after_invoke_advanced_operations( state, @@ -626,18 +606,18 @@ fn test_invoke_tx_advanced_operations( account_tx.execute(state, block_context, true, true).unwrap(); let expected_ec_point = [ - StarkFelt::new([ - 0x05, 0x07, 0xF8, 0x28, 0xEA, 0xE0, 0x0C, 0x08, 0xED, 0x10, 0x60, 0x5B, 0xAA, 0xD4, - 0x80, 0xB7, 0x4B, 0x0E, 0x9B, 0x61, 0x9C, 0x1A, 0x2C, 0x53, 0xFB, 0x75, 0x86, 0xE3, - 0xEE, 0x1A, 0x82, 0xBA, - ]) - .unwrap(), - StarkFelt::new([ - 0x05, 0x43, 0x9A, 0x5D, 0xC0, 0x8C, 0xC1, 0x35, 0x64, 0x11, 0xA4, 0x57, 0x8F, 0x50, - 0x71, 0x54, 0xB4, 0x84, 0x7B, 0xAA, 0x73, 0x70, 0x68, 0x17, 0x1D, 0xFA, 0x6C, 0x8A, - 0xB3, 0x49, 0x9D, 0x8B, - ]) - .unwrap(), + Felt::from_bytes_be(&[ + 0x05_u8, 0x07_u8, 0xF8_u8, 0x28_u8, 0xEA_u8, 0xE0_u8, 0x0C_u8, 0x08_u8, 0xED_u8, + 0x10_u8, 0x60_u8, 0x5B_u8, 0xAA_u8, 0xD4_u8, 0x80_u8, 0xB7_u8, 0x4B_u8, 0x0E_u8, + 0x9B_u8, 0x61_u8, 0x9C_u8, 0x1A_u8, 0x2C_u8, 0x53_u8, 0xFB_u8, 0x75_u8, 0x86_u8, + 0xE3_u8, 0xEE_u8, 0x1A_u8, 0x82_u8, 0xBA_u8, + ]), + Felt::from_bytes_be(&[ + 0x05_u8, 0x43_u8, 0x9A_u8, 0x5D_u8, 0xC0_u8, 0x8C_u8, 0xC1_u8, 0x35_u8, 0x64_u8, + 0x11_u8, 0xA4_u8, 0x57_u8, 0x8F_u8, 0x50_u8, 0x71_u8, 0x54_u8, 0xB4_u8, 0x84_u8, + 0x7B_u8, 0xAA_u8, 0x73_u8, 0x70_u8, 0x68_u8, 0x17_u8, 0x1D_u8, 0xFA_u8, 0x6C_u8, + 0x8A_u8, 0xB3_u8, 0x49_u8, 0x9D_u8, 0x8B_u8, + ]), ]; let next_nonce = nonce_manager.next(account_address); verify_storage_after_invoke_advanced_operations( @@ -651,8 +631,8 @@ fn test_invoke_tx_advanced_operations( ); // Invoke add_signature_to_counters function. - let signature_values = [Felt252::from(200_u64), Felt252::from(300_u64)]; - let signature = TransactionSignature(signature_values.iter().map(felt_to_stark_felt).collect()); + let signature_values = [Felt::from(200_u64), Felt::from(300_u64)]; + let signature = TransactionSignature(signature_values.into()); let account_tx = account_invoke_tx(invoke_tx_args! { signature, @@ -664,12 +644,8 @@ fn test_invoke_tx_advanced_operations( account_tx.execute(state, block_context, true, true).unwrap(); let expected_counters = [ - felt_to_stark_felt( - &(stark_felt_to_felt(expected_counters[0]) + signature_values[0].clone()), - ), - felt_to_stark_felt( - &(stark_felt_to_felt(expected_counters[1]) + signature_values[1].clone()), - ), + (expected_counters[0] + signature_values[0]), + (expected_counters[1] + signature_values[1]), ]; let next_nonce = nonce_manager.next(account_address); verify_storage_after_invoke_advanced_operations( @@ -683,11 +659,11 @@ fn test_invoke_tx_advanced_operations( ); // Invoke send_message function that send a message to L1. - let to_address = Felt252::from(85); + let to_address = Felt::from(85); let account_tx = account_invoke_tx(invoke_tx_args! { nonce: next_nonce, calldata: - create_calldata(contract_address, "send_message", &[felt_to_stark_felt(&to_address)]), + create_calldata(contract_address, "send_message", &[to_address]), ..base_tx_args }); let execution_info = account_tx.execute(state, block_context, true, true).unwrap(); @@ -704,8 +680,8 @@ fn test_invoke_tx_advanced_operations( let expected_msg = OrderedL2ToL1Message { order: 0, message: MessageToL1 { - to_address: EthAddress::try_from(felt_to_stark_felt(&to_address)).unwrap(), - payload: L2ToL1Payload(vec![stark_felt!(12_u32), stark_felt!(34_u32)]), + to_address: EthAddress::try_from(to_address).unwrap(), + payload: L2ToL1Payload(vec![felt!(12_u32), felt!(34_u32)]), }, }; assert_eq!( @@ -729,8 +705,9 @@ fn test_state_get_fee_token_balance( let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let state = &mut test_state(chain_info, BALANCE, &[(account, 1), (test_contract, 1)]); let account_address = account.get_instance_address(0); - let (mint_high, mint_low) = (stark_felt!(54_u8), stark_felt!(39_u8)); - let recipient = stark_felt!(10_u8); + let (mint_high, mint_low) = (felt!(54_u8), felt!(39_u8)); + let recipient_int = 10_u8; + let recipient = felt!(recipient_int); let fee_token_address = chain_info.fee_token_address(&fee_type); // Give the account mint privileges. @@ -756,7 +733,7 @@ fn test_state_get_fee_token_balance( // Get balance from state, and validate. let (low, high) = - state.get_fee_token_balance(contract_address!(recipient), fee_token_address).unwrap(); + state.get_fee_token_balance(contract_address!(recipient_int), fee_token_address).unwrap(); assert_eq!(low, mint_low); assert_eq!(high, mint_high); @@ -1079,23 +1056,27 @@ fn declare_validate_callinfo( /// Returns the expected used L1 gas and blob gas (according to use_kzg_da flag) due to execution of /// a declare transaction. fn declare_expected_state_changes_count(version: TransactionVersion) -> StateChangesCount { - match version { - TransactionVersion::ZERO => StateChangesCount { + // TODO: Make TransactionVersion an enum and use match here. + if version == TransactionVersion::ZERO { + StateChangesCount { n_storage_updates: 1, // Sender balance. ..StateChangesCount::default() - }, - TransactionVersion::ONE => StateChangesCount { + } + } else if version == TransactionVersion::ONE { + StateChangesCount { n_storage_updates: 1, // Sender balance. n_modified_contracts: 1, // Nonce. ..StateChangesCount::default() - }, - TransactionVersion::TWO | TransactionVersion::THREE => StateChangesCount { + } + } else if version == TransactionVersion::TWO || version == TransactionVersion::THREE { + StateChangesCount { n_storage_updates: 1, // Sender balance. n_modified_contracts: 1, // Nonce. n_compiled_class_hash_updates: 1, // Also set compiled class hash. ..StateChangesCount::default() - }, - version => panic!("Unsupported version {version:?}."), + } + } else { + panic!("Unsupported version {version:?}.") } } @@ -1267,7 +1248,7 @@ fn test_deploy_account_tx( .set_storage_at( chain_info.fee_token_address(&fee_type), deployed_account_balance_key, - stark_felt!(BALANCE), + felt!(BALANCE), ) .unwrap(); } @@ -1423,7 +1404,7 @@ fn test_fail_deploy_account_undeclared_class_hash(block_context: BlockContext) { .set_storage_at( chain_info.fee_token_address(&FeeType::Eth), get_fee_token_var_address(deploy_account.contract_address), - stark_felt!(BALANCE), + felt!(BALANCE), ) .unwrap(); @@ -1498,9 +1479,9 @@ fn test_validate_accounts_tx( // Try to call another contract (forbidden). let account_tx = create_account_tx_for_validate_test_nonce_0(FaultyAccountTxCreatorArgs { scenario: CALL_CONTRACT, - additional_data: Some(vec![stark_felt!("0x1991")]), /* Some address different than - * the address of - * faulty_account. */ + additional_data: Some(vec![felt!("0x1991")]), /* Some address different than + * the address of + * faulty_account. */ contract_address_salt: salt_manager.next_salt(), ..default_args }); @@ -1584,7 +1565,7 @@ fn test_validate_accounts_tx( FaultyAccountTxCreatorArgs { scenario: GET_BLOCK_NUMBER, contract_address_salt: salt_manager.next_salt(), - additional_data: Some(vec![StarkFelt::from(CURRENT_BLOCK_NUMBER_FOR_VALIDATE)]), + additional_data: Some(vec![Felt::from(CURRENT_BLOCK_NUMBER_FOR_VALIDATE)]), declared_contract: Some(FeatureContract::AccountWithoutValidations( declared_contract_cairo_version, )), @@ -1601,7 +1582,7 @@ fn test_validate_accounts_tx( FaultyAccountTxCreatorArgs { scenario: GET_BLOCK_TIMESTAMP, contract_address_salt: salt_manager.next_salt(), - additional_data: Some(vec![StarkFelt::from(CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE)]), + additional_data: Some(vec![Felt::from(CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE)]), declared_contract: Some(FeatureContract::Empty(declared_contract_cairo_version)), ..default_args }, @@ -1619,9 +1600,9 @@ fn test_validate_accounts_tx( scenario: GET_EXECUTION_INFO, contract_address_salt: salt_manager.next_salt(), additional_data: Some(vec![ - StarkFelt::from(CURRENT_BLOCK_NUMBER_FOR_VALIDATE), - StarkFelt::from(CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE), - StarkFelt::from(0_u64), // Sequencer address for validate. + Felt::from(CURRENT_BLOCK_NUMBER_FOR_VALIDATE), + Felt::from(CURRENT_BLOCK_TIMESTAMP_FOR_VALIDATE), + Felt::from(0_u64), // Sequencer address for validate. ]), declared_contract: Some(FeatureContract::Empty(declared_contract_cairo_version)), ..default_args @@ -1675,51 +1656,51 @@ fn test_only_query_flag( account_balance, &[(account, 1), (test_contract, 1)], ); - let mut version = Felt252::from(3_u8); + let mut version = Felt::from(3_u8); if only_query { - let query_version_base = Pow::pow(Felt252::from(2_u8), constants::QUERY_VERSION_BASE_BIT); + let query_version_base = Felt::TWO.pow(constants::QUERY_VERSION_BASE_BIT); version += query_version_base; } let sender_address = account.get_instance_address(0); let test_contract_address = test_contract.get_instance_address(0); let expected_tx_info = vec![ - felt_to_stark_felt(&version), // Transaction version. - *sender_address.0.key(), // Account address. - StarkFelt::ZERO, // Max fee. - StarkFelt::ZERO, // Signature. - StarkFelt::ZERO, // Transaction hash. - stark_felt!(&*ChainId(CHAIN_ID_NAME.to_string()).as_hex()), // Chain ID. - StarkFelt::ZERO, // Nonce. + version, // Transaction version. + *sender_address.0.key(), // Account address. + Felt::ZERO, // Max fee. + Felt::ZERO, // Signature. + Felt::ZERO, // Transaction hash. + felt!(&*ChainId::Other(CHAIN_ID_NAME.to_string()).as_hex()), // Chain ID. + Felt::ZERO, // Nonce. ]; let expected_resource_bounds = vec![ - StarkFelt::TWO, // Length of ResourceBounds array. - stark_felt!(L1_GAS), // Resource. - stark_felt!(MAX_L1_GAS_AMOUNT), // Max amount. - stark_felt!(MAX_L1_GAS_PRICE), // Max price per unit. - stark_felt!(L2_GAS), // Resource. - StarkFelt::ZERO, // Max amount. - StarkFelt::ZERO, // Max price per unit. + Felt::TWO, // Length of ResourceBounds array. + felt!(L1_GAS), // Resource. + felt!(MAX_L1_GAS_AMOUNT), // Max amount. + felt!(MAX_L1_GAS_PRICE), // Max price per unit. + felt!(L2_GAS), // Resource. + Felt::ZERO, // Max amount. + Felt::ZERO, // Max price per unit. ]; let expected_unsupported_fields = vec![ - StarkFelt::ZERO, // Tip. - StarkFelt::ZERO, // Paymaster data. - StarkFelt::ZERO, // Nonce DA. - StarkFelt::ZERO, // Fee DA. - StarkFelt::ZERO, // Account data. + Felt::ZERO, // Tip. + Felt::ZERO, // Paymaster data. + Felt::ZERO, // Nonce DA. + Felt::ZERO, // Fee DA. + Felt::ZERO, // Account data. ]; let entry_point_selector = selector_from_name("test_get_execution_info"); let expected_call_info = vec![ - *sender_address.0.key(), // Caller address. - *test_contract_address.0.key(), // Storage address. - stark_felt!(entry_point_selector.0), // Entry point selector. + *sender_address.0.key(), // Caller address. + *test_contract_address.0.key(), // Storage address. + entry_point_selector.0, // Entry point selector. ]; let expected_block_info = [ - stark_felt!(CURRENT_BLOCK_NUMBER), // Block number. - stark_felt!(CURRENT_BLOCK_TIMESTAMP), // Block timestamp. - stark_felt!(TEST_SEQUENCER_ADDRESS), // Sequencer address. + felt!(CURRENT_BLOCK_NUMBER), // Block number. + felt!(CURRENT_BLOCK_TIMESTAMP), // Block timestamp. + felt!(TEST_SEQUENCER_ADDRESS), // Sequencer address. ]; let calldata_len = expected_block_info.len() + expected_tx_info.len() @@ -1731,7 +1712,7 @@ fn test_only_query_flag( entry_point_selector.0, // EP selector. // TODO(Ori, 1/2/2024): Write an indicative expect message explaining why the conversion // works. - stark_felt!(u64::try_from(calldata_len).expect("Failed to convert usize to u64.")), /* Calldata length. */ + felt!(u64::try_from(calldata_len).expect("Failed to convert usize to u64.")), /* Calldata length. */ ]; let execute_calldata = Calldata( [ @@ -1796,7 +1777,7 @@ fn test_l1_handler(#[values(false, true)] use_kzg_da: bool) { resources: ExecutionResources { n_steps: 154, n_memory_holes: 0, - builtin_instance_counter: HashMap::from([(RANGE_CHECK_BUILTIN_NAME.to_string(), 6)]), + builtin_instance_counter: HashMap::from([(BuiltinName::range_check, 6)]), }, accessed_storage_keys: HashSet::from_iter(vec![accessed_storage_key]), ..Default::default() @@ -1822,11 +1803,11 @@ fn test_l1_handler(#[values(false, true)] use_kzg_da: bool) { let mut expected_execution_resources = ExecutionResources { builtin_instance_counter: HashMap::from([ - (HASH_BUILTIN_NAME.to_string(), 11 + payload_size), + (BuiltinName::pedersen, 11 + payload_size), ( - RANGE_CHECK_BUILTIN_NAME.to_string(), + BuiltinName::range_check, get_tx_resources(TransactionType::L1Handler).builtin_instance_counter - [&RANGE_CHECK_BUILTIN_NAME.to_string()] + [&BuiltinName::range_check] + 6, ), ]), @@ -1891,13 +1872,7 @@ fn test_l1_handler(#[values(false, true)] use_kzg_da: bool) { // set the storage back to 0, so the fee will also include the storage write. // TODO(Meshi, 15/6/2024): change the l1_handler_set_value cairo function to // always uptade the storage instad. - state - .set_storage_at( - contract_address, - StorageKey::try_from(key).unwrap(), - StarkFelt::from_u128(0), - ) - .unwrap(); + state.set_storage_at(contract_address, StorageKey::try_from(key).unwrap(), Felt::ZERO).unwrap(); let tx_no_fee = L1HandlerTransaction::create_for_testing(Fee(0), contract_address); let error = tx_no_fee.execute(state, block_context, true, true).unwrap_err(); // Today, we check that the paid_fee is positive, no matter what was the actual fee. @@ -1929,7 +1904,7 @@ fn test_execute_tx_with_invalid_transaction_version( let calldata = create_calldata( test_contract.get_instance_address(0), "test_tx_version", - &[stark_felt!(invalid_version)], + &[felt!(invalid_version)], ); let account_tx = account_invoke_tx(invoke_tx_args! { resource_bounds: max_resource_bounds, @@ -1960,29 +1935,29 @@ fn max_event_data() -> usize { #[rstest] #[case::positive_flow( - vec![stark_felt!(1_u16); max_event_keys()], - vec![stark_felt!(2_u16); max_event_data()], + vec![felt!(1_u16); max_event_keys()], + vec![felt!(2_u16); max_event_data()], max_n_emitted_events(), None)] #[case::exceeds_max_number_of_events( - vec![stark_felt!(1_u16)], - vec![stark_felt!(2_u16)], + vec![felt!(1_u16)], + vec![felt!(2_u16)], max_n_emitted_events() + 1, Some(EmitEventError::ExceedsMaxNumberOfEmittedEvents { n_emitted_events: max_n_emitted_events() + 1, max_n_emitted_events: max_n_emitted_events(), }))] #[case::exceeds_max_number_of_keys( - vec![stark_felt!(3_u16); max_event_keys() + 1], - vec![stark_felt!(4_u16)], + vec![felt!(3_u16); max_event_keys() + 1], + vec![felt!(4_u16)], 1, Some(EmitEventError::ExceedsMaxKeysLength{ keys_length: max_event_keys() + 1, max_keys_length: max_event_keys(), }))] #[case::exceeds_data_length( - vec![stark_felt!(5_u16)], - vec![stark_felt!(6_u16); max_event_data() + 1], + vec![felt!(5_u16)], + vec![felt!(6_u16); max_event_data() + 1], 1, Some(EmitEventError::ExceedsMaxDataLength{ data_length: max_event_data() + 1, @@ -1991,8 +1966,8 @@ fn max_event_data() -> usize { fn test_emit_event_exceeds_limit( block_context: BlockContext, max_resource_bounds: ResourceBoundsMapping, - #[case] event_keys: Vec, - #[case] event_data: Vec, + #[case] event_keys: Vec, + #[case] event_data: Vec, #[case] n_emitted_events: usize, #[case] expected_error: Option, #[values(CairoVersion::Cairo0, CairoVersion::Cairo1)] cairo_version: CairoVersion, @@ -2007,17 +1982,11 @@ fn test_emit_event_exceeds_limit( ); let calldata = [ - vec![stark_felt!( - u16::try_from(n_emitted_events).expect("Failed to convert usize to u16.") - )] - .to_owned(), - vec![stark_felt!( - u16::try_from(event_keys.len()).expect("Failed to convert usize to u16.") - )], + vec![felt!(u16::try_from(n_emitted_events).expect("Failed to convert usize to u16."))] + .to_owned(), + vec![felt!(u16::try_from(event_keys.len()).expect("Failed to convert usize to u16."))], event_keys.clone(), - vec![stark_felt!( - u16::try_from(event_data.len()).expect("Failed to convert usize to u16.") - )], + vec![felt!(u16::try_from(event_data.len()).expect("Failed to convert usize to u16."))], event_data.clone(), ] .concat(); @@ -2025,9 +1994,7 @@ fn test_emit_event_exceeds_limit( [ vec![test_contract.get_instance_address(0).into()], vec![selector_from_name("test_emit_events").0], - vec![stark_felt!( - u16::try_from(calldata.len()).expect("Failed to convert usize to u16.") - )], + vec![felt!(u16::try_from(calldata.len()).expect("Failed to convert usize to u16."))], calldata.clone(), ] .concat() @@ -2054,6 +2021,6 @@ fn test_emit_event_exceeds_limit( #[test] fn test_balance_print() { - let int = balance_to_big_uint(&StarkFelt::from(16_u64), &StarkFelt::from(1_u64)); + let int = balance_to_big_uint(&Felt::from(16_u64), &Felt::from(1_u64)); assert!(format!("{}", int) == (BigUint::from(u128::MAX) + BigUint::from(17_u128)).to_string()); } diff --git a/crates/blockifier/src/versioned_constants.rs b/crates/blockifier/src/versioned_constants.rs index a44b05296a..b36032b5b9 100644 --- a/crates/blockifier/src/versioned_constants.rs +++ b/crates/blockifier/src/versioned_constants.rs @@ -3,7 +3,7 @@ use std::io; use std::path::Path; use std::sync::Arc; -use cairo_vm::vm::runners::builtin_runner; +use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use indexmap::{IndexMap, IndexSet}; use num_rational::Ratio; @@ -125,34 +125,16 @@ impl VersionedConstants { pub fn create_for_account_testing() -> Self { let vm_resource_fee_cost = Arc::new(HashMap::from([ (crate::abi::constants::N_STEPS_RESOURCE.to_string(), ResourceCost::from_integer(1)), + (BuiltinName::pedersen.to_str_with_suffix().to_string(), ResourceCost::from_integer(1)), ( - cairo_vm::vm::runners::builtin_runner::HASH_BUILTIN_NAME.to_string(), - ResourceCost::from_integer(1), - ), - ( - cairo_vm::vm::runners::builtin_runner::RANGE_CHECK_BUILTIN_NAME.to_string(), - ResourceCost::from_integer(1), - ), - ( - cairo_vm::vm::runners::builtin_runner::SIGNATURE_BUILTIN_NAME.to_string(), - ResourceCost::from_integer(1), - ), - ( - cairo_vm::vm::runners::builtin_runner::BITWISE_BUILTIN_NAME.to_string(), - ResourceCost::from_integer(1), - ), - ( - cairo_vm::vm::runners::builtin_runner::POSEIDON_BUILTIN_NAME.to_string(), - ResourceCost::from_integer(1), - ), - ( - cairo_vm::vm::runners::builtin_runner::OUTPUT_BUILTIN_NAME.to_string(), - ResourceCost::from_integer(1), - ), - ( - cairo_vm::vm::runners::builtin_runner::EC_OP_BUILTIN_NAME.to_string(), + BuiltinName::range_check.to_str_with_suffix().to_string(), ResourceCost::from_integer(1), ), + (BuiltinName::ecdsa.to_str_with_suffix().to_string(), ResourceCost::from_integer(1)), + (BuiltinName::bitwise.to_str_with_suffix().to_string(), ResourceCost::from_integer(1)), + (BuiltinName::poseidon.to_str_with_suffix().to_string(), ResourceCost::from_integer(1)), + (BuiltinName::output.to_str_with_suffix().to_string(), ResourceCost::from_integer(1)), + (BuiltinName::ec_op.to_str_with_suffix().to_string(), ResourceCost::from_integer(1)), ])); Self { vm_resource_fee_cost, ..Self::create_for_testing() } @@ -163,34 +145,13 @@ impl VersionedConstants { pub fn create_float_for_testing() -> Self { let vm_resource_fee_cost = Arc::new(HashMap::from([ (crate::abi::constants::N_STEPS_RESOURCE.to_string(), ResourceCost::new(25, 10000)), - ( - cairo_vm::vm::runners::builtin_runner::HASH_BUILTIN_NAME.to_string(), - ResourceCost::new(8, 100), - ), - ( - cairo_vm::vm::runners::builtin_runner::RANGE_CHECK_BUILTIN_NAME.to_string(), - ResourceCost::new(4, 100), - ), - ( - cairo_vm::vm::runners::builtin_runner::SIGNATURE_BUILTIN_NAME.to_string(), - ResourceCost::new(512, 100), - ), - ( - cairo_vm::vm::runners::builtin_runner::BITWISE_BUILTIN_NAME.to_string(), - ResourceCost::new(16, 100), - ), - ( - cairo_vm::vm::runners::builtin_runner::POSEIDON_BUILTIN_NAME.to_string(), - ResourceCost::new(8, 100), - ), - ( - cairo_vm::vm::runners::builtin_runner::OUTPUT_BUILTIN_NAME.to_string(), - ResourceCost::from_integer(0), - ), - ( - cairo_vm::vm::runners::builtin_runner::EC_OP_BUILTIN_NAME.to_string(), - ResourceCost::new(256, 100), - ), + (BuiltinName::pedersen.to_str_with_suffix().to_string(), ResourceCost::new(8, 100)), + (BuiltinName::range_check.to_str_with_suffix().to_string(), ResourceCost::new(4, 100)), + (BuiltinName::ecdsa.to_str_with_suffix().to_string(), ResourceCost::new(512, 100)), + (BuiltinName::bitwise.to_str_with_suffix().to_string(), ResourceCost::new(16, 100)), + (BuiltinName::poseidon.to_str_with_suffix().to_string(), ResourceCost::new(8, 100)), + (BuiltinName::output.to_str_with_suffix().to_string(), ResourceCost::from_integer(0)), + (BuiltinName::ec_op.to_str_with_suffix().to_string(), ResourceCost::new(256, 100)), ])); Self { vm_resource_fee_cost, ..Self::create_for_testing() } @@ -312,17 +273,20 @@ impl OsResources { } } - let known_builtin_names: HashSet<&str> = HashSet::from([ - builtin_runner::OUTPUT_BUILTIN_NAME, - builtin_runner::HASH_BUILTIN_NAME, - builtin_runner::RANGE_CHECK_BUILTIN_NAME, - builtin_runner::SIGNATURE_BUILTIN_NAME, - builtin_runner::BITWISE_BUILTIN_NAME, - builtin_runner::EC_OP_BUILTIN_NAME, - builtin_runner::KECCAK_BUILTIN_NAME, - builtin_runner::POSEIDON_BUILTIN_NAME, - builtin_runner::SEGMENT_ARENA_BUILTIN_NAME, - ]); + let known_builtin_names: HashSet<&str> = [ + BuiltinName::output, + BuiltinName::pedersen, + BuiltinName::range_check, + BuiltinName::ecdsa, + BuiltinName::bitwise, + BuiltinName::ec_op, + BuiltinName::keccak, + BuiltinName::poseidon, + BuiltinName::segment_arena, + ] + .iter() + .map(|builtin| builtin.to_str_with_suffix()) + .collect(); let execution_resources = self .execute_txs_inner @@ -338,7 +302,7 @@ impl OsResources { let builtin_names = execution_resources.flat_map(|resources| resources.builtin_instance_counter.keys()); for builtin_name in builtin_names { - if !(known_builtin_names.contains(builtin_name.as_str())) { + if !(known_builtin_names.contains(builtin_name.to_str_with_suffix())) { return Err(DeserializationError::custom(format!( "ValidationError: unknown os resource {builtin_name}" ))); diff --git a/crates/blockifier/src/versioned_constants_test.rs b/crates/blockifier/src/versioned_constants_test.rs index d449dff959..5fd6be69b5 100644 --- a/crates/blockifier/src/versioned_constants_test.rs +++ b/crates/blockifier/src/versioned_constants_test.rs @@ -1,3 +1,4 @@ +use cairo_vm::types::builtin_name::BuiltinName; use glob::glob; use pretty_assertions::assert_eq; @@ -125,8 +126,8 @@ fn test_default_values() { let expected_declare_resources = ExecutionResources { n_steps: 2839, builtin_instance_counter: HashMap::from([ - ("pedersen_builtin".to_string(), 16), - ("range_check_builtin".to_string(), 63), + (BuiltinName::pedersen, 16), + (BuiltinName::range_check, 63), ]), ..Default::default() }; diff --git a/crates/native_blockifier/Cargo.toml b/crates/native_blockifier/Cargo.toml index 6ac4da1a35..b6085a5dee 100644 --- a/crates/native_blockifier/Cargo.toml +++ b/crates/native_blockifier/Cargo.toml @@ -38,6 +38,7 @@ pyo3 = { workspace = true, features = ["hashbrown", "num-bigint"] } pyo3-log.workspace = true serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true, features = ["arbitrary_precision"] } +starknet-types-core.workspace = true starknet_api = { workspace = true, features = ["testing"] } thiserror.workspace = true diff --git a/crates/native_blockifier/src/errors.rs b/crates/native_blockifier/src/errors.rs index 82da5bced2..66bb70c249 100644 --- a/crates/native_blockifier/src/errors.rs +++ b/crates/native_blockifier/src/errors.rs @@ -7,10 +7,12 @@ use blockifier::transaction::errors::{ }; use blockifier::transaction::transaction_types::TransactionType; use cairo_vm::types::errors::program_errors::ProgramError; +use num_bigint::BigUint; use pyo3::create_exception; use pyo3::exceptions::PyException; use pyo3::prelude::*; use starknet_api::StarknetApiError; +use starknet_types_core::felt::FromStrError; use thiserror::Error; pub type NativeBlockifierResult = Result; @@ -85,11 +87,15 @@ pub enum NativeBlockifierInputError { #[error(transparent)] ProgramError(#[from] ProgramError), #[error(transparent)] + PyFeltParseError(#[from] FromStrError), + #[error(transparent)] StarknetApiError(#[from] StarknetApiError), + #[error("Unknown builtin: {0}.")] + UnknownBuiltin(String), #[error("Contract class of version {version} is unsupported.")] UnsupportedContractClassVersion { version: usize }, #[error("Transaction of type {tx_type:?} is unsupported in version {version}.")] - UnsupportedTransactionVersion { tx_type: TransactionType, version: usize }, + UnsupportedTransactionVersion { tx_type: TransactionType, version: BigUint }, } #[derive(Debug, Error)] diff --git a/crates/native_blockifier/src/py_block_executor.rs b/crates/native_blockifier/src/py_block_executor.rs index 13096b37d8..25fe55b7b5 100644 --- a/crates/native_blockifier/src/py_block_executor.rs +++ b/crates/native_blockifier/src/py_block_executor.rs @@ -17,8 +17,8 @@ use pyo3::{FromPyObject, PyAny, Python}; use serde::Serialize; use starknet_api::block::BlockNumber; use starknet_api::core::{ChainId, ContractAddress}; -use starknet_api::hash::StarkFelt; use starknet_api::transaction::Fee; +use starknet_types_core::felt::Felt; use crate::errors::{NativeBlockifierError, NativeBlockifierResult}; use crate::py_objects::{PyBouncerConfig, PyConcurrencyConfig, PyVersionedConstantsOverrides}; @@ -108,7 +108,7 @@ impl PyBlockExecutor { log::debug!("Initialized Block Executor."); Self { - bouncer_config: bouncer_config.into(), + bouncer_config: bouncer_config.try_into().expect("Failed to parse bouncer config."), tx_executor_config: TransactionExecutorConfig { concurrency_config: concurrency_config.into(), }, @@ -306,7 +306,7 @@ impl PyBlockExecutor { let mut block_id_fixed_bytes = [0_u8; 32]; block_id_fixed_bytes.copy_from_slice(&block_id_bytes); - Ok(Some(PyFelt(StarkFelt::new(block_id_fixed_bytes)?))) + Ok(Some(PyFelt(Felt::from_bytes_be(&block_id_fixed_bytes)))) } #[pyo3(signature = (source_block_number))] @@ -442,7 +442,7 @@ impl TryFrom for ChainInfo { impl Default for PyOsConfig { fn default() -> Self { Self { - chain_id: ChainId("".to_string()), + chain_id: ChainId::Other("".to_string()), deprecated_fee_token_address: Default::default(), fee_token_address: Default::default(), } diff --git a/crates/native_blockifier/src/py_block_executor_test.rs b/crates/native_blockifier/src/py_block_executor_test.rs index bbeb3daa88..ffc5908ad8 100644 --- a/crates/native_blockifier/src/py_block_executor_test.rs +++ b/crates/native_blockifier/src/py_block_executor_test.rs @@ -6,9 +6,9 @@ use blockifier::state::state_api::StateReader; use cached::Cached; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use pretty_assertions::assert_eq; -use starknet_api::class_hash; use starknet_api::core::ClassHash; -use starknet_api::hash::{StarkFelt, StarkHash}; +use starknet_api::{class_hash, felt}; +use starknet_types_core::felt::Felt; use crate::py_block_executor::{PyBlockExecutor, PyGeneralConfig}; use crate::py_objects::PyConcurrencyConfig; @@ -73,7 +73,7 @@ fn get_block_id() { 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, ]; let max_class_hash_vec = Vec::from(max_class_hash); - let expected_max_class_hash_as_py_felt = PyFelt(StarkFelt::new(max_class_hash).unwrap()); + let expected_max_class_hash_as_py_felt = PyFelt(Felt::from_bytes_be(&max_class_hash)); let storage = MockStorage { block_number_to_class_hash: HashMap::from([(1138, max_class_hash_vec)]) }; diff --git a/crates/native_blockifier/src/py_declare.rs b/crates/native_blockifier/src/py_declare.rs index 8a4145e7ee..ff62737aab 100644 --- a/crates/native_blockifier/src/py_declare.rs +++ b/crates/native_blockifier/src/py_declare.rs @@ -9,6 +9,7 @@ use starknet_api::transaction::{ AccountDeploymentData, DeclareTransactionV0V1, DeclareTransactionV2, DeclareTransactionV3, Fee, PaymasterData, ResourceBoundsMapping, Tip, TransactionHash, TransactionSignature, }; +use starknet_types_core::felt::Felt; use crate::errors::{NativeBlockifierInputError, NativeBlockifierResult}; use crate::py_transaction::{PyClassInfo, PyDataAvailabilityMode, PyResourceBoundsMapping}; @@ -102,32 +103,29 @@ pub fn py_declare( py_tx: &PyAny, py_class_info: PyClassInfo, ) -> NativeBlockifierResult { - let version = usize::try_from(py_attr::(py_tx, "version")?.0)?; - let tx = match version { - 0 => { - let py_declare_tx: PyDeclareTransactionV0V1 = py_tx.extract()?; - let declare_tx = DeclareTransactionV0V1::try_from(py_declare_tx)?; - Ok(starknet_api::transaction::DeclareTransaction::V0(declare_tx)) - } - 1 => { - let py_declare_tx: PyDeclareTransactionV0V1 = py_tx.extract()?; - let declare_tx = DeclareTransactionV0V1::try_from(py_declare_tx)?; - Ok(starknet_api::transaction::DeclareTransaction::V1(declare_tx)) - } - 2 => { - let py_declare_tx: PyDeclareTransactionV2 = py_tx.extract()?; - let declare_tx = DeclareTransactionV2::try_from(py_declare_tx)?; - Ok(starknet_api::transaction::DeclareTransaction::V2(declare_tx)) - } - 3 => { - let py_declare_tx: PyDeclareTransactionV3 = py_tx.extract()?; - let declare_tx = DeclareTransactionV3::try_from(py_declare_tx)?; - Ok(starknet_api::transaction::DeclareTransaction::V3(declare_tx)) - } - _ => Err(NativeBlockifierInputError::UnsupportedTransactionVersion { + let version = py_attr::(py_tx, "version")?.0; + // TODO: Make TransactionVersion an enum and use match here. + let tx = if version == Felt::ZERO { + let py_declare_tx: PyDeclareTransactionV0V1 = py_tx.extract()?; + let declare_tx = DeclareTransactionV0V1::try_from(py_declare_tx)?; + Ok(starknet_api::transaction::DeclareTransaction::V0(declare_tx)) + } else if version == Felt::ONE { + let py_declare_tx: PyDeclareTransactionV0V1 = py_tx.extract()?; + let declare_tx = DeclareTransactionV0V1::try_from(py_declare_tx)?; + Ok(starknet_api::transaction::DeclareTransaction::V1(declare_tx)) + } else if version == Felt::TWO { + let py_declare_tx: PyDeclareTransactionV2 = py_tx.extract()?; + let declare_tx = DeclareTransactionV2::try_from(py_declare_tx)?; + Ok(starknet_api::transaction::DeclareTransaction::V2(declare_tx)) + } else if version == Felt::THREE { + let py_declare_tx: PyDeclareTransactionV3 = py_tx.extract()?; + let declare_tx = DeclareTransactionV3::try_from(py_declare_tx)?; + Ok(starknet_api::transaction::DeclareTransaction::V3(declare_tx)) + } else { + Err(NativeBlockifierInputError::UnsupportedTransactionVersion { tx_type: TransactionType::Declare, - version, - }), + version: version.to_biguint(), + }) }?; let tx_hash = TransactionHash(py_attr::(py_tx, "hash_value")?.0); let class_info = PyClassInfo::try_from(py_class_info, &tx)?; diff --git a/crates/native_blockifier/src/py_deploy_account.rs b/crates/native_blockifier/src/py_deploy_account.rs index faed5a5a78..06cad45d3f 100644 --- a/crates/native_blockifier/src/py_deploy_account.rs +++ b/crates/native_blockifier/src/py_deploy_account.rs @@ -9,6 +9,7 @@ use starknet_api::transaction::{ Calldata, ContractAddressSalt, DeployAccountTransactionV1, DeployAccountTransactionV3, Fee, PaymasterData, ResourceBoundsMapping, Tip, TransactionHash, TransactionSignature, }; +use starknet_types_core::felt::Felt; use crate::errors::{NativeBlockifierInputError, NativeBlockifierResult}; use crate::py_transaction::{PyDataAvailabilityMode, PyResourceBoundsMapping}; @@ -72,22 +73,21 @@ impl TryFrom for DeployAccountTransactionV3 { } pub fn py_deploy_account(py_tx: &PyAny) -> NativeBlockifierResult { - let version = usize::try_from(py_attr::(py_tx, "version")?.0)?; - let tx = match version { - 1 => { - let py_deploy_account_tx: PyDeployAccountTransactionV1 = py_tx.extract()?; - let deploy_account_tx = DeployAccountTransactionV1::from(py_deploy_account_tx); - Ok(starknet_api::transaction::DeployAccountTransaction::V1(deploy_account_tx)) - } - 3 => { - let py_deploy_account_tx: PyDeployAccountTransactionV3 = py_tx.extract()?; - let deploy_account_tx = DeployAccountTransactionV3::try_from(py_deploy_account_tx)?; - Ok(starknet_api::transaction::DeployAccountTransaction::V3(deploy_account_tx)) - } - _ => Err(NativeBlockifierInputError::UnsupportedTransactionVersion { + let version = py_attr::(py_tx, "version")?.0; + // TODO: Make TransactionVersion an enum and use match here. + let tx = if version == Felt::ONE { + let py_deploy_account_tx: PyDeployAccountTransactionV1 = py_tx.extract()?; + let deploy_account_tx = DeployAccountTransactionV1::from(py_deploy_account_tx); + Ok(starknet_api::transaction::DeployAccountTransaction::V1(deploy_account_tx)) + } else if version == Felt::THREE { + let py_deploy_account_tx: PyDeployAccountTransactionV3 = py_tx.extract()?; + let deploy_account_tx = DeployAccountTransactionV3::try_from(py_deploy_account_tx)?; + Ok(starknet_api::transaction::DeployAccountTransaction::V3(deploy_account_tx)) + } else { + Err(NativeBlockifierInputError::UnsupportedTransactionVersion { tx_type: TransactionType::DeployAccount, - version, - }), + version: version.to_biguint(), + }) }?; let tx_hash = TransactionHash(py_attr::(py_tx, "hash_value")?.0); diff --git a/crates/native_blockifier/src/py_invoke_function.rs b/crates/native_blockifier/src/py_invoke_function.rs index 00466ac35c..9e5a781ed7 100644 --- a/crates/native_blockifier/src/py_invoke_function.rs +++ b/crates/native_blockifier/src/py_invoke_function.rs @@ -11,6 +11,7 @@ use starknet_api::transaction::{ InvokeTransactionV3, PaymasterData, ResourceBoundsMapping, Tip, TransactionHash, TransactionSignature, }; +use starknet_types_core::felt::Felt; use crate::errors::{NativeBlockifierInputError, NativeBlockifierResult}; use crate::py_transaction::{PyDataAvailabilityMode, PyResourceBoundsMapping}; @@ -97,27 +98,25 @@ impl TryFrom for InvokeTransactionV3 { } pub fn py_invoke_function(py_tx: &PyAny) -> NativeBlockifierResult { - let version = usize::try_from(py_attr::(py_tx, "version")?.0)?; - let tx = match version { - 0 => { - let py_invoke_tx: PyInvokeTransactionV0 = py_tx.extract()?; - let invoke_tx = InvokeTransactionV0::try_from(py_invoke_tx)?; - Ok(starknet_api::transaction::InvokeTransaction::V0(invoke_tx)) - } - 1 => { - let py_invoke_tx: PyInvokeTransactionV1 = py_tx.extract()?; - let invoke_tx = InvokeTransactionV1::try_from(py_invoke_tx)?; - Ok(starknet_api::transaction::InvokeTransaction::V1(invoke_tx)) - } - 3 => { - let py_invoke_tx: PyInvokeTransactionV3 = py_tx.extract()?; - let invoke_tx = InvokeTransactionV3::try_from(py_invoke_tx)?; - Ok(starknet_api::transaction::InvokeTransaction::V3(invoke_tx)) - } - _ => Err(NativeBlockifierInputError::UnsupportedTransactionVersion { + let version = py_attr::(py_tx, "version")?.0; + // TODO: Make TransactionVersion an enum and use match here. + let tx = if version == Felt::ZERO { + let py_invoke_tx: PyInvokeTransactionV0 = py_tx.extract()?; + let invoke_tx = InvokeTransactionV0::try_from(py_invoke_tx)?; + Ok(starknet_api::transaction::InvokeTransaction::V0(invoke_tx)) + } else if version == Felt::ONE { + let py_invoke_tx: PyInvokeTransactionV1 = py_tx.extract()?; + let invoke_tx = InvokeTransactionV1::try_from(py_invoke_tx)?; + Ok(starknet_api::transaction::InvokeTransaction::V1(invoke_tx)) + } else if version == Felt::THREE { + let py_invoke_tx: PyInvokeTransactionV3 = py_tx.extract()?; + let invoke_tx = InvokeTransactionV3::try_from(py_invoke_tx)?; + Ok(starknet_api::transaction::InvokeTransaction::V3(invoke_tx)) + } else { + Err(NativeBlockifierInputError::UnsupportedTransactionVersion { tx_type: TransactionType::InvokeFunction, - version, - }), + version: version.to_biguint(), + }) }?; let tx_hash = TransactionHash(py_attr::(py_tx, "hash_value")?.0); diff --git a/crates/native_blockifier/src/py_objects.rs b/crates/native_blockifier/src/py_objects.rs index a8027c4059..cb2c0cdb67 100644 --- a/crates/native_blockifier/src/py_objects.rs +++ b/crates/native_blockifier/src/py_objects.rs @@ -2,12 +2,15 @@ use std::collections::HashMap; use blockifier::abi::constants; use blockifier::blockifier::config::ConcurrencyConfig; -use blockifier::bouncer::{BouncerConfig, BouncerWeights, BuiltinCount}; +use blockifier::bouncer::{BouncerConfig, BouncerWeights, BuiltinCount, HashMapWrapper}; use blockifier::versioned_constants::{VersionedConstants, VersionedConstantsOverrides}; +use cairo_vm::types::builtin_name::BuiltinName; use cairo_vm::vm::runners::cairo_runner::ExecutionResources; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; +use crate::errors::{NativeBlockifierError, NativeBlockifierInputError, NativeBlockifierResult}; + // From Rust to Python. #[pyclass] @@ -25,7 +28,11 @@ impl From for PyExecutionResources { fn from(resources: ExecutionResources) -> Self { Self { n_steps: resources.n_steps, - builtin_instance_counter: resources.builtin_instance_counter, + builtin_instance_counter: resources + .builtin_instance_counter + .iter() + .map(|(builtin, count)| (builtin.to_str_with_suffix().to_string(), *count)) + .collect(), n_memory_holes: resources.n_memory_holes, } } @@ -91,32 +98,51 @@ pub struct PyBouncerConfig { pub full_total_weights: HashMap, } -impl From for BouncerConfig { - fn from(py_bouncer_config: PyBouncerConfig) -> Self { - BouncerConfig { +impl TryFrom for BouncerConfig { + type Error = NativeBlockifierError; + fn try_from(py_bouncer_config: PyBouncerConfig) -> Result { + Ok(BouncerConfig { block_max_capacity: hash_map_into_bouncer_weights( py_bouncer_config.full_total_weights.clone(), - ), + )?, block_max_capacity_with_keccak: hash_map_into_bouncer_weights( py_bouncer_config.full_total_weights_with_keccak.clone(), - ), - } + )?, + }) } } -fn hash_map_into_bouncer_weights(mut data: HashMap) -> BouncerWeights { - BouncerWeights { - gas: data.remove(constants::L1_GAS_USAGE).expect("gas_weight must be present"), - n_steps: data.remove(constants::N_STEPS_RESOURCE).expect("n_steps must be present"), - message_segment_length: data - .remove(constants::MESSAGE_SEGMENT_LENGTH) - .expect("message_segment_length must be present"), - state_diff_size: data - .remove(constants::STATE_DIFF_SIZE) - .expect("state_diff_size must be present"), - n_events: data.remove(constants::N_EVENTS).expect("n_events must be present"), - builtin_count: BuiltinCount::from(data), +fn hash_map_into_builtin_count( + builtins: HashMap, +) -> Result { + let mut wrapper = HashMapWrapper::new(); + for (builtin_name, count) in builtins.iter() { + let builtin = BuiltinName::from_str_with_suffix(builtin_name) + .ok_or(NativeBlockifierInputError::UnknownBuiltin(builtin_name.clone()))?; + wrapper.insert(builtin, *count); } + Ok(wrapper.into()) +} + +fn hash_map_into_bouncer_weights( + mut data: HashMap, +) -> NativeBlockifierResult { + let gas = data.remove(constants::L1_GAS_USAGE).expect("gas_weight must be present"); + let n_steps = data.remove(constants::N_STEPS_RESOURCE).expect("n_steps must be present"); + let message_segment_length = data + .remove(constants::MESSAGE_SEGMENT_LENGTH) + .expect("message_segment_length must be present"); + let state_diff_size = + data.remove(constants::STATE_DIFF_SIZE).expect("state_diff_size must be present"); + let n_events = data.remove(constants::N_EVENTS).expect("n_events must be present"); + Ok(BouncerWeights { + gas, + n_steps, + message_segment_length, + state_diff_size, + n_events, + builtin_count: hash_map_into_builtin_count(data)?, + }) } #[derive(Debug, Default, FromPyObject)] diff --git a/crates/native_blockifier/src/py_test_utils.rs b/crates/native_blockifier/src/py_test_utils.rs index 7ec663512f..0e66423790 100644 --- a/crates/native_blockifier/src/py_test_utils.rs +++ b/crates/native_blockifier/src/py_test_utils.rs @@ -1,12 +1,10 @@ use std::collections::HashMap; -use std::convert::TryFrom; use blockifier::execution::contract_class::ContractClassV0; use blockifier::state::cached_state::CachedState; use blockifier::test_utils::dict_state_reader::DictStateReader; -use starknet_api::class_hash; use starknet_api::core::ClassHash; -use starknet_api::hash::StarkHash; +use starknet_api::{class_hash, felt}; pub const TOKEN_FOR_TESTING_CLASS_HASH: &str = "0x30"; // This package is run within the StarkWare repository build directory. diff --git a/crates/native_blockifier/src/py_utils.rs b/crates/native_blockifier/src/py_utils.rs index 1e258c71b7..21f2050ce7 100644 --- a/crates/native_blockifier/src/py_utils.rs +++ b/crates/native_blockifier/src/py_utils.rs @@ -1,33 +1,31 @@ -use std::convert::TryFrom; - use blockifier::blockifier::block::BlockNumberHashPair; use num_bigint::BigUint; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use starknet_api::core::{ChainId, ClassHash, CompiledClassHash, ContractAddress, EthAddress}; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; +use starknet_types_core::felt::Felt; -use crate::errors::NativeBlockifierResult; +use crate::errors::{NativeBlockifierInputError, NativeBlockifierResult}; #[derive(Clone, Copy, Debug, Default, Eq, FromPyObject, Hash, PartialEq)] -pub struct PyFelt(#[pyo3(from_py_with = "int_to_stark_felt")] pub StarkFelt); +pub struct PyFelt(#[pyo3(from_py_with = "int_to_stark_felt")] pub Felt); impl IntoPy for PyFelt { fn into_py(self, py: Python<'_>) -> PyObject { - BigUint::from_bytes_be(self.0.bytes()).into_py(py) + BigUint::from_bytes_be(self.0.to_bytes_be().as_slice()).into_py(py) } } impl From for PyFelt { fn from(value: u64) -> Self { - Self(StarkFelt::from(value)) + Self(Felt::from(value)) } } impl From for PyFelt { fn from(value: u8) -> Self { - Self(StarkFelt::from(value)) + Self(Felt::from(value)) } } @@ -43,7 +41,7 @@ impl From for PyFelt { // Pad with 12 zeros. let mut bytes = [0; 32]; bytes[12..32].copy_from_slice(&address_as_bytes); - PyFelt(StarkFelt::new(bytes).expect("Convert Ethereum address to StarkFelt")) + PyFelt(Felt::from_bytes_be(&bytes)) } } @@ -65,15 +63,15 @@ impl From for PyFelt { } } -fn int_to_stark_felt(int: &PyAny) -> PyResult { +fn int_to_stark_felt(int: &PyAny) -> PyResult { let biguint: BigUint = int.extract()?; biguint_to_felt(biguint).map_err(|e| PyValueError::new_err(e.to_string())) } -// TODO: Convert to a `TryFrom` cast and put in starknet-api (In StarkFelt). -pub fn biguint_to_felt(biguint: BigUint) -> NativeBlockifierResult { +// TODO: Convert to a `TryFrom` cast and put in starknet-api (In Felt). +pub fn biguint_to_felt(biguint: BigUint) -> NativeBlockifierResult { let biguint_hex = format!("{biguint:#x}"); - Ok(StarkFelt::try_from(&*biguint_hex)?) + Ok(Felt::from_hex(&biguint_hex).map_err(NativeBlockifierInputError::from)?) } pub fn to_py_vec(values: Vec, converter: F) -> Vec @@ -83,13 +81,13 @@ where values.into_iter().map(converter).collect() } -pub fn from_py_felts(py_felts: Vec) -> Vec { +pub fn from_py_felts(py_felts: Vec) -> Vec { py_felts.into_iter().map(|felt| felt.0).collect() } pub fn int_to_chain_id(int: &PyAny) -> PyResult { let biguint: BigUint = int.extract()?; - Ok(ChainId(String::from_utf8_lossy(&biguint.to_bytes_be()).into())) + Ok(ChainId::Other(String::from_utf8_lossy(&biguint.to_bytes_be()).into())) } pub fn py_attr(obj: &PyAny, attr: &str) -> NativeBlockifierResult diff --git a/crates/native_blockifier/src/state_readers/papyrus_state.rs b/crates/native_blockifier/src/state_readers/papyrus_state.rs index c80e5d7af8..463d242b0c 100644 --- a/crates/native_blockifier/src/state_readers/papyrus_state.rs +++ b/crates/native_blockifier/src/state_readers/papyrus_state.rs @@ -8,8 +8,8 @@ use papyrus_storage::state::StateStorageReader; use papyrus_storage::StorageReader; use starknet_api::block::BlockNumber; use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; -use starknet_api::hash::StarkFelt; use starknet_api::state::{StateNumber, StorageKey}; +use starknet_types_core::felt::Felt; #[cfg(test)] #[path = "papyrus_state_test.rs"] @@ -87,7 +87,7 @@ impl StateReader for PapyrusReader { &self, contract_address: ContractAddress, key: StorageKey, - ) -> StateResult { + ) -> StateResult { let state_number = StateNumber(self.latest_block); self.reader()? .get_state_reader() diff --git a/crates/native_blockifier/src/state_readers/papyrus_state_test.rs b/crates/native_blockifier/src/state_readers/papyrus_state_test.rs index afded114cc..5d3b536b66 100644 --- a/crates/native_blockifier/src/state_readers/papyrus_state_test.rs +++ b/crates/native_blockifier/src/state_readers/papyrus_state_test.rs @@ -8,12 +8,12 @@ use blockifier::state::state_api::StateReader; use blockifier::test_utils::contracts::FeatureContract; use blockifier::test_utils::{trivial_external_entry_point_new, CairoVersion}; use indexmap::IndexMap; +use papyrus_storage::class::ClassStorageWriter; use papyrus_storage::state::StateStorageWriter; use starknet_api::block::BlockNumber; -use starknet_api::hash::StarkFelt; use starknet_api::state::{StateDiff, StorageKey}; use starknet_api::transaction::Calldata; -use starknet_api::{calldata, stark_felt}; +use starknet_api::{calldata, felt}; use crate::state_readers::papyrus_state::PapyrusReader; @@ -23,16 +23,21 @@ fn test_entry_point_with_papyrus_state() -> papyrus_storage::StorageResult<()> { let test_contract = FeatureContract::TestContract(CairoVersion::Cairo0); let test_class_hash = test_contract.get_class_hash(); + let test_class = test_contract.get_deprecated_contract_class(); // Initialize Storage: add test contract and class. let deployed_contracts = IndexMap::from([(test_contract.get_instance_address(0), test_class_hash)]); - let state_diff = StateDiff { deployed_contracts, ..Default::default() }; + let state_diff = StateDiff { + deployed_contracts, + deprecated_declared_classes: IndexMap::from([(test_class_hash, test_class.clone())]), + ..Default::default() + }; - let deprecated_declared_classes = - IndexMap::from([(test_class_hash, test_contract.get_deprecated_contract_class())]); + let block_number = BlockNumber::default(); storage_writer .begin_rw_txn()? - .append_state_diff(BlockNumber::default(), state_diff, deprecated_declared_classes)? + .append_state_diff(block_number, state_diff.into())? + .append_classes(block_number, Default::default(), &[(test_class_hash, &test_class)])? .commit()?; // BlockNumber is 1 due to the initialization step above. @@ -45,8 +50,8 @@ fn test_entry_point_with_papyrus_state() -> papyrus_storage::StorageResult<()> { let mut state = CachedState::from(papyrus_reader); // Call entrypoint that want to write to storage, which updates the cached state's write cache. - let key = stark_felt!(1234_u16); - let value = stark_felt!(18_u8); + let key = felt!(1234_u16); + let value = felt!(18_u8); let calldata = calldata![key, value]; let entry_point_call = CallEntryPoint { calldata, diff --git a/crates/native_blockifier/src/state_readers/py_state_reader.rs b/crates/native_blockifier/src/state_readers/py_state_reader.rs index 169f84a845..61c7ba3213 100644 --- a/crates/native_blockifier/src/state_readers/py_state_reader.rs +++ b/crates/native_blockifier/src/state_readers/py_state_reader.rs @@ -3,8 +3,8 @@ use blockifier::state::errors::StateError; use blockifier::state::state_api::{StateReader, StateResult}; use pyo3::{FromPyObject, PyAny, PyErr, PyObject, PyResult, Python}; use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce}; -use starknet_api::hash::StarkFelt; use starknet_api::state::StorageKey; +use starknet_types_core::felt::Felt; use crate::errors::{ NativeBlockifierError, NativeBlockifierInputError, NativeBlockifierResult, @@ -35,7 +35,7 @@ impl StateReader for PyStateReader { &self, contract_address: ContractAddress, key: StorageKey, - ) -> StateResult { + ) -> StateResult { Python::with_gil(|py| -> PyResult { let args = (ON_CHAIN_STORAGE_DOMAIN, PyFelt::from(contract_address), PyFelt::from(key)); self.state_reader_proxy.as_ref(py).call_method1("get_storage_at", args)?.extract() diff --git a/crates/native_blockifier/src/storage.rs b/crates/native_blockifier/src/storage.rs index 8afe8e12af..d08a4b6383 100644 --- a/crates/native_blockifier/src/storage.rs +++ b/crates/native_blockifier/src/storage.rs @@ -4,6 +4,7 @@ use std::path::PathBuf; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use indexmap::IndexMap; +use papyrus_storage::class::ClassStorageWriter; use papyrus_storage::compiled_class::CasmStorageWriter; use papyrus_storage::header::{HeaderStorageReader, HeaderStorageWriter}; use papyrus_storage::state::{StateStorageReader, StateStorageWriter}; @@ -12,7 +13,7 @@ use starknet_api::block::{BlockHash, BlockHeader, BlockNumber}; use starknet_api::core::{ChainId, ClassHash, CompiledClassHash, ContractAddress}; use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContractClass; use starknet_api::hash::StarkHash; -use starknet_api::state::{ContractClass, StateDiff, StateNumber}; +use starknet_api::state::{ContractClass, StateDiff, StateNumber, ThinStateDiff}; use crate::errors::NativeBlockifierResult; use crate::py_state_diff::PyBlockInfo; @@ -93,7 +94,7 @@ impl Storage for PapyrusStorage { .reader() .begin_ro_txn()? .get_block_header(block_number)? - .map(|block_header| Vec::from(block_header.block_hash.0.bytes().as_slice())); + .map(|block_header| Vec::from(block_header.block_hash.0.to_bytes_be().as_slice())); Ok(block_hash) } @@ -196,12 +197,19 @@ impl Storage for PapyrusStorage { state_diff.declared_classes = declared_classes; state_diff.replaced_classes = replaced_classes; - let deployed_contract_class_definitions = - IndexMap::::new(); - append_txn = append_txn.append_state_diff( + let (thin_state_diff, declared_classes, deprecated_declared_classes) = + ThinStateDiff::from_state_diff(state_diff); + + append_txn = append_txn.append_state_diff(block_number, thin_state_diff)?.append_classes( block_number, - state_diff, - deployed_contract_class_definitions, + &declared_classes + .iter() + .map(|(class_hash, contract_class)| (*class_hash, contract_class)) + .collect::>(), + &deprecated_declared_classes + .iter() + .map(|(class_hash, contract_class)| (*class_hash, contract_class)) + .collect::>(), )?; let previous_block_id = previous_block_id.unwrap_or_else(|| PyFelt::from(GENESIS_BLOCK_ID));