From 9289516695eeda62af02bb6db1260bf8e6738935 Mon Sep 17 00:00:00 2001 From: codyx Date: Fri, 6 Dec 2024 11:49:29 +0400 Subject: [PATCH 01/75] Add account verification hints and utility functions - Introduced new hints for account verification: `HINT_N_ACCOUNTS`, `HINT_N_PROOFS`, `HINT_ACCOUNT_KEY`, and `HINT_GET_MPT_PROOF`. - Added utility functions for handling hexadecimal values in `utils/mod.rs`. - Updated `vars.rs` to include new identifiers related to accounts and proofs. - Created a new module structure for verifiers under `lib/verifiers/evm`. - Enhanced the hint processor to incorporate the new account verification hints. --- cairo_vm_hints/src/hint_processor/mod.rs | 4 + cairo_vm_hints/src/hints/lib/mod.rs | 2 + cairo_vm_hints/src/hints/lib/utils/mod.rs | 30 ++++ .../lib/verifiers/evm/account_verifier.rs | 151 ++++++++++++++++++ .../src/hints/lib/verifiers/evm/mod.rs | 1 + cairo_vm_hints/src/hints/lib/verifiers/mod.rs | 1 + cairo_vm_hints/src/hints/vars.rs | 9 ++ 7 files changed, 198 insertions(+) create mode 100644 cairo_vm_hints/src/hints/lib/utils/mod.rs create mode 100644 cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs create mode 100644 cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs create mode 100644 cairo_vm_hints/src/hints/lib/verifiers/mod.rs diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index c6c79adb..e5a8b4dc 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -88,6 +88,10 @@ impl CustomHintProcessor { hints.insert(lib::decoder::evm::has_type_prefix::HINT_HAS_TYPE_PREFIX.into(), lib::decoder::evm::has_type_prefix::hint_has_type_prefix); hints.insert(lib::decoder::evm::is_byzantium::HINT_IS_BYZANTIUM.into(), lib::decoder::evm::is_byzantium::hint_is_byzantium); hints.insert(lib::decoder::evm::v_is_encoded::HINT_V_IS_ENCODED.into(), lib::decoder::evm::v_is_encoded::hint_v_is_encoded); + hints.insert(lib::verifiers::evm::account_verifier::HINT_N_ACCOUNTS.into(), lib::verifiers::evm::account_verifier::hint_n_accounts); + hints.insert(lib::verifiers::evm::account_verifier::HINT_N_PROOFS.into(), lib::verifiers::evm::account_verifier::hint_n_proofs); + hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_KEY.into(), lib::verifiers::evm::account_verifier::hint_account_key); + hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), lib::verifiers::evm::account_verifier::hint_get_mpt_proof); hints.insert(lib::rlp::divmod::HINT_DIVMOD_RLP.into(), lib::rlp::divmod::hint_divmod_rlp); hints.insert(lib::rlp::divmod::HINT_DIVMOD_VALUE.into(), lib::rlp::divmod::hint_divmod_value); hints.insert(lib::rlp::item_type::HINT_IS_LONG.into(), lib::rlp::item_type::hint_is_long); diff --git a/cairo_vm_hints/src/hints/lib/mod.rs b/cairo_vm_hints/src/hints/lib/mod.rs index c9df03d0..a9177eaa 100644 --- a/cairo_vm_hints/src/hints/lib/mod.rs +++ b/cairo_vm_hints/src/hints/lib/mod.rs @@ -4,3 +4,5 @@ pub mod merkle; pub mod print; pub mod rlp; pub mod segments; +pub mod utils; +pub mod verifiers; diff --git a/cairo_vm_hints/src/hints/lib/utils/mod.rs b/cairo_vm_hints/src/hints/lib/utils/mod.rs new file mode 100644 index 00000000..7c850e61 --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/utils/mod.rs @@ -0,0 +1,30 @@ +use num_bigint::BigUint; +use num_traits::One; + +pub fn count_leading_zero_nibbles_from_hex(hex_str: &str) -> u32 { + let hex_str = hex_str.strip_prefix("0x").unwrap_or(hex_str); + hex_str.chars().take_while(|&c| c == '0').count() as u32 +} + +pub fn hex_to_int_array(hex_array: &[&str]) -> Vec { + hex_array + .iter() + .map(|x| u32::from_str_radix(x, 16).expect("Invalid hex input")) + .collect() +} + +pub fn nested_hex_to_int_array(nested_hex_array: &[&[&str]]) -> Vec { + nested_hex_array + .iter() + .flat_map(|x| hex_to_int_array(x)) + .collect() +} + +pub fn split_128(a: &BigUint) -> (BigUint, BigUint) { + // Create a mask for the lower 128 bits: (1 << 128) - 1 + let mask = (&BigUint::one() << 128) - BigUint::one(); + let low = a & &mask; // lower 128 bits + let high = a >> 128; // remaining higher bits + + (low, high) +} diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs new file mode 100644 index 00000000..a77df3f0 --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs @@ -0,0 +1,151 @@ +use cairo_vm::{ + hint_processor::builtin_hint_processor::{ + builtin_hint_processor_definition::HintProcessorData, + hint_utils::{ + get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, + }, + }, + types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use num_bigint::BigUint; +use num_traits::Num; +use std::collections::HashMap; + +use crate::hints::{ + lib::utils::{ + count_leading_zero_nibbles_from_hex, hex_to_int_array, nested_hex_to_int_array, split_128, + }, + vars, +}; + +pub const HINT_N_ACCOUNTS: &str = "ids.n_accounts = len(batch[\"accounts\"])"; + +pub fn hint_n_accounts( + vm: &mut VirtualMachine, + _exec_scope: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + // TODO: Retrieve `batch["accounts"]` when supported. + let n_accounts = Felt252::from(0); + + insert_value_from_var_name( + vars::ids::N_ACCOUNTS, + MaybeRelocatable::Int(n_accounts), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + ) +} + +pub const HINT_N_PROOFS: &str = "ids.n_proofs = len(account[\"proofs\"])"; + +pub fn hint_n_proofs( + vm: &mut VirtualMachine, + _exec_scope: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + // TODO: Retrieve `account["proofs"]` when supported. + let n_proofs = Felt252::from(0); + + insert_value_from_var_name( + vars::ids::N_PROOFS, + MaybeRelocatable::Int(n_proofs), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + ) +} + +pub const HINT_ACCOUNT_KEY: &str = "from tools.py.utils import split_128, count_leading_zero_nibbles_from_hex, hex_to_int_array, nested_hex_to_int_array account = batch[\"accounts\"][ids.index] ids.key_leading_zeros = count_leading_zero_nibbles_from_hex(account[\"account_key\"]) segments.write_arg(ids.address, hex_to_int_array(account[\"address\"])) (key_low, key_high) = split_128(int(account[\"account_key\"], \"16\")) ids.key.low = key_low ids.key.high = key_high"; + +pub fn hint_account_key( + vm: &mut VirtualMachine, + _exec_scope: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let _index = get_integer_from_var_name( + vars::ids::INDEX, + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + // TODO: Retrieve account_key from`batch["accounts"][index]` when supported. + let account_key = ""; + let _key_leading_zeros = count_leading_zero_nibbles_from_hex(account_key); + + let address_ptr = get_ptr_from_var_name( + vars::ids::ADDRESS, + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + + // TODO: Retrieve address from `batch["accounts"][index]["address"]` when supported. + let address_int_array = hex_to_int_array(&[]); + vm.write_arg(address_ptr, &address_int_array)?; + + let (key_low, key_high) = split_128(&BigUint::from_str_radix(account_key, 16).unwrap()); + insert_value_from_var_name( + vars::ids::KEY_LOW, + MaybeRelocatable::Int(Felt252::from(key_low)), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + insert_value_from_var_name( + vars::ids::KEY_HIGH, + MaybeRelocatable::Int(Felt252::from(key_high)), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + + Ok(()) +} + +pub const HINT_GET_MPT_PROOF: &str = "proof = account[\"proofs\"][ids.proof_idx] ids.block_number = proof[\"block_number\"] segments.write_arg(ids.mpt_proof, nested_hex_to_int_array(proof[\"proof\"])) segments.write_arg(ids.proof_bytes_len, proof[\"proof_bytes_len\"]) ids.proof_len = len(proof[\"proof\"])"; + +pub fn hint_get_mpt_proof( + vm: &mut VirtualMachine, + _exec_scope: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + // TODO: Retrieve `account["proofs"][proof_idx]` when supported. + let _proof = ""; + + // TODO: Retrieve `proof["block_number"]` when supported. + let block_number = Felt252::from(0); + insert_value_from_var_name( + vars::ids::BLOCK_NUMBER, + MaybeRelocatable::Int(block_number), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + + let mpt_proof_ptr = get_ptr_from_var_name( + vars::ids::MPT_PROOF, + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + let nested_hex_array: &[&[&str]] = &[&[]]; + vm.write_arg(mpt_proof_ptr, &nested_hex_to_int_array(nested_hex_array))?; + + let proof_bytes_len_ptr = get_ptr_from_var_name( + vars::ids::PROOF_BYTES_LEN, + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + // TODO: Retrieve `proof["proof_bytes_len"]` when supported. + vm.write_arg(proof_bytes_len_ptr, &0)?; + + Ok(()) +} diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs new file mode 100644 index 00000000..158bbb7c --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs @@ -0,0 +1 @@ +pub mod account_verifier; diff --git a/cairo_vm_hints/src/hints/lib/verifiers/mod.rs b/cairo_vm_hints/src/hints/lib/verifiers/mod.rs new file mode 100644 index 00000000..c469d0c8 --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/verifiers/mod.rs @@ -0,0 +1 @@ +pub mod evm; diff --git a/cairo_vm_hints/src/hints/vars.rs b/cairo_vm_hints/src/hints/vars.rs index c76cffc3..45b3e33e 100644 --- a/cairo_vm_hints/src/hints/vars.rs +++ b/cairo_vm_hints/src/hints/vars.rs @@ -7,18 +7,27 @@ pub mod scopes { } pub mod ids { + pub(crate) const ADDRESS: &str = "ids.address"; pub(crate) const ALL_ENCODINGS: &str = "all_encodings"; pub(crate) const BUILTIN_PARAMS: &str = "builtin_params"; pub(crate) const BUILTIN_PTRS: &str = "builtin_ptrs"; + pub(crate) const BLOCK_NUMBER: &str = "ids.block_number"; pub(crate) const COMPILED_CLASS: &str = "compiled_class"; pub(crate) const CURRENT_ITEM: &str = "ids.current_item"; pub(crate) const DEVISOR: &str = "ids.devisor"; pub(crate) const FIRST_BYTE: &str = "ids.first_byte"; pub(crate) const I: &str = "ids.i"; + pub(crate) const INDEX: &str = "ids.index"; pub(crate) const IS_LEFT_SMALLER: &str = "ids.is_left_smaller"; pub(crate) const IS_LONG: &str = "ids.is_long"; pub(crate) const ITEM_TYPE: &str = "ids.item_type"; + pub(crate) const KEY_LOW: &str = "ids.key_low"; + pub(crate) const KEY_HIGH: &str = "ids.key_high"; pub(crate) const LEFT: &str = "ids.left"; + pub(crate) const MPT_PROOF: &str = "ids.mpt_proof"; + pub(crate) const PROOF_BYTES_LEN: &str = "ids.proof_bytes_len"; + pub(crate) const N_ACCOUNTS: &str = "ids.n_accounts"; + pub(crate) const N_PROOFS: &str = "ids.n_proofs"; pub(crate) const N_BUILTINS: &str = "n_builtins"; pub(crate) const N_PROCESSED_WORDS: &str = "ids.n_processed_words"; pub(crate) const N_SELECTED_BUILTINS: &str = "n_selected_builtins"; From e79dc7de9c5c392cd046b5f86f223c5ce5412b86 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 9 Dec 2024 11:52:40 +0100 Subject: [PATCH 02/75] input types defs --- cairo_vm_hints/Cargo.toml | 4 ++- cairo_vm_hints/src/hint_processor/input.rs | 2 +- .../src/hint_processor/models/mod.rs | 20 +++++++++++++++ .../{models.rs => models/param.rs} | 7 ------ .../hint_processor/models/proofs/account.rs | 22 ++++++++++++++++ .../hint_processor/models/proofs/header.rs | 18 +++++++++++++ .../src/hint_processor/models/proofs/mmr.rs | 15 +++++++++++ .../src/hint_processor/models/proofs/mod.rs | 25 +++++++++++++++++++ .../src/hint_processor/models/proofs/mpt.rs | 11 ++++++++ .../hint_processor/models/proofs/receipt.rs | 15 +++++++++++ .../hint_processor/models/proofs/storage.rs | 24 ++++++++++++++++++ .../models/proofs/transaction.rs | 15 +++++++++++ .../hints/lib/contract_bootloader/params.rs | 2 +- 13 files changed, 170 insertions(+), 10 deletions(-) create mode 100644 cairo_vm_hints/src/hint_processor/models/mod.rs rename cairo_vm_hints/src/hint_processor/{models.rs => models/param.rs} (59%) create mode 100644 cairo_vm_hints/src/hint_processor/models/proofs/account.rs create mode 100644 cairo_vm_hints/src/hint_processor/models/proofs/header.rs create mode 100644 cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs create mode 100644 cairo_vm_hints/src/hint_processor/models/proofs/mod.rs create mode 100644 cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs create mode 100644 cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs create mode 100644 cairo_vm_hints/src/hint_processor/models/proofs/storage.rs create mode 100644 cairo_vm_hints/src/hint_processor/models/proofs/transaction.rs diff --git a/cairo_vm_hints/Cargo.toml b/cairo_vm_hints/Cargo.toml index 3376c55e..167741b7 100644 --- a/cairo_vm_hints/Cargo.toml +++ b/cairo_vm_hints/Cargo.toml @@ -24,4 +24,6 @@ starknet-types-core.workspace = true thiserror.workspace = true tiny-keccak.workspace = true tokio = { workspace = true } -strum_macros.workspace = true \ No newline at end of file +strum_macros.workspace = true +serde_with.workspace = true +starknet-core.workspace = true \ No newline at end of file diff --git a/cairo_vm_hints/src/hint_processor/input.rs b/cairo_vm_hints/src/hint_processor/input.rs index d415420b..abce7b6a 100644 --- a/cairo_vm_hints/src/hint_processor/input.rs +++ b/cairo_vm_hints/src/hint_processor/input.rs @@ -1,5 +1,5 @@ use super::{ - models::{HDPDryRunInput, Param}, + models::{param::Param, HDPDryRunInput}, CustomHintProcessor, }; use crate::hints::vars; diff --git a/cairo_vm_hints/src/hint_processor/models/mod.rs b/cairo_vm_hints/src/hint_processor/models/mod.rs new file mode 100644 index 00000000..9de2f91a --- /dev/null +++ b/cairo_vm_hints/src/hint_processor/models/mod.rs @@ -0,0 +1,20 @@ +pub mod param; +pub mod proofs; + +use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; +use param::Param; +use proofs::Proofs; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct HDPDryRunInput { + pub params: Vec, + pub compiled_class: CasmContractClass, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct HDPInput { + pub proofs: Proofs, + pub params: Vec, + pub compiled_class: CasmContractClass, +} diff --git a/cairo_vm_hints/src/hint_processor/models.rs b/cairo_vm_hints/src/hint_processor/models/param.rs similarity index 59% rename from cairo_vm_hints/src/hint_processor/models.rs rename to cairo_vm_hints/src/hint_processor/models/param.rs index ab11a28c..b8708973 100644 --- a/cairo_vm_hints/src/hint_processor/models.rs +++ b/cairo_vm_hints/src/hint_processor/models/param.rs @@ -1,4 +1,3 @@ -use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use cairo_vm::Felt252; use serde::{Deserialize, Serialize}; @@ -14,9 +13,3 @@ pub enum Visibility { Public, Private, } - -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -pub struct HDPDryRunInput { - pub params: Vec, - pub compiled_class: CasmContractClass, -} diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/account.rs b/cairo_vm_hints/src/hint_processor/models/proofs/account.rs new file mode 100644 index 00000000..0d1cca3c --- /dev/null +++ b/cairo_vm_hints/src/hint_processor/models/proofs/account.rs @@ -0,0 +1,22 @@ +use super::mpt::MPTProof; +use alloy::primitives::{keccak256, Address, B256}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +pub struct Account { + pub address: Address, + pub account_key: B256, + pub proofs: Vec, +} + +impl Account { + pub fn new(address: Address, proofs: Vec) -> Self { + // TODO: actually this is account trie leaf to be more accurate + let account_trie_leaf = keccak256(address); + Account { + address, + account_key: account_trie_leaf, + proofs, + } + } +} diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/header.rs b/cairo_vm_hints/src/hint_processor/models/proofs/header.rs new file mode 100644 index 00000000..6226e6b6 --- /dev/null +++ b/cairo_vm_hints/src/hint_processor/models/proofs/header.rs @@ -0,0 +1,18 @@ +use alloy::primitives::Bytes; +use cairo_vm::Felt252; +use serde::{Deserialize, Serialize}; +use serde_with::serde_as; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +#[serde_as] +pub struct HeaderProof { + pub leaf_idx: u64, + #[serde_as(as = "Vec")] + pub mmr_path: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +pub struct Header { + pub rlp: Vec, + pub proof: HeaderProof, +} diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs b/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs new file mode 100644 index 00000000..9a16924e --- /dev/null +++ b/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs @@ -0,0 +1,15 @@ +use cairo_vm::Felt252; +use serde::{Deserialize, Serialize}; +use serde_with::serde_as; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +#[serde_as] +pub struct MmrMeta { + pub id: u64, + pub size: u64, + #[serde_as(as = "starknet_core::serde::unsigned_field_element::UfeHex")] + pub root: Felt252, + pub chain_id: u64, + #[serde_as(as = "Vec")] + pub peaks: Vec, +} diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mod.rs b/cairo_vm_hints/src/hint_processor/models/proofs/mod.rs new file mode 100644 index 00000000..e3150e6d --- /dev/null +++ b/cairo_vm_hints/src/hint_processor/models/proofs/mod.rs @@ -0,0 +1,25 @@ +pub mod account; +pub mod header; +pub mod mmr; +pub mod mpt; +pub mod receipt; +pub mod storage; +pub mod transaction; + +use account::Account; +use header::Header; +use mmr::MmrMeta; +use receipt::Receipt; +use serde::{Deserialize, Serialize}; +use storage::Storage; +use transaction::Transaction; + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub struct Proofs { + pub mmr_meta: Vec, + pub headers: Vec
, + pub accounts: Vec, + pub storages: Vec, + pub transactions: Vec, + pub transaction_receipts: Vec, +} diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs b/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs new file mode 100644 index 00000000..cc6fbfd9 --- /dev/null +++ b/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs @@ -0,0 +1,11 @@ +use cairo_vm::Felt252; +use serde::{Deserialize, Serialize}; +use serde_with::serde_as; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +#[serde_as] +pub struct MPTProof { + pub block_number: u64, + #[serde_as(as = "starknet_core::serde::unsigned_field_element::UfeHex")] + pub proof: Vec, +} diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs b/cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs new file mode 100644 index 00000000..18f5cebc --- /dev/null +++ b/cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs @@ -0,0 +1,15 @@ +use super::mpt::MPTProof; +use alloy::primitives::U256; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +pub struct Receipt { + pub key: U256, + pub proofs: Vec, +} + +impl Receipt { + pub fn new(key: U256, proofs: Vec) -> Self { + Self { key, proofs } + } +} diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs b/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs new file mode 100644 index 00000000..2137b0fa --- /dev/null +++ b/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs @@ -0,0 +1,24 @@ +use super::mpt::MPTProof; +use alloy::primitives::{keccak256, Address, StorageKey, B256}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +pub struct Storage { + pub address: Address, + pub slot: B256, + pub storage_key: StorageKey, + pub proofs: Vec, +} + +impl Storage { + pub fn new(address: Address, slot: B256, proofs: Vec) -> Self { + // TODO: actually this is storage leaf. slot == storage key + let storage_trie_leaf = keccak256(slot); + Storage { + address, + slot, + storage_key: storage_trie_leaf, + proofs, + } + } +} diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/transaction.rs b/cairo_vm_hints/src/hint_processor/models/proofs/transaction.rs new file mode 100644 index 00000000..0cca9801 --- /dev/null +++ b/cairo_vm_hints/src/hint_processor/models/proofs/transaction.rs @@ -0,0 +1,15 @@ +use super::mpt::MPTProof; +use alloy::primitives::U256; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +pub struct Transaction { + pub key: U256, + pub proofs: Vec, +} + +impl Transaction { + pub fn new(key: U256, proofs: Vec) -> Self { + Self { key, proofs } + } +} diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/params.rs b/cairo_vm_hints/src/hints/lib/contract_bootloader/params.rs index 076a31cf..5ae0a305 100644 --- a/cairo_vm_hints/src/hints/lib/contract_bootloader/params.rs +++ b/cairo_vm_hints/src/hints/lib/contract_bootloader/params.rs @@ -1,4 +1,4 @@ -use crate::{hint_processor::models::Param, hints::vars}; +use crate::{hint_processor::models::param::Param, hints::vars}; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, From fde35c969149320e9428e568e0e77030d43d13ce Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 9 Dec 2024 13:02:08 +0100 Subject: [PATCH 03/75] fixes --- cairo_vm_hints/src/hint_processor/models/proofs/account.rs | 6 +++--- cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs | 6 +++--- cairo_vm_hints/src/hint_processor/models/proofs/storage.rs | 6 +++--- .../src/hint_processor/models/proofs/transaction.rs | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/account.rs b/cairo_vm_hints/src/hint_processor/models/proofs/account.rs index 0d1cca3c..4888a032 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/account.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/account.rs @@ -6,17 +6,17 @@ use serde::{Deserialize, Serialize}; pub struct Account { pub address: Address, pub account_key: B256, - pub proofs: Vec, + pub proof: MPTProof, } impl Account { - pub fn new(address: Address, proofs: Vec) -> Self { + pub fn new(address: Address, proof: MPTProof) -> Self { // TODO: actually this is account trie leaf to be more accurate let account_trie_leaf = keccak256(address); Account { address, account_key: account_trie_leaf, - proofs, + proof, } } } diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs b/cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs index 18f5cebc..69d70c89 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs @@ -5,11 +5,11 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] pub struct Receipt { pub key: U256, - pub proofs: Vec, + pub proof: MPTProof, } impl Receipt { - pub fn new(key: U256, proofs: Vec) -> Self { - Self { key, proofs } + pub fn new(key: U256, proof: MPTProof) -> Self { + Self { key, proof } } } diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs b/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs index 2137b0fa..4b1e51d2 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs @@ -7,18 +7,18 @@ pub struct Storage { pub address: Address, pub slot: B256, pub storage_key: StorageKey, - pub proofs: Vec, + pub proof: MPTProof, } impl Storage { - pub fn new(address: Address, slot: B256, proofs: Vec) -> Self { + pub fn new(address: Address, slot: B256, proof: MPTProof) -> Self { // TODO: actually this is storage leaf. slot == storage key let storage_trie_leaf = keccak256(slot); Storage { address, slot, storage_key: storage_trie_leaf, - proofs, + proof, } } } diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/transaction.rs b/cairo_vm_hints/src/hint_processor/models/proofs/transaction.rs index 0cca9801..8c7b522b 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/transaction.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/transaction.rs @@ -5,11 +5,11 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] pub struct Transaction { pub key: U256, - pub proofs: Vec, + pub proof: MPTProof, } impl Transaction { - pub fn new(key: U256, proofs: Vec) -> Self { - Self { key, proofs } + pub fn new(key: U256, proof: MPTProof) -> Self { + Self { key, proof } } } From 44afa9e1418dd45f177ac01deb2a1b91d1c06bec Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 9 Dec 2024 14:52:07 +0100 Subject: [PATCH 04/75] verifier hints refactors --- Cargo.lock | 258 +++++++++++++++++- Cargo.toml | 8 +- .../src/hint_processor/models/mod.rs | 2 +- .../src/hint_processor/models/proofs/mod.rs | 2 +- src/contract_bootloader/contract.cairo | 10 +- src/hdp.cairo | 129 ++------- src/utils/utils.cairo | 11 +- src/verifiers/evm/account_verifier.cairo | 2 +- src/verifiers/evm/block_tx_verifier.cairo | 2 +- src/verifiers/evm/receipt_verifier.cairo | 2 +- src/verifiers/evm/storage_item_verifier.cairo | 2 +- src/verifiers/mmr_verifier.cairo | 17 +- src/verifiers/verify.cairo | 6 +- tools/py/schema.py | 121 +++----- 14 files changed, 342 insertions(+), 230 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5d4b3239..d2c3009c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -597,7 +597,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90352f4cf78017905c3244f48b38fadc345970bbc9095087c0f985a580550488" dependencies = [ "alloy-json-rpc", - "base64", + "base64 0.22.1", "futures-util", "futures-utils-wasm", "serde", @@ -677,6 +677,21 @@ dependencies = [ "tracing", ] +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + [[package]] name = "anstream" version = "0.6.18" @@ -959,6 +974,18 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + [[package]] name = "base64" version = "0.22.1" @@ -1614,6 +1641,19 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "chrono" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "num-traits", + "serde", + "windows-targets 0.52.6", +] + [[package]] name = "clap" version = "4.5.21" @@ -1811,6 +1851,41 @@ dependencies = [ "typenum", ] +[[package]] +name = "darling" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.89", +] + +[[package]] +name = "darling_macro" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.89", +] + [[package]] name = "dashmap" version = "6.1.0" @@ -1841,6 +1916,16 @@ dependencies = [ "zeroize", ] +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", + "serde", +] + [[package]] name = "derivative" version = "2.2.0" @@ -2360,7 +2445,9 @@ dependencies = [ "rand", "serde", "serde_json", + "serde_with 3.11.0", "sha3", + "starknet-core", "starknet-crypto 0.7.3", "starknet-types-core", "strum_macros", @@ -2505,6 +2592,29 @@ dependencies = [ "tracing", ] +[[package]] +name = "iana-time-zone" +version = "0.1.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "1.5.0" @@ -2629,6 +2739,12 @@ version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "25a2bc672d1148e28034f176e01fffebb08b35768468cc954630da77a1449005" +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.0.3" @@ -3088,6 +3204,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + [[package]] name = "num-integer" version = "0.1.46" @@ -3422,6 +3544,12 @@ dependencies = [ "portable-atomic", ] +[[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.20" @@ -3672,7 +3800,7 @@ version = "0.12.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a77c62af46e79de0a562e1a9849205ffcb7fc1238876e9bd743357570e04046f" dependencies = [ - "base64", + "base64 0.22.1", "bytes", "futures-core", "futures-util", @@ -4101,6 +4229,17 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_json_pythonic" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62212da9872ca2a0cad0093191ee33753eddff9266cbbc1b4a602d13a3a768db" +dependencies = [ + "itoa", + "ryu", + "serde", +] + [[package]] name = "serde_spanned" version = "0.6.8" @@ -4122,6 +4261,63 @@ dependencies = [ "serde", ] +[[package]] +name = "serde_with" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07ff71d2c147a7b57362cead5e22f772cd52f6ab31cfcd9edcd7f6aeb2a0afbe" +dependencies = [ + "base64 0.13.1", + "chrono", + "hex", + "serde", + "serde_json", + "serde_with_macros 2.3.3", + "time", +] + +[[package]] +name = "serde_with" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28bdad6db2b8340e449f7108f020b3b092e8583a9e3fb82713e1d4e71fe817" +dependencies = [ + "base64 0.22.1", + "chrono", + "hex", + "indexmap 1.9.3", + "indexmap 2.6.0", + "serde", + "serde_derive", + "serde_json", + "serde_with_macros 3.11.0", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "881b6f881b17d13214e5d494c939ebab463d01264ce1811e9d4ac3a882e7695f" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.89", +] + +[[package]] +name = "serde_with_macros" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d846214a9854ef724f3da161b426242d8de7c1fc7de2f89bb1efcb154dca79d" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.89", +] + [[package]] name = "sha1" version = "0.10.6" @@ -4263,6 +4459,24 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" +[[package]] +name = "starknet-core" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d506e02a4083290d13b427dfe437fd95aa8b56315c455bb2f9cdeca76620d457" +dependencies = [ + "base64 0.21.7", + "crypto-bigint", + "hex", + "serde", + "serde_json", + "serde_json_pythonic", + "serde_with 2.3.3", + "sha3", + "starknet-crypto 0.7.3", + "starknet-types-core", +] + [[package]] name = "starknet-crypto" version = "0.6.2" @@ -4570,6 +4784,37 @@ dependencies = [ "num_cpus", ] +[[package]] +name = "time" +version = "0.3.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35e7868883861bd0e56d9ac6efcaaca0d6d5d82a2a7ec8209ff492c07cf37b21" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" + +[[package]] +name = "time-macros" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2834e6017e3e5e4b9834939793b282bc03b37a3336245fa820e35e233e2a85de" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tiny-keccak" version = "2.0.2" @@ -5093,6 +5338,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-registry" version = "0.2.0" diff --git a/Cargo.toml b/Cargo.toml index d7c72066..5b223cfe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,10 +19,12 @@ rand = "0.8" serde = "1.0.215" serde_json = "1.0.132" sha3 = "0.10.8" -starknet-crypto = "0.7.2" -starknet-types-core = "0.1.7" thiserror = "1.0.64" tiny-keccak = { version = "2.0.2", features = ["keccak"] } tokio = { version = "1.41.1", features = ["full"] } alloy-rlp = { version = "0.3.5", features = ["derive"] } -strum_macros = "0.26.4" \ No newline at end of file +strum_macros = "0.26.4" +serde_with = { version = "3.11.0", features = ["hex"] } +starknet-core = { version = "0.11.1", default-features = false } +starknet-crypto = { version = "0.7.1", default-features = false } +starknet-types-core = { version = "0.1.5", default-features = false } \ No newline at end of file diff --git a/cairo_vm_hints/src/hint_processor/models/mod.rs b/cairo_vm_hints/src/hint_processor/models/mod.rs index 9de2f91a..f6c722b4 100644 --- a/cairo_vm_hints/src/hint_processor/models/mod.rs +++ b/cairo_vm_hints/src/hint_processor/models/mod.rs @@ -14,7 +14,7 @@ pub struct HDPDryRunInput { #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct HDPInput { - pub proofs: Proofs, + pub proofs: Vec, pub params: Vec, pub compiled_class: CasmContractClass, } diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mod.rs b/cairo_vm_hints/src/hint_processor/models/proofs/mod.rs index e3150e6d..e79ca441 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/mod.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/mod.rs @@ -16,7 +16,7 @@ use transaction::Transaction; #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct Proofs { - pub mmr_meta: Vec, + pub mmr_meta: MmrMeta, pub headers: Vec
, pub accounts: Vec, pub storages: Vec, diff --git a/src/contract_bootloader/contract.cairo b/src/contract_bootloader/contract.cairo index 4a095f4c..749c807c 100644 --- a/src/contract_bootloader/contract.cairo +++ b/src/contract_bootloader/contract.cairo @@ -32,8 +32,11 @@ func compute_contract{ starknet_memorizer: DictAccess*, starknet_decoder_ptr: felt***, starknet_key_hasher_ptr: felt**, -}(inputs: felt*, inputs_len: felt) -> (result: Uint256, program_hash: felt) { +}() -> (result: Uint256, program_hash: felt) { alloc_locals; + + local params_len: felt; + let (params) = alloc(); local compiled_class: CompiledClass*; %{ @@ -41,6 +44,11 @@ func compute_contract{ ids.compiled_class = segments.gen_arg(get_compiled_class_struct(compiled_class=compiled_class)) %} + %{ + ids.params_len = len(params) + segments.write_arg(ids.params, [param.value for param in params]) + %} + let (builtin_costs: felt*) = alloc(); assert builtin_costs[0] = 0; assert builtin_costs[1] = 0; diff --git a/src/hdp.cairo b/src/hdp.cairo index deb0ba5c..e238fe5c 100644 --- a/src/hdp.cairo +++ b/src/hdp.cairo @@ -20,21 +20,18 @@ from src.verifiers.verify import run_state_verification from src.module import init_module from src.types import MMRMeta from src.utils.utils import write_output_ptr - from src.memorizers.evm.memorizer import EvmMemorizer from src.memorizers.starknet.memorizer import StarknetMemorizer from src.memorizers.bare import BareMemorizer, SingleBareMemorizer from src.memorizers.evm.state_access import EvmStateAccess, EvmDecoder from src.memorizers.starknet.state_access import StarknetStateAccess, StarknetDecoder - from src.utils.chain_info import Layout - -from packages.eth_essentials.lib.utils import pow2alloc251, write_felt_array_to_dict_keys - from src.utils.merkle import compute_tasks_hash, compute_tasks_root, compute_results_root from src.utils.chain_info import fetch_chain_info from src.contract_bootloader.contract import compute_contract +from packages.eth_essentials.lib.utils import pow2alloc251, write_felt_array_to_dict_keys + func main{ output_ptr: felt*, pedersen_ptr: HashBuiltin*, @@ -71,40 +68,23 @@ func run{ }() { alloc_locals; - // MMR Params - let (mmr_metas: MMRMeta*) = alloc(); + %{ + from tools.py.schema import HDPInput + run_input = HDPInput.Schema().load(program_input) + proofs = run_input.proofs + params = run_input.params + compiled_class = run_input.compiled_class + %} // Memorizers let (evm_memorizer, evm_memorizer_start) = EvmMemorizer.init(); let (starknet_memorizer, starknet_memorizer_start) = StarknetMemorizer.init(); - // Task Params - local tasks_len: felt; - let (results: Uint256*) = alloc(); - // Misc let pow2_array: felt* = pow2alloc251(); - %{ - from tools.py.utils import split_128, count_leading_zero_nibbles_from_hex - - debug_mode = False - def conditional_print(*args): - if debug_mode: - print(*args) - - def hex_to_int(x): - return int(x, 16) - - def hex_to_int_array(hex_array): - return [int(x, 16) for x in hex_array] - - def nested_hex_to_int_array(hex_array): - return [[int(x, 16) for x in y] for y in hex_array] - - ids.tasks_len = 1 - cairo_run_output_path = program_input["cairo_run_output_path"] - %} + // MMR Params + let (mmr_metas: MMRMeta*) = alloc(); let (local mmr_metas_len) = run_state_verification{ range_check_ptr=range_check_ptr, @@ -122,7 +102,7 @@ func run{ let starknet_key_hasher_ptr = StarknetStateAccess.init(); let starknet_decoder_ptr = StarknetDecoder.init(); - let (tasks_root, results_root, results, results_len) = compute_tasks{ + let (program_hash, results, results_len) = compute_tasks{ pedersen_ptr=pedersen_ptr, range_check_ptr=range_check_ptr, ecdsa_ptr=ecdsa_ptr, @@ -139,33 +119,6 @@ func run{ starknet_key_hasher_ptr=starknet_key_hasher_ptr, }(); - %{ - print(f"Tasks Root: {hex(ids.tasks_root.high * 2 ** 128 + ids.tasks_root.low)}") - print(f"Results Root: {hex(ids.results_root.high * 2 ** 128 + ids.results_root.low)}") - %} - - // Post Verification Checks: Ensure the roots match the expected roots - %{ - if "result_root" in program_input: - assert ids.results_root.high * 2 ** 128 + ids.results_root.low == hex_to_int(program_input["result_root"]), "Expected results root mismatch" - if "task_root" in program_input: - assert ids.tasks_root.high * 2 ** 128 + ids.tasks_root.low == hex_to_int(program_input["task_root"]), "Expected results root mismatch" - %} - - %{ - import json - - dictionary = dict() - dictionary["tasks_root"] = '0x' + (hex(ids.tasks_root.high * 2 ** 128 + ids.tasks_root.low)[2:].zfill(64)) - dictionary["results_root"] = '0x' + (hex(ids.results_root.high * 2 ** 128 + ids.results_root.low)[2:].zfill(64)) - results = list() - for i in range(ids.results_len): - results.append('0x' + (hex(memory[ids.results.address_ + i])[2:].zfill(64))) - dictionary["results"] = results - with open(cairo_run_output_path, 'w') as json_file: - json.dump(dictionary, json_file) - %} - // Post Verification Checks: Ensure dict consistency default_dict_finalize(evm_memorizer_start, evm_memorizer, BareMemorizer.DEFAULT_VALUE); default_dict_finalize( @@ -197,62 +150,12 @@ func compute_tasks{ starknet_memorizer: DictAccess*, starknet_decoder_ptr: felt***, starknet_key_hasher_ptr: felt**, -}() -> (tasks_root: Uint256, results_root: Uint256, results: Uint256*, results_len: felt) { +}() -> (program_hash: felt, result: Uint256) { alloc_locals; - let (results: Uint256*) = alloc(); - - // Task Params - local encoded_task_len: felt; - local task_bytes_len: felt; - let (encoded_task) = alloc(); - - local inputs_len: felt; - let (inputs) = alloc(); - - %{ - from tools.py.schema import Module, CompiledClass, Visibility - - # Load the module input - module_input = Module.Schema().load(program_input["tasks"][0]["context"]) - - compiled_class = module_input.module_class - - ids.task_bytes_len = module_input.task_bytes_len - ids.encoded_task_len = len(module_input.encoded_task) - - segments.write_arg(ids.encoded_task, module_input.encoded_task) - - inputs = [input.value for input in module_input.inputs] - ids.inputs_len = len(inputs) - segments.write_arg(ids.inputs, inputs) - %} - - let (local module_task) = init_module(encoded_task); - - %{ assert [int(input.value) for input in module_input.inputs if input.visibility == Visibility.PUBLIC] == [int(memory[ids.module_task.module_inputs + i]) for i in range(ids.module_task.module_inputs_len)] %} - - let (result, program_hash) = compute_contract(inputs, inputs_len); - assert results[0] = result; - - %{ - target_result = hex(ids.result.high * 2 ** 128 + ids.result.low) - print(f"Task Result: {target_result}") - %} - - let task_hash = compute_tasks_hash{ - range_check_ptr=range_check_ptr, bitwise_ptr=bitwise_ptr, keccak_ptr=keccak_ptr - }(encoded_task=encoded_task, task_bytes_len=task_bytes_len); - - let (flipped_task_hash) = uint256_reverse_endian(task_hash); - - let tasks_root = compute_tasks_root{ - range_check_ptr=range_check_ptr, bitwise_ptr=bitwise_ptr, keccak_ptr=keccak_ptr - }(task_hash=flipped_task_hash); + let (result, program_hash) = compute_contract(); - let results_root = compute_results_root{ - range_check_ptr=range_check_ptr, bitwise_ptr=bitwise_ptr, keccak_ptr=keccak_ptr - }(task_hash=flipped_task_hash, result=result); + %{ print(f"Task Result: {hex(ids.result.high * 2 ** 128 + ids.result.low)}") %} - return (tasks_root=tasks_root, results_root=results_root, results=results, results_len=1); + return (program_hash=program_hash, result=result); } diff --git a/src/utils/utils.cairo b/src/utils/utils.cairo index 9e3f4bd9..035b971d 100644 --- a/src/utils/utils.cairo +++ b/src/utils/utils.cairo @@ -22,13 +22,12 @@ from src.types import MMRMeta // The first 4 words are reserved for the tasks and results root. // The rest of the words are reserved for the MMR metas. Each MMR will contain 4 fields, and we can add an arbitrary amount of them. func write_output_ptr{output_ptr: felt*}( - mmr_metas: MMRMeta*, mmr_metas_len: felt, tasks_root: Uint256, results_root: Uint256 + mmr_metas: MMRMeta*, mmr_metas_len: felt, program_hash: felt, result: Uint256 ) { - assert [output_ptr] = results_root.low; - assert [output_ptr + 1] = results_root.high; - assert [output_ptr + 2] = tasks_root.low; - assert [output_ptr + 3] = tasks_root.high; - let output_ptr = output_ptr + 4; + assert [output_ptr + 0] = program_hash; + assert [output_ptr + 1] = result.low; + assert [output_ptr + 2] = result.high; + let output_ptr = output_ptr + 3; tempvar counter = 0; diff --git a/src/verifiers/evm/account_verifier.cairo b/src/verifiers/evm/account_verifier.cairo index a288b07d..27c6a118 100644 --- a/src/verifiers/evm/account_verifier.cairo +++ b/src/verifiers/evm/account_verifier.cairo @@ -22,7 +22,7 @@ func verify_accounts{ }() { alloc_locals; local n_accounts: felt; - %{ ids.n_accounts = len(batch["accounts"]) %} + %{ ids.n_accounts = len(batch.accounts) %} verify_accounts_inner(n_accounts, 0); diff --git a/src/verifiers/evm/block_tx_verifier.cairo b/src/verifiers/evm/block_tx_verifier.cairo index c5d8c725..86a940cd 100644 --- a/src/verifiers/evm/block_tx_verifier.cairo +++ b/src/verifiers/evm/block_tx_verifier.cairo @@ -30,7 +30,7 @@ func verify_block_tx_proofs{ alloc_locals; local n_tx_proofs: felt; - %{ ids.n_tx_proofs = len(batch["transactions"]) %} + %{ ids.n_tx_proofs = len(batch.transactions) %} verify_block_tx_proofs_inner(n_tx_proofs, 0); return (); diff --git a/src/verifiers/evm/receipt_verifier.cairo b/src/verifiers/evm/receipt_verifier.cairo index 5ca0015e..ba45db0b 100644 --- a/src/verifiers/evm/receipt_verifier.cairo +++ b/src/verifiers/evm/receipt_verifier.cairo @@ -29,7 +29,7 @@ func verify_block_receipt_proofs{ alloc_locals; local n_receipts: felt; - %{ ids.n_receipts = len(batch["transaction_receipts"]) %} + %{ ids.n_receipts = len(batch.receipts) %} verify_block_receipt_proofs_inner(n_receipts, 0); return (); diff --git a/src/verifiers/evm/storage_item_verifier.cairo b/src/verifiers/evm/storage_item_verifier.cairo index 4deabe8c..8d8f4bbb 100644 --- a/src/verifiers/evm/storage_item_verifier.cairo +++ b/src/verifiers/evm/storage_item_verifier.cairo @@ -28,7 +28,7 @@ func verify_storage_items{ }() { alloc_locals; local n_storage_items: felt; - %{ ids.n_storage_items = len(batch["storages"]) %} + %{ ids.n_storage_items = len(batch.storages) %} verify_storage_items_inner(n_storage_items, 0); diff --git a/src/verifiers/mmr_verifier.cairo b/src/verifiers/mmr_verifier.cairo index 5aa9cf62..12b2197c 100644 --- a/src/verifiers/mmr_verifier.cairo +++ b/src/verifiers/mmr_verifier.cairo @@ -29,17 +29,12 @@ func validate_mmr_meta{range_check_ptr, poseidon_ptr: PoseidonBuiltin*, pow2_arr local peaks_len: felt; %{ - def hex_to_int_array(hex_array): - return [int(x, 16) for x in hex_array] - - # Load data from inputs - memory[ids.mmr_meta._reference_value] = mmr_batch["mmr_meta"]["id"] - memory[ids.mmr_meta._reference_value + 1] = int(mmr_batch["mmr_meta"]["root"], 16) - memory[ids.mmr_meta._reference_value + 2] = mmr_batch["mmr_meta"]["size"] - memory[ids.mmr_meta._reference_value + 3] = ids.chain_id - - ids.peaks_len = len(mmr_batch["mmr_meta"]["peaks"]) - segments.write_arg(ids.peaks, hex_to_int_array(mmr_batch["mmr_meta"]["peaks"])) + memory[ids.mmr_meta._reference_value + 0] = batch.mmr_meta.id + memory[ids.mmr_meta._reference_value + 1] = batch.mmr_meta.root + memory[ids.mmr_meta._reference_value + 2] = batch.mmr_meta.size + memory[ids.mmr_meta._reference_value + 3] = batch.mmr_meta.chain_id + ids.peaks_len = len(batch.mmr_meta.peaks) + segments.write_arg(ids.peaks, batch.mmr_meta.peaks) %} assert_mmr_size_is_valid(mmr_meta.size); diff --git a/src/verifiers/verify.cairo b/src/verifiers/verify.cairo index 4ebe4c4c..de7f2f2d 100644 --- a/src/verifiers/verify.cairo +++ b/src/verifiers/verify.cairo @@ -49,7 +49,7 @@ func run_state_verification_inner{ } local chain_id: felt; - %{ ids.chain_id = int(program_input["proofs"][ids.batch_len - 1]["chain_id"], 16) %} + %{ ids.chain_id = proofs[ids.batch_len - 1].mmr_meta.chain_id %} let (chain_info) = fetch_chain_info(chain_id); @@ -58,7 +58,7 @@ func run_state_verification_inner{ %{ print("EVM") %} %{ vm_enter_scope({ - 'batch': program_input["proofs"][ids.batch_len - 1], + 'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager }) %} @@ -73,7 +73,7 @@ func run_state_verification_inner{ %{ print("STARKNET") %} %{ vm_enter_scope({ - 'batch': program_input["proofs"][ids.batch_len - 1], + 'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager }) %} diff --git a/tools/py/schema.py b/tools/py/schema.py index abe3d925..f10323b9 100644 --- a/tools/py/schema.py +++ b/tools/py/schema.py @@ -1,5 +1,5 @@ from enum import Enum -from typing import List, Optional, Union +from typing import List from marshmallow import ValidationError import marshmallow_dataclass from dataclasses import field @@ -14,16 +14,19 @@ @marshmallow_dataclass.dataclass(frozen=True) -class ProcessedMPTProof: +class MPTProof: block_number: int - proof: List[str] + proof: List[str] = field( + metadata=additional_metadata(marshmallow_field=mfields.List(IntAsHex())) + ) @marshmallow_dataclass.dataclass(frozen=True) class MMRMeta: id: int - root: str size: int + root: str + chain_id: int peaks: List[str] = field( metadata=additional_metadata(marshmallow_field=mfields.List(IntAsHex())) ) @@ -31,62 +34,51 @@ class MMRMeta: @marshmallow_dataclass.dataclass(frozen=True) class HeaderProof: - rlp: str leaf_idx: int mmr_path: List[str] @marshmallow_dataclass.dataclass(frozen=True) -class AccountProof: +class Header: + rlp: str + proof: HeaderProof + + +@marshmallow_dataclass.dataclass(frozen=True) +class Account: address: str account_key: str - proofs: List[ProcessedMPTProof] + proof: MPTProof @marshmallow_dataclass.dataclass(frozen=True) -class StorageProof: +class Storage: address: str slot: str storage_key: str - proofs: List[ProcessedMPTProof] + proof: MPTProof @marshmallow_dataclass.dataclass(frozen=True) -class TransactionProof: +class Transaction: key: str - block_number: int - proof: List[str] + proof: MPTProof @marshmallow_dataclass.dataclass(frozen=True) -class ReceiptProof: +class Receipt: key: str - block_number: int - proof: List[str] + proof: MPTProof @marshmallow_dataclass.dataclass(frozen=True) -class Proofs(ValidatedMarshmallowDataclass): +class Proof(ValidatedMarshmallowDataclass): mmr_meta: MMRMeta - headers: List[HeaderProof] - accounts: List[AccountProof] - storages: List[StorageProof] - transactions: List[TransactionProof] - transaction_receipts: List[ReceiptProof] - - -@marshmallow_dataclass.dataclass(frozen=True) -class Datalake: - task_bytes_len: int - encoded_task: List[int] = field( - metadata=additional_metadata(marshmallow_field=mfields.List(IntAsHex())) - ) - datalake_bytes_len: int - encoded_datalake: List[int] = field( - metadata=additional_metadata(marshmallow_field=mfields.List(IntAsHex())) - ) - datalake_type: int - property_type: int + headers: List[Header] + accounts: List[Account] + storages: List[Storage] + transactions: List[Transaction] + receipts: List[Receipt] class Visibility(Enum): @@ -106,7 +98,7 @@ def _deserialize(self, value, attr, data, **kwargs): @marshmallow_dataclass.dataclass(frozen=True) -class Input: +class Param: visibility: Visibility = field( metadata={"marshmallow_field": VisibilityField(required=True)} ) @@ -114,66 +106,25 @@ class Input: @marshmallow_dataclass.dataclass(frozen=True) -class Module(ValidatedMarshmallowDataclass): - inputs: List[Input] = field( +class HDPInput(ValidatedMarshmallowDataclass): + proofs: List[Proof] = field( metadata=additional_metadata( - marshmallow_field=mfields.List(mfields.Nested(Input.Schema)) + marshmallow_field=mfields.List(mfields.Nested(Proof.Schema)) ) ) - encoded_task: List[int] = field( - metadata=additional_metadata(marshmallow_field=mfields.List(IntAsHex())) - ) - task_bytes_len: int - module_class: CompiledClass - - -@marshmallow_dataclass.dataclass(frozen=True) -class DryRunModule(ValidatedMarshmallowDataclass): - inputs: List[Input] = field( + params: List[Param] = field( metadata=additional_metadata( - marshmallow_field=mfields.List(mfields.Nested(Input.Schema)) + marshmallow_field=mfields.List(mfields.Nested(Param.Schema)) ) ) module_class: CompiledClass -@marshmallow_dataclass.dataclass(frozen=True) -class DatalakeTask: - datalake: Datalake - - -@marshmallow_dataclass.dataclass(frozen=True) -class ModuleTask: - module: Module - - -@marshmallow_dataclass.dataclass(frozen=True) -class InputTask(ValidatedMarshmallowDataclass): - task: Union[DatalakeTask, ModuleTask] = field( - metadata=additional_metadata(marshmallow_field=mfields.Raw()) - ) - - -@marshmallow_dataclass.dataclass(frozen=True) -class HDPInput(ValidatedMarshmallowDataclass): - cairo_run_output_path: str - task_root: int = field(metadata=additional_metadata(marshmallow_field=IntAsHex())) - proofs: Proofs - tasks: List[InputTask] = field( - metadata=additional_metadata( - marshmallow_field=mfields.List(mfields.Nested(InputTask.Schema)) - ) - ) - result_root: Optional[int] = field( - default=None, metadata=additional_metadata(marshmallow_field=IntAsHex()) - ) - - @marshmallow_dataclass.dataclass(frozen=True) class HDPDryRunInput(ValidatedMarshmallowDataclass): - dry_run_output_path: str - modules: List[DryRunModule] = field( + params: List[Param] = field( metadata=additional_metadata( - marshmallow_field=mfields.List(mfields.Nested(DryRunModule.Schema)) + marshmallow_field=mfields.List(mfields.Nested(Param.Schema)) ) ) + module_class: CompiledClass From fb7be949c975d5494b499920828abbe9e26cf85e Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 9 Dec 2024 15:11:14 +0100 Subject: [PATCH 05/75] header_verifier hint refactor --- src/verifiers/evm/header_verifier.cairo | 15 ++++++--------- src/verifiers/verify.cairo | 20 +++----------------- 2 files changed, 9 insertions(+), 26 deletions(-) diff --git a/src/verifiers/evm/header_verifier.cairo b/src/verifiers/evm/header_verifier.cairo index 9d695140..8e072a1c 100644 --- a/src/verifiers/evm/header_verifier.cairo +++ b/src/verifiers/evm/header_verifier.cairo @@ -93,12 +93,10 @@ func verify_headers_with_mmr_peaks{ local rlp_len: felt; local leaf_idx: felt; %{ - from tools.py.utils import hex_to_int_array - - header = mmr_batch["headers"][ids.idx - 1] - segments.write_arg(ids.rlp, hex_to_int_array(header["rlp"])) - ids.rlp_len = len(header["rlp"]) - ids.leaf_idx = header["proof"]["leaf_idx"] + header = batch.headers[ids.idx - 1] + ids.rlp_len = len(header.rlp) + segments.write_arg(ids.rlp, [int(x, 16) for x in header.rlp]) + ids.leaf_idx = header.proof.leaf_idx %} // compute the hash of the header @@ -123,9 +121,8 @@ func verify_headers_with_mmr_peaks{ let (mmr_path) = alloc(); local mmr_path_len: felt; %{ - proof = header["proof"] - segments.write_arg(ids.mmr_path, hex_to_int_array(proof["mmr_path"])) - ids.mmr_path_len = len(proof["mmr_path"]) + ids.mmr_path_len = len(header.proof.mmr_path) + segments.write_arg(ids.mmr_path, [int(x, 16) for x in header.proof.mmr_path]) %} // compute the peak of the header diff --git a/src/verifiers/verify.cairo b/src/verifiers/verify.cairo index de7f2f2d..f24598fd 100644 --- a/src/verifiers/verify.cairo +++ b/src/verifiers/verify.cairo @@ -26,7 +26,7 @@ func run_state_verification{ }() -> (mmr_metas_len: felt) { alloc_locals; local batch_len: felt; - %{ ids.batch_len = len(program_input["proofs"]) %} + %{ ids.batch_len = len(proofs) %} let (mmr_meta_idx) = run_state_verification_inner(batch_len, 0); return (mmr_metas_len=mmr_meta_idx); @@ -54,14 +54,7 @@ func run_state_verification_inner{ let (chain_info) = fetch_chain_info(chain_id); if (chain_info.layout == 0) { - // EVM - %{ print("EVM") %} - %{ - vm_enter_scope({ - 'batch': proofs[ids.batch_len - 1], - '__dict_manager': __dict_manager - }) - %} + %{ vm_enter_scope({'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager}) %} with chain_info { let mmr_meta_idx = evm_run_state_verification(mmr_meta_idx); } @@ -69,14 +62,7 @@ func run_state_verification_inner{ return run_state_verification_inner(batch_len=batch_len - 1, mmr_meta_idx=mmr_meta_idx); } else { - // STARKNET - %{ print("STARKNET") %} - %{ - vm_enter_scope({ - 'batch': proofs[ids.batch_len - 1], - '__dict_manager': __dict_manager - }) - %} + %{ vm_enter_scope({'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager}) %} with chain_info { let mmr_meta_idx = starknet_run_state_verification(mmr_meta_idx); } From e463c42f9dd9b495bc7ef81e05c015cd5bd4f5e5 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 9 Dec 2024 15:27:51 +0100 Subject: [PATCH 06/75] header hints refined --- src/verifiers/evm/header_verifier.cairo | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/src/verifiers/evm/header_verifier.cairo b/src/verifiers/evm/header_verifier.cairo index 8e072a1c..888ff761 100644 --- a/src/verifiers/evm/header_verifier.cairo +++ b/src/verifiers/evm/header_verifier.cairo @@ -45,21 +45,13 @@ func verify_mmr_batches_inner{ return (); } - %{ - vm_enter_scope({ - 'mmr_batch': batch["mmr_with_headers"][ids.idx], - '__dict_manager': __dict_manager - }) - %} let (mmr_meta, peaks_dict, peaks_dict_start) = validate_mmr_meta(chain_id); assert mmr_metas[mmr_meta_idx + idx] = mmr_meta; - local n_header_proofs: felt; - %{ ids.n_header_proofs = len(mmr_batch["headers"]) %} + local n_header_proofs: felt = nondet %{ len(batch.headers) %}; with mmr_meta, peaks_dict { verify_headers_with_mmr_peaks(n_header_proofs); } - %{ vm_exit_scope() %} // Ensure the peaks dict for this batch is finalized default_dict_finalize(peaks_dict_start, peaks_dict, -1); @@ -90,15 +82,14 @@ func verify_headers_with_mmr_peaks{ } let (rlp) = alloc(); - local rlp_len: felt; - local leaf_idx: felt; %{ header = batch.headers[ids.idx - 1] - ids.rlp_len = len(header.rlp) segments.write_arg(ids.rlp, [int(x, 16) for x in header.rlp]) - ids.leaf_idx = header.proof.leaf_idx %} + local rlp_len: felt = nondet %{ len(header.rlp) %}; + local leaf_idx: felt = nondet %{ len(header.proof.leaf_idx) %}; + // compute the hash of the header let (poseidon_hash) = poseidon_hash_many(n=rlp_len, elements=rlp); @@ -119,11 +110,8 @@ func verify_headers_with_mmr_peaks{ } let (mmr_path) = alloc(); - local mmr_path_len: felt; - %{ - ids.mmr_path_len = len(header.proof.mmr_path) - segments.write_arg(ids.mmr_path, [int(x, 16) for x in header.proof.mmr_path]) - %} + local mmr_path_len: felt = nondet %{ len(header.proof.mmr_path) %}; + %{ segments.write_arg(ids.mmr_path, [int(x, 16) for x in header.proof.mmr_path]) %} // compute the peak of the header let (computed_peak) = hash_subtree_path( From 7b5714a90284b050bd0920b93e92dbd02771a921 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 10 Dec 2024 09:55:16 +0100 Subject: [PATCH 07/75] header_verifier one mmr per batch --- src/verifiers/evm/header_verifier.cairo | 30 ++----------------------- src/verifiers/verify.cairo | 12 +++++----- 2 files changed, 8 insertions(+), 34 deletions(-) diff --git a/src/verifiers/evm/header_verifier.cairo b/src/verifiers/evm/header_verifier.cairo index 888ff761..e029f23d 100644 --- a/src/verifiers/evm/header_verifier.cairo +++ b/src/verifiers/evm/header_verifier.cairo @@ -19,34 +19,10 @@ func verify_mmr_batches{ evm_memorizer: DictAccess*, mmr_metas: MMRMeta*, chain_id: felt, -}(mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { +}() -> () { alloc_locals; - local mmr_batches_len: felt; - %{ ids.mmr_batches_len = len(batch["mmr_with_headers"]) %} - verify_mmr_batches_inner(mmr_batches_len, 0, mmr_meta_idx); - - return (mmr_meta_idx=mmr_meta_idx + mmr_batches_len); -} - -// Check if the passed MMR meta is valid and if the headers are included in the MMR. -// Headers included in the MMR are memorized. -func verify_mmr_batches_inner{ - range_check_ptr, - poseidon_ptr: PoseidonBuiltin*, - bitwise_ptr: BitwiseBuiltin*, - pow2_array: felt*, - evm_memorizer: DictAccess*, - mmr_metas: MMRMeta*, - chain_id: felt, -}(mmr_batches_len: felt, idx: felt, mmr_meta_idx: felt) { - alloc_locals; - if (mmr_batches_len == idx) { - return (); - } - let (mmr_meta, peaks_dict, peaks_dict_start) = validate_mmr_meta(chain_id); - assert mmr_metas[mmr_meta_idx + idx] = mmr_meta; local n_header_proofs: felt = nondet %{ len(batch.headers) %}; with mmr_meta, peaks_dict { @@ -56,9 +32,7 @@ func verify_mmr_batches_inner{ // Ensure the peaks dict for this batch is finalized default_dict_finalize(peaks_dict_start, peaks_dict, -1); - return verify_mmr_batches_inner( - mmr_batches_len=mmr_batches_len, idx=idx + 1, mmr_meta_idx=mmr_meta_idx - ); + return (); } // Guard function that verifies the inclusion of headers in the MMR. diff --git a/src/verifiers/verify.cairo b/src/verifiers/verify.cairo index f24598fd..ff382255 100644 --- a/src/verifiers/verify.cairo +++ b/src/verifiers/verify.cairo @@ -42,10 +42,10 @@ func run_state_verification_inner{ evm_memorizer: DictAccess*, starknet_memorizer: DictAccess*, mmr_metas: MMRMeta*, -}(batch_len: felt, mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { +}(batch_len: felt) -> () { alloc_locals; if (batch_len == 0) { - return (mmr_meta_idx=mmr_meta_idx); + return (); } local chain_id: felt; @@ -56,18 +56,18 @@ func run_state_verification_inner{ if (chain_info.layout == 0) { %{ vm_enter_scope({'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager}) %} with chain_info { - let mmr_meta_idx = evm_run_state_verification(mmr_meta_idx); + evm_run_state_verification(); } %{ vm_exit_scope() %} - return run_state_verification_inner(batch_len=batch_len - 1, mmr_meta_idx=mmr_meta_idx); + return run_state_verification_inner(batch_len=batch_len - 1); } else { %{ vm_enter_scope({'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager}) %} with chain_info { - let mmr_meta_idx = starknet_run_state_verification(mmr_meta_idx); + starknet_run_state_verification(); } %{ vm_exit_scope() %} - return run_state_verification_inner(batch_len=batch_len - 1, mmr_meta_idx=mmr_meta_idx); + return run_state_verification_inner(batch_len=batch_len - 1); } } From 64a96c6d96ac499fcebfc910ef6aa3fd145f3839 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 10 Dec 2024 10:17:30 +0100 Subject: [PATCH 08/75] compiler fixes --- src/contract_bootloader/contract.cairo | 4 +-- src/hdp.cairo | 9 ++--- src/verifiers/evm/header_verifier.cairo | 5 +-- src/verifiers/evm/verify.cairo | 4 +-- src/verifiers/starknet/header_verifier.cairo | 38 ++------------------ src/verifiers/starknet/verify.cairo | 4 +-- src/verifiers/verify.cairo | 15 ++++---- 7 files changed, 23 insertions(+), 56 deletions(-) diff --git a/src/contract_bootloader/contract.cairo b/src/contract_bootloader/contract.cairo index 749c807c..0978ceb5 100644 --- a/src/contract_bootloader/contract.cairo +++ b/src/contract_bootloader/contract.cairo @@ -79,8 +79,8 @@ func compute_contract{ assert calldata[2] = nondet %{ ids.starknet_memorizer.address_.segment_index %}; assert calldata[3] = nondet %{ ids.starknet_memorizer.address_.offset %}; - memcpy(dst=calldata + 4, src=inputs, len=inputs_len); - let calldata_size = 4 + inputs_len; + memcpy(dst=calldata + 4, src=params, len=params_len); + let calldata_size = 4 + params_len; with evm_memorizer, starknet_memorizer, pow2_array { let (retdata_size, retdata) = run_contract_bootloader( diff --git a/src/hdp.cairo b/src/hdp.cairo index e238fe5c..96ba97b9 100644 --- a/src/hdp.cairo +++ b/src/hdp.cairo @@ -86,7 +86,7 @@ func run{ // MMR Params let (mmr_metas: MMRMeta*) = alloc(); - let (local mmr_metas_len) = run_state_verification{ + let (mmr_metas_len) = run_state_verification{ range_check_ptr=range_check_ptr, poseidon_ptr=poseidon_ptr, keccak_ptr=keccak_ptr, @@ -102,7 +102,7 @@ func run{ let starknet_key_hasher_ptr = StarknetStateAccess.init(); let starknet_decoder_ptr = StarknetDecoder.init(); - let (program_hash, results, results_len) = compute_tasks{ + let (program_hash, result) = compute_tasks{ pedersen_ptr=pedersen_ptr, range_check_ptr=range_check_ptr, ecdsa_ptr=ecdsa_ptr, @@ -126,10 +126,7 @@ func run{ ); write_output_ptr{output_ptr=output_ptr}( - mmr_metas=mmr_metas, - mmr_metas_len=mmr_metas_len, - tasks_root=tasks_root, - results_root=results_root, + mmr_metas=mmr_metas, mmr_metas_len=mmr_metas_len, program_hash=program_hash, result=result ); return (); diff --git a/src/verifiers/evm/header_verifier.cairo b/src/verifiers/evm/header_verifier.cairo index e029f23d..5b1c0ede 100644 --- a/src/verifiers/evm/header_verifier.cairo +++ b/src/verifiers/evm/header_verifier.cairo @@ -19,10 +19,11 @@ func verify_mmr_batches{ evm_memorizer: DictAccess*, mmr_metas: MMRMeta*, chain_id: felt, -}() -> () { +}(mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { alloc_locals; let (mmr_meta, peaks_dict, peaks_dict_start) = validate_mmr_meta(chain_id); + assert mmr_metas[mmr_meta_idx] = mmr_meta; local n_header_proofs: felt = nondet %{ len(batch.headers) %}; with mmr_meta, peaks_dict { @@ -32,7 +33,7 @@ func verify_mmr_batches{ // Ensure the peaks dict for this batch is finalized default_dict_finalize(peaks_dict_start, peaks_dict, -1); - return (); + return (mmr_meta_idx=mmr_meta_idx + 1); } // Guard function that verifies the inclusion of headers in the MMR. diff --git a/src/verifiers/evm/verify.cairo b/src/verifiers/evm/verify.cairo index cc090538..65527160 100644 --- a/src/verifiers/evm/verify.cairo +++ b/src/verifiers/evm/verify.cairo @@ -18,7 +18,7 @@ func run_state_verification{ evm_memorizer: DictAccess*, mmr_metas: MMRMeta*, chain_info: ChainInfo, -}(mmr_meta_idx: felt) -> felt { +}(mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { alloc_locals; // Step 1: Verify MMR and headers inclusion @@ -39,5 +39,5 @@ func run_state_verification{ // Step 5: Verify the block receipt proofs verify_block_receipt_proofs(); - return mmr_meta_idx; + return (mmr_meta_idx=mmr_meta_idx); } diff --git a/src/verifiers/starknet/header_verifier.cairo b/src/verifiers/starknet/header_verifier.cairo index b894c0e8..07691c08 100644 --- a/src/verifiers/starknet/header_verifier.cairo +++ b/src/verifiers/starknet/header_verifier.cairo @@ -21,50 +21,18 @@ func verify_mmr_batches{ }(mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { alloc_locals; - local mmr_batches_len: felt; - %{ ids.mmr_batches_len = len(batch["mmr_with_headers"]) %} - verify_mmr_batches_inner(mmr_batches_len, 0, mmr_meta_idx); - - return (mmr_meta_idx=mmr_meta_idx + mmr_batches_len); -} - -// Check if the passed MMR meta is valid and if the headers are included in the MMR. -// Headers included in the MMR are memorized. -func verify_mmr_batches_inner{ - range_check_ptr, - poseidon_ptr: PoseidonBuiltin*, - pow2_array: felt*, - mmr_metas: MMRMeta*, - starknet_memorizer: DictAccess*, - chain_id: felt, -}(mmr_batches_len: felt, idx: felt, mmr_meta_idx: felt) { - alloc_locals; - if (mmr_batches_len == idx) { - return (); - } - - %{ - vm_enter_scope({ - 'mmr_batch': batch["mmr_with_headers"][ids.idx], - '__dict_manager': __dict_manager - }) - %} let (mmr_meta, peaks_dict, peaks_dict_start) = validate_mmr_meta(chain_id); - assert mmr_metas[mmr_meta_idx + idx] = mmr_meta; + assert mmr_metas[mmr_meta_idx] = mmr_meta; - local n_header_proofs: felt; - %{ ids.n_header_proofs = len(mmr_batch["headers"]) %} + local n_header_proofs: felt = nondet %{ len(batch.headers) %}; with mmr_meta, peaks_dict { verify_headers_with_mmr_peaks(n_header_proofs); } - %{ vm_exit_scope() %} // Ensure the peaks dict for this batch is finalized default_dict_finalize(peaks_dict_start, peaks_dict, -1); - return verify_mmr_batches_inner( - mmr_batches_len=mmr_batches_len, idx=idx + 1, mmr_meta_idx=mmr_meta_idx - ); + return (mmr_meta_idx=mmr_meta_idx + 1); } // Guard function that verifies the inclusion of headers in the MMR. diff --git a/src/verifiers/starknet/verify.cairo b/src/verifiers/starknet/verify.cairo index b8e5dcaf..10efc05d 100644 --- a/src/verifiers/starknet/verify.cairo +++ b/src/verifiers/starknet/verify.cairo @@ -19,7 +19,7 @@ func run_state_verification{ starknet_memorizer: DictAccess*, mmr_metas: MMRMeta*, chain_info: ChainInfo, -}(mmr_meta_idx: felt) -> felt { +}(mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { alloc_locals; // Step 1: Verify MMR and headers inclusion @@ -40,5 +40,5 @@ func run_state_verification{ // // Step 5: Verify the block receipt proofs // verify_block_receipt_proofs(); - return mmr_meta_idx; + return (mmr_meta_idx=mmr_meta_idx); } diff --git a/src/verifiers/verify.cairo b/src/verifiers/verify.cairo index ff382255..521272c3 100644 --- a/src/verifiers/verify.cairo +++ b/src/verifiers/verify.cairo @@ -25,10 +25,11 @@ func run_state_verification{ mmr_metas: MMRMeta*, }() -> (mmr_metas_len: felt) { alloc_locals; + local batch_len: felt; %{ ids.batch_len = len(proofs) %} - let (mmr_meta_idx) = run_state_verification_inner(batch_len, 0); + return (mmr_metas_len=mmr_meta_idx); } @@ -42,10 +43,10 @@ func run_state_verification_inner{ evm_memorizer: DictAccess*, starknet_memorizer: DictAccess*, mmr_metas: MMRMeta*, -}(batch_len: felt) -> () { +}(batch_len: felt, mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { alloc_locals; if (batch_len == 0) { - return (); + return (mmr_meta_idx=mmr_meta_idx); } local chain_id: felt; @@ -56,18 +57,18 @@ func run_state_verification_inner{ if (chain_info.layout == 0) { %{ vm_enter_scope({'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager}) %} with chain_info { - evm_run_state_verification(); + let (mmr_meta_idx) = evm_run_state_verification(mmr_meta_idx); } %{ vm_exit_scope() %} - return run_state_verification_inner(batch_len=batch_len - 1); + return run_state_verification_inner(batch_len=batch_len - 1, mmr_meta_idx=mmr_meta_idx); } else { %{ vm_enter_scope({'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager}) %} with chain_info { - starknet_run_state_verification(); + let (mmr_meta_idx) = starknet_run_state_verification(mmr_meta_idx); } %{ vm_exit_scope() %} - return run_state_verification_inner(batch_len=batch_len - 1); + return run_state_verification_inner(batch_len=batch_len - 1, mmr_meta_idx=mmr_meta_idx); } } From 2dea6fdd85a17f2925721fc1092c8e76e5a6ec27 Mon Sep 17 00:00:00 2001 From: codyx Date: Tue, 10 Dec 2024 15:36:14 +0400 Subject: [PATCH 09/75] Add verifier\'s verify hints --- cairo_vm_hints/src/hint_processor/mod.rs | 8 +- cairo_vm_hints/src/hints/lib/mod.rs | 1 + cairo_vm_hints/src/hints/lib/verifiers/mod.rs | 1 + .../src/hints/lib/verifiers/verify.rs | 74 +++++++++++++++++++ cairo_vm_hints/src/hints/vars.rs | 4 + 5 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 cairo_vm_hints/src/hints/lib/verifiers/mod.rs create mode 100644 cairo_vm_hints/src/hints/lib/verifiers/verify.rs diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index ce6366fe..b0a56d8f 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -70,6 +70,8 @@ impl CustomHintProcessor { hints.insert(lib::decoder::evm::has_type_prefix::HINT_HAS_TYPE_PREFIX.into(), lib::decoder::evm::has_type_prefix::hint_has_type_prefix); hints.insert(lib::decoder::evm::is_byzantium::HINT_IS_BYZANTIUM.into(), lib::decoder::evm::is_byzantium::hint_is_byzantium); hints.insert(lib::decoder::evm::v_is_encoded::HINT_V_IS_ENCODED.into(), lib::decoder::evm::v_is_encoded::hint_v_is_encoded); + hints.insert(lib::merkle::HINT_TARGET_TASK_HASH.into(), lib::merkle::hint_target_task_hash); + hints.insert(lib::merkle::HINT_IS_LEFT_SMALLER.into(), lib::merkle::hint_is_left_smaller); hints.insert(lib::rlp::divmod::HINT_DIVMOD_RLP.into(), lib::rlp::divmod::hint_divmod_rlp); hints.insert(lib::rlp::divmod::HINT_DIVMOD_VALUE.into(), lib::rlp::divmod::hint_divmod_value); hints.insert(lib::rlp::item_type::HINT_IS_LONG.into(), lib::rlp::item_type::hint_is_long); @@ -81,8 +83,10 @@ impl CustomHintProcessor { hints.insert(lib::segments::SEGMENTS_ADD_EVM_MEMORIZER_OFFSET.into(), lib::segments::segments_add_evm_memorizer_offset); hints.insert(lib::segments::SEGMENTS_ADD_EVM_STARKNET_MEMORIZER_INDEX.into(), lib::segments::segments_add_evm_starknet_memorizer_index); hints.insert(lib::segments::SEGMENTS_ADD_STARKNET_MEMORIZER_OFFSET.into(), lib::segments::segments_add_starknet_memorizer_offset); - hints.insert(lib::merkle::HINT_TARGET_TASK_HASH.into(), lib::merkle::hint_target_task_hash); - hints.insert(lib::merkle::HINT_IS_LEFT_SMALLER.into(), lib::merkle::hint_is_left_smaller); + hints.insert(lib::verifiers::verify::HINT_BATCH_LEN.into(), lib::verifiers::verify::hint_batch_len); + hints.insert(lib::verifiers::verify::HINT_CHAIN_ID.into(), lib::verifiers::verify::hint_chain_id); + hints.insert(lib::verifiers::verify::HINT_VM_ENTER_SCOPE.into(), lib::verifiers::verify::hint_vm_enter_scope); + hints } diff --git a/cairo_vm_hints/src/hints/lib/mod.rs b/cairo_vm_hints/src/hints/lib/mod.rs index c9df03d0..84bd4fea 100644 --- a/cairo_vm_hints/src/hints/lib/mod.rs +++ b/cairo_vm_hints/src/hints/lib/mod.rs @@ -4,3 +4,4 @@ pub mod merkle; pub mod print; pub mod rlp; pub mod segments; +pub mod verifiers; diff --git a/cairo_vm_hints/src/hints/lib/verifiers/mod.rs b/cairo_vm_hints/src/hints/lib/verifiers/mod.rs new file mode 100644 index 00000000..a8118c56 --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/verifiers/mod.rs @@ -0,0 +1 @@ +pub mod verify; diff --git a/cairo_vm_hints/src/hints/lib/verifiers/verify.rs b/cairo_vm_hints/src/hints/lib/verifiers/verify.rs new file mode 100644 index 00000000..ce1c6d16 --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/verifiers/verify.rs @@ -0,0 +1,74 @@ +use cairo_vm::{ + hint_processor::builtin_hint_processor::{ + builtin_hint_processor_definition::HintProcessorData, dict_manager::DictManager, hint_utils::insert_value_from_var_name, + }, + types::relocatable::MaybeRelocatable, +}; +use cairo_vm::{ + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use std::{any::Any, collections::HashMap}; + +use crate::{hint_processor::models::proofs::Proofs, hints::vars}; + +pub const HINT_BATCH_LEN: &str = "ids.batch_len = len(ids.proofs)"; + +pub fn hint_batch_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let proofs = exec_scopes.get::>(vars::scopes::PROOFS)?; + + insert_value_from_var_name( + vars::ids::BATCH_LEN, + MaybeRelocatable::Int(proofs.len().into()), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + ) +} + +pub const HINT_CHAIN_ID: &str = "ids.chain_id = proofs[ids.batch_len - 1].mmr_meta.chain_id"; + +pub fn hint_chain_id( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let proofs = exec_scopes.get::>(vars::scopes::PROOFS)?; + + let chain_id = proofs[proofs.len() - 1].mmr_meta.chain_id; + + insert_value_from_var_name( + vars::ids::CHAIN_ID, + MaybeRelocatable::Int(chain_id.into()), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + ) +} + +pub const HINT_VM_ENTER_SCOPE: &str = "vm_enter_scope({'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager})"; + +pub fn hint_vm_enter_scope( + _vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let proofs = exec_scopes.get::>(vars::scopes::PROOFS)?; + + let batch: Box = Box::new(proofs[proofs.len() - 1].clone()); + let dict_manager: Box = Box::new(exec_scopes.get::(vars::scopes::DICT_MANAGER)?); + exec_scopes.enter_scope(HashMap::from([ + (String::from(vars::scopes::BATCH), batch), + (String::from(vars::scopes::DICT_MANAGER), dict_manager), + ])); + + Ok(()) +} diff --git a/cairo_vm_hints/src/hints/vars.rs b/cairo_vm_hints/src/hints/vars.rs index c76cffc3..9d3994e2 100644 --- a/cairo_vm_hints/src/hints/vars.rs +++ b/cairo_vm_hints/src/hints/vars.rs @@ -1,15 +1,19 @@ pub mod scopes { + pub(crate) const BATCH: &str = "batch"; pub(crate) const COMPILED_CLASS: &str = "compiled_class"; pub(crate) const DICT_MANAGER: &str = "dict_manager"; pub(crate) const N_SELECTED_BUILTINS: &str = "n_selected_builtins"; pub(crate) const PARAMS: &str = "params"; + pub(crate) const PROOFS: &str = "proofs"; pub(crate) const SYSCALL_HANDLER: &str = "syscall_handler"; } pub mod ids { pub(crate) const ALL_ENCODINGS: &str = "all_encodings"; + pub(crate) const BATCH_LEN: &str = "batch_len"; pub(crate) const BUILTIN_PARAMS: &str = "builtin_params"; pub(crate) const BUILTIN_PTRS: &str = "builtin_ptrs"; + pub(crate) const CHAIN_ID: &str = "chain_id"; pub(crate) const COMPILED_CLASS: &str = "compiled_class"; pub(crate) const CURRENT_ITEM: &str = "ids.current_item"; pub(crate) const DEVISOR: &str = "ids.devisor"; From 8dc973b7d3600b164a2f1feb495864a3ea95f54b Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 10 Dec 2024 12:47:30 +0100 Subject: [PATCH 10/75] hints refactored --- .../hint_processor/models/proofs/account.rs | 6 +- .../src/hint_processor/models/proofs/mpt.rs | 1 + .../hint_processor/models/proofs/storage.rs | 6 +- src/verifiers/evm/account_verifier.cairo | 59 +++++++++-------- src/verifiers/evm/block_tx_verifier.cairo | 39 +++++------ src/verifiers/evm/receipt_verifier.cairo | 39 +++++------ src/verifiers/evm/storage_item_verifier.cairo | 64 ++++++++----------- tools/py/schema.py | 17 +++-- 8 files changed, 117 insertions(+), 114 deletions(-) diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/account.rs b/cairo_vm_hints/src/hint_processor/models/proofs/account.rs index 4888a032..0d1cca3c 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/account.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/account.rs @@ -6,17 +6,17 @@ use serde::{Deserialize, Serialize}; pub struct Account { pub address: Address, pub account_key: B256, - pub proof: MPTProof, + pub proofs: Vec, } impl Account { - pub fn new(address: Address, proof: MPTProof) -> Self { + pub fn new(address: Address, proofs: Vec) -> Self { // TODO: actually this is account trie leaf to be more accurate let account_trie_leaf = keccak256(address); Account { address, account_key: account_trie_leaf, - proof, + proofs, } } } diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs b/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs index cc6fbfd9..b373c951 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs @@ -6,6 +6,7 @@ use serde_with::serde_as; #[serde_as] pub struct MPTProof { pub block_number: u64, + pub proof_bytes_len: u64, #[serde_as(as = "starknet_core::serde::unsigned_field_element::UfeHex")] pub proof: Vec, } diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs b/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs index 4b1e51d2..2137b0fa 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs @@ -7,18 +7,18 @@ pub struct Storage { pub address: Address, pub slot: B256, pub storage_key: StorageKey, - pub proof: MPTProof, + pub proofs: Vec, } impl Storage { - pub fn new(address: Address, slot: B256, proof: MPTProof) -> Self { + pub fn new(address: Address, slot: B256, proofs: Vec) -> Self { // TODO: actually this is storage leaf. slot == storage key let storage_trie_leaf = keccak256(slot); Storage { address, slot, storage_key: storage_trie_leaf, - proof, + proofs, } } } diff --git a/src/verifiers/evm/account_verifier.cairo b/src/verifiers/evm/account_verifier.cairo index 27c6a118..be295192 100644 --- a/src/verifiers/evm/account_verifier.cairo +++ b/src/verifiers/evm/account_verifier.cairo @@ -37,36 +37,40 @@ func verify_accounts_inner{ evm_memorizer: DictAccess*, chain_info: ChainInfo, pow2_array: felt*, -}(n_accounts: felt, index: felt) { +}(n_accounts: felt, idx: felt) { alloc_locals; - if (n_accounts == index) { + if (n_accounts == idx) { return (); } let (address: felt*) = alloc(); + %{ + account = batch.accounts[ids.idx] + segments.write_arg(ids.address, [int(x, 16) for x in account.address])) + %} + local key: Uint256; - local key_leading_zeros: felt; %{ - from tools.py.utils import split_128, count_leading_zero_nibbles_from_hex, hex_to_int_array, nested_hex_to_int_array - account = batch["accounts"][ids.index] - ids.key_leading_zeros = count_leading_zero_nibbles_from_hex(account["account_key"]) - segments.write_arg(ids.address, hex_to_int_array(account["address"])) - (key_low, key_high) = split_128(int(account["account_key"], 16)) - ids.key.low = key_low - ids.key.high = key_high + from tools.py.utils import split_128 + (ids.key.low, ids.key.high) = split_128(int(account.account_key, 16)) %} + local key_leading_zeros: felt; + %{ ids.key_leading_zeros = len(account.account_key.lstrip("0x")) - len(account.account_key.lstrip("0x").lstrip("0")) %} + // Validate MPT key matches address let (hash: Uint256) = keccak_bigend(address, 20); assert key.low = hash.low; assert key.high = hash.high; - local n_proofs: felt; - %{ ids.n_proofs = len(account["proofs"]) %} + let (felt_address) = le_address_chunks_to_felt(address); - verify_account(address, key, key_leading_zeros, n_proofs, 0); + local n_proofs: felt = nondet %{ len(account.proofs) %}; + verify_account( + address=felt_address, key=key, key_leading_zeros=key_leading_zeros, n_proofs=n_proofs, idx=0 + ); - return verify_accounts_inner(n_accounts=n_accounts, index=index + 1); + return verify_accounts_inner(n_accounts=n_accounts, idx=idx + 1); } func verify_account{ @@ -77,24 +81,21 @@ func verify_account{ evm_memorizer: DictAccess*, chain_info: ChainInfo, pow2_array: felt*, -}(address: felt*, key: Uint256, key_leading_zeros: felt, n_proofs: felt, proof_idx: felt) { +}(address: felt, key: Uint256, key_leading_zeros: felt, n_proofs: felt, idx: felt) { alloc_locals; - if (proof_idx == n_proofs) { + if (idx == n_proofs) { return (); } - local block_number: felt; - let (mpt_proof: felt**) = alloc(); - local proof_len: felt; + %{ proof = account.proofs[ids.idx] %} + local proof_len: felt = nondet %{ len(proof.proof) %}; + local block_number: felt = nondet %{ proof.block_number %}; + let (proof_bytes_len: felt*) = alloc(); + %{ segments.write_arg(ids.proof_bytes_len, proof.proof_bytes_len) %} - %{ - proof = account["proofs"][ids.proof_idx] - ids.block_number = proof["block_number"] - segments.write_arg(ids.mpt_proof, nested_hex_to_int_array(proof["proof"])) - segments.write_arg(ids.proof_bytes_len, proof["proof_bytes_len"]) - ids.proof_len = len(proof["proof"]) - %} + let (mpt_proof: felt**) = alloc(); + %{ segments.write_arg(ids.mpt_proof, [int(x, 16) for x in proof.proof]) %} // get state_root from verified headers let memorizer_key = EvmHashParams.header(chain_id=chain_info.id, block_number=block_number); @@ -111,11 +112,9 @@ func verify_account{ pow2_array=pow2_array, ); - let (felt_address) = le_address_chunks_to_felt(address); - // add account to memorizer let memorizer_key = EvmHashParams.account( - chain_id=chain_info.id, block_number=block_number, address=felt_address + chain_id=chain_info.id, block_number=block_number, address=address ); EvmMemorizer.add(key=memorizer_key, data=rlp); @@ -124,6 +123,6 @@ func verify_account{ key=key, key_leading_zeros=key_leading_zeros, n_proofs=n_proofs, - proof_idx=proof_idx + 1, + idx=idx + 1, ); } diff --git a/src/verifiers/evm/block_tx_verifier.cairo b/src/verifiers/evm/block_tx_verifier.cairo index 86a940cd..deedaa05 100644 --- a/src/verifiers/evm/block_tx_verifier.cairo +++ b/src/verifiers/evm/block_tx_verifier.cairo @@ -28,11 +28,11 @@ func verify_block_tx_proofs{ pow2_array: felt*, }() { alloc_locals; - local n_tx_proofs: felt; %{ ids.n_tx_proofs = len(batch.transactions) %} verify_block_tx_proofs_inner(n_tx_proofs, 0); + return (); } @@ -44,32 +44,33 @@ func verify_block_tx_proofs_inner{ evm_memorizer: DictAccess*, chain_info: ChainInfo, pow2_array: felt*, -}(n_tx_proofs: felt, index: felt) { +}(n_tx_proofs: felt, idx: felt) { alloc_locals; - if (n_tx_proofs == index) { + if (n_tx_proofs == idx) { return (); } - local block_number: felt; - local proof_len: felt; - let (mpt_proof: felt**) = alloc(); - let (proof_bytes_len: felt*) = alloc(); + %{ transaction = transactions[ids.idx] %} + local key: Uint256; - local key_leading_zeros: felt; %{ - from tools.py.utils import split_128, count_leading_zero_nibbles_from_hex, hex_to_int_array, nested_hex_to_int_array - transaction = batch["transactions"][ids.index] - ids.key_leading_zeros = count_leading_zero_nibbles_from_hex(transaction["key"]) - (key_low, key_high) = split_128(int(transaction["key"], 16)) - ids.key.low = key_low - ids.key.high = key_high - ids.block_number = transaction["block_number"] - segments.write_arg(ids.mpt_proof, nested_hex_to_int_array(transaction["proof"])) - segments.write_arg(ids.proof_bytes_len, transaction["proof_bytes_len"]) - ids.proof_len = len(transaction["proof"]) + from tools.py.utils import split_128 + (ids.key.low, ids.key.high) = split_128(int(transaction.key, 16)) %} + local key_leading_zeros: felt; + %{ ids.key_leading_zeros = len(transaction.key.lstrip("0x")) - len(transaction.key.lstrip("0x").lstrip("0")) %} + + local proof_len: felt = nondet %{ len(transaction.proof) %}; + local block_number: felt = nondet %{ transaction.block_number %}; + + let (proof_bytes_len: felt*) = alloc(); + %{ segments.write_arg(ids.proof_bytes_len, transaction.proof_bytes_len) %} + + let (mpt_proof: felt**) = alloc(); + %{ segments.write_arg(ids.mpt_proof, [int(x, 16) for x in transaction.proof]) %} + let memorizer_key = EvmHashParams.header(chain_id=chain_info.id, block_number=block_number); let (header_rlp) = EvmMemorizer.get(key=memorizer_key); let tx_root = HeaderDecoder.get_field(header_rlp, HeaderField.TRANSACTION_ROOT); @@ -92,5 +93,5 @@ func verify_block_tx_proofs_inner{ ); EvmMemorizer.add(key=memorizer_key, data=rlp); - return verify_block_tx_proofs_inner(n_tx_proofs=n_tx_proofs, index=index + 1); + return verify_block_tx_proofs_inner(n_tx_proofs=n_tx_proofs, idx=idx + 1); } diff --git a/src/verifiers/evm/receipt_verifier.cairo b/src/verifiers/evm/receipt_verifier.cairo index ba45db0b..c2418cae 100644 --- a/src/verifiers/evm/receipt_verifier.cairo +++ b/src/verifiers/evm/receipt_verifier.cairo @@ -32,6 +32,7 @@ func verify_block_receipt_proofs{ %{ ids.n_receipts = len(batch.receipts) %} verify_block_receipt_proofs_inner(n_receipts, 0); + return (); } @@ -43,33 +44,33 @@ func verify_block_receipt_proofs_inner{ evm_memorizer: DictAccess*, chain_info: ChainInfo, pow2_array: felt*, -}(n_receipts: felt, index: felt) { +}(n_receipts: felt, idx: felt) { alloc_locals; - if (n_receipts == index) { + if (n_receipts == idx) { return (); } - local block_number: felt; - local proof_len: felt; - let (mpt_proof: felt**) = alloc(); - let (proof_bytes_len: felt*) = alloc(); + %{ receipt = receipts[ids.idx] %} + local key: Uint256; - local key_leading_zeros: felt; %{ - from tools.py.utils import split_128, count_leading_zero_nibbles_from_hex, hex_to_int_array, nested_hex_to_int_array - - transaction = batch["transaction_receipts"][ids.index] - ids.key_leading_zeros = count_leading_zero_nibbles_from_hex(transaction["key"]) - (key_low, key_high) = split_128(int(transaction["key"], 16)) - ids.key.low = key_low - ids.key.high = key_high - ids.block_number = transaction["block_number"] - segments.write_arg(ids.mpt_proof, nested_hex_to_int_array(transaction["proof"])) - segments.write_arg(ids.proof_bytes_len, transaction["proof_bytes_len"]) - ids.proof_len = len(transaction["proof"]) + from tools.py.utils import split_128 + (ids.key.low, ids.key.high) = split_128(int(receipt.key, 16)) %} + local key_leading_zeros: felt; + %{ ids.key_leading_zeros = len(receipt.key.lstrip("0x")) - len(receipt.key.lstrip("0x").lstrip("0")) %} + + local proof_len: felt = nondet %{ len(receipt.proof) %}; + local block_number: felt = nondet %{ receipt.block_number %}; + + let (proof_bytes_len: felt*) = alloc(); + %{ segments.write_arg(ids.proof_bytes_len, receipt.proof_bytes_len) %} + + let (mpt_proof: felt**) = alloc(); + %{ segments.write_arg(ids.mpt_proof, [int(x, 16) for x in receipt.proof]) %} + let memorizer_key = EvmHashParams.header(chain_id=chain_info.id, block_number=block_number); let (header_rlp) = EvmMemorizer.get(key=memorizer_key); let receipt_root = HeaderDecoder.get_field(header_rlp, HeaderField.RECEIPT_ROOT); @@ -93,5 +94,5 @@ func verify_block_receipt_proofs_inner{ ); EvmMemorizer.add(key=memorizer_key, data=rlp); - return verify_block_receipt_proofs_inner(n_receipts=n_receipts, index=index + 1); + return verify_block_receipt_proofs_inner(n_receipts=n_receipts, idx=idx + 1); } diff --git a/src/verifiers/evm/storage_item_verifier.cairo b/src/verifiers/evm/storage_item_verifier.cairo index 8d8f4bbb..f804b409 100644 --- a/src/verifiers/evm/storage_item_verifier.cairo +++ b/src/verifiers/evm/storage_item_verifier.cairo @@ -43,31 +43,31 @@ func verify_storage_items_inner{ evm_memorizer: DictAccess*, chain_info: ChainInfo, pow2_array: felt*, -}(n_storage_items: felt, index: felt) { +}(n_storage_items: felt, idx: felt) { alloc_locals; - if (n_storage_items == index) { + if (n_storage_items == idx) { return (); } let (address: felt*) = alloc(); + %{ + storage = batch.storages[ids.idx] + segments.write_arg(ids.address, [int(x, 16) for x in storage.address])) + %} + let (slot: felt*) = alloc(); - local n_proofs: felt; + %{ segments.write_arg(ids.slot, [int(x, 16) for x in storage.slot])) %} + local key: Uint256; - local key_leading_zeros: felt; %{ - from tools.py.utils import split_128, count_leading_zero_nibbles_from_hex, hex_to_int_array, nested_hex_to_int_array - - storage_item = batch["storages"][ids.index] - ids.n_proofs = len(storage_item["proofs"]) - segments.write_arg(ids.address, hex_to_int_array(storage_item["address"])) - segments.write_arg(ids.slot, hex_to_int_array(storage_item["slot"])) - (key_low, key_high) = split_128(int(storage_item["storage_key"], 16)) - ids.key.low = key_low - ids.key.high = key_high - ids.key_leading_zeros = count_leading_zero_nibbles_from_hex(storage_item["storage_key"]) + from tools.py.utils import split_128 + (ids.key.low, ids.key.high) = split_128(int(storage.storage_key, 16)) %} + local key_leading_zeros: felt; + %{ ids.key_leading_zeros = len(storage.storage_key.lstrip("0x")) - len(storage.storage_key.lstrip("0x").lstrip("0")) %} + // ensure that slot matches the key let (hash: Uint256) = keccak_bigend(slot, 32); assert key.low = hash.low; @@ -79,16 +79,17 @@ func verify_storage_items_inner{ let (felt_address) = le_address_chunks_to_felt(address); + local n_proofs: felt = nondet %{ len(storage.proofs) %}; verify_storage_item( address=felt_address, slot=slot_be, key=key, key_leading_zeros=key_leading_zeros, n_proofs=n_proofs, - proof_idx=0, + idx=0, ); - return verify_storage_items_inner(n_storage_items=n_storage_items, index=index + 1); + return verify_storage_items_inner(n_storage_items=n_storage_items, idx=idx + 1); } func verify_storage_item{ @@ -99,31 +100,22 @@ func verify_storage_item{ evm_memorizer: DictAccess*, chain_info: ChainInfo, pow2_array: felt*, -}( - address: felt, - slot: Uint256, - key: Uint256, - key_leading_zeros: felt, - n_proofs: felt, - proof_idx: felt, -) { +}(address: felt, slot: Uint256, key: Uint256, key_leading_zeros: felt, n_proofs: felt, idx: felt) { alloc_locals; - if (n_proofs == proof_idx) { + if (n_proofs == idx) { return (); } - local block_number: felt; - local proof_len: felt; - let (mpt_proof: felt**) = alloc(); + %{ proof = storage.proofs[ids.idx] %} + local proof_len: felt = nondet %{ len(proof.proof) %}; + local block_number: felt = nondet %{ proof.block_number %}; + let (proof_bytes_len: felt*) = alloc(); - %{ - proof = storage_item["proofs"][ids.proof_idx] - ids.block_number = proof["block_number"] - segments.write_arg(ids.mpt_proof, nested_hex_to_int_array(proof["proof"])) - segments.write_arg(ids.proof_bytes_len, proof["proof_bytes_len"]) - ids.proof_len = len(proof["proof"]) - %} + %{ segments.write_arg(ids.proof_bytes_len, proof.proof_bytes_len) %} + + let (mpt_proof: felt**) = alloc(); + %{ segments.write_arg(ids.mpt_proof, [int(x, 16) for x in proof.proof]) %} let memorizer_key = EvmHashParams.account( chain_id=chain_info.id, block_number=block_number, address=address @@ -152,6 +144,6 @@ func verify_storage_item{ key=key, key_leading_zeros=key_leading_zeros, n_proofs=n_proofs, - proof_idx=proof_idx + 1, + idx=idx + 1, ); } diff --git a/tools/py/schema.py b/tools/py/schema.py index f10323b9..87e856d1 100644 --- a/tools/py/schema.py +++ b/tools/py/schema.py @@ -16,6 +16,7 @@ @marshmallow_dataclass.dataclass(frozen=True) class MPTProof: block_number: int + proof_bytes_len: int proof: List[str] = field( metadata=additional_metadata(marshmallow_field=mfields.List(IntAsHex())) ) @@ -48,7 +49,11 @@ class Header: class Account: address: str account_key: str - proof: MPTProof + proofs: List[MPTProof] = field( + metadata=additional_metadata( + marshmallow_field=mfields.List(mfields.Nested(MPTProof.Schema)) + ) + ) @marshmallow_dataclass.dataclass(frozen=True) @@ -56,19 +61,23 @@ class Storage: address: str slot: str storage_key: str - proof: MPTProof + proofs: List[MPTProof] = field( + metadata=additional_metadata( + marshmallow_field=mfields.List(mfields.Nested(MPTProof.Schema)) + ) + ) @marshmallow_dataclass.dataclass(frozen=True) class Transaction: key: str - proof: MPTProof + proofs: MPTProof @marshmallow_dataclass.dataclass(frozen=True) class Receipt: key: str - proof: MPTProof + proofs: MPTProof @marshmallow_dataclass.dataclass(frozen=True) From 48cd989cf5a360dc99981541bb7ef680a5bad883 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 10 Dec 2024 13:06:23 +0100 Subject: [PATCH 11/75] fixes --- src/verifiers/evm/account_verifier.cairo | 3 +-- src/verifiers/evm/block_tx_verifier.cairo | 3 +-- src/verifiers/evm/receipt_verifier.cairo | 4 +--- src/verifiers/evm/storage_item_verifier.cairo | 3 +-- src/verifiers/starknet/header_verifier.cairo | 19 +++++++------------ src/verifiers/starknet/storage_verifier.cairo | 3 +-- 6 files changed, 12 insertions(+), 23 deletions(-) diff --git a/src/verifiers/evm/account_verifier.cairo b/src/verifiers/evm/account_verifier.cairo index be295192..480f7f57 100644 --- a/src/verifiers/evm/account_verifier.cairo +++ b/src/verifiers/evm/account_verifier.cairo @@ -21,9 +21,8 @@ func verify_accounts{ pow2_array: felt*, }() { alloc_locals; - local n_accounts: felt; - %{ ids.n_accounts = len(batch.accounts) %} + local n_accounts: felt = nondet %{ len(batch.accounts) %}; verify_accounts_inner(n_accounts, 0); return (); diff --git a/src/verifiers/evm/block_tx_verifier.cairo b/src/verifiers/evm/block_tx_verifier.cairo index deedaa05..1f5a55b1 100644 --- a/src/verifiers/evm/block_tx_verifier.cairo +++ b/src/verifiers/evm/block_tx_verifier.cairo @@ -28,9 +28,8 @@ func verify_block_tx_proofs{ pow2_array: felt*, }() { alloc_locals; - local n_tx_proofs: felt; - %{ ids.n_tx_proofs = len(batch.transactions) %} + local n_tx_proofs: felt = nondet %{ len(batch.transactions) %}; verify_block_tx_proofs_inner(n_tx_proofs, 0); return (); diff --git a/src/verifiers/evm/receipt_verifier.cairo b/src/verifiers/evm/receipt_verifier.cairo index c2418cae..3120d39b 100644 --- a/src/verifiers/evm/receipt_verifier.cairo +++ b/src/verifiers/evm/receipt_verifier.cairo @@ -28,9 +28,7 @@ func verify_block_receipt_proofs{ }() { alloc_locals; - local n_receipts: felt; - %{ ids.n_receipts = len(batch.receipts) %} - + local n_receipts: felt = nondet %{ len(batch.receipts) %}; verify_block_receipt_proofs_inner(n_receipts, 0); return (); diff --git a/src/verifiers/evm/storage_item_verifier.cairo b/src/verifiers/evm/storage_item_verifier.cairo index f804b409..49a5eff6 100644 --- a/src/verifiers/evm/storage_item_verifier.cairo +++ b/src/verifiers/evm/storage_item_verifier.cairo @@ -27,9 +27,8 @@ func verify_storage_items{ pow2_array: felt*, }() { alloc_locals; - local n_storage_items: felt; - %{ ids.n_storage_items = len(batch.storages) %} + local n_storage_items: felt = nondet %{ len(batch.storages) %}; verify_storage_items_inner(n_storage_items, 0); return (); diff --git a/src/verifiers/starknet/header_verifier.cairo b/src/verifiers/starknet/header_verifier.cairo index 07691c08..f9a1ce98 100644 --- a/src/verifiers/starknet/header_verifier.cairo +++ b/src/verifiers/starknet/header_verifier.cairo @@ -55,15 +55,14 @@ func verify_headers_with_mmr_peaks{ } let (fields) = alloc(); - local fields_len: felt; - local leaf_idx: felt; %{ - header = mmr_batch["headers"][ids.idx - 1] - segments.write_arg(ids.fields, hex_to_int_array(header["fields"])) - ids.fields_len = len(header["fields"]) - ids.leaf_idx = header["proof"]["leaf_idx"] + header = batch.headers[ids.idx - 1] + segments.write_arg(ids.fields, [int(x, 16) for x in header.fields]) %} + local fields_len: felt = nondet %{ len(header.fields) %}; + local leaf_idx: felt = nondet %{ len(header.proof.leaf_idx) %}; + // compute the hash of the header let (header_hash) = poseidon_hash_many(n=fields_len, elements=fields); @@ -82,12 +81,8 @@ func verify_headers_with_mmr_peaks{ } let (mmr_path) = alloc(); - local mmr_path_len: felt; - %{ - proof = header["proof"] - segments.write_arg(ids.mmr_path, hex_to_int_array(proof["mmr_path"])) - ids.mmr_path_len = len(proof["mmr_path"]) - %} + local mmr_path_len: felt = nondet %{ len(header.proof.mmr_path) %}; + %{ segments.write_arg(ids.mmr_path, [int(x, 16) for x in header.proof.mmr_path]) %} // compute the peak of the header let (computed_peak) = hash_subtree_path( diff --git a/src/verifiers/starknet/storage_verifier.cairo b/src/verifiers/starknet/storage_verifier.cairo index c1a07b3d..06b31bd4 100644 --- a/src/verifiers/starknet/storage_verifier.cairo +++ b/src/verifiers/starknet/storage_verifier.cairo @@ -28,9 +28,8 @@ func verify_proofs{ pow2_array: felt*, }() { alloc_locals; - local n_storage_items: felt; - %{ ids.n_storage_items = len(batch["storages"]) %} + local n_storage_items: felt = nondet %{ len(batch.storages) %}; verify_proofs_loop(n_storage_items, 0); return (); From 49cb27b087a85fe39e2379d109e3b8ab97a75a62 Mon Sep 17 00:00:00 2001 From: codyx Date: Tue, 10 Dec 2024 23:20:51 +0400 Subject: [PATCH 12/75] Add dry run and run input hints with corresponding implementations - Introduced `dry_run_input.rs` and `run_input.rs` to handle new hint processing for HDP dry run and run inputs. - Updated `mod.rs` to include new modules and integrate the new hint functions. - Added utility function `hint_print_task_result` in `utils.rs` for printing task results. - Enhanced hint processing logic to accommodate new hints and ensure proper execution scope management. --- .../{input.rs => dry_run_input.rs} | 4 +- cairo_vm_hints/src/hint_processor/mod.rs | 8 ++-- .../src/hint_processor/run_input.rs | 31 ++++++++++++++ cairo_vm_hints/src/hints/lib/verifiers/mod.rs | 1 + .../src/hints/lib/verifiers/utils.rs | 40 +++++++++++++++++++ 5 files changed, 79 insertions(+), 5 deletions(-) rename cairo_vm_hints/src/hint_processor/{input.rs => dry_run_input.rs} (80%) create mode 100644 cairo_vm_hints/src/hint_processor/run_input.rs create mode 100644 cairo_vm_hints/src/hints/lib/verifiers/utils.rs diff --git a/cairo_vm_hints/src/hint_processor/input.rs b/cairo_vm_hints/src/hint_processor/dry_run_input.rs similarity index 80% rename from cairo_vm_hints/src/hint_processor/input.rs rename to cairo_vm_hints/src/hint_processor/dry_run_input.rs index abce7b6a..ec92257a 100644 --- a/cairo_vm_hints/src/hint_processor/input.rs +++ b/cairo_vm_hints/src/hint_processor/dry_run_input.rs @@ -12,10 +12,10 @@ use cairo_vm::{ }; use std::collections::HashMap; -pub const HINT_INPUT: &str = "from tools.py.schema import HDPDryRunInput\ndry_run_input = HDPDryRunInput.Schema().load(program_input)\nparams = dry_run_input.params\ncompiled_class = dry_run_input.compiled_class"; +pub const HINT_DRY_RUN_INPUT: &str = "from tools.py.schema import HDPDryRunInput\ndry_run_input = HDPDryRunInput.Schema().load(program_input)\nparams = dry_run_input.params\ncompiled_class = dry_run_input.compiled_class"; impl CustomHintProcessor { - pub fn hint_input( + pub fn hint_dry_run_input( &mut self, _vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index b0a56d8f..233d1f53 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -1,6 +1,7 @@ -pub mod input; +pub mod dry_run_input; pub mod models; pub mod output; +pub mod run_input; use crate::hints::{lib, vars}; use crate::syscall_handler::SyscallHandlerWrapper; @@ -83,10 +84,10 @@ impl CustomHintProcessor { hints.insert(lib::segments::SEGMENTS_ADD_EVM_MEMORIZER_OFFSET.into(), lib::segments::segments_add_evm_memorizer_offset); hints.insert(lib::segments::SEGMENTS_ADD_EVM_STARKNET_MEMORIZER_INDEX.into(), lib::segments::segments_add_evm_starknet_memorizer_index); hints.insert(lib::segments::SEGMENTS_ADD_STARKNET_MEMORIZER_OFFSET.into(), lib::segments::segments_add_starknet_memorizer_offset); + hints.insert(lib::verifiers::utils::HINT_PRINT_TASK_RESULT.into(), lib::verifiers::utils::hint_print_task_result); hints.insert(lib::verifiers::verify::HINT_BATCH_LEN.into(), lib::verifiers::verify::hint_batch_len); hints.insert(lib::verifiers::verify::HINT_CHAIN_ID.into(), lib::verifiers::verify::hint_chain_id); hints.insert(lib::verifiers::verify::HINT_VM_ENTER_SCOPE.into(), lib::verifiers::verify::hint_vm_enter_scope); - hints } @@ -120,7 +121,8 @@ impl HintProcessorLogic for CustomHintProcessor { let hint_code = hpd.code.as_str(); let res = match hint_code { - crate::hint_processor::input::HINT_INPUT => self.hint_input(vm, exec_scopes, hpd, constants), + crate::hint_processor::dry_run_input::HINT_DRY_RUN_INPUT => self.hint_dry_run_input(vm, exec_scopes, hpd, constants), + crate::hint_processor::run_input::HINT_RUN_INPUT => self.hint_run_input(vm, exec_scopes, hpd, constants), crate::hint_processor::output::HINT_OUTPUT => self.hint_output(vm, exec_scopes, hpd, constants), _ => Err(HintError::UnknownHint(hint_code.to_string().into_boxed_str())), }; diff --git a/cairo_vm_hints/src/hint_processor/run_input.rs b/cairo_vm_hints/src/hint_processor/run_input.rs new file mode 100644 index 00000000..0f90f864 --- /dev/null +++ b/cairo_vm_hints/src/hint_processor/run_input.rs @@ -0,0 +1,31 @@ +use super::{ + models::{param::Param, proofs::Proofs, HDPInput}, + CustomHintProcessor, +}; +use crate::hints::vars; +use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; +use cairo_vm::{ + hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData, + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use std::collections::HashMap; + +pub const HINT_RUN_INPUT: &str = "from tools.py.schema import HDPInput\nrun_input = HDPInput.Schema().load(program_input)\nproofs = run_input.proofs\nparams = run_input.params\ncompiled_class = run_input.compiled_class"; + +impl CustomHintProcessor { + pub fn hint_run_input( + &mut self, + _vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, + ) -> Result<(), HintError> { + let hdp_input: HDPInput = serde_json::from_value(self.private_inputs.clone()).map_err(|_| HintError::WrongHintData)?; + exec_scopes.insert_value::>(vars::scopes::PROOFS, hdp_input.proofs); + exec_scopes.insert_value::>(vars::scopes::PARAMS, hdp_input.params); + exec_scopes.insert_value::(vars::scopes::COMPILED_CLASS, hdp_input.compiled_class); + Ok(()) + } +} diff --git a/cairo_vm_hints/src/hints/lib/verifiers/mod.rs b/cairo_vm_hints/src/hints/lib/verifiers/mod.rs index a8118c56..cc8e1d68 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/mod.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/mod.rs @@ -1 +1,2 @@ +pub mod utils; pub mod verify; diff --git a/cairo_vm_hints/src/hints/lib/verifiers/utils.rs b/cairo_vm_hints/src/hints/lib/verifiers/utils.rs new file mode 100644 index 00000000..67152026 --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/verifiers/utils.rs @@ -0,0 +1,40 @@ +use cairo_vm::hint_processor::builtin_hint_processor::{ + builtin_hint_processor_definition::HintProcessorData, hint_utils::get_relocatable_from_var_name, +}; +use cairo_vm::{ + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use num_bigint::BigUint; +use std::collections::HashMap; + +use crate::hints::vars; + +pub const HINT_PRINT_TASK_RESULT: &str = "print(f\"Task Result: {hex(ids.result.high * 2 ** 128 + ids.result.low)}\")"; + +pub fn hint_print_task_result( + vm: &mut VirtualMachine, + _exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let result_ptr = get_relocatable_from_var_name(vars::ids::RESULT, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + + let result = vm + .get_continuous_range(result_ptr, 2)? + .into_iter() + .map(|v| v.get_int().unwrap()) + .collect::>(); + + let result_low = result[0].to_biguint(); + let result_high = result[1].to_biguint(); + let base = BigUint::from(2u32).pow(128); + + let result_value = result_high * base + result_low; + + // TODO: add appropriate logger + println!("Task Result: 0x{:x}", result_value); + + Ok(()) +} From cd1cb301550ae2750d53b67bab8a537f7fc95ec0 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 11 Dec 2024 09:27:28 +0100 Subject: [PATCH 13/75] alloy provider --- cairo_vm_hints/src/cairo_types/evm/account.rs | 11 +- cairo_vm_hints/src/provider/evm/mod.rs | 122 ------------------ cairo_vm_hints/src/provider/evm/traits.rs | 13 -- .../src/syscall_handler/evm/dryrun/account.rs | 7 +- .../src/syscall_handler/evm/dryrun/header.rs | 11 +- .../src/syscall_handler/evm/dryrun/storage.rs | 16 ++- 6 files changed, 25 insertions(+), 155 deletions(-) delete mode 100644 cairo_vm_hints/src/provider/evm/traits.rs diff --git a/cairo_vm_hints/src/cairo_types/evm/account.rs b/cairo_vm_hints/src/cairo_types/evm/account.rs index 11c003eb..b7aa5bd3 100644 --- a/cairo_vm_hints/src/cairo_types/evm/account.rs +++ b/cairo_vm_hints/src/cairo_types/evm/account.rs @@ -59,14 +59,9 @@ impl CairoAccount { } } -impl From for CairoAccount { - fn from(value: EIP1186AccountProofResponse) -> Self { - Self(Account { - nonce: value.nonce, - balance: value.balance, - storage_root: value.storage_hash, - code_hash: value.code_hash, - }) +impl From for CairoAccount { + fn from(value: Account) -> Self { + Self(value) } } diff --git a/cairo_vm_hints/src/provider/evm/mod.rs b/cairo_vm_hints/src/provider/evm/mod.rs index 54c2db54..8b137891 100644 --- a/cairo_vm_hints/src/provider/evm/mod.rs +++ b/cairo_vm_hints/src/provider/evm/mod.rs @@ -1,123 +1 @@ -use alloy::{ - hex::ToHexExt, - primitives::{Address, BlockNumber, StorageKey, StorageValue, B256}, - rpc::{ - client::{ClientBuilder, ReqwestClient, Waiter}, - types::{Block, EIP1186AccountProofResponse, Receipt, Transaction}, - }, - transports::{http::reqwest::Url, RpcError, TransportErrorKind}, -}; -use serde_json::json; -use traits::EVMProviderTrait; -pub mod traits; - -pub struct EVMProvider { - client: ReqwestClient, -} - -impl EVMProvider { - pub fn new(url: Url) -> Self { - Self { - client: ClientBuilder::default().http(url), - } - } -} - -impl EVMProviderTrait for EVMProvider { - async fn get_account(&self, address: Address, block_number: BlockNumber) -> Result> { - let mut batch = self.client.new_batch(); - let fut: Waiter = batch.add_call( - "eth_getProof", - &json!([ - address.encode_hex_with_prefix(), - [], - format!("0x{}", block_number.to_be_bytes().encode_hex().trim_start_matches('0')) - ]), - )?; - batch.send().await?; - fut.await - } - - async fn get_block(&self, block_number: BlockNumber) -> Result> { - let mut batch = self.client.new_batch(); - let fut = batch.add_call( - "eth_getBlockByNumber", - &json!([format!("0x{}", block_number.to_be_bytes().encode_hex().trim_start_matches('0')), false]), - )?; - batch.send().await?; - fut.await - } - - async fn get_transaction_receipt(&self, hash: B256) -> Result> { - let mut batch = self.client.new_batch(); - let fut = batch.add_call("eth_getTransactionReceipt", &json!([hash.encode_hex_with_prefix()]))?; - batch.send().await?; - fut.await - } - - async fn get_transaction(&self, hash: B256) -> Result> { - let mut batch = self.client.new_batch(); - let fut = batch.add_call("eth_getTransactionByHash", &json!([hash.encode_hex_with_prefix()]))?; - batch.send().await?; - fut.await - } - - async fn get_storage(&self, address: Address, block_number: BlockNumber, key: StorageKey) -> Result> { - let mut batch = self.client.new_batch(); - let fut = batch.add_call( - "eth_getStorageAt", - &json!([ - address.encode_hex_with_prefix(), - key.encode_hex_with_prefix(), - format!("0x{}", block_number.to_be_bytes().encode_hex().trim_start_matches('0')) - ]), - )?; - batch.send().await?; - fut.await - } -} - -#[cfg(test)] -mod tests { - use super::{EVMProvider, EVMProviderTrait}; - use alloy::{ - hex::FromHex, - primitives::{Address, B256}, - }; - - const RPC_URL: &str = "https://eth-mainnet.g.alchemy.com/v2/u_DzVM70jRTQByTwvcdhjvgVRQE0dVnf"; - - #[tokio::test] - async fn test_get_account() { - let client = EVMProvider::new(RPC_URL.parse().unwrap()); - client - .get_account(Address::from_hex("F585A4aE338bC165D96E8126e8BBcAcAE725d79E").unwrap(), 20992954) - .await - .unwrap(); - } - - #[tokio::test] - async fn test_get_block() { - let client = EVMProvider::new(RPC_URL.parse().unwrap()); - client.get_block(20992954).await.unwrap(); - } - - #[tokio::test] - async fn test_get_recipt() { - let client = EVMProvider::new(RPC_URL.parse().unwrap()); - client - .get_transaction_receipt(B256::from_hex("237f99e622d67413956b8674cf16ea56b0ba0a18a9f68a5e254f4ac8d2050b51").unwrap()) - .await - .unwrap(); - } - - #[tokio::test] - async fn test_get_transaction() { - let client = EVMProvider::new(RPC_URL.parse().unwrap()); - client - .get_transaction(B256::from_hex("237f99e622d67413956b8674cf16ea56b0ba0a18a9f68a5e254f4ac8d2050b51").unwrap()) - .await - .unwrap(); - } -} diff --git a/cairo_vm_hints/src/provider/evm/traits.rs b/cairo_vm_hints/src/provider/evm/traits.rs deleted file mode 100644 index ae13c464..00000000 --- a/cairo_vm_hints/src/provider/evm/traits.rs +++ /dev/null @@ -1,13 +0,0 @@ -use alloy::{ - primitives::{Address, BlockNumber, StorageKey, StorageValue, B256}, - rpc::types::{Block, EIP1186AccountProofResponse, Receipt, Transaction}, - transports::{RpcError, TransportErrorKind}, -}; - -pub trait EVMProviderTrait { - async fn get_account(&self, address: Address, block_number: BlockNumber) -> Result>; - async fn get_block(&self, block_number: BlockNumber) -> Result>; - async fn get_storage(&self, address: Address, block_number: BlockNumber, key: StorageKey) -> Result>; - async fn get_transaction_receipt(&self, hash: B256) -> Result>; - async fn get_transaction(&self, hash: B256) -> Result>; -} diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs index 7cf15933..c23994bf 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs @@ -1,4 +1,3 @@ -use crate::provider::evm::{traits::EVMProviderTrait, EVMProvider}; use crate::syscall_handler::{ traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, @@ -12,6 +11,8 @@ use crate::{ }, syscall_handler::RPC, }; +use alloy::providers::{Provider, RootProvider}; +use alloy::transports::http::{Client, Http}; use alloy::{ hex::FromHex, primitives::{Address, BlockNumber, ChainId}, @@ -39,10 +40,10 @@ impl CallHandler for AccountCallHandler { } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { - let provider = EVMProvider::new(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let runtime = tokio::runtime::Runtime::new().unwrap(); let account = runtime - .block_on(async { provider.get_account(key.address, key.block_number).await }) + .block_on(async { provider.get_account(key.address).block_id(key.block_number.into()).await }) .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; Ok(CairoAccount::from(account).handle(function_id)) diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs index f451bfd1..126d300b 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs @@ -1,4 +1,3 @@ -use crate::provider::evm::{traits::EVMProviderTrait, EVMProvider}; use crate::syscall_handler::{ traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, @@ -12,6 +11,9 @@ use crate::{ }, syscall_handler::RPC, }; +use alloy::providers::{Provider, RootProvider}; +use alloy::rpc::types::BlockTransactionsKind; +use alloy::transports::http::{Client, Http}; use alloy::{ primitives::{BlockNumber, ChainId}, transports::http::reqwest::Url, @@ -38,11 +40,12 @@ impl CallHandler for HeaderCallHandler { } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { - let provider = EVMProvider::new(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let runtime = tokio::runtime::Runtime::new().unwrap(); let block = runtime - .block_on(async { provider.get_block(key.block_number).await }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + .block_on(async { provider.get_block_by_number(key.block_number.into(), BlockTransactionsKind::Hashes).await }) + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))? + .ok_or(SyscallExecutionError::InternalError("Block not found".into()))?; Ok(CairoHeader::from(block.header.inner).handle(function_id)) } diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs index 9bc94666..3e218ed3 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs @@ -1,4 +1,3 @@ -use crate::provider::evm::{traits::EVMProviderTrait, EVMProvider}; use crate::syscall_handler::{ traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, @@ -12,6 +11,8 @@ use crate::{ }, syscall_handler::RPC, }; +use alloy::providers::{Provider, RootProvider}; +use alloy::transports::http::{Client, Http}; use alloy::{ hex::FromHex, primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, @@ -39,13 +40,18 @@ impl CallHandler for StorageCallHandler { } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { - let provider = EVMProvider::new(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let runtime = tokio::runtime::Runtime::new().unwrap(); - let account = runtime - .block_on(async { provider.get_storage(key.address, key.block_number, key.storage_slot).await }) + let storage_value = runtime + .block_on(async { + provider + .get_storage_at(key.address, key.storage_slot.into()) + .block_id(key.block_number.into()) + .await + }) .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(CairoStorage::from(account).handle(function_id)) + Ok(CairoStorage::from(storage_value).handle(function_id)) } } From 1303193966d4edaa948df46cdff5c7b244d0127b Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 11 Dec 2024 10:51:19 +0100 Subject: [PATCH 14/75] indexer provider --- Cargo.lock | 78 +++++++++++ Cargo.toml | 3 +- cairo_vm_hints/Cargo.toml | 3 +- cairo_vm_hints/src/provider/indexer/mod.rs | 78 +++++++++++ cairo_vm_hints/src/provider/indexer/types.rs | 131 +++++++++++++++++++ cairo_vm_hints/src/provider/mod.rs | 1 + 6 files changed, 292 insertions(+), 2 deletions(-) create mode 100644 cairo_vm_hints/src/provider/indexer/mod.rs create mode 100644 cairo_vm_hints/src/provider/indexer/types.rs diff --git a/Cargo.lock b/Cargo.lock index d2c3009c..ce9afa9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -936,6 +936,12 @@ dependencies = [ "rustc_version 0.4.1", ] +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "auto_impl" version = "1.2.0" @@ -2092,6 +2098,15 @@ dependencies = [ "log", ] +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + [[package]] name = "equivalent" version = "1.0.1" @@ -2392,6 +2407,25 @@ dependencies = [ "subtle", ] +[[package]] +name = "h2" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccae279728d634d083c00f6099cb58f01cc99c145b84b8be2f6c74618d79922e" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap 2.6.0", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "hashbrown" version = "0.12.3" @@ -2443,6 +2477,7 @@ dependencies = [ "num-bigint", "num-traits", "rand", + "reqwest", "serde", "serde_json", "serde_with 3.11.0", @@ -2547,6 +2582,7 @@ dependencies = [ "bytes", "futures-channel", "futures-util", + "h2", "http", "http-body", "httparse", @@ -2557,6 +2593,23 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-rustls" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333" +dependencies = [ + "futures-util", + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tower-service", +] + [[package]] name = "hyper-tls" version = "0.6.0" @@ -3802,12 +3855,15 @@ checksum = "a77c62af46e79de0a562e1a9849205ffcb7fc1238876e9bd743357570e04046f" dependencies = [ "base64 0.22.1", "bytes", + "encoding_rs", "futures-core", "futures-util", + "h2", "http", "http-body", "http-body-util", "hyper", + "hyper-rustls", "hyper-tls", "hyper-util", "ipnet", @@ -3823,6 +3879,7 @@ dependencies = [ "serde_json", "serde_urlencoded", "sync_wrapper 1.0.2", + "system-configuration", "tokio", "tokio-native-tls", "tower-service", @@ -4685,6 +4742,27 @@ dependencies = [ "syn 2.0.89", ] +[[package]] +name = "system-configuration" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b" +dependencies = [ + "bitflags", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "tap" version = "1.0.1" diff --git a/Cargo.toml b/Cargo.toml index 5b223cfe..b4ebdbc7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,4 +27,5 @@ strum_macros = "0.26.4" serde_with = { version = "3.11.0", features = ["hex"] } starknet-core = { version = "0.11.1", default-features = false } starknet-crypto = { version = "0.7.1", default-features = false } -starknet-types-core = { version = "0.1.5", default-features = false } \ No newline at end of file +starknet-types-core = { version = "0.1.5", default-features = false } +reqwest = "0.12.9" \ No newline at end of file diff --git a/cairo_vm_hints/Cargo.toml b/cairo_vm_hints/Cargo.toml index 167741b7..4b8794ec 100644 --- a/cairo_vm_hints/Cargo.toml +++ b/cairo_vm_hints/Cargo.toml @@ -26,4 +26,5 @@ tiny-keccak.workspace = true tokio = { workspace = true } strum_macros.workspace = true serde_with.workspace = true -starknet-core.workspace = true \ No newline at end of file +starknet-core.workspace = true +reqwest.workspace = true \ No newline at end of file diff --git a/cairo_vm_hints/src/provider/indexer/mod.rs b/cairo_vm_hints/src/provider/indexer/mod.rs new file mode 100644 index 00000000..6473f3cc --- /dev/null +++ b/cairo_vm_hints/src/provider/indexer/mod.rs @@ -0,0 +1,78 @@ +pub mod types; + +use reqwest::Client; +use types::{IndexerError, IndexerHeadersProofResponse, IndexerQuery, MMRFromNewIndexer}; + +pub const HERODOTUS_RS_INDEXER_URL: &str = "https://rs-indexer.api.herodotus.cloud/accumulators/proofs"; + +#[derive(Clone)] +pub struct Indexer { + client: Client, +} + +impl Default for Indexer { + fn default() -> Self { + Self::new() + } +} + +impl Indexer { + pub fn new() -> Self { + Self { client: Client::new() } + } + + /// Fetch MMR and headers proof from Herodotus Indexer + pub async fn get_headers_proof(&self, query: IndexerQuery) -> Result { + let response = self + .client + .get(HERODOTUS_RS_INDEXER_URL) + .query(&query) + .send() + .await + .map_err(IndexerError::ReqwestError)?; + + if response.status().is_success() { + let parsed_mmr: MMRFromNewIndexer = + serde_json::from_value(response.json().await.map_err(IndexerError::ReqwestError)?).map_err(IndexerError::SerdeJsonError)?; + + if parsed_mmr.data.is_empty() { + Err(IndexerError::ValidationError("No MMR found".to_string())) + } else if parsed_mmr.data.len() > 1 { + Err(IndexerError::ValidationError("MMR length should be 1".to_string())) + } else { + let mmr_data = parsed_mmr.data[0].clone(); + if mmr_data.proofs.len() as usize != (query.to_block_number_inclusive - query.from_block_number_inclusive + 1) as usize { + Err(IndexerError::ValidationError( + "Indexer didn't return the correct number of headers that were requested".to_string(), + )) + } else { + Ok(IndexerHeadersProofResponse::new(mmr_data)) + } + } + } else { + Err(IndexerError::GetHeadersProofError( + response.text().await.map_err(IndexerError::ReqwestError)?, + )) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn test_get_headers_proof() { + let response = Indexer::default().get_headers_proof(IndexerQuery::new(11155111, 1, 1)).await.unwrap(); + assert_eq!(response.headers.len(), 1); + } + + #[tokio::test] + async fn test_get_headers_proof_multiple_blocks() { + let response = Indexer::default() + .get_headers_proof(IndexerQuery::new(11155111, 5800000, 5800010)) + .await + .unwrap(); + assert_eq!(response.headers.len(), 11); + } +} diff --git a/cairo_vm_hints/src/provider/indexer/types.rs b/cairo_vm_hints/src/provider/indexer/types.rs new file mode 100644 index 00000000..55e02942 --- /dev/null +++ b/cairo_vm_hints/src/provider/indexer/types.rs @@ -0,0 +1,131 @@ +use alloy::primitives::{BlockNumber, ChainId}; +use serde::{Deserialize, Serialize}; +use serde_with::serde_as; +use std::collections::HashMap; +use thiserror::Error; + +/// Enum for available hashing functions +#[derive(Debug, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum HashingFunction { + Keccak, + Poseidon, + Pedersen, +} + +/// Enum for available contract types +#[derive(Debug, Serialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum ContractType { + Aggregator, + Accumulator, + Remapper, +} + +/// Error from [`Indexer`] +#[derive(Error, Debug)] +pub enum IndexerError { + /// The block range provided is invalid. + #[error("Invalid block range")] + InvalidBlockRange, + + /// Failed to send a request using [`reqwest`]. + #[error("Failed to send request")] + ReqwestError(#[from] reqwest::Error), + + /// Failed to parse the response using [`serde_json`]. + #[error("Failed to parse response")] + SerdeJsonError(#[from] serde_json::Error), + + /// Validation error with a detailed message. + #[error("Validation error: {0}")] + ValidationError(String), + + /// Failed to get headers proof with a detailed message. + #[error("Failed to get headers proof: {0}")] + GetHeadersProofError(String), +} + +/// Query parameters for the indexer +#[derive(Debug, Serialize)] +pub struct IndexerQuery { + pub deployed_on_chain: ChainId, + pub accumulates_chain: ChainId, + pub hashing_function: HashingFunction, + pub contract_type: ContractType, + pub from_block_number_inclusive: BlockNumber, + pub to_block_number_inclusive: BlockNumber, + pub is_meta_included: bool, + pub is_whole_tree: bool, + pub is_rlp_included: bool, + pub is_pure_rlp: bool, +} + +impl IndexerQuery { + pub fn new(chain_id: ChainId, from_block: BlockNumber, to_block: BlockNumber) -> Self { + Self { + deployed_on_chain: chain_id, + accumulates_chain: chain_id, + hashing_function: HashingFunction::Poseidon, + contract_type: ContractType::Aggregator, + from_block_number_inclusive: from_block, + to_block_number_inclusive: to_block, + is_meta_included: true, + is_whole_tree: true, + is_rlp_included: true, + is_pure_rlp: true, + } + } +} + +/// MMR metadata and proof returned from indexer +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde(rename_all = "camelCase")] +pub struct MMRFromNewIndexer { + pub data: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct MMRDataFromNewIndexer { + pub meta: MMRMetaFromNewIndexer, + pub proofs: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct MMRMetaFromNewIndexer { + pub mmr_id: String, + pub mmr_peaks: Vec, + pub mmr_root: String, + pub mmr_size: u64, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +#[serde_as] +pub struct MMRProofFromNewIndexer { + pub block_number: u64, + pub element_hash: String, + pub element_index: u64, + pub block_header: BlockHeader, + pub siblings_hashes: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub enum BlockHeader { + RlpString(String), + RlpLittleEndian8ByteChunks(Vec), + Fields(Vec), +} + +#[derive(Debug)] +pub struct IndexerHeadersProofResponse { + pub mmr_meta: MMRMetaFromNewIndexer, + pub headers: HashMap, +} + +impl IndexerHeadersProofResponse { + pub fn new(mmr_data: MMRDataFromNewIndexer) -> Self { + let mmr_meta = mmr_data.meta; + let headers = mmr_data.proofs.into_iter().map(|block| (block.block_number, block)).collect(); + Self { mmr_meta, headers } + } +} diff --git a/cairo_vm_hints/src/provider/mod.rs b/cairo_vm_hints/src/provider/mod.rs index 9f3dd66d..c264f067 100644 --- a/cairo_vm_hints/src/provider/mod.rs +++ b/cairo_vm_hints/src/provider/mod.rs @@ -1,2 +1,3 @@ pub mod evm; +pub mod indexer; pub mod starknet; From 9cc0db7a7a9d124105275ed17f60dd67641c5eb5 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 11 Dec 2024 11:00:44 +0100 Subject: [PATCH 15/75] structs renamed --- cairo_vm_hints/src/provider/indexer/mod.rs | 4 ++-- cairo_vm_hints/src/provider/indexer/types.rs | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/cairo_vm_hints/src/provider/indexer/mod.rs b/cairo_vm_hints/src/provider/indexer/mod.rs index 6473f3cc..e04687fb 100644 --- a/cairo_vm_hints/src/provider/indexer/mod.rs +++ b/cairo_vm_hints/src/provider/indexer/mod.rs @@ -1,7 +1,7 @@ pub mod types; use reqwest::Client; -use types::{IndexerError, IndexerHeadersProofResponse, IndexerQuery, MMRFromNewIndexer}; +use types::{IndexerError, IndexerHeadersProofResponse, IndexerQuery, MMRResponse}; pub const HERODOTUS_RS_INDEXER_URL: &str = "https://rs-indexer.api.herodotus.cloud/accumulators/proofs"; @@ -32,7 +32,7 @@ impl Indexer { .map_err(IndexerError::ReqwestError)?; if response.status().is_success() { - let parsed_mmr: MMRFromNewIndexer = + let parsed_mmr: MMRResponse = serde_json::from_value(response.json().await.map_err(IndexerError::ReqwestError)?).map_err(IndexerError::SerdeJsonError)?; if parsed_mmr.data.is_empty() { diff --git a/cairo_vm_hints/src/provider/indexer/types.rs b/cairo_vm_hints/src/provider/indexer/types.rs index 55e02942..e8709ed0 100644 --- a/cairo_vm_hints/src/provider/indexer/types.rs +++ b/cairo_vm_hints/src/provider/indexer/types.rs @@ -81,18 +81,18 @@ impl IndexerQuery { /// MMR metadata and proof returned from indexer #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] -pub struct MMRFromNewIndexer { - pub data: Vec, +pub struct MMRResponse { + pub data: Vec, } #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct MMRDataFromNewIndexer { - pub meta: MMRMetaFromNewIndexer, - pub proofs: Vec, +pub struct MMRData { + pub meta: MMRMetadata, + pub proofs: Vec, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] -pub struct MMRMetaFromNewIndexer { +pub struct MMRMetadata { pub mmr_id: String, pub mmr_peaks: Vec, pub mmr_root: String, @@ -101,7 +101,7 @@ pub struct MMRMetaFromNewIndexer { #[derive(Serialize, Deserialize, Debug, Clone)] #[serde_as] -pub struct MMRProofFromNewIndexer { +pub struct MMRProof { pub block_number: u64, pub element_hash: String, pub element_index: u64, @@ -118,12 +118,12 @@ pub enum BlockHeader { #[derive(Debug)] pub struct IndexerHeadersProofResponse { - pub mmr_meta: MMRMetaFromNewIndexer, - pub headers: HashMap, + pub mmr_meta: MMRMetadata, + pub headers: HashMap, } impl IndexerHeadersProofResponse { - pub fn new(mmr_data: MMRDataFromNewIndexer) -> Self { + pub fn new(mmr_data: MMRData) -> Self { let mmr_meta = mmr_data.meta; let headers = mmr_data.proofs.into_iter().map(|block| (block.block_number, block)).collect(); Self { mmr_meta, headers } From f7f7816a762bb896e559bdbe3ba20b324dfd358b Mon Sep 17 00:00:00 2001 From: codyx Date: Wed, 11 Dec 2024 15:10:13 +0400 Subject: [PATCH 16/75] Refactor account verifier hints and utility functions - Simplified hex to integer array conversion in `utils/mod.rs`. - Enhanced `account_verifier.rs` with new hints for batch accounts length, account address retrieval, and proof handling. - Updated hint functions to improve clarity and maintainability. - Removed unused utility functions and streamlined existing logic for better performance. - Added new constants for account proof handling and improved integration with execution scopes. --- cairo_vm_hints/src/hints/lib/utils/mod.rs | 12 +- .../lib/verifiers/evm/account_verifier.rs | 235 ++++++++++++------ 2 files changed, 158 insertions(+), 89 deletions(-) diff --git a/cairo_vm_hints/src/hints/lib/utils/mod.rs b/cairo_vm_hints/src/hints/lib/utils/mod.rs index 7c850e61..ebf979a1 100644 --- a/cairo_vm_hints/src/hints/lib/utils/mod.rs +++ b/cairo_vm_hints/src/hints/lib/utils/mod.rs @@ -7,17 +7,7 @@ pub fn count_leading_zero_nibbles_from_hex(hex_str: &str) -> u32 { } pub fn hex_to_int_array(hex_array: &[&str]) -> Vec { - hex_array - .iter() - .map(|x| u32::from_str_radix(x, 16).expect("Invalid hex input")) - .collect() -} - -pub fn nested_hex_to_int_array(nested_hex_array: &[&[&str]]) -> Vec { - nested_hex_array - .iter() - .flat_map(|x| hex_to_int_array(x)) - .collect() + hex_array.iter().map(|x| u32::from_str_radix(x, 16).expect("Invalid hex input")).collect() } pub fn split_128(a: &BigUint) -> (BigUint, BigUint) { diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs index a77df3f0..107c2d60 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs @@ -1,9 +1,7 @@ use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, - hint_utils::{ - get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, - }, + hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, }, types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, @@ -13,83 +11,65 @@ use num_bigint::BigUint; use num_traits::Num; use std::collections::HashMap; -use crate::hints::{ - lib::utils::{ - count_leading_zero_nibbles_from_hex, hex_to_int_array, nested_hex_to_int_array, split_128, +use crate::{ + hint_processor::models::proofs::Proofs, + hints::{ + lib::utils::{count_leading_zero_nibbles_from_hex, split_128}, + vars, }, - vars, }; -pub const HINT_N_ACCOUNTS: &str = "ids.n_accounts = len(batch[\"accounts\"])"; +pub const HINT_BATCH_ACCOUNTS_LEN: &str = "len(batch[\"accounts\"])"; -pub fn hint_n_accounts( +pub fn hint_batch_accounts_len( vm: &mut VirtualMachine, - _exec_scope: &mut ExecutionScopes, - hint_data: &HintProcessorData, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - // TODO: Retrieve `batch["accounts"]` when supported. - let n_accounts = Felt252::from(0); + let batch = exec_scopes.get::("batch")?; - insert_value_from_var_name( - vars::ids::N_ACCOUNTS, - MaybeRelocatable::Int(n_accounts), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, - ) + insert_value_into_ap(vm, Felt252::from(batch.accounts.len())) } -pub const HINT_N_PROOFS: &str = "ids.n_proofs = len(account[\"proofs\"])"; +pub const HINT_GET_ACCOUNT_ADDRESS: &str = + "account = batch.accounts[ids.idx]\nsegments.write_arg(ids.address, [int(x, 16) for x in account.address])"; -pub fn hint_n_proofs( +pub fn hint_get_account_address( vm: &mut VirtualMachine, - _exec_scope: &mut ExecutionScopes, + exec_scopes: &mut ExecutionScopes, hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - // TODO: Retrieve `account["proofs"]` when supported. - let n_proofs = Felt252::from(0); + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let account = batch.accounts[idx].clone(); + let address = BigUint::from_str_radix(&account.address.to_string(), 16).unwrap(); - insert_value_from_var_name( - vars::ids::N_PROOFS, - MaybeRelocatable::Int(n_proofs), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, - ) + let address_ptr = get_ptr_from_var_name(vars::ids::ADDRESS, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.insert_value(address_ptr, Felt252::from(address))?; + + Ok(()) } -pub const HINT_ACCOUNT_KEY: &str = "from tools.py.utils import split_128, count_leading_zero_nibbles_from_hex, hex_to_int_array, nested_hex_to_int_array account = batch[\"accounts\"][ids.index] ids.key_leading_zeros = count_leading_zero_nibbles_from_hex(account[\"account_key\"]) segments.write_arg(ids.address, hex_to_int_array(account[\"address\"])) (key_low, key_high) = split_128(int(account[\"account_key\"], \"16\")) ids.key.low = key_low ids.key.high = key_high"; +pub const HINT_ACCOUNT_KEY: &str = "from tools.py.utils import split_128\n(ids.key.low, ids.key.high) = split_128(int(account.account_key, 16))"; pub fn hint_account_key( vm: &mut VirtualMachine, - _exec_scope: &mut ExecutionScopes, + exec_scopes: &mut ExecutionScopes, hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let _index = get_integer_from_var_name( - vars::ids::INDEX, - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, - )?; - // TODO: Retrieve account_key from`batch["accounts"][index]` when supported. - let account_key = ""; - let _key_leading_zeros = count_leading_zero_nibbles_from_hex(account_key); - - let address_ptr = get_ptr_from_var_name( - vars::ids::ADDRESS, - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, - )?; - - // TODO: Retrieve address from `batch["accounts"][index]["address"]` when supported. - let address_int_array = hex_to_int_array(&[]); - vm.write_arg(address_ptr, &address_int_array)?; - - let (key_low, key_high) = split_128(&BigUint::from_str_radix(account_key, 16).unwrap()); + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let account = batch.accounts[idx].clone(); + let account_key = BigUint::from_str_radix(&account.account_key.to_string(), 16).unwrap(); + + let (key_low, key_high) = split_128(&account_key); insert_value_from_var_name( vars::ids::KEY_LOW, MaybeRelocatable::Int(Felt252::from(key_low)), @@ -108,44 +88,143 @@ pub fn hint_account_key( Ok(()) } -pub const HINT_GET_MPT_PROOF: &str = "proof = account[\"proofs\"][ids.proof_idx] ids.block_number = proof[\"block_number\"] segments.write_arg(ids.mpt_proof, nested_hex_to_int_array(proof[\"proof\"])) segments.write_arg(ids.proof_bytes_len, proof[\"proof_bytes_len\"]) ids.proof_len = len(proof[\"proof\"])"; +pub const HINT_ACCOUNT_KEY_LEADING_ZEROS: &str = + "ids.key_leading_zeros = len(account.account_key.lstrip(\"0x\")) - len(account.account_key.lstrip(\"0x\").lstrip(\"0\"))"; -pub fn hint_get_mpt_proof( +pub fn hint_account_key_leading_zeros( vm: &mut VirtualMachine, - _exec_scope: &mut ExecutionScopes, + exec_scopes: &mut ExecutionScopes, hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - // TODO: Retrieve `account["proofs"][proof_idx]` when supported. - let _proof = ""; + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let account = batch.accounts[idx].clone(); - // TODO: Retrieve `proof["block_number"]` when supported. - let block_number = Felt252::from(0); + let key_leading_zeros = count_leading_zero_nibbles_from_hex(&account.account_key.to_string()); insert_value_from_var_name( - vars::ids::BLOCK_NUMBER, - MaybeRelocatable::Int(block_number), + vars::ids::KEY_LEADING_ZEROS, + MaybeRelocatable::Int(Felt252::from(key_leading_zeros)), vm, &hint_data.ids_data, &hint_data.ap_tracking, - )?; + ) +} - let mpt_proof_ptr = get_ptr_from_var_name( - vars::ids::MPT_PROOF, - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, - )?; - let nested_hex_array: &[&[&str]] = &[&[]]; - vm.write_arg(mpt_proof_ptr, &nested_hex_to_int_array(nested_hex_array))?; +pub const HINT_ACCOUNT_PROOFS_LEN: &str = "len(account.proofs)"; + +pub fn hint_account_proofs_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let account = batch.accounts[idx].clone(); + + insert_value_into_ap(vm, Felt252::from(account.proofs.len())) +} + +pub const HINT_ACCOUNT_PROOF_AT: &str = "proof = account.proofs[ids.idx]"; + +pub fn hint_account_proof_at( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let proof = batch.accounts[idx].proofs[idx].clone(); + + let proof_ptr = get_ptr_from_var_name(vars::ids::PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.write_arg(proof_ptr, &proof)?; - let proof_bytes_len_ptr = get_ptr_from_var_name( + Ok(()) +} + +pub const HINT_ACCOUNT_PROOF_LEN: &str = "len(proof.proof)"; + +pub fn hint_account_proof_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let proof = batch.accounts[idx].proofs[idx].clone(); + + insert_value_into_ap(vm, Felt252::from(proof.proof.len())) +} + +pub const HINT_ACCOUNT_PROOF_BLOCK_NUMBER: &str = "proof.block_number"; + +pub fn hint_account_proof_block_number( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let proof = batch.accounts[idx].proofs[idx].clone(); + + insert_value_into_ap(vm, Felt252::from(proof.block_number)) +} + +pub const HINT_ACCOUNT_PROOF_BYTES_LEN: &str = "segments.write_arg(ids.proof_bytes_len, proof.proof_bytes_len)"; + +pub fn hint_account_proof_bytes_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let proof = batch.accounts[idx].proofs[idx].clone(); + + insert_value_from_var_name( vars::ids::PROOF_BYTES_LEN, + MaybeRelocatable::Int(Felt252::from(proof.proof_bytes_len)), vm, &hint_data.ids_data, &hint_data.ap_tracking, - )?; - // TODO: Retrieve `proof["proof_bytes_len"]` when supported. - vm.write_arg(proof_bytes_len_ptr, &0)?; + ) +} + +pub const HINT_GET_MPT_PROOF: &str = "segments.write_arg(ids.mpt_proof, [int(x, 16) for x in proof.proof])"; + +pub fn hint_get_mpt_proof( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let proof = batch.accounts[idx].proofs[idx].clone(); + let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + + let proof_bytes: Vec = proof.proof.iter().map(|x| x.to_bytes_be()).flatten().collect(); + let proof_bytes_biguint = BigUint::from_bytes_be(&proof_bytes); + vm.insert_value(mpt_proof_ptr, Felt252::from(proof_bytes_biguint))?; Ok(()) } From f7102e3509f684ca25122c4bd292a671f269804c Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 11 Dec 2024 18:41:07 +0100 Subject: [PATCH 17/75] key set --- cairo_vm_hints/src/hint_processor/mod.rs | 3 +- .../src/syscall_handler/call_contract.rs | 80 --------------- .../src/syscall_handler/evm/dryrun/account.rs | 3 +- .../src/syscall_handler/evm/dryrun/header.rs | 5 +- .../src/syscall_handler/evm/dryrun/mod.rs | 98 ++++++++++++++++++- .../src/syscall_handler/evm/dryrun/storage.rs | 3 +- cairo_vm_hints/src/syscall_handler/mod.rs | 19 ++-- cairo_vm_hints/src/syscall_handler/traits.rs | 10 +- cairo_vm_hints/src/syscall_handler/utils.rs | 44 ++------- 9 files changed, 125 insertions(+), 140 deletions(-) delete mode 100644 cairo_vm_hints/src/syscall_handler/call_contract.rs diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index b0a56d8f..79c42064 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -147,8 +147,7 @@ impl HintProcessorLogic for CustomHintProcessor { if let Some(hint) = hint_data.downcast_ref::() { if let Hint::Starknet(StarknetHint::SystemCall { system }) = hint { let syscall_ptr = get_ptr_from_res_operand(vm, system)?; - let syscall_handler = exec_scopes.get::(vars::scopes::SYSCALL_HANDLER)?; - + let syscall_handler = exec_scopes.get_mut_ref::(vars::scopes::SYSCALL_HANDLER)?; return syscall_handler.execute_syscall(vm, syscall_ptr).map(|_| HintExtension::default()); } else { return self diff --git a/cairo_vm_hints/src/syscall_handler/call_contract.rs b/cairo_vm_hints/src/syscall_handler/call_contract.rs deleted file mode 100644 index 51e4945a..00000000 --- a/cairo_vm_hints/src/syscall_handler/call_contract.rs +++ /dev/null @@ -1,80 +0,0 @@ -use super::{ - evm, - traits::CallHandler, - utils::{felt_from_ptr, SyscallExecutionError, SyscallHandler, SyscallResult, WriteResponseResult}, -}; -use crate::cairo_types::{ - new_syscalls::{CallContractRequest, CallContractResponse}, - traits::CairoType, -}; -use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine}; - -pub struct CallContractHandler; - -impl SyscallHandler for CallContractHandler { - type Request = CallContractRequest; - type Response = CallContractResponse; - - fn read_request(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { - let ret = Self::Request::from_memory(vm, *ptr)?; - *ptr = (*ptr + Self::Request::cairo_size())?; - Ok(ret) - } - - fn execute(request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult { - let mut calldata = request.calldata_start; - - let call_handler_id = evm::dryrun::CallHandlerId::try_from(request.contract_address)?; - - let segment_index = felt_from_ptr(vm, &mut calldata)?; - let offset = felt_from_ptr(vm, &mut calldata)?; - - let _memorizer = Relocatable::from(( - segment_index - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - offset - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - )); - - let retdata_start = vm.add_temporary_segment(); - let mut retdata_end = retdata_start; - - match call_handler_id { - evm::dryrun::CallHandlerId::Header => { - let key = evm::dryrun::header::HeaderCallHandler::derive_key(vm, &mut calldata)?; - let function_id = evm::dryrun::header::HeaderCallHandler::derive_id(request.selector)?; - println!("key: {:?}, function_id: {:?}", key, function_id); - let result = evm::dryrun::header::HeaderCallHandler::handle(key, function_id)?; - result.to_memory(vm, retdata_end)?; - retdata_end += ::CallHandlerResult::n_fields(); - } - evm::dryrun::CallHandlerId::Account => { - let key = evm::dryrun::account::AccountCallHandler::derive_key(vm, &mut calldata)?; - let function_id = evm::dryrun::account::AccountCallHandler::derive_id(request.selector)?; - println!("key: {:?}, function_id: {:?}", key, function_id); - let result = evm::dryrun::account::AccountCallHandler::handle(key, function_id)?; - result.to_memory(vm, retdata_end)?; - retdata_end += ::CallHandlerResult::n_fields(); - } - evm::dryrun::CallHandlerId::Storage => { - let key = evm::dryrun::storage::StorageCallHandler::derive_key(vm, &mut calldata)?; - let function_id = evm::dryrun::storage::StorageCallHandler::derive_id(request.selector)?; - println!("key: {:?}, function_id: {:?}", key, function_id); - let result = evm::dryrun::storage::StorageCallHandler::handle(key, function_id)?; - result.to_memory(vm, retdata_end)?; - retdata_end += ::CallHandlerResult::n_fields(); - } - _ => {} - } - - Ok(Self::Response { retdata_start, retdata_end }) - } - - fn write_response(response: Self::Response, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { - response.to_memory(vm, *ptr)?; - *ptr = (*ptr + Self::Response::cairo_size())?; - Ok(()) - } -} diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs index c23994bf..70c731c1 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs @@ -19,6 +19,7 @@ use alloy::{ transports::http::reqwest::Url, }; use cairo_vm::{vm::errors::memory_errors::MemoryError, Felt252}; +use serde::{Deserialize, Serialize}; use std::env; pub struct AccountCallHandler; @@ -76,7 +77,7 @@ impl CairoType for CairoKey { } } -#[derive(Debug)] +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct Key { chain_id: ChainId, block_number: BlockNumber, diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs index 126d300b..e9368c04 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs @@ -19,6 +19,7 @@ use alloy::{ transports::http::reqwest::Url, }; use cairo_vm::{vm::errors::memory_errors::MemoryError, Felt252}; +use serde::{Deserialize, Serialize}; use std::env; pub struct HeaderCallHandler; @@ -51,7 +52,7 @@ impl CallHandler for HeaderCallHandler { } } -#[derive(Debug)] +#[derive(Debug, Serialize, Deserialize)] pub struct CairoKey { chain_id: Felt252, block_number: Felt252, @@ -74,7 +75,7 @@ impl CairoType for CairoKey { } } -#[derive(Debug)] +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct Key { chain_id: ChainId, block_number: BlockNumber, diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs index 48b0d10f..9573322e 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs @@ -5,8 +5,19 @@ pub mod receipt; pub mod storage; pub mod transaction; -use crate::syscall_handler::utils::SyscallExecutionError; -use cairo_vm::Felt252; +use crate::cairo_types::traits::CairoType; +use crate::syscall_handler::traits::CallHandler; +use crate::{ + cairo_types::new_syscalls::{CallContractRequest, CallContractResponse}, + syscall_handler::{ + traits::SyscallHandler, + utils::{felt_from_ptr, SyscallExecutionError, SyscallResult, WriteResponseResult}, + }, +}; +use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::{collections::HashSet, hash::Hash, marker::PhantomData}; use strum_macros::FromRepr; #[derive(FromRepr)] @@ -18,6 +29,79 @@ pub enum CallHandlerId { Receipt = 4, } +#[derive(Debug, Default)] +pub struct CallContractHandler { + key_set: HashSet, +} + +impl SyscallHandler for CallContractHandler { + type Request = CallContractRequest; + type Response = CallContractResponse; + + fn read_request(&mut self, vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { + let ret = Self::Request::from_memory(vm, *ptr)?; + *ptr = (*ptr + Self::Request::cairo_size())?; + Ok(ret) + } + + fn execute(&mut self, request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult { + let mut calldata = request.calldata_start; + + let call_handler_id = CallHandlerId::try_from(request.contract_address)?; + + let segment_index = felt_from_ptr(vm, &mut calldata)?; + let offset = felt_from_ptr(vm, &mut calldata)?; + + let _memorizer = Relocatable::from(( + segment_index + .try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + offset + .try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + )); + + let retdata_start = vm.add_temporary_segment(); + let mut retdata_end = retdata_start; + + match call_handler_id { + CallHandlerId::Header => { + let key = header::HeaderCallHandler::derive_key(vm, &mut calldata)?; + let function_id = header::HeaderCallHandler::derive_id(request.selector)?; + println!("key: {:?}, function_id: {:?}", key, function_id); + let result = header::HeaderCallHandler::handle(key, function_id)?; + result.to_memory(vm, retdata_end)?; + retdata_end += ::CallHandlerResult::n_fields(); + } + CallHandlerId::Account => { + let key = account::AccountCallHandler::derive_key(vm, &mut calldata)?; + let function_id = account::AccountCallHandler::derive_id(request.selector)?; + println!("key: {:?}, function_id: {:?}", key, function_id); + let result = account::AccountCallHandler::handle(key, function_id)?; + result.to_memory(vm, retdata_end)?; + retdata_end += ::CallHandlerResult::n_fields(); + } + CallHandlerId::Storage => { + let key = storage::StorageCallHandler::derive_key(vm, &mut calldata)?; + let function_id = storage::StorageCallHandler::derive_id(request.selector)?; + println!("key: {:?}, function_id: {:?}", key, function_id); + let result = storage::StorageCallHandler::handle(key, function_id)?; + result.to_memory(vm, retdata_end)?; + retdata_end += ::CallHandlerResult::n_fields(); + } + _ => {} + } + + Ok(Self::Response { retdata_start, retdata_end }) + } + + fn write_response(&mut self, response: Self::Response, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { + response.to_memory(vm, *ptr)?; + *ptr = (*ptr + Self::Response::cairo_size())?; + Ok(()) + } +} + impl TryFrom for CallHandlerId { type Error = SyscallExecutionError; fn try_from(value: Felt252) -> Result { @@ -31,3 +115,13 @@ impl TryFrom for CallHandlerId { }) } } + +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +enum DryRunKey { + Account(account::Key), + Header(header::Key), + Storage(storage::Key), +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct DryRunKeySet(HashSet); diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs index 3e218ed3..acdcf3e3 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs @@ -19,6 +19,7 @@ use alloy::{ transports::http::reqwest::Url, }; use cairo_vm::{vm::errors::memory_errors::MemoryError, Felt252}; +use serde::{Deserialize, Serialize}; use std::env; pub struct StorageCallHandler; @@ -87,7 +88,7 @@ impl CairoType for CairoKey { } } -#[derive(Debug)] +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct Key { chain_id: ChainId, block_number: BlockNumber, diff --git a/cairo_vm_hints/src/syscall_handler/mod.rs b/cairo_vm_hints/src/syscall_handler/mod.rs index 181cf4ae..fbc17299 100644 --- a/cairo_vm_hints/src/syscall_handler/mod.rs +++ b/cairo_vm_hints/src/syscall_handler/mod.rs @@ -1,4 +1,3 @@ -pub mod call_contract; pub mod evm; pub mod starknet; pub mod traits; @@ -8,35 +7,29 @@ use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, }; -use call_contract::CallContractHandler; use std::{rc::Rc, sync::RwLock}; use utils::{felt_from_ptr, run_handler, SyscallSelector}; pub(crate) const RPC: &str = "RPC"; /// SyscallHandler implementation for execution of system calls in the StarkNet OS -#[derive(Debug)] +#[derive(Debug, Default)] pub struct HDPSyscallHandler { syscall_ptr: Option, + call_contract_handler: evm::dryrun::CallContractHandler, } /// SyscallHandler is wrapped in Rc> in order /// to clone the reference when entering and exiting vm scopes -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] pub struct SyscallHandlerWrapper { pub syscall_handler: Rc>, } -impl Default for SyscallHandlerWrapper { - fn default() -> Self { - Self::new() - } -} - impl SyscallHandlerWrapper { pub fn new() -> Self { Self { - syscall_handler: Rc::new(RwLock::new(HDPSyscallHandler { syscall_ptr: None })), + syscall_handler: Rc::new(RwLock::new(HDPSyscallHandler::default())), } } pub fn set_syscall_ptr(&self, syscall_ptr: Relocatable) { @@ -49,7 +42,7 @@ impl SyscallHandlerWrapper { syscall_handler.syscall_ptr } - pub fn execute_syscall(&self, vm: &mut VirtualMachine, syscall_ptr: Relocatable) -> Result<(), HintError> { + pub fn execute_syscall(&mut self, vm: &mut VirtualMachine, syscall_ptr: Relocatable) -> Result<(), HintError> { let mut syscall_handler = self.syscall_handler.write().unwrap(); let ptr = &mut syscall_handler .syscall_ptr @@ -58,7 +51,7 @@ impl SyscallHandlerWrapper { assert_eq!(*ptr, syscall_ptr); match SyscallSelector::try_from(felt_from_ptr(vm, ptr)?)? { - SyscallSelector::CallContract => run_handler::(ptr, vm), + SyscallSelector::CallContract => run_handler(&mut syscall_handler.call_contract_handler, ptr, vm), }?; syscall_handler.syscall_ptr = Some(*ptr); diff --git a/cairo_vm_hints/src/syscall_handler/traits.rs b/cairo_vm_hints/src/syscall_handler/traits.rs index 9ad8f998..d8133ba6 100644 --- a/cairo_vm_hints/src/syscall_handler/traits.rs +++ b/cairo_vm_hints/src/syscall_handler/traits.rs @@ -1,8 +1,16 @@ use crate::cairo_types::traits::CairoType; -use super::utils::SyscallResult; +use super::utils::{SyscallResult, WriteResponseResult}; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +pub trait SyscallHandler { + type Request; + type Response; + fn read_request(&mut self, vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult; + fn execute(&mut self, request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult; + fn write_response(&mut self, response: Self::Response, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult; +} + pub trait CallHandler { type Key; type Id; diff --git a/cairo_vm_hints/src/syscall_handler/utils.rs b/cairo_vm_hints/src/syscall_handler/utils.rs index d5f4db4d..a44223aa 100644 --- a/cairo_vm_hints/src/syscall_handler/utils.rs +++ b/cairo_vm_hints/src/syscall_handler/utils.rs @@ -11,6 +11,8 @@ use cairo_vm::{ }; use thiserror::Error; +use super::traits::SyscallHandler; + #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum SyscallSelector { CallContract, @@ -128,37 +130,6 @@ impl From for SyscallExecutionError { pub type SyscallResult = Result; pub type WriteResponseResult = SyscallResult<()>; -// Common structs. - -#[derive(Debug, Eq, PartialEq)] -pub struct EmptyRequest; - -#[derive(Debug, Eq, PartialEq)] -pub struct EmptyResponse; - -#[derive(Debug)] -pub struct ReadOnlySegment { - pub start_ptr: Relocatable, - pub length: usize, -} - -pub fn write_segment(vm: &mut VirtualMachine, ptr: &mut Relocatable, segment: ReadOnlySegment) -> SyscallResult<()> { - write_maybe_relocatable(vm, ptr, segment.start_ptr)?; - let segment_end_ptr = (segment.start_ptr + segment.length)?; - write_maybe_relocatable(vm, ptr, segment_end_ptr)?; - - Ok(()) -} - -#[allow(async_fn_in_trait)] -pub trait SyscallHandler { - type Request; - type Response; - fn read_request(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult; - fn execute(request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult; - fn write_response(response: Self::Response, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult; -} - fn write_failure(gas_counter: Felt252, error_data: Vec, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> SyscallResult<()> { write_felt(vm, ptr, gas_counter)?; // 1 to indicate failure. @@ -177,18 +148,15 @@ fn write_failure(gas_counter: Felt252, error_data: Vec, vm: &mut Virtua pub const OUT_OF_GAS_ERROR: &str = "0x000000000000000000000000000000000000000000004f7574206f6620676173"; -pub fn run_handler(syscall_ptr: &mut Relocatable, vm: &mut VirtualMachine) -> Result<(), HintError> -where - SH: SyscallHandler, -{ +pub fn run_handler(syscall_handler: &mut impl SyscallHandler, syscall_ptr: &mut Relocatable, vm: &mut VirtualMachine) -> Result<(), HintError> { let remaining_gas = felt_from_ptr(vm, syscall_ptr)?; - let request = SH::read_request(vm, syscall_ptr)?; - let syscall_result = SH::execute(request, vm); + let request = syscall_handler.read_request(vm, syscall_ptr)?; + let syscall_result = syscall_handler.execute(request, vm); match syscall_result { Ok(response) => { write_felt(vm, syscall_ptr, remaining_gas)?; write_felt(vm, syscall_ptr, Felt252::ZERO)?; - SH::write_response(response, vm, syscall_ptr)? + syscall_handler.write_response(response, vm, syscall_ptr)? } Err(SyscallExecutionError::SyscallError { error_data: data }) => { write_failure(Felt252::ZERO, data, vm, syscall_ptr)?; From 1a7c63f3dcf040d6f11efa4f123e0cf44d270820 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Thu, 12 Dec 2024 11:56:43 +0100 Subject: [PATCH 18/75] wip --- cairo_vm_hints/src/main.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/cairo_vm_hints/src/main.rs b/cairo_vm_hints/src/main.rs index 35144739..6cf64017 100644 --- a/cairo_vm_hints/src/main.rs +++ b/cairo_vm_hints/src/main.rs @@ -30,8 +30,8 @@ struct Args { program_input: PathBuf, } -fn run(args: impl Iterator) -> Result<(), HdpOsError> { - let args = Args::try_parse_from(args).map_err(HdpOsError::Args)?; +fn main() -> Result<(), HdpOsError> { + let args = Args::try_parse_from(std::env::args()).map_err(HdpOsError::Args)?; // Init CairoRunConfig let cairo_run_config = CairoRunConfig { @@ -71,7 +71,3 @@ fn run(args: impl Iterator) -> Result<(), HdpOsError> { Ok(()) } - -fn main() -> Result<(), HdpOsError> { - run(std::env::args()) -} From 5a68240ea276f67ecaa7258076211d57f49d3034 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Thu, 12 Dec 2024 14:38:43 +0100 Subject: [PATCH 19/75] syscall handler keys saving --- cairo_vm_hints/src/hint_processor/mod.rs | 6 +- .../hints/lib/contract_bootloader/scopes.rs | 2 +- .../contract_bootloader/syscall_handler.rs | 2 +- cairo_vm_hints/src/main.rs | 21 +++++- .../src/syscall_handler/evm/dryrun/account.rs | 9 ++- .../src/syscall_handler/evm/dryrun/header.rs | 9 ++- .../src/syscall_handler/evm/dryrun/mod.rs | 74 ++++++++++++++++--- .../src/syscall_handler/evm/dryrun/storage.rs | 9 ++- cairo_vm_hints/src/syscall_handler/mod.rs | 55 -------------- 9 files changed, 107 insertions(+), 80 deletions(-) diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index 79c42064..730c7873 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -2,8 +2,10 @@ pub mod input; pub mod models; pub mod output; -use crate::hints::{lib, vars}; -use crate::syscall_handler::SyscallHandlerWrapper; +use crate::{ + hints::{lib, vars}, + syscall_handler::evm::dryrun::SyscallHandlerWrapper, +}; use cairo_lang_casm::{ hints::{Hint, StarknetHint}, operand::{BinOpOperand, DerefOrImmediate, Operation, Register, ResOperand}, diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/scopes.rs b/cairo_vm_hints/src/hints/lib/contract_bootloader/scopes.rs index 976883d4..c92c3d9d 100644 --- a/cairo_vm_hints/src/hints/lib/contract_bootloader/scopes.rs +++ b/cairo_vm_hints/src/hints/lib/contract_bootloader/scopes.rs @@ -1,4 +1,4 @@ -use crate::{hints::vars, syscall_handler::SyscallHandlerWrapper}; +use crate::{hints::vars, syscall_handler::evm::dryrun::SyscallHandlerWrapper}; use cairo_vm::{ hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData, types::exec_scope::ExecutionScopes, diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/syscall_handler.rs b/cairo_vm_hints/src/hints/lib/contract_bootloader/syscall_handler.rs index 161cfaa5..33278e20 100644 --- a/cairo_vm_hints/src/hints/lib/contract_bootloader/syscall_handler.rs +++ b/cairo_vm_hints/src/hints/lib/contract_bootloader/syscall_handler.rs @@ -1,4 +1,4 @@ -use crate::{hints::vars, syscall_handler::SyscallHandlerWrapper}; +use crate::{hints::vars, syscall_handler::evm::dryrun::SyscallHandlerWrapper}; use cairo_vm::{ hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_ptr_from_var_name}, types::exec_scope::ExecutionScopes, diff --git a/cairo_vm_hints/src/main.rs b/cairo_vm_hints/src/main.rs index 6cf64017..bee1707d 100644 --- a/cairo_vm_hints/src/main.rs +++ b/cairo_vm_hints/src/main.rs @@ -14,7 +14,9 @@ use cairo_vm::vm::runners::cairo_runner::CairoRunner; use clap::{Parser, ValueHint}; use hdp_cairo_vm_hints::HdpOsError; use hint_processor::CustomHintProcessor; -use std::path::PathBuf; +use hints::vars; +use std::{fs, path::PathBuf}; +use syscall_handler::evm::dryrun::{SyscallHandler, SyscallHandlerWrapper}; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] @@ -28,6 +30,8 @@ struct Args { proof_mode: bool, #[structopt(long = "program_input")] program_input: PathBuf, + #[structopt(long = "program_output")] + program_output: PathBuf, } fn main() -> Result<(), HdpOsError> { @@ -69,5 +73,20 @@ fn main() -> Result<(), HdpOsError> { .map_err(|err| VmException::from_vm_error(&cairo_runner, err)) .map_err(|e| HdpOsError::Runner(e.into()))?; + fs::write( + args.program_output, + serde_json::to_vec::( + &cairo_runner + .exec_scopes + .get::(vars::scopes::SYSCALL_HANDLER) + .unwrap() + .syscall_handler + .try_read() + .unwrap(), + ) + .unwrap(), + ) + .unwrap(); + Ok(()) } diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs index 70c731c1..8557db81 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs @@ -1,7 +1,6 @@ use crate::syscall_handler::{ traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, - Relocatable, VirtualMachine, }; use crate::{ cairo_types::{ @@ -18,7 +17,11 @@ use alloy::{ primitives::{Address, BlockNumber, ChainId}, transports::http::reqwest::Url, }; -use cairo_vm::{vm::errors::memory_errors::MemoryError, Felt252}; +use cairo_vm::{ + types::relocatable::Relocatable, + vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, + Felt252, +}; use serde::{Deserialize, Serialize}; use std::env; @@ -77,7 +80,7 @@ impl CairoType for CairoKey { } } -#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct Key { chain_id: ChainId, block_number: BlockNumber, diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs index e9368c04..180cb1e5 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs @@ -1,7 +1,6 @@ use crate::syscall_handler::{ traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, - Relocatable, VirtualMachine, }; use crate::{ cairo_types::{ @@ -18,7 +17,11 @@ use alloy::{ primitives::{BlockNumber, ChainId}, transports::http::reqwest::Url, }; -use cairo_vm::{vm::errors::memory_errors::MemoryError, Felt252}; +use cairo_vm::{ + types::relocatable::Relocatable, + vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, + Felt252, +}; use serde::{Deserialize, Serialize}; use std::env; @@ -75,7 +78,7 @@ impl CairoType for CairoKey { } } -#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct Key { chain_id: ChainId, block_number: BlockNumber, diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs index 9573322e..c64a9801 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs @@ -6,20 +6,35 @@ pub mod storage; pub mod transaction; use crate::cairo_types::traits::CairoType; -use crate::syscall_handler::traits::CallHandler; +use crate::syscall_handler::traits::{self, CallHandler}; +use crate::syscall_handler::utils::{run_handler, SyscallSelector}; use crate::{ cairo_types::new_syscalls::{CallContractRequest, CallContractResponse}, - syscall_handler::{ - traits::SyscallHandler, - utils::{felt_from_ptr, SyscallExecutionError, SyscallResult, WriteResponseResult}, - }, + syscall_handler::utils::{felt_from_ptr, SyscallExecutionError, SyscallResult, WriteResponseResult}, }; +use cairo_vm::vm::errors::hint_errors::HintError; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use serde::{Deserialize, Serialize}; use serde_json::Value; +use std::rc::Rc; +use std::sync::RwLock; use std::{collections::HashSet, hash::Hash, marker::PhantomData}; use strum_macros::FromRepr; +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct SyscallHandler { + #[serde(skip)] + syscall_ptr: Option, + call_contract_handler: CallContractHandler, +} + +/// SyscallHandler is wrapped in Rc> in order +/// to clone the reference when entering and exiting vm scopes +#[derive(Debug, Clone, Default)] +pub struct SyscallHandlerWrapper { + pub syscall_handler: Rc>, +} + #[derive(FromRepr)] pub enum CallHandlerId { Header = 0, @@ -29,12 +44,46 @@ pub enum CallHandlerId { Receipt = 4, } -#[derive(Debug, Default)] +#[derive(Debug, Default, Serialize, Deserialize)] pub struct CallContractHandler { key_set: HashSet, } -impl SyscallHandler for CallContractHandler { +impl SyscallHandlerWrapper { + pub fn new() -> Self { + Self { + syscall_handler: Rc::new(RwLock::new(SyscallHandler::default())), + } + } + pub fn set_syscall_ptr(&self, syscall_ptr: Relocatable) { + let mut syscall_handler = self.syscall_handler.write().unwrap(); + syscall_handler.syscall_ptr = Some(syscall_ptr); + } + + pub fn syscall_ptr(&self) -> Option { + let syscall_handler = self.syscall_handler.read().unwrap(); + syscall_handler.syscall_ptr + } + + pub fn execute_syscall(&mut self, vm: &mut VirtualMachine, syscall_ptr: Relocatable) -> Result<(), HintError> { + let mut syscall_handler = self.syscall_handler.write().unwrap(); + let ptr = &mut syscall_handler + .syscall_ptr + .ok_or(HintError::CustomHint(Box::from("syscall_ptr is None")))?; + + assert_eq!(*ptr, syscall_ptr); + + match SyscallSelector::try_from(felt_from_ptr(vm, ptr)?)? { + SyscallSelector::CallContract => run_handler(&mut syscall_handler.call_contract_handler, ptr, vm), + }?; + + syscall_handler.syscall_ptr = Some(*ptr); + + Ok(()) + } +} + +impl traits::SyscallHandler for CallContractHandler { type Request = CallContractRequest; type Response = CallContractResponse; @@ -69,25 +118,27 @@ impl SyscallHandler for CallContractHandler { let key = header::HeaderCallHandler::derive_key(vm, &mut calldata)?; let function_id = header::HeaderCallHandler::derive_id(request.selector)?; println!("key: {:?}, function_id: {:?}", key, function_id); - let result = header::HeaderCallHandler::handle(key, function_id)?; + let result = header::HeaderCallHandler::handle(key.clone(), function_id)?; result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); + self.key_set.insert(DryRunKey::Header(key)); } CallHandlerId::Account => { let key = account::AccountCallHandler::derive_key(vm, &mut calldata)?; let function_id = account::AccountCallHandler::derive_id(request.selector)?; println!("key: {:?}, function_id: {:?}", key, function_id); - let result = account::AccountCallHandler::handle(key, function_id)?; + let result = account::AccountCallHandler::handle(key.clone(), function_id)?; result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); + self.key_set.insert(DryRunKey::Account(key)); } CallHandlerId::Storage => { let key = storage::StorageCallHandler::derive_key(vm, &mut calldata)?; let function_id = storage::StorageCallHandler::derive_id(request.selector)?; - println!("key: {:?}, function_id: {:?}", key, function_id); - let result = storage::StorageCallHandler::handle(key, function_id)?; + let result = storage::StorageCallHandler::handle(key.clone(), function_id)?; result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); + self.key_set.insert(DryRunKey::Storage(key)); } _ => {} } @@ -117,6 +168,7 @@ impl TryFrom for CallHandlerId { } #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "lowercase")] enum DryRunKey { Account(account::Key), Header(header::Key), diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs index acdcf3e3..c9dc3469 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs @@ -1,7 +1,6 @@ use crate::syscall_handler::{ traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, - Relocatable, VirtualMachine, }; use crate::{ cairo_types::{ @@ -18,7 +17,11 @@ use alloy::{ primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, transports::http::reqwest::Url, }; -use cairo_vm::{vm::errors::memory_errors::MemoryError, Felt252}; +use cairo_vm::{ + types::relocatable::Relocatable, + vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, + Felt252, +}; use serde::{Deserialize, Serialize}; use std::env; @@ -88,7 +91,7 @@ impl CairoType for CairoKey { } } -#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct Key { chain_id: ChainId, block_number: BlockNumber, diff --git a/cairo_vm_hints/src/syscall_handler/mod.rs b/cairo_vm_hints/src/syscall_handler/mod.rs index fbc17299..90a5ffbf 100644 --- a/cairo_vm_hints/src/syscall_handler/mod.rs +++ b/cairo_vm_hints/src/syscall_handler/mod.rs @@ -3,59 +3,4 @@ pub mod starknet; pub mod traits; pub mod utils; -use cairo_vm::{ - types::relocatable::Relocatable, - vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, -}; -use std::{rc::Rc, sync::RwLock}; -use utils::{felt_from_ptr, run_handler, SyscallSelector}; - pub(crate) const RPC: &str = "RPC"; - -/// SyscallHandler implementation for execution of system calls in the StarkNet OS -#[derive(Debug, Default)] -pub struct HDPSyscallHandler { - syscall_ptr: Option, - call_contract_handler: evm::dryrun::CallContractHandler, -} - -/// SyscallHandler is wrapped in Rc> in order -/// to clone the reference when entering and exiting vm scopes -#[derive(Debug, Clone, Default)] -pub struct SyscallHandlerWrapper { - pub syscall_handler: Rc>, -} - -impl SyscallHandlerWrapper { - pub fn new() -> Self { - Self { - syscall_handler: Rc::new(RwLock::new(HDPSyscallHandler::default())), - } - } - pub fn set_syscall_ptr(&self, syscall_ptr: Relocatable) { - let mut syscall_handler = self.syscall_handler.write().unwrap(); - syscall_handler.syscall_ptr = Some(syscall_ptr); - } - - pub fn syscall_ptr(&self) -> Option { - let syscall_handler = self.syscall_handler.read().unwrap(); - syscall_handler.syscall_ptr - } - - pub fn execute_syscall(&mut self, vm: &mut VirtualMachine, syscall_ptr: Relocatable) -> Result<(), HintError> { - let mut syscall_handler = self.syscall_handler.write().unwrap(); - let ptr = &mut syscall_handler - .syscall_ptr - .ok_or(HintError::CustomHint(Box::from("syscall_ptr is None")))?; - - assert_eq!(*ptr, syscall_ptr); - - match SyscallSelector::try_from(felt_from_ptr(vm, ptr)?)? { - SyscallSelector::CallContract => run_handler(&mut syscall_handler.call_contract_handler, ptr, vm), - }?; - - syscall_handler.syscall_ptr = Some(*ptr); - - Ok(()) - } -} From b919084aa9f1b1105f7a767e9d1aca69f9bec607 Mon Sep 17 00:00:00 2001 From: codyx Date: Thu, 12 Dec 2024 20:12:56 +0400 Subject: [PATCH 20/75] Refactor account verifier and utility functions - Added new constants for ACCOUNT and PROOF in `vars.rs` to enhance hint referencing. - Removed the unused `hex_to_int_array` function from `utils/mod.rs` for cleaner code. - Updated hints in `account_verifier.rs` to improve clarity and maintainability, including adjustments to account address retrieval and proof handling. - Streamlined logic for accessing account data from execution scopes, enhancing performance and readability. --- cairo_vm_hints/src/hints/lib/utils/mod.rs | 4 - .../lib/verifiers/evm/account_verifier.rs | 78 ++++++------------- cairo_vm_hints/src/hints/vars.rs | 3 +- 3 files changed, 26 insertions(+), 59 deletions(-) diff --git a/cairo_vm_hints/src/hints/lib/utils/mod.rs b/cairo_vm_hints/src/hints/lib/utils/mod.rs index ebf979a1..584dc52c 100644 --- a/cairo_vm_hints/src/hints/lib/utils/mod.rs +++ b/cairo_vm_hints/src/hints/lib/utils/mod.rs @@ -6,10 +6,6 @@ pub fn count_leading_zero_nibbles_from_hex(hex_str: &str) -> u32 { hex_str.chars().take_while(|&c| c == '0').count() as u32 } -pub fn hex_to_int_array(hex_array: &[&str]) -> Vec { - hex_array.iter().map(|x| u32::from_str_radix(x, 16).expect("Invalid hex input")).collect() -} - pub fn split_128(a: &BigUint) -> (BigUint, BigUint) { // Create a mask for the lower 128 bits: (1 << 128) - 1 let mask = (&BigUint::one() << 128) - BigUint::one(); diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs index 107c2d60..d1f61a0b 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs @@ -12,14 +12,14 @@ use num_traits::Num; use std::collections::HashMap; use crate::{ - hint_processor::models::proofs::Proofs, + hint_processor::models::proofs::{account::Account, mpt::MPTProof, Proofs}, hints::{ lib::utils::{count_leading_zero_nibbles_from_hex, split_128}, vars, }, }; -pub const HINT_BATCH_ACCOUNTS_LEN: &str = "len(batch[\"accounts\"])"; +pub const HINT_BATCH_ACCOUNTS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.accounts))"; pub fn hint_batch_accounts_len( vm: &mut VirtualMachine, @@ -33,7 +33,7 @@ pub fn hint_batch_accounts_len( } pub const HINT_GET_ACCOUNT_ADDRESS: &str = - "account = batch.accounts[ids.idx]\nsegments.write_arg(ids.address, [int(x, 16) for x in account.address])"; + "account = batch.accounts[ids.idx]\nsegments.write_arg(ids.address, [int(x, 16) for x in account.address]))"; pub fn hint_get_account_address( vm: &mut VirtualMachine, @@ -46,10 +46,12 @@ pub fn hint_get_account_address( .try_into() .unwrap(); let account = batch.accounts[idx].clone(); - let address = BigUint::from_str_radix(&account.address.to_string(), 16).unwrap(); + let address = account.address; + + exec_scopes.insert_value::(vars::scopes::ACCOUNT, account); let address_ptr = get_ptr_from_var_name(vars::ids::ADDRESS, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.insert_value(address_ptr, Felt252::from(address))?; + vm.write_arg(address_ptr, &address)?; Ok(()) } @@ -62,11 +64,7 @@ pub fn hint_account_key( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; - let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? - .try_into() - .unwrap(); - let account = batch.accounts[idx].clone(); + let account = exec_scopes.get::(vars::scopes::ACCOUNT)?; let account_key = BigUint::from_str_radix(&account.account_key.to_string(), 16).unwrap(); let (key_low, key_high) = split_128(&account_key); @@ -97,13 +95,9 @@ pub fn hint_account_key_leading_zeros( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; - let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? - .try_into() - .unwrap(); - let account = batch.accounts[idx].clone(); - + let account = exec_scopes.get::(vars::scopes::ACCOUNT)?; let key_leading_zeros = count_leading_zero_nibbles_from_hex(&account.account_key.to_string()); + insert_value_from_var_name( vars::ids::KEY_LEADING_ZEROS, MaybeRelocatable::Int(Felt252::from(key_leading_zeros)), @@ -113,19 +107,15 @@ pub fn hint_account_key_leading_zeros( ) } -pub const HINT_ACCOUNT_PROOFS_LEN: &str = "len(account.proofs)"; +pub const HINT_ACCOUNT_PROOFS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(account.proofs))"; pub fn hint_account_proofs_len( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, + _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; - let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? - .try_into() - .unwrap(); - let account = batch.accounts[idx].clone(); + let account = exec_scopes.get::(vars::scopes::ACCOUNT)?; insert_value_into_ap(vm, Felt252::from(account.proofs.len())) } @@ -138,48 +128,38 @@ pub fn hint_account_proof_at( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; + let account = exec_scopes.get::(vars::scopes::ACCOUNT)?; let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? .try_into() .unwrap(); - let proof = batch.accounts[idx].proofs[idx].clone(); - let proof_ptr = get_ptr_from_var_name(vars::ids::PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.write_arg(proof_ptr, &proof)?; + exec_scopes.insert_value::(vars::scopes::PROOF, account.proofs[idx].clone()); Ok(()) } -pub const HINT_ACCOUNT_PROOF_LEN: &str = "len(proof.proof)"; +pub const HINT_ACCOUNT_PROOF_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(proof.proof))"; pub fn hint_account_proof_len( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, + _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; - let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? - .try_into() - .unwrap(); - let proof = batch.accounts[idx].proofs[idx].clone(); + let proof = exec_scopes.get::(vars::scopes::PROOF)?; insert_value_into_ap(vm, Felt252::from(proof.proof.len())) } -pub const HINT_ACCOUNT_PROOF_BLOCK_NUMBER: &str = "proof.block_number"; +pub const HINT_ACCOUNT_PROOF_BLOCK_NUMBER: &str = "memory[ap] = to_felt_or_relocatable(proof.block_number)"; pub fn hint_account_proof_block_number( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, + _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; - let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? - .try_into() - .unwrap(); - let proof = batch.accounts[idx].proofs[idx].clone(); + let proof = exec_scopes.get::(vars::scopes::PROOF)?; insert_value_into_ap(vm, Felt252::from(proof.block_number)) } @@ -192,11 +172,7 @@ pub fn hint_account_proof_bytes_len( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; - let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? - .try_into() - .unwrap(); - let proof = batch.accounts[idx].proofs[idx].clone(); + let proof = exec_scopes.get::(vars::scopes::PROOF)?; insert_value_from_var_name( vars::ids::PROOF_BYTES_LEN, @@ -215,16 +191,10 @@ pub fn hint_get_mpt_proof( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; - let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? - .try_into() - .unwrap(); - let proof = batch.accounts[idx].proofs[idx].clone(); + let proof = exec_scopes.get::(vars::scopes::PROOF)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_bytes: Vec = proof.proof.iter().map(|x| x.to_bytes_be()).flatten().collect(); - let proof_bytes_biguint = BigUint::from_bytes_be(&proof_bytes); - vm.insert_value(mpt_proof_ptr, Felt252::from(proof_bytes_biguint))?; + vm.write_arg(mpt_proof_ptr, &proof.proof)?; Ok(()) } diff --git a/cairo_vm_hints/src/hints/vars.rs b/cairo_vm_hints/src/hints/vars.rs index 10830f0f..774f749b 100644 --- a/cairo_vm_hints/src/hints/vars.rs +++ b/cairo_vm_hints/src/hints/vars.rs @@ -1,9 +1,11 @@ pub mod scopes { + pub(crate) const ACCOUNT: &str = "account"; pub(crate) const BATCH: &str = "batch"; pub(crate) const COMPILED_CLASS: &str = "compiled_class"; pub(crate) const DICT_MANAGER: &str = "dict_manager"; pub(crate) const N_SELECTED_BUILTINS: &str = "n_selected_builtins"; pub(crate) const PARAMS: &str = "params"; + pub(crate) const PROOF: &str = "proof"; pub(crate) const PROOFS: &str = "proofs"; pub(crate) const SYSCALL_HANDLER: &str = "syscall_handler"; } @@ -29,7 +31,6 @@ pub mod ids { pub(crate) const KEY_HIGH: &str = "ids.key_high"; pub(crate) const LEFT: &str = "ids.left"; pub(crate) const MPT_PROOF: &str = "ids.mpt_proof"; - pub(crate) const PROOF: &str = "ids.proof"; pub(crate) const PROOF_BYTES_LEN: &str = "ids.proof_bytes_len"; pub(crate) const N_BUILTINS: &str = "n_builtins"; pub(crate) const N_PROCESSED_WORDS: &str = "ids.n_processed_words"; From d01564bbf9c754fb075c024a1a9686e19f9e056e Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 13 Dec 2024 08:38:12 +0100 Subject: [PATCH 21/75] dry run entrypoint --- cairo_vm_hints/src/lib.rs | 8 -------- cairo_vm_hints/src/main.rs | 4 ++-- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/cairo_vm_hints/src/lib.rs b/cairo_vm_hints/src/lib.rs index 2c086ae0..08d1386e 100644 --- a/cairo_vm_hints/src/lib.rs +++ b/cairo_vm_hints/src/lib.rs @@ -11,14 +11,6 @@ pub use hint_processor::CustomHintProcessor; #[derive(thiserror::Error, Debug)] pub enum HdpOsError { - #[error("Error: {0}")] - CatchAll(String), - #[error("PIE Parse Error: {0}")] - PieParsing(String), - #[error("PIE Zip Error: {0}")] - PieZipping(String), - #[error("PIE Encode Error: {0}")] - PieEncoding(String), #[error(transparent)] Args(#[from] clap::error::Error), #[error("Runner Error: {0}")] diff --git a/cairo_vm_hints/src/main.rs b/cairo_vm_hints/src/main.rs index bee1707d..1ebb59d9 100644 --- a/cairo_vm_hints/src/main.rs +++ b/cairo_vm_hints/src/main.rs @@ -84,9 +84,9 @@ fn main() -> Result<(), HdpOsError> { .try_read() .unwrap(), ) - .unwrap(), + .map_err(|e| HdpOsError::IO(e.into()))?, ) - .unwrap(); + .map_err(HdpOsError::IO)?; Ok(()) } From db122276e99976df3ff89d27c7e82d469261cf5d Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 13 Dec 2024 08:57:25 +0100 Subject: [PATCH 22/75] address chunked --- cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs index d1f61a0b..aaf7cd28 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs @@ -46,7 +46,7 @@ pub fn hint_get_account_address( .try_into() .unwrap(); let account = batch.accounts[idx].clone(); - let address = account.address; + let address: Vec = account.address.chunks(8).map(Felt252::from_bytes_le_slice).collect(); exec_scopes.insert_value::(vars::scopes::ACCOUNT, account); From 92fe0b1757adfcd11595f979bd1358ec8be18aea Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 13 Dec 2024 11:50:15 +0100 Subject: [PATCH 23/75] Fetch keys trait --- .../src/syscall_handler/evm/dryrun/account.rs | 63 +--------- .../src/syscall_handler/evm/dryrun/header.rs | 58 +-------- .../src/syscall_handler/evm/dryrun/mod.rs | 15 ++- .../src/syscall_handler/evm/dryrun/storage.rs | 84 +------------ .../src/syscall_handler/keys/account.rs | 94 ++++++++++++++ .../src/syscall_handler/keys/header.rs | 89 ++++++++++++++ .../src/syscall_handler/keys/mod.rs | 15 +++ .../src/syscall_handler/keys/receipt.rs | 1 + .../src/syscall_handler/keys/storage.rs | 116 ++++++++++++++++++ .../src/syscall_handler/keys/transaction.rs | 1 + cairo_vm_hints/src/syscall_handler/mod.rs | 1 + 11 files changed, 339 insertions(+), 198 deletions(-) create mode 100644 cairo_vm_hints/src/syscall_handler/keys/account.rs create mode 100644 cairo_vm_hints/src/syscall_handler/keys/header.rs create mode 100644 cairo_vm_hints/src/syscall_handler/keys/mod.rs create mode 100644 cairo_vm_hints/src/syscall_handler/keys/receipt.rs create mode 100644 cairo_vm_hints/src/syscall_handler/keys/storage.rs create mode 100644 cairo_vm_hints/src/syscall_handler/keys/transaction.rs diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs index 8557db81..50e10cfb 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs @@ -1,4 +1,8 @@ use crate::syscall_handler::{ + keys::{ + account::{CairoKey, Key}, + KeyFetch, + }, traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, }; @@ -44,63 +48,6 @@ impl CallHandler for AccountCallHandler { } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { - let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let runtime = tokio::runtime::Runtime::new().unwrap(); - let account = runtime - .block_on(async { provider.get_account(key.address).block_id(key.block_number.into()).await }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - - Ok(CairoAccount::from(account).handle(function_id)) - } -} - -#[derive(Debug)] -pub struct CairoKey { - chain_id: Felt252, - block_number: Felt252, - address: Felt252, -} - -impl CairoType for CairoKey { - fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result { - Ok(Self { - chain_id: *vm.get_integer((address + 0)?)?, - block_number: *vm.get_integer((address + 1)?)?, - address: *vm.get_integer((address + 2)?)?, - }) - } - fn to_memory(&self, vm: &mut VirtualMachine, address: Relocatable) -> Result<(), MemoryError> { - vm.insert_value((address + 0)?, self.chain_id)?; - vm.insert_value((address + 1)?, self.block_number)?; - vm.insert_value((address + 2)?, self.address)?; - Ok(()) - } - fn n_fields() -> usize { - 3 - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub struct Key { - chain_id: ChainId, - block_number: BlockNumber, - address: Address, -} - -impl TryFrom for Key { - type Error = SyscallExecutionError; - fn try_from(value: CairoKey) -> Result { - Ok(Self { - chain_id: value - .chain_id - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - block_number: value - .block_number - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - address: Address::try_from(value.address.to_biguint().to_bytes_be().as_slice()) - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - }) + Ok(CairoAccount::from(key.fetch_value()?).handle(function_id)) } } diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs index 180cb1e5..56acb2f4 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs @@ -1,4 +1,8 @@ use crate::syscall_handler::{ + keys::{ + header::{CairoKey, Key}, + KeyFetch, + }, traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, }; @@ -44,58 +48,6 @@ impl CallHandler for HeaderCallHandler { } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { - let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let runtime = tokio::runtime::Runtime::new().unwrap(); - let block = runtime - .block_on(async { provider.get_block_by_number(key.block_number.into(), BlockTransactionsKind::Hashes).await }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))? - .ok_or(SyscallExecutionError::InternalError("Block not found".into()))?; - - Ok(CairoHeader::from(block.header.inner).handle(function_id)) - } -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct CairoKey { - chain_id: Felt252, - block_number: Felt252, -} - -impl CairoType for CairoKey { - fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result { - Ok(Self { - chain_id: *vm.get_integer((address + 0)?)?, - block_number: *vm.get_integer((address + 1)?)?, - }) - } - fn to_memory(&self, vm: &mut VirtualMachine, address: Relocatable) -> Result<(), MemoryError> { - vm.insert_value((address + 0)?, self.chain_id)?; - vm.insert_value((address + 1)?, self.block_number)?; - Ok(()) - } - fn n_fields() -> usize { - 2 - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub struct Key { - chain_id: ChainId, - block_number: BlockNumber, -} - -impl TryFrom for Key { - type Error = SyscallExecutionError; - fn try_from(value: CairoKey) -> Result { - Ok(Self { - chain_id: value - .chain_id - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - block_number: value - .block_number - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - }) + Ok(CairoHeader::from(key.fetch_value()?.header.inner).handle(function_id)) } } diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs index c64a9801..02067a4f 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs @@ -6,6 +6,7 @@ pub mod storage; pub mod transaction; use crate::cairo_types::traits::CairoType; +use crate::syscall_handler::keys; use crate::syscall_handler::traits::{self, CallHandler}; use crate::syscall_handler::utils::{run_handler, SyscallSelector}; use crate::{ @@ -117,28 +118,26 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Header => { let key = header::HeaderCallHandler::derive_key(vm, &mut calldata)?; let function_id = header::HeaderCallHandler::derive_id(request.selector)?; - println!("key: {:?}, function_id: {:?}", key, function_id); let result = header::HeaderCallHandler::handle(key.clone(), function_id)?; + self.key_set.insert(DryRunKey::Header(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); - self.key_set.insert(DryRunKey::Header(key)); } CallHandlerId::Account => { let key = account::AccountCallHandler::derive_key(vm, &mut calldata)?; let function_id = account::AccountCallHandler::derive_id(request.selector)?; - println!("key: {:?}, function_id: {:?}", key, function_id); let result = account::AccountCallHandler::handle(key.clone(), function_id)?; + self.key_set.insert(DryRunKey::Account(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); - self.key_set.insert(DryRunKey::Account(key)); } CallHandlerId::Storage => { let key = storage::StorageCallHandler::derive_key(vm, &mut calldata)?; let function_id = storage::StorageCallHandler::derive_id(request.selector)?; let result = storage::StorageCallHandler::handle(key.clone(), function_id)?; + self.key_set.insert(DryRunKey::Storage(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); - self.key_set.insert(DryRunKey::Storage(key)); } _ => {} } @@ -170,9 +169,9 @@ impl TryFrom for CallHandlerId { #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] #[serde(rename_all = "lowercase")] enum DryRunKey { - Account(account::Key), - Header(header::Key), - Storage(storage::Key), + Account(keys::account::Key), + Header(keys::header::Key), + Storage(keys::storage::Key), } #[derive(Debug, Serialize, Deserialize)] diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs index c9dc3469..5c68a8e5 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs @@ -1,4 +1,8 @@ use crate::syscall_handler::{ + keys::{ + storage::{CairoKey, Key}, + KeyFetch, + }, traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, }; @@ -44,84 +48,6 @@ impl CallHandler for StorageCallHandler { } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { - let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let runtime = tokio::runtime::Runtime::new().unwrap(); - let storage_value = runtime - .block_on(async { - provider - .get_storage_at(key.address, key.storage_slot.into()) - .block_id(key.block_number.into()) - .await - }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - - Ok(CairoStorage::from(storage_value).handle(function_id)) - } -} - -#[derive(Debug)] -pub struct CairoKey { - chain_id: Felt252, - block_number: Felt252, - address: Felt252, - storage_slot_high: Felt252, - storage_slot_low: Felt252, -} - -impl CairoType for CairoKey { - fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result { - Ok(Self { - chain_id: *vm.get_integer((address + 0)?)?, - block_number: *vm.get_integer((address + 1)?)?, - address: *vm.get_integer((address + 2)?)?, - storage_slot_high: *vm.get_integer((address + 3)?)?, - storage_slot_low: *vm.get_integer((address + 4)?)?, - }) - } - fn to_memory(&self, vm: &mut VirtualMachine, address: Relocatable) -> Result<(), MemoryError> { - vm.insert_value((address + 0)?, self.chain_id)?; - vm.insert_value((address + 1)?, self.block_number)?; - vm.insert_value((address + 2)?, self.address)?; - vm.insert_value((address + 2)?, self.storage_slot_high)?; - vm.insert_value((address + 2)?, self.storage_slot_low)?; - Ok(()) - } - fn n_fields() -> usize { - 5 - } -} - -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] -pub struct Key { - chain_id: ChainId, - block_number: BlockNumber, - address: Address, - storage_slot: StorageKey, -} - -impl TryFrom for Key { - type Error = SyscallExecutionError; - fn try_from(value: CairoKey) -> Result { - Ok(Self { - chain_id: value - .chain_id - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - block_number: value - .block_number - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - address: Address::try_from(value.address.to_biguint().to_bytes_be().as_slice()) - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - storage_slot: StorageKey::from( - &[ - &value.storage_slot_high.to_bytes_be().as_slice()[16..], - &value.storage_slot_low.to_bytes_be().as_slice()[16..], - ] - .concat() - .try_into() - .map_err(|_| SyscallExecutionError::InternalError("Failed to form StorageKey".into()))?, - ), - }) + Ok(CairoStorage::from(key.fetch_value()?).handle(function_id)) } } diff --git a/cairo_vm_hints/src/syscall_handler/keys/account.rs b/cairo_vm_hints/src/syscall_handler/keys/account.rs new file mode 100644 index 00000000..60565918 --- /dev/null +++ b/cairo_vm_hints/src/syscall_handler/keys/account.rs @@ -0,0 +1,94 @@ +use super::KeyFetch; +use crate::{ + cairo_types::traits::CairoType, + syscall_handler::{utils::SyscallExecutionError, RPC}, +}; +use alloy::{ + consensus::Account, + primitives::{Address, BlockNumber, ChainId}, + providers::{Provider, RootProvider}, + rpc::types::EIP1186AccountProofResponse, + transports::http::Http, +}; +use cairo_vm::{ + types::relocatable::Relocatable, + vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, + Felt252, +}; +use reqwest::{Client, Url}; +use serde::{Deserialize, Serialize}; +use std::env; + +#[derive(Debug)] +pub struct CairoKey { + chain_id: Felt252, + block_number: Felt252, + address: Felt252, +} + +impl CairoType for CairoKey { + fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result { + Ok(Self { + chain_id: *vm.get_integer((address + 0)?)?, + block_number: *vm.get_integer((address + 1)?)?, + address: *vm.get_integer((address + 2)?)?, + }) + } + fn to_memory(&self, vm: &mut VirtualMachine, address: Relocatable) -> Result<(), MemoryError> { + vm.insert_value((address + 0)?, self.chain_id)?; + vm.insert_value((address + 1)?, self.block_number)?; + vm.insert_value((address + 2)?, self.address)?; + Ok(()) + } + fn n_fields() -> usize { + 3 + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] +pub struct Key { + chain_id: ChainId, + block_number: BlockNumber, + address: Address, +} + +impl KeyFetch for Key { + type Value = Account; + type Proof = EIP1186AccountProofResponse; + + fn fetch_value(&self) -> Result { + let runtime = tokio::runtime::Runtime::new().unwrap(); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let value = runtime + .block_on(async { provider.get_account(self.address).block_id(self.block_number.into()).await }) + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + Ok(value) + } + + fn fetch_proof(&self) -> Result { + let runtime = tokio::runtime::Runtime::new().unwrap(); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let value = runtime + .block_on(async { provider.get_proof(self.address, vec![]).block_id(self.block_number.into()).await }) + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + Ok(value) + } +} + +impl TryFrom for Key { + type Error = SyscallExecutionError; + fn try_from(value: CairoKey) -> Result { + Ok(Self { + chain_id: value + .chain_id + .try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + block_number: value + .block_number + .try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + address: Address::try_from(value.address.to_biguint().to_bytes_be().as_slice()) + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + }) + } +} diff --git a/cairo_vm_hints/src/syscall_handler/keys/header.rs b/cairo_vm_hints/src/syscall_handler/keys/header.rs new file mode 100644 index 00000000..f060094d --- /dev/null +++ b/cairo_vm_hints/src/syscall_handler/keys/header.rs @@ -0,0 +1,89 @@ +use std::env; + +use crate::{ + cairo_types::traits::CairoType, + syscall_handler::{utils::SyscallExecutionError, RPC}, +}; +use alloy::{ + primitives::{BlockNumber, ChainId}, + providers::{Provider, RootProvider}, + rpc::types::{Block, BlockTransactionsKind}, + transports::http::Http, +}; +use cairo_vm::{ + types::relocatable::Relocatable, + vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, + Felt252, +}; +use reqwest::{Client, Url}; +use serde::{Deserialize, Serialize}; + +use super::KeyFetch; + +#[derive(Debug, Serialize, Deserialize)] +pub struct CairoKey { + chain_id: Felt252, + block_number: Felt252, +} + +impl CairoType for CairoKey { + fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result { + Ok(Self { + chain_id: *vm.get_integer((address + 0)?)?, + block_number: *vm.get_integer((address + 1)?)?, + }) + } + fn to_memory(&self, vm: &mut VirtualMachine, address: Relocatable) -> Result<(), MemoryError> { + vm.insert_value((address + 0)?, self.chain_id)?; + vm.insert_value((address + 1)?, self.block_number)?; + Ok(()) + } + fn n_fields() -> usize { + 2 + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] +pub struct Key { + chain_id: ChainId, + block_number: BlockNumber, +} + +impl KeyFetch for Key { + type Value = Block; + type Proof = Block; // TODO change it + + fn fetch_value(&self) -> Result { + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let runtime = tokio::runtime::Runtime::new().unwrap(); + let block = runtime + .block_on(async { + provider + .get_block_by_number(self.block_number.into(), BlockTransactionsKind::Hashes) + .await + }) + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))? + .ok_or(SyscallExecutionError::InternalError("Block not found".into()))?; + Ok(block) + } + + fn fetch_proof(&self) -> Result { + todo!() + } +} + +impl TryFrom for Key { + type Error = SyscallExecutionError; + fn try_from(value: CairoKey) -> Result { + Ok(Self { + chain_id: value + .chain_id + .try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + block_number: value + .block_number + .try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + }) + } +} diff --git a/cairo_vm_hints/src/syscall_handler/keys/mod.rs b/cairo_vm_hints/src/syscall_handler/keys/mod.rs new file mode 100644 index 00000000..809e2772 --- /dev/null +++ b/cairo_vm_hints/src/syscall_handler/keys/mod.rs @@ -0,0 +1,15 @@ +#![allow(unused)] + +use super::utils::SyscallExecutionError; +pub mod account; +pub mod header; +pub mod receipt; +pub mod storage; +pub mod transaction; + +pub trait KeyFetch { + type Value; + type Proof; + fn fetch_value(&self) -> Result; + fn fetch_proof(&self) -> Result; +} diff --git a/cairo_vm_hints/src/syscall_handler/keys/receipt.rs b/cairo_vm_hints/src/syscall_handler/keys/receipt.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/cairo_vm_hints/src/syscall_handler/keys/receipt.rs @@ -0,0 +1 @@ + diff --git a/cairo_vm_hints/src/syscall_handler/keys/storage.rs b/cairo_vm_hints/src/syscall_handler/keys/storage.rs new file mode 100644 index 00000000..6c0c7fc7 --- /dev/null +++ b/cairo_vm_hints/src/syscall_handler/keys/storage.rs @@ -0,0 +1,116 @@ +use std::env; + +use crate::{ + cairo_types::traits::CairoType, + syscall_handler::{utils::SyscallExecutionError, RPC}, +}; +use alloy::{ + primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, + providers::{Provider, RootProvider}, + rpc::types::EIP1186AccountProofResponse, + transports::http::Http, +}; +use cairo_vm::{ + types::relocatable::Relocatable, + vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, + Felt252, +}; +use reqwest::{Client, Url}; +use serde::{Deserialize, Serialize}; + +use super::KeyFetch; + +#[derive(Debug)] +pub struct CairoKey { + chain_id: Felt252, + block_number: Felt252, + address: Felt252, + storage_slot_high: Felt252, + storage_slot_low: Felt252, +} + +impl CairoType for CairoKey { + fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result { + Ok(Self { + chain_id: *vm.get_integer((address + 0)?)?, + block_number: *vm.get_integer((address + 1)?)?, + address: *vm.get_integer((address + 2)?)?, + storage_slot_high: *vm.get_integer((address + 3)?)?, + storage_slot_low: *vm.get_integer((address + 4)?)?, + }) + } + fn to_memory(&self, vm: &mut VirtualMachine, address: Relocatable) -> Result<(), MemoryError> { + vm.insert_value((address + 0)?, self.chain_id)?; + vm.insert_value((address + 1)?, self.block_number)?; + vm.insert_value((address + 2)?, self.address)?; + vm.insert_value((address + 2)?, self.storage_slot_high)?; + vm.insert_value((address + 2)?, self.storage_slot_low)?; + Ok(()) + } + fn n_fields() -> usize { + 5 + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] +pub struct Key { + chain_id: ChainId, + block_number: BlockNumber, + address: Address, + storage_slot: StorageKey, +} + +impl KeyFetch for Key { + type Value = StorageValue; + type Proof = EIP1186AccountProofResponse; + + fn fetch_value(&self) -> Result { + let runtime = tokio::runtime::Runtime::new().unwrap(); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let value = runtime + .block_on(async { + provider + .get_storage_at(self.address, self.storage_slot.into()) + .block_id(self.block_number.into()) + .await + }) + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + Ok(value) + } + + fn fetch_proof(&self) -> Result { + let runtime = tokio::runtime::Runtime::new().unwrap(); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let value = runtime + .block_on(async { provider.get_proof(self.address, vec![]).block_id(self.block_number.into()).await }) + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + Ok(value) + } +} + +impl TryFrom for Key { + type Error = SyscallExecutionError; + fn try_from(value: CairoKey) -> Result { + Ok(Self { + chain_id: value + .chain_id + .try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + block_number: value + .block_number + .try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + address: Address::try_from(value.address.to_biguint().to_bytes_be().as_slice()) + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + storage_slot: StorageKey::from( + &[ + &value.storage_slot_high.to_bytes_be().as_slice()[16..], + &value.storage_slot_low.to_bytes_be().as_slice()[16..], + ] + .concat() + .try_into() + .map_err(|_| SyscallExecutionError::InternalError("Failed to form StorageKey".into()))?, + ), + }) + } +} diff --git a/cairo_vm_hints/src/syscall_handler/keys/transaction.rs b/cairo_vm_hints/src/syscall_handler/keys/transaction.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/cairo_vm_hints/src/syscall_handler/keys/transaction.rs @@ -0,0 +1 @@ + diff --git a/cairo_vm_hints/src/syscall_handler/mod.rs b/cairo_vm_hints/src/syscall_handler/mod.rs index 90a5ffbf..6ae37808 100644 --- a/cairo_vm_hints/src/syscall_handler/mod.rs +++ b/cairo_vm_hints/src/syscall_handler/mod.rs @@ -1,4 +1,5 @@ pub mod evm; +pub mod keys; pub mod starknet; pub mod traits; pub mod utils; From 3297a148a3a554c1f1a52ca54cc4aae4b91f6f4e Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 13 Dec 2024 12:17:00 +0100 Subject: [PATCH 24/75] no felts in types - handle them in hints not in types --- .../src/hint_processor/models/proofs/header.rs | 4 +--- .../src/hint_processor/models/proofs/mmr.rs | 8 +++----- .../src/hint_processor/models/proofs/mpt.rs | 12 ++++++++---- cairo_vm_hints/src/syscall_handler/keys/account.rs | 5 +++-- cairo_vm_hints/src/syscall_handler/keys/header.rs | 9 ++++----- cairo_vm_hints/src/syscall_handler/keys/storage.rs | 11 +++++------ 6 files changed, 24 insertions(+), 25 deletions(-) diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/header.rs b/cairo_vm_hints/src/hint_processor/models/proofs/header.rs index 6226e6b6..757bd77d 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/header.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/header.rs @@ -1,5 +1,4 @@ use alloy::primitives::Bytes; -use cairo_vm::Felt252; use serde::{Deserialize, Serialize}; use serde_with::serde_as; @@ -7,8 +6,7 @@ use serde_with::serde_as; #[serde_as] pub struct HeaderProof { pub leaf_idx: u64, - #[serde_as(as = "Vec")] - pub mmr_path: Vec, + pub mmr_path: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs b/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs index 9a16924e..d3d8d6d9 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs @@ -1,4 +1,4 @@ -use cairo_vm::Felt252; +use alloy::primitives::Bytes; use serde::{Deserialize, Serialize}; use serde_with::serde_as; @@ -7,9 +7,7 @@ use serde_with::serde_as; pub struct MmrMeta { pub id: u64, pub size: u64, - #[serde_as(as = "starknet_core::serde::unsigned_field_element::UfeHex")] - pub root: Felt252, + pub root: Bytes, pub chain_id: u64, - #[serde_as(as = "Vec")] - pub peaks: Vec, + pub peaks: Vec, } diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs b/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs index b373c951..8662dd3c 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs @@ -1,4 +1,4 @@ -use cairo_vm::Felt252; +use alloy::primitives::Bytes; use serde::{Deserialize, Serialize}; use serde_with::serde_as; @@ -6,7 +6,11 @@ use serde_with::serde_as; #[serde_as] pub struct MPTProof { pub block_number: u64, - pub proof_bytes_len: u64, - #[serde_as(as = "starknet_core::serde::unsigned_field_element::UfeHex")] - pub proof: Vec, + pub proof: Vec, +} + +impl MPTProof { + pub fn new(block_number: u64, proof: Vec) -> Self { + Self { block_number, proof } + } } diff --git a/cairo_vm_hints/src/syscall_handler/keys/account.rs b/cairo_vm_hints/src/syscall_handler/keys/account.rs index 60565918..15159b0c 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/account.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/account.rs @@ -1,6 +1,7 @@ use super::KeyFetch; use crate::{ cairo_types::traits::CairoType, + hint_processor::models::proofs::mpt::MPTProof, syscall_handler::{utils::SyscallExecutionError, RPC}, }; use alloy::{ @@ -54,7 +55,7 @@ pub struct Key { impl KeyFetch for Key { type Value = Account; - type Proof = EIP1186AccountProofResponse; + type Proof = MPTProof; fn fetch_value(&self) -> Result { let runtime = tokio::runtime::Runtime::new().unwrap(); @@ -71,7 +72,7 @@ impl KeyFetch for Key { let value = runtime .block_on(async { provider.get_proof(self.address, vec![]).block_id(self.block_number.into()).await }) .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(value) + Ok(Self::Proof::new(self.block_number, value.account_proof)) } } diff --git a/cairo_vm_hints/src/syscall_handler/keys/header.rs b/cairo_vm_hints/src/syscall_handler/keys/header.rs index f060094d..2e4f041f 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/header.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/header.rs @@ -1,7 +1,7 @@ -use std::env; - +use super::KeyFetch; use crate::{ cairo_types::traits::CairoType, + hint_processor::models::proofs::header::HeaderProof, syscall_handler::{utils::SyscallExecutionError, RPC}, }; use alloy::{ @@ -17,8 +17,7 @@ use cairo_vm::{ }; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; - -use super::KeyFetch; +use std::env; #[derive(Debug, Serialize, Deserialize)] pub struct CairoKey { @@ -51,7 +50,7 @@ pub struct Key { impl KeyFetch for Key { type Value = Block; - type Proof = Block; // TODO change it + type Proof = HeaderProof; fn fetch_value(&self) -> Result { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); diff --git a/cairo_vm_hints/src/syscall_handler/keys/storage.rs b/cairo_vm_hints/src/syscall_handler/keys/storage.rs index 6c0c7fc7..56912228 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/storage.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/storage.rs @@ -1,7 +1,7 @@ -use std::env; - +use super::KeyFetch; use crate::{ cairo_types::traits::CairoType, + hint_processor::models::proofs::mpt::MPTProof, syscall_handler::{utils::SyscallExecutionError, RPC}, }; use alloy::{ @@ -17,8 +17,7 @@ use cairo_vm::{ }; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; - -use super::KeyFetch; +use std::env; #[derive(Debug)] pub struct CairoKey { @@ -62,7 +61,7 @@ pub struct Key { impl KeyFetch for Key { type Value = StorageValue; - type Proof = EIP1186AccountProofResponse; + type Proof = MPTProof; fn fetch_value(&self) -> Result { let runtime = tokio::runtime::Runtime::new().unwrap(); @@ -84,7 +83,7 @@ impl KeyFetch for Key { let value = runtime .block_on(async { provider.get_proof(self.address, vec![]).block_id(self.block_number.into()).await }) .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(value) + Ok(Self::Proof::new(self.block_number, value.account_proof)) } } From 3deb96c5aabd36bd8c24d82f083e637ec9fabf1f Mon Sep 17 00:00:00 2001 From: codyx Date: Fri, 13 Dec 2024 16:53:08 +0400 Subject: [PATCH 25/75] Add block_tx_verifier related hints --- cairo_vm_hints/src/hint_processor/mod.rs | 8 + .../lib/verifiers/evm/block_tx_verifier.rs | 159 ++++++++++++++++++ .../src/hints/lib/verifiers/evm/mod.rs | 1 + 3 files changed, 168 insertions(+) create mode 100644 cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index fea6f492..40842150 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -94,6 +94,14 @@ impl CustomHintProcessor { hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_LEN.into(), lib::verifiers::evm::account_verifier::hint_account_proof_len); hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_ACCOUNT_ADDRESS.into(), lib::verifiers::evm::account_verifier::hint_get_account_address); hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), lib::verifiers::evm::account_verifier::hint_get_mpt_proof); + hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), lib::verifiers::evm::block_tx_verifier::hint_batch_transactions_len); + hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx); + hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX_KEY.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx_key); + hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX_KEY_LEADING_ZEROS.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx_key_leading_zeros); + hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX_PROOF_LEN.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx_proof_len); + hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx_block_number); + hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::block_tx_verifier::hint_proof_bytes_len); + hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_MPT_PROOF.into(), lib::verifiers::evm::block_tx_verifier::hint_mpt_proof); hints.insert(lib::verifiers::verify::HINT_BATCH_LEN.into(), lib::verifiers::verify::hint_batch_len); hints.insert(lib::verifiers::verify::HINT_CHAIN_ID.into(), lib::verifiers::verify::hint_chain_id); hints.insert(lib::verifiers::verify::HINT_VM_ENTER_SCOPE.into(), lib::verifiers::verify::hint_vm_enter_scope); diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs new file mode 100644 index 00000000..a347b352 --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs @@ -0,0 +1,159 @@ +use cairo_vm::{ + hint_processor::builtin_hint_processor::{ + builtin_hint_processor_definition::HintProcessorData, + hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, + }, + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use std::collections::HashMap; + +use crate::{ + hint_processor::models::proofs::{transaction::Transaction, Proofs}, + hints::{lib::utils::count_leading_zero_nibbles_from_hex, vars}, +}; + +pub const HINT_BATCH_TRANSACTIONS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.transactions))"; + +pub fn hint_batch_transactions_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + + insert_value_into_ap(vm, Felt252::from(batch.transactions.len())) +} + +pub const HINT_SET_TX: &str = "transaction = transactions[ids.idx]"; + +pub fn hint_set_tx( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let transaction = batch.transactions[idx].clone(); + + exec_scopes.insert_value::("transaction", transaction); + + Ok(()) +} + +pub const HINT_SET_TX_KEY: &str = "from tools.py.utils import split_128\n(ids.key.low, ids.key.high) = split_128(int(transaction.key, 16))"; + +pub fn hint_set_tx_key( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let transaction = exec_scopes.get::("transaction")?; + let key = transaction.key; + + let key_as_limbs = key.as_limbs(); + let key_low = key_as_limbs[0] as u128 | ((key_as_limbs[1] as u128) << 64); + let key_high = key_as_limbs[2] as u128 | ((key_as_limbs[3] as u128) << 64); + + insert_value_from_var_name( + vars::ids::KEY_LOW, + Felt252::from(key_low), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + insert_value_from_var_name( + vars::ids::KEY_HIGH, + Felt252::from(key_high), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + + Ok(()) +} + +pub const HINT_SET_TX_KEY_LEADING_ZEROS: &str = + "ids.key_leading_zeros = len(transaction.key.lstrip(\"0x\")) - len(transaction.key.lstrip(\"0x\").lstrip(\"0\"))"; + +pub fn hint_set_tx_key_leading_zeros( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let transaction = exec_scopes.get::("transaction")?; + let key_leading_zeros = count_leading_zero_nibbles_from_hex(&format!("{:x}", transaction.key)); + + insert_value_from_var_name( + vars::ids::KEY_LEADING_ZEROS, + Felt252::from(key_leading_zeros), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + ) +} + +pub const HINT_SET_TX_PROOF_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(transaction.proof))"; + +pub fn hint_set_tx_proof_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let transaction = exec_scopes.get::("transaction")?; + + insert_value_into_ap(vm, Felt252::from(transaction.proof.proof.len())) +} + +pub const HINT_SET_TX_BLOCK_NUMBER: &str = "memory[ap] = to_felt_or_relocatable(transaction.block_number)"; + +pub fn hint_set_tx_block_number( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let transaction = exec_scopes.get::("transaction")?; + + insert_value_into_ap(vm, Felt252::from(transaction.proof.block_number)) +} + +pub const HINT_PROOF_BYTES_LEN: &str = "segments.write_arg(ids.proof_bytes_len, transaction.proof_bytes_len)"; + +pub fn hint_proof_bytes_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let transaction = exec_scopes.get::("transaction")?; + + let proof_bytes_len_ptr = get_ptr_from_var_name(vars::ids::PROOF_BYTES_LEN, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.insert_value(proof_bytes_len_ptr, Felt252::from(transaction.proof.proof_bytes_len))?; + + Ok(()) +} + +pub const HINT_MPT_PROOF: &str = "segments.write_arg(ids.mpt_proof, [int(x, 16) for x in transaction.proof])"; + +pub fn hint_mpt_proof( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let transaction = exec_scopes.get::("transaction")?; + + let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.write_arg(mpt_proof_ptr, &transaction.proof.proof)?; + + Ok(()) +} diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs index 158bbb7c..7118d73f 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs @@ -1 +1,2 @@ pub mod account_verifier; +pub mod block_tx_verifier; From 02e6029b6801a6f0067eeb116b6e470c538ef298 Mon Sep 17 00:00:00 2001 From: codyx Date: Fri, 13 Dec 2024 17:17:26 +0400 Subject: [PATCH 26/75] Add header verifier hints --- cairo_vm_hints/src/hint_processor/mod.rs | 8 +- .../lib/verifiers/evm/header_verifier.rs | 106 ++++++++++++++++++ .../src/hints/lib/verifiers/evm/mod.rs | 1 + cairo_vm_hints/src/hints/vars.rs | 1 + 4 files changed, 115 insertions(+), 1 deletion(-) create mode 100644 cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index 40842150..6d732e23 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -84,7 +84,6 @@ impl CustomHintProcessor { hints.insert(lib::segments::SEGMENTS_ADD_EVM_MEMORIZER_OFFSET.into(), lib::segments::segments_add_evm_memorizer_offset); hints.insert(lib::segments::SEGMENTS_ADD_EVM_STARKNET_MEMORIZER_INDEX.into(), lib::segments::segments_add_evm_starknet_memorizer_index); hints.insert(lib::segments::SEGMENTS_ADD_STARKNET_MEMORIZER_OFFSET.into(), lib::segments::segments_add_starknet_memorizer_offset); - hints.insert(lib::verifiers::evm::account_verifier::HINT_BATCH_ACCOUNTS_LEN.into(), lib::verifiers::evm::account_verifier::hint_batch_accounts_len); hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_KEY.into(), lib::verifiers::evm::account_verifier::hint_account_key); hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_KEY_LEADING_ZEROS.into(), lib::verifiers::evm::account_verifier::hint_account_key_leading_zeros); hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_AT.into(), lib::verifiers::evm::account_verifier::hint_account_proof_at); @@ -92,6 +91,7 @@ impl CustomHintProcessor { hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::account_verifier::hint_account_proof_bytes_len); hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOFS_LEN.into(), lib::verifiers::evm::account_verifier::hint_account_proofs_len); hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_LEN.into(), lib::verifiers::evm::account_verifier::hint_account_proof_len); + hints.insert(lib::verifiers::evm::account_verifier::HINT_BATCH_ACCOUNTS_LEN.into(), lib::verifiers::evm::account_verifier::hint_batch_accounts_len); hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_ACCOUNT_ADDRESS.into(), lib::verifiers::evm::account_verifier::hint_get_account_address); hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), lib::verifiers::evm::account_verifier::hint_get_mpt_proof); hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), lib::verifiers::evm::block_tx_verifier::hint_batch_transactions_len); @@ -102,6 +102,12 @@ impl CustomHintProcessor { hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx_block_number); hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::block_tx_verifier::hint_proof_bytes_len); hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_MPT_PROOF.into(), lib::verifiers::evm::block_tx_verifier::hint_mpt_proof); + hints.insert(lib::verifiers::evm::header_verifier::HINT_BATCH_HEADERS_LEN.into(), lib::verifiers::evm::header_verifier::hint_batch_headers_len); + hints.insert(lib::verifiers::evm::header_verifier::HINT_LEAF_IDX.into(), lib::verifiers::evm::header_verifier::hint_leaf_idx); + hints.insert(lib::verifiers::evm::header_verifier::HINT_MMR_PATH_LEN.into(), lib::verifiers::evm::header_verifier::hint_mmr_path_len); + hints.insert(lib::verifiers::evm::header_verifier::HINT_MMR_PATH.into(), lib::verifiers::evm::header_verifier::hint_mmr_path); + hints.insert(lib::verifiers::evm::header_verifier::HINT_RLP_LEN.into(), lib::verifiers::evm::header_verifier::hint_rlp_len); + hints.insert(lib::verifiers::evm::header_verifier::HINT_SET_HEADER.into(), lib::verifiers::evm::header_verifier::hint_set_header); hints.insert(lib::verifiers::verify::HINT_BATCH_LEN.into(), lib::verifiers::verify::hint_batch_len); hints.insert(lib::verifiers::verify::HINT_CHAIN_ID.into(), lib::verifiers::verify::hint_chain_id); hints.insert(lib::verifiers::verify::HINT_VM_ENTER_SCOPE.into(), lib::verifiers::verify::hint_vm_enter_scope); diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs new file mode 100644 index 00000000..da52dcc7 --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs @@ -0,0 +1,106 @@ +use cairo_vm::{ + hint_processor::builtin_hint_processor::{ + builtin_hint_processor_definition::HintProcessorData, + hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_into_ap}, + }, + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use std::collections::HashMap; + +use crate::{ + hint_processor::models::proofs::{header::Header, Proofs}, + hints::vars, +}; + +pub const HINT_BATCH_HEADERS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.headers))"; + +pub fn hint_batch_headers_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + + insert_value_into_ap(vm, Felt252::from(batch.headers.len())) +} + +pub const HINT_SET_HEADER: &str = "header = batch.headers[ids.idx - 1]\nsegments.write_arg(ids.rlp, [int(x, 16) for x in header.rlp])"; + +pub fn hint_set_header( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let header = batch.headers[idx - 1].clone(); + let rlp = header.rlp.clone(); + + exec_scopes.insert_value::
("header", header); + + let rlp_ptr = get_ptr_from_var_name(vars::ids::RLP, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.write_arg(rlp_ptr, &rlp)?; + + Ok(()) +} + +pub const HINT_RLP_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(header.rlp))"; + +pub fn hint_rlp_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let header = exec_scopes.get::
("header")?; + + insert_value_into_ap(vm, Felt252::from(header.rlp.len())) +} + +pub const HINT_LEAF_IDX: &str = "memory[ap] = to_felt_or_relocatable(len(header.proof.leaf_idx))"; + +pub fn hint_leaf_idx( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let header = exec_scopes.get::
("header")?; + + insert_value_into_ap(vm, Felt252::from(header.proof.leaf_idx)) +} + +pub const HINT_MMR_PATH_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(header.proof.mmr_path))"; + +pub fn hint_mmr_path_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let header = exec_scopes.get::
("header")?; + + insert_value_into_ap(vm, Felt252::from(header.proof.mmr_path.len())) +} + +pub const HINT_MMR_PATH: &str = "segments.write_arg(ids.mmr_path, [int(x, 16) for x in header.proof.mmr_path])"; + +pub fn hint_mmr_path( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let header = exec_scopes.get::
("header")?; + + let mmr_path_ptr = get_ptr_from_var_name(vars::ids::MMR_PATH, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.write_arg(mmr_path_ptr, &header.proof.mmr_path)?; + + Ok(()) +} diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs index 7118d73f..ad6b2ccd 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs @@ -1,2 +1,3 @@ pub mod account_verifier; pub mod block_tx_verifier; +pub mod header_verifier; diff --git a/cairo_vm_hints/src/hints/vars.rs b/cairo_vm_hints/src/hints/vars.rs index 774f749b..d5475e25 100644 --- a/cairo_vm_hints/src/hints/vars.rs +++ b/cairo_vm_hints/src/hints/vars.rs @@ -30,6 +30,7 @@ pub mod ids { pub(crate) const KEY_LEADING_ZEROS: &str = "ids.key_leading_zeros"; pub(crate) const KEY_HIGH: &str = "ids.key_high"; pub(crate) const LEFT: &str = "ids.left"; + pub(crate) const MMR_PATH: &str = "ids.mmr_path"; pub(crate) const MPT_PROOF: &str = "ids.mpt_proof"; pub(crate) const PROOF_BYTES_LEN: &str = "ids.proof_bytes_len"; pub(crate) const N_BUILTINS: &str = "n_builtins"; From 881d4d9f7572b453181bdb0ecfb37c3535d36790 Mon Sep 17 00:00:00 2001 From: codyx Date: Fri, 13 Dec 2024 19:22:06 +0400 Subject: [PATCH 27/75] Add receipt verifier hints --- cairo_vm_hints/src/hint_processor/mod.rs | 8 + .../src/hints/lib/verifiers/evm/mod.rs | 1 + .../lib/verifiers/evm/receipt_verifier.rs | 160 ++++++++++++++++++ 3 files changed, 169 insertions(+) create mode 100644 cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index 6d732e23..14eb7811 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -108,6 +108,14 @@ impl CustomHintProcessor { hints.insert(lib::verifiers::evm::header_verifier::HINT_MMR_PATH.into(), lib::verifiers::evm::header_verifier::hint_mmr_path); hints.insert(lib::verifiers::evm::header_verifier::HINT_RLP_LEN.into(), lib::verifiers::evm::header_verifier::hint_rlp_len); hints.insert(lib::verifiers::evm::header_verifier::HINT_SET_HEADER.into(), lib::verifiers::evm::header_verifier::hint_set_header); + hints.insert(lib::verifiers::evm::receipt_verifier::HINT_BATCH_RECEIPTS_LEN.into(), lib::verifiers::evm::receipt_verifier::hint_batch_receipts_len); + hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_BLOCK_NUMBER.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_block_number); + hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_key); + hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY_LEADING_ZEROS.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_key_leading_zeros); + hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_MPT_PROOF.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_mpt_proof); + hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_LEN.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_proof_len); + hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_proof_bytes_len); + hints.insert(lib::verifiers::evm::receipt_verifier::HINT_SET_RECEIPT.into(), lib::verifiers::evm::receipt_verifier::hint_set_receipt); hints.insert(lib::verifiers::verify::HINT_BATCH_LEN.into(), lib::verifiers::verify::hint_batch_len); hints.insert(lib::verifiers::verify::HINT_CHAIN_ID.into(), lib::verifiers::verify::hint_chain_id); hints.insert(lib::verifiers::verify::HINT_VM_ENTER_SCOPE.into(), lib::verifiers::verify::hint_vm_enter_scope); diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs index ad6b2ccd..dd2867c1 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs @@ -1,3 +1,4 @@ pub mod account_verifier; pub mod block_tx_verifier; pub mod header_verifier; +pub mod receipt_verifier; diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs new file mode 100644 index 00000000..d2977f83 --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs @@ -0,0 +1,160 @@ +use cairo_vm::{ + hint_processor::builtin_hint_processor::{ + builtin_hint_processor_definition::HintProcessorData, + hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, + }, + types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use std::collections::HashMap; + +use crate::{ + hint_processor::models::proofs::{receipt::Receipt, Proofs}, + hints::{lib::utils::count_leading_zero_nibbles_from_hex, vars}, +}; + +pub const HINT_BATCH_RECEIPTS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.receipts))"; + +pub fn hint_batch_receipts_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + + insert_value_into_ap(vm, Felt252::from(batch.transaction_receipts.len())) +} + +pub const HINT_SET_RECEIPT: &str = "receipt = receipts[ids.idx]"; + +pub fn hint_set_receipt( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::("batch")?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let receipt = batch.transaction_receipts[idx].clone(); + + exec_scopes.insert_value::("receipt", receipt); + + Ok(()) +} + +pub const HINT_RECEIPT_KEY: &str = "from tools.py.utils import split_128\n(ids.key.low, ids.key.high) = split_128(int(receipt.key, 16))"; + +pub fn hint_receipt_key( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let receipt = exec_scopes.get::("receipt")?; + let key_as_limbs = receipt.key.as_limbs(); + let key_low = key_as_limbs[0] as u128 | ((key_as_limbs[1] as u128) << 64); + let key_high = key_as_limbs[2] as u128 | ((key_as_limbs[3] as u128) << 64); + + insert_value_from_var_name( + vars::ids::KEY_LOW, + Felt252::from(key_low), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + insert_value_from_var_name( + vars::ids::KEY_HIGH, + Felt252::from(key_high), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + + Ok(()) +} + +pub const HINT_RECEIPT_KEY_LEADING_ZEROS: &str = + "ids.key_leading_zeros = len(receipt.key.lstrip(\"0x\")) - len(receipt.key.lstrip(\"0x\").lstrip(\"0\"))"; + +pub fn hint_receipt_key_leading_zeros( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let receipt = exec_scopes.get::("receipt")?; + let key_leading_zeros = count_leading_zero_nibbles_from_hex(&format!("{:x}", receipt.key)); + + insert_value_from_var_name( + vars::ids::KEY_LEADING_ZEROS, + MaybeRelocatable::Int(Felt252::from(key_leading_zeros)), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + ) +} + +pub const HINT_RECEIPT_PROOF_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(receipt.proof))"; + +pub fn hint_receipt_proof_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let receipt = exec_scopes.get::("receipt")?; + + insert_value_into_ap(vm, Felt252::from(receipt.proof.proof.len())) +} + +pub const HINT_RECEIPT_BLOCK_NUMBER: &str = "memory[ap] = to_felt_or_relocatable(receipt.block_number)"; + +pub fn hint_receipt_block_number( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let receipt = exec_scopes.get::("receipt")?; + + insert_value_into_ap(vm, Felt252::from(receipt.proof.block_number)) +} + +pub const HINT_RECEIPT_PROOF_BYTES_LEN: &str = "segments.write_arg(ids.proof_bytes_len, receipt.proof_bytes_len)"; + +pub fn hint_receipt_proof_bytes_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let receipt = exec_scopes.get::("receipt")?; + + insert_value_from_var_name( + vars::ids::PROOF_BYTES_LEN, + MaybeRelocatable::Int(Felt252::from(receipt.proof.proof_bytes_len)), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + ) +} + +pub const HINT_RECEIPT_MPT_PROOF: &str = "segments.write_arg(ids.mpt_proof, [int(x, 16) for x in receipt.proof])"; + +pub fn hint_receipt_mpt_proof( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let receipt = exec_scopes.get::("receipt")?; + + let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.write_arg(mpt_proof_ptr, &receipt.proof.proof)?; + + Ok(()) +} From 9a881b98da982e3a42dd6667c209ff474fc4eb85 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Sat, 14 Dec 2024 01:43:30 +0100 Subject: [PATCH 28/75] header proofs fecher --- .../hint_processor/models/proofs/header.rs | 10 ++- .../src/hint_processor/models/proofs/mmr.rs | 18 +++++ cairo_vm_hints/src/provider/indexer/types.rs | 2 +- .../src/syscall_handler/keys/header.rs | 73 ++++++++++++++++++- 4 files changed, 97 insertions(+), 6 deletions(-) diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/header.rs b/cairo_vm_hints/src/hint_processor/models/proofs/header.rs index 757bd77d..14a6b2f3 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/header.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/header.rs @@ -11,6 +11,14 @@ pub struct HeaderProof { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] pub struct Header { - pub rlp: Vec, + pub rlp: Bytes, pub proof: HeaderProof, } + +// impl TryFrom for Header { +// fn try_from(value: MMRProof) -> Result { +// Self { +// rlp: value.block_header.. +// } +// } +// } diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs b/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs index d3d8d6d9..4a50c62d 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs @@ -11,3 +11,21 @@ pub struct MmrMeta { pub chain_id: u64, pub peaks: Vec, } + +// impl MmrMeta { +// pub fn from_indexer(data: indexer::types::MMRMetadata) -> Result { +// Ok(Self { +// id: u64::from_str_radix(&data.mmr_id, 16).unwrap(), +// size: (), +// root: (), +// chain_id: (), +// peaks: (), +// }) +// } +// } + +#[derive(thiserror::Error, Debug)] +pub enum MmrMetaError { + #[error(transparent)] + SerdeJson(#[from] serde_json::Error), +} diff --git a/cairo_vm_hints/src/provider/indexer/types.rs b/cairo_vm_hints/src/provider/indexer/types.rs index e8709ed0..a2fcc4ae 100644 --- a/cairo_vm_hints/src/provider/indexer/types.rs +++ b/cairo_vm_hints/src/provider/indexer/types.rs @@ -102,10 +102,10 @@ pub struct MMRMetadata { #[derive(Serialize, Deserialize, Debug, Clone)] #[serde_as] pub struct MMRProof { + pub block_header: BlockHeader, pub block_number: u64, pub element_hash: String, pub element_index: u64, - pub block_header: BlockHeader, pub siblings_hashes: Vec, } diff --git a/cairo_vm_hints/src/syscall_handler/keys/header.rs b/cairo_vm_hints/src/syscall_handler/keys/header.rs index 2e4f041f..41decdfa 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/header.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/header.rs @@ -1,11 +1,20 @@ use super::KeyFetch; use crate::{ cairo_types::traits::CairoType, - hint_processor::models::proofs::header::HeaderProof, + hint_processor::models::proofs::{ + self, + header::{Header, HeaderProof}, + mmr::MmrMeta, + }, + provider::indexer::{ + types::{BlockHeader, IndexerQuery, MMRData}, + Indexer, + }, syscall_handler::{utils::SyscallExecutionError, RPC}, }; use alloy::{ - primitives::{BlockNumber, ChainId}, + hex::FromHexError, + primitives::{BlockNumber, Bytes, ChainId}, providers::{Provider, RootProvider}, rpc::types::{Block, BlockTransactionsKind}, transports::http::Http, @@ -17,6 +26,7 @@ use cairo_vm::{ }; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; +use starknet_types_core::felt::FromStrError; use std::env; #[derive(Debug, Serialize, Deserialize)] @@ -50,7 +60,7 @@ pub struct Key { impl KeyFetch for Key { type Value = Block; - type Proof = HeaderProof; + type Proof = (MmrMeta, Header); fn fetch_value(&self) -> Result { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); @@ -67,7 +77,62 @@ impl KeyFetch for Key { } fn fetch_proof(&self) -> Result { - todo!() + let provider = Indexer::default(); + let runtime = tokio::runtime::Runtime::new().unwrap(); + let response = runtime + .block_on(async { + provider + .get_headers_proof(IndexerQuery::new(self.chain_id, self.block_number, self.block_number)) + .await + }) + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + + let mmr_meta = MmrMeta { + id: response + .mmr_meta + .mmr_id + .parse() + .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, + size: response.mmr_meta.mmr_size, + root: response + .mmr_meta + .mmr_root + .parse() + .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, + chain_id: self.chain_id, + peaks: response + .mmr_meta + .mmr_peaks + .iter() + .map(|f| f.parse()) + .collect::, FromHexError>>() + .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, + }; + + let mmr_proof = response + .headers + .get(&self.block_number) + .ok_or(SyscallExecutionError::InternalError("block not found".into()))?; + + let rlp = match &mmr_proof.block_header { + BlockHeader::RlpString(rlp) => rlp, + _ => panic!("wrong rlp format"), + }; + + let header = Header { + rlp: rlp.parse().map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, + proof: HeaderProof { + leaf_idx: mmr_proof.element_index, + mmr_path: mmr_proof + .siblings_hashes + .iter() + .map(|f| f.parse()) + .collect::, FromHexError>>() + .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, + }, + }; + + Ok((mmr_meta, header)) } } From 4ca020a81b1891af51d6cf6a2425dbf6e9d1e82f Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 16 Dec 2024 08:53:28 +0100 Subject: [PATCH 29/75] proof fetcher fixes --- .../src/hint_processor/models/proofs/mmr.rs | 12 ---------- .../src/syscall_handler/keys/account.rs | 9 +++++--- .../src/syscall_handler/keys/header.rs | 14 +++++++---- .../src/syscall_handler/keys/storage.rs | 23 +++++++++++++++---- 4 files changed, 35 insertions(+), 23 deletions(-) diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs b/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs index 4a50c62d..a388038c 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs @@ -12,18 +12,6 @@ pub struct MmrMeta { pub peaks: Vec, } -// impl MmrMeta { -// pub fn from_indexer(data: indexer::types::MMRMetadata) -> Result { -// Ok(Self { -// id: u64::from_str_radix(&data.mmr_id, 16).unwrap(), -// size: (), -// root: (), -// chain_id: (), -// peaks: (), -// }) -// } -// } - #[derive(thiserror::Error, Debug)] pub enum MmrMetaError { #[error(transparent)] diff --git a/cairo_vm_hints/src/syscall_handler/keys/account.rs b/cairo_vm_hints/src/syscall_handler/keys/account.rs index 15159b0c..6812f772 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/account.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/account.rs @@ -1,7 +1,7 @@ use super::KeyFetch; use crate::{ cairo_types::traits::CairoType, - hint_processor::models::proofs::mpt::MPTProof, + hint_processor::models::proofs::{self, mpt::MPTProof}, syscall_handler::{utils::SyscallExecutionError, RPC}, }; use alloy::{ @@ -55,7 +55,7 @@ pub struct Key { impl KeyFetch for Key { type Value = Account; - type Proof = MPTProof; + type Proof = proofs::account::Account; fn fetch_value(&self) -> Result { let runtime = tokio::runtime::Runtime::new().unwrap(); @@ -72,7 +72,10 @@ impl KeyFetch for Key { let value = runtime .block_on(async { provider.get_proof(self.address, vec![]).block_id(self.block_number.into()).await }) .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(Self::Proof::new(self.block_number, value.account_proof)) + Ok(Self::Proof::new( + value.address, + vec![MPTProof::new(self.block_number, value.account_proof)], + )) } } diff --git a/cairo_vm_hints/src/syscall_handler/keys/header.rs b/cairo_vm_hints/src/syscall_handler/keys/header.rs index 41decdfa..b9043b9e 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/header.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/header.rs @@ -79,6 +79,8 @@ impl KeyFetch for Key { fn fetch_proof(&self) -> Result { let provider = Indexer::default(); let runtime = tokio::runtime::Runtime::new().unwrap(); + + // Fetch proof response let response = runtime .block_on(async { provider @@ -87,6 +89,7 @@ impl KeyFetch for Key { }) .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + // Extract MMR metadata let mmr_meta = MmrMeta { id: response .mmr_meta @@ -104,21 +107,24 @@ impl KeyFetch for Key { .mmr_meta .mmr_peaks .iter() - .map(|f| f.parse()) + .map(|peak| peak.parse()) .collect::, FromHexError>>() .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, }; + // Retrieve MMR proof let mmr_proof = response .headers .get(&self.block_number) - .ok_or(SyscallExecutionError::InternalError("block not found".into()))?; + .ok_or_else(|| SyscallExecutionError::InternalError("block not found".into()))?; + // Parse RLP let rlp = match &mmr_proof.block_header { BlockHeader::RlpString(rlp) => rlp, - _ => panic!("wrong rlp format"), + _ => return Err(SyscallExecutionError::InternalError("wrong rlp format".into())), }; + // Construct Header let header = Header { rlp: rlp.parse().map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, proof: HeaderProof { @@ -126,7 +132,7 @@ impl KeyFetch for Key { mmr_path: mmr_proof .siblings_hashes .iter() - .map(|f| f.parse()) + .map(|hash| hash.parse()) .collect::, FromHexError>>() .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, }, diff --git a/cairo_vm_hints/src/syscall_handler/keys/storage.rs b/cairo_vm_hints/src/syscall_handler/keys/storage.rs index 56912228..d1a5b1c5 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/storage.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/storage.rs @@ -1,7 +1,7 @@ use super::KeyFetch; use crate::{ cairo_types::traits::CairoType, - hint_processor::models::proofs::mpt::MPTProof, + hint_processor::models::proofs::{self, mpt::MPTProof}, syscall_handler::{utils::SyscallExecutionError, RPC}, }; use alloy::{ @@ -61,7 +61,7 @@ pub struct Key { impl KeyFetch for Key { type Value = StorageValue; - type Proof = MPTProof; + type Proof = (proofs::account::Account, proofs::storage::Storage); fn fetch_value(&self) -> Result { let runtime = tokio::runtime::Runtime::new().unwrap(); @@ -81,9 +81,24 @@ impl KeyFetch for Key { let runtime = tokio::runtime::Runtime::new().unwrap(); let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let value = runtime - .block_on(async { provider.get_proof(self.address, vec![]).block_id(self.block_number.into()).await }) + .block_on(async { + provider + .get_proof(self.address, vec![self.storage_slot]) + .block_id(self.block_number.into()) + .await + }) .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(Self::Proof::new(self.block_number, value.account_proof)) + Ok(( + proofs::account::Account::new(value.address, vec![MPTProof::new(self.block_number, value.account_proof)]), + proofs::storage::Storage::new( + value.address, + self.storage_slot, + vec![MPTProof::new( + self.block_number, + value.storage_proof.into_iter().flat_map(|f| f.proof).collect(), + )], + ), + )) } } From 4c45bca125ca75d433f9338b3c25ffbd2fe953c6 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 16 Dec 2024 13:28:41 +0100 Subject: [PATCH 30/75] fix --- cairo_vm_hints/src/hint_processor/models/proofs/header.rs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/header.rs b/cairo_vm_hints/src/hint_processor/models/proofs/header.rs index 14a6b2f3..c29630fa 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/header.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/header.rs @@ -14,11 +14,3 @@ pub struct Header { pub rlp: Bytes, pub proof: HeaderProof, } - -// impl TryFrom for Header { -// fn try_from(value: MMRProof) -> Result { -// Self { -// rlp: value.block_header.. -// } -// } -// } From 226eba9755f81494bb18341326bdd85ec08a9b0a Mon Sep 17 00:00:00 2001 From: codyx Date: Mon, 16 Dec 2024 16:52:57 +0400 Subject: [PATCH 31/75] Hotfixes --- .../lib/verifiers/evm/account_verifier.rs | 4 +-- .../lib/verifiers/evm/block_tx_verifier.rs | 31 ++++++++++--------- .../lib/verifiers/evm/header_verifier.rs | 14 ++++----- .../lib/verifiers/evm/receipt_verifier.rs | 18 +++++------ cairo_vm_hints/src/hints/vars.rs | 3 ++ 5 files changed, 37 insertions(+), 33 deletions(-) diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs index aaf7cd28..b8cf17c1 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs @@ -27,7 +27,7 @@ pub fn hint_batch_accounts_len( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; + let batch = exec_scopes.get::(vars::scopes::BATCH)?; insert_value_into_ap(vm, Felt252::from(batch.accounts.len())) } @@ -41,7 +41,7 @@ pub fn hint_get_account_address( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; + let batch = exec_scopes.get::(vars::scopes::BATCH)?; let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? .try_into() .unwrap(); diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs index a347b352..4a51ca30 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs @@ -7,11 +7,15 @@ use cairo_vm::{ vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; +use num_bigint::BigUint; use std::collections::HashMap; use crate::{ hint_processor::models::proofs::{transaction::Transaction, Proofs}, - hints::{lib::utils::count_leading_zero_nibbles_from_hex, vars}, + hints::{ + lib::utils::{count_leading_zero_nibbles_from_hex, split_128}, + vars, + }, }; pub const HINT_BATCH_TRANSACTIONS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.transactions))"; @@ -22,7 +26,7 @@ pub fn hint_batch_transactions_len( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; + let batch = exec_scopes.get::(vars::scopes::BATCH)?; insert_value_into_ap(vm, Felt252::from(batch.transactions.len())) } @@ -35,13 +39,13 @@ pub fn hint_set_tx( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; + let batch = exec_scopes.get::(vars::scopes::BATCH)?; let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? .try_into() .unwrap(); let transaction = batch.transactions[idx].clone(); - exec_scopes.insert_value::("transaction", transaction); + exec_scopes.insert_value::(vars::scopes::TRANSACTION, transaction); Ok(()) } @@ -54,13 +58,10 @@ pub fn hint_set_tx_key( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let transaction = exec_scopes.get::("transaction")?; - let key = transaction.key; - - let key_as_limbs = key.as_limbs(); - let key_low = key_as_limbs[0] as u128 | ((key_as_limbs[1] as u128) << 64); - let key_high = key_as_limbs[2] as u128 | ((key_as_limbs[3] as u128) << 64); + let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; + let key = BigUint::from_bytes_be(&transaction.key.to_be_bytes::<32>()); + let (key_low, key_high) = split_128(&key); insert_value_from_var_name( vars::ids::KEY_LOW, Felt252::from(key_low), @@ -88,7 +89,7 @@ pub fn hint_set_tx_key_leading_zeros( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let transaction = exec_scopes.get::("transaction")?; + let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; let key_leading_zeros = count_leading_zero_nibbles_from_hex(&format!("{:x}", transaction.key)); insert_value_from_var_name( @@ -108,7 +109,7 @@ pub fn hint_set_tx_proof_len( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let transaction = exec_scopes.get::("transaction")?; + let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; insert_value_into_ap(vm, Felt252::from(transaction.proof.proof.len())) } @@ -121,7 +122,7 @@ pub fn hint_set_tx_block_number( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let transaction = exec_scopes.get::("transaction")?; + let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; insert_value_into_ap(vm, Felt252::from(transaction.proof.block_number)) } @@ -134,7 +135,7 @@ pub fn hint_proof_bytes_len( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let transaction = exec_scopes.get::("transaction")?; + let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; let proof_bytes_len_ptr = get_ptr_from_var_name(vars::ids::PROOF_BYTES_LEN, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; vm.insert_value(proof_bytes_len_ptr, Felt252::from(transaction.proof.proof_bytes_len))?; @@ -150,7 +151,7 @@ pub fn hint_mpt_proof( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let transaction = exec_scopes.get::("transaction")?; + let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; vm.write_arg(mpt_proof_ptr, &transaction.proof.proof)?; diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs index da52dcc7..78344374 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs @@ -22,7 +22,7 @@ pub fn hint_batch_headers_len( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; + let batch = exec_scopes.get::(vars::scopes::BATCH)?; insert_value_into_ap(vm, Felt252::from(batch.headers.len())) } @@ -35,14 +35,14 @@ pub fn hint_set_header( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; + let batch = exec_scopes.get::(vars::scopes::BATCH)?; let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? .try_into() .unwrap(); let header = batch.headers[idx - 1].clone(); let rlp = header.rlp.clone(); - exec_scopes.insert_value::
("header", header); + exec_scopes.insert_value::
(vars::scopes::HEADER, header); let rlp_ptr = get_ptr_from_var_name(vars::ids::RLP, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; vm.write_arg(rlp_ptr, &rlp)?; @@ -58,7 +58,7 @@ pub fn hint_rlp_len( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let header = exec_scopes.get::
("header")?; + let header = exec_scopes.get::
(vars::scopes::HEADER)?; insert_value_into_ap(vm, Felt252::from(header.rlp.len())) } @@ -71,7 +71,7 @@ pub fn hint_leaf_idx( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let header = exec_scopes.get::
("header")?; + let header = exec_scopes.get::
(vars::scopes::HEADER)?; insert_value_into_ap(vm, Felt252::from(header.proof.leaf_idx)) } @@ -84,7 +84,7 @@ pub fn hint_mmr_path_len( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let header = exec_scopes.get::
("header")?; + let header = exec_scopes.get::
(vars::scopes::HEADER)?; insert_value_into_ap(vm, Felt252::from(header.proof.mmr_path.len())) } @@ -97,7 +97,7 @@ pub fn hint_mmr_path( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let header = exec_scopes.get::
("header")?; + let header = exec_scopes.get::
(vars::scopes::HEADER)?; let mmr_path_ptr = get_ptr_from_var_name(vars::ids::MMR_PATH, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; vm.write_arg(mmr_path_ptr, &header.proof.mmr_path)?; diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs index d2977f83..5dcb4e53 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs @@ -22,7 +22,7 @@ pub fn hint_batch_receipts_len( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; + let batch = exec_scopes.get::(vars::scopes::BATCH)?; insert_value_into_ap(vm, Felt252::from(batch.transaction_receipts.len())) } @@ -35,13 +35,13 @@ pub fn hint_set_receipt( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::("batch")?; + let batch = exec_scopes.get::(vars::scopes::BATCH)?; let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? .try_into() .unwrap(); let receipt = batch.transaction_receipts[idx].clone(); - exec_scopes.insert_value::("receipt", receipt); + exec_scopes.insert_value::(vars::scopes::RECEIPT, receipt); Ok(()) } @@ -54,7 +54,7 @@ pub fn hint_receipt_key( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let receipt = exec_scopes.get::("receipt")?; + let receipt = exec_scopes.get::(vars::scopes::RECEIPT)?; let key_as_limbs = receipt.key.as_limbs(); let key_low = key_as_limbs[0] as u128 | ((key_as_limbs[1] as u128) << 64); let key_high = key_as_limbs[2] as u128 | ((key_as_limbs[3] as u128) << 64); @@ -86,7 +86,7 @@ pub fn hint_receipt_key_leading_zeros( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let receipt = exec_scopes.get::("receipt")?; + let receipt = exec_scopes.get::(vars::scopes::RECEIPT)?; let key_leading_zeros = count_leading_zero_nibbles_from_hex(&format!("{:x}", receipt.key)); insert_value_from_var_name( @@ -106,7 +106,7 @@ pub fn hint_receipt_proof_len( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let receipt = exec_scopes.get::("receipt")?; + let receipt = exec_scopes.get::(vars::scopes::RECEIPT)?; insert_value_into_ap(vm, Felt252::from(receipt.proof.proof.len())) } @@ -119,7 +119,7 @@ pub fn hint_receipt_block_number( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let receipt = exec_scopes.get::("receipt")?; + let receipt = exec_scopes.get::(vars::scopes::RECEIPT)?; insert_value_into_ap(vm, Felt252::from(receipt.proof.block_number)) } @@ -132,7 +132,7 @@ pub fn hint_receipt_proof_bytes_len( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let receipt = exec_scopes.get::("receipt")?; + let receipt = exec_scopes.get::(vars::scopes::RECEIPT)?; insert_value_from_var_name( vars::ids::PROOF_BYTES_LEN, @@ -151,7 +151,7 @@ pub fn hint_receipt_mpt_proof( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let receipt = exec_scopes.get::("receipt")?; + let receipt = exec_scopes.get::(vars::scopes::RECEIPT)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; vm.write_arg(mpt_proof_ptr, &receipt.proof.proof)?; diff --git a/cairo_vm_hints/src/hints/vars.rs b/cairo_vm_hints/src/hints/vars.rs index d5475e25..ff6d9b7d 100644 --- a/cairo_vm_hints/src/hints/vars.rs +++ b/cairo_vm_hints/src/hints/vars.rs @@ -3,11 +3,14 @@ pub mod scopes { pub(crate) const BATCH: &str = "batch"; pub(crate) const COMPILED_CLASS: &str = "compiled_class"; pub(crate) const DICT_MANAGER: &str = "dict_manager"; + pub(crate) const HEADER: &str = "header"; pub(crate) const N_SELECTED_BUILTINS: &str = "n_selected_builtins"; pub(crate) const PARAMS: &str = "params"; pub(crate) const PROOF: &str = "proof"; pub(crate) const PROOFS: &str = "proofs"; + pub(crate) const RECEIPT: &str = "receipt"; pub(crate) const SYSCALL_HANDLER: &str = "syscall_handler"; + pub(crate) const TRANSACTION: &str = "transaction"; } pub mod ids { From 0b614db7508c704981e2203a7a4057b955741af7 Mon Sep 17 00:00:00 2001 From: codyx Date: Mon, 16 Dec 2024 17:29:09 +0400 Subject: [PATCH 32/75] Add storage item verifier (evm) --- cairo_vm_hints/src/hint_processor/mod.rs | 11 + .../src/hints/lib/verifiers/evm/mod.rs | 1 + .../verifiers/evm/storage_item_verifier.rs | 213 ++++++++++++++++++ cairo_vm_hints/src/hints/vars.rs | 2 + 4 files changed, 227 insertions(+) create mode 100644 cairo_vm_hints/src/hints/lib/verifiers/evm/storage_item_verifier.rs diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index 14eb7811..f2f0a88d 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -116,6 +116,17 @@ impl CustomHintProcessor { hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_LEN.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_proof_len); hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_proof_bytes_len); hints.insert(lib::verifiers::evm::receipt_verifier::HINT_SET_RECEIPT.into(), lib::verifiers::evm::receipt_verifier::hint_set_receipt); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_BATCH_STORAGES_LEN.into(), lib::verifiers::evm::storage_item_verifier::hint_batch_storages_len); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_BATCH_STORAGES.into(), lib::verifiers::evm::storage_item_verifier::hint_set_batch_storages); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_MPT_PROOF.into(), lib::verifiers::evm::storage_item_verifier::hint_set_mpt_proof); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_PROOF_LEN.into(), lib::verifiers::evm::storage_item_verifier::hint_set_proof_len); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BYTES_LEN.into(), lib::verifiers::evm::storage_item_verifier::hint_set_proof_bytes_len); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BLOCK_NUMBER.into(), lib::verifiers::evm::storage_item_verifier::hint_set_proof_block_number); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_key); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY_LEADING_ZEROS.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_key_leading_zeros); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOFS_LEN.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_proofs_len); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOF_AT.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_proof_at); + hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_SLOT.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_slot); hints.insert(lib::verifiers::verify::HINT_BATCH_LEN.into(), lib::verifiers::verify::hint_batch_len); hints.insert(lib::verifiers::verify::HINT_CHAIN_ID.into(), lib::verifiers::verify::hint_chain_id); hints.insert(lib::verifiers::verify::HINT_VM_ENTER_SCOPE.into(), lib::verifiers::verify::hint_vm_enter_scope); diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs index dd2867c1..c87b737a 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs @@ -2,3 +2,4 @@ pub mod account_verifier; pub mod block_tx_verifier; pub mod header_verifier; pub mod receipt_verifier; +pub mod storage_item_verifier; diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/storage_item_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/storage_item_verifier.rs new file mode 100644 index 00000000..a7e554a7 --- /dev/null +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/storage_item_verifier.rs @@ -0,0 +1,213 @@ +use cairo_vm::{ + hint_processor::builtin_hint_processor::{ + builtin_hint_processor_definition::HintProcessorData, + hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, + }, + types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use num_bigint::BigUint; +use num_traits::Num; +use std::collections::HashMap; + +use crate::{ + hint_processor::models::proofs::{mpt::MPTProof, storage::Storage, Proofs}, + hints::{ + lib::utils::{count_leading_zero_nibbles_from_hex, split_128}, + vars, + }, +}; + +pub const HINT_BATCH_STORAGES_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.storages))"; + +pub fn hint_batch_storages_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::(vars::scopes::BATCH)?; + + insert_value_into_ap(vm, Felt252::from(batch.storages.len())) +} + +pub const HINT_SET_BATCH_STORAGES: &str = + "storage = batch.storages[ids.idx]\nsegments.write_arg(ids.address, [int(x, 16) for x in storage.address]))"; + +pub fn hint_set_batch_storages( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let batch = exec_scopes.get::(vars::scopes::BATCH)?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let storage = batch.storages[idx].clone(); + + exec_scopes.insert_value::(vars::scopes::STORAGE, storage); + + Ok(()) +} + +pub const HINT_SET_STORAGE_SLOT: &str = "segments.write_arg(ids.slot, [int(x, 16) for x in storage.slot]))"; + +pub fn hint_set_storage_slot( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let storage = exec_scopes.get::(vars::scopes::STORAGE)?; + let slot = BigUint::from_str_radix(&storage.slot.to_string(), 16).unwrap(); + + let slot_ptr = get_ptr_from_var_name(vars::ids::SLOT, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.insert_value(slot_ptr, &Felt252::from(slot))?; + + Ok(()) +} + +pub const HINT_SET_STORAGE_KEY: &str = "from tools.py.utils import split_128\n(ids.key.low, ids.key.high) = split_128(int(storage.storage_key, 16))"; + +pub fn hint_set_storage_key( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let storage = exec_scopes.get::(vars::scopes::STORAGE)?; + let key = BigUint::from_str_radix(&storage.storage_key.to_string(), 16).unwrap(); + + let (key_low, key_high) = split_128(&key); + insert_value_from_var_name( + vars::ids::KEY_LOW, + MaybeRelocatable::Int(Felt252::from(key_low)), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + insert_value_from_var_name( + vars::ids::KEY_HIGH, + MaybeRelocatable::Int(Felt252::from(key_high)), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + + Ok(()) +} + +pub const HINT_SET_STORAGE_KEY_LEADING_ZEROS: &str = + "ids.key_leading_zeros = len(storage.storage_key.lstrip(\"0x\")) - len(storage.storage_key.lstrip(\"0x\").lstrip(\"0\"))"; + +pub fn hint_set_storage_key_leading_zeros( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let storage = exec_scopes.get::(vars::scopes::STORAGE)?; + let key_leading_zeros = count_leading_zero_nibbles_from_hex(&storage.storage_key.to_string()); + + insert_value_from_var_name( + vars::ids::KEY_LEADING_ZEROS, + MaybeRelocatable::Int(Felt252::from(key_leading_zeros)), + vm, + &hint_data.ids_data, + &hint_data.ap_tracking, + )?; + + Ok(()) +} + +pub const HINT_SET_STORAGE_PROOFS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(storage.proofs))"; + +pub fn hint_set_storage_proofs_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let storage = exec_scopes.get::(vars::scopes::STORAGE)?; + + insert_value_into_ap(vm, Felt252::from(storage.proofs.len())) +} + +pub const HINT_SET_STORAGE_PROOF_AT: &str = "proof = storage.proofs[ids.idx]"; + +pub fn hint_set_storage_proof_at( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let storage = exec_scopes.get::(vars::scopes::STORAGE)?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + let proof = storage.proofs[idx].clone(); + + exec_scopes.insert_value::(vars::scopes::PROOF, proof); + + Ok(()) +} + +pub const HINT_SET_PROOF_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(proof.proof))"; + +pub fn hint_set_proof_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let proof = exec_scopes.get::(vars::scopes::PROOF)?; + + insert_value_into_ap(vm, Felt252::from(proof.proof.len())) +} + +pub const HINT_SET_PROOF_BLOCK_NUMBER: &str = "memory[ap] = to_felt_or_relocatable(proof.block_number)"; + +pub fn hint_set_proof_block_number( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let proof = exec_scopes.get::(vars::scopes::PROOF)?; + + insert_value_into_ap(vm, Felt252::from(proof.block_number)) +} + +pub const HINT_SET_PROOF_BYTES_LEN: &str = "segments.write_arg(ids.proof_bytes_len, proof.proof_bytes_len)"; + +pub fn hint_set_proof_bytes_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let proof = exec_scopes.get::(vars::scopes::PROOF)?; + + let proof_bytes_len_ptr = get_ptr_from_var_name(vars::ids::PROOF_BYTES_LEN, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.insert_value(proof_bytes_len_ptr, &Felt252::from(proof.proof_bytes_len))?; + + Ok(()) +} + +pub const HINT_SET_MPT_PROOF: &str = "segments.write_arg(ids.mpt_proof, [int(x, 16) for x in proof.proof])"; + +pub fn hint_set_mpt_proof( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let proof = exec_scopes.get::(vars::scopes::PROOF)?; + + let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.write_arg(mpt_proof_ptr, &proof.proof)?; + + Ok(()) +} diff --git a/cairo_vm_hints/src/hints/vars.rs b/cairo_vm_hints/src/hints/vars.rs index ff6d9b7d..0a8c9ac9 100644 --- a/cairo_vm_hints/src/hints/vars.rs +++ b/cairo_vm_hints/src/hints/vars.rs @@ -9,6 +9,7 @@ pub mod scopes { pub(crate) const PROOF: &str = "proof"; pub(crate) const PROOFS: &str = "proofs"; pub(crate) const RECEIPT: &str = "receipt"; + pub(crate) const STORAGE: &str = "storage"; pub(crate) const SYSCALL_HANDLER: &str = "syscall_handler"; pub(crate) const TRANSACTION: &str = "transaction"; } @@ -51,6 +52,7 @@ pub mod ids { pub(crate) const SELECT_BUILTIN: &str = "select_builtin"; pub(crate) const SELECTED_ENCODINGS: &str = "selected_encodings"; pub(crate) const SELECTED_PTRS: &str = "selected_ptrs"; + pub(crate) const SLOT: &str = "ids.slot"; pub(crate) const SYSCALL_PTR: &str = "syscall_ptr"; pub(crate) const TASK_HASH: &str = "ids.task_hash"; pub(crate) const VALUE_LEN: &str = "ids.value_len"; From ae6e57f83136bb304d933a6c5e3dfa24fd62d9f8 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 16 Dec 2024 15:20:37 +0100 Subject: [PATCH 33/75] fetch abstracted --- .../src/syscall_handler/evm/dryrun/account.rs | 2 +- .../src/syscall_handler/evm/dryrun/header.rs | 2 +- .../src/syscall_handler/evm/dryrun/storage.rs | 2 +- .../src/syscall_handler/keys/account.rs | 28 ++-- .../src/syscall_handler/keys/header.rs | 121 +++++++++--------- .../src/syscall_handler/keys/mod.rs | 11 +- .../src/syscall_handler/keys/storage.rs | 51 ++++---- 7 files changed, 110 insertions(+), 107 deletions(-) diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs index 50e10cfb..eac2250f 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs @@ -1,7 +1,7 @@ use crate::syscall_handler::{ keys::{ account::{CairoKey, Key}, - KeyFetch, + FetchValue, }, traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs index 56acb2f4..4f6a6940 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs @@ -1,7 +1,7 @@ use crate::syscall_handler::{ keys::{ header::{CairoKey, Key}, - KeyFetch, + FetchValue, }, traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs b/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs index 5c68a8e5..3e9256c8 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs +++ b/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs @@ -1,7 +1,7 @@ use crate::syscall_handler::{ keys::{ storage::{CairoKey, Key}, - KeyFetch, + FetchValue, }, traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, diff --git a/cairo_vm_hints/src/syscall_handler/keys/account.rs b/cairo_vm_hints/src/syscall_handler/keys/account.rs index 6812f772..9acd8ea0 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/account.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/account.rs @@ -1,4 +1,3 @@ -use super::KeyFetch; use crate::{ cairo_types::traits::CairoType, hint_processor::models::proofs::{self, mpt::MPTProof}, @@ -20,6 +19,8 @@ use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use std::env; +use super::FetchValue; + #[derive(Debug)] pub struct CairoKey { chain_id: Felt252, @@ -53,9 +54,8 @@ pub struct Key { address: Address, } -impl KeyFetch for Key { +impl FetchValue for Key { type Value = Account; - type Proof = proofs::account::Account; fn fetch_value(&self) -> Result { let runtime = tokio::runtime::Runtime::new().unwrap(); @@ -66,17 +66,17 @@ impl KeyFetch for Key { Ok(value) } - fn fetch_proof(&self) -> Result { - let runtime = tokio::runtime::Runtime::new().unwrap(); - let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let value = runtime - .block_on(async { provider.get_proof(self.address, vec![]).block_id(self.block_number.into()).await }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(Self::Proof::new( - value.address, - vec![MPTProof::new(self.block_number, value.account_proof)], - )) - } + // fn fetch_proof(&self) -> Result { + // let runtime = tokio::runtime::Runtime::new().unwrap(); + // let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + // let value = runtime + // .block_on(async { provider.get_proof(self.address, vec![]).block_id(self.block_number.into()).await }) + // .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + // Ok(Self::Proof::new( + // value.address, + // vec![MPTProof::new(self.block_number, value.account_proof)], + // )) + // } } impl TryFrom for Key { diff --git a/cairo_vm_hints/src/syscall_handler/keys/header.rs b/cairo_vm_hints/src/syscall_handler/keys/header.rs index b9043b9e..8892e13f 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/header.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/header.rs @@ -1,4 +1,4 @@ -use super::KeyFetch; +use super::FetchValue; use crate::{ cairo_types::traits::CairoType, hint_processor::models::proofs::{ @@ -58,9 +58,8 @@ pub struct Key { block_number: BlockNumber, } -impl KeyFetch for Key { +impl FetchValue for Key { type Value = Block; - type Proof = (MmrMeta, Header); fn fetch_value(&self) -> Result { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); @@ -76,70 +75,70 @@ impl KeyFetch for Key { Ok(block) } - fn fetch_proof(&self) -> Result { - let provider = Indexer::default(); - let runtime = tokio::runtime::Runtime::new().unwrap(); + // fn fetch_proof(&self) -> Result { + // let provider = Indexer::default(); + // let runtime = tokio::runtime::Runtime::new().unwrap(); - // Fetch proof response - let response = runtime - .block_on(async { - provider - .get_headers_proof(IndexerQuery::new(self.chain_id, self.block_number, self.block_number)) - .await - }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + // // Fetch proof response + // let response = runtime + // .block_on(async { + // provider + // .get_headers_proof(IndexerQuery::new(self.chain_id, self.block_number, self.block_number)) + // .await + // }) + // .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - // Extract MMR metadata - let mmr_meta = MmrMeta { - id: response - .mmr_meta - .mmr_id - .parse() - .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, - size: response.mmr_meta.mmr_size, - root: response - .mmr_meta - .mmr_root - .parse() - .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, - chain_id: self.chain_id, - peaks: response - .mmr_meta - .mmr_peaks - .iter() - .map(|peak| peak.parse()) - .collect::, FromHexError>>() - .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, - }; + // // Extract MMR metadata + // let mmr_meta = MmrMeta { + // id: response + // .mmr_meta + // .mmr_id + // .parse() + // .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, + // size: response.mmr_meta.mmr_size, + // root: response + // .mmr_meta + // .mmr_root + // .parse() + // .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, + // chain_id: self.chain_id, + // peaks: response + // .mmr_meta + // .mmr_peaks + // .iter() + // .map(|peak| peak.parse()) + // .collect::, FromHexError>>() + // .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, + // }; - // Retrieve MMR proof - let mmr_proof = response - .headers - .get(&self.block_number) - .ok_or_else(|| SyscallExecutionError::InternalError("block not found".into()))?; + // // Retrieve MMR proof + // let mmr_proof = response + // .headers + // .get(&self.block_number) + // .ok_or_else(|| SyscallExecutionError::InternalError("block not found".into()))?; - // Parse RLP - let rlp = match &mmr_proof.block_header { - BlockHeader::RlpString(rlp) => rlp, - _ => return Err(SyscallExecutionError::InternalError("wrong rlp format".into())), - }; + // // Parse RLP + // let rlp = match &mmr_proof.block_header { + // BlockHeader::RlpString(rlp) => rlp, + // _ => return Err(SyscallExecutionError::InternalError("wrong rlp format".into())), + // }; - // Construct Header - let header = Header { - rlp: rlp.parse().map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, - proof: HeaderProof { - leaf_idx: mmr_proof.element_index, - mmr_path: mmr_proof - .siblings_hashes - .iter() - .map(|hash| hash.parse()) - .collect::, FromHexError>>() - .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, - }, - }; + // // Construct Header + // let header = Header { + // rlp: rlp.parse().map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, + // proof: HeaderProof { + // leaf_idx: mmr_proof.element_index, + // mmr_path: mmr_proof + // .siblings_hashes + // .iter() + // .map(|hash| hash.parse()) + // .collect::, FromHexError>>() + // .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, + // }, + // }; - Ok((mmr_meta, header)) - } + // Ok((mmr_meta, header)) + // } } impl TryFrom for Key { diff --git a/cairo_vm_hints/src/syscall_handler/keys/mod.rs b/cairo_vm_hints/src/syscall_handler/keys/mod.rs index 809e2772..0aa4c83c 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/mod.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/mod.rs @@ -1,5 +1,7 @@ #![allow(unused)] +use crate::hint_processor::models::proofs::Proofs; + use super::utils::SyscallExecutionError; pub mod account; pub mod header; @@ -7,9 +9,12 @@ pub mod receipt; pub mod storage; pub mod transaction; -pub trait KeyFetch { +pub trait FetchValue { type Value; - type Proof; fn fetch_value(&self) -> Result; - fn fetch_proof(&self) -> Result; +} + +pub trait FetchProofs { + type Key; + fn fetch_proofs(&self, keys: Vec) -> Result; } diff --git a/cairo_vm_hints/src/syscall_handler/keys/storage.rs b/cairo_vm_hints/src/syscall_handler/keys/storage.rs index d1a5b1c5..159c0ed7 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/storage.rs +++ b/cairo_vm_hints/src/syscall_handler/keys/storage.rs @@ -1,4 +1,4 @@ -use super::KeyFetch; +use super::FetchValue; use crate::{ cairo_types::traits::CairoType, hint_processor::models::proofs::{self, mpt::MPTProof}, @@ -59,9 +59,8 @@ pub struct Key { storage_slot: StorageKey, } -impl KeyFetch for Key { +impl FetchValue for Key { type Value = StorageValue; - type Proof = (proofs::account::Account, proofs::storage::Storage); fn fetch_value(&self) -> Result { let runtime = tokio::runtime::Runtime::new().unwrap(); @@ -77,29 +76,29 @@ impl KeyFetch for Key { Ok(value) } - fn fetch_proof(&self) -> Result { - let runtime = tokio::runtime::Runtime::new().unwrap(); - let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let value = runtime - .block_on(async { - provider - .get_proof(self.address, vec![self.storage_slot]) - .block_id(self.block_number.into()) - .await - }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(( - proofs::account::Account::new(value.address, vec![MPTProof::new(self.block_number, value.account_proof)]), - proofs::storage::Storage::new( - value.address, - self.storage_slot, - vec![MPTProof::new( - self.block_number, - value.storage_proof.into_iter().flat_map(|f| f.proof).collect(), - )], - ), - )) - } + // fn fetch_proof(&self) -> Result { + // let runtime = tokio::runtime::Runtime::new().unwrap(); + // let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + // let value = runtime + // .block_on(async { + // provider + // .get_proof(self.address, vec![self.storage_slot]) + // .block_id(self.block_number.into()) + // .await + // }) + // .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + // Ok(( + // proofs::account::Account::new(value.address, vec![MPTProof::new(self.block_number, value.account_proof)]), + // proofs::storage::Storage::new( + // value.address, + // self.storage_slot, + // vec![MPTProof::new( + // self.block_number, + // value.storage_proof.into_iter().flat_map(|f| f.proof).collect(), + // )], + // ), + // )) + // } } impl TryFrom for Key { From a577ed61dba63fe1b8b57918a3be6f070439286f Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 16 Dec 2024 15:57:28 +0100 Subject: [PATCH 34/75] data manip fixes & refactor --- cairo_vm_hints/src/hint_processor/mod.rs | 16 ++++++++-------- .../src/hint_processor/models/proofs/header.rs | 2 +- .../src/hint_processor/models/proofs/mpt.rs | 6 ++---- .../hints/lib/verifiers/evm/account_verifier.rs | 10 ++++++---- .../hints/lib/verifiers/evm/header_verifier.rs | 5 +++-- .../src/hints/lib/verifiers/evm/mod.rs | 2 +- .../hints/lib/verifiers/evm/receipt_verifier.rs | 7 ++++--- .../lib/verifiers/evm/storage_item_verifier.rs | 14 ++++++++------ ...ck_tx_verifier.rs => transaction_verifier.rs} | 9 +++++---- 9 files changed, 38 insertions(+), 33 deletions(-) rename cairo_vm_hints/src/hints/lib/verifiers/evm/{block_tx_verifier.rs => transaction_verifier.rs} (96%) diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index f2f0a88d..4287afc1 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -94,14 +94,14 @@ impl CustomHintProcessor { hints.insert(lib::verifiers::evm::account_verifier::HINT_BATCH_ACCOUNTS_LEN.into(), lib::verifiers::evm::account_verifier::hint_batch_accounts_len); hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_ACCOUNT_ADDRESS.into(), lib::verifiers::evm::account_verifier::hint_get_account_address); hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), lib::verifiers::evm::account_verifier::hint_get_mpt_proof); - hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), lib::verifiers::evm::block_tx_verifier::hint_batch_transactions_len); - hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx); - hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX_KEY.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx_key); - hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX_KEY_LEADING_ZEROS.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx_key_leading_zeros); - hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX_PROOF_LEN.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx_proof_len); - hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), lib::verifiers::evm::block_tx_verifier::hint_set_tx_block_number); - hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::block_tx_verifier::hint_proof_bytes_len); - hints.insert(lib::verifiers::evm::block_tx_verifier::HINT_MPT_PROOF.into(), lib::verifiers::evm::block_tx_verifier::hint_mpt_proof); + hints.insert(lib::verifiers::evm::transaction_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), lib::verifiers::evm::transaction_verifier::hint_batch_transactions_len); + hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx); + hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX_KEY.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx_key); + hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX_KEY_LEADING_ZEROS.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx_key_leading_zeros); + hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX_PROOF_LEN.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx_proof_len); + hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx_block_number); + hints.insert(lib::verifiers::evm::transaction_verifier::HINT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::transaction_verifier::hint_proof_bytes_len); + hints.insert(lib::verifiers::evm::transaction_verifier::HINT_MPT_PROOF.into(), lib::verifiers::evm::transaction_verifier::hint_mpt_proof); hints.insert(lib::verifiers::evm::header_verifier::HINT_BATCH_HEADERS_LEN.into(), lib::verifiers::evm::header_verifier::hint_batch_headers_len); hints.insert(lib::verifiers::evm::header_verifier::HINT_LEAF_IDX.into(), lib::verifiers::evm::header_verifier::hint_leaf_idx); hints.insert(lib::verifiers::evm::header_verifier::HINT_MMR_PATH_LEN.into(), lib::verifiers::evm::header_verifier::hint_mmr_path_len); diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/header.rs b/cairo_vm_hints/src/hint_processor/models/proofs/header.rs index 6226e6b6..a8393cf3 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/header.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/header.rs @@ -13,6 +13,6 @@ pub struct HeaderProof { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] pub struct Header { - pub rlp: Vec, + pub rlp: Bytes, pub proof: HeaderProof, } diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs b/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs index b373c951..64219585 100644 --- a/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs +++ b/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs @@ -1,4 +1,4 @@ -use cairo_vm::Felt252; +use alloy::primitives::Bytes; use serde::{Deserialize, Serialize}; use serde_with::serde_as; @@ -6,7 +6,5 @@ use serde_with::serde_as; #[serde_as] pub struct MPTProof { pub block_number: u64, - pub proof_bytes_len: u64, - #[serde_as(as = "starknet_core::serde::unsigned_field_element::UfeHex")] - pub proof: Vec, + pub proof: Bytes, } diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs index b8cf17c1..67d8df23 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs @@ -46,12 +46,13 @@ pub fn hint_get_account_address( .try_into() .unwrap(); let account = batch.accounts[idx].clone(); - let address: Vec = account.address.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + let address_le_chunks: Vec = account.address.chunks(8).map(Felt252::from_bytes_le_slice).collect(); exec_scopes.insert_value::(vars::scopes::ACCOUNT, account); let address_ptr = get_ptr_from_var_name(vars::ids::ADDRESS, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.write_arg(address_ptr, &address)?; + + vm.write_arg(address_ptr, &address_le_chunks)?; Ok(()) } @@ -176,7 +177,7 @@ pub fn hint_account_proof_bytes_len( insert_value_from_var_name( vars::ids::PROOF_BYTES_LEN, - MaybeRelocatable::Int(Felt252::from(proof.proof_bytes_len)), + MaybeRelocatable::Int(Felt252::from(proof.proof.len())), vm, &hint_data.ids_data, &hint_data.ap_tracking, @@ -193,8 +194,9 @@ pub fn hint_get_mpt_proof( ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + let proof_le_chunks: Vec = proof.proof.chunks(8).map(Felt252::from_bytes_le_slice).collect(); - vm.write_arg(mpt_proof_ptr, &proof.proof)?; + vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; Ok(()) } diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs index 78344374..c775b216 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs @@ -40,12 +40,13 @@ pub fn hint_set_header( .try_into() .unwrap(); let header = batch.headers[idx - 1].clone(); - let rlp = header.rlp.clone(); + let rlp_le_chunks: Vec = header.rlp.chunks(8).map(Felt252::from_bytes_le_slice).collect(); exec_scopes.insert_value::
(vars::scopes::HEADER, header); let rlp_ptr = get_ptr_from_var_name(vars::ids::RLP, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.write_arg(rlp_ptr, &rlp)?; + + vm.write_arg(rlp_ptr, &rlp_le_chunks)?; Ok(()) } diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs index c87b737a..a4c1c4a2 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs @@ -1,5 +1,5 @@ pub mod account_verifier; -pub mod block_tx_verifier; pub mod header_verifier; pub mod receipt_verifier; pub mod storage_item_verifier; +pub mod transaction_verifier; diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs index 5dcb4e53..da2565e5 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs @@ -136,7 +136,7 @@ pub fn hint_receipt_proof_bytes_len( insert_value_from_var_name( vars::ids::PROOF_BYTES_LEN, - MaybeRelocatable::Int(Felt252::from(receipt.proof.proof_bytes_len)), + MaybeRelocatable::Int(Felt252::from(receipt.proof.proof.len())), vm, &hint_data.ids_data, &hint_data.ap_tracking, @@ -152,9 +152,10 @@ pub fn hint_receipt_mpt_proof( _constants: &HashMap, ) -> Result<(), HintError> { let receipt = exec_scopes.get::(vars::scopes::RECEIPT)?; - let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.write_arg(mpt_proof_ptr, &receipt.proof.proof)?; + let proof_le_chunks: Vec = receipt.proof.proof.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + + vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; Ok(()) } diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/storage_item_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/storage_item_verifier.rs index a7e554a7..bba6ef7b 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/storage_item_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/storage_item_verifier.rs @@ -61,10 +61,11 @@ pub fn hint_set_storage_slot( _constants: &HashMap, ) -> Result<(), HintError> { let storage = exec_scopes.get::(vars::scopes::STORAGE)?; - let slot = BigUint::from_str_radix(&storage.slot.to_string(), 16).unwrap(); + let slot_le_chunks: Vec = storage.slot.chunks(8).map(Felt252::from_bytes_le_slice).collect(); let slot_ptr = get_ptr_from_var_name(vars::ids::SLOT, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.insert_value(slot_ptr, &Felt252::from(slot))?; + + vm.write_arg(slot_ptr, &slot_le_chunks)?; Ok(()) } @@ -189,9 +190,9 @@ pub fn hint_set_proof_bytes_len( _constants: &HashMap, ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; - let proof_bytes_len_ptr = get_ptr_from_var_name(vars::ids::PROOF_BYTES_LEN, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.insert_value(proof_bytes_len_ptr, &Felt252::from(proof.proof_bytes_len))?; + + vm.insert_value(proof_bytes_len_ptr, Felt252::from(proof.proof.len()))?; Ok(()) } @@ -205,9 +206,10 @@ pub fn hint_set_mpt_proof( _constants: &HashMap, ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; - let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.write_arg(mpt_proof_ptr, &proof.proof)?; + let proof_le_chunks: Vec = proof.proof.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + + vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; Ok(()) } diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/transaction_verifier.rs similarity index 96% rename from cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs rename to cairo_vm_hints/src/hints/lib/verifiers/evm/transaction_verifier.rs index 4a51ca30..caaf935d 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/block_tx_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/transaction_verifier.rs @@ -136,9 +136,9 @@ pub fn hint_proof_bytes_len( _constants: &HashMap, ) -> Result<(), HintError> { let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; - let proof_bytes_len_ptr = get_ptr_from_var_name(vars::ids::PROOF_BYTES_LEN, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.insert_value(proof_bytes_len_ptr, Felt252::from(transaction.proof.proof_bytes_len))?; + + vm.insert_value(proof_bytes_len_ptr, Felt252::from(transaction.proof.proof.len()))?; Ok(()) } @@ -152,9 +152,10 @@ pub fn hint_mpt_proof( _constants: &HashMap, ) -> Result<(), HintError> { let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; - let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.write_arg(mpt_proof_ptr, &transaction.proof.proof)?; + let proof_le_chunks: Vec = transaction.proof.proof.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + + vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; Ok(()) } From d52ab3999f1b9ace575b7db8ebd0f863590906bb Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 16 Dec 2024 16:20:56 +0100 Subject: [PATCH 35/75] mmr path writearg fix --- .../src/hints/lib/verifiers/evm/header_verifier.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs b/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs index c775b216..4cb4edbc 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs @@ -99,9 +99,10 @@ pub fn hint_mmr_path( _constants: &HashMap, ) -> Result<(), HintError> { let header = exec_scopes.get::
(vars::scopes::HEADER)?; - let mmr_path_ptr = get_ptr_from_var_name(vars::ids::MMR_PATH, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.write_arg(mmr_path_ptr, &header.proof.mmr_path)?; + let mmr_path: Vec = header.proof.mmr_path.into_iter().map(|f| Felt252::from_bytes_be_slice(&f.0)).collect(); + + vm.write_arg(mmr_path_ptr, &mmr_path)?; Ok(()) } From 672ad3f250f3f951098e7322b38e6e2f534b1e35 Mon Sep 17 00:00:00 2001 From: codyx Date: Mon, 16 Dec 2024 20:16:13 +0400 Subject: [PATCH 36/75] Rewrite --- cairo_vm_hints/src/hint_processor/mod.rs | 1 - cairo_vm_hints/src/hints/lib/decoder/evm/has_type_prefix.rs | 2 +- cairo_vm_hints/src/hints/lib/decoder/evm/is_byzantium.rs | 2 +- cairo_vm_hints/src/hints/lib/decoder/evm/v_is_encoded.rs | 2 +- cairo_vm_hints/src/hints/lib/merkle/mod.rs | 4 ++-- cairo_vm_hints/src/hints/lib/rlp/item_type.rs | 4 ++-- cairo_vm_hints/src/hints/lib/verifiers/verify.rs | 2 +- 7 files changed, 8 insertions(+), 9 deletions(-) diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/cairo_vm_hints/src/hint_processor/mod.rs index f2f0a88d..1641612a 100644 --- a/cairo_vm_hints/src/hint_processor/mod.rs +++ b/cairo_vm_hints/src/hint_processor/mod.rs @@ -90,7 +90,6 @@ impl CustomHintProcessor { hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BLOCK_NUMBER.into(), lib::verifiers::evm::account_verifier::hint_account_proof_block_number); hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::account_verifier::hint_account_proof_bytes_len); hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOFS_LEN.into(), lib::verifiers::evm::account_verifier::hint_account_proofs_len); - hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_LEN.into(), lib::verifiers::evm::account_verifier::hint_account_proof_len); hints.insert(lib::verifiers::evm::account_verifier::HINT_BATCH_ACCOUNTS_LEN.into(), lib::verifiers::evm::account_verifier::hint_batch_accounts_len); hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_ACCOUNT_ADDRESS.into(), lib::verifiers::evm::account_verifier::hint_get_account_address); hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), lib::verifiers::evm::account_verifier::hint_get_mpt_proof); diff --git a/cairo_vm_hints/src/hints/lib/decoder/evm/has_type_prefix.rs b/cairo_vm_hints/src/hints/lib/decoder/evm/has_type_prefix.rs index 415ad5d6..e60992c7 100644 --- a/cairo_vm_hints/src/hints/lib/decoder/evm/has_type_prefix.rs +++ b/cairo_vm_hints/src/hints/lib/decoder/evm/has_type_prefix.rs @@ -11,7 +11,7 @@ use std::collections::HashMap; const FELT_4: Felt252 = Felt252::from_hex_unchecked("0x04"); -pub const HINT_HAS_TYPE_PREFIX: &str = "ids.has_type_prefix = 1 if 0x0 < ids.first_byte < 0x04 else 0"; +pub const HINT_HAS_TYPE_PREFIX: &str = "# typed transactions have a type prefix in this range [1, 3]\nif 0x0 < ids.first_byte < 0x04:\n ids.has_type_prefix = 1\nelse:\n ids.has_type_prefix = 0"; pub fn hint_has_type_prefix( vm: &mut VirtualMachine, diff --git a/cairo_vm_hints/src/hints/lib/decoder/evm/is_byzantium.rs b/cairo_vm_hints/src/hints/lib/decoder/evm/is_byzantium.rs index d72e867d..945513de 100644 --- a/cairo_vm_hints/src/hints/lib/decoder/evm/is_byzantium.rs +++ b/cairo_vm_hints/src/hints/lib/decoder/evm/is_byzantium.rs @@ -11,7 +11,7 @@ use std::{cmp::Ordering, collections::HashMap}; const BYZANTIUM_START_BLOCK_NUMBER: Felt252 = Felt252::from_hex_unchecked("0x42AE50"); -pub const HINT_IS_BYZANTIUM: &str = "ids.is_byzantium = 1 if ids.block_number >= ids.chain_info.byzantium else 0"; +pub const HINT_IS_BYZANTIUM: &str = "if ids.block_number >= ids.chain_info.byzantium:\n ids.is_byzantium = 1\nelse:\n ids.is_byzantium = 0"; pub fn hint_is_byzantium( vm: &mut VirtualMachine, diff --git a/cairo_vm_hints/src/hints/lib/decoder/evm/v_is_encoded.rs b/cairo_vm_hints/src/hints/lib/decoder/evm/v_is_encoded.rs index b02b80fa..8e8cc4ea 100644 --- a/cairo_vm_hints/src/hints/lib/decoder/evm/v_is_encoded.rs +++ b/cairo_vm_hints/src/hints/lib/decoder/evm/v_is_encoded.rs @@ -11,7 +11,7 @@ use std::{cmp::Ordering, collections::HashMap}; const FELT_127: Felt252 = Felt252::from_hex_unchecked("0x7f"); -pub const HINT_V_IS_ENCODED: &str = "ids.v_is_encoded = 1 if ids.v.low > 0x7f else 0"; +pub const HINT_V_IS_ENCODED: &str = "if ids.v.low <= 0x7f:\n ids.v_is_encoded = 0\nelse:\n ids.v_is_encoded = 1"; pub fn hint_v_is_encoded( vm: &mut VirtualMachine, diff --git a/cairo_vm_hints/src/hints/lib/merkle/mod.rs b/cairo_vm_hints/src/hints/lib/merkle/mod.rs index 465286a6..f907e2fe 100644 --- a/cairo_vm_hints/src/hints/lib/merkle/mod.rs +++ b/cairo_vm_hints/src/hints/lib/merkle/mod.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; const FELT_TWO_POW_128: Felt252 = Felt252::from_hex_unchecked("0x0100000000000000000000000000000000"); pub const HINT_TARGET_TASK_HASH: &str = - "target_task_hash = hex(ids.task_hash.low + ids.task_hash.high*2**128)[2:] print(f\"Task Hash: 0x{target_task_hash}\")"; + "target_task_hash = hex(ids.task_hash.low + ids.task_hash.high*2**128)[2:]\nprint(f\"Task Hash: 0x{target_task_hash}\")"; pub fn hint_target_task_hash( vm: &mut VirtualMachine, @@ -39,7 +39,7 @@ pub fn hint_target_task_hash( } pub const HINT_IS_LEFT_SMALLER: &str = - "def flip_endianess(val): val_hex = hex(val)[2:] if len(val_hex) % 2: val_hex = '0' + val_hex # Convert hex string to bytes byte_data = bytes.fromhex(val_hex) num = int.from_bytes(byte_data, byteorder=\"little\") return num # In LE Uint256, the low and high are reversed left = flip_endianess(ids.left.low) * 2**128 + flip_endianess(ids.left.high) right = flip_endianess(ids.right.low) * 2**128 + flip_endianess(ids.right.high) # Compare the values to derive correct hashing order if left < right: ids.is_left_smaller = 1 #print(f\"H({hex(left)}, {hex(right)}\") else: #print(f\"H({hex(right)}, {hex(left)}\") ids.is_left_smaller = 0"; + "def flip_endianess(val):\n val_hex = hex(val)[2:]\n\n if len(val_hex) % 2:\n val_hex = '0' + val_hex\n\n # Convert hex string to bytes\n byte_data = bytes.fromhex(val_hex)\n num = int.from_bytes(byte_data, byteorder=\"little\")\n\n return num\n\n# In LE Uint256, the low and high are reversed\nleft = flip_endianess(ids.left.low) * 2**128 + flip_endianess(ids.left.high)\nright = flip_endianess(ids.right.low) * 2**128 + flip_endianess(ids.right.high)\n\n# Compare the values to derive correct hashing order\nif left < right:\n ids.is_left_smaller = 1\n #print(f\"H({hex(left)}, {hex(right)})\")\nelse:\n #print(f\"H({hex(right)}, {hex(left)})\")\n ids.is_left_smaller = 0"; pub fn hint_is_left_smaller( vm: &mut VirtualMachine, diff --git a/cairo_vm_hints/src/hints/lib/rlp/item_type.rs b/cairo_vm_hints/src/hints/lib/rlp/item_type.rs index cb1425cb..329be85f 100644 --- a/cairo_vm_hints/src/hints/lib/rlp/item_type.rs +++ b/cairo_vm_hints/src/hints/lib/rlp/item_type.rs @@ -13,7 +13,7 @@ use cairo_vm::{ use std::collections::HashMap; pub const HINT_IS_LONG: &str = - "ids.is_long = 0 if 0xc0 <= ids.first_byte <= 0xf6 else 1 if 0xf7 <= ids.first_byte <= 0xff else assert False, 'Invalid RLP list'"; + "if 0xc0 <= ids.first_byte <= 0xf6:\n ids.is_long = 0 # short list\nelif 0xf7 <= ids.first_byte <= 0xff:\n ids.is_long = 1 # long list\nelse:\n assert False, \"Invalid RLP list\""; pub fn hint_is_long( vm: &mut VirtualMachine, @@ -40,7 +40,7 @@ pub fn hint_is_long( ) } -pub const HINT_ITEM_TYPE: &str = "ids.item_type = 0 if ids.current_item <= 0x7f else 1 if 0x80 <= ids.current_item <= 0xb6 else 2 if 0xb7 <= ids.current_item <= 0xbf else 3 if 0xc0 <= ids.current_item <= 0xf6 else 4 if 0xf7 <= ids.current_item <= 0xff else assert False, 'Invalid RLP item'"; +pub const HINT_ITEM_TYPE: &str = "if ids.current_item <= 0x7f:\n ids.item_type = 0 # single byte\nelif 0x80 <= ids.current_item <= 0xb6:\n ids.item_type = 1 # short string\nelif 0xb7 <= ids.current_item <= 0xbf:\n ids.item_type = 2 # long string\nelif 0xc0 <= ids.current_item <= 0xf6:\n ids.item_type = 3 # short list\nelif 0xf7 <= ids.current_item <= 0xff:\n ids.item_type = 4 # long list\nelse:\n assert False, \"Invalid RLP item\""; pub fn hint_item_type( vm: &mut VirtualMachine, diff --git a/cairo_vm_hints/src/hints/lib/verifiers/verify.rs b/cairo_vm_hints/src/hints/lib/verifiers/verify.rs index ce1c6d16..b0737466 100644 --- a/cairo_vm_hints/src/hints/lib/verifiers/verify.rs +++ b/cairo_vm_hints/src/hints/lib/verifiers/verify.rs @@ -13,7 +13,7 @@ use std::{any::Any, collections::HashMap}; use crate::{hint_processor::models::proofs::Proofs, hints::vars}; -pub const HINT_BATCH_LEN: &str = "ids.batch_len = len(ids.proofs)"; +pub const HINT_BATCH_LEN: &str = "ids.batch_len = len(proofs)"; pub fn hint_batch_len( vm: &mut VirtualMachine, From 53bb878036c04ab1baab3be11572e896bda184c0 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 16 Dec 2024 19:23:35 +0100 Subject: [PATCH 37/75] crates reorg (major) --- Cargo.lock | 45 ++++++++++++-- Cargo.toml | 14 ++++- cairo_vm_hints/src/hints/vars.rs | 60 ------------------- crates/cairo_types/Cargo.toml | 14 +++++ .../cairo_types/src}/evm/account.rs | 16 +---- .../cairo_types/src}/evm/header.rs | 16 +---- .../cairo_types/src}/evm/mod.rs | 0 .../cairo_types/src}/evm/receipt.rs | 2 +- .../cairo_types/src}/evm/storage.rs | 16 +---- .../cairo_types/src}/evm/transaction.rs | 2 +- .../mod.rs => crates/cairo_types/src/lib.rs | 10 ++-- .../cairo_types/src}/new_syscalls.rs | 0 .../cairo_types/src}/starknet/mod.rs | 0 .../cairo_types/src}/structs.rs | 2 +- .../cairo_types/src}/traits.rs | 0 crates/dry_run/Cargo.toml | 11 ++++ {cairo_vm_hints => crates/dry_run}/src/lib.rs | 15 +---- .../dry_run}/src/main.rs | 28 ++++----- .../hdp_hint_processor}/Cargo.toml | 12 ++-- .../src/hint_processor/dry_run_input.rs | 0 .../src/hint_processor/mod.rs | 0 .../src/hint_processor/models/mod.rs | 0 .../src/hint_processor/models/param.rs | 0 .../hint_processor/models/proofs/account.rs | 0 .../hint_processor/models/proofs/header.rs | 0 .../src/hint_processor/models/proofs/mmr.rs | 0 .../src/hint_processor/models/proofs/mod.rs | 0 .../src/hint_processor/models/proofs/mpt.rs | 0 .../hint_processor/models/proofs/receipt.rs | 0 .../hint_processor/models/proofs/storage.rs | 0 .../models/proofs/transaction.rs | 0 .../src/hint_processor/output.rs | 0 .../src/hint_processor/run_input.rs | 0 .../hints/lib/contract_bootloader/builtins.rs | 3 +- .../lib/contract_bootloader/contract_class.rs | 0 .../lib/contract_bootloader/dict_manager.rs | 0 .../src/hints/lib/contract_bootloader/mod.rs | 0 .../hints/lib/contract_bootloader/params.rs | 0 .../hints/lib/contract_bootloader/program.rs | 3 +- .../hints/lib/contract_bootloader/scopes.rs | 0 .../contract_bootloader/syscall_handler.rs | 0 .../hints/lib/decoder/evm/has_type_prefix.rs | 0 .../src/hints/lib/decoder/evm/is_byzantium.rs | 0 .../src/hints/lib/decoder/evm/mod.rs | 0 .../src/hints/lib/decoder/evm/v_is_encoded.rs | 0 .../src/hints/lib/decoder/mod.rs | 0 .../src/hints/lib/merkle/mod.rs | 0 .../hdp_hint_processor}/src/hints/lib/mod.rs | 0 .../src/hints/lib/print.rs | 0 .../src/hints/lib/rlp/divmod.rs | 0 .../src/hints/lib/rlp/item_type.rs | 0 .../src/hints/lib/rlp/mod.rs | 0 .../src/hints/lib/rlp/processed_words.rs | 0 .../src/hints/lib/segments.rs | 0 .../src/hints/lib/utils/mod.rs | 0 .../lib/verifiers/evm/account_verifier.rs | 0 .../lib/verifiers/evm/header_verifier.rs | 0 .../src/hints/lib/verifiers/evm/mod.rs | 0 .../lib/verifiers/evm/receipt_verifier.rs | 0 .../verifiers/evm/storage_item_verifier.rs | 0 .../lib/verifiers/evm/transaction_verifier.rs | 0 .../src/hints/lib/verifiers/mod.rs | 0 .../src/hints/lib/verifiers/utils.rs | 0 .../src/hints/lib/verifiers/verify.rs | 0 .../hdp_hint_processor}/src/hints/mod.rs | 0 crates/hdp_hint_processor/src/hints/vars.rs | 60 +++++++++++++++++++ crates/hdp_hint_processor/src/lib.rs | 8 +++ .../src/syscall_handler/evm/dryrun/account.rs | 23 ++++--- .../src/syscall_handler/evm/dryrun/header.rs | 23 ++++--- .../src/syscall_handler/evm/dryrun/mod.rs | 8 +-- .../src/syscall_handler/evm/dryrun/receipt.rs | 0 .../src/syscall_handler/evm/dryrun/storage.rs | 23 ++++--- .../syscall_handler/evm/dryrun/transaction.rs | 0 .../src/syscall_handler/evm/mod.rs | 0 .../src/syscall_handler/evm/soundrun}/mod.rs | 0 .../src/syscall_handler/keys/account.rs | 2 +- .../src/syscall_handler/keys/header.rs | 10 ++-- .../src/syscall_handler/keys/mod.rs | 0 .../src/syscall_handler/keys/receipt.rs | 0 .../src/syscall_handler/keys/storage.rs | 2 +- .../src/syscall_handler/keys/transaction.rs | 0 .../src/syscall_handler/mod.rs | 0 .../syscall_handler/starknet/dryrun}/mod.rs | 0 .../src/syscall_handler/starknet/mod.rs | 0 .../syscall_handler/starknet}/soundrun/mod.rs | 0 .../src/syscall_handler/traits.rs | 2 +- .../src/syscall_handler/utils.rs | 0 .../hdp_hint_processor}/src/tests/mod.rs | 2 +- crates/provider/Cargo.toml | 13 ++++ .../dryrun => crates/provider/src/evm}/mod.rs | 0 .../provider/src}/indexer/mod.rs | 0 .../provider/src}/indexer/types.rs | 0 .../mod.rs => crates/provider/src/lib.rs | 0 .../provider/src/starknet}/mod.rs | 0 94 files changed, 249 insertions(+), 196 deletions(-) delete mode 100644 cairo_vm_hints/src/hints/vars.rs create mode 100644 crates/cairo_types/Cargo.toml rename {cairo_vm_hints/src/cairo_types => crates/cairo_types/src}/evm/account.rs (73%) rename {cairo_vm_hints/src/cairo_types => crates/cairo_types/src}/evm/header.rs (87%) rename {cairo_vm_hints/src/cairo_types => crates/cairo_types/src}/evm/mod.rs (100%) rename {cairo_vm_hints/src/cairo_types => crates/cairo_types/src}/evm/receipt.rs (95%) rename {cairo_vm_hints/src/cairo_types => crates/cairo_types/src}/evm/storage.rs (65%) rename {cairo_vm_hints/src/cairo_types => crates/cairo_types/src}/evm/transaction.rs (95%) rename cairo_vm_hints/src/cairo_types/mod.rs => crates/cairo_types/src/lib.rs (92%) rename {cairo_vm_hints/src/cairo_types => crates/cairo_types/src}/new_syscalls.rs (100%) rename {cairo_vm_hints/src/cairo_types => crates/cairo_types/src}/starknet/mod.rs (100%) rename {cairo_vm_hints/src/cairo_types => crates/cairo_types/src}/structs.rs (97%) rename {cairo_vm_hints/src/cairo_types => crates/cairo_types/src}/traits.rs (100%) create mode 100644 crates/dry_run/Cargo.toml rename {cairo_vm_hints => crates/dry_run}/src/lib.rs (59%) rename {cairo_vm_hints => crates/dry_run}/src/main.rs (83%) rename {cairo_vm_hints => crates/hdp_hint_processor}/Cargo.toml (83%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/dry_run_input.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/models/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/models/param.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/models/proofs/account.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/models/proofs/header.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/models/proofs/mmr.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/models/proofs/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/models/proofs/mpt.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/models/proofs/receipt.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/models/proofs/storage.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/models/proofs/transaction.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/output.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hint_processor/run_input.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/contract_bootloader/builtins.rs (98%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/contract_bootloader/contract_class.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/contract_bootloader/dict_manager.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/contract_bootloader/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/contract_bootloader/params.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/contract_bootloader/program.rs (95%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/contract_bootloader/scopes.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/contract_bootloader/syscall_handler.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/decoder/evm/has_type_prefix.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/decoder/evm/is_byzantium.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/decoder/evm/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/decoder/evm/v_is_encoded.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/decoder/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/merkle/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/print.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/rlp/divmod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/rlp/item_type.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/rlp/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/rlp/processed_words.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/segments.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/utils/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/verifiers/evm/account_verifier.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/verifiers/evm/header_verifier.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/verifiers/evm/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/verifiers/evm/receipt_verifier.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/verifiers/evm/storage_item_verifier.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/verifiers/evm/transaction_verifier.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/verifiers/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/verifiers/utils.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/lib/verifiers/verify.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/hints/mod.rs (100%) create mode 100644 crates/hdp_hint_processor/src/hints/vars.rs create mode 100644 crates/hdp_hint_processor/src/lib.rs rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/evm/dryrun/account.rs (71%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/evm/dryrun/header.rs (72%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/evm/dryrun/mod.rs (96%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/evm/dryrun/receipt.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/evm/dryrun/storage.rs (72%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/evm/dryrun/transaction.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/evm/mod.rs (100%) rename {cairo_vm_hints/src/provider/evm => crates/hdp_hint_processor/src/syscall_handler/evm/soundrun}/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/keys/account.rs (98%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/keys/header.rs (97%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/keys/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/keys/receipt.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/keys/storage.rs (99%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/keys/transaction.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/mod.rs (100%) rename {cairo_vm_hints/src/provider/starknet => crates/hdp_hint_processor/src/syscall_handler/starknet/dryrun}/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/starknet/mod.rs (100%) rename {cairo_vm_hints/src/syscall_handler/evm => crates/hdp_hint_processor/src/syscall_handler/starknet}/soundrun/mod.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/traits.rs (95%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/syscall_handler/utils.rs (100%) rename {cairo_vm_hints => crates/hdp_hint_processor}/src/tests/mod.rs (91%) create mode 100644 crates/provider/Cargo.toml rename {cairo_vm_hints/src/syscall_handler/starknet/dryrun => crates/provider/src/evm}/mod.rs (100%) rename {cairo_vm_hints/src/provider => crates/provider/src}/indexer/mod.rs (100%) rename {cairo_vm_hints/src/provider => crates/provider/src}/indexer/types.rs (100%) rename cairo_vm_hints/src/provider/mod.rs => crates/provider/src/lib.rs (100%) rename {cairo_vm_hints/src/syscall_handler/starknet/soundrun => crates/provider/src/starknet}/mod.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index ce9afa9d..28b48a7a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1632,6 +1632,20 @@ dependencies = [ "zip", ] +[[package]] +name = "cairo_types" +version = "0.1.0" +dependencies = [ + "alloy", + "alloy-rlp", + "cairo-lang-casm", + "cairo-lang-starknet-classes", + "cairo-type-derive", + "cairo-vm", + "starknet-crypto 0.7.3", + "strum_macros", +] + [[package]] name = "cc" version = "1.2.2" @@ -2038,6 +2052,17 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aac81fa3e28d21450aa4d2ac065992ba96a1d7303efbce51a95f4fd175b67562" +[[package]] +name = "dry_run" +version = "0.1.0" +dependencies = [ + "cairo-vm", + "clap", + "hdp_hint_processor", + "serde_json", + "thiserror 1.0.69", +] + [[package]] name = "dunce" version = "1.0.5" @@ -2462,7 +2487,7 @@ dependencies = [ ] [[package]] -name = "hdp_cairo_vm_hints" +name = "hdp_hint_processor" version = "0.1.0" dependencies = [ "alloy", @@ -2472,22 +2497,21 @@ dependencies = [ "cairo-lang-starknet-classes", "cairo-type-derive", "cairo-vm", - "clap", + "cairo_types", "hex", "num-bigint", "num-traits", + "provider", "rand", "reqwest", "serde", "serde_json", "serde_with 3.11.0", - "sha3", "starknet-core", "starknet-crypto 0.7.3", "starknet-types-core", "strum_macros", "thiserror 1.0.69", - "tiny-keccak", "tokio", ] @@ -3699,6 +3723,19 @@ dependencies = [ "unarray", ] +[[package]] +name = "provider" +version = "0.1.0" +dependencies = [ + "alloy", + "reqwest", + "serde", + "serde_json", + "serde_with 3.11.0", + "thiserror 1.0.69", + "tokio", +] + [[package]] name = "quick-error" version = "1.2.3" diff --git a/Cargo.toml b/Cargo.toml index b4ebdbc7..74e6ebf3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,8 +1,12 @@ [workspace] resolver = "2" -members = ["cairo_vm_hints"] - +members = [ + "crates/hdp_hint_processor", + "crates/provider", + "crates/cairo_types", + "crates/dry_run" +] [workspace.dependencies] alloy = { version = "0.7.2", features = ["full"] } @@ -28,4 +32,8 @@ serde_with = { version = "3.11.0", features = ["hex"] } starknet-core = { version = "0.11.1", default-features = false } starknet-crypto = { version = "0.7.1", default-features = false } starknet-types-core = { version = "0.1.5", default-features = false } -reqwest = "0.12.9" \ No newline at end of file +reqwest = "0.12.9" + +hdp_hint_processor = { path = "crates/hdp_hint_processor" } +provider = { path = "crates/provider" } +cairo_types = { path = "crates/cairo_types" } diff --git a/cairo_vm_hints/src/hints/vars.rs b/cairo_vm_hints/src/hints/vars.rs deleted file mode 100644 index 0a8c9ac9..00000000 --- a/cairo_vm_hints/src/hints/vars.rs +++ /dev/null @@ -1,60 +0,0 @@ -pub mod scopes { - pub(crate) const ACCOUNT: &str = "account"; - pub(crate) const BATCH: &str = "batch"; - pub(crate) const COMPILED_CLASS: &str = "compiled_class"; - pub(crate) const DICT_MANAGER: &str = "dict_manager"; - pub(crate) const HEADER: &str = "header"; - pub(crate) const N_SELECTED_BUILTINS: &str = "n_selected_builtins"; - pub(crate) const PARAMS: &str = "params"; - pub(crate) const PROOF: &str = "proof"; - pub(crate) const PROOFS: &str = "proofs"; - pub(crate) const RECEIPT: &str = "receipt"; - pub(crate) const STORAGE: &str = "storage"; - pub(crate) const SYSCALL_HANDLER: &str = "syscall_handler"; - pub(crate) const TRANSACTION: &str = "transaction"; -} - -pub mod ids { - pub(crate) const ADDRESS: &str = "ids.address"; - pub(crate) const ALL_ENCODINGS: &str = "all_encodings"; - pub(crate) const BATCH_LEN: &str = "batch_len"; - pub(crate) const BUILTIN_PARAMS: &str = "builtin_params"; - pub(crate) const BUILTIN_PTRS: &str = "builtin_ptrs"; - pub(crate) const CHAIN_ID: &str = "chain_id"; - pub(crate) const COMPILED_CLASS: &str = "compiled_class"; - pub(crate) const CURRENT_ITEM: &str = "ids.current_item"; - pub(crate) const DEVISOR: &str = "ids.devisor"; - pub(crate) const FIRST_BYTE: &str = "ids.first_byte"; - pub(crate) const I: &str = "ids.i"; - pub(crate) const IDX: &str = "ids.idx"; - pub(crate) const IS_LEFT_SMALLER: &str = "ids.is_left_smaller"; - pub(crate) const IS_LONG: &str = "ids.is_long"; - pub(crate) const ITEM_TYPE: &str = "ids.item_type"; - pub(crate) const KEY_LOW: &str = "ids.key_low"; - pub(crate) const KEY_LEADING_ZEROS: &str = "ids.key_leading_zeros"; - pub(crate) const KEY_HIGH: &str = "ids.key_high"; - pub(crate) const LEFT: &str = "ids.left"; - pub(crate) const MMR_PATH: &str = "ids.mmr_path"; - pub(crate) const MPT_PROOF: &str = "ids.mpt_proof"; - pub(crate) const PROOF_BYTES_LEN: &str = "ids.proof_bytes_len"; - pub(crate) const N_BUILTINS: &str = "n_builtins"; - pub(crate) const N_PROCESSED_WORDS: &str = "ids.n_processed_words"; - pub(crate) const N_SELECTED_BUILTINS: &str = "n_selected_builtins"; - pub(crate) const PARAMS_LEN: &str = "params_len"; - pub(crate) const PARAMS: &str = "params"; - pub(crate) const PROGRAM_HASH: &str = "program_hash"; - pub(crate) const Q: &str = "ids.q"; - pub(crate) const R: &str = "ids.r"; - pub(crate) const RESULT: &str = "result"; - pub(crate) const RETURN_BUILTIN_PTRS: &str = "return_builtin_ptrs"; - pub(crate) const RIGHT: &str = "ids.right"; - pub(crate) const RLP: &str = "ids.rlp"; - pub(crate) const SELECT_BUILTIN: &str = "select_builtin"; - pub(crate) const SELECTED_ENCODINGS: &str = "selected_encodings"; - pub(crate) const SELECTED_PTRS: &str = "selected_ptrs"; - pub(crate) const SLOT: &str = "ids.slot"; - pub(crate) const SYSCALL_PTR: &str = "syscall_ptr"; - pub(crate) const TASK_HASH: &str = "ids.task_hash"; - pub(crate) const VALUE_LEN: &str = "ids.value_len"; - pub(crate) const VALUE: &str = "ids.value"; -} diff --git a/crates/cairo_types/Cargo.toml b/crates/cairo_types/Cargo.toml new file mode 100644 index 00000000..a10cd48d --- /dev/null +++ b/crates/cairo_types/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "cairo_types" +version = "0.1.0" +edition = "2021" + +[dependencies] +alloy.workspace = true +cairo-vm.workspace = true +starknet-crypto.workspace = true +cairo-lang-casm.workspace = true +cairo-lang-starknet-classes.workspace = true +cairo-type-derive.workspace = true +alloy-rlp.workspace = true +strum_macros.workspace = true \ No newline at end of file diff --git a/cairo_vm_hints/src/cairo_types/evm/account.rs b/crates/cairo_types/src/evm/account.rs similarity index 73% rename from cairo_vm_hints/src/cairo_types/evm/account.rs rename to crates/cairo_types/src/evm/account.rs index b7aa5bd3..08574e0d 100644 --- a/cairo_vm_hints/src/cairo_types/evm/account.rs +++ b/crates/cairo_types/src/evm/account.rs @@ -1,4 +1,4 @@ -use crate::{cairo_types::structs::Uint256, syscall_handler::utils::SyscallExecutionError}; +use crate::structs::Uint256; use alloy::{consensus::Account, primitives::keccak256, rpc::types::EIP1186AccountProofResponse}; use alloy_rlp::{Decodable, Encodable}; use cairo_vm::Felt252; @@ -64,17 +64,3 @@ impl From for CairoAccount { Self(value) } } - -impl TryFrom for FunctionId { - type Error = SyscallExecutionError; - fn try_from(value: Felt252) -> Result { - Self::from_repr(value.try_into().map_err(|e| Self::Error::InvalidSyscallInput { - input: value, - info: format!("{}", e), - })?) - .ok_or(Self::Error::InvalidSyscallInput { - input: value, - info: "Invalid function identifier".to_string(), - }) - } -} diff --git a/cairo_vm_hints/src/cairo_types/evm/header.rs b/crates/cairo_types/src/evm/header.rs similarity index 87% rename from cairo_vm_hints/src/cairo_types/evm/header.rs rename to crates/cairo_types/src/evm/header.rs index 64abddca..af6261e1 100644 --- a/cairo_vm_hints/src/cairo_types/evm/header.rs +++ b/crates/cairo_types/src/evm/header.rs @@ -1,4 +1,4 @@ -use crate::{cairo_types::structs::Uint256, syscall_handler::utils::SyscallExecutionError}; +use crate::structs::Uint256; use alloy::{ consensus::Header, primitives::{keccak256, Bloom, Bytes}, @@ -157,17 +157,3 @@ impl From
for CairoHeader { Self(value) } } - -impl TryFrom for FunctionId { - type Error = SyscallExecutionError; - fn try_from(value: Felt252) -> Result { - Self::from_repr(value.try_into().map_err(|e| Self::Error::InvalidSyscallInput { - input: value, - info: format!("{}", e), - })?) - .ok_or(Self::Error::InvalidSyscallInput { - input: value, - info: "Invalid function identifier".to_string(), - }) - } -} diff --git a/cairo_vm_hints/src/cairo_types/evm/mod.rs b/crates/cairo_types/src/evm/mod.rs similarity index 100% rename from cairo_vm_hints/src/cairo_types/evm/mod.rs rename to crates/cairo_types/src/evm/mod.rs diff --git a/cairo_vm_hints/src/cairo_types/evm/receipt.rs b/crates/cairo_types/src/evm/receipt.rs similarity index 95% rename from cairo_vm_hints/src/cairo_types/evm/receipt.rs rename to crates/cairo_types/src/evm/receipt.rs index e0dfb2d9..c3bcb784 100644 --- a/cairo_vm_hints/src/cairo_types/evm/receipt.rs +++ b/crates/cairo_types/src/evm/receipt.rs @@ -1,4 +1,4 @@ -use crate::cairo_types::structs::Uint256; +use crate::structs::Uint256; use alloy::{ consensus::{ReceiptWithBloom, RlpEncodableReceipt, TxReceipt}, primitives::keccak256, diff --git a/cairo_vm_hints/src/cairo_types/evm/storage.rs b/crates/cairo_types/src/evm/storage.rs similarity index 65% rename from cairo_vm_hints/src/cairo_types/evm/storage.rs rename to crates/cairo_types/src/evm/storage.rs index 3d48547a..2ad0626f 100644 --- a/cairo_vm_hints/src/cairo_types/evm/storage.rs +++ b/crates/cairo_types/src/evm/storage.rs @@ -1,4 +1,4 @@ -use crate::{cairo_types::structs::Uint256, syscall_handler::utils::SyscallExecutionError}; +use crate::structs::Uint256; use alloy::primitives::{keccak256, StorageValue}; use alloy_rlp::{Decodable, Encodable}; use cairo_vm::Felt252; @@ -46,17 +46,3 @@ impl From for CairoStorage { Self(value) } } - -impl TryFrom for FunctionId { - type Error = SyscallExecutionError; - fn try_from(value: Felt252) -> Result { - Self::from_repr(value.try_into().map_err(|e| Self::Error::InvalidSyscallInput { - input: value, - info: format!("{}", e), - })?) - .ok_or(Self::Error::InvalidSyscallInput { - input: value, - info: "Invalid function identifier".to_string(), - }) - } -} diff --git a/cairo_vm_hints/src/cairo_types/evm/transaction.rs b/crates/cairo_types/src/evm/transaction.rs similarity index 95% rename from cairo_vm_hints/src/cairo_types/evm/transaction.rs rename to crates/cairo_types/src/evm/transaction.rs index be193d2b..7659acf3 100644 --- a/cairo_vm_hints/src/cairo_types/evm/transaction.rs +++ b/crates/cairo_types/src/evm/transaction.rs @@ -1,4 +1,4 @@ -use crate::cairo_types::structs::Uint256; +use crate::structs::Uint256; use alloy::{consensus::transaction::TxEnvelope, rpc::types::Transaction}; use alloy_rlp::{Decodable, Encodable}; diff --git a/cairo_vm_hints/src/cairo_types/mod.rs b/crates/cairo_types/src/lib.rs similarity index 92% rename from cairo_vm_hints/src/cairo_types/mod.rs rename to crates/cairo_types/src/lib.rs index 4c7ce4b8..7882b93c 100644 --- a/cairo_vm_hints/src/cairo_types/mod.rs +++ b/crates/cairo_types/src/lib.rs @@ -1,11 +1,11 @@ use cairo_vm::Felt252; use starknet_crypto::Felt; -pub(crate) mod evm; -pub(crate) mod new_syscalls; -pub(crate) mod starknet; -pub(crate) mod structs; -pub(crate) mod traits; +pub mod evm; +pub mod new_syscalls; +pub mod starknet; +pub mod structs; +pub mod traits; pub const FELT_0: Felt = Felt252::from_hex_unchecked("0x00"); pub const FELT_1: Felt252 = Felt252::from_hex_unchecked("0x01"); diff --git a/cairo_vm_hints/src/cairo_types/new_syscalls.rs b/crates/cairo_types/src/new_syscalls.rs similarity index 100% rename from cairo_vm_hints/src/cairo_types/new_syscalls.rs rename to crates/cairo_types/src/new_syscalls.rs diff --git a/cairo_vm_hints/src/cairo_types/starknet/mod.rs b/crates/cairo_types/src/starknet/mod.rs similarity index 100% rename from cairo_vm_hints/src/cairo_types/starknet/mod.rs rename to crates/cairo_types/src/starknet/mod.rs diff --git a/cairo_vm_hints/src/cairo_types/structs.rs b/crates/cairo_types/src/structs.rs similarity index 97% rename from cairo_vm_hints/src/cairo_types/structs.rs rename to crates/cairo_types/src/structs.rs index e18f20b9..c8534ae2 100644 --- a/cairo_vm_hints/src/cairo_types/structs.rs +++ b/crates/cairo_types/src/structs.rs @@ -1,4 +1,4 @@ -use crate::cairo_types::traits::CairoType; +use crate::traits::CairoType; use alloy::primitives::{Address, B256, B64, U256}; use cairo_type_derive::{CairoType, FieldOffsetGetters}; use cairo_vm::{ diff --git a/cairo_vm_hints/src/cairo_types/traits.rs b/crates/cairo_types/src/traits.rs similarity index 100% rename from cairo_vm_hints/src/cairo_types/traits.rs rename to crates/cairo_types/src/traits.rs diff --git a/crates/dry_run/Cargo.toml b/crates/dry_run/Cargo.toml new file mode 100644 index 00000000..0b14a736 --- /dev/null +++ b/crates/dry_run/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "dry_run" +version = "0.1.0" +edition = "2021" + +[dependencies] +hdp_hint_processor.workspace = true +cairo-vm.workspace = true +clap.workspace = true +thiserror.workspace = true +serde_json.workspace = true \ No newline at end of file diff --git a/cairo_vm_hints/src/lib.rs b/crates/dry_run/src/lib.rs similarity index 59% rename from cairo_vm_hints/src/lib.rs rename to crates/dry_run/src/lib.rs index 08d1386e..5f977d5f 100644 --- a/cairo_vm_hints/src/lib.rs +++ b/crates/dry_run/src/lib.rs @@ -1,15 +1,7 @@ -#![forbid(unsafe_code)] -#![allow(async_fn_in_trait)] -pub mod cairo_types; -pub mod hint_processor; -pub mod hints; -pub mod provider; -pub mod syscall_handler; - use cairo_vm::vm::errors::cairo_run_errors::CairoRunError; -pub use hint_processor::CustomHintProcessor; +use thiserror::Error; -#[derive(thiserror::Error, Debug)] +#[derive(Error, Debug)] pub enum HdpOsError { #[error(transparent)] Args(#[from] clap::error::Error), @@ -22,6 +14,3 @@ pub enum HdpOsError { #[error(transparent)] SerdeJson(#[from] serde_json::Error), } - -#[cfg(test)] -pub mod tests; diff --git a/cairo_vm_hints/src/main.rs b/crates/dry_run/src/main.rs similarity index 83% rename from cairo_vm_hints/src/main.rs rename to crates/dry_run/src/main.rs index 1ebb59d9..26b27958 100644 --- a/cairo_vm_hints/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -1,22 +1,20 @@ #![forbid(unsafe_code)] #![allow(async_fn_in_trait)] -pub mod cairo_types; -pub mod hint_processor; -pub mod hints; -pub mod provider; -pub mod syscall_handler; +use std::{fs, path::PathBuf}; -use cairo_vm::cairo_run::CairoRunConfig; -use cairo_vm::types::layout_name::LayoutName; -use cairo_vm::types::program::Program; -use cairo_vm::vm::errors::vm_exception::VmException; -use cairo_vm::vm::runners::cairo_runner::CairoRunner; +use cairo_vm::{ + cairo_run::CairoRunConfig, + types::{layout_name::LayoutName, program::Program}, + vm::{errors::vm_exception::VmException, runners::cairo_runner::CairoRunner}, +}; use clap::{Parser, ValueHint}; -use hdp_cairo_vm_hints::HdpOsError; -use hint_processor::CustomHintProcessor; -use hints::vars; -use std::{fs, path::PathBuf}; -use syscall_handler::evm::dryrun::{SyscallHandler, SyscallHandlerWrapper}; +use dry_run::HdpOsError; +use hdp_hint_processor::{ + self, + hint_processor::CustomHintProcessor, + hints::vars, + syscall_handler::evm::dryrun::{SyscallHandler, SyscallHandlerWrapper}, +}; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] diff --git a/cairo_vm_hints/Cargo.toml b/crates/hdp_hint_processor/Cargo.toml similarity index 83% rename from cairo_vm_hints/Cargo.toml rename to crates/hdp_hint_processor/Cargo.toml index 4b8794ec..25bcb7e2 100644 --- a/cairo_vm_hints/Cargo.toml +++ b/crates/hdp_hint_processor/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "hdp_cairo_vm_hints" +name = "hdp_hint_processor" version = "0.1.0" edition = "2021" @@ -11,20 +11,20 @@ cairo-lang-casm.workspace = true cairo-lang-starknet-classes.workspace = true cairo-type-derive.workspace = true cairo-vm.workspace = true -clap.workspace = true hex.workspace = true num-bigint.workspace = true num-traits.workspace = true rand.workspace = true serde_json.workspace = true serde.workspace = true -sha3.workspace = true starknet-crypto.workspace = true starknet-types-core.workspace = true thiserror.workspace = true -tiny-keccak.workspace = true tokio = { workspace = true } -strum_macros.workspace = true serde_with.workspace = true +reqwest.workspace = true +strum_macros.workspace = true starknet-core.workspace = true -reqwest.workspace = true \ No newline at end of file + +provider.workspace = true +cairo_types.workspace = true \ No newline at end of file diff --git a/cairo_vm_hints/src/hint_processor/dry_run_input.rs b/crates/hdp_hint_processor/src/hint_processor/dry_run_input.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/dry_run_input.rs rename to crates/hdp_hint_processor/src/hint_processor/dry_run_input.rs diff --git a/cairo_vm_hints/src/hint_processor/mod.rs b/crates/hdp_hint_processor/src/hint_processor/mod.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/mod.rs rename to crates/hdp_hint_processor/src/hint_processor/mod.rs diff --git a/cairo_vm_hints/src/hint_processor/models/mod.rs b/crates/hdp_hint_processor/src/hint_processor/models/mod.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/models/mod.rs rename to crates/hdp_hint_processor/src/hint_processor/models/mod.rs diff --git a/cairo_vm_hints/src/hint_processor/models/param.rs b/crates/hdp_hint_processor/src/hint_processor/models/param.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/models/param.rs rename to crates/hdp_hint_processor/src/hint_processor/models/param.rs diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/account.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/account.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/models/proofs/account.rs rename to crates/hdp_hint_processor/src/hint_processor/models/proofs/account.rs diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/header.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/header.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/models/proofs/header.rs rename to crates/hdp_hint_processor/src/hint_processor/models/proofs/header.rs diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/models/proofs/mmr.rs rename to crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mod.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/models/proofs/mod.rs rename to crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mpt.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/models/proofs/mpt.rs rename to crates/hdp_hint_processor/src/hint_processor/models/proofs/mpt.rs diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/receipt.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/models/proofs/receipt.rs rename to crates/hdp_hint_processor/src/hint_processor/models/proofs/receipt.rs diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/storage.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/storage.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/models/proofs/storage.rs rename to crates/hdp_hint_processor/src/hint_processor/models/proofs/storage.rs diff --git a/cairo_vm_hints/src/hint_processor/models/proofs/transaction.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/transaction.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/models/proofs/transaction.rs rename to crates/hdp_hint_processor/src/hint_processor/models/proofs/transaction.rs diff --git a/cairo_vm_hints/src/hint_processor/output.rs b/crates/hdp_hint_processor/src/hint_processor/output.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/output.rs rename to crates/hdp_hint_processor/src/hint_processor/output.rs diff --git a/cairo_vm_hints/src/hint_processor/run_input.rs b/crates/hdp_hint_processor/src/hint_processor/run_input.rs similarity index 100% rename from cairo_vm_hints/src/hint_processor/run_input.rs rename to crates/hdp_hint_processor/src/hint_processor/run_input.rs diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/builtins.rs b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/builtins.rs similarity index 98% rename from cairo_vm_hints/src/hints/lib/contract_bootloader/builtins.rs rename to crates/hdp_hint_processor/src/hints/lib/contract_bootloader/builtins.rs index 6591710b..c2f130a5 100644 --- a/cairo_vm_hints/src/hints/lib/contract_bootloader/builtins.rs +++ b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/builtins.rs @@ -1,4 +1,5 @@ -use crate::{cairo_types::structs::BuiltinParams, hints::vars}; +use crate::hints::vars; +use cairo_types::structs::BuiltinParams; use cairo_vm::{ hint_processor::{ builtin_hint_processor::{ diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/contract_class.rs b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/contract_class.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/contract_bootloader/contract_class.rs rename to crates/hdp_hint_processor/src/hints/lib/contract_bootloader/contract_class.rs diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/dict_manager.rs b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/dict_manager.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/contract_bootloader/dict_manager.rs rename to crates/hdp_hint_processor/src/hints/lib/contract_bootloader/dict_manager.rs diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/mod.rs b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/mod.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/contract_bootloader/mod.rs rename to crates/hdp_hint_processor/src/hints/lib/contract_bootloader/mod.rs diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/params.rs b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/params.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/contract_bootloader/params.rs rename to crates/hdp_hint_processor/src/hints/lib/contract_bootloader/params.rs diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/program.rs b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/program.rs similarity index 95% rename from cairo_vm_hints/src/hints/lib/contract_bootloader/program.rs rename to crates/hdp_hint_processor/src/hints/lib/contract_bootloader/program.rs index 996ce5e0..8415f123 100644 --- a/cairo_vm_hints/src/hints/lib/contract_bootloader/program.rs +++ b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/program.rs @@ -1,5 +1,6 @@ -use crate::{cairo_types::structs::CompiledClass, hints::vars}; +use crate::hints::vars; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; +use cairo_types::structs::CompiledClass; use cairo_vm::{ any_box, hint_processor::{ diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/scopes.rs b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/scopes.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/contract_bootloader/scopes.rs rename to crates/hdp_hint_processor/src/hints/lib/contract_bootloader/scopes.rs diff --git a/cairo_vm_hints/src/hints/lib/contract_bootloader/syscall_handler.rs b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/syscall_handler.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/contract_bootloader/syscall_handler.rs rename to crates/hdp_hint_processor/src/hints/lib/contract_bootloader/syscall_handler.rs diff --git a/cairo_vm_hints/src/hints/lib/decoder/evm/has_type_prefix.rs b/crates/hdp_hint_processor/src/hints/lib/decoder/evm/has_type_prefix.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/decoder/evm/has_type_prefix.rs rename to crates/hdp_hint_processor/src/hints/lib/decoder/evm/has_type_prefix.rs diff --git a/cairo_vm_hints/src/hints/lib/decoder/evm/is_byzantium.rs b/crates/hdp_hint_processor/src/hints/lib/decoder/evm/is_byzantium.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/decoder/evm/is_byzantium.rs rename to crates/hdp_hint_processor/src/hints/lib/decoder/evm/is_byzantium.rs diff --git a/cairo_vm_hints/src/hints/lib/decoder/evm/mod.rs b/crates/hdp_hint_processor/src/hints/lib/decoder/evm/mod.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/decoder/evm/mod.rs rename to crates/hdp_hint_processor/src/hints/lib/decoder/evm/mod.rs diff --git a/cairo_vm_hints/src/hints/lib/decoder/evm/v_is_encoded.rs b/crates/hdp_hint_processor/src/hints/lib/decoder/evm/v_is_encoded.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/decoder/evm/v_is_encoded.rs rename to crates/hdp_hint_processor/src/hints/lib/decoder/evm/v_is_encoded.rs diff --git a/cairo_vm_hints/src/hints/lib/decoder/mod.rs b/crates/hdp_hint_processor/src/hints/lib/decoder/mod.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/decoder/mod.rs rename to crates/hdp_hint_processor/src/hints/lib/decoder/mod.rs diff --git a/cairo_vm_hints/src/hints/lib/merkle/mod.rs b/crates/hdp_hint_processor/src/hints/lib/merkle/mod.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/merkle/mod.rs rename to crates/hdp_hint_processor/src/hints/lib/merkle/mod.rs diff --git a/cairo_vm_hints/src/hints/lib/mod.rs b/crates/hdp_hint_processor/src/hints/lib/mod.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/mod.rs rename to crates/hdp_hint_processor/src/hints/lib/mod.rs diff --git a/cairo_vm_hints/src/hints/lib/print.rs b/crates/hdp_hint_processor/src/hints/lib/print.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/print.rs rename to crates/hdp_hint_processor/src/hints/lib/print.rs diff --git a/cairo_vm_hints/src/hints/lib/rlp/divmod.rs b/crates/hdp_hint_processor/src/hints/lib/rlp/divmod.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/rlp/divmod.rs rename to crates/hdp_hint_processor/src/hints/lib/rlp/divmod.rs diff --git a/cairo_vm_hints/src/hints/lib/rlp/item_type.rs b/crates/hdp_hint_processor/src/hints/lib/rlp/item_type.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/rlp/item_type.rs rename to crates/hdp_hint_processor/src/hints/lib/rlp/item_type.rs diff --git a/cairo_vm_hints/src/hints/lib/rlp/mod.rs b/crates/hdp_hint_processor/src/hints/lib/rlp/mod.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/rlp/mod.rs rename to crates/hdp_hint_processor/src/hints/lib/rlp/mod.rs diff --git a/cairo_vm_hints/src/hints/lib/rlp/processed_words.rs b/crates/hdp_hint_processor/src/hints/lib/rlp/processed_words.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/rlp/processed_words.rs rename to crates/hdp_hint_processor/src/hints/lib/rlp/processed_words.rs diff --git a/cairo_vm_hints/src/hints/lib/segments.rs b/crates/hdp_hint_processor/src/hints/lib/segments.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/segments.rs rename to crates/hdp_hint_processor/src/hints/lib/segments.rs diff --git a/cairo_vm_hints/src/hints/lib/utils/mod.rs b/crates/hdp_hint_processor/src/hints/lib/utils/mod.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/utils/mod.rs rename to crates/hdp_hint_processor/src/hints/lib/utils/mod.rs diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/account_verifier.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/verifiers/evm/account_verifier.rs rename to crates/hdp_hint_processor/src/hints/lib/verifiers/evm/account_verifier.rs diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/header_verifier.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/verifiers/evm/header_verifier.rs rename to crates/hdp_hint_processor/src/hints/lib/verifiers/evm/header_verifier.rs diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/mod.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/verifiers/evm/mod.rs rename to crates/hdp_hint_processor/src/hints/lib/verifiers/evm/mod.rs diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/receipt_verifier.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/verifiers/evm/receipt_verifier.rs rename to crates/hdp_hint_processor/src/hints/lib/verifiers/evm/receipt_verifier.rs diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/storage_item_verifier.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/storage_item_verifier.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/verifiers/evm/storage_item_verifier.rs rename to crates/hdp_hint_processor/src/hints/lib/verifiers/evm/storage_item_verifier.rs diff --git a/cairo_vm_hints/src/hints/lib/verifiers/evm/transaction_verifier.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/transaction_verifier.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/verifiers/evm/transaction_verifier.rs rename to crates/hdp_hint_processor/src/hints/lib/verifiers/evm/transaction_verifier.rs diff --git a/cairo_vm_hints/src/hints/lib/verifiers/mod.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/mod.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/verifiers/mod.rs rename to crates/hdp_hint_processor/src/hints/lib/verifiers/mod.rs diff --git a/cairo_vm_hints/src/hints/lib/verifiers/utils.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/utils.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/verifiers/utils.rs rename to crates/hdp_hint_processor/src/hints/lib/verifiers/utils.rs diff --git a/cairo_vm_hints/src/hints/lib/verifiers/verify.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/verify.rs similarity index 100% rename from cairo_vm_hints/src/hints/lib/verifiers/verify.rs rename to crates/hdp_hint_processor/src/hints/lib/verifiers/verify.rs diff --git a/cairo_vm_hints/src/hints/mod.rs b/crates/hdp_hint_processor/src/hints/mod.rs similarity index 100% rename from cairo_vm_hints/src/hints/mod.rs rename to crates/hdp_hint_processor/src/hints/mod.rs diff --git a/crates/hdp_hint_processor/src/hints/vars.rs b/crates/hdp_hint_processor/src/hints/vars.rs new file mode 100644 index 00000000..2e4f1046 --- /dev/null +++ b/crates/hdp_hint_processor/src/hints/vars.rs @@ -0,0 +1,60 @@ +pub mod scopes { + pub const ACCOUNT: &str = "account"; + pub const BATCH: &str = "batch"; + pub const COMPILED_CLASS: &str = "compiled_class"; + pub const DICT_MANAGER: &str = "dict_manager"; + pub const HEADER: &str = "header"; + pub const N_SELECTED_BUILTINS: &str = "n_selected_builtins"; + pub const PARAMS: &str = "params"; + pub const PROOF: &str = "proof"; + pub const PROOFS: &str = "proofs"; + pub const RECEIPT: &str = "receipt"; + pub const STORAGE: &str = "storage"; + pub const SYSCALL_HANDLER: &str = "syscall_handler"; + pub const TRANSACTION: &str = "transaction"; +} + +pub mod ids { + pub const ADDRESS: &str = "ids.address"; + pub const ALL_ENCODINGS: &str = "all_encodings"; + pub const BATCH_LEN: &str = "batch_len"; + pub const BUILTIN_PARAMS: &str = "builtin_params"; + pub const BUILTIN_PTRS: &str = "builtin_ptrs"; + pub const CHAIN_ID: &str = "chain_id"; + pub const COMPILED_CLASS: &str = "compiled_class"; + pub const CURRENT_ITEM: &str = "ids.current_item"; + pub const DEVISOR: &str = "ids.devisor"; + pub const FIRST_BYTE: &str = "ids.first_byte"; + pub const I: &str = "ids.i"; + pub const IDX: &str = "ids.idx"; + pub const IS_LEFT_SMALLER: &str = "ids.is_left_smaller"; + pub const IS_LONG: &str = "ids.is_long"; + pub const ITEM_TYPE: &str = "ids.item_type"; + pub const KEY_LOW: &str = "ids.key_low"; + pub const KEY_LEADING_ZEROS: &str = "ids.key_leading_zeros"; + pub const KEY_HIGH: &str = "ids.key_high"; + pub const LEFT: &str = "ids.left"; + pub const MMR_PATH: &str = "ids.mmr_path"; + pub const MPT_PROOF: &str = "ids.mpt_proof"; + pub const PROOF_BYTES_LEN: &str = "ids.proof_bytes_len"; + pub const N_BUILTINS: &str = "n_builtins"; + pub const N_PROCESSED_WORDS: &str = "ids.n_processed_words"; + pub const N_SELECTED_BUILTINS: &str = "n_selected_builtins"; + pub const PARAMS_LEN: &str = "params_len"; + pub const PARAMS: &str = "params"; + pub const PROGRAM_HASH: &str = "program_hash"; + pub const Q: &str = "ids.q"; + pub const R: &str = "ids.r"; + pub const RESULT: &str = "result"; + pub const RETURN_BUILTIN_PTRS: &str = "return_builtin_ptrs"; + pub const RIGHT: &str = "ids.right"; + pub const RLP: &str = "ids.rlp"; + pub const SELECT_BUILTIN: &str = "select_builtin"; + pub const SELECTED_ENCODINGS: &str = "selected_encodings"; + pub const SELECTED_PTRS: &str = "selected_ptrs"; + pub const SLOT: &str = "ids.slot"; + pub const SYSCALL_PTR: &str = "syscall_ptr"; + pub const TASK_HASH: &str = "ids.task_hash"; + pub const VALUE_LEN: &str = "ids.value_len"; + pub const VALUE: &str = "ids.value"; +} diff --git a/crates/hdp_hint_processor/src/lib.rs b/crates/hdp_hint_processor/src/lib.rs new file mode 100644 index 00000000..61b2a2ba --- /dev/null +++ b/crates/hdp_hint_processor/src/lib.rs @@ -0,0 +1,8 @@ +#![forbid(unsafe_code)] +#![allow(async_fn_in_trait)] +pub mod hint_processor; +pub mod hints; +pub mod syscall_handler; + +#[cfg(test)] +pub mod tests; diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/account.rs similarity index 71% rename from cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs rename to crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/account.rs index eac2250f..01cb0756 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/account.rs @@ -1,3 +1,4 @@ +use crate::syscall_handler::RPC; use crate::syscall_handler::{ keys::{ account::{CairoKey, Key}, @@ -6,14 +7,6 @@ use crate::syscall_handler::{ traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, }; -use crate::{ - cairo_types::{ - evm::account::{CairoAccount, FunctionId}, - structs::Uint256, - traits::CairoType, - }, - syscall_handler::RPC, -}; use alloy::providers::{Provider, RootProvider}; use alloy::transports::http::{Client, Http}; use alloy::{ @@ -21,6 +14,11 @@ use alloy::{ primitives::{Address, BlockNumber, ChainId}, transports::http::reqwest::Url, }; +use cairo_types::{ + evm::account::{CairoAccount, FunctionId}, + structs::Uint256, + traits::CairoType, +}; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, @@ -44,7 +42,14 @@ impl CallHandler for AccountCallHandler { } fn derive_id(selector: Felt252) -> SyscallResult { - Self::Id::try_from(selector) + Self::Id::from_repr(selector.try_into().map_err(|e| SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: format!("{}", e), + })?) + .ok_or(SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: "Invalid function identifier".to_string(), + }) } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/header.rs similarity index 72% rename from cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs rename to crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/header.rs index 4f6a6940..dce87ea1 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/header.rs @@ -1,3 +1,4 @@ +use crate::syscall_handler::RPC; use crate::syscall_handler::{ keys::{ header::{CairoKey, Key}, @@ -6,14 +7,6 @@ use crate::syscall_handler::{ traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, }; -use crate::{ - cairo_types::{ - evm::header::{CairoHeader, FunctionId}, - structs::Uint256, - traits::CairoType, - }, - syscall_handler::RPC, -}; use alloy::providers::{Provider, RootProvider}; use alloy::rpc::types::BlockTransactionsKind; use alloy::transports::http::{Client, Http}; @@ -21,6 +14,11 @@ use alloy::{ primitives::{BlockNumber, ChainId}, transports::http::reqwest::Url, }; +use cairo_types::{ + evm::header::{CairoHeader, FunctionId}, + structs::Uint256, + traits::CairoType, +}; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, @@ -44,7 +42,14 @@ impl CallHandler for HeaderCallHandler { } fn derive_id(selector: Felt252) -> SyscallResult { - Self::Id::try_from(selector) + Self::Id::from_repr(selector.try_into().map_err(|e| SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: format!("{}", e), + })?) + .ok_or(SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: "Invalid function identifier".to_string(), + }) } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/mod.rs similarity index 96% rename from cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs rename to crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/mod.rs index 02067a4f..124eea9b 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/mod.rs @@ -5,13 +5,13 @@ pub mod receipt; pub mod storage; pub mod transaction; -use crate::cairo_types::traits::CairoType; use crate::syscall_handler::keys; use crate::syscall_handler::traits::{self, CallHandler}; +use crate::syscall_handler::utils::{felt_from_ptr, SyscallExecutionError, SyscallResult, WriteResponseResult}; use crate::syscall_handler::utils::{run_handler, SyscallSelector}; -use crate::{ - cairo_types::new_syscalls::{CallContractRequest, CallContractResponse}, - syscall_handler::utils::{felt_from_ptr, SyscallExecutionError, SyscallResult, WriteResponseResult}, +use cairo_types::{ + new_syscalls::{CallContractRequest, CallContractResponse}, + traits::CairoType, }; use cairo_vm::vm::errors::hint_errors::HintError; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/receipt.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/receipt.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/evm/dryrun/receipt.rs rename to crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/receipt.rs diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/storage.rs similarity index 72% rename from cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs rename to crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/storage.rs index 3e9256c8..effe4d0e 100644 --- a/cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/storage.rs @@ -1,3 +1,4 @@ +use crate::syscall_handler::RPC; use crate::syscall_handler::{ keys::{ storage::{CairoKey, Key}, @@ -6,14 +7,6 @@ use crate::syscall_handler::{ traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, }; -use crate::{ - cairo_types::{ - evm::storage::{CairoStorage, FunctionId}, - structs::Uint256, - traits::CairoType, - }, - syscall_handler::RPC, -}; use alloy::providers::{Provider, RootProvider}; use alloy::transports::http::{Client, Http}; use alloy::{ @@ -21,6 +14,11 @@ use alloy::{ primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, transports::http::reqwest::Url, }; +use cairo_types::{ + evm::storage::{CairoStorage, FunctionId}, + structs::Uint256, + traits::CairoType, +}; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, @@ -44,7 +42,14 @@ impl CallHandler for StorageCallHandler { } fn derive_id(selector: Felt252) -> SyscallResult { - Self::Id::try_from(selector) + Self::Id::from_repr(selector.try_into().map_err(|e| SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: format!("{}", e), + })?) + .ok_or(SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: "Invalid function identifier".to_string(), + }) } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { diff --git a/cairo_vm_hints/src/syscall_handler/evm/dryrun/transaction.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/transaction.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/evm/dryrun/transaction.rs rename to crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/transaction.rs diff --git a/cairo_vm_hints/src/syscall_handler/evm/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/mod.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/evm/mod.rs rename to crates/hdp_hint_processor/src/syscall_handler/evm/mod.rs diff --git a/cairo_vm_hints/src/provider/evm/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/soundrun/mod.rs similarity index 100% rename from cairo_vm_hints/src/provider/evm/mod.rs rename to crates/hdp_hint_processor/src/syscall_handler/evm/soundrun/mod.rs diff --git a/cairo_vm_hints/src/syscall_handler/keys/account.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs similarity index 98% rename from cairo_vm_hints/src/syscall_handler/keys/account.rs rename to crates/hdp_hint_processor/src/syscall_handler/keys/account.rs index 9acd8ea0..805632d1 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/account.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs @@ -1,5 +1,4 @@ use crate::{ - cairo_types::traits::CairoType, hint_processor::models::proofs::{self, mpt::MPTProof}, syscall_handler::{utils::SyscallExecutionError, RPC}, }; @@ -10,6 +9,7 @@ use alloy::{ rpc::types::EIP1186AccountProofResponse, transports::http::Http, }; +use cairo_types::traits::CairoType; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, diff --git a/cairo_vm_hints/src/syscall_handler/keys/header.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs similarity index 97% rename from cairo_vm_hints/src/syscall_handler/keys/header.rs rename to crates/hdp_hint_processor/src/syscall_handler/keys/header.rs index 8892e13f..4fd1cbc6 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/header.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs @@ -1,15 +1,10 @@ use super::FetchValue; use crate::{ - cairo_types::traits::CairoType, hint_processor::models::proofs::{ self, header::{Header, HeaderProof}, mmr::MmrMeta, }, - provider::indexer::{ - types::{BlockHeader, IndexerQuery, MMRData}, - Indexer, - }, syscall_handler::{utils::SyscallExecutionError, RPC}, }; use alloy::{ @@ -19,11 +14,16 @@ use alloy::{ rpc::types::{Block, BlockTransactionsKind}, transports::http::Http, }; +use cairo_types::traits::CairoType; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; +use provider::indexer::{ + types::{BlockHeader, IndexerQuery, MMRData}, + Indexer, +}; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use starknet_types_core::felt::FromStrError; diff --git a/cairo_vm_hints/src/syscall_handler/keys/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/keys/mod.rs rename to crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs diff --git a/cairo_vm_hints/src/syscall_handler/keys/receipt.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/receipt.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/keys/receipt.rs rename to crates/hdp_hint_processor/src/syscall_handler/keys/receipt.rs diff --git a/cairo_vm_hints/src/syscall_handler/keys/storage.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs similarity index 99% rename from cairo_vm_hints/src/syscall_handler/keys/storage.rs rename to crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs index 159c0ed7..09a02771 100644 --- a/cairo_vm_hints/src/syscall_handler/keys/storage.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs @@ -1,6 +1,5 @@ use super::FetchValue; use crate::{ - cairo_types::traits::CairoType, hint_processor::models::proofs::{self, mpt::MPTProof}, syscall_handler::{utils::SyscallExecutionError, RPC}, }; @@ -10,6 +9,7 @@ use alloy::{ rpc::types::EIP1186AccountProofResponse, transports::http::Http, }; +use cairo_types::traits::CairoType; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, diff --git a/cairo_vm_hints/src/syscall_handler/keys/transaction.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/transaction.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/keys/transaction.rs rename to crates/hdp_hint_processor/src/syscall_handler/keys/transaction.rs diff --git a/cairo_vm_hints/src/syscall_handler/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/mod.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/mod.rs rename to crates/hdp_hint_processor/src/syscall_handler/mod.rs diff --git a/cairo_vm_hints/src/provider/starknet/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs similarity index 100% rename from cairo_vm_hints/src/provider/starknet/mod.rs rename to crates/hdp_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs diff --git a/cairo_vm_hints/src/syscall_handler/starknet/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/starknet/mod.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/starknet/mod.rs rename to crates/hdp_hint_processor/src/syscall_handler/starknet/mod.rs diff --git a/cairo_vm_hints/src/syscall_handler/evm/soundrun/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/evm/soundrun/mod.rs rename to crates/hdp_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs diff --git a/cairo_vm_hints/src/syscall_handler/traits.rs b/crates/hdp_hint_processor/src/syscall_handler/traits.rs similarity index 95% rename from cairo_vm_hints/src/syscall_handler/traits.rs rename to crates/hdp_hint_processor/src/syscall_handler/traits.rs index d8133ba6..eab0b3c4 100644 --- a/cairo_vm_hints/src/syscall_handler/traits.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/traits.rs @@ -1,4 +1,4 @@ -use crate::cairo_types::traits::CairoType; +use cairo_types::traits::CairoType; use super::utils::{SyscallResult, WriteResponseResult}; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; diff --git a/cairo_vm_hints/src/syscall_handler/utils.rs b/crates/hdp_hint_processor/src/syscall_handler/utils.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/utils.rs rename to crates/hdp_hint_processor/src/syscall_handler/utils.rs diff --git a/cairo_vm_hints/src/tests/mod.rs b/crates/hdp_hint_processor/src/tests/mod.rs similarity index 91% rename from cairo_vm_hints/src/tests/mod.rs rename to crates/hdp_hint_processor/src/tests/mod.rs index 8ab14e6e..4edb8b74 100644 --- a/cairo_vm_hints/src/tests/mod.rs +++ b/crates/hdp_hint_processor/src/tests/mod.rs @@ -3,7 +3,7 @@ use cairo_vm::{ vm::{errors::cairo_run_errors::CairoRunError, runners::cairo_runner::CairoRunner}, }; -use crate::CustomHintProcessor; +use crate::hint_processor::CustomHintProcessor; pub fn run_cairo_program(program_content: &[u8]) -> Result { let cairo_run_config = cairo_run::CairoRunConfig { diff --git a/crates/provider/Cargo.toml b/crates/provider/Cargo.toml new file mode 100644 index 00000000..ed7a4397 --- /dev/null +++ b/crates/provider/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "provider" +version = "0.1.0" +edition = "2021" + +[dependencies] +alloy.workspace = true +tokio.workspace = true +serde.workspace = true +serde_json.workspace = true +serde_with.workspace = true +thiserror.workspace = true +reqwest.workspace = true \ No newline at end of file diff --git a/cairo_vm_hints/src/syscall_handler/starknet/dryrun/mod.rs b/crates/provider/src/evm/mod.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/starknet/dryrun/mod.rs rename to crates/provider/src/evm/mod.rs diff --git a/cairo_vm_hints/src/provider/indexer/mod.rs b/crates/provider/src/indexer/mod.rs similarity index 100% rename from cairo_vm_hints/src/provider/indexer/mod.rs rename to crates/provider/src/indexer/mod.rs diff --git a/cairo_vm_hints/src/provider/indexer/types.rs b/crates/provider/src/indexer/types.rs similarity index 100% rename from cairo_vm_hints/src/provider/indexer/types.rs rename to crates/provider/src/indexer/types.rs diff --git a/cairo_vm_hints/src/provider/mod.rs b/crates/provider/src/lib.rs similarity index 100% rename from cairo_vm_hints/src/provider/mod.rs rename to crates/provider/src/lib.rs diff --git a/cairo_vm_hints/src/syscall_handler/starknet/soundrun/mod.rs b/crates/provider/src/starknet/mod.rs similarity index 100% rename from cairo_vm_hints/src/syscall_handler/starknet/soundrun/mod.rs rename to crates/provider/src/starknet/mod.rs From 1ec36b89b97b643c7ce33d63ae59c9237cce0a47 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 16 Dec 2024 23:52:08 +0100 Subject: [PATCH 38/75] proof fetcher --- Cargo.lock | 15 +++ Cargo.toml | 5 +- README.md | 2 +- crates/fetcher/Cargo.toml | 16 +++ crates/fetcher/src/lib.rs | 26 ++++ crates/fetcher/src/main.rs | 85 ++++++++++++ crates/fetcher/src/proof_keys.rs | 125 ++++++++++++++++++ .../src/hint_processor/models/proofs/mmr.rs | 2 +- .../src/hint_processor/models/proofs/mod.rs | 3 +- .../src/hint_processor/models/proofs/mpt.rs | 4 +- .../lib/verifiers/evm/account_verifier.rs | 6 +- .../lib/verifiers/evm/receipt_verifier.rs | 7 +- .../verifiers/evm/storage_item_verifier.rs | 6 +- .../lib/verifiers/evm/transaction_verifier.rs | 7 +- .../src/syscall_handler/evm/dryrun/account.rs | 2 +- .../src/syscall_handler/evm/dryrun/header.rs | 2 +- .../src/syscall_handler/evm/dryrun/mod.rs | 22 ++- .../src/syscall_handler/evm/dryrun/storage.rs | 2 +- .../src/syscall_handler/keys/account.rs | 31 +++-- .../src/syscall_handler/keys/header.rs | 88 +++--------- .../src/syscall_handler/keys/mod.rs | 5 - .../src/syscall_handler/keys/storage.rs | 35 +---- .../src/syscall_handler/mod.rs | 2 - crates/provider/src/lib.rs | 2 + 24 files changed, 363 insertions(+), 137 deletions(-) create mode 100644 crates/fetcher/Cargo.toml create mode 100644 crates/fetcher/src/lib.rs create mode 100644 crates/fetcher/src/main.rs create mode 100644 crates/fetcher/src/proof_keys.rs diff --git a/Cargo.lock b/Cargo.lock index 28b48a7a..2fbba276 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2165,6 +2165,21 @@ dependencies = [ "bytes", ] +[[package]] +name = "fetcher" +version = "0.1.0" +dependencies = [ + "alloy", + "cairo-vm", + "clap", + "hdp_hint_processor", + "hex", + "provider", + "serde_json", + "thiserror 1.0.69", + "tokio", +] + [[package]] name = "ff" version = "0.13.0" diff --git a/Cargo.toml b/Cargo.toml index 74e6ebf3..321d5d0d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,10 +2,11 @@ resolver = "2" members = [ + "crates/cairo_types", + "crates/dry_run", "crates/hdp_hint_processor", + "crates/fetcher", "crates/provider", - "crates/cairo_types", - "crates/dry_run" ] [workspace.dependencies] diff --git a/README.md b/README.md index 5ba79e77..394cfae4 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Before running the program, prepare the input data. The inputs are provided via To run the program, use: ```bash -make run-hdp +cargo run --bin dry_run -- build/compiled_cairo_files/contract_dry_run.json --program_input rust_input.json --program_output a.json --layout all_cairo ``` The program will output the results root and tasks root. These roots can be used to extract the results from the on-chain contract. diff --git a/crates/fetcher/Cargo.toml b/crates/fetcher/Cargo.toml new file mode 100644 index 00000000..6d78a2a9 --- /dev/null +++ b/crates/fetcher/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "fetcher" +version = "0.1.0" +edition = "2021" + +[dependencies] +hdp_hint_processor.workspace = true +cairo-vm.workspace = true +clap.workspace = true +thiserror.workspace = true +tokio.workspace = true +serde_json.workspace = true +alloy.workspace = true +hex.workspace = true + +provider.workspace = true \ No newline at end of file diff --git a/crates/fetcher/src/lib.rs b/crates/fetcher/src/lib.rs new file mode 100644 index 00000000..a5493bff --- /dev/null +++ b/crates/fetcher/src/lib.rs @@ -0,0 +1,26 @@ +use alloy::hex::FromHexError; +use provider::indexer::types::IndexerError; +use std::num::ParseIntError; +use thiserror::Error; + +pub mod proof_keys; + +#[derive(Error, Debug)] +pub enum FetcherError { + #[error(transparent)] + Args(#[from] clap::error::Error), + #[error("Output Error: {0}")] + Output(String), + #[error(transparent)] + IO(#[from] std::io::Error), + #[error(transparent)] + Indexer(#[from] IndexerError), + #[error(transparent)] + ParseIntError(#[from] ParseIntError), + #[error(transparent)] + FromHexError(#[from] FromHexError), + #[error(transparent)] + SerdeJson(#[from] serde_json::Error), + #[error("Internal Error: {0}")] + InternalError(String), +} diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs new file mode 100644 index 00000000..d5524e44 --- /dev/null +++ b/crates/fetcher/src/main.rs @@ -0,0 +1,85 @@ +#![forbid(unsafe_code)] +#![allow(async_fn_in_trait)] +use clap::{Parser, ValueHint}; +use fetcher::{proof_keys::ProofKeys, FetcherError}; +use hdp_hint_processor::{ + hint_processor::models::proofs::{account::Account, header::Header, mmr::MmrMeta, storage::Storage, Proofs}, + syscall_handler::evm::{self, dryrun::SyscallHandler}, +}; +use std::{collections::HashSet, fs, path::PathBuf}; + +pub mod proof_keys; + +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + #[clap(value_parser, value_hint=ValueHint::FilePath)] + filename: PathBuf, + #[structopt(long = "program_output")] + program_output: PathBuf, +} + +fn main() -> Result<(), FetcherError> { + let args = Args::try_parse_from(std::env::args()).map_err(FetcherError::Args)?; + + let input_file = fs::read(args.filename)?; + let syscall_handler = serde_json::from_slice::(&input_file)?; + + let mut proof_keys = ProofKeys::default(); + for key in syscall_handler.call_contract_handler.key_set { + match key { + evm::dryrun::DryRunKey::Account(value) => { + proof_keys.account_keys.insert(value); + } + evm::dryrun::DryRunKey::Header(value) => { + proof_keys.header_keys.insert(value); + } + evm::dryrun::DryRunKey::Storage(value) => { + proof_keys.storage_keys.insert(value); + } + } + } + + let mut headers_with_mmr = proof_keys + .header_keys + .iter() + .map(ProofKeys::fetch_header_proof) + .collect::, FetcherError>>()?; + + let mut accounts: HashSet = HashSet::default(); + + for (header_with_mmr, account) in proof_keys + .account_keys + .iter() + .map(ProofKeys::fetch_account_proof) + .collect::, FetcherError>>()? + .into_iter() + { + headers_with_mmr.insert(header_with_mmr); + accounts.insert(account); + } + + let mut storages: HashSet = HashSet::default(); + + for (header_with_mmr, account, storage) in proof_keys + .storage_keys + .iter() + .map(ProofKeys::fetch_storage_proof) + .collect::, FetcherError>>()? + .into_iter() + { + headers_with_mmr.insert(header_with_mmr); + accounts.insert(account); + storages.insert(storage); + } + + let proofs = Proofs { + headers_with_mmr: headers_with_mmr.into_iter().collect(), + accounts: accounts.into_iter().collect(), + storages: storages.into_iter().collect(), + ..Default::default() + }; + fs::write(args.program_output, serde_json::to_vec(&proofs).map_err(|e| FetcherError::IO(e.into()))?)?; + + Ok(()) +} diff --git a/crates/fetcher/src/proof_keys.rs b/crates/fetcher/src/proof_keys.rs new file mode 100644 index 00000000..caf72c44 --- /dev/null +++ b/crates/fetcher/src/proof_keys.rs @@ -0,0 +1,125 @@ +use alloy::{ + hex::FromHexError, + primitives::Bytes, + providers::{Provider, RootProvider}, + transports::http::{reqwest::Url, Client, Http}, +}; +use hdp_hint_processor::{ + hint_processor::models::proofs::{ + account::Account, + header::{Header, HeaderProof}, + mmr::MmrMeta, + mpt::MPTProof, + storage::Storage, + }, + syscall_handler::keys, +}; +use provider::{ + indexer::{ + types::{BlockHeader, IndexerQuery}, + Indexer, + }, + RPC, +}; +use std::{collections::HashSet, env}; + +use crate::FetcherError; + +#[derive(Debug, Default)] +pub struct ProofKeys { + pub header_keys: HashSet, + pub account_keys: HashSet, + pub storage_keys: HashSet, +} + +impl ProofKeys { + pub fn fetch_header_proof(key: &keys::header::Key) -> Result<(MmrMeta, Header), FetcherError> { + let provider = Indexer::default(); + let runtime = tokio::runtime::Runtime::new().unwrap(); + + // Fetch proof response + let response = runtime.block_on(async { + provider + .get_headers_proof(IndexerQuery::new(key.chain_id, key.block_number, key.block_number)) + .await + })?; + + // Extract MMR metadata + let mmr_meta = MmrMeta { + id: u64::from_str_radix(&response.mmr_meta.mmr_id[2..], 16)?, + size: response.mmr_meta.mmr_size, + root: response.mmr_meta.mmr_root.parse()?, + chain_id: key.chain_id, + peaks: response + .mmr_meta + .mmr_peaks + .iter() + .map(|peak| peak.parse()) + .collect::, FromHexError>>()?, + }; + + // Retrieve MMR proof + let mmr_proof = response + .headers + .get(&key.block_number) + .ok_or_else(|| FetcherError::InternalError("block not found".into()))?; + + // Parse RLP + let rlp = match &mmr_proof.block_header { + BlockHeader::RlpString(rlp) => rlp, + _ => return Err(FetcherError::InternalError("wrong rlp format".into())), + }; + + // Construct Header + let header = Header { + rlp: rlp.parse()?, + proof: HeaderProof { + leaf_idx: mmr_proof.element_index, + mmr_path: mmr_proof + .siblings_hashes + .iter() + .map(|hash| hash.parse()) + .collect::, FromHexError>>()?, + }, + }; + + Ok((mmr_meta, header)) + } + + pub fn fetch_account_proof(key: &keys::account::Key) -> Result<((MmrMeta, Header), Account), FetcherError> { + let runtime = tokio::runtime::Runtime::new().unwrap(); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let value = runtime + .block_on(async { provider.get_proof(key.address, vec![]).block_id(key.block_number.into()).await }) + .map_err(|e| FetcherError::InternalError(e.to_string()))?; + Ok(( + Self::fetch_header_proof(&key.to_owned().into())?, + Account::new(value.address, vec![MPTProof::new(key.block_number, value.account_proof)]), + )) + } + + pub fn fetch_storage_proof(key: &keys::storage::Key) -> Result<((MmrMeta, Header), Account, Storage), FetcherError> { + let runtime = tokio::runtime::Runtime::new().unwrap(); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let value = runtime + .block_on(async { + provider + .get_proof(key.address, vec![key.storage_slot]) + .block_id(key.block_number.into()) + .await + }) + .map_err(|e| FetcherError::InternalError(e.to_string()))?; + Ok(( + Self::fetch_header_proof(&key.to_owned().into())?, + Account::new(value.address, vec![MPTProof::new(key.block_number, value.account_proof)]), + Storage::new( + value.address, + key.storage_slot, + vec![MPTProof::new( + key.block_number, + value.storage_proof.into_iter().flat_map(|f| f.proof).collect(), + )], + ), + )) + } +} diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs index a388038c..22e1d605 100644 --- a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs +++ b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs @@ -2,7 +2,7 @@ use alloy::primitives::Bytes; use serde::{Deserialize, Serialize}; use serde_with::serde_as; -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash, Default)] #[serde_as] pub struct MmrMeta { pub id: u64, diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs index e79ca441..261ee474 100644 --- a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs +++ b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs @@ -14,10 +14,11 @@ use serde::{Deserialize, Serialize}; use storage::Storage; use transaction::Transaction; -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)] pub struct Proofs { pub mmr_meta: MmrMeta, pub headers: Vec
, + pub headers_with_mmr: Vec<(MmrMeta, Header)>, pub accounts: Vec, pub storages: Vec, pub transactions: Vec, diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mpt.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mpt.rs index 30abcdf8..8662dd3c 100644 --- a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mpt.rs +++ b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mpt.rs @@ -6,11 +6,11 @@ use serde_with::serde_as; #[serde_as] pub struct MPTProof { pub block_number: u64, - pub proof: Bytes, + pub proof: Vec, } impl MPTProof { - pub fn new(block_number: u64, proof: Bytes) -> Self { + pub fn new(block_number: u64, proof: Vec) -> Self { Self { block_number, proof } } } diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/account_verifier.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/account_verifier.rs index 67d8df23..c2eb8ba7 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/account_verifier.rs +++ b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/account_verifier.rs @@ -194,7 +194,11 @@ pub fn hint_get_mpt_proof( ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec = proof.proof.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + let proof_le_chunks: Vec> = proof + .proof + .into_iter() + .map(|p| p.chunks(8).map(Felt252::from_bytes_le_slice).collect()) + .collect(); vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/receipt_verifier.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/receipt_verifier.rs index da2565e5..26f86ca5 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/receipt_verifier.rs +++ b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/receipt_verifier.rs @@ -153,7 +153,12 @@ pub fn hint_receipt_mpt_proof( ) -> Result<(), HintError> { let receipt = exec_scopes.get::(vars::scopes::RECEIPT)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec = receipt.proof.proof.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + let proof_le_chunks: Vec> = receipt + .proof + .proof + .into_iter() + .map(|p| p.chunks(8).map(Felt252::from_bytes_le_slice).collect()) + .collect(); vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/storage_item_verifier.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/storage_item_verifier.rs index bba6ef7b..53d71bdc 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/storage_item_verifier.rs +++ b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/storage_item_verifier.rs @@ -207,7 +207,11 @@ pub fn hint_set_mpt_proof( ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec = proof.proof.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + let proof_le_chunks: Vec> = proof + .proof + .into_iter() + .map(|p| p.chunks(8).map(Felt252::from_bytes_le_slice).collect()) + .collect(); vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/transaction_verifier.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/transaction_verifier.rs index caaf935d..04451187 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/transaction_verifier.rs +++ b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/transaction_verifier.rs @@ -153,7 +153,12 @@ pub fn hint_mpt_proof( ) -> Result<(), HintError> { let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec = transaction.proof.proof.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + let proof_le_chunks: Vec> = transaction + .proof + .proof + .into_iter() + .map(|p| p.chunks(8).map(Felt252::from_bytes_le_slice).collect()) + .collect(); vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/account.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/account.rs index 01cb0756..bfa55d90 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/account.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/account.rs @@ -1,4 +1,3 @@ -use crate::syscall_handler::RPC; use crate::syscall_handler::{ keys::{ account::{CairoKey, Key}, @@ -24,6 +23,7 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; +use provider::RPC; use serde::{Deserialize, Serialize}; use std::env; diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/header.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/header.rs index dce87ea1..0d2cd500 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/header.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/header.rs @@ -1,4 +1,3 @@ -use crate::syscall_handler::RPC; use crate::syscall_handler::{ keys::{ header::{CairoKey, Key}, @@ -24,6 +23,7 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; +use provider::RPC; use serde::{Deserialize, Serialize}; use std::env; diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/mod.rs index 124eea9b..d97c6e78 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/mod.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/mod.rs @@ -25,8 +25,8 @@ use strum_macros::FromRepr; #[derive(Debug, Default, Serialize, Deserialize)] pub struct SyscallHandler { #[serde(skip)] - syscall_ptr: Option, - call_contract_handler: CallContractHandler, + pub syscall_ptr: Option, + pub call_contract_handler: CallContractHandler, } /// SyscallHandler is wrapped in Rc> in order @@ -47,7 +47,7 @@ pub enum CallHandlerId { #[derive(Debug, Default, Serialize, Deserialize)] pub struct CallContractHandler { - key_set: HashSet, + pub key_set: HashSet, } impl SyscallHandlerWrapper { @@ -168,11 +168,25 @@ impl TryFrom for CallHandlerId { #[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] #[serde(rename_all = "lowercase")] -enum DryRunKey { +pub enum DryRunKey { Account(keys::account::Key), Header(keys::header::Key), Storage(keys::storage::Key), } +impl DryRunKey { + pub fn is_account(&self) -> bool { + matches!(self, Self::Account(_)) + } + + pub fn is_header(&self) -> bool { + matches!(self, Self::Header(_)) + } + + pub fn is_storage(&self) -> bool { + matches!(self, Self::Storage(_)) + } +} + #[derive(Debug, Serialize, Deserialize)] pub struct DryRunKeySet(HashSet); diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/storage.rs b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/storage.rs index effe4d0e..437ed08c 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/storage.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/storage.rs @@ -1,4 +1,3 @@ -use crate::syscall_handler::RPC; use crate::syscall_handler::{ keys::{ storage::{CairoKey, Key}, @@ -24,6 +23,7 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; +use provider::RPC; use serde::{Deserialize, Serialize}; use std::env; diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs index 805632d1..0f348f78 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs @@ -1,6 +1,6 @@ use crate::{ hint_processor::models::proofs::{self, mpt::MPTProof}, - syscall_handler::{utils::SyscallExecutionError, RPC}, + syscall_handler::utils::SyscallExecutionError, }; use alloy::{ consensus::Account, @@ -15,11 +15,12 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; +use provider::RPC; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use std::env; -use super::FetchValue; +use super::{storage, FetchValue}; #[derive(Debug)] pub struct CairoKey { @@ -49,9 +50,9 @@ impl CairoType for CairoKey { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct Key { - chain_id: ChainId, - block_number: BlockNumber, - address: Address, + pub chain_id: ChainId, + pub block_number: BlockNumber, + pub address: Address, } impl FetchValue for Key { @@ -65,18 +66,16 @@ impl FetchValue for Key { .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; Ok(value) } +} - // fn fetch_proof(&self) -> Result { - // let runtime = tokio::runtime::Runtime::new().unwrap(); - // let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - // let value = runtime - // .block_on(async { provider.get_proof(self.address, vec![]).block_id(self.block_number.into()).await }) - // .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - // Ok(Self::Proof::new( - // value.address, - // vec![MPTProof::new(self.block_number, value.account_proof)], - // )) - // } +impl From for Key { + fn from(value: storage::Key) -> Self { + Self { + chain_id: value.chain_id, + block_number: value.block_number, + address: value.address, + } + } } impl TryFrom for Key { diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs index 4fd1cbc6..2acd19b3 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs @@ -1,11 +1,11 @@ -use super::FetchValue; +use super::{account, storage, FetchValue}; use crate::{ hint_processor::models::proofs::{ self, header::{Header, HeaderProof}, mmr::MmrMeta, }, - syscall_handler::{utils::SyscallExecutionError, RPC}, + syscall_handler::utils::SyscallExecutionError, }; use alloy::{ hex::FromHexError, @@ -24,6 +24,7 @@ use provider::indexer::{ types::{BlockHeader, IndexerQuery, MMRData}, Indexer, }; +use provider::RPC; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use starknet_types_core::felt::FromStrError; @@ -54,8 +55,8 @@ impl CairoType for CairoKey { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct Key { - chain_id: ChainId, - block_number: BlockNumber, + pub chain_id: ChainId, + pub block_number: BlockNumber, } impl FetchValue for Key { @@ -74,71 +75,24 @@ impl FetchValue for Key { .ok_or(SyscallExecutionError::InternalError("Block not found".into()))?; Ok(block) } +} - // fn fetch_proof(&self) -> Result { - // let provider = Indexer::default(); - // let runtime = tokio::runtime::Runtime::new().unwrap(); - - // // Fetch proof response - // let response = runtime - // .block_on(async { - // provider - // .get_headers_proof(IndexerQuery::new(self.chain_id, self.block_number, self.block_number)) - // .await - // }) - // .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - - // // Extract MMR metadata - // let mmr_meta = MmrMeta { - // id: response - // .mmr_meta - // .mmr_id - // .parse() - // .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, - // size: response.mmr_meta.mmr_size, - // root: response - // .mmr_meta - // .mmr_root - // .parse() - // .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, - // chain_id: self.chain_id, - // peaks: response - // .mmr_meta - // .mmr_peaks - // .iter() - // .map(|peak| peak.parse()) - // .collect::, FromHexError>>() - // .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, - // }; - - // // Retrieve MMR proof - // let mmr_proof = response - // .headers - // .get(&self.block_number) - // .ok_or_else(|| SyscallExecutionError::InternalError("block not found".into()))?; - - // // Parse RLP - // let rlp = match &mmr_proof.block_header { - // BlockHeader::RlpString(rlp) => rlp, - // _ => return Err(SyscallExecutionError::InternalError("wrong rlp format".into())), - // }; - - // // Construct Header - // let header = Header { - // rlp: rlp.parse().map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, - // proof: HeaderProof { - // leaf_idx: mmr_proof.element_index, - // mmr_path: mmr_proof - // .siblings_hashes - // .iter() - // .map(|hash| hash.parse()) - // .collect::, FromHexError>>() - // .map_err(|e| SyscallExecutionError::InternalError(format!("{e}").into()))?, - // }, - // }; +impl From for Key { + fn from(value: account::Key) -> Self { + Self { + chain_id: value.chain_id, + block_number: value.block_number, + } + } +} - // Ok((mmr_meta, header)) - // } +impl From for Key { + fn from(value: storage::Key) -> Self { + Self { + chain_id: value.chain_id, + block_number: value.block_number, + } + } } impl TryFrom for Key { diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs index 0aa4c83c..ac97615e 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs @@ -13,8 +13,3 @@ pub trait FetchValue { type Value; fn fetch_value(&self) -> Result; } - -pub trait FetchProofs { - type Key; - fn fetch_proofs(&self, keys: Vec) -> Result; -} diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs index 09a02771..6a193ee2 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs @@ -1,7 +1,7 @@ use super::FetchValue; use crate::{ hint_processor::models::proofs::{self, mpt::MPTProof}, - syscall_handler::{utils::SyscallExecutionError, RPC}, + syscall_handler::utils::SyscallExecutionError, }; use alloy::{ primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, @@ -15,6 +15,7 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; +use provider::RPC; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use std::env; @@ -53,10 +54,10 @@ impl CairoType for CairoKey { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)] pub struct Key { - chain_id: ChainId, - block_number: BlockNumber, - address: Address, - storage_slot: StorageKey, + pub chain_id: ChainId, + pub block_number: BlockNumber, + pub address: Address, + pub storage_slot: StorageKey, } impl FetchValue for Key { @@ -75,30 +76,6 @@ impl FetchValue for Key { .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; Ok(value) } - - // fn fetch_proof(&self) -> Result { - // let runtime = tokio::runtime::Runtime::new().unwrap(); - // let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - // let value = runtime - // .block_on(async { - // provider - // .get_proof(self.address, vec![self.storage_slot]) - // .block_id(self.block_number.into()) - // .await - // }) - // .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - // Ok(( - // proofs::account::Account::new(value.address, vec![MPTProof::new(self.block_number, value.account_proof)]), - // proofs::storage::Storage::new( - // value.address, - // self.storage_slot, - // vec![MPTProof::new( - // self.block_number, - // value.storage_proof.into_iter().flat_map(|f| f.proof).collect(), - // )], - // ), - // )) - // } } impl TryFrom for Key { diff --git a/crates/hdp_hint_processor/src/syscall_handler/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/mod.rs index 6ae37808..429c5de9 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/mod.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/mod.rs @@ -3,5 +3,3 @@ pub mod keys; pub mod starknet; pub mod traits; pub mod utils; - -pub(crate) const RPC: &str = "RPC"; diff --git a/crates/provider/src/lib.rs b/crates/provider/src/lib.rs index c264f067..bc37d9bd 100644 --- a/crates/provider/src/lib.rs +++ b/crates/provider/src/lib.rs @@ -1,3 +1,5 @@ pub mod evm; pub mod indexer; pub mod starknet; + +pub const RPC: &str = "RPC"; From fd87bfa7ba3ed57d94a268c94c424ff5b934982b Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 17 Dec 2024 13:31:19 +0100 Subject: [PATCH 39/75] proof fetcher & batching refactor --- crates/fetcher/src/main.rs | 8 +-- crates/fetcher/src/proof_keys.rs | 39 +++++++---- .../src/hint_processor/mod.rs | 3 - .../hint_processor/models/proofs/header.rs | 4 +- .../src/hint_processor/models/proofs/mmr.rs | 1 - .../src/hint_processor/models/proofs/mod.rs | 10 ++- .../lib/verifiers/evm/header_verifier.rs | 42 ++++++++--- .../src/hints/lib/verifiers/verify.rs | 70 +++++-------------- crates/hdp_hint_processor/src/hints/vars.rs | 1 + crates/provider/src/indexer/types.rs | 2 + src/types.cairo | 1 - src/utils/utils.cairo | 1 - src/verifiers/evm/header_verifier.cairo | 27 ++++--- src/verifiers/evm/verify.cairo | 31 ++++---- src/verifiers/mmr_verifier.cairo | 17 +++-- src/verifiers/starknet/header_verifier.cairo | 15 ++-- src/verifiers/verify.cairo | 46 ++---------- 17 files changed, 147 insertions(+), 171 deletions(-) diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index d5524e44..0d174223 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -3,7 +3,7 @@ use clap::{Parser, ValueHint}; use fetcher::{proof_keys::ProofKeys, FetcherError}; use hdp_hint_processor::{ - hint_processor::models::proofs::{account::Account, header::Header, mmr::MmrMeta, storage::Storage, Proofs}, + hint_processor::models::proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}, syscall_handler::evm::{self, dryrun::SyscallHandler}, }; use std::{collections::HashSet, fs, path::PathBuf}; @@ -44,7 +44,7 @@ fn main() -> Result<(), FetcherError> { .header_keys .iter() .map(ProofKeys::fetch_header_proof) - .collect::, FetcherError>>()?; + .collect::, FetcherError>>()?; let mut accounts: HashSet = HashSet::default(); @@ -52,7 +52,7 @@ fn main() -> Result<(), FetcherError> { .account_keys .iter() .map(ProofKeys::fetch_account_proof) - .collect::, FetcherError>>()? + .collect::, FetcherError>>()? .into_iter() { headers_with_mmr.insert(header_with_mmr); @@ -65,7 +65,7 @@ fn main() -> Result<(), FetcherError> { .storage_keys .iter() .map(ProofKeys::fetch_storage_proof) - .collect::, FetcherError>>()? + .collect::, FetcherError>>()? .into_iter() { headers_with_mmr.insert(header_with_mmr); diff --git a/crates/fetcher/src/proof_keys.rs b/crates/fetcher/src/proof_keys.rs index caf72c44..d6d0b965 100644 --- a/crates/fetcher/src/proof_keys.rs +++ b/crates/fetcher/src/proof_keys.rs @@ -11,6 +11,7 @@ use hdp_hint_processor::{ mmr::MmrMeta, mpt::MPTProof, storage::Storage, + HeaderMmrMeta, }, syscall_handler::keys, }; @@ -33,7 +34,12 @@ pub struct ProofKeys { } impl ProofKeys { - pub fn fetch_header_proof(key: &keys::header::Key) -> Result<(MmrMeta, Header), FetcherError> { + fn normalize_hex(input: &str) -> String { + let hex_str = input.trim_start_matches("0x"); + format!("{:0>width$}", hex_str, width = (hex_str.len() + 1) / 2 * 2) + } + + pub fn fetch_header_proof(key: &keys::header::Key) -> Result { let provider = Indexer::default(); let runtime = tokio::runtime::Runtime::new().unwrap(); @@ -48,45 +54,54 @@ impl ProofKeys { let mmr_meta = MmrMeta { id: u64::from_str_radix(&response.mmr_meta.mmr_id[2..], 16)?, size: response.mmr_meta.mmr_size, - root: response.mmr_meta.mmr_root.parse()?, - chain_id: key.chain_id, + root: Self::normalize_hex(&response.mmr_meta.mmr_root).parse()?, peaks: response .mmr_meta .mmr_peaks .iter() - .map(|peak| peak.parse()) + .map(|peak| Self::normalize_hex(peak).parse()) .collect::, FromHexError>>()?, }; - // Retrieve MMR proof let mmr_proof = response .headers .get(&key.block_number) .ok_or_else(|| FetcherError::InternalError("block not found".into()))?; // Parse RLP - let rlp = match &mmr_proof.block_header { - BlockHeader::RlpString(rlp) => rlp, + let rlp: Bytes = match &mmr_proof.block_header { + BlockHeader::RlpString(rlp) => rlp.parse()?, + BlockHeader::RlpLittleEndian8ByteChunks(rlp) => { + let rlp_chunks: Vec = rlp + .clone() + .iter() + .map(|x| Self::normalize_hex(x).parse()) + .collect::, FromHexError>>()?; + rlp_chunks.iter().flat_map(|x| x.iter().rev().cloned()).collect::>().into() + } _ => return Err(FetcherError::InternalError("wrong rlp format".into())), }; // Construct Header let header = Header { - rlp: rlp.parse()?, + rlp, proof: HeaderProof { leaf_idx: mmr_proof.element_index, mmr_path: mmr_proof .siblings_hashes .iter() - .map(|hash| hash.parse()) + .map(|hash| Self::normalize_hex(hash).parse()) .collect::, FromHexError>>()?, }, }; - Ok((mmr_meta, header)) + Ok(HeaderMmrMeta { + mmr_meta, + headers: vec![header], + }) } - pub fn fetch_account_proof(key: &keys::account::Key) -> Result<((MmrMeta, Header), Account), FetcherError> { + pub fn fetch_account_proof(key: &keys::account::Key) -> Result<(HeaderMmrMeta, Account), FetcherError> { let runtime = tokio::runtime::Runtime::new().unwrap(); let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let value = runtime @@ -98,7 +113,7 @@ impl ProofKeys { )) } - pub fn fetch_storage_proof(key: &keys::storage::Key) -> Result<((MmrMeta, Header), Account, Storage), FetcherError> { + pub fn fetch_storage_proof(key: &keys::storage::Key) -> Result<(HeaderMmrMeta, Account, Storage), FetcherError> { let runtime = tokio::runtime::Runtime::new().unwrap(); let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let value = runtime diff --git a/crates/hdp_hint_processor/src/hint_processor/mod.rs b/crates/hdp_hint_processor/src/hint_processor/mod.rs index 5dde7b97..c825421a 100644 --- a/crates/hdp_hint_processor/src/hint_processor/mod.rs +++ b/crates/hdp_hint_processor/src/hint_processor/mod.rs @@ -103,7 +103,6 @@ impl CustomHintProcessor { hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx_block_number); hints.insert(lib::verifiers::evm::transaction_verifier::HINT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::transaction_verifier::hint_proof_bytes_len); hints.insert(lib::verifiers::evm::transaction_verifier::HINT_MPT_PROOF.into(), lib::verifiers::evm::transaction_verifier::hint_mpt_proof); - hints.insert(lib::verifiers::evm::header_verifier::HINT_BATCH_HEADERS_LEN.into(), lib::verifiers::evm::header_verifier::hint_batch_headers_len); hints.insert(lib::verifiers::evm::header_verifier::HINT_LEAF_IDX.into(), lib::verifiers::evm::header_verifier::hint_leaf_idx); hints.insert(lib::verifiers::evm::header_verifier::HINT_MMR_PATH_LEN.into(), lib::verifiers::evm::header_verifier::hint_mmr_path_len); hints.insert(lib::verifiers::evm::header_verifier::HINT_MMR_PATH.into(), lib::verifiers::evm::header_verifier::hint_mmr_path); @@ -128,8 +127,6 @@ impl CustomHintProcessor { hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOFS_LEN.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_proofs_len); hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOF_AT.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_proof_at); hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_SLOT.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_slot); - hints.insert(lib::verifiers::verify::HINT_BATCH_LEN.into(), lib::verifiers::verify::hint_batch_len); - hints.insert(lib::verifiers::verify::HINT_CHAIN_ID.into(), lib::verifiers::verify::hint_chain_id); hints.insert(lib::verifiers::verify::HINT_VM_ENTER_SCOPE.into(), lib::verifiers::verify::hint_vm_enter_scope); hints.insert(lib::verifiers::utils::HINT_PRINT_TASK_RESULT.into(), lib::verifiers::utils::hint_print_task_result); hints diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/header.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/header.rs index c29630fa..54d65e38 100644 --- a/crates/hdp_hint_processor/src/hint_processor/models/proofs/header.rs +++ b/crates/hdp_hint_processor/src/hint_processor/models/proofs/header.rs @@ -2,14 +2,14 @@ use alloy::primitives::Bytes; use serde::{Deserialize, Serialize}; use serde_with::serde_as; -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash, Default)] #[serde_as] pub struct HeaderProof { pub leaf_idx: u64, pub mmr_path: Vec, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash, Default)] pub struct Header { pub rlp: Bytes, pub proof: HeaderProof, diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs index 22e1d605..ea407beb 100644 --- a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs +++ b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs @@ -8,7 +8,6 @@ pub struct MmrMeta { pub id: u64, pub size: u64, pub root: Bytes, - pub chain_id: u64, pub peaks: Vec, } diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs index 261ee474..410c82d4 100644 --- a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs +++ b/crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs @@ -14,11 +14,15 @@ use serde::{Deserialize, Serialize}; use storage::Storage; use transaction::Transaction; +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default, Hash)] +pub struct HeaderMmrMeta { + pub headers: Vec
, + pub mmr_meta: MmrMeta, +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Default)] pub struct Proofs { - pub mmr_meta: MmrMeta, - pub headers: Vec
, - pub headers_with_mmr: Vec<(MmrMeta, Header)>, + pub headers_with_mmr: Vec, pub accounts: Vec, pub storages: Vec, pub transactions: Vec, diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/header_verifier.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/header_verifier.rs index 4cb4edbc..e253eaba 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/header_verifier.rs +++ b/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/header_verifier.rs @@ -1,33 +1,57 @@ use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, + dict_manager::DictManager, hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_into_ap}, }, types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; -use std::collections::HashMap; +use std::{any::Any, collections::HashMap}; use crate::{ - hint_processor::models::proofs::{header::Header, Proofs}, + hint_processor::models::proofs::{header::Header, HeaderMmrMeta, Proofs}, hints::vars, }; -pub const HINT_BATCH_HEADERS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.headers))"; +pub const HINT_VM_ENTER_SCOPE: &str = "vm_enter_scope({'header_with_mmr': batch.header_with_mmr[ids.idx], '__dict_manager': __dict_manager})"; -pub fn hint_batch_headers_len( +pub fn hint_vm_enter_scope( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let proofs = exec_scopes.get::(vars::scopes::BATCH)?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + + let headers_with_mmr: Box = Box::new(proofs.headers_with_mmr[idx].clone()); + let dict_manager: Box = Box::new(exec_scopes.get::(vars::scopes::DICT_MANAGER)?); + exec_scopes.enter_scope(HashMap::from([ + (String::from(vars::scopes::HEADER_WITH_MMR), headers_with_mmr), + (String::from(vars::scopes::DICT_MANAGER), dict_manager), + ])); + + Ok(()) +} + +pub const HINT_HEADERS_WITH_MMR_HEADERS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(headers_with_mmr.headers))"; + +pub fn hint_headers_with_mmr_headers_len( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::(vars::scopes::BATCH)?; + let header_with_mmr = exec_scopes.get::(vars::scopes::HEADER_WITH_MMR)?; - insert_value_into_ap(vm, Felt252::from(batch.headers.len())) + insert_value_into_ap(vm, Felt252::from(header_with_mmr.headers.len())) } -pub const HINT_SET_HEADER: &str = "header = batch.headers[ids.idx - 1]\nsegments.write_arg(ids.rlp, [int(x, 16) for x in header.rlp])"; +pub const HINT_SET_HEADER: &str = "header = header_with_mmr.headers[ids.idx - 1]\nsegments.write_arg(ids.rlp, [int(x, 16) for x in header.rlp])"; pub fn hint_set_header( vm: &mut VirtualMachine, @@ -35,11 +59,11 @@ pub fn hint_set_header( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch = exec_scopes.get::(vars::scopes::BATCH)?; + let headers_with_mmr = exec_scopes.get::(vars::scopes::HEADER_WITH_MMR)?; let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? .try_into() .unwrap(); - let header = batch.headers[idx - 1].clone(); + let header = headers_with_mmr.headers[idx - 1].clone(); let rlp_le_chunks: Vec = header.rlp.chunks(8).map(Felt252::from_bytes_le_slice).collect(); exec_scopes.insert_value::
(vars::scopes::HEADER, header); diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/verify.rs b/crates/hdp_hint_processor/src/hints/lib/verifiers/verify.rs index b0737466..c1773004 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/verify.rs +++ b/crates/hdp_hint_processor/src/hints/lib/verifiers/verify.rs @@ -1,9 +1,6 @@ -use cairo_vm::{ - hint_processor::builtin_hint_processor::{ - builtin_hint_processor_definition::HintProcessorData, dict_manager::DictManager, hint_utils::insert_value_from_var_name, - }, - types::relocatable::MaybeRelocatable, -}; +use crate::{hint_processor::models::proofs::Proofs, hints::vars}; +use cairo_vm::hint_processor::builtin_hint_processor::hint_utils::insert_value_into_ap; +use cairo_vm::hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, dict_manager::DictManager}; use cairo_vm::{ types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, @@ -11,49 +8,7 @@ use cairo_vm::{ }; use std::{any::Any, collections::HashMap}; -use crate::{hint_processor::models::proofs::Proofs, hints::vars}; - -pub const HINT_BATCH_LEN: &str = "ids.batch_len = len(proofs)"; - -pub fn hint_batch_len( - vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let proofs = exec_scopes.get::>(vars::scopes::PROOFS)?; - - insert_value_from_var_name( - vars::ids::BATCH_LEN, - MaybeRelocatable::Int(proofs.len().into()), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, - ) -} - -pub const HINT_CHAIN_ID: &str = "ids.chain_id = proofs[ids.batch_len - 1].mmr_meta.chain_id"; - -pub fn hint_chain_id( - vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let proofs = exec_scopes.get::>(vars::scopes::PROOFS)?; - - let chain_id = proofs[proofs.len() - 1].mmr_meta.chain_id; - - insert_value_from_var_name( - vars::ids::CHAIN_ID, - MaybeRelocatable::Int(chain_id.into()), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, - ) -} - -pub const HINT_VM_ENTER_SCOPE: &str = "vm_enter_scope({'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager})"; +pub const HINT_VM_ENTER_SCOPE: &str = "vm_enter_scope({'batch': proofs, '__dict_manager': __dict_manager})"; pub fn hint_vm_enter_scope( _vm: &mut VirtualMachine, @@ -61,9 +16,9 @@ pub fn hint_vm_enter_scope( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let proofs = exec_scopes.get::>(vars::scopes::PROOFS)?; + let proofs = exec_scopes.get::(vars::scopes::PROOFS)?; - let batch: Box = Box::new(proofs[proofs.len() - 1].clone()); + let batch: Box = Box::new(proofs); let dict_manager: Box = Box::new(exec_scopes.get::(vars::scopes::DICT_MANAGER)?); exec_scopes.enter_scope(HashMap::from([ (String::from(vars::scopes::BATCH), batch), @@ -72,3 +27,16 @@ pub fn hint_vm_enter_scope( Ok(()) } + +pub const HINT_HEADERS_WITH_MMR_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.headers_with_mmr))"; + +pub fn hint_headers_with_mmr_headers_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let proofs = exec_scopes.get::(vars::scopes::PROOF)?; + + insert_value_into_ap(vm, Felt252::from(proofs.headers_with_mmr.len())) +} diff --git a/crates/hdp_hint_processor/src/hints/vars.rs b/crates/hdp_hint_processor/src/hints/vars.rs index 2e4f1046..190e849a 100644 --- a/crates/hdp_hint_processor/src/hints/vars.rs +++ b/crates/hdp_hint_processor/src/hints/vars.rs @@ -12,6 +12,7 @@ pub mod scopes { pub const STORAGE: &str = "storage"; pub const SYSCALL_HANDLER: &str = "syscall_handler"; pub const TRANSACTION: &str = "transaction"; + pub const HEADER_WITH_MMR: &str = "header_with_mmr"; } pub mod ids { diff --git a/crates/provider/src/indexer/types.rs b/crates/provider/src/indexer/types.rs index a2fcc4ae..860e75e3 100644 --- a/crates/provider/src/indexer/types.rs +++ b/crates/provider/src/indexer/types.rs @@ -59,6 +59,7 @@ pub struct IndexerQuery { pub is_whole_tree: bool, pub is_rlp_included: bool, pub is_pure_rlp: bool, + pub prefer_native_block_header: bool, } impl IndexerQuery { @@ -74,6 +75,7 @@ impl IndexerQuery { is_whole_tree: true, is_rlp_included: true, is_pure_rlp: true, + prefer_native_block_header: false, } } } diff --git a/src/types.cairo b/src/types.cairo index 762bfc2d..baef9a28 100644 --- a/src/types.cairo +++ b/src/types.cairo @@ -11,7 +11,6 @@ struct MMRMeta { id: felt, root: felt, size: felt, - chain_id: felt, } struct ModuleTask { diff --git a/src/utils/utils.cairo b/src/utils/utils.cairo index 035b971d..aea4cca3 100644 --- a/src/utils/utils.cairo +++ b/src/utils/utils.cairo @@ -39,7 +39,6 @@ func write_output_ptr{output_ptr: felt*}( assert [output_ptr + counter * 4] = mmr_metas[counter].id; assert [output_ptr + counter * 4 + 1] = mmr_metas[counter].size; - assert [output_ptr + counter * 4 + 2] = mmr_metas[counter].chain_id; assert [output_ptr + counter * 4 + 3] = mmr_metas[counter].root; [ap] = counter + 1, ap++; diff --git a/src/verifiers/evm/header_verifier.cairo b/src/verifiers/evm/header_verifier.cairo index 5b1c0ede..9655c7cc 100644 --- a/src/verifiers/evm/header_verifier.cairo +++ b/src/verifiers/evm/header_verifier.cairo @@ -18,22 +18,30 @@ func verify_mmr_batches{ pow2_array: felt*, evm_memorizer: DictAccess*, mmr_metas: MMRMeta*, - chain_id: felt, -}(mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { + chain_info: ChainInfo, +}(idx: felt, mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { alloc_locals; - let (mmr_meta, peaks_dict, peaks_dict_start) = validate_mmr_meta(chain_id); + if (0 == idx) { + return (mmr_meta_idx=mmr_meta_idx); + } + + %{ vm_enter_scope({'header_with_mmr': batch.header_with_mmr[ids.idx], '__dict_manager': __dict_manager}) %} + + let (mmr_meta, peaks_dict, peaks_dict_start) = validate_mmr_meta(); assert mmr_metas[mmr_meta_idx] = mmr_meta; - local n_header_proofs: felt = nondet %{ len(batch.headers) %}; + local n_header_proofs: felt = nondet %{ len(header_with_mmr.headers) %}; with mmr_meta, peaks_dict { verify_headers_with_mmr_peaks(n_header_proofs); } + %{ vm_exit_scope() %} + // Ensure the peaks dict for this batch is finalized default_dict_finalize(peaks_dict_start, peaks_dict, -1); - return (mmr_meta_idx=mmr_meta_idx + 1); + return verify_mmr_batches(idx=idx - 1, mmr_meta_idx=mmr_meta_idx + 1); } // Guard function that verifies the inclusion of headers in the MMR. @@ -48,6 +56,7 @@ func verify_headers_with_mmr_peaks{ bitwise_ptr: BitwiseBuiltin*, pow2_array: felt*, evm_memorizer: DictAccess*, + chain_info: ChainInfo, mmr_meta: MMRMeta, peaks_dict: DictAccess*, }(idx: felt) { @@ -58,7 +67,7 @@ func verify_headers_with_mmr_peaks{ let (rlp) = alloc(); %{ - header = batch.headers[ids.idx - 1] + header = header_with_mmr.headers[ids.idx - 1] segments.write_arg(ids.rlp, [int(x, 16) for x in header.rlp]) %} @@ -76,9 +85,7 @@ func verify_headers_with_mmr_peaks{ // add to memorizer let block_number = HeaderDecoder.get_block_number(rlp); - let memorizer_key = EvmHashParams.header( - chain_id=mmr_meta.chain_id, block_number=block_number - ); + let memorizer_key = EvmHashParams.header(chain_id=chain_info.id, block_number=block_number); EvmMemorizer.add(key=memorizer_key, data=rlp); return verify_headers_with_mmr_peaks(idx=idx - 1); @@ -103,7 +110,7 @@ func verify_headers_with_mmr_peaks{ // add to memorizer let block_number = HeaderDecoder.get_block_number(rlp); - let memorizer_key = EvmHashParams.header(chain_id=mmr_meta.chain_id, block_number=block_number); + let memorizer_key = EvmHashParams.header(chain_id=chain_info.id, block_number=block_number); EvmMemorizer.add(key=memorizer_key, data=rlp); return verify_headers_with_mmr_peaks(idx=idx - 1); diff --git a/src/verifiers/evm/verify.cairo b/src/verifiers/evm/verify.cairo index 65527160..a0205776 100644 --- a/src/verifiers/evm/verify.cairo +++ b/src/verifiers/evm/verify.cairo @@ -3,11 +3,10 @@ from src.verifiers.evm.storage_item_verifier import verify_storage_items from src.verifiers.evm.header_verifier import verify_mmr_batches from src.verifiers.evm.block_tx_verifier import verify_block_tx_proofs from src.verifiers.evm.receipt_verifier import verify_block_receipt_proofs - from starkware.cairo.common.dict_access import DictAccess from starkware.cairo.common.cairo_builtins import PoseidonBuiltin, BitwiseBuiltin, KeccakBuiltin - from src.types import MMRMeta, ChainInfo +from src.utils.chain_info import fetch_chain_info func run_state_verification{ range_check_ptr, @@ -17,27 +16,27 @@ func run_state_verification{ pow2_array: felt*, evm_memorizer: DictAccess*, mmr_metas: MMRMeta*, - chain_info: ChainInfo, }(mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { alloc_locals; - // Step 1: Verify MMR and headers inclusion - let chain_id = chain_info.id; - with chain_id { - let (mmr_meta_idx) = verify_mmr_batches(mmr_meta_idx); - } + let (chain_info) = fetch_chain_info(11155111); + with chain_info { + // Step 1: Verify MMR and headers inclusion + local n_proofs: felt = nondet %{ len(batch.header_with_mmr) %}; + let (mmr_meta_idx) = verify_mmr_batches(n_proofs, mmr_meta_idx); - // Step 2: Verify the accounts - verify_accounts(); + // Step 2: Verify the accounts + verify_accounts(); - // Step 3: Verify the storage items - verify_storage_items(); + // Step 3: Verify the storage items + verify_storage_items(); - // Step 4: Verify the block tx proofs - verify_block_tx_proofs(); + // Step 4: Verify the block tx proofs + verify_block_tx_proofs(); - // Step 5: Verify the block receipt proofs - verify_block_receipt_proofs(); + // Step 5: Verify the block receipt proofs + verify_block_receipt_proofs(); + } return (mmr_meta_idx=mmr_meta_idx); } diff --git a/src/verifiers/mmr_verifier.cairo b/src/verifiers/mmr_verifier.cairo index 12b2197c..df4b151b 100644 --- a/src/verifiers/mmr_verifier.cairo +++ b/src/verifiers/mmr_verifier.cairo @@ -16,9 +16,9 @@ from packages.eth_essentials.lib.mmr import ( // 2. mmr_peaks_len matches the expected value based on mmr_size // 3. mmr_peaks, mmr_size recreate the mmr_root // It writes the peaks to the dict and returns the mmr_meta. -func validate_mmr_meta{range_check_ptr, poseidon_ptr: PoseidonBuiltin*, pow2_array: felt*}( - chain_id: felt -) -> (mmr_meta: MMRMeta, dict: DictAccess*, dict_start: DictAccess*) { +func validate_mmr_meta{range_check_ptr, poseidon_ptr: PoseidonBuiltin*, pow2_array: felt*}() -> ( + mmr_meta: MMRMeta, dict: DictAccess*, dict_start: DictAccess* +) { alloc_locals; let (local dict: DictAccess*) = default_dict_new(default_value=-1); @@ -29,12 +29,11 @@ func validate_mmr_meta{range_check_ptr, poseidon_ptr: PoseidonBuiltin*, pow2_arr local peaks_len: felt; %{ - memory[ids.mmr_meta._reference_value + 0] = batch.mmr_meta.id - memory[ids.mmr_meta._reference_value + 1] = batch.mmr_meta.root - memory[ids.mmr_meta._reference_value + 2] = batch.mmr_meta.size - memory[ids.mmr_meta._reference_value + 3] = batch.mmr_meta.chain_id - ids.peaks_len = len(batch.mmr_meta.peaks) - segments.write_arg(ids.peaks, batch.mmr_meta.peaks) + memory[ids.mmr_meta._reference_value + 0] = header_with_mmr.mmr_meta.id + memory[ids.mmr_meta._reference_value + 1] = header_with_mmr.mmr_meta.root + memory[ids.mmr_meta._reference_value + 2] = header_with_mmr.mmr_meta.size + ids.peaks_len = len(header_with_mmr.mmr_meta.peaks) + segments.write_arg(ids.peaks, header_with_mmr.mmr_meta.peaks) %} assert_mmr_size_is_valid(mmr_meta.size); diff --git a/src/verifiers/starknet/header_verifier.cairo b/src/verifiers/starknet/header_verifier.cairo index f9a1ce98..fb09152c 100644 --- a/src/verifiers/starknet/header_verifier.cairo +++ b/src/verifiers/starknet/header_verifier.cairo @@ -6,7 +6,7 @@ from starkware.cairo.common.memcpy import memcpy from starkware.cairo.common.builtin_poseidon.poseidon import poseidon_hash_many from starkware.cairo.common.default_dict import default_dict_finalize from packages.eth_essentials.lib.mmr import hash_subtree_path -from src.types import MMRMeta +from src.types import MMRMeta, ChainInfo from src.memorizers.starknet.memorizer import StarknetMemorizer, StarknetHashParams from src.decoders.starknet.header_decoder import StarknetHeaderDecoder, StarknetHeaderFields from src.verifiers.mmr_verifier import validate_mmr_meta @@ -17,14 +17,14 @@ func verify_mmr_batches{ pow2_array: felt*, starknet_memorizer: DictAccess*, mmr_metas: MMRMeta*, - chain_id: felt, + chain_info: ChainInfo, }(mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { alloc_locals; - let (mmr_meta, peaks_dict, peaks_dict_start) = validate_mmr_meta(chain_id); + let (mmr_meta, peaks_dict, peaks_dict_start) = validate_mmr_meta(); assert mmr_metas[mmr_meta_idx] = mmr_meta; - local n_header_proofs: felt = nondet %{ len(batch.headers) %}; + local n_header_proofs: felt = nondet %{ len(batch.header_with_mmr.headers) %}; with mmr_meta, peaks_dict { verify_headers_with_mmr_peaks(n_header_proofs); } @@ -45,6 +45,7 @@ func verify_headers_with_mmr_peaks{ range_check_ptr, poseidon_ptr: PoseidonBuiltin*, pow2_array: felt*, + chain_info: ChainInfo, mmr_meta: MMRMeta, starknet_memorizer: DictAccess*, peaks_dict: DictAccess*, @@ -56,7 +57,7 @@ func verify_headers_with_mmr_peaks{ let (fields) = alloc(); %{ - header = batch.headers[ids.idx - 1] + header = batch.header_with_mmr.headers[ids.idx - 1] segments.write_arg(ids.fields, [int(x, 16) for x in header.fields]) %} @@ -74,7 +75,7 @@ func verify_headers_with_mmr_peaks{ // add to memorizer let block_number = [fields + 1]; - let memorizer_key = StarknetHashParams.header(mmr_meta.chain_id, block_number); + let memorizer_key = StarknetHashParams.header(chain_info.id, block_number); StarknetMemorizer.add(key=memorizer_key, data=fields); return verify_headers_with_mmr_peaks(idx=idx - 1); @@ -105,7 +106,7 @@ func verify_headers_with_mmr_peaks{ let (block_number) = StarknetHeaderDecoder.get_field( length_and_fields, StarknetHeaderFields.BLOCK_NUMBER ); - let memorizer_key = StarknetHashParams.header(mmr_meta.chain_id, block_number); + let memorizer_key = StarknetHashParams.header(chain_info.id, block_number); StarknetMemorizer.add(key=memorizer_key, data=length_and_fields); return verify_headers_with_mmr_peaks(idx=idx - 1); diff --git a/src/verifiers/verify.cairo b/src/verifiers/verify.cairo index 521272c3..ce73dd72 100644 --- a/src/verifiers/verify.cairo +++ b/src/verifiers/verify.cairo @@ -26,49 +26,11 @@ func run_state_verification{ }() -> (mmr_metas_len: felt) { alloc_locals; - local batch_len: felt; - %{ ids.batch_len = len(proofs) %} - let (mmr_meta_idx) = run_state_verification_inner(batch_len, 0); + %{ vm_enter_scope({'batch': proofs, '__dict_manager': __dict_manager}) %} - return (mmr_metas_len=mmr_meta_idx); -} + let (mmr_meta_idx) = evm_run_state_verification(0); -func run_state_verification_inner{ - range_check_ptr, - pedersen_ptr: HashBuiltin*, - poseidon_ptr: PoseidonBuiltin*, - keccak_ptr: KeccakBuiltin*, - bitwise_ptr: BitwiseBuiltin*, - pow2_array: felt*, - evm_memorizer: DictAccess*, - starknet_memorizer: DictAccess*, - mmr_metas: MMRMeta*, -}(batch_len: felt, mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { - alloc_locals; - if (batch_len == 0) { - return (mmr_meta_idx=mmr_meta_idx); - } - - local chain_id: felt; - %{ ids.chain_id = proofs[ids.batch_len - 1].mmr_meta.chain_id %} + %{ vm_exit_scope() %} - let (chain_info) = fetch_chain_info(chain_id); - - if (chain_info.layout == 0) { - %{ vm_enter_scope({'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager}) %} - with chain_info { - let (mmr_meta_idx) = evm_run_state_verification(mmr_meta_idx); - } - %{ vm_exit_scope() %} - - return run_state_verification_inner(batch_len=batch_len - 1, mmr_meta_idx=mmr_meta_idx); - } else { - %{ vm_enter_scope({'batch': proofs[ids.batch_len - 1], '__dict_manager': __dict_manager}) %} - with chain_info { - let (mmr_meta_idx) = starknet_run_state_verification(mmr_meta_idx); - } - %{ vm_exit_scope() %} - - return run_state_verification_inner(batch_len=batch_len - 1, mmr_meta_idx=mmr_meta_idx); - } + return (mmr_metas_len=mmr_meta_idx); } From def5bcc436b2c0ecac9adb5f654f0f2c405fe6e3 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 17 Dec 2024 15:01:34 +0100 Subject: [PATCH 40/75] sound_run --- Cargo.lock | 11 +++++ Cargo.toml | 3 +- README.md | 2 + crates/dry_run/src/lib.rs | 16 ------- crates/dry_run/src/main.rs | 23 ++++++++-- crates/sound_run/Cargo.toml | 11 +++++ crates/sound_run/src/main.rs | 85 ++++++++++++++++++++++++++++++++++++ 7 files changed, 130 insertions(+), 21 deletions(-) delete mode 100644 crates/dry_run/src/lib.rs create mode 100644 crates/sound_run/Cargo.toml create mode 100644 crates/sound_run/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 2fbba276..e06b0db4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4534,6 +4534,17 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "sound_run" +version = "0.1.0" +dependencies = [ + "cairo-vm", + "clap", + "hdp_hint_processor", + "serde_json", + "thiserror 1.0.69", +] + [[package]] name = "spin" version = "0.9.8" diff --git a/Cargo.toml b/Cargo.toml index 321d5d0d..f32d4299 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,9 +4,10 @@ resolver = "2" members = [ "crates/cairo_types", "crates/dry_run", - "crates/hdp_hint_processor", "crates/fetcher", + "crates/hdp_hint_processor", "crates/provider", + "crates/sound_run", ] [workspace.dependencies] diff --git a/README.md b/README.md index 394cfae4..c7e0816a 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ To run the program, use: ```bash cargo run --bin dry_run -- build/compiled_cairo_files/contract_dry_run.json --program_input rust_input.json --program_output a.json --layout all_cairo + +cargo run --bin fetcher -- a.json --program_output b.json ``` The program will output the results root and tasks root. These roots can be used to extract the results from the on-chain contract. diff --git a/crates/dry_run/src/lib.rs b/crates/dry_run/src/lib.rs deleted file mode 100644 index 5f977d5f..00000000 --- a/crates/dry_run/src/lib.rs +++ /dev/null @@ -1,16 +0,0 @@ -use cairo_vm::vm::errors::cairo_run_errors::CairoRunError; -use thiserror::Error; - -#[derive(Error, Debug)] -pub enum HdpOsError { - #[error(transparent)] - Args(#[from] clap::error::Error), - #[error("Runner Error: {0}")] - Runner(CairoRunError), - #[error("Output Error: {0}")] - Output(String), - #[error(transparent)] - IO(#[from] std::io::Error), - #[error(transparent)] - SerdeJson(#[from] serde_json::Error), -} diff --git a/crates/dry_run/src/main.rs b/crates/dry_run/src/main.rs index 26b27958..775978b6 100644 --- a/crates/dry_run/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -1,20 +1,18 @@ #![forbid(unsafe_code)] #![allow(async_fn_in_trait)] -use std::{fs, path::PathBuf}; - use cairo_vm::{ cairo_run::CairoRunConfig, types::{layout_name::LayoutName, program::Program}, vm::{errors::vm_exception::VmException, runners::cairo_runner::CairoRunner}, }; use clap::{Parser, ValueHint}; -use dry_run::HdpOsError; use hdp_hint_processor::{ self, hint_processor::CustomHintProcessor, hints::vars, syscall_handler::evm::dryrun::{SyscallHandler, SyscallHandlerWrapper}, }; +use std::path::PathBuf; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] @@ -71,7 +69,7 @@ fn main() -> Result<(), HdpOsError> { .map_err(|err| VmException::from_vm_error(&cairo_runner, err)) .map_err(|e| HdpOsError::Runner(e.into()))?; - fs::write( + std::fs::write( args.program_output, serde_json::to_vec::( &cairo_runner @@ -88,3 +86,20 @@ fn main() -> Result<(), HdpOsError> { Ok(()) } + +use cairo_vm::vm::errors::cairo_run_errors::CairoRunError; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum HdpOsError { + #[error(transparent)] + Args(#[from] clap::error::Error), + #[error("Runner Error: {0}")] + Runner(CairoRunError), + #[error("Output Error: {0}")] + Output(String), + #[error(transparent)] + IO(#[from] std::io::Error), + #[error(transparent)] + SerdeJson(#[from] serde_json::Error), +} diff --git a/crates/sound_run/Cargo.toml b/crates/sound_run/Cargo.toml new file mode 100644 index 00000000..c3106559 --- /dev/null +++ b/crates/sound_run/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "sound_run" +version = "0.1.0" +edition = "2021" + +[dependencies] +hdp_hint_processor.workspace = true +cairo-vm.workspace = true +clap.workspace = true +thiserror.workspace = true +serde_json.workspace = true \ No newline at end of file diff --git a/crates/sound_run/src/main.rs b/crates/sound_run/src/main.rs new file mode 100644 index 00000000..002a7b25 --- /dev/null +++ b/crates/sound_run/src/main.rs @@ -0,0 +1,85 @@ +#![forbid(unsafe_code)] +#![allow(async_fn_in_trait)] +use cairo_vm::{ + cairo_run::CairoRunConfig, + types::{layout_name::LayoutName, program::Program}, + vm::{errors::vm_exception::VmException, runners::cairo_runner::CairoRunner}, +}; +use clap::{Parser, ValueHint}; +use hdp_hint_processor::{self, hint_processor::CustomHintProcessor}; +use std::path::PathBuf; + +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + #[clap(value_parser, value_hint=ValueHint::FilePath)] + filename: PathBuf, + /// When using dynamic layout, it's parameters must be specified through a layout params file. + #[clap(long = "layout", default_value = "plain", value_enum)] + layout: LayoutName, + #[structopt(long = "proof_mode")] + proof_mode: bool, + #[structopt(long = "program_input")] + program_input: PathBuf, + #[structopt(long = "program_output")] + program_output: PathBuf, +} + +fn main() -> Result<(), HdpOsError> { + let args = Args::try_parse_from(std::env::args()).map_err(HdpOsError::Args)?; + + // Init CairoRunConfig + let cairo_run_config = CairoRunConfig { + layout: args.layout, + relocate_mem: true, + trace_enabled: true, + ..Default::default() + }; + + let program_file = std::fs::read(args.filename).map_err(HdpOsError::IO)?; + let program_inputs = std::fs::read(args.program_input).map_err(HdpOsError::IO)?; + + // Load the Program + let program = Program::from_bytes(&program_file, Some(cairo_run_config.entrypoint)).map_err(|e| HdpOsError::Runner(e.into()))?; + + // Init cairo runner + let mut cairo_runner = CairoRunner::new( + &program, + cairo_run_config.layout, + None, + cairo_run_config.proof_mode, + cairo_run_config.trace_enabled, + ) + .map_err(|e| HdpOsError::Runner(e.into()))?; + + // Init the Cairo VM + let end = cairo_runner + .initialize(cairo_run_config.allow_missing_builtins.unwrap_or(false)) + .map_err(|e| HdpOsError::Runner(e.into()))?; + + // Run the Cairo VM + let mut hint_processor = CustomHintProcessor::new(serde_json::from_slice(&program_inputs)?); + cairo_runner + .run_until_pc(end, &mut hint_processor) + .map_err(|err| VmException::from_vm_error(&cairo_runner, err)) + .map_err(|e| HdpOsError::Runner(e.into()))?; + + Ok(()) +} + +use cairo_vm::vm::errors::cairo_run_errors::CairoRunError; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum HdpOsError { + #[error(transparent)] + Args(#[from] clap::error::Error), + #[error("Runner Error: {0}")] + Runner(CairoRunError), + #[error("Output Error: {0}")] + Output(String), + #[error(transparent)] + IO(#[from] std::io::Error), + #[error(transparent)] + SerdeJson(#[from] serde_json::Error), +} From 7b57649372e7255fa1d5962ce1a5669cf9f2209d Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 17 Dec 2024 15:37:57 +0100 Subject: [PATCH 41/75] major crates reorg --- Cargo.lock | 48 ++++++ Cargo.toml | 4 + crates/dry_run/Cargo.toml | 4 +- crates/dry_run/src/main.rs | 2 +- crates/fetcher/Cargo.toml | 3 +- crates/fetcher/src/main.rs | 6 +- crates/fetcher/src/proof_keys.rs | 20 ++- crates/hdp_hint_processor/Cargo.toml | 4 +- .../src/hint_processor/dry_run_input.rs | 8 +- .../src/hint_processor/mod.rs | 146 +++++++++--------- .../src/hint_processor/output.rs | 2 +- .../src/hint_processor/run_input.rs | 8 +- .../contract_bootloader/syscall_handler.rs | 53 ------- crates/hdp_hint_processor/src/hints/mod.rs | 2 - crates/hdp_hint_processor/src/lib.rs | 2 +- .../lib/contract_bootloader => }/scopes.rs | 3 +- .../src/syscall_handler/keys/account.rs | 5 +- .../src/syscall_handler/keys/header.rs | 9 +- .../src/syscall_handler/keys/mod.rs | 2 - .../src/syscall_handler/keys/storage.rs | 5 +- .../src/syscall_handler/mod.rs | 55 +++++++ crates/hints/Cargo.toml | 30 ++++ .../src}/contract_bootloader/builtins.rs | 2 +- .../contract_bootloader/contract_class.rs | 2 +- .../src}/contract_bootloader/dict_manager.rs | 3 +- .../src}/contract_bootloader/mod.rs | 2 - .../src}/contract_bootloader/params.rs | 3 +- .../src}/contract_bootloader/program.rs | 2 +- .../src}/decoder/evm/has_type_prefix.rs | 0 .../src}/decoder/evm/is_byzantium.rs | 0 .../lib => hints/src}/decoder/evm/mod.rs | 0 .../src}/decoder/evm/v_is_encoded.rs | 0 .../hints/lib => hints/src}/decoder/mod.rs | 0 .../src/hints/lib/mod.rs => hints/src/lib.rs} | 1 + .../src/hints/lib => hints/src}/merkle/mod.rs | 2 +- .../src/hints/lib => hints/src}/print.rs | 2 +- .../src/hints/lib => hints/src}/rlp/divmod.rs | 3 +- .../hints/lib => hints/src}/rlp/item_type.rs | 3 +- .../src/hints/lib => hints/src}/rlp/mod.rs | 0 .../lib => hints/src}/rlp/processed_words.rs | 3 +- .../src/hints/lib => hints/src}/segments.rs | 0 .../src/hints/lib => hints/src}/utils/mod.rs | 0 .../src/hints => hints/src}/vars.rs | 0 .../src}/verifiers/evm/account_verifier.rs | 13 +- .../src}/verifiers/evm/header_verifier.rs | 7 +- .../lib => hints/src}/verifiers/evm/mod.rs | 0 .../src}/verifiers/evm/receipt_verifier.rs | 7 +- .../verifiers/evm/storage_item_verifier.rs | 13 +- .../verifiers/evm/transaction_verifier.rs | 13 +- .../hints/lib => hints/src}/verifiers/mod.rs | 0 .../lib => hints/src}/verifiers/utils.rs | 3 +- .../lib => hints/src}/verifiers/verify.rs | 3 +- crates/types/Cargo.toml | 15 ++ .../models/mod.rs => types/src/lib.rs} | 0 .../models => types/src}/param.rs | 0 .../models => types/src}/proofs/account.rs | 0 .../models => types/src}/proofs/header.rs | 0 .../models => types/src}/proofs/mmr.rs | 0 .../models => types/src}/proofs/mod.rs | 0 .../models => types/src}/proofs/mpt.rs | 0 .../models => types/src}/proofs/receipt.rs | 0 .../models => types/src}/proofs/storage.rs | 0 .../src}/proofs/transaction.rs | 0 63 files changed, 292 insertions(+), 231 deletions(-) delete mode 100644 crates/hdp_hint_processor/src/hints/lib/contract_bootloader/syscall_handler.rs delete mode 100644 crates/hdp_hint_processor/src/hints/mod.rs rename crates/hdp_hint_processor/src/{hints/lib/contract_bootloader => }/scopes.rs (91%) create mode 100644 crates/hints/Cargo.toml rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/contract_bootloader/builtins.rs (99%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/contract_bootloader/contract_class.rs (99%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/contract_bootloader/dict_manager.rs (97%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/contract_bootloader/mod.rs (70%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/contract_bootloader/params.rs (95%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/contract_bootloader/program.rs (98%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/decoder/evm/has_type_prefix.rs (100%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/decoder/evm/is_byzantium.rs (100%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/decoder/evm/mod.rs (100%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/decoder/evm/v_is_encoded.rs (100%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/decoder/mod.rs (100%) rename crates/{hdp_hint_processor/src/hints/lib/mod.rs => hints/src/lib.rs} (91%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/merkle/mod.rs (99%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/print.rs (97%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/rlp/divmod.rs (99%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/rlp/item_type.rs (99%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/rlp/mod.rs (100%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/rlp/processed_words.rs (97%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/segments.rs (100%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/utils/mod.rs (100%) rename crates/{hdp_hint_processor/src/hints => hints/src}/vars.rs (100%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/verifiers/evm/account_verifier.rs (97%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/verifiers/evm/header_verifier.rs (97%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/verifiers/evm/mod.rs (100%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/verifiers/evm/receipt_verifier.rs (97%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/verifiers/evm/storage_item_verifier.rs (97%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/verifiers/evm/transaction_verifier.rs (96%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/verifiers/mod.rs (100%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/verifiers/utils.rs (98%) rename crates/{hdp_hint_processor/src/hints/lib => hints/src}/verifiers/verify.rs (96%) create mode 100644 crates/types/Cargo.toml rename crates/{hdp_hint_processor/src/hint_processor/models/mod.rs => types/src/lib.rs} (100%) rename crates/{hdp_hint_processor/src/hint_processor/models => types/src}/param.rs (100%) rename crates/{hdp_hint_processor/src/hint_processor/models => types/src}/proofs/account.rs (100%) rename crates/{hdp_hint_processor/src/hint_processor/models => types/src}/proofs/header.rs (100%) rename crates/{hdp_hint_processor/src/hint_processor/models => types/src}/proofs/mmr.rs (100%) rename crates/{hdp_hint_processor/src/hint_processor/models => types/src}/proofs/mod.rs (100%) rename crates/{hdp_hint_processor/src/hint_processor/models => types/src}/proofs/mpt.rs (100%) rename crates/{hdp_hint_processor/src/hint_processor/models => types/src}/proofs/receipt.rs (100%) rename crates/{hdp_hint_processor/src/hint_processor/models => types/src}/proofs/storage.rs (100%) rename crates/{hdp_hint_processor/src/hint_processor/models => types/src}/proofs/transaction.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index e06b0db4..45e4a75f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2059,6 +2059,7 @@ dependencies = [ "cairo-vm", "clap", "hdp_hint_processor", + "hints", "serde_json", "thiserror 1.0.69", ] @@ -2178,6 +2179,7 @@ dependencies = [ "serde_json", "thiserror 1.0.69", "tokio", + "types", ] [[package]] @@ -2514,6 +2516,7 @@ dependencies = [ "cairo-vm", "cairo_types", "hex", + "hints", "num-bigint", "num-traits", "provider", @@ -2528,6 +2531,7 @@ dependencies = [ "strum_macros", "thiserror 1.0.69", "tokio", + "types", ] [[package]] @@ -2563,6 +2567,35 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" +[[package]] +name = "hints" +version = "0.1.0" +dependencies = [ + "alloy", + "alloy-rlp", + "bincode", + "cairo-lang-casm", + "cairo-lang-starknet-classes", + "cairo-type-derive", + "cairo-vm", + "cairo_types", + "hex", + "num-bigint", + "num-traits", + "rand", + "reqwest", + "serde", + "serde_json", + "serde_with 3.11.0", + "starknet-core", + "starknet-crypto 0.7.3", + "starknet-types-core", + "strum_macros", + "thiserror 1.0.69", + "tokio", + "types", +] + [[package]] name = "hmac" version = "0.12.1" @@ -5199,6 +5232,21 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +[[package]] +name = "types" +version = "0.1.0" +dependencies = [ + "alloy", + "cairo-lang-casm", + "cairo-lang-starknet-classes", + "cairo-type-derive", + "cairo-vm", + "serde", + "serde_json", + "serde_with 3.11.0", + "thiserror 1.0.69", +] + [[package]] name = "ucd-trie" version = "0.1.7" diff --git a/Cargo.toml b/Cargo.toml index f32d4299..e5b0c670 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,8 @@ members = [ "crates/fetcher", "crates/hdp_hint_processor", "crates/provider", + "crates/hints", + "crates/types", "crates/sound_run", ] @@ -39,3 +41,5 @@ reqwest = "0.12.9" hdp_hint_processor = { path = "crates/hdp_hint_processor" } provider = { path = "crates/provider" } cairo_types = { path = "crates/cairo_types" } +types = { path = "crates/types" } +hints = { path = "crates/hints" } \ No newline at end of file diff --git a/crates/dry_run/Cargo.toml b/crates/dry_run/Cargo.toml index 0b14a736..c21fd67a 100644 --- a/crates/dry_run/Cargo.toml +++ b/crates/dry_run/Cargo.toml @@ -8,4 +8,6 @@ hdp_hint_processor.workspace = true cairo-vm.workspace = true clap.workspace = true thiserror.workspace = true -serde_json.workspace = true \ No newline at end of file +serde_json.workspace = true + +hints.workspace = true \ No newline at end of file diff --git a/crates/dry_run/src/main.rs b/crates/dry_run/src/main.rs index 775978b6..a8b78c40 100644 --- a/crates/dry_run/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -9,9 +9,9 @@ use clap::{Parser, ValueHint}; use hdp_hint_processor::{ self, hint_processor::CustomHintProcessor, - hints::vars, syscall_handler::evm::dryrun::{SyscallHandler, SyscallHandlerWrapper}, }; +use hints::vars; use std::path::PathBuf; #[derive(Parser, Debug)] diff --git a/crates/fetcher/Cargo.toml b/crates/fetcher/Cargo.toml index 6d78a2a9..444a2815 100644 --- a/crates/fetcher/Cargo.toml +++ b/crates/fetcher/Cargo.toml @@ -13,4 +13,5 @@ serde_json.workspace = true alloy.workspace = true hex.workspace = true -provider.workspace = true \ No newline at end of file +provider.workspace = true +types.workspace = true \ No newline at end of file diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index 0d174223..f47516ec 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -2,11 +2,9 @@ #![allow(async_fn_in_trait)] use clap::{Parser, ValueHint}; use fetcher::{proof_keys::ProofKeys, FetcherError}; -use hdp_hint_processor::{ - hint_processor::models::proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}, - syscall_handler::evm::{self, dryrun::SyscallHandler}, -}; +use hdp_hint_processor::syscall_handler::evm::{self, dryrun::SyscallHandler}; use std::{collections::HashSet, fs, path::PathBuf}; +use types::proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}; pub mod proof_keys; diff --git a/crates/fetcher/src/proof_keys.rs b/crates/fetcher/src/proof_keys.rs index d6d0b965..0d980a62 100644 --- a/crates/fetcher/src/proof_keys.rs +++ b/crates/fetcher/src/proof_keys.rs @@ -4,17 +4,7 @@ use alloy::{ providers::{Provider, RootProvider}, transports::http::{reqwest::Url, Client, Http}, }; -use hdp_hint_processor::{ - hint_processor::models::proofs::{ - account::Account, - header::{Header, HeaderProof}, - mmr::MmrMeta, - mpt::MPTProof, - storage::Storage, - HeaderMmrMeta, - }, - syscall_handler::keys, -}; +use hdp_hint_processor::syscall_handler::keys; use provider::{ indexer::{ types::{BlockHeader, IndexerQuery}, @@ -23,6 +13,14 @@ use provider::{ RPC, }; use std::{collections::HashSet, env}; +use types::proofs::{ + account::Account, + header::{Header, HeaderProof}, + mmr::MmrMeta, + mpt::MPTProof, + storage::Storage, + HeaderMmrMeta, +}; use crate::FetcherError; diff --git a/crates/hdp_hint_processor/Cargo.toml b/crates/hdp_hint_processor/Cargo.toml index 25bcb7e2..9981f92a 100644 --- a/crates/hdp_hint_processor/Cargo.toml +++ b/crates/hdp_hint_processor/Cargo.toml @@ -27,4 +27,6 @@ strum_macros.workspace = true starknet-core.workspace = true provider.workspace = true -cairo_types.workspace = true \ No newline at end of file +cairo_types.workspace = true +types.workspace = true +hints.workspace = true \ No newline at end of file diff --git a/crates/hdp_hint_processor/src/hint_processor/dry_run_input.rs b/crates/hdp_hint_processor/src/hint_processor/dry_run_input.rs index ec92257a..02f98eb8 100644 --- a/crates/hdp_hint_processor/src/hint_processor/dry_run_input.rs +++ b/crates/hdp_hint_processor/src/hint_processor/dry_run_input.rs @@ -1,8 +1,4 @@ -use super::{ - models::{param::Param, HDPDryRunInput}, - CustomHintProcessor, -}; -use crate::hints::vars; +use super::CustomHintProcessor; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use cairo_vm::{ hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData, @@ -10,7 +6,9 @@ use cairo_vm::{ vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; +use hints::vars; use std::collections::HashMap; +use types::{param::Param, HDPDryRunInput}; pub const HINT_DRY_RUN_INPUT: &str = "from tools.py.schema import HDPDryRunInput\ndry_run_input = HDPDryRunInput.Schema().load(program_input)\nparams = dry_run_input.params\ncompiled_class = dry_run_input.compiled_class"; diff --git a/crates/hdp_hint_processor/src/hint_processor/mod.rs b/crates/hdp_hint_processor/src/hint_processor/mod.rs index c825421a..b79d450f 100644 --- a/crates/hdp_hint_processor/src/hint_processor/mod.rs +++ b/crates/hdp_hint_processor/src/hint_processor/mod.rs @@ -1,11 +1,10 @@ pub mod dry_run_input; -pub mod models; pub mod output; pub mod run_input; use crate::{ - hints::{lib, vars}, - syscall_handler::evm::dryrun::SyscallHandlerWrapper, + scopes, + syscall_handler::{self, evm::dryrun::SyscallHandlerWrapper}, }; use cairo_lang_casm::{ hints::{Hint, StarknetHint}, @@ -21,6 +20,7 @@ use cairo_vm::{ vm::{errors::hint_errors::HintError, runners::cairo_runner::ResourceTracker, vm_core::VirtualMachine}, Felt252, }; +use hints::{contract_bootloader, decoder, merkle, print, rlp, segments, vars, verifiers}; use starknet_types_core::felt::Felt; use std::{any::Any, collections::HashMap}; @@ -60,82 +60,82 @@ impl CustomHintProcessor { #[rustfmt::skip] fn hints() -> HashMap { let mut hints = HashMap::::new(); - hints.insert(lib::contract_bootloader::contract_class::LOAD_CONTRACT_CLASS.into(), lib::contract_bootloader::contract_class::load_contract_class); - hints.insert(lib::contract_bootloader::dict_manager::DICT_MANAGER_CREATE.into(), lib::contract_bootloader::dict_manager::dict_manager_create); - hints.insert(lib::contract_bootloader::params::LOAD_PARMAS.into(), lib::contract_bootloader::params::load_parmas); - hints.insert(lib::contract_bootloader::scopes::ENTER_SCOPE_SYSCALL_HANDLER.into(), lib::contract_bootloader::scopes::enter_scope_syscall_handler); - hints.insert(lib::contract_bootloader::syscall_handler::SYSCALL_HANDLER_CREATE.into(), lib::contract_bootloader::syscall_handler::syscall_handler_create); - hints.insert(lib::contract_bootloader::syscall_handler::DRY_RUN_SYSCALL_HANDLER_CREATE.into(), lib::contract_bootloader::syscall_handler::dry_run_syscall_handler_create); - hints.insert(lib::contract_bootloader::syscall_handler::SYSCALL_HANDLER_SET_SYSCALL_PTR.into(), lib::contract_bootloader::syscall_handler::syscall_handler_set_syscall_ptr); - hints.insert(lib::contract_bootloader::builtins::UPDATE_BUILTIN_PTRS.into(), lib::contract_bootloader::builtins::update_builtin_ptrs); - hints.insert(lib::contract_bootloader::builtins::SELECTED_BUILTINS.into(), lib::contract_bootloader::builtins::selected_builtins); - hints.insert(lib::contract_bootloader::builtins::SELECT_BUILTIN.into(), lib::contract_bootloader::builtins::select_builtin); - hints.insert(lib::decoder::evm::has_type_prefix::HINT_HAS_TYPE_PREFIX.into(), lib::decoder::evm::has_type_prefix::hint_has_type_prefix); - hints.insert(lib::decoder::evm::is_byzantium::HINT_IS_BYZANTIUM.into(), lib::decoder::evm::is_byzantium::hint_is_byzantium); - hints.insert(lib::decoder::evm::v_is_encoded::HINT_V_IS_ENCODED.into(), lib::decoder::evm::v_is_encoded::hint_v_is_encoded); - hints.insert(lib::merkle::HINT_TARGET_TASK_HASH.into(), lib::merkle::hint_target_task_hash); - hints.insert(lib::merkle::HINT_IS_LEFT_SMALLER.into(), lib::merkle::hint_is_left_smaller); - hints.insert(lib::rlp::divmod::HINT_DIVMOD_VALUE.into(), lib::rlp::divmod::hint_divmod_value); - hints.insert(lib::rlp::divmod::HINT_DIVMOD_RLP.into(), lib::rlp::divmod::hint_divmod_rlp); - hints.insert(lib::rlp::item_type::HINT_IS_LONG.into(), lib::rlp::item_type::hint_is_long); - hints.insert(lib::rlp::item_type::HINT_ITEM_TYPE.into(), lib::rlp::item_type::hint_item_type); - hints.insert(lib::rlp::processed_words::HINT_PROCESSED_WORDS.into(), lib::rlp::processed_words::hint_processed_words); - hints.insert(lib::print::PROGRAM_HASH.into(), lib::print::program_hash); - hints.insert(lib::segments::SEGMENTS_ADD.into(), lib::segments::segments_add); - hints.insert(lib::segments::SEGMENTS_ADD_EVM_MEMORIZER_SEGMENT_INDEX.into(), lib::segments::segments_add_evm_memorizer_segment_index); - hints.insert(lib::segments::SEGMENTS_ADD_EVM_MEMORIZER_OFFSET.into(), lib::segments::segments_add_evm_memorizer_offset); - hints.insert(lib::segments::SEGMENTS_ADD_EVM_STARKNET_MEMORIZER_INDEX.into(), lib::segments::segments_add_evm_starknet_memorizer_index); - hints.insert(lib::segments::SEGMENTS_ADD_STARKNET_MEMORIZER_OFFSET.into(), lib::segments::segments_add_starknet_memorizer_offset); - hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_KEY.into(), lib::verifiers::evm::account_verifier::hint_account_key); - hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_KEY_LEADING_ZEROS.into(), lib::verifiers::evm::account_verifier::hint_account_key_leading_zeros); - hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_AT.into(), lib::verifiers::evm::account_verifier::hint_account_proof_at); - hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BLOCK_NUMBER.into(), lib::verifiers::evm::account_verifier::hint_account_proof_block_number); - hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::account_verifier::hint_account_proof_bytes_len); - hints.insert(lib::verifiers::evm::account_verifier::HINT_ACCOUNT_PROOFS_LEN.into(), lib::verifiers::evm::account_verifier::hint_account_proofs_len); - hints.insert(lib::verifiers::evm::account_verifier::HINT_BATCH_ACCOUNTS_LEN.into(), lib::verifiers::evm::account_verifier::hint_batch_accounts_len); - hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_ACCOUNT_ADDRESS.into(), lib::verifiers::evm::account_verifier::hint_get_account_address); - hints.insert(lib::verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), lib::verifiers::evm::account_verifier::hint_get_mpt_proof); - hints.insert(lib::verifiers::evm::transaction_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), lib::verifiers::evm::transaction_verifier::hint_batch_transactions_len); - hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx); - hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX_KEY.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx_key); - hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX_KEY_LEADING_ZEROS.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx_key_leading_zeros); - hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX_PROOF_LEN.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx_proof_len); - hints.insert(lib::verifiers::evm::transaction_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), lib::verifiers::evm::transaction_verifier::hint_set_tx_block_number); - hints.insert(lib::verifiers::evm::transaction_verifier::HINT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::transaction_verifier::hint_proof_bytes_len); - hints.insert(lib::verifiers::evm::transaction_verifier::HINT_MPT_PROOF.into(), lib::verifiers::evm::transaction_verifier::hint_mpt_proof); - hints.insert(lib::verifiers::evm::header_verifier::HINT_LEAF_IDX.into(), lib::verifiers::evm::header_verifier::hint_leaf_idx); - hints.insert(lib::verifiers::evm::header_verifier::HINT_MMR_PATH_LEN.into(), lib::verifiers::evm::header_verifier::hint_mmr_path_len); - hints.insert(lib::verifiers::evm::header_verifier::HINT_MMR_PATH.into(), lib::verifiers::evm::header_verifier::hint_mmr_path); - hints.insert(lib::verifiers::evm::header_verifier::HINT_RLP_LEN.into(), lib::verifiers::evm::header_verifier::hint_rlp_len); - hints.insert(lib::verifiers::evm::header_verifier::HINT_SET_HEADER.into(), lib::verifiers::evm::header_verifier::hint_set_header); - hints.insert(lib::verifiers::evm::receipt_verifier::HINT_BATCH_RECEIPTS_LEN.into(), lib::verifiers::evm::receipt_verifier::hint_batch_receipts_len); - hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_BLOCK_NUMBER.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_block_number); - hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_key); - hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY_LEADING_ZEROS.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_key_leading_zeros); - hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_MPT_PROOF.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_mpt_proof); - hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_LEN.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_proof_len); - hints.insert(lib::verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_BYTES_LEN.into(), lib::verifiers::evm::receipt_verifier::hint_receipt_proof_bytes_len); - hints.insert(lib::verifiers::evm::receipt_verifier::HINT_SET_RECEIPT.into(), lib::verifiers::evm::receipt_verifier::hint_set_receipt); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_BATCH_STORAGES_LEN.into(), lib::verifiers::evm::storage_item_verifier::hint_batch_storages_len); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_BATCH_STORAGES.into(), lib::verifiers::evm::storage_item_verifier::hint_set_batch_storages); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_MPT_PROOF.into(), lib::verifiers::evm::storage_item_verifier::hint_set_mpt_proof); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_PROOF_LEN.into(), lib::verifiers::evm::storage_item_verifier::hint_set_proof_len); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BYTES_LEN.into(), lib::verifiers::evm::storage_item_verifier::hint_set_proof_bytes_len); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BLOCK_NUMBER.into(), lib::verifiers::evm::storage_item_verifier::hint_set_proof_block_number); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_key); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY_LEADING_ZEROS.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_key_leading_zeros); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOFS_LEN.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_proofs_len); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOF_AT.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_proof_at); - hints.insert(lib::verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_SLOT.into(), lib::verifiers::evm::storage_item_verifier::hint_set_storage_slot); - hints.insert(lib::verifiers::verify::HINT_VM_ENTER_SCOPE.into(), lib::verifiers::verify::hint_vm_enter_scope); - hints.insert(lib::verifiers::utils::HINT_PRINT_TASK_RESULT.into(), lib::verifiers::utils::hint_print_task_result); + hints.insert(contract_bootloader::contract_class::LOAD_CONTRACT_CLASS.into(), contract_bootloader::contract_class::load_contract_class); + hints.insert(contract_bootloader::dict_manager::DICT_MANAGER_CREATE.into(), contract_bootloader::dict_manager::dict_manager_create); + hints.insert(contract_bootloader::params::LOAD_PARMAS.into(), contract_bootloader::params::load_parmas); + hints.insert(contract_bootloader::builtins::UPDATE_BUILTIN_PTRS.into(), contract_bootloader::builtins::update_builtin_ptrs); + hints.insert(contract_bootloader::builtins::SELECTED_BUILTINS.into(), contract_bootloader::builtins::selected_builtins); + hints.insert(contract_bootloader::builtins::SELECT_BUILTIN.into(), contract_bootloader::builtins::select_builtin); + hints.insert(decoder::evm::has_type_prefix::HINT_HAS_TYPE_PREFIX.into(), decoder::evm::has_type_prefix::hint_has_type_prefix); + hints.insert(decoder::evm::is_byzantium::HINT_IS_BYZANTIUM.into(), decoder::evm::is_byzantium::hint_is_byzantium); + hints.insert(decoder::evm::v_is_encoded::HINT_V_IS_ENCODED.into(), decoder::evm::v_is_encoded::hint_v_is_encoded); + hints.insert(merkle::HINT_TARGET_TASK_HASH.into(), merkle::hint_target_task_hash); + hints.insert(merkle::HINT_IS_LEFT_SMALLER.into(), merkle::hint_is_left_smaller); + hints.insert(rlp::divmod::HINT_DIVMOD_VALUE.into(), rlp::divmod::hint_divmod_value); + hints.insert(rlp::divmod::HINT_DIVMOD_RLP.into(), rlp::divmod::hint_divmod_rlp); + hints.insert(rlp::item_type::HINT_IS_LONG.into(), rlp::item_type::hint_is_long); + hints.insert(rlp::item_type::HINT_ITEM_TYPE.into(), rlp::item_type::hint_item_type); + hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS.into(), rlp::processed_words::hint_processed_words); + hints.insert(print::PROGRAM_HASH.into(), print::program_hash); + hints.insert(segments::SEGMENTS_ADD.into(), segments::segments_add); + hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_SEGMENT_INDEX.into(), segments::segments_add_evm_memorizer_segment_index); + hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_OFFSET.into(), segments::segments_add_evm_memorizer_offset); + hints.insert(segments::SEGMENTS_ADD_EVM_STARKNET_MEMORIZER_INDEX.into(), segments::segments_add_evm_starknet_memorizer_index); + hints.insert(segments::SEGMENTS_ADD_STARKNET_MEMORIZER_OFFSET.into(), segments::segments_add_starknet_memorizer_offset); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY.into(), verifiers::evm::account_verifier::hint_account_key); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY_LEADING_ZEROS.into(), verifiers::evm::account_verifier::hint_account_key_leading_zeros); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_AT.into(), verifiers::evm::account_verifier::hint_account_proof_at); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BLOCK_NUMBER.into(), verifiers::evm::account_verifier::hint_account_proof_block_number); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BYTES_LEN.into(), verifiers::evm::account_verifier::hint_account_proof_bytes_len); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOFS_LEN.into(), verifiers::evm::account_verifier::hint_account_proofs_len); + hints.insert(verifiers::evm::account_verifier::HINT_BATCH_ACCOUNTS_LEN.into(), verifiers::evm::account_verifier::hint_batch_accounts_len); + hints.insert(verifiers::evm::account_verifier::HINT_GET_ACCOUNT_ADDRESS.into(), verifiers::evm::account_verifier::hint_get_account_address); + hints.insert(verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), verifiers::evm::account_verifier::hint_get_mpt_proof); + hints.insert(verifiers::evm::transaction_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), verifiers::evm::transaction_verifier::hint_batch_transactions_len); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX.into(), verifiers::evm::transaction_verifier::hint_set_tx); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY.into(), verifiers::evm::transaction_verifier::hint_set_tx_key); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY_LEADING_ZEROS.into(), verifiers::evm::transaction_verifier::hint_set_tx_key_leading_zeros); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_PROOF_LEN.into(), verifiers::evm::transaction_verifier::hint_set_tx_proof_len); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), verifiers::evm::transaction_verifier::hint_set_tx_block_number); + hints.insert(verifiers::evm::transaction_verifier::HINT_PROOF_BYTES_LEN.into(), verifiers::evm::transaction_verifier::hint_proof_bytes_len); + hints.insert(verifiers::evm::transaction_verifier::HINT_MPT_PROOF.into(), verifiers::evm::transaction_verifier::hint_mpt_proof); + hints.insert(verifiers::evm::header_verifier::HINT_LEAF_IDX.into(), verifiers::evm::header_verifier::hint_leaf_idx); + hints.insert(verifiers::evm::header_verifier::HINT_MMR_PATH_LEN.into(), verifiers::evm::header_verifier::hint_mmr_path_len); + hints.insert(verifiers::evm::header_verifier::HINT_MMR_PATH.into(), verifiers::evm::header_verifier::hint_mmr_path); + hints.insert(verifiers::evm::header_verifier::HINT_RLP_LEN.into(), verifiers::evm::header_verifier::hint_rlp_len); + hints.insert(verifiers::evm::header_verifier::HINT_SET_HEADER.into(), verifiers::evm::header_verifier::hint_set_header); + hints.insert(verifiers::evm::receipt_verifier::HINT_BATCH_RECEIPTS_LEN.into(), verifiers::evm::receipt_verifier::hint_batch_receipts_len); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_BLOCK_NUMBER.into(), verifiers::evm::receipt_verifier::hint_receipt_block_number); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY.into(), verifiers::evm::receipt_verifier::hint_receipt_key); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY_LEADING_ZEROS.into(), verifiers::evm::receipt_verifier::hint_receipt_key_leading_zeros); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_MPT_PROOF.into(), verifiers::evm::receipt_verifier::hint_receipt_mpt_proof); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_len); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_BYTES_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_bytes_len); + hints.insert(verifiers::evm::receipt_verifier::HINT_SET_RECEIPT.into(), verifiers::evm::receipt_verifier::hint_set_receipt); + hints.insert(verifiers::evm::storage_item_verifier::HINT_BATCH_STORAGES_LEN.into(), verifiers::evm::storage_item_verifier::hint_batch_storages_len); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_BATCH_STORAGES.into(), verifiers::evm::storage_item_verifier::hint_set_batch_storages); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_MPT_PROOF.into(), verifiers::evm::storage_item_verifier::hint_set_mpt_proof); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_proof_len); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BYTES_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_proof_bytes_len); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BLOCK_NUMBER.into(), verifiers::evm::storage_item_verifier::hint_set_proof_block_number); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY_LEADING_ZEROS.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key_leading_zeros); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOFS_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_storage_proofs_len); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOF_AT.into(), verifiers::evm::storage_item_verifier::hint_set_storage_proof_at); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_SLOT.into(), verifiers::evm::storage_item_verifier::hint_set_storage_slot); + hints.insert(verifiers::verify::HINT_VM_ENTER_SCOPE.into(), verifiers::verify::hint_vm_enter_scope); + hints.insert(verifiers::utils::HINT_PRINT_TASK_RESULT.into(), verifiers::utils::hint_print_task_result); + hints.insert(syscall_handler::DRY_RUN_SYSCALL_HANDLER_CREATE.into(), syscall_handler::dry_run_syscall_handler_create); + hints.insert(syscall_handler::SYSCALL_HANDLER_CREATE.into(), syscall_handler::syscall_handler_create); + hints.insert(syscall_handler::SYSCALL_HANDLER_SET_SYSCALL_PTR.into(), syscall_handler::syscall_handler_set_syscall_ptr); + hints.insert(scopes::ENTER_SCOPE_SYSCALL_HANDLER.into(), scopes::enter_scope_syscall_handler); hints } #[rustfmt::skip] fn extensive_hints() -> HashMap { let mut hints = HashMap::::new(); - hints.insert(crate::hints::lib::contract_bootloader::program::LOAD_PROGRAM.into(), crate::hints::lib::contract_bootloader::program::load_program); + hints.insert(hints::contract_bootloader::program::LOAD_PROGRAM.into(), hints::contract_bootloader::program::load_program); hints } } diff --git a/crates/hdp_hint_processor/src/hint_processor/output.rs b/crates/hdp_hint_processor/src/hint_processor/output.rs index 8fc1ffd4..b2c867f9 100644 --- a/crates/hdp_hint_processor/src/hint_processor/output.rs +++ b/crates/hdp_hint_processor/src/hint_processor/output.rs @@ -1,11 +1,11 @@ use super::CustomHintProcessor; -use crate::hints::vars; use cairo_vm::{ hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_relocatable_from_var_name}, types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; +use hints::vars; use std::collections::HashMap; pub const HINT_OUTPUT: &str = "print(\"result\", [hex(ids.result.low), hex(ids.result.high)])"; diff --git a/crates/hdp_hint_processor/src/hint_processor/run_input.rs b/crates/hdp_hint_processor/src/hint_processor/run_input.rs index 0f90f864..8685af08 100644 --- a/crates/hdp_hint_processor/src/hint_processor/run_input.rs +++ b/crates/hdp_hint_processor/src/hint_processor/run_input.rs @@ -1,8 +1,4 @@ -use super::{ - models::{param::Param, proofs::Proofs, HDPInput}, - CustomHintProcessor, -}; -use crate::hints::vars; +use super::CustomHintProcessor; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use cairo_vm::{ hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData, @@ -10,7 +6,9 @@ use cairo_vm::{ vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; +use hints::vars; use std::collections::HashMap; +use types::{param::Param, proofs::Proofs, HDPInput}; pub const HINT_RUN_INPUT: &str = "from tools.py.schema import HDPInput\nrun_input = HDPInput.Schema().load(program_input)\nproofs = run_input.proofs\nparams = run_input.params\ncompiled_class = run_input.compiled_class"; diff --git a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/syscall_handler.rs b/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/syscall_handler.rs deleted file mode 100644 index 33278e20..00000000 --- a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/syscall_handler.rs +++ /dev/null @@ -1,53 +0,0 @@ -use crate::{hints::vars, syscall_handler::evm::dryrun::SyscallHandlerWrapper}; -use cairo_vm::{ - hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_ptr_from_var_name}, - types::exec_scope::ExecutionScopes, - vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, - Felt252, -}; -use std::collections::HashMap; - -pub const SYSCALL_HANDLER_CREATE: &str = "if 'syscall_handler' not in globals():\n from contract_bootloader.syscall_handler import SyscallHandler\n syscall_handler = SyscallHandler(segments=segments, dict_manager=__dict_manager)"; - -pub fn syscall_handler_create( - _vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - _hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - if let Err(HintError::VariableNotInScopeError(_)) = exec_scopes.get::(vars::scopes::SYSCALL_HANDLER) { - let syscall_handler = SyscallHandlerWrapper::new(); - exec_scopes.insert_value(vars::scopes::SYSCALL_HANDLER, syscall_handler); - } - - Ok(()) -} - -pub const DRY_RUN_SYSCALL_HANDLER_CREATE: &str = "from contract_bootloader.dryrun_syscall_handler import DryRunSyscallHandler\nsyscall_handler = DryRunSyscallHandler(segments=segments, dict_manager=__dict_manager)"; - -pub fn dry_run_syscall_handler_create( - _vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - _hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let syscall_handler = SyscallHandlerWrapper::new(); - exec_scopes.insert_value(vars::scopes::SYSCALL_HANDLER, syscall_handler); - - Ok(()) -} - -pub const SYSCALL_HANDLER_SET_SYSCALL_PTR: &str = "syscall_handler.set_syscall_ptr(syscall_ptr=ids.syscall_ptr)"; - -pub fn syscall_handler_set_syscall_ptr( - vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let syscall_ptr = get_ptr_from_var_name(vars::ids::SYSCALL_PTR, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let syscall_handler = exec_scopes.get_mut_ref::(vars::scopes::SYSCALL_HANDLER)?; - syscall_handler.set_syscall_ptr(syscall_ptr); - - Ok(()) -} diff --git a/crates/hdp_hint_processor/src/hints/mod.rs b/crates/hdp_hint_processor/src/hints/mod.rs deleted file mode 100644 index c7a7e1c3..00000000 --- a/crates/hdp_hint_processor/src/hints/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod lib; -pub mod vars; diff --git a/crates/hdp_hint_processor/src/lib.rs b/crates/hdp_hint_processor/src/lib.rs index 61b2a2ba..2abbd59a 100644 --- a/crates/hdp_hint_processor/src/lib.rs +++ b/crates/hdp_hint_processor/src/lib.rs @@ -1,7 +1,7 @@ #![forbid(unsafe_code)] #![allow(async_fn_in_trait)] pub mod hint_processor; -pub mod hints; +pub mod scopes; pub mod syscall_handler; #[cfg(test)] diff --git a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/scopes.rs b/crates/hdp_hint_processor/src/scopes.rs similarity index 91% rename from crates/hdp_hint_processor/src/hints/lib/contract_bootloader/scopes.rs rename to crates/hdp_hint_processor/src/scopes.rs index c92c3d9d..4aad0d64 100644 --- a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/scopes.rs +++ b/crates/hdp_hint_processor/src/scopes.rs @@ -1,10 +1,11 @@ -use crate::{hints::vars, syscall_handler::evm::dryrun::SyscallHandlerWrapper}; +use crate::syscall_handler::evm::dryrun::SyscallHandlerWrapper; use cairo_vm::{ hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData, types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; +use hints::vars; use std::{any::Any, collections::HashMap}; pub const ENTER_SCOPE_SYSCALL_HANDLER: &str = "vm_enter_scope({'syscall_handler': syscall_handler})"; diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs index 0f348f78..f02e7de5 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs @@ -1,7 +1,4 @@ -use crate::{ - hint_processor::models::proofs::{self, mpt::MPTProof}, - syscall_handler::utils::SyscallExecutionError, -}; +use crate::syscall_handler::utils::SyscallExecutionError; use alloy::{ consensus::Account, primitives::{Address, BlockNumber, ChainId}, diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs index 2acd19b3..e1978ada 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs @@ -1,12 +1,5 @@ use super::{account, storage, FetchValue}; -use crate::{ - hint_processor::models::proofs::{ - self, - header::{Header, HeaderProof}, - mmr::MmrMeta, - }, - syscall_handler::utils::SyscallExecutionError, -}; +use crate::syscall_handler::utils::SyscallExecutionError; use alloy::{ hex::FromHexError, primitives::{BlockNumber, Bytes, ChainId}, diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs index ac97615e..89a59d2f 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs @@ -1,7 +1,5 @@ #![allow(unused)] -use crate::hint_processor::models::proofs::Proofs; - use super::utils::SyscallExecutionError; pub mod account; pub mod header; diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs b/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs index 6a193ee2..d7e6d575 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs @@ -1,8 +1,5 @@ use super::FetchValue; -use crate::{ - hint_processor::models::proofs::{self, mpt::MPTProof}, - syscall_handler::utils::SyscallExecutionError, -}; +use crate::syscall_handler::utils::SyscallExecutionError; use alloy::{ primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, providers::{Provider, RootProvider}, diff --git a/crates/hdp_hint_processor/src/syscall_handler/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/mod.rs index 429c5de9..e15abd0b 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/mod.rs +++ b/crates/hdp_hint_processor/src/syscall_handler/mod.rs @@ -1,5 +1,60 @@ +use cairo_vm::{ + hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_ptr_from_var_name}, + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use evm::dryrun::SyscallHandlerWrapper; +use hints::vars; +use std::collections::HashMap; + pub mod evm; pub mod keys; pub mod starknet; pub mod traits; pub mod utils; + +pub const SYSCALL_HANDLER_CREATE: &str = "if 'syscall_handler' not in globals():\n from contract_bootloader.syscall_handler import SyscallHandler\n syscall_handler = SyscallHandler(segments=segments, dict_manager=__dict_manager)"; + +pub fn syscall_handler_create( + _vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + if let Err(HintError::VariableNotInScopeError(_)) = exec_scopes.get::(vars::scopes::SYSCALL_HANDLER) { + let syscall_handler = SyscallHandlerWrapper::new(); + exec_scopes.insert_value(vars::scopes::SYSCALL_HANDLER, syscall_handler); + } + + Ok(()) +} + +pub const DRY_RUN_SYSCALL_HANDLER_CREATE: &str = "from contract_bootloader.dryrun_syscall_handler import DryRunSyscallHandler\nsyscall_handler = DryRunSyscallHandler(segments=segments, dict_manager=__dict_manager)"; + +pub fn dry_run_syscall_handler_create( + _vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let syscall_handler = SyscallHandlerWrapper::new(); + exec_scopes.insert_value(vars::scopes::SYSCALL_HANDLER, syscall_handler); + + Ok(()) +} + +pub const SYSCALL_HANDLER_SET_SYSCALL_PTR: &str = "syscall_handler.set_syscall_ptr(syscall_ptr=ids.syscall_ptr)"; + +pub fn syscall_handler_set_syscall_ptr( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let syscall_ptr = get_ptr_from_var_name(vars::ids::SYSCALL_PTR, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + let syscall_handler = exec_scopes.get_mut_ref::(vars::scopes::SYSCALL_HANDLER)?; + syscall_handler.set_syscall_ptr(syscall_ptr); + + Ok(()) +} diff --git a/crates/hints/Cargo.toml b/crates/hints/Cargo.toml new file mode 100644 index 00000000..8de6c697 --- /dev/null +++ b/crates/hints/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "hints" +version = "0.1.0" +edition = "2021" + +[dependencies] +alloy.workspace = true +alloy-rlp.workspace = true +bincode.workspace = true +cairo-lang-casm.workspace = true +cairo-lang-starknet-classes.workspace = true +cairo-type-derive.workspace = true +cairo-vm.workspace = true +hex.workspace = true +num-bigint.workspace = true +num-traits.workspace = true +rand.workspace = true +serde_json.workspace = true +serde.workspace = true +starknet-crypto.workspace = true +starknet-types-core.workspace = true +thiserror.workspace = true +tokio = { workspace = true } +serde_with.workspace = true +reqwest.workspace = true +strum_macros.workspace = true +starknet-core.workspace = true + +cairo_types.workspace = true +types.workspace = true \ No newline at end of file diff --git a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/builtins.rs b/crates/hints/src/contract_bootloader/builtins.rs similarity index 99% rename from crates/hdp_hint_processor/src/hints/lib/contract_bootloader/builtins.rs rename to crates/hints/src/contract_bootloader/builtins.rs index c2f130a5..a96ed175 100644 --- a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/builtins.rs +++ b/crates/hints/src/contract_bootloader/builtins.rs @@ -1,4 +1,4 @@ -use crate::hints::vars; +use crate::vars; use cairo_types::structs::BuiltinParams; use cairo_vm::{ hint_processor::{ diff --git a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/contract_class.rs b/crates/hints/src/contract_bootloader/contract_class.rs similarity index 99% rename from crates/hdp_hint_processor/src/hints/lib/contract_bootloader/contract_class.rs rename to crates/hints/src/contract_bootloader/contract_class.rs index 78df19fe..568f9548 100644 --- a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/contract_class.rs +++ b/crates/hints/src/contract_bootloader/contract_class.rs @@ -1,4 +1,4 @@ -use crate::hints::vars; +use crate::vars; use cairo_lang_starknet_classes::casm_contract_class::{CasmContractClass, CasmContractEntryPoint}; use cairo_vm::{ hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::insert_value_from_var_name}, diff --git a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/dict_manager.rs b/crates/hints/src/contract_bootloader/dict_manager.rs similarity index 97% rename from crates/hdp_hint_processor/src/hints/lib/contract_bootloader/dict_manager.rs rename to crates/hints/src/contract_bootloader/dict_manager.rs index 1ee046b3..8758f02f 100644 --- a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/dict_manager.rs +++ b/crates/hints/src/contract_bootloader/dict_manager.rs @@ -1,3 +1,4 @@ +use crate::vars; use cairo_vm::{ hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, dict_manager::DictManager}, types::exec_scope::ExecutionScopes, @@ -6,8 +7,6 @@ use cairo_vm::{ }; use std::{cell::RefCell, collections::HashMap, rc::Rc}; -use crate::hints::vars; - pub const DICT_MANAGER_CREATE: &str = "if '__dict_manager' not in globals():\n from starkware.cairo.common.dict import DictManager\n __dict_manager = DictManager()"; diff --git a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/mod.rs b/crates/hints/src/contract_bootloader/mod.rs similarity index 70% rename from crates/hdp_hint_processor/src/hints/lib/contract_bootloader/mod.rs rename to crates/hints/src/contract_bootloader/mod.rs index e9e82720..7738d463 100644 --- a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/mod.rs +++ b/crates/hints/src/contract_bootloader/mod.rs @@ -3,5 +3,3 @@ pub mod contract_class; pub mod dict_manager; pub mod params; pub mod program; -pub mod scopes; -pub mod syscall_handler; diff --git a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/params.rs b/crates/hints/src/contract_bootloader/params.rs similarity index 95% rename from crates/hdp_hint_processor/src/hints/lib/contract_bootloader/params.rs rename to crates/hints/src/contract_bootloader/params.rs index 5ae0a305..8edb2e19 100644 --- a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/params.rs +++ b/crates/hints/src/contract_bootloader/params.rs @@ -1,4 +1,4 @@ -use crate::{hint_processor::models::param::Param, hints::vars}; +use crate::vars; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, @@ -9,6 +9,7 @@ use cairo_vm::{ Felt252, }; use std::collections::HashMap; +use types::param::Param; pub const LOAD_PARMAS: &str = "ids.params_len = len(params)\nsegments.write_arg(ids.params, [param.value for param in params])"; diff --git a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/program.rs b/crates/hints/src/contract_bootloader/program.rs similarity index 98% rename from crates/hdp_hint_processor/src/hints/lib/contract_bootloader/program.rs rename to crates/hints/src/contract_bootloader/program.rs index 8415f123..4be4b6bc 100644 --- a/crates/hdp_hint_processor/src/hints/lib/contract_bootloader/program.rs +++ b/crates/hints/src/contract_bootloader/program.rs @@ -1,4 +1,4 @@ -use crate::hints::vars; +use crate::vars; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use cairo_types::structs::CompiledClass; use cairo_vm::{ diff --git a/crates/hdp_hint_processor/src/hints/lib/decoder/evm/has_type_prefix.rs b/crates/hints/src/decoder/evm/has_type_prefix.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/lib/decoder/evm/has_type_prefix.rs rename to crates/hints/src/decoder/evm/has_type_prefix.rs diff --git a/crates/hdp_hint_processor/src/hints/lib/decoder/evm/is_byzantium.rs b/crates/hints/src/decoder/evm/is_byzantium.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/lib/decoder/evm/is_byzantium.rs rename to crates/hints/src/decoder/evm/is_byzantium.rs diff --git a/crates/hdp_hint_processor/src/hints/lib/decoder/evm/mod.rs b/crates/hints/src/decoder/evm/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/lib/decoder/evm/mod.rs rename to crates/hints/src/decoder/evm/mod.rs diff --git a/crates/hdp_hint_processor/src/hints/lib/decoder/evm/v_is_encoded.rs b/crates/hints/src/decoder/evm/v_is_encoded.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/lib/decoder/evm/v_is_encoded.rs rename to crates/hints/src/decoder/evm/v_is_encoded.rs diff --git a/crates/hdp_hint_processor/src/hints/lib/decoder/mod.rs b/crates/hints/src/decoder/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/lib/decoder/mod.rs rename to crates/hints/src/decoder/mod.rs diff --git a/crates/hdp_hint_processor/src/hints/lib/mod.rs b/crates/hints/src/lib.rs similarity index 91% rename from crates/hdp_hint_processor/src/hints/lib/mod.rs rename to crates/hints/src/lib.rs index a9177eaa..118a1c61 100644 --- a/crates/hdp_hint_processor/src/hints/lib/mod.rs +++ b/crates/hints/src/lib.rs @@ -5,4 +5,5 @@ pub mod print; pub mod rlp; pub mod segments; pub mod utils; +pub mod vars; pub mod verifiers; diff --git a/crates/hdp_hint_processor/src/hints/lib/merkle/mod.rs b/crates/hints/src/merkle/mod.rs similarity index 99% rename from crates/hdp_hint_processor/src/hints/lib/merkle/mod.rs rename to crates/hints/src/merkle/mod.rs index f907e2fe..dd88a0aa 100644 --- a/crates/hdp_hint_processor/src/hints/lib/merkle/mod.rs +++ b/crates/hints/src/merkle/mod.rs @@ -1,4 +1,4 @@ -use crate::hints::vars; +use crate::vars; use cairo_vm::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData; use cairo_vm::hint_processor::builtin_hint_processor::hint_utils::{get_relocatable_from_var_name, insert_value_from_var_name}; use cairo_vm::types::relocatable::MaybeRelocatable; diff --git a/crates/hdp_hint_processor/src/hints/lib/print.rs b/crates/hints/src/print.rs similarity index 97% rename from crates/hdp_hint_processor/src/hints/lib/print.rs rename to crates/hints/src/print.rs index cc37f265..4899fa60 100644 --- a/crates/hdp_hint_processor/src/hints/lib/print.rs +++ b/crates/hints/src/print.rs @@ -1,4 +1,4 @@ -use crate::hints::vars; +use crate::vars; use cairo_vm::{ hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_integer_from_var_name}, types::exec_scope::ExecutionScopes, diff --git a/crates/hdp_hint_processor/src/hints/lib/rlp/divmod.rs b/crates/hints/src/rlp/divmod.rs similarity index 99% rename from crates/hdp_hint_processor/src/hints/lib/rlp/divmod.rs rename to crates/hints/src/rlp/divmod.rs index 0f610b4f..7c473f9a 100644 --- a/crates/hdp_hint_processor/src/hints/lib/rlp/divmod.rs +++ b/crates/hints/src/rlp/divmod.rs @@ -1,3 +1,4 @@ +use crate::vars; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, @@ -13,8 +14,6 @@ use cairo_vm::{ use starknet_types_core::felt::NonZeroFelt; use std::collections::HashMap; -use crate::hints::vars; - pub const HINT_DIVMOD_RLP: &str = "ids.q, ids.r = divmod(memory[ids.rlp + ids.i], ids.devisor)"; pub fn hint_divmod_rlp( diff --git a/crates/hdp_hint_processor/src/hints/lib/rlp/item_type.rs b/crates/hints/src/rlp/item_type.rs similarity index 99% rename from crates/hdp_hint_processor/src/hints/lib/rlp/item_type.rs rename to crates/hints/src/rlp/item_type.rs index 329be85f..1b37d4fb 100644 --- a/crates/hdp_hint_processor/src/hints/lib/rlp/item_type.rs +++ b/crates/hints/src/rlp/item_type.rs @@ -1,6 +1,5 @@ -use crate::hints::vars; - use super::*; +use crate::vars; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, diff --git a/crates/hdp_hint_processor/src/hints/lib/rlp/mod.rs b/crates/hints/src/rlp/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/lib/rlp/mod.rs rename to crates/hints/src/rlp/mod.rs diff --git a/crates/hdp_hint_processor/src/hints/lib/rlp/processed_words.rs b/crates/hints/src/rlp/processed_words.rs similarity index 97% rename from crates/hdp_hint_processor/src/hints/lib/rlp/processed_words.rs rename to crates/hints/src/rlp/processed_words.rs index 90f6574b..9fa41828 100644 --- a/crates/hdp_hint_processor/src/hints/lib/rlp/processed_words.rs +++ b/crates/hints/src/rlp/processed_words.rs @@ -1,3 +1,4 @@ +use crate::vars; use cairo_vm::{ hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData, hint_processor::builtin_hint_processor::hint_utils::{get_integer_from_var_name, insert_value_into_ap}, @@ -9,8 +10,6 @@ use cairo_vm::{ }; use std::{cmp::Ordering, collections::HashMap}; -use crate::hints::vars; - pub const HINT_PROCESSED_WORDS: &str = "memory[ap] = 1 if (ids.value_len - ids.n_processed_words == 0) else 0"; pub fn hint_processed_words( diff --git a/crates/hdp_hint_processor/src/hints/lib/segments.rs b/crates/hints/src/segments.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/lib/segments.rs rename to crates/hints/src/segments.rs diff --git a/crates/hdp_hint_processor/src/hints/lib/utils/mod.rs b/crates/hints/src/utils/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/lib/utils/mod.rs rename to crates/hints/src/utils/mod.rs diff --git a/crates/hdp_hint_processor/src/hints/vars.rs b/crates/hints/src/vars.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/vars.rs rename to crates/hints/src/vars.rs diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/account_verifier.rs b/crates/hints/src/verifiers/evm/account_verifier.rs similarity index 97% rename from crates/hdp_hint_processor/src/hints/lib/verifiers/evm/account_verifier.rs rename to crates/hints/src/verifiers/evm/account_verifier.rs index c2eb8ba7..cad56407 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/account_verifier.rs +++ b/crates/hints/src/verifiers/evm/account_verifier.rs @@ -1,3 +1,7 @@ +use crate::{ + utils::{count_leading_zero_nibbles_from_hex, split_128}, + vars, +}; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, @@ -10,14 +14,7 @@ use cairo_vm::{ use num_bigint::BigUint; use num_traits::Num; use std::collections::HashMap; - -use crate::{ - hint_processor::models::proofs::{account::Account, mpt::MPTProof, Proofs}, - hints::{ - lib::utils::{count_leading_zero_nibbles_from_hex, split_128}, - vars, - }, -}; +use types::proofs::{account::Account, mpt::MPTProof, Proofs}; pub const HINT_BATCH_ACCOUNTS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.accounts))"; diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/header_verifier.rs b/crates/hints/src/verifiers/evm/header_verifier.rs similarity index 97% rename from crates/hdp_hint_processor/src/hints/lib/verifiers/evm/header_verifier.rs rename to crates/hints/src/verifiers/evm/header_verifier.rs index e253eaba..3bdb9e92 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/header_verifier.rs +++ b/crates/hints/src/verifiers/evm/header_verifier.rs @@ -1,3 +1,4 @@ +use crate::vars; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, @@ -9,11 +10,7 @@ use cairo_vm::{ Felt252, }; use std::{any::Any, collections::HashMap}; - -use crate::{ - hint_processor::models::proofs::{header::Header, HeaderMmrMeta, Proofs}, - hints::vars, -}; +use types::proofs::{header::Header, HeaderMmrMeta, Proofs}; pub const HINT_VM_ENTER_SCOPE: &str = "vm_enter_scope({'header_with_mmr': batch.header_with_mmr[ids.idx], '__dict_manager': __dict_manager})"; diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/mod.rs b/crates/hints/src/verifiers/evm/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/lib/verifiers/evm/mod.rs rename to crates/hints/src/verifiers/evm/mod.rs diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/receipt_verifier.rs b/crates/hints/src/verifiers/evm/receipt_verifier.rs similarity index 97% rename from crates/hdp_hint_processor/src/hints/lib/verifiers/evm/receipt_verifier.rs rename to crates/hints/src/verifiers/evm/receipt_verifier.rs index 26f86ca5..8438d022 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/receipt_verifier.rs +++ b/crates/hints/src/verifiers/evm/receipt_verifier.rs @@ -1,3 +1,4 @@ +use crate::{utils::count_leading_zero_nibbles_from_hex, vars}; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, @@ -8,11 +9,7 @@ use cairo_vm::{ Felt252, }; use std::collections::HashMap; - -use crate::{ - hint_processor::models::proofs::{receipt::Receipt, Proofs}, - hints::{lib::utils::count_leading_zero_nibbles_from_hex, vars}, -}; +use types::proofs::{receipt::Receipt, Proofs}; pub const HINT_BATCH_RECEIPTS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.receipts))"; diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/storage_item_verifier.rs b/crates/hints/src/verifiers/evm/storage_item_verifier.rs similarity index 97% rename from crates/hdp_hint_processor/src/hints/lib/verifiers/evm/storage_item_verifier.rs rename to crates/hints/src/verifiers/evm/storage_item_verifier.rs index 53d71bdc..2baa452f 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/storage_item_verifier.rs +++ b/crates/hints/src/verifiers/evm/storage_item_verifier.rs @@ -1,3 +1,7 @@ +use crate::{ + utils::{count_leading_zero_nibbles_from_hex, split_128}, + vars, +}; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, @@ -10,14 +14,7 @@ use cairo_vm::{ use num_bigint::BigUint; use num_traits::Num; use std::collections::HashMap; - -use crate::{ - hint_processor::models::proofs::{mpt::MPTProof, storage::Storage, Proofs}, - hints::{ - lib::utils::{count_leading_zero_nibbles_from_hex, split_128}, - vars, - }, -}; +use types::proofs::{mpt::MPTProof, storage::Storage, Proofs}; pub const HINT_BATCH_STORAGES_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.storages))"; diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/transaction_verifier.rs b/crates/hints/src/verifiers/evm/transaction_verifier.rs similarity index 96% rename from crates/hdp_hint_processor/src/hints/lib/verifiers/evm/transaction_verifier.rs rename to crates/hints/src/verifiers/evm/transaction_verifier.rs index 04451187..c1ba2902 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/evm/transaction_verifier.rs +++ b/crates/hints/src/verifiers/evm/transaction_verifier.rs @@ -1,3 +1,7 @@ +use crate::{ + utils::{count_leading_zero_nibbles_from_hex, split_128}, + vars, +}; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, @@ -9,14 +13,7 @@ use cairo_vm::{ }; use num_bigint::BigUint; use std::collections::HashMap; - -use crate::{ - hint_processor::models::proofs::{transaction::Transaction, Proofs}, - hints::{ - lib::utils::{count_leading_zero_nibbles_from_hex, split_128}, - vars, - }, -}; +use types::proofs::{transaction::Transaction, Proofs}; pub const HINT_BATCH_TRANSACTIONS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.transactions))"; diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/mod.rs b/crates/hints/src/verifiers/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/hints/lib/verifiers/mod.rs rename to crates/hints/src/verifiers/mod.rs diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/utils.rs b/crates/hints/src/verifiers/utils.rs similarity index 98% rename from crates/hdp_hint_processor/src/hints/lib/verifiers/utils.rs rename to crates/hints/src/verifiers/utils.rs index 67152026..c8e77e8e 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/utils.rs +++ b/crates/hints/src/verifiers/utils.rs @@ -1,3 +1,4 @@ +use crate::vars; use cairo_vm::hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, hint_utils::get_relocatable_from_var_name, }; @@ -9,8 +10,6 @@ use cairo_vm::{ use num_bigint::BigUint; use std::collections::HashMap; -use crate::hints::vars; - pub const HINT_PRINT_TASK_RESULT: &str = "print(f\"Task Result: {hex(ids.result.high * 2 ** 128 + ids.result.low)}\")"; pub fn hint_print_task_result( diff --git a/crates/hdp_hint_processor/src/hints/lib/verifiers/verify.rs b/crates/hints/src/verifiers/verify.rs similarity index 96% rename from crates/hdp_hint_processor/src/hints/lib/verifiers/verify.rs rename to crates/hints/src/verifiers/verify.rs index c1773004..ac4f6a5c 100644 --- a/crates/hdp_hint_processor/src/hints/lib/verifiers/verify.rs +++ b/crates/hints/src/verifiers/verify.rs @@ -1,4 +1,4 @@ -use crate::{hint_processor::models::proofs::Proofs, hints::vars}; +use crate::vars; use cairo_vm::hint_processor::builtin_hint_processor::hint_utils::insert_value_into_ap; use cairo_vm::hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, dict_manager::DictManager}; use cairo_vm::{ @@ -7,6 +7,7 @@ use cairo_vm::{ Felt252, }; use std::{any::Any, collections::HashMap}; +use types::proofs::Proofs; pub const HINT_VM_ENTER_SCOPE: &str = "vm_enter_scope({'batch': proofs, '__dict_manager': __dict_manager})"; diff --git a/crates/types/Cargo.toml b/crates/types/Cargo.toml new file mode 100644 index 00000000..09c5c35e --- /dev/null +++ b/crates/types/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "types" +version = "0.1.0" +edition = "2021" + +[dependencies] +alloy.workspace = true +cairo-lang-casm.workspace = true +cairo-lang-starknet-classes.workspace = true +cairo-type-derive.workspace = true +cairo-vm.workspace = true +serde_json.workspace = true +serde_with.workspace = true +serde.workspace = true +thiserror.workspace = true \ No newline at end of file diff --git a/crates/hdp_hint_processor/src/hint_processor/models/mod.rs b/crates/types/src/lib.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/models/mod.rs rename to crates/types/src/lib.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/models/param.rs b/crates/types/src/param.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/models/param.rs rename to crates/types/src/param.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/account.rs b/crates/types/src/proofs/account.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/models/proofs/account.rs rename to crates/types/src/proofs/account.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/header.rs b/crates/types/src/proofs/header.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/models/proofs/header.rs rename to crates/types/src/proofs/header.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs b/crates/types/src/proofs/mmr.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/models/proofs/mmr.rs rename to crates/types/src/proofs/mmr.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs b/crates/types/src/proofs/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/models/proofs/mod.rs rename to crates/types/src/proofs/mod.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/mpt.rs b/crates/types/src/proofs/mpt.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/models/proofs/mpt.rs rename to crates/types/src/proofs/mpt.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/receipt.rs b/crates/types/src/proofs/receipt.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/models/proofs/receipt.rs rename to crates/types/src/proofs/receipt.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/storage.rs b/crates/types/src/proofs/storage.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/models/proofs/storage.rs rename to crates/types/src/proofs/storage.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/models/proofs/transaction.rs b/crates/types/src/proofs/transaction.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/models/proofs/transaction.rs rename to crates/types/src/proofs/transaction.rs From 5b393a62300f8cab686dcfbbd3488525aa625052 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 17 Dec 2024 15:57:11 +0100 Subject: [PATCH 42/75] provider reduced to indexer --- Cargo.lock | 105 ++++++++---------- Cargo.toml | 9 +- crates/dry_run/Cargo.toml | 2 +- crates/dry_run/src/main.rs | 6 +- .../Cargo.toml | 4 +- .../src}/dry_run_input.rs | 0 .../src/lib.rs} | 20 ++-- .../src}/output.rs | 0 .../src}/run_input.rs | 0 .../src/scopes.rs | 2 +- .../src/syscall_handler/evm}/account.rs | 1 - .../src/syscall_handler/evm}/header.rs | 1 - .../src/syscall_handler/evm}/mod.rs | 0 .../src/syscall_handler/evm}/receipt.rs | 0 .../src/syscall_handler/evm}/storage.rs | 1 - .../src/syscall_handler/evm}/transaction.rs | 0 .../src/syscall_handler/keys/account.rs | 3 +- .../src/syscall_handler/keys/header.rs | 7 +- .../src/syscall_handler/keys/mod.rs | 0 .../src/syscall_handler/keys/receipt.rs | 0 .../src/syscall_handler/keys/storage.rs | 3 +- .../src/syscall_handler/keys/transaction.rs | 0 .../src/syscall_handler/mod.rs | 2 +- .../syscall_handler/starknet/dryrun}/mod.rs | 0 .../src/syscall_handler/starknet}/mod.rs | 0 .../syscall_handler/starknet/soundrun}/mod.rs | 0 .../src/syscall_handler/traits.rs | 0 .../src/syscall_handler/utils.rs | 0 .../src/tests/mod.rs | 3 +- crates/fetcher/Cargo.toml | 4 +- crates/fetcher/src/lib.rs | 2 +- crates/fetcher/src/main.rs | 8 +- crates/fetcher/src/proof_keys.rs | 11 +- crates/hdp_hint_processor/src/lib.rs | 8 -- .../src/syscall_handler/starknet/mod.rs | 2 - .../syscall_handler/starknet/soundrun/mod.rs | 1 - crates/{provider => indexer}/Cargo.toml | 2 +- .../src/indexer/mod.rs => indexer/src/lib.rs} | 0 .../src/indexer => indexer/src}/types.rs | 0 crates/provider/src/evm/mod.rs | 1 - crates/provider/src/lib.rs | 5 - crates/provider/src/starknet/mod.rs | 1 - crates/sound_run/Cargo.toml | 11 -- crates/sound_run/src/main.rs | 85 -------------- 44 files changed, 88 insertions(+), 222 deletions(-) rename crates/{hdp_hint_processor => dry_run_hint_processor}/Cargo.toml (92%) rename crates/{hdp_hint_processor/src/hint_processor => dry_run_hint_processor/src}/dry_run_input.rs (100%) rename crates/{hdp_hint_processor/src/hint_processor/mod.rs => dry_run_hint_processor/src/lib.rs} (96%) rename crates/{hdp_hint_processor/src/hint_processor => dry_run_hint_processor/src}/output.rs (100%) rename crates/{hdp_hint_processor/src/hint_processor => dry_run_hint_processor/src}/run_input.rs (100%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/scopes.rs (93%) rename crates/{hdp_hint_processor/src/syscall_handler/evm/dryrun => dry_run_hint_processor/src/syscall_handler/evm}/account.rs (98%) rename crates/{hdp_hint_processor/src/syscall_handler/evm/dryrun => dry_run_hint_processor/src/syscall_handler/evm}/header.rs (98%) rename crates/{hdp_hint_processor/src/syscall_handler/evm/dryrun => dry_run_hint_processor/src/syscall_handler/evm}/mod.rs (100%) rename crates/{hdp_hint_processor/src/syscall_handler/evm/dryrun => dry_run_hint_processor/src/syscall_handler/evm}/receipt.rs (100%) rename crates/{hdp_hint_processor/src/syscall_handler/evm/dryrun => dry_run_hint_processor/src/syscall_handler/evm}/storage.rs (98%) rename crates/{hdp_hint_processor/src/syscall_handler/evm/dryrun => dry_run_hint_processor/src/syscall_handler/evm}/transaction.rs (100%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/syscall_handler/keys/account.rs (97%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/syscall_handler/keys/header.rs (94%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/syscall_handler/keys/mod.rs (100%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/syscall_handler/keys/receipt.rs (100%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/syscall_handler/keys/storage.rs (97%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/syscall_handler/keys/transaction.rs (100%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/syscall_handler/mod.rs (98%) rename crates/{hdp_hint_processor/src/syscall_handler/evm/soundrun => dry_run_hint_processor/src/syscall_handler/starknet/dryrun}/mod.rs (100%) rename crates/{hdp_hint_processor/src/syscall_handler/evm => dry_run_hint_processor/src/syscall_handler/starknet}/mod.rs (100%) rename crates/{hdp_hint_processor/src/syscall_handler/starknet/dryrun => dry_run_hint_processor/src/syscall_handler/starknet/soundrun}/mod.rs (100%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/syscall_handler/traits.rs (100%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/syscall_handler/utils.rs (100%) rename crates/{hdp_hint_processor => dry_run_hint_processor}/src/tests/mod.rs (91%) delete mode 100644 crates/hdp_hint_processor/src/lib.rs delete mode 100644 crates/hdp_hint_processor/src/syscall_handler/starknet/mod.rs delete mode 100644 crates/hdp_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs rename crates/{provider => indexer}/Cargo.toml (92%) rename crates/{provider/src/indexer/mod.rs => indexer/src/lib.rs} (100%) rename crates/{provider/src/indexer => indexer/src}/types.rs (100%) delete mode 100644 crates/provider/src/evm/mod.rs delete mode 100644 crates/provider/src/lib.rs delete mode 100644 crates/provider/src/starknet/mod.rs delete mode 100644 crates/sound_run/Cargo.toml delete mode 100644 crates/sound_run/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index 45e4a75f..ca24c4a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2058,12 +2058,43 @@ version = "0.1.0" dependencies = [ "cairo-vm", "clap", - "hdp_hint_processor", + "dry_run_hint_processor", "hints", "serde_json", "thiserror 1.0.69", ] +[[package]] +name = "dry_run_hint_processor" +version = "0.1.0" +dependencies = [ + "alloy", + "alloy-rlp", + "bincode", + "cairo-lang-casm", + "cairo-lang-starknet-classes", + "cairo-type-derive", + "cairo-vm", + "cairo_types", + "hex", + "hints", + "indexer", + "num-bigint", + "num-traits", + "rand", + "reqwest", + "serde", + "serde_json", + "serde_with 3.11.0", + "starknet-core", + "starknet-crypto 0.7.3", + "starknet-types-core", + "strum_macros", + "thiserror 1.0.69", + "tokio", + "types", +] + [[package]] name = "dunce" version = "1.0.5" @@ -2173,9 +2204,9 @@ dependencies = [ "alloy", "cairo-vm", "clap", - "hdp_hint_processor", + "dry_run_hint_processor", "hex", - "provider", + "indexer", "serde_json", "thiserror 1.0.69", "tokio", @@ -2503,37 +2534,6 @@ dependencies = [ "serde", ] -[[package]] -name = "hdp_hint_processor" -version = "0.1.0" -dependencies = [ - "alloy", - "alloy-rlp", - "bincode", - "cairo-lang-casm", - "cairo-lang-starknet-classes", - "cairo-type-derive", - "cairo-vm", - "cairo_types", - "hex", - "hints", - "num-bigint", - "num-traits", - "provider", - "rand", - "reqwest", - "serde", - "serde_json", - "serde_with 3.11.0", - "starknet-core", - "starknet-crypto 0.7.3", - "starknet-types-core", - "strum_macros", - "thiserror 1.0.69", - "tokio", - "types", -] - [[package]] name = "heck" version = "0.4.1" @@ -2933,6 +2933,19 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9f1a0777d972970f204fdf8ef319f1f4f8459131636d7e3c96c5d59570d0fa6" +[[package]] +name = "indexer" +version = "0.1.0" +dependencies = [ + "alloy", + "reqwest", + "serde", + "serde_json", + "serde_with 3.11.0", + "thiserror 1.0.69", + "tokio", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -3771,19 +3784,6 @@ dependencies = [ "unarray", ] -[[package]] -name = "provider" -version = "0.1.0" -dependencies = [ - "alloy", - "reqwest", - "serde", - "serde_json", - "serde_with 3.11.0", - "thiserror 1.0.69", - "tokio", -] - [[package]] name = "quick-error" version = "1.2.3" @@ -4567,17 +4567,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "sound_run" -version = "0.1.0" -dependencies = [ - "cairo-vm", - "clap", - "hdp_hint_processor", - "serde_json", - "thiserror 1.0.69", -] - [[package]] name = "spin" version = "0.9.8" diff --git a/Cargo.toml b/Cargo.toml index e5b0c670..62fe6dcc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,11 +5,10 @@ members = [ "crates/cairo_types", "crates/dry_run", "crates/fetcher", - "crates/hdp_hint_processor", - "crates/provider", + "crates/dry_run_hint_processor", + "crates/indexer", "crates/hints", "crates/types", - "crates/sound_run", ] [workspace.dependencies] @@ -38,8 +37,8 @@ starknet-crypto = { version = "0.7.1", default-features = false } starknet-types-core = { version = "0.1.5", default-features = false } reqwest = "0.12.9" -hdp_hint_processor = { path = "crates/hdp_hint_processor" } -provider = { path = "crates/provider" } +dry_run_hint_processor = { path = "crates/dry_run_hint_processor" } +indexer = { path = "crates/indexer" } cairo_types = { path = "crates/cairo_types" } types = { path = "crates/types" } hints = { path = "crates/hints" } \ No newline at end of file diff --git a/crates/dry_run/Cargo.toml b/crates/dry_run/Cargo.toml index c21fd67a..f809b794 100644 --- a/crates/dry_run/Cargo.toml +++ b/crates/dry_run/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] -hdp_hint_processor.workspace = true +dry_run_hint_processor.workspace = true cairo-vm.workspace = true clap.workspace = true thiserror.workspace = true diff --git a/crates/dry_run/src/main.rs b/crates/dry_run/src/main.rs index a8b78c40..faa1e930 100644 --- a/crates/dry_run/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -6,10 +6,10 @@ use cairo_vm::{ vm::{errors::vm_exception::VmException, runners::cairo_runner::CairoRunner}, }; use clap::{Parser, ValueHint}; -use hdp_hint_processor::{ +use dry_run_hint_processor::{ self, - hint_processor::CustomHintProcessor, - syscall_handler::evm::dryrun::{SyscallHandler, SyscallHandlerWrapper}, + syscall_handler::evm::{SyscallHandler, SyscallHandlerWrapper}, + CustomHintProcessor, }; use hints::vars; use std::path::PathBuf; diff --git a/crates/hdp_hint_processor/Cargo.toml b/crates/dry_run_hint_processor/Cargo.toml similarity index 92% rename from crates/hdp_hint_processor/Cargo.toml rename to crates/dry_run_hint_processor/Cargo.toml index 9981f92a..00b06f3c 100644 --- a/crates/hdp_hint_processor/Cargo.toml +++ b/crates/dry_run_hint_processor/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "hdp_hint_processor" +name = "dry_run_hint_processor" version = "0.1.0" edition = "2021" @@ -26,7 +26,7 @@ reqwest.workspace = true strum_macros.workspace = true starknet-core.workspace = true -provider.workspace = true +indexer.workspace = true cairo_types.workspace = true types.workspace = true hints.workspace = true \ No newline at end of file diff --git a/crates/hdp_hint_processor/src/hint_processor/dry_run_input.rs b/crates/dry_run_hint_processor/src/dry_run_input.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/dry_run_input.rs rename to crates/dry_run_hint_processor/src/dry_run_input.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/mod.rs b/crates/dry_run_hint_processor/src/lib.rs similarity index 96% rename from crates/hdp_hint_processor/src/hint_processor/mod.rs rename to crates/dry_run_hint_processor/src/lib.rs index b79d450f..747eccd6 100644 --- a/crates/hdp_hint_processor/src/hint_processor/mod.rs +++ b/crates/dry_run_hint_processor/src/lib.rs @@ -1,11 +1,11 @@ +#![forbid(unsafe_code)] +#![allow(async_fn_in_trait)] pub mod dry_run_input; pub mod output; pub mod run_input; +pub mod scopes; +pub mod syscall_handler; -use crate::{ - scopes, - syscall_handler::{self, evm::dryrun::SyscallHandlerWrapper}, -}; use cairo_lang_casm::{ hints::{Hint, StarknetHint}, operand::{BinOpOperand, DerefOrImmediate, Operation, Register, ResOperand}, @@ -23,6 +23,9 @@ use cairo_vm::{ use hints::{contract_bootloader, decoder, merkle, print, rlp, segments, vars, verifiers}; use starknet_types_core::felt::Felt; use std::{any::Any, collections::HashMap}; +use syscall_handler::evm::SyscallHandlerWrapper; + +pub const RPC: &str = "RPC"; pub type HintImpl = fn(&mut VirtualMachine, &mut ExecutionScopes, &HintProcessorData, &HashMap) -> Result<(), HintError>; @@ -162,9 +165,9 @@ impl HintProcessorLogic for CustomHintProcessor { let hint_code = hpd.code.as_str(); let res = match hint_code { - crate::hint_processor::dry_run_input::HINT_DRY_RUN_INPUT => self.hint_dry_run_input(vm, exec_scopes, hpd, constants), - crate::hint_processor::run_input::HINT_RUN_INPUT => self.hint_run_input(vm, exec_scopes, hpd, constants), - crate::hint_processor::output::HINT_OUTPUT => self.hint_output(vm, exec_scopes, hpd, constants), + crate::dry_run_input::HINT_DRY_RUN_INPUT => self.hint_dry_run_input(vm, exec_scopes, hpd, constants), + crate::run_input::HINT_RUN_INPUT => self.hint_run_input(vm, exec_scopes, hpd, constants), + crate::output::HINT_OUTPUT => self.hint_output(vm, exec_scopes, hpd, constants), _ => Err(HintError::UnknownHint(hint_code.to_string().into_boxed_str())), }; @@ -229,3 +232,6 @@ fn get_ptr_from_res_operand(vm: &mut VirtualMachine, res: &ResOperand) -> Result let cell_reloc = (base + (i32::from(cell.offset)))?; (vm.get_relocatable(cell_reloc)? + &base_offset).map_err(|e| e.into()) } + +#[cfg(test)] +pub mod tests; diff --git a/crates/hdp_hint_processor/src/hint_processor/output.rs b/crates/dry_run_hint_processor/src/output.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/output.rs rename to crates/dry_run_hint_processor/src/output.rs diff --git a/crates/hdp_hint_processor/src/hint_processor/run_input.rs b/crates/dry_run_hint_processor/src/run_input.rs similarity index 100% rename from crates/hdp_hint_processor/src/hint_processor/run_input.rs rename to crates/dry_run_hint_processor/src/run_input.rs diff --git a/crates/hdp_hint_processor/src/scopes.rs b/crates/dry_run_hint_processor/src/scopes.rs similarity index 93% rename from crates/hdp_hint_processor/src/scopes.rs rename to crates/dry_run_hint_processor/src/scopes.rs index 4aad0d64..3707f199 100644 --- a/crates/hdp_hint_processor/src/scopes.rs +++ b/crates/dry_run_hint_processor/src/scopes.rs @@ -1,4 +1,4 @@ -use crate::syscall_handler::evm::dryrun::SyscallHandlerWrapper; +use crate::syscall_handler::evm::SyscallHandlerWrapper; use cairo_vm::{ hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData, types::exec_scope::ExecutionScopes, diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/account.rs b/crates/dry_run_hint_processor/src/syscall_handler/evm/account.rs similarity index 98% rename from crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/account.rs rename to crates/dry_run_hint_processor/src/syscall_handler/evm/account.rs index bfa55d90..d1be42da 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/account.rs +++ b/crates/dry_run_hint_processor/src/syscall_handler/evm/account.rs @@ -23,7 +23,6 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; -use provider::RPC; use serde::{Deserialize, Serialize}; use std::env; diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/header.rs b/crates/dry_run_hint_processor/src/syscall_handler/evm/header.rs similarity index 98% rename from crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/header.rs rename to crates/dry_run_hint_processor/src/syscall_handler/evm/header.rs index 0d2cd500..9764e4ac 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/header.rs +++ b/crates/dry_run_hint_processor/src/syscall_handler/evm/header.rs @@ -23,7 +23,6 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; -use provider::RPC; use serde::{Deserialize, Serialize}; use std::env; diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/mod.rs b/crates/dry_run_hint_processor/src/syscall_handler/evm/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/mod.rs rename to crates/dry_run_hint_processor/src/syscall_handler/evm/mod.rs diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/receipt.rs b/crates/dry_run_hint_processor/src/syscall_handler/evm/receipt.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/receipt.rs rename to crates/dry_run_hint_processor/src/syscall_handler/evm/receipt.rs diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/storage.rs b/crates/dry_run_hint_processor/src/syscall_handler/evm/storage.rs similarity index 98% rename from crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/storage.rs rename to crates/dry_run_hint_processor/src/syscall_handler/evm/storage.rs index 437ed08c..8b951538 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/storage.rs +++ b/crates/dry_run_hint_processor/src/syscall_handler/evm/storage.rs @@ -23,7 +23,6 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; -use provider::RPC; use serde::{Deserialize, Serialize}; use std::env; diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/transaction.rs b/crates/dry_run_hint_processor/src/syscall_handler/evm/transaction.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/evm/dryrun/transaction.rs rename to crates/dry_run_hint_processor/src/syscall_handler/evm/transaction.rs diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs b/crates/dry_run_hint_processor/src/syscall_handler/keys/account.rs similarity index 97% rename from crates/hdp_hint_processor/src/syscall_handler/keys/account.rs rename to crates/dry_run_hint_processor/src/syscall_handler/keys/account.rs index f02e7de5..97011f08 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/account.rs +++ b/crates/dry_run_hint_processor/src/syscall_handler/keys/account.rs @@ -1,4 +1,4 @@ -use crate::syscall_handler::utils::SyscallExecutionError; +use crate::{syscall_handler::utils::SyscallExecutionError, RPC}; use alloy::{ consensus::Account, primitives::{Address, BlockNumber, ChainId}, @@ -12,7 +12,6 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; -use provider::RPC; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use std::env; diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs b/crates/dry_run_hint_processor/src/syscall_handler/keys/header.rs similarity index 94% rename from crates/hdp_hint_processor/src/syscall_handler/keys/header.rs rename to crates/dry_run_hint_processor/src/syscall_handler/keys/header.rs index e1978ada..83e80090 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/header.rs +++ b/crates/dry_run_hint_processor/src/syscall_handler/keys/header.rs @@ -1,5 +1,5 @@ use super::{account, storage, FetchValue}; -use crate::syscall_handler::utils::SyscallExecutionError; +use crate::{syscall_handler::utils::SyscallExecutionError, RPC}; use alloy::{ hex::FromHexError, primitives::{BlockNumber, Bytes, ChainId}, @@ -13,11 +13,6 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; -use provider::indexer::{ - types::{BlockHeader, IndexerQuery, MMRData}, - Indexer, -}; -use provider::RPC; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use starknet_types_core::felt::FromStrError; diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs b/crates/dry_run_hint_processor/src/syscall_handler/keys/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/keys/mod.rs rename to crates/dry_run_hint_processor/src/syscall_handler/keys/mod.rs diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/receipt.rs b/crates/dry_run_hint_processor/src/syscall_handler/keys/receipt.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/keys/receipt.rs rename to crates/dry_run_hint_processor/src/syscall_handler/keys/receipt.rs diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs b/crates/dry_run_hint_processor/src/syscall_handler/keys/storage.rs similarity index 97% rename from crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs rename to crates/dry_run_hint_processor/src/syscall_handler/keys/storage.rs index d7e6d575..c14ca05c 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/keys/storage.rs +++ b/crates/dry_run_hint_processor/src/syscall_handler/keys/storage.rs @@ -1,5 +1,5 @@ use super::FetchValue; -use crate::syscall_handler::utils::SyscallExecutionError; +use crate::{syscall_handler::utils::SyscallExecutionError, RPC}; use alloy::{ primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, providers::{Provider, RootProvider}, @@ -12,7 +12,6 @@ use cairo_vm::{ vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; -use provider::RPC; use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use std::env; diff --git a/crates/hdp_hint_processor/src/syscall_handler/keys/transaction.rs b/crates/dry_run_hint_processor/src/syscall_handler/keys/transaction.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/keys/transaction.rs rename to crates/dry_run_hint_processor/src/syscall_handler/keys/transaction.rs diff --git a/crates/hdp_hint_processor/src/syscall_handler/mod.rs b/crates/dry_run_hint_processor/src/syscall_handler/mod.rs similarity index 98% rename from crates/hdp_hint_processor/src/syscall_handler/mod.rs rename to crates/dry_run_hint_processor/src/syscall_handler/mod.rs index e15abd0b..6ad113d1 100644 --- a/crates/hdp_hint_processor/src/syscall_handler/mod.rs +++ b/crates/dry_run_hint_processor/src/syscall_handler/mod.rs @@ -4,7 +4,7 @@ use cairo_vm::{ vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; -use evm::dryrun::SyscallHandlerWrapper; +use evm::SyscallHandlerWrapper; use hints::vars; use std::collections::HashMap; diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/soundrun/mod.rs b/crates/dry_run_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/evm/soundrun/mod.rs rename to crates/dry_run_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs diff --git a/crates/hdp_hint_processor/src/syscall_handler/evm/mod.rs b/crates/dry_run_hint_processor/src/syscall_handler/starknet/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/evm/mod.rs rename to crates/dry_run_hint_processor/src/syscall_handler/starknet/mod.rs diff --git a/crates/hdp_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs b/crates/dry_run_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs rename to crates/dry_run_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs diff --git a/crates/hdp_hint_processor/src/syscall_handler/traits.rs b/crates/dry_run_hint_processor/src/syscall_handler/traits.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/traits.rs rename to crates/dry_run_hint_processor/src/syscall_handler/traits.rs diff --git a/crates/hdp_hint_processor/src/syscall_handler/utils.rs b/crates/dry_run_hint_processor/src/syscall_handler/utils.rs similarity index 100% rename from crates/hdp_hint_processor/src/syscall_handler/utils.rs rename to crates/dry_run_hint_processor/src/syscall_handler/utils.rs diff --git a/crates/hdp_hint_processor/src/tests/mod.rs b/crates/dry_run_hint_processor/src/tests/mod.rs similarity index 91% rename from crates/hdp_hint_processor/src/tests/mod.rs rename to crates/dry_run_hint_processor/src/tests/mod.rs index 4edb8b74..023df9af 100644 --- a/crates/hdp_hint_processor/src/tests/mod.rs +++ b/crates/dry_run_hint_processor/src/tests/mod.rs @@ -1,10 +1,9 @@ +use crate::CustomHintProcessor; use cairo_vm::{ cairo_run, vm::{errors::cairo_run_errors::CairoRunError, runners::cairo_runner::CairoRunner}, }; -use crate::hint_processor::CustomHintProcessor; - pub fn run_cairo_program(program_content: &[u8]) -> Result { let cairo_run_config = cairo_run::CairoRunConfig { layout: cairo_vm::types::layout_name::LayoutName::all_cairo, diff --git a/crates/fetcher/Cargo.toml b/crates/fetcher/Cargo.toml index 444a2815..f1804bb3 100644 --- a/crates/fetcher/Cargo.toml +++ b/crates/fetcher/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] -hdp_hint_processor.workspace = true +dry_run_hint_processor.workspace = true cairo-vm.workspace = true clap.workspace = true thiserror.workspace = true @@ -13,5 +13,5 @@ serde_json.workspace = true alloy.workspace = true hex.workspace = true -provider.workspace = true +indexer.workspace = true types.workspace = true \ No newline at end of file diff --git a/crates/fetcher/src/lib.rs b/crates/fetcher/src/lib.rs index a5493bff..24550560 100644 --- a/crates/fetcher/src/lib.rs +++ b/crates/fetcher/src/lib.rs @@ -1,5 +1,5 @@ use alloy::hex::FromHexError; -use provider::indexer::types::IndexerError; +use indexer::types::IndexerError; use std::num::ParseIntError; use thiserror::Error; diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index f47516ec..1cbc3580 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -1,8 +1,8 @@ #![forbid(unsafe_code)] #![allow(async_fn_in_trait)] use clap::{Parser, ValueHint}; +use dry_run_hint_processor::syscall_handler::evm::{self, SyscallHandler}; use fetcher::{proof_keys::ProofKeys, FetcherError}; -use hdp_hint_processor::syscall_handler::evm::{self, dryrun::SyscallHandler}; use std::{collections::HashSet, fs, path::PathBuf}; use types::proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}; @@ -26,13 +26,13 @@ fn main() -> Result<(), FetcherError> { let mut proof_keys = ProofKeys::default(); for key in syscall_handler.call_contract_handler.key_set { match key { - evm::dryrun::DryRunKey::Account(value) => { + evm::DryRunKey::Account(value) => { proof_keys.account_keys.insert(value); } - evm::dryrun::DryRunKey::Header(value) => { + evm::DryRunKey::Header(value) => { proof_keys.header_keys.insert(value); } - evm::dryrun::DryRunKey::Storage(value) => { + evm::DryRunKey::Storage(value) => { proof_keys.storage_keys.insert(value); } } diff --git a/crates/fetcher/src/proof_keys.rs b/crates/fetcher/src/proof_keys.rs index 0d980a62..263c357b 100644 --- a/crates/fetcher/src/proof_keys.rs +++ b/crates/fetcher/src/proof_keys.rs @@ -4,13 +4,10 @@ use alloy::{ providers::{Provider, RootProvider}, transports::http::{reqwest::Url, Client, Http}, }; -use hdp_hint_processor::syscall_handler::keys; -use provider::{ - indexer::{ - types::{BlockHeader, IndexerQuery}, - Indexer, - }, - RPC, +use dry_run_hint_processor::{syscall_handler::keys, RPC}; +use indexer::{ + types::{BlockHeader, IndexerQuery}, + Indexer, }; use std::{collections::HashSet, env}; use types::proofs::{ diff --git a/crates/hdp_hint_processor/src/lib.rs b/crates/hdp_hint_processor/src/lib.rs deleted file mode 100644 index 2abbd59a..00000000 --- a/crates/hdp_hint_processor/src/lib.rs +++ /dev/null @@ -1,8 +0,0 @@ -#![forbid(unsafe_code)] -#![allow(async_fn_in_trait)] -pub mod hint_processor; -pub mod scopes; -pub mod syscall_handler; - -#[cfg(test)] -pub mod tests; diff --git a/crates/hdp_hint_processor/src/syscall_handler/starknet/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/starknet/mod.rs deleted file mode 100644 index de5683ca..00000000 --- a/crates/hdp_hint_processor/src/syscall_handler/starknet/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod dryrun; -pub mod soundrun; diff --git a/crates/hdp_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs b/crates/hdp_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs deleted file mode 100644 index 8b137891..00000000 --- a/crates/hdp_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/crates/provider/Cargo.toml b/crates/indexer/Cargo.toml similarity index 92% rename from crates/provider/Cargo.toml rename to crates/indexer/Cargo.toml index ed7a4397..5cf7efb8 100644 --- a/crates/provider/Cargo.toml +++ b/crates/indexer/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "provider" +name = "indexer" version = "0.1.0" edition = "2021" diff --git a/crates/provider/src/indexer/mod.rs b/crates/indexer/src/lib.rs similarity index 100% rename from crates/provider/src/indexer/mod.rs rename to crates/indexer/src/lib.rs diff --git a/crates/provider/src/indexer/types.rs b/crates/indexer/src/types.rs similarity index 100% rename from crates/provider/src/indexer/types.rs rename to crates/indexer/src/types.rs diff --git a/crates/provider/src/evm/mod.rs b/crates/provider/src/evm/mod.rs deleted file mode 100644 index 8b137891..00000000 --- a/crates/provider/src/evm/mod.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/crates/provider/src/lib.rs b/crates/provider/src/lib.rs deleted file mode 100644 index bc37d9bd..00000000 --- a/crates/provider/src/lib.rs +++ /dev/null @@ -1,5 +0,0 @@ -pub mod evm; -pub mod indexer; -pub mod starknet; - -pub const RPC: &str = "RPC"; diff --git a/crates/provider/src/starknet/mod.rs b/crates/provider/src/starknet/mod.rs deleted file mode 100644 index 8b137891..00000000 --- a/crates/provider/src/starknet/mod.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/crates/sound_run/Cargo.toml b/crates/sound_run/Cargo.toml deleted file mode 100644 index c3106559..00000000 --- a/crates/sound_run/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "sound_run" -version = "0.1.0" -edition = "2021" - -[dependencies] -hdp_hint_processor.workspace = true -cairo-vm.workspace = true -clap.workspace = true -thiserror.workspace = true -serde_json.workspace = true \ No newline at end of file diff --git a/crates/sound_run/src/main.rs b/crates/sound_run/src/main.rs deleted file mode 100644 index 002a7b25..00000000 --- a/crates/sound_run/src/main.rs +++ /dev/null @@ -1,85 +0,0 @@ -#![forbid(unsafe_code)] -#![allow(async_fn_in_trait)] -use cairo_vm::{ - cairo_run::CairoRunConfig, - types::{layout_name::LayoutName, program::Program}, - vm::{errors::vm_exception::VmException, runners::cairo_runner::CairoRunner}, -}; -use clap::{Parser, ValueHint}; -use hdp_hint_processor::{self, hint_processor::CustomHintProcessor}; -use std::path::PathBuf; - -#[derive(Parser, Debug)] -#[clap(author, version, about, long_about = None)] -struct Args { - #[clap(value_parser, value_hint=ValueHint::FilePath)] - filename: PathBuf, - /// When using dynamic layout, it's parameters must be specified through a layout params file. - #[clap(long = "layout", default_value = "plain", value_enum)] - layout: LayoutName, - #[structopt(long = "proof_mode")] - proof_mode: bool, - #[structopt(long = "program_input")] - program_input: PathBuf, - #[structopt(long = "program_output")] - program_output: PathBuf, -} - -fn main() -> Result<(), HdpOsError> { - let args = Args::try_parse_from(std::env::args()).map_err(HdpOsError::Args)?; - - // Init CairoRunConfig - let cairo_run_config = CairoRunConfig { - layout: args.layout, - relocate_mem: true, - trace_enabled: true, - ..Default::default() - }; - - let program_file = std::fs::read(args.filename).map_err(HdpOsError::IO)?; - let program_inputs = std::fs::read(args.program_input).map_err(HdpOsError::IO)?; - - // Load the Program - let program = Program::from_bytes(&program_file, Some(cairo_run_config.entrypoint)).map_err(|e| HdpOsError::Runner(e.into()))?; - - // Init cairo runner - let mut cairo_runner = CairoRunner::new( - &program, - cairo_run_config.layout, - None, - cairo_run_config.proof_mode, - cairo_run_config.trace_enabled, - ) - .map_err(|e| HdpOsError::Runner(e.into()))?; - - // Init the Cairo VM - let end = cairo_runner - .initialize(cairo_run_config.allow_missing_builtins.unwrap_or(false)) - .map_err(|e| HdpOsError::Runner(e.into()))?; - - // Run the Cairo VM - let mut hint_processor = CustomHintProcessor::new(serde_json::from_slice(&program_inputs)?); - cairo_runner - .run_until_pc(end, &mut hint_processor) - .map_err(|err| VmException::from_vm_error(&cairo_runner, err)) - .map_err(|e| HdpOsError::Runner(e.into()))?; - - Ok(()) -} - -use cairo_vm::vm::errors::cairo_run_errors::CairoRunError; -use thiserror::Error; - -#[derive(Error, Debug)] -pub enum HdpOsError { - #[error(transparent)] - Args(#[from] clap::error::Error), - #[error("Runner Error: {0}")] - Runner(CairoRunError), - #[error("Output Error: {0}")] - Output(String), - #[error(transparent)] - IO(#[from] std::io::Error), - #[error(transparent)] - SerdeJson(#[from] serde_json::Error), -} From eb3d8375f263732cd7a057839c74518c131b48c2 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 18 Dec 2024 08:53:22 +0100 Subject: [PATCH 43/75] format --- .gitignore | 1 + Cargo.lock | 48 +++++++------------ Cargo.toml | 6 +-- clippy.toml | 1 + crates/cairo_types/Cargo.toml | 14 ------ .../Cargo.toml | 3 +- .../src/dry_run_input.rs | 0 .../src/lib.rs | 2 - .../src/output.rs | 0 .../src/run_input.rs | 0 .../src/scopes.rs | 0 .../src/syscall_handler/evm/account.rs | 27 ++++++----- .../src/syscall_handler/evm/header.rs | 28 ++++++----- .../src/syscall_handler/evm/mod.rs | 8 ++-- .../src/syscall_handler/evm/receipt.rs | 0 .../src/syscall_handler/evm/storage.rs | 35 +++++++++----- .../src/syscall_handler/evm/transaction.rs | 0 .../src/syscall_handler/mod.rs | 1 - .../syscall_handler/starknet/dryrun}/mod.rs | 0 .../src/syscall_handler/starknet/mod.rs | 0 .../syscall_handler/starknet/soundrun}/mod.rs | 0 .../src/syscall_handler/traits.rs | 3 +- .../src/syscall_handler/utils.rs | 0 .../src/tests/mod.rs | 0 crates/dry_run/Cargo.toml | 2 +- crates/dry_run/src/main.rs | 3 +- .../src/syscall_handler/keys/mod.rs | 13 ----- crates/fetcher/Cargo.toml | 2 +- crates/fetcher/src/main.rs | 2 +- crates/fetcher/src/proof_keys.rs | 19 ++++---- crates/hints/Cargo.toml | 1 - .../hints/src/contract_bootloader/builtins.rs | 2 +- .../hints/src/contract_bootloader/program.rs | 2 +- crates/types/Cargo.toml | 6 ++- .../src => types/src/cairo}/evm/account.rs | 2 +- .../src => types/src/cairo}/evm/header.rs | 2 +- .../src => types/src/cairo}/evm/mod.rs | 0 .../src => types/src/cairo}/evm/receipt.rs | 2 +- .../src => types/src/cairo}/evm/storage.rs | 2 +- .../src/cairo}/evm/transaction.rs | 2 +- .../src/lib.rs => types/src/cairo/mod.rs} | 0 .../src => types/src/cairo}/new_syscalls.rs | 0 .../src/cairo/starknet}/mod.rs | 0 .../src => types/src/cairo}/structs.rs | 2 +- .../src => types/src/cairo}/traits.rs | 0 .../src}/keys/account.rs | 34 +++---------- .../src}/keys/header.rs | 36 ++------------ crates/types/src/keys/mod.rs | 14 ++++++ .../src}/keys/receipt.rs | 0 .../src}/keys/storage.rs | 41 ++++------------ .../src}/keys/transaction.rs | 0 crates/types/src/lib.rs | 4 ++ rust-toolchain => rust-toolchain.toml | 0 53 files changed, 149 insertions(+), 221 deletions(-) create mode 100644 clippy.toml delete mode 100644 crates/cairo_types/Cargo.toml rename crates/{dry_run_hint_processor => dry_hint_processor}/Cargo.toml (92%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/dry_run_input.rs (100%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/lib.rs (99%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/output.rs (100%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/run_input.rs (100%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/scopes.rs (100%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/syscall_handler/evm/account.rs (66%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/syscall_handler/evm/header.rs (63%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/syscall_handler/evm/mod.rs (97%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/syscall_handler/evm/receipt.rs (100%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/syscall_handler/evm/storage.rs (64%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/syscall_handler/evm/transaction.rs (100%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/syscall_handler/mod.rs (99%) rename crates/{cairo_types/src/starknet => dry_hint_processor/src/syscall_handler/starknet/dryrun}/mod.rs (100%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/syscall_handler/starknet/mod.rs (100%) rename crates/{dry_run_hint_processor/src/syscall_handler/starknet/dryrun => dry_hint_processor/src/syscall_handler/starknet/soundrun}/mod.rs (100%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/syscall_handler/traits.rs (96%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/syscall_handler/utils.rs (100%) rename crates/{dry_run_hint_processor => dry_hint_processor}/src/tests/mod.rs (100%) delete mode 100644 crates/dry_run_hint_processor/src/syscall_handler/keys/mod.rs rename crates/{cairo_types/src => types/src/cairo}/evm/account.rs (97%) rename crates/{cairo_types/src => types/src/cairo}/evm/header.rs (99%) rename crates/{cairo_types/src => types/src/cairo}/evm/mod.rs (100%) rename crates/{cairo_types/src => types/src/cairo}/evm/receipt.rs (95%) rename crates/{cairo_types/src => types/src/cairo}/evm/storage.rs (96%) rename crates/{cairo_types/src => types/src/cairo}/evm/transaction.rs (95%) rename crates/{cairo_types/src/lib.rs => types/src/cairo/mod.rs} (100%) rename crates/{cairo_types/src => types/src/cairo}/new_syscalls.rs (100%) rename crates/{dry_run_hint_processor/src/syscall_handler/starknet/soundrun => types/src/cairo/starknet}/mod.rs (100%) rename crates/{cairo_types/src => types/src/cairo}/structs.rs (98%) rename crates/{cairo_types/src => types/src/cairo}/traits.rs (100%) rename crates/{dry_run_hint_processor/src/syscall_handler => types/src}/keys/account.rs (60%) rename crates/{dry_run_hint_processor/src/syscall_handler => types/src}/keys/header.rs (58%) create mode 100644 crates/types/src/keys/mod.rs rename crates/{dry_run_hint_processor/src/syscall_handler => types/src}/keys/receipt.rs (100%) rename crates/{dry_run_hint_processor/src/syscall_handler => types/src}/keys/storage.rs (61%) rename crates/{dry_run_hint_processor/src/syscall_handler => types/src}/keys/transaction.rs (100%) rename rust-toolchain => rust-toolchain.toml (100%) diff --git a/.gitignore b/.gitignore index 8af5fa99..ab714bcf 100644 --- a/.gitignore +++ b/.gitignore @@ -61,3 +61,4 @@ hdp/ # Scarb & snfoundry target .snfoundry_cache/ +.cargo \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index ca24c4a3..b18331ba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1632,20 +1632,6 @@ dependencies = [ "zip", ] -[[package]] -name = "cairo_types" -version = "0.1.0" -dependencies = [ - "alloy", - "alloy-rlp", - "cairo-lang-casm", - "cairo-lang-starknet-classes", - "cairo-type-derive", - "cairo-vm", - "starknet-crypto 0.7.3", - "strum_macros", -] - [[package]] name = "cc" version = "1.2.2" @@ -2053,19 +2039,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aac81fa3e28d21450aa4d2ac065992ba96a1d7303efbce51a95f4fd175b67562" [[package]] -name = "dry_run" -version = "0.1.0" -dependencies = [ - "cairo-vm", - "clap", - "dry_run_hint_processor", - "hints", - "serde_json", - "thiserror 1.0.69", -] - -[[package]] -name = "dry_run_hint_processor" +name = "dry_hint_processor" version = "0.1.0" dependencies = [ "alloy", @@ -2075,7 +2049,6 @@ dependencies = [ "cairo-lang-starknet-classes", "cairo-type-derive", "cairo-vm", - "cairo_types", "hex", "hints", "indexer", @@ -2095,6 +2068,18 @@ dependencies = [ "types", ] +[[package]] +name = "dry_run" +version = "0.1.0" +dependencies = [ + "cairo-vm", + "clap", + "dry_hint_processor", + "hints", + "serde_json", + "thiserror 1.0.69", +] + [[package]] name = "dunce" version = "1.0.5" @@ -2204,7 +2189,7 @@ dependencies = [ "alloy", "cairo-vm", "clap", - "dry_run_hint_processor", + "dry_hint_processor", "hex", "indexer", "serde_json", @@ -2578,7 +2563,6 @@ dependencies = [ "cairo-lang-starknet-classes", "cairo-type-derive", "cairo-vm", - "cairo_types", "hex", "num-bigint", "num-traits", @@ -5226,6 +5210,7 @@ name = "types" version = "0.1.0" dependencies = [ "alloy", + "alloy-rlp", "cairo-lang-casm", "cairo-lang-starknet-classes", "cairo-type-derive", @@ -5233,6 +5218,9 @@ dependencies = [ "serde", "serde_json", "serde_with 3.11.0", + "starknet-crypto 0.7.3", + "starknet-types-core", + "strum_macros", "thiserror 1.0.69", ] diff --git a/Cargo.toml b/Cargo.toml index 62fe6dcc..08f99e2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,10 +2,9 @@ resolver = "2" members = [ - "crates/cairo_types", "crates/dry_run", "crates/fetcher", - "crates/dry_run_hint_processor", + "crates/dry_hint_processor", "crates/indexer", "crates/hints", "crates/types", @@ -37,8 +36,7 @@ starknet-crypto = { version = "0.7.1", default-features = false } starknet-types-core = { version = "0.1.5", default-features = false } reqwest = "0.12.9" -dry_run_hint_processor = { path = "crates/dry_run_hint_processor" } +dry_hint_processor = { path = "crates/dry_hint_processor" } indexer = { path = "crates/indexer" } -cairo_types = { path = "crates/cairo_types" } types = { path = "crates/types" } hints = { path = "crates/hints" } \ No newline at end of file diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 00000000..78ae4e48 --- /dev/null +++ b/clippy.toml @@ -0,0 +1 @@ +enum-variant-name-threshold = 1 \ No newline at end of file diff --git a/crates/cairo_types/Cargo.toml b/crates/cairo_types/Cargo.toml deleted file mode 100644 index a10cd48d..00000000 --- a/crates/cairo_types/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "cairo_types" -version = "0.1.0" -edition = "2021" - -[dependencies] -alloy.workspace = true -cairo-vm.workspace = true -starknet-crypto.workspace = true -cairo-lang-casm.workspace = true -cairo-lang-starknet-classes.workspace = true -cairo-type-derive.workspace = true -alloy-rlp.workspace = true -strum_macros.workspace = true \ No newline at end of file diff --git a/crates/dry_run_hint_processor/Cargo.toml b/crates/dry_hint_processor/Cargo.toml similarity index 92% rename from crates/dry_run_hint_processor/Cargo.toml rename to crates/dry_hint_processor/Cargo.toml index 00b06f3c..579f4d5e 100644 --- a/crates/dry_run_hint_processor/Cargo.toml +++ b/crates/dry_hint_processor/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "dry_run_hint_processor" +name = "dry_hint_processor" version = "0.1.0" edition = "2021" @@ -27,6 +27,5 @@ strum_macros.workspace = true starknet-core.workspace = true indexer.workspace = true -cairo_types.workspace = true types.workspace = true hints.workspace = true \ No newline at end of file diff --git a/crates/dry_run_hint_processor/src/dry_run_input.rs b/crates/dry_hint_processor/src/dry_run_input.rs similarity index 100% rename from crates/dry_run_hint_processor/src/dry_run_input.rs rename to crates/dry_hint_processor/src/dry_run_input.rs diff --git a/crates/dry_run_hint_processor/src/lib.rs b/crates/dry_hint_processor/src/lib.rs similarity index 99% rename from crates/dry_run_hint_processor/src/lib.rs rename to crates/dry_hint_processor/src/lib.rs index 747eccd6..e602be55 100644 --- a/crates/dry_run_hint_processor/src/lib.rs +++ b/crates/dry_hint_processor/src/lib.rs @@ -25,8 +25,6 @@ use starknet_types_core::felt::Felt; use std::{any::Any, collections::HashMap}; use syscall_handler::evm::SyscallHandlerWrapper; -pub const RPC: &str = "RPC"; - pub type HintImpl = fn(&mut VirtualMachine, &mut ExecutionScopes, &HintProcessorData, &HashMap) -> Result<(), HintError>; /// Hint Extensions extend the current map of hints used by the VM. diff --git a/crates/dry_run_hint_processor/src/output.rs b/crates/dry_hint_processor/src/output.rs similarity index 100% rename from crates/dry_run_hint_processor/src/output.rs rename to crates/dry_hint_processor/src/output.rs diff --git a/crates/dry_run_hint_processor/src/run_input.rs b/crates/dry_hint_processor/src/run_input.rs similarity index 100% rename from crates/dry_run_hint_processor/src/run_input.rs rename to crates/dry_hint_processor/src/run_input.rs diff --git a/crates/dry_run_hint_processor/src/scopes.rs b/crates/dry_hint_processor/src/scopes.rs similarity index 100% rename from crates/dry_run_hint_processor/src/scopes.rs rename to crates/dry_hint_processor/src/scopes.rs diff --git a/crates/dry_run_hint_processor/src/syscall_handler/evm/account.rs b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs similarity index 66% rename from crates/dry_run_hint_processor/src/syscall_handler/evm/account.rs rename to crates/dry_hint_processor/src/syscall_handler/evm/account.rs index d1be42da..6bda75de 100644 --- a/crates/dry_run_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs @@ -1,8 +1,4 @@ use crate::syscall_handler::{ - keys::{ - account::{CairoKey, Key}, - FetchValue, - }, traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, }; @@ -13,11 +9,6 @@ use alloy::{ primitives::{Address, BlockNumber, ChainId}, transports::http::reqwest::Url, }; -use cairo_types::{ - evm::account::{CairoAccount, FunctionId}, - structs::Uint256, - traits::CairoType, -}; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, @@ -25,6 +16,15 @@ use cairo_vm::{ }; use serde::{Deserialize, Serialize}; use std::env; +use types::{ + cairo::{ + evm::account::{CairoAccount, FunctionId}, + structs::Uint256, + traits::CairoType, + }, + keys::account::{CairoKey, Key}, + RPC, +}; pub struct AccountCallHandler; @@ -37,7 +37,7 @@ impl CallHandler for AccountCallHandler { fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { let ret = CairoKey::from_memory(vm, *ptr)?; *ptr = (*ptr + CairoKey::n_fields())?; - ret.try_into() + ret.try_into().map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into())) } fn derive_id(selector: Felt252) -> SyscallResult { @@ -52,6 +52,11 @@ impl CallHandler for AccountCallHandler { } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { - Ok(CairoAccount::from(key.fetch_value()?).handle(function_id)) + let runtime = tokio::runtime::Runtime::new().unwrap(); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let value = runtime + .block_on(async { provider.get_account(key.address).block_id(key.block_number.into()).await }) + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + Ok(CairoAccount::from(value).handle(function_id)) } } diff --git a/crates/dry_run_hint_processor/src/syscall_handler/evm/header.rs b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs similarity index 63% rename from crates/dry_run_hint_processor/src/syscall_handler/evm/header.rs rename to crates/dry_hint_processor/src/syscall_handler/evm/header.rs index 9764e4ac..a920be6d 100644 --- a/crates/dry_run_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs @@ -1,8 +1,4 @@ use crate::syscall_handler::{ - keys::{ - header::{CairoKey, Key}, - FetchValue, - }, traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, }; @@ -13,11 +9,6 @@ use alloy::{ primitives::{BlockNumber, ChainId}, transports::http::reqwest::Url, }; -use cairo_types::{ - evm::header::{CairoHeader, FunctionId}, - structs::Uint256, - traits::CairoType, -}; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, @@ -25,6 +16,15 @@ use cairo_vm::{ }; use serde::{Deserialize, Serialize}; use std::env; +use types::{ + cairo::{ + evm::header::{CairoHeader, FunctionId}, + structs::Uint256, + traits::CairoType, + }, + keys::header::{CairoKey, Key}, + RPC, +}; pub struct HeaderCallHandler; @@ -37,7 +37,7 @@ impl CallHandler for HeaderCallHandler { fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { let ret = CairoKey::from_memory(vm, *ptr)?; *ptr = (*ptr + CairoKey::n_fields())?; - ret.try_into() + ret.try_into().map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into())) } fn derive_id(selector: Felt252) -> SyscallResult { @@ -52,6 +52,12 @@ impl CallHandler for HeaderCallHandler { } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { - Ok(CairoHeader::from(key.fetch_value()?.header.inner).handle(function_id)) + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let runtime = tokio::runtime::Runtime::new().unwrap(); + let value = runtime + .block_on(async { provider.get_block_by_number(key.block_number.into(), BlockTransactionsKind::Hashes).await }) + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))? + .ok_or(SyscallExecutionError::InternalError("Block not found".into()))?; + Ok(CairoHeader::from(value.header.inner).handle(function_id)) } } diff --git a/crates/dry_run_hint_processor/src/syscall_handler/evm/mod.rs b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs similarity index 97% rename from crates/dry_run_hint_processor/src/syscall_handler/evm/mod.rs rename to crates/dry_hint_processor/src/syscall_handler/evm/mod.rs index d97c6e78..c7f13c05 100644 --- a/crates/dry_run_hint_processor/src/syscall_handler/evm/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs @@ -5,14 +5,9 @@ pub mod receipt; pub mod storage; pub mod transaction; -use crate::syscall_handler::keys; use crate::syscall_handler::traits::{self, CallHandler}; use crate::syscall_handler::utils::{felt_from_ptr, SyscallExecutionError, SyscallResult, WriteResponseResult}; use crate::syscall_handler::utils::{run_handler, SyscallSelector}; -use cairo_types::{ - new_syscalls::{CallContractRequest, CallContractResponse}, - traits::CairoType, -}; use cairo_vm::vm::errors::hint_errors::HintError; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use serde::{Deserialize, Serialize}; @@ -21,6 +16,9 @@ use std::rc::Rc; use std::sync::RwLock; use std::{collections::HashSet, hash::Hash, marker::PhantomData}; use strum_macros::FromRepr; +use types::cairo::new_syscalls::{CallContractRequest, CallContractResponse}; +use types::cairo::traits::CairoType; +use types::keys; #[derive(Debug, Default, Serialize, Deserialize)] pub struct SyscallHandler { diff --git a/crates/dry_run_hint_processor/src/syscall_handler/evm/receipt.rs b/crates/dry_hint_processor/src/syscall_handler/evm/receipt.rs similarity index 100% rename from crates/dry_run_hint_processor/src/syscall_handler/evm/receipt.rs rename to crates/dry_hint_processor/src/syscall_handler/evm/receipt.rs diff --git a/crates/dry_run_hint_processor/src/syscall_handler/evm/storage.rs b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs similarity index 64% rename from crates/dry_run_hint_processor/src/syscall_handler/evm/storage.rs rename to crates/dry_hint_processor/src/syscall_handler/evm/storage.rs index 8b951538..dd51e2d2 100644 --- a/crates/dry_run_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs @@ -1,8 +1,4 @@ use crate::syscall_handler::{ - keys::{ - storage::{CairoKey, Key}, - FetchValue, - }, traits::CallHandler, utils::{SyscallExecutionError, SyscallResult}, }; @@ -13,11 +9,6 @@ use alloy::{ primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, transports::http::reqwest::Url, }; -use cairo_types::{ - evm::storage::{CairoStorage, FunctionId}, - structs::Uint256, - traits::CairoType, -}; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, @@ -25,6 +16,18 @@ use cairo_vm::{ }; use serde::{Deserialize, Serialize}; use std::env; +use types::{ + cairo::{ + evm::storage::{CairoStorage, FunctionId}, + structs::Uint256, + traits::CairoType, + }, + keys::{ + storage::{CairoKey, Key}, + KeyError, + }, + RPC, +}; pub struct StorageCallHandler; @@ -37,7 +40,7 @@ impl CallHandler for StorageCallHandler { fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { let ret = CairoKey::from_memory(vm, *ptr)?; *ptr = (*ptr + CairoKey::n_fields())?; - ret.try_into() + ret.try_into().map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into())) } fn derive_id(selector: Felt252) -> SyscallResult { @@ -52,6 +55,16 @@ impl CallHandler for StorageCallHandler { } fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { - Ok(CairoStorage::from(key.fetch_value()?).handle(function_id)) + let runtime = tokio::runtime::Runtime::new().unwrap(); + let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); + let value = runtime + .block_on(async { + provider + .get_storage_at(key.address, key.storage_slot.into()) + .block_id(key.block_number.into()) + .await + }) + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + Ok(CairoStorage::from(value).handle(function_id)) } } diff --git a/crates/dry_run_hint_processor/src/syscall_handler/evm/transaction.rs b/crates/dry_hint_processor/src/syscall_handler/evm/transaction.rs similarity index 100% rename from crates/dry_run_hint_processor/src/syscall_handler/evm/transaction.rs rename to crates/dry_hint_processor/src/syscall_handler/evm/transaction.rs diff --git a/crates/dry_run_hint_processor/src/syscall_handler/mod.rs b/crates/dry_hint_processor/src/syscall_handler/mod.rs similarity index 99% rename from crates/dry_run_hint_processor/src/syscall_handler/mod.rs rename to crates/dry_hint_processor/src/syscall_handler/mod.rs index 6ad113d1..17a986c9 100644 --- a/crates/dry_run_hint_processor/src/syscall_handler/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/mod.rs @@ -9,7 +9,6 @@ use hints::vars; use std::collections::HashMap; pub mod evm; -pub mod keys; pub mod starknet; pub mod traits; pub mod utils; diff --git a/crates/cairo_types/src/starknet/mod.rs b/crates/dry_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs similarity index 100% rename from crates/cairo_types/src/starknet/mod.rs rename to crates/dry_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs diff --git a/crates/dry_run_hint_processor/src/syscall_handler/starknet/mod.rs b/crates/dry_hint_processor/src/syscall_handler/starknet/mod.rs similarity index 100% rename from crates/dry_run_hint_processor/src/syscall_handler/starknet/mod.rs rename to crates/dry_hint_processor/src/syscall_handler/starknet/mod.rs diff --git a/crates/dry_run_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs b/crates/dry_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs similarity index 100% rename from crates/dry_run_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs rename to crates/dry_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs diff --git a/crates/dry_run_hint_processor/src/syscall_handler/traits.rs b/crates/dry_hint_processor/src/syscall_handler/traits.rs similarity index 96% rename from crates/dry_run_hint_processor/src/syscall_handler/traits.rs rename to crates/dry_hint_processor/src/syscall_handler/traits.rs index eab0b3c4..4bc8ac8a 100644 --- a/crates/dry_run_hint_processor/src/syscall_handler/traits.rs +++ b/crates/dry_hint_processor/src/syscall_handler/traits.rs @@ -1,7 +1,6 @@ -use cairo_types::traits::CairoType; - use super::utils::{SyscallResult, WriteResponseResult}; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use types::cairo::traits::CairoType; pub trait SyscallHandler { type Request; diff --git a/crates/dry_run_hint_processor/src/syscall_handler/utils.rs b/crates/dry_hint_processor/src/syscall_handler/utils.rs similarity index 100% rename from crates/dry_run_hint_processor/src/syscall_handler/utils.rs rename to crates/dry_hint_processor/src/syscall_handler/utils.rs diff --git a/crates/dry_run_hint_processor/src/tests/mod.rs b/crates/dry_hint_processor/src/tests/mod.rs similarity index 100% rename from crates/dry_run_hint_processor/src/tests/mod.rs rename to crates/dry_hint_processor/src/tests/mod.rs diff --git a/crates/dry_run/Cargo.toml b/crates/dry_run/Cargo.toml index f809b794..6140100c 100644 --- a/crates/dry_run/Cargo.toml +++ b/crates/dry_run/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] -dry_run_hint_processor.workspace = true +dry_hint_processor.workspace = true cairo-vm.workspace = true clap.workspace = true thiserror.workspace = true diff --git a/crates/dry_run/src/main.rs b/crates/dry_run/src/main.rs index faa1e930..a0c1463a 100644 --- a/crates/dry_run/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -6,8 +6,7 @@ use cairo_vm::{ vm::{errors::vm_exception::VmException, runners::cairo_runner::CairoRunner}, }; use clap::{Parser, ValueHint}; -use dry_run_hint_processor::{ - self, +use dry_hint_processor::{ syscall_handler::evm::{SyscallHandler, SyscallHandlerWrapper}, CustomHintProcessor, }; diff --git a/crates/dry_run_hint_processor/src/syscall_handler/keys/mod.rs b/crates/dry_run_hint_processor/src/syscall_handler/keys/mod.rs deleted file mode 100644 index 89a59d2f..00000000 --- a/crates/dry_run_hint_processor/src/syscall_handler/keys/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -#![allow(unused)] - -use super::utils::SyscallExecutionError; -pub mod account; -pub mod header; -pub mod receipt; -pub mod storage; -pub mod transaction; - -pub trait FetchValue { - type Value; - fn fetch_value(&self) -> Result; -} diff --git a/crates/fetcher/Cargo.toml b/crates/fetcher/Cargo.toml index f1804bb3..b01bd65e 100644 --- a/crates/fetcher/Cargo.toml +++ b/crates/fetcher/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] -dry_run_hint_processor.workspace = true +dry_hint_processor.workspace = true cairo-vm.workspace = true clap.workspace = true thiserror.workspace = true diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index 1cbc3580..253bbb23 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -1,7 +1,7 @@ #![forbid(unsafe_code)] #![allow(async_fn_in_trait)] use clap::{Parser, ValueHint}; -use dry_run_hint_processor::syscall_handler::evm::{self, SyscallHandler}; +use dry_hint_processor::syscall_handler::evm::{self, SyscallHandler}; use fetcher::{proof_keys::ProofKeys, FetcherError}; use std::{collections::HashSet, fs, path::PathBuf}; use types::proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}; diff --git a/crates/fetcher/src/proof_keys.rs b/crates/fetcher/src/proof_keys.rs index 263c357b..b5882d5c 100644 --- a/crates/fetcher/src/proof_keys.rs +++ b/crates/fetcher/src/proof_keys.rs @@ -4,19 +4,22 @@ use alloy::{ providers::{Provider, RootProvider}, transports::http::{reqwest::Url, Client, Http}, }; -use dry_run_hint_processor::{syscall_handler::keys, RPC}; use indexer::{ types::{BlockHeader, IndexerQuery}, Indexer, }; use std::{collections::HashSet, env}; -use types::proofs::{ - account::Account, - header::{Header, HeaderProof}, - mmr::MmrMeta, - mpt::MPTProof, - storage::Storage, - HeaderMmrMeta, +use types::{ + keys, + proofs::{ + account::Account, + header::{Header, HeaderProof}, + mmr::MmrMeta, + mpt::MPTProof, + storage::Storage, + HeaderMmrMeta, + }, + RPC, }; use crate::FetcherError; diff --git a/crates/hints/Cargo.toml b/crates/hints/Cargo.toml index 8de6c697..6fe90dc3 100644 --- a/crates/hints/Cargo.toml +++ b/crates/hints/Cargo.toml @@ -26,5 +26,4 @@ reqwest.workspace = true strum_macros.workspace = true starknet-core.workspace = true -cairo_types.workspace = true types.workspace = true \ No newline at end of file diff --git a/crates/hints/src/contract_bootloader/builtins.rs b/crates/hints/src/contract_bootloader/builtins.rs index a96ed175..99e1a695 100644 --- a/crates/hints/src/contract_bootloader/builtins.rs +++ b/crates/hints/src/contract_bootloader/builtins.rs @@ -1,5 +1,4 @@ use crate::vars; -use cairo_types::structs::BuiltinParams; use cairo_vm::{ hint_processor::{ builtin_hint_processor::{ @@ -13,6 +12,7 @@ use cairo_vm::{ Felt252, }; use std::{any::Any, collections::HashMap}; +use types::cairo::structs::BuiltinParams; pub const UPDATE_BUILTIN_PTRS: &str = "from starkware.starknet.core.os.os_utils import update_builtin_pointers\n\n# Fill the values of all builtin pointers after the current transaction.\nids.return_builtin_ptrs = segments.gen_arg(\n update_builtin_pointers(\n memory=memory,\n n_builtins=ids.n_builtins,\n builtins_encoding_addr=ids.builtin_params.builtin_encodings.address_,\n n_selected_builtins=ids.n_selected_builtins,\n selected_builtins_encoding_addr=ids.selected_encodings,\n orig_builtin_ptrs_addr=ids.builtin_ptrs.selectable.address_,\n selected_builtin_ptrs_addr=ids.selected_ptrs,\n ),\n )"; diff --git a/crates/hints/src/contract_bootloader/program.rs b/crates/hints/src/contract_bootloader/program.rs index 4be4b6bc..c086152f 100644 --- a/crates/hints/src/contract_bootloader/program.rs +++ b/crates/hints/src/contract_bootloader/program.rs @@ -1,6 +1,5 @@ use crate::vars; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; -use cairo_types::structs::CompiledClass; use cairo_vm::{ any_box, hint_processor::{ @@ -12,6 +11,7 @@ use cairo_vm::{ Felt252, }; use std::collections::HashMap; +use types::cairo::structs::CompiledClass; pub const LOAD_PROGRAM: &str = "vm_load_program(\n compiled_class.get_runnable_program(entrypoint_builtins=[]),\n ids.compiled_class.bytecode_ptr\n)"; diff --git a/crates/types/Cargo.toml b/crates/types/Cargo.toml index 09c5c35e..9654198a 100644 --- a/crates/types/Cargo.toml +++ b/crates/types/Cargo.toml @@ -12,4 +12,8 @@ cairo-vm.workspace = true serde_json.workspace = true serde_with.workspace = true serde.workspace = true -thiserror.workspace = true \ No newline at end of file +thiserror.workspace = true +starknet-crypto.workspace = true +starknet-types-core.workspace = true +alloy-rlp.workspace = true +strum_macros.workspace = true \ No newline at end of file diff --git a/crates/cairo_types/src/evm/account.rs b/crates/types/src/cairo/evm/account.rs similarity index 97% rename from crates/cairo_types/src/evm/account.rs rename to crates/types/src/cairo/evm/account.rs index 08574e0d..fd4ad16d 100644 --- a/crates/cairo_types/src/evm/account.rs +++ b/crates/types/src/cairo/evm/account.rs @@ -1,4 +1,4 @@ -use crate::structs::Uint256; +use crate::cairo::structs::Uint256; use alloy::{consensus::Account, primitives::keccak256, rpc::types::EIP1186AccountProofResponse}; use alloy_rlp::{Decodable, Encodable}; use cairo_vm::Felt252; diff --git a/crates/cairo_types/src/evm/header.rs b/crates/types/src/cairo/evm/header.rs similarity index 99% rename from crates/cairo_types/src/evm/header.rs rename to crates/types/src/cairo/evm/header.rs index af6261e1..1090fbe8 100644 --- a/crates/cairo_types/src/evm/header.rs +++ b/crates/types/src/cairo/evm/header.rs @@ -1,4 +1,4 @@ -use crate::structs::Uint256; +use crate::cairo::structs::Uint256; use alloy::{ consensus::Header, primitives::{keccak256, Bloom, Bytes}, diff --git a/crates/cairo_types/src/evm/mod.rs b/crates/types/src/cairo/evm/mod.rs similarity index 100% rename from crates/cairo_types/src/evm/mod.rs rename to crates/types/src/cairo/evm/mod.rs diff --git a/crates/cairo_types/src/evm/receipt.rs b/crates/types/src/cairo/evm/receipt.rs similarity index 95% rename from crates/cairo_types/src/evm/receipt.rs rename to crates/types/src/cairo/evm/receipt.rs index c3bcb784..6c557c42 100644 --- a/crates/cairo_types/src/evm/receipt.rs +++ b/crates/types/src/cairo/evm/receipt.rs @@ -1,4 +1,4 @@ -use crate::structs::Uint256; +use crate::cairo::structs::Uint256; use alloy::{ consensus::{ReceiptWithBloom, RlpEncodableReceipt, TxReceipt}, primitives::keccak256, diff --git a/crates/cairo_types/src/evm/storage.rs b/crates/types/src/cairo/evm/storage.rs similarity index 96% rename from crates/cairo_types/src/evm/storage.rs rename to crates/types/src/cairo/evm/storage.rs index 2ad0626f..5a18d4ab 100644 --- a/crates/cairo_types/src/evm/storage.rs +++ b/crates/types/src/cairo/evm/storage.rs @@ -1,4 +1,4 @@ -use crate::structs::Uint256; +use crate::cairo::structs::Uint256; use alloy::primitives::{keccak256, StorageValue}; use alloy_rlp::{Decodable, Encodable}; use cairo_vm::Felt252; diff --git a/crates/cairo_types/src/evm/transaction.rs b/crates/types/src/cairo/evm/transaction.rs similarity index 95% rename from crates/cairo_types/src/evm/transaction.rs rename to crates/types/src/cairo/evm/transaction.rs index 7659acf3..c65cbddf 100644 --- a/crates/cairo_types/src/evm/transaction.rs +++ b/crates/types/src/cairo/evm/transaction.rs @@ -1,4 +1,4 @@ -use crate::structs::Uint256; +use crate::cairo::structs::Uint256; use alloy::{consensus::transaction::TxEnvelope, rpc::types::Transaction}; use alloy_rlp::{Decodable, Encodable}; diff --git a/crates/cairo_types/src/lib.rs b/crates/types/src/cairo/mod.rs similarity index 100% rename from crates/cairo_types/src/lib.rs rename to crates/types/src/cairo/mod.rs diff --git a/crates/cairo_types/src/new_syscalls.rs b/crates/types/src/cairo/new_syscalls.rs similarity index 100% rename from crates/cairo_types/src/new_syscalls.rs rename to crates/types/src/cairo/new_syscalls.rs diff --git a/crates/dry_run_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs b/crates/types/src/cairo/starknet/mod.rs similarity index 100% rename from crates/dry_run_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs rename to crates/types/src/cairo/starknet/mod.rs diff --git a/crates/cairo_types/src/structs.rs b/crates/types/src/cairo/structs.rs similarity index 98% rename from crates/cairo_types/src/structs.rs rename to crates/types/src/cairo/structs.rs index c8534ae2..0ab5e454 100644 --- a/crates/cairo_types/src/structs.rs +++ b/crates/types/src/cairo/structs.rs @@ -1,4 +1,4 @@ -use crate::traits::CairoType; +use crate::cairo::traits::CairoType; use alloy::primitives::{Address, B256, B64, U256}; use cairo_type_derive::{CairoType, FieldOffsetGetters}; use cairo_vm::{ diff --git a/crates/cairo_types/src/traits.rs b/crates/types/src/cairo/traits.rs similarity index 100% rename from crates/cairo_types/src/traits.rs rename to crates/types/src/cairo/traits.rs diff --git a/crates/dry_run_hint_processor/src/syscall_handler/keys/account.rs b/crates/types/src/keys/account.rs similarity index 60% rename from crates/dry_run_hint_processor/src/syscall_handler/keys/account.rs rename to crates/types/src/keys/account.rs index 97011f08..612bcef0 100644 --- a/crates/dry_run_hint_processor/src/syscall_handler/keys/account.rs +++ b/crates/types/src/keys/account.rs @@ -1,4 +1,5 @@ -use crate::{syscall_handler::utils::SyscallExecutionError, RPC}; +use super::{storage, KeyError}; +use crate::cairo::traits::CairoType; use alloy::{ consensus::Account, primitives::{Address, BlockNumber, ChainId}, @@ -6,18 +7,14 @@ use alloy::{ rpc::types::EIP1186AccountProofResponse, transports::http::Http, }; -use cairo_types::traits::CairoType; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; -use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use std::env; -use super::{storage, FetchValue}; - #[derive(Debug)] pub struct CairoKey { chain_id: Felt252, @@ -51,19 +48,6 @@ pub struct Key { pub address: Address, } -impl FetchValue for Key { - type Value = Account; - - fn fetch_value(&self) -> Result { - let runtime = tokio::runtime::Runtime::new().unwrap(); - let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let value = runtime - .block_on(async { provider.get_account(self.address).block_id(self.block_number.into()).await }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(value) - } -} - impl From for Key { fn from(value: storage::Key) -> Self { Self { @@ -75,19 +59,13 @@ impl From for Key { } impl TryFrom for Key { - type Error = SyscallExecutionError; + type Error = KeyError; fn try_from(value: CairoKey) -> Result { Ok(Self { - chain_id: value - .chain_id - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - block_number: value - .block_number - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + chain_id: value.chain_id.try_into().map_err(|e| KeyError::ConversionError(format!("{}", e)))?, + block_number: value.block_number.try_into().map_err(|e| KeyError::ConversionError(format!("{}", e)))?, address: Address::try_from(value.address.to_biguint().to_bytes_be().as_slice()) - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + .map_err(|e| KeyError::ConversionError(format!("{}", e)))?, }) } } diff --git a/crates/dry_run_hint_processor/src/syscall_handler/keys/header.rs b/crates/types/src/keys/header.rs similarity index 58% rename from crates/dry_run_hint_processor/src/syscall_handler/keys/header.rs rename to crates/types/src/keys/header.rs index 83e80090..80bfb85a 100644 --- a/crates/dry_run_hint_processor/src/syscall_handler/keys/header.rs +++ b/crates/types/src/keys/header.rs @@ -1,5 +1,5 @@ -use super::{account, storage, FetchValue}; -use crate::{syscall_handler::utils::SyscallExecutionError, RPC}; +use super::{account, storage, KeyError}; +use crate::cairo::traits::CairoType; use alloy::{ hex::FromHexError, primitives::{BlockNumber, Bytes, ChainId}, @@ -7,13 +7,11 @@ use alloy::{ rpc::types::{Block, BlockTransactionsKind}, transports::http::Http, }; -use cairo_types::traits::CairoType; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; -use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use starknet_types_core::felt::FromStrError; use std::env; @@ -47,24 +45,6 @@ pub struct Key { pub block_number: BlockNumber, } -impl FetchValue for Key { - type Value = Block; - - fn fetch_value(&self) -> Result { - let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let runtime = tokio::runtime::Runtime::new().unwrap(); - let block = runtime - .block_on(async { - provider - .get_block_by_number(self.block_number.into(), BlockTransactionsKind::Hashes) - .await - }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))? - .ok_or(SyscallExecutionError::InternalError("Block not found".into()))?; - Ok(block) - } -} - impl From for Key { fn from(value: account::Key) -> Self { Self { @@ -84,17 +64,11 @@ impl From for Key { } impl TryFrom for Key { - type Error = SyscallExecutionError; + type Error = KeyError; fn try_from(value: CairoKey) -> Result { Ok(Self { - chain_id: value - .chain_id - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - block_number: value - .block_number - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + chain_id: value.chain_id.try_into().map_err(|e| KeyError::ConversionError(format!("{}", e)))?, + block_number: value.block_number.try_into().map_err(|e| KeyError::ConversionError(format!("{}", e)))?, }) } } diff --git a/crates/types/src/keys/mod.rs b/crates/types/src/keys/mod.rs new file mode 100644 index 00000000..e0933ff1 --- /dev/null +++ b/crates/types/src/keys/mod.rs @@ -0,0 +1,14 @@ +#![allow(unused)] +pub mod account; +pub mod header; +pub mod receipt; +pub mod storage; +pub mod transaction; + +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum KeyError { + #[error("Conversion Error: {0}")] + ConversionError(String), +} diff --git a/crates/dry_run_hint_processor/src/syscall_handler/keys/receipt.rs b/crates/types/src/keys/receipt.rs similarity index 100% rename from crates/dry_run_hint_processor/src/syscall_handler/keys/receipt.rs rename to crates/types/src/keys/receipt.rs diff --git a/crates/dry_run_hint_processor/src/syscall_handler/keys/storage.rs b/crates/types/src/keys/storage.rs similarity index 61% rename from crates/dry_run_hint_processor/src/syscall_handler/keys/storage.rs rename to crates/types/src/keys/storage.rs index c14ca05c..3e038c75 100644 --- a/crates/dry_run_hint_processor/src/syscall_handler/keys/storage.rs +++ b/crates/types/src/keys/storage.rs @@ -1,21 +1,20 @@ -use super::FetchValue; -use crate::{syscall_handler::utils::SyscallExecutionError, RPC}; +use crate::cairo::traits::CairoType; use alloy::{ primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, providers::{Provider, RootProvider}, rpc::types::EIP1186AccountProofResponse, transports::http::Http, }; -use cairo_types::traits::CairoType; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; -use reqwest::{Client, Url}; use serde::{Deserialize, Serialize}; use std::env; +use super::KeyError; + #[derive(Debug)] pub struct CairoKey { chain_id: Felt252, @@ -56,38 +55,14 @@ pub struct Key { pub storage_slot: StorageKey, } -impl FetchValue for Key { - type Value = StorageValue; - - fn fetch_value(&self) -> Result { - let runtime = tokio::runtime::Runtime::new().unwrap(); - let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let value = runtime - .block_on(async { - provider - .get_storage_at(self.address, self.storage_slot.into()) - .block_id(self.block_number.into()) - .await - }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(value) - } -} - impl TryFrom for Key { - type Error = SyscallExecutionError; + type Error = KeyError; fn try_from(value: CairoKey) -> Result { Ok(Self { - chain_id: value - .chain_id - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - block_number: value - .block_number - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + chain_id: value.chain_id.try_into().map_err(|e| KeyError::ConversionError(format!("{}", e)))?, + block_number: value.block_number.try_into().map_err(|e| KeyError::ConversionError(format!("{}", e)))?, address: Address::try_from(value.address.to_biguint().to_bytes_be().as_slice()) - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + .map_err(|e| KeyError::ConversionError(format!("{}", e)))?, storage_slot: StorageKey::from( &[ &value.storage_slot_high.to_bytes_be().as_slice()[16..], @@ -95,7 +70,7 @@ impl TryFrom for Key { ] .concat() .try_into() - .map_err(|_| SyscallExecutionError::InternalError("Failed to form StorageKey".into()))?, + .map_err(|_| KeyError::ConversionError("Failed to form StorageKey".into()))?, ), }) } diff --git a/crates/dry_run_hint_processor/src/syscall_handler/keys/transaction.rs b/crates/types/src/keys/transaction.rs similarity index 100% rename from crates/dry_run_hint_processor/src/syscall_handler/keys/transaction.rs rename to crates/types/src/keys/transaction.rs diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index f6c722b4..43a13215 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -1,3 +1,5 @@ +pub mod cairo; +pub mod keys; pub mod param; pub mod proofs; @@ -6,6 +8,8 @@ use param::Param; use proofs::Proofs; use serde::{Deserialize, Serialize}; +pub const RPC: &str = "RPC"; + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct HDPDryRunInput { pub params: Vec, diff --git a/rust-toolchain b/rust-toolchain.toml similarity index 100% rename from rust-toolchain rename to rust-toolchain.toml From 37ab74104ddb61f3cb095e9c6a0b671031d29205 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 18 Dec 2024 09:07:43 +0100 Subject: [PATCH 44/75] rm unused --- .../src/{dry_run_input.rs => input.rs} | 4 +- crates/dry_hint_processor/src/lib.rs | 9 +- crates/dry_hint_processor/src/scopes.rs | 23 ----- .../src/syscall_handler/evm/account.rs | 13 +-- .../src/syscall_handler/evm/header.rs | 12 +-- .../src/syscall_handler/evm/mod.rs | 4 +- .../src/syscall_handler/evm/storage.rs | 18 +--- .../src/syscall_handler/mod.rs | 16 +++- .../syscall_handler/starknet/dryrun/mod.rs | 1 - .../src/syscall_handler/starknet/mod.rs | 3 +- .../syscall_handler/starknet/soundrun/mod.rs | 1 - crates/types/src/cairo/evm/account.rs | 3 +- crates/types/src/cairo/evm/header.rs | 1 - crates/types/src/cairo/evm/mod.rs | 1 - crates/types/src/cairo/evm/storage.rs | 1 - crates/types/src/cairo/new_syscalls.rs | 2 - crates/types/src/cairo/structs.rs | 1 - crates/types/src/cairo/traits.rs | 90 ------------------- crates/types/src/keys/account.rs | 9 +- crates/types/src/keys/header.rs | 10 +-- crates/types/src/keys/mod.rs | 1 - crates/types/src/keys/storage.rs | 11 +-- 22 files changed, 34 insertions(+), 200 deletions(-) rename crates/dry_hint_processor/src/{dry_run_input.rs => input.rs} (80%) delete mode 100644 crates/dry_hint_processor/src/scopes.rs delete mode 100644 crates/dry_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs delete mode 100644 crates/dry_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs diff --git a/crates/dry_hint_processor/src/dry_run_input.rs b/crates/dry_hint_processor/src/input.rs similarity index 80% rename from crates/dry_hint_processor/src/dry_run_input.rs rename to crates/dry_hint_processor/src/input.rs index 02f98eb8..1659493f 100644 --- a/crates/dry_hint_processor/src/dry_run_input.rs +++ b/crates/dry_hint_processor/src/input.rs @@ -10,10 +10,10 @@ use hints::vars; use std::collections::HashMap; use types::{param::Param, HDPDryRunInput}; -pub const HINT_DRY_RUN_INPUT: &str = "from tools.py.schema import HDPDryRunInput\ndry_run_input = HDPDryRunInput.Schema().load(program_input)\nparams = dry_run_input.params\ncompiled_class = dry_run_input.compiled_class"; +pub const HINT_INPUT: &str = "from tools.py.schema import HDPDryRunInput\ndry_run_input = HDPDryRunInput.Schema().load(program_input)\nparams = dry_run_input.params\ncompiled_class = dry_run_input.compiled_class"; impl CustomHintProcessor { - pub fn hint_dry_run_input( + pub fn hint_input( &mut self, _vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, diff --git a/crates/dry_hint_processor/src/lib.rs b/crates/dry_hint_processor/src/lib.rs index e602be55..ae8cc898 100644 --- a/crates/dry_hint_processor/src/lib.rs +++ b/crates/dry_hint_processor/src/lib.rs @@ -1,9 +1,7 @@ #![forbid(unsafe_code)] #![allow(async_fn_in_trait)] -pub mod dry_run_input; +pub mod input; pub mod output; -pub mod run_input; -pub mod scopes; pub mod syscall_handler; use cairo_lang_casm::{ @@ -129,7 +127,7 @@ impl CustomHintProcessor { hints.insert(syscall_handler::DRY_RUN_SYSCALL_HANDLER_CREATE.into(), syscall_handler::dry_run_syscall_handler_create); hints.insert(syscall_handler::SYSCALL_HANDLER_CREATE.into(), syscall_handler::syscall_handler_create); hints.insert(syscall_handler::SYSCALL_HANDLER_SET_SYSCALL_PTR.into(), syscall_handler::syscall_handler_set_syscall_ptr); - hints.insert(scopes::ENTER_SCOPE_SYSCALL_HANDLER.into(), scopes::enter_scope_syscall_handler); + hints.insert(syscall_handler::ENTER_SCOPE_SYSCALL_HANDLER.into(), syscall_handler::enter_scope_syscall_handler); hints } @@ -163,8 +161,7 @@ impl HintProcessorLogic for CustomHintProcessor { let hint_code = hpd.code.as_str(); let res = match hint_code { - crate::dry_run_input::HINT_DRY_RUN_INPUT => self.hint_dry_run_input(vm, exec_scopes, hpd, constants), - crate::run_input::HINT_RUN_INPUT => self.hint_run_input(vm, exec_scopes, hpd, constants), + crate::input::HINT_INPUT => self.hint_input(vm, exec_scopes, hpd, constants), crate::output::HINT_OUTPUT => self.hint_output(vm, exec_scopes, hpd, constants), _ => Err(HintError::UnknownHint(hint_code.to_string().into_boxed_str())), }; diff --git a/crates/dry_hint_processor/src/scopes.rs b/crates/dry_hint_processor/src/scopes.rs deleted file mode 100644 index 3707f199..00000000 --- a/crates/dry_hint_processor/src/scopes.rs +++ /dev/null @@ -1,23 +0,0 @@ -use crate::syscall_handler::evm::SyscallHandlerWrapper; -use cairo_vm::{ - hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData, - types::exec_scope::ExecutionScopes, - vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, - Felt252, -}; -use hints::vars; -use std::{any::Any, collections::HashMap}; - -pub const ENTER_SCOPE_SYSCALL_HANDLER: &str = "vm_enter_scope({'syscall_handler': syscall_handler})"; - -pub fn enter_scope_syscall_handler( - _vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - _hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let syscall_handler: Box = Box::new(exec_scopes.get::(vars::scopes::SYSCALL_HANDLER)?); - exec_scopes.enter_scope(HashMap::from_iter([(vars::scopes::SYSCALL_HANDLER.to_string(), syscall_handler)])); - - Ok(()) -} diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs index 6bda75de..4685a142 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs @@ -3,18 +3,9 @@ use crate::syscall_handler::{ utils::{SyscallExecutionError, SyscallResult}, }; use alloy::providers::{Provider, RootProvider}; +use alloy::transports::http::reqwest::Url; use alloy::transports::http::{Client, Http}; -use alloy::{ - hex::FromHex, - primitives::{Address, BlockNumber, ChainId}, - transports::http::reqwest::Url, -}; -use cairo_vm::{ - types::relocatable::Relocatable, - vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, - Felt252, -}; -use serde::{Deserialize, Serialize}; +use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use std::env; use types::{ cairo::{ diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs index a920be6d..985a878a 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs @@ -4,17 +4,9 @@ use crate::syscall_handler::{ }; use alloy::providers::{Provider, RootProvider}; use alloy::rpc::types::BlockTransactionsKind; +use alloy::transports::http::reqwest::Url; use alloy::transports::http::{Client, Http}; -use alloy::{ - primitives::{BlockNumber, ChainId}, - transports::http::reqwest::Url, -}; -use cairo_vm::{ - types::relocatable::Relocatable, - vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, - Felt252, -}; -use serde::{Deserialize, Serialize}; +use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use std::env; use types::{ cairo::{ diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs index c7f13c05..9410a79d 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs @@ -1,4 +1,3 @@ -#![allow(unused)] pub mod account; pub mod header; pub mod receipt; @@ -11,10 +10,9 @@ use crate::syscall_handler::utils::{run_handler, SyscallSelector}; use cairo_vm::vm::errors::hint_errors::HintError; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use serde::{Deserialize, Serialize}; -use serde_json::Value; use std::rc::Rc; use std::sync::RwLock; -use std::{collections::HashSet, hash::Hash, marker::PhantomData}; +use std::{collections::HashSet, hash::Hash}; use strum_macros::FromRepr; use types::cairo::new_syscalls::{CallContractRequest, CallContractResponse}; use types::cairo::traits::CairoType; diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs index dd51e2d2..afc728d0 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs @@ -3,18 +3,9 @@ use crate::syscall_handler::{ utils::{SyscallExecutionError, SyscallResult}, }; use alloy::providers::{Provider, RootProvider}; +use alloy::transports::http::reqwest::Url; use alloy::transports::http::{Client, Http}; -use alloy::{ - hex::FromHex, - primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, - transports::http::reqwest::Url, -}; -use cairo_vm::{ - types::relocatable::Relocatable, - vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, - Felt252, -}; -use serde::{Deserialize, Serialize}; +use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use std::env; use types::{ cairo::{ @@ -22,10 +13,7 @@ use types::{ structs::Uint256, traits::CairoType, }, - keys::{ - storage::{CairoKey, Key}, - KeyError, - }, + keys::storage::{CairoKey, Key}, RPC, }; diff --git a/crates/dry_hint_processor/src/syscall_handler/mod.rs b/crates/dry_hint_processor/src/syscall_handler/mod.rs index 17a986c9..3e06610b 100644 --- a/crates/dry_hint_processor/src/syscall_handler/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/mod.rs @@ -6,7 +6,7 @@ use cairo_vm::{ }; use evm::SyscallHandlerWrapper; use hints::vars; -use std::collections::HashMap; +use std::{any::Any, collections::HashMap}; pub mod evm; pub mod starknet; @@ -57,3 +57,17 @@ pub fn syscall_handler_set_syscall_ptr( Ok(()) } + +pub const ENTER_SCOPE_SYSCALL_HANDLER: &str = "vm_enter_scope({'syscall_handler': syscall_handler})"; + +pub fn enter_scope_syscall_handler( + _vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let syscall_handler: Box = Box::new(exec_scopes.get::(vars::scopes::SYSCALL_HANDLER)?); + exec_scopes.enter_scope(HashMap::from_iter([(vars::scopes::SYSCALL_HANDLER.to_string(), syscall_handler)])); + + Ok(()) +} diff --git a/crates/dry_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs b/crates/dry_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs deleted file mode 100644 index 8b137891..00000000 --- a/crates/dry_hint_processor/src/syscall_handler/starknet/dryrun/mod.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/crates/dry_hint_processor/src/syscall_handler/starknet/mod.rs b/crates/dry_hint_processor/src/syscall_handler/starknet/mod.rs index de5683ca..8b137891 100644 --- a/crates/dry_hint_processor/src/syscall_handler/starknet/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/starknet/mod.rs @@ -1,2 +1 @@ -pub mod dryrun; -pub mod soundrun; + diff --git a/crates/dry_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs b/crates/dry_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs deleted file mode 100644 index 8b137891..00000000 --- a/crates/dry_hint_processor/src/syscall_handler/starknet/soundrun/mod.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/crates/types/src/cairo/evm/account.rs b/crates/types/src/cairo/evm/account.rs index fd4ad16d..a03708b8 100644 --- a/crates/types/src/cairo/evm/account.rs +++ b/crates/types/src/cairo/evm/account.rs @@ -1,7 +1,6 @@ use crate::cairo::structs::Uint256; -use alloy::{consensus::Account, primitives::keccak256, rpc::types::EIP1186AccountProofResponse}; +use alloy::{consensus::Account, primitives::keccak256}; use alloy_rlp::{Decodable, Encodable}; -use cairo_vm::Felt252; use strum_macros::FromRepr; #[derive(FromRepr, Debug)] diff --git a/crates/types/src/cairo/evm/header.rs b/crates/types/src/cairo/evm/header.rs index 1090fbe8..43b533cc 100644 --- a/crates/types/src/cairo/evm/header.rs +++ b/crates/types/src/cairo/evm/header.rs @@ -4,7 +4,6 @@ use alloy::{ primitives::{keccak256, Bloom, Bytes}, }; use alloy_rlp::{Decodable, Encodable}; -use cairo_vm::Felt252; use strum_macros::FromRepr; #[derive(FromRepr, Debug)] diff --git a/crates/types/src/cairo/evm/mod.rs b/crates/types/src/cairo/evm/mod.rs index b99a2690..937326d2 100644 --- a/crates/types/src/cairo/evm/mod.rs +++ b/crates/types/src/cairo/evm/mod.rs @@ -1,4 +1,3 @@ -#![allow(unused)] pub mod account; pub mod header; pub mod receipt; diff --git a/crates/types/src/cairo/evm/storage.rs b/crates/types/src/cairo/evm/storage.rs index 5a18d4ab..182501ff 100644 --- a/crates/types/src/cairo/evm/storage.rs +++ b/crates/types/src/cairo/evm/storage.rs @@ -1,7 +1,6 @@ use crate::cairo::structs::Uint256; use alloy::primitives::{keccak256, StorageValue}; use alloy_rlp::{Decodable, Encodable}; -use cairo_vm::Felt252; use strum_macros::FromRepr; #[derive(FromRepr, Debug)] diff --git a/crates/types/src/cairo/new_syscalls.rs b/crates/types/src/cairo/new_syscalls.rs index b0cdb92b..b0d99128 100644 --- a/crates/types/src/cairo/new_syscalls.rs +++ b/crates/types/src/cairo/new_syscalls.rs @@ -6,7 +6,6 @@ use cairo_vm::{ Felt252, }; -#[allow(unused)] #[derive(FieldOffsetGetters, Debug)] pub struct CallContractRequest { // The address of the L2 contract to call. @@ -43,7 +42,6 @@ impl CairoType for CallContractRequest { } } -#[allow(unused)] #[derive(FieldOffsetGetters, Debug)] pub struct CallContractResponse { pub retdata_start: Relocatable, diff --git a/crates/types/src/cairo/structs.rs b/crates/types/src/cairo/structs.rs index 0ab5e454..a3351708 100644 --- a/crates/types/src/cairo/structs.rs +++ b/crates/types/src/cairo/structs.rs @@ -7,7 +7,6 @@ use cairo_vm::{ Felt252, }; -#[allow(unused)] #[derive(FieldOffsetGetters, CairoType, Default, Debug)] pub struct Uint256 { pub high: Felt252, diff --git a/crates/types/src/cairo/traits.rs b/crates/types/src/cairo/traits.rs index 031976d0..289c0676 100644 --- a/crates/types/src/cairo/traits.rs +++ b/crates/types/src/cairo/traits.rs @@ -3,97 +3,7 @@ use cairo_vm::vm::errors::memory_errors::MemoryError; use cairo_vm::vm::vm_core::VirtualMachine; pub trait CairoType: Sized { - #[allow(unused)] fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result; fn to_memory(&self, vm: &mut VirtualMachine, address: Relocatable) -> Result<(), MemoryError>; - - #[allow(unused)] fn n_fields() -> usize; } - -#[cfg(test)] -mod tests { - use std::borrow::Cow; - - use cairo_type_derive::{CairoType, FieldOffsetGetters}; - use cairo_vm::Felt252; - - use super::*; - - #[derive(CairoType, FieldOffsetGetters)] - struct MyType { - pub a: Felt252, - pub b: Felt252, - pub c: Felt252, - } - - #[derive(FieldOffsetGetters)] - struct MyNestedType { - #[allow(unused)] - pub x: Felt252, - #[allow(unused)] - pub y: MyType, - #[allow(unused)] - pub z: Felt252, - } - - #[test] - fn write_cairo_type() { - let mut vm = VirtualMachine::new(false); - let base_address = vm.add_memory_segment(); - - let m = MyType { - a: Felt252::ONE, - b: Felt252::TWO, - c: Felt252::THREE, - }; - m.to_memory(&mut vm, base_address).unwrap(); - - let values = vm.get_integer_range(base_address, 3).unwrap(); - assert_eq!(values[0], Cow::Borrowed(&m.a)); - assert_eq!(values[1], Cow::Borrowed(&m.b)); - assert_eq!(values[2], Cow::Borrowed(&m.c)); - } - - #[test] - fn read_cairo_type() { - let mut vm = VirtualMachine::new(false); - - // Check that reading from a non-existing segment fails - assert!(MyType::from_memory(&vm, Relocatable::from((0, 0))).is_err()); - - // Check that reading an existing segment without data fails - let base_address = vm.add_memory_segment(); - assert!(MyType::from_memory(&vm, base_address).is_err()); - - // Write the data and read it - vm.insert_value(base_address, Felt252::ONE).unwrap(); - vm.insert_value((base_address + 1usize).unwrap(), Felt252::TWO).unwrap(); - vm.insert_value((base_address + 2usize).unwrap(), Felt252::THREE).unwrap(); - - let m = MyType::from_memory(&vm, base_address).unwrap(); - assert_eq!(m.a, Felt252::ONE); - assert_eq!(m.b, Felt252::TWO); - assert_eq!(m.c, Felt252::THREE); - } - - #[test] - fn n_fields() { - assert_eq!(MyType::n_fields(), 3); - } - - #[test] - fn field_offsets() { - assert_eq!(MyType::a_offset(), 0); - assert_eq!(MyType::b_offset(), 1); - assert_eq!(MyType::c_offset(), 2); - - assert_eq!(MyType::cairo_size(), 3); - - assert_eq!(MyNestedType::x_offset(), 0); - assert_eq!(MyNestedType::y_offset(), 1); - assert_eq!(MyNestedType::z_offset(), 4); - - assert_eq!(MyNestedType::cairo_size(), 5); - } -} diff --git a/crates/types/src/keys/account.rs b/crates/types/src/keys/account.rs index 612bcef0..2e350e0d 100644 --- a/crates/types/src/keys/account.rs +++ b/crates/types/src/keys/account.rs @@ -1,19 +1,12 @@ use super::{storage, KeyError}; use crate::cairo::traits::CairoType; -use alloy::{ - consensus::Account, - primitives::{Address, BlockNumber, ChainId}, - providers::{Provider, RootProvider}, - rpc::types::EIP1186AccountProofResponse, - transports::http::Http, -}; +use alloy::primitives::{Address, BlockNumber, ChainId}; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; use serde::{Deserialize, Serialize}; -use std::env; #[derive(Debug)] pub struct CairoKey { diff --git a/crates/types/src/keys/header.rs b/crates/types/src/keys/header.rs index 80bfb85a..09abe9bb 100644 --- a/crates/types/src/keys/header.rs +++ b/crates/types/src/keys/header.rs @@ -1,20 +1,12 @@ use super::{account, storage, KeyError}; use crate::cairo::traits::CairoType; -use alloy::{ - hex::FromHexError, - primitives::{BlockNumber, Bytes, ChainId}, - providers::{Provider, RootProvider}, - rpc::types::{Block, BlockTransactionsKind}, - transports::http::Http, -}; +use alloy::primitives::{BlockNumber, ChainId}; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; use serde::{Deserialize, Serialize}; -use starknet_types_core::felt::FromStrError; -use std::env; #[derive(Debug, Serialize, Deserialize)] pub struct CairoKey { diff --git a/crates/types/src/keys/mod.rs b/crates/types/src/keys/mod.rs index e0933ff1..50239120 100644 --- a/crates/types/src/keys/mod.rs +++ b/crates/types/src/keys/mod.rs @@ -1,4 +1,3 @@ -#![allow(unused)] pub mod account; pub mod header; pub mod receipt; diff --git a/crates/types/src/keys/storage.rs b/crates/types/src/keys/storage.rs index 3e038c75..33b67eb8 100644 --- a/crates/types/src/keys/storage.rs +++ b/crates/types/src/keys/storage.rs @@ -1,19 +1,12 @@ +use super::KeyError; use crate::cairo::traits::CairoType; -use alloy::{ - primitives::{Address, BlockNumber, ChainId, StorageKey, StorageValue}, - providers::{Provider, RootProvider}, - rpc::types::EIP1186AccountProofResponse, - transports::http::Http, -}; +use alloy::primitives::{Address, BlockNumber, ChainId, StorageKey}; use cairo_vm::{ types::relocatable::Relocatable, vm::{errors::memory_errors::MemoryError, vm_core::VirtualMachine}, Felt252, }; use serde::{Deserialize, Serialize}; -use std::env; - -use super::KeyError; #[derive(Debug)] pub struct CairoKey { From bb8685da375f0c198ce0aa5d8a6627c3a0894822 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 18 Dec 2024 09:21:31 +0100 Subject: [PATCH 45/75] syscall_handler crate extraction --- Cargo.lock | 701 +++++++++--------- Cargo.toml | 24 +- crates/dry_hint_processor/Cargo.toml | 3 +- .../src/syscall_handler/evm/account.rs | 6 +- .../src/syscall_handler/evm/header.rs | 6 +- .../src/syscall_handler/evm/mod.rs | 5 +- .../src/syscall_handler/evm/storage.rs | 6 +- .../src/syscall_handler/mod.rs | 2 - crates/syscall_handler/Cargo.toml | 10 + .../utils.rs => syscall_handler/src/lib.rs} | 7 +- .../src}/traits.rs | 3 +- 11 files changed, 372 insertions(+), 401 deletions(-) create mode 100644 crates/syscall_handler/Cargo.toml rename crates/{dry_hint_processor/src/syscall_handler/utils.rs => syscall_handler/src/lib.rs} (97%) rename crates/{dry_hint_processor/src/syscall_handler => syscall_handler/src}/traits.rs (94%) diff --git a/Cargo.lock b/Cargo.lock index b18331ba..c79f9fc4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -41,15 +41,15 @@ dependencies = [ [[package]] name = "allocator-api2" -version = "0.2.20" +version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45862d1c77f2228b9e10bc609d5bc203d86ebc9b87ad8d5d5167a6c9abf739d9" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" [[package]] name = "alloy" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44ab65cb6104c389b46df77b7990cab08780f57e41b412b46d6d12baf7e8c716" +checksum = "02b0561294ccedc6181e5528b850b4579e3fbde696507baa00109bfd9054c5bb" dependencies = [ "alloy-consensus", "alloy-contract", @@ -72,9 +72,9 @@ dependencies = [ [[package]] name = "alloy-chains" -version = "0.1.47" +version = "0.1.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18c5c520273946ecf715c0010b4e3503d7eba9893cd9ce6b7fff5654c4a3c470" +checksum = "a0161082e0edd9013d23083465cc04b20e44b7a15646d36ba7b0cdb7cd6fe18f" dependencies = [ "alloy-primitives", "num_enum", @@ -83,9 +83,9 @@ dependencies = [ [[package]] name = "alloy-consensus" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73dd0ab7003dfa3efd252e423873cd3bc241d1456147e752f995cc8aabd1d1f6" +checksum = "a101d4d016f47f13890a74290fdd17b05dd175191d9337bc600791fb96e4dea8" dependencies = [ "alloy-eips", "alloy-primitives", @@ -101,9 +101,9 @@ dependencies = [ [[package]] name = "alloy-consensus-any" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d08234c0eece0e08602db5095a16dc942cad91967cccfcfc2c6a42c25563964f" +checksum = "fa60357dda9a3d0f738f18844bd6d0f4a5924cc5cf00bfad2ff1369897966123" dependencies = [ "alloy-consensus", "alloy-eips", @@ -115,9 +115,9 @@ dependencies = [ [[package]] name = "alloy-contract" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a01f5593f6878452c6dde102ece391b60cba79801c5f606f8fe898ff57cd5d7" +checksum = "2869e4fb31331d3b8c58c7db567d1e4e4e94ef64640beda3b6dd9b7045690941" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -131,14 +131,14 @@ dependencies = [ "alloy-transport", "futures", "futures-util", - "thiserror 2.0.3", + "thiserror 2.0.8", ] [[package]] name = "alloy-core" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d14d531c99995de71558e8e2206c27d709559ee8e5a0452b965ea82405a013" +checksum = "c618bd382f0bc2ac26a7e4bfae01c9b015ca8f21b37ca40059ae35a7e62b3dc6" dependencies = [ "alloy-dyn-abi", "alloy-json-abi", @@ -149,9 +149,9 @@ dependencies = [ [[package]] name = "alloy-dyn-abi" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80759b3f57b3b20fa7cd8fef6479930fc95461b58ff8adea6e87e618449c8a1d" +checksum = "41056bde53ae10ffbbf11618efbe1e0290859e5eab0fe9ef82ebdb62f12a866f" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -190,9 +190,9 @@ dependencies = [ [[package]] name = "alloy-eips" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50c242de43a1869bcb2fbce3b377130959d10dfd562b87ac7aa2f04d98baac51" +checksum = "8b6755b093afef5925f25079dd5a7c8d096398b804ba60cb5275397b06b31689" dependencies = [ "alloy-eip2930", "alloy-eip7702", @@ -208,20 +208,21 @@ dependencies = [ [[package]] name = "alloy-genesis" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd39b72f860cb0c542fac925f91d1939c2b14a0970b39d0ae304b5b7574a0ac" +checksum = "aeec8e6eab6e52b7c9f918748c9b811e87dbef7312a2e3a2ca1729a92966a6af" dependencies = [ "alloy-primitives", "alloy-serde", + "alloy-trie", "serde", ] [[package]] name = "alloy-json-abi" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac4b22b3e51cac09fd2adfcc73b55f447b4df669f983c13f7894ec82b607c63f" +checksum = "c357da577dfb56998d01f574d81ad7a1958d248740a7981b205d69d65a7da404" dependencies = [ "alloy-primitives", "alloy-sol-type-parser", @@ -231,23 +232,23 @@ dependencies = [ [[package]] name = "alloy-json-rpc" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c15c11661571a19a06896663c93e804ccf013159275a89a98e892014df514d8" +checksum = "4fa077efe0b834bcd89ff4ba547f48fb081e4fdc3673dd7da1b295a2cf2bb7b7" dependencies = [ "alloy-primitives", "alloy-sol-types", "serde", "serde_json", - "thiserror 2.0.3", + "thiserror 2.0.8", "tracing", ] [[package]] name = "alloy-network" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60dd0b99eaa5e715dd90d42021f7f08a0a70976ea84f41a0ad233770e0c1962b" +checksum = "209a1882a08e21aca4aac6e2a674dc6fcf614058ef8cb02947d63782b1899552" dependencies = [ "alloy-consensus", "alloy-consensus-any", @@ -265,14 +266,14 @@ dependencies = [ "futures-utils-wasm", "serde", "serde_json", - "thiserror 2.0.3", + "thiserror 2.0.8", ] [[package]] name = "alloy-network-primitives" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18abfc73ce48f074c8bc6e05c1f08ef0b1ddc9b04f191a821d0beb9470a42a29" +checksum = "c20219d1ad261da7a6331c16367214ee7ded41d001fabbbd656fbf71898b2773" dependencies = [ "alloy-consensus", "alloy-eips", @@ -283,9 +284,9 @@ dependencies = [ [[package]] name = "alloy-primitives" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9db948902dfbae96a73c2fbf1f7abec62af034ab883e4c777c3fd29702bd6e2c" +checksum = "6259a506ab13e1d658796c31e6e39d2e2ee89243bcc505ddc613b35732e0a430" dependencies = [ "alloy-rlp", "bytes", @@ -295,7 +296,7 @@ dependencies = [ "foldhash", "hashbrown 0.15.2", "hex-literal", - "indexmap 2.6.0", + "indexmap 2.7.0", "itoa", "k256", "keccak-asm", @@ -311,9 +312,9 @@ dependencies = [ [[package]] name = "alloy-provider" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4933c761f10e44d5e901804b56efb2ce6e0945e6c57d2fa1e5ace303fae6f74a" +checksum = "9eefa6f4c798ad01f9b4202d02cea75f5ec11fa180502f4701e2b47965a8c0bb" dependencies = [ "alloy-chains", "alloy-consensus", @@ -342,7 +343,7 @@ dependencies = [ "schnellru", "serde", "serde_json", - "thiserror 2.0.3", + "thiserror 2.0.8", "tokio", "tracing", "url", @@ -351,9 +352,9 @@ dependencies = [ [[package]] name = "alloy-pubsub" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "808719714bfb2aa24b0eb2a38411ce8e654ba11c0ebf2a6648fcbe9fabfe696d" +checksum = "aac9a7210e0812b1d814118f426f57eb7fc260a419224dd1c76d169879c06907" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -370,9 +371,9 @@ dependencies = [ [[package]] name = "alloy-rlp" -version = "0.3.9" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0822426598f95e45dd1ea32a738dac057529a709ee645fcc516ffa4cbde08f" +checksum = "f542548a609dca89fcd72b3b9f355928cf844d4363c5eed9c5273a3dd225e097" dependencies = [ "alloy-rlp-derive", "arrayvec", @@ -381,20 +382,20 @@ dependencies = [ [[package]] name = "alloy-rlp-derive" -version = "0.3.9" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b09cae092c27b6f1bde952653a22708691802e57bfef4a2973b80bea21efd3f" +checksum = "5a833d97bf8a5f0f878daf2c8451fff7de7f9de38baa5a45d936ec718d81255a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] name = "alloy-rpc-client" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce26c25efb8290b6ba559ae6c40bf6630d337e107ae242e5790501420dba7b7" +checksum = "ed30bf1041e84cabc5900f52978ca345dd9969f2194a945e6fdec25b0620705c" dependencies = [ "alloy-json-rpc", "alloy-primitives", @@ -418,9 +419,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41080ce2640928f0df45c41d2af629b88db3cb31af3abbe614964ae10001ddac" +checksum = "5ab686b0fa475d2a4f5916c5f07797734a691ec58e44f0f55d4746ea39cbcefb" dependencies = [ "alloy-primitives", "alloy-rpc-types-engine", @@ -431,9 +432,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-any" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abca110e59f760259e26d0c84912121468008aba48dd227af0f306cfd7bce9ae" +checksum = "200661999b6e235d9840be5d60a6e8ae2f0af9eb2a256dd378786744660e36ec" dependencies = [ "alloy-consensus-any", "alloy-rpc-types-eth", @@ -442,9 +443,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-engine" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3b000c7f3469e7faa575ba70207294cf07e91dfd6ce4d04d5d5d8069f974a66" +checksum = "5d297268357e3eae834ddd6888b15f764cbc0f4b3be9265f5f6ec239013f3d68" dependencies = [ "alloy-consensus", "alloy-eips", @@ -458,9 +459,9 @@ dependencies = [ [[package]] name = "alloy-rpc-types-eth" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3468e7385fbb86b0fde5497d685c02f765ea09d36f7e07c5d1c9a52b077d38e2" +checksum = "a0600b8b5e2dc0cab12cbf91b5a885c35871789fb7b3a57b434bd4fced5b7a8b" dependencies = [ "alloy-consensus", "alloy-consensus-any", @@ -478,9 +479,9 @@ dependencies = [ [[package]] name = "alloy-serde" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42de6002e2154b50b3568aea27e26bd9caf7b754658f43065f2e9b6ee0a8c839" +checksum = "9afa753a97002a33b2ccb707d9f15f31c81b8c1b786c95b73cc62bb1d1fd0c3f" dependencies = [ "alloy-primitives", "serde", @@ -489,23 +490,23 @@ dependencies = [ [[package]] name = "alloy-signer" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f288a9a25e2578dab17845fd8d2be1d32de33565783ed185ded161a65f92381b" +checksum = "9b2cbff01a673936c2efd7e00d4c0e9a4dbbd6d600e2ce298078d33efbb19cd7" dependencies = [ "alloy-primitives", "async-trait", "auto_impl", "elliptic-curve", "k256", - "thiserror 2.0.3", + "thiserror 2.0.8", ] [[package]] name = "alloy-signer-local" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8081f589ddc11a959605e30c723d51cad2562d9072305f8e3ef311f077e5eb" +checksum = "bd6d988cb6cd7d2f428a74476515b1a6e901e08c796767f9f93311ab74005c8b" dependencies = [ "alloy-consensus", "alloy-network", @@ -514,47 +515,47 @@ dependencies = [ "async-trait", "k256", "rand", - "thiserror 2.0.3", + "thiserror 2.0.8", ] [[package]] name = "alloy-sol-macro" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bfd7853b65a2b4f49629ec975fee274faf6dff15ab8894c620943398ef283c0" +checksum = "d9d64f851d95619233f74b310f12bcf16e0cbc27ee3762b6115c14a84809280a" dependencies = [ "alloy-sol-macro-expander", "alloy-sol-macro-input", "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] name = "alloy-sol-macro-expander" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82ec42f342d9a9261699f8078e57a7a4fda8aaa73c1a212ed3987080e6a9cd13" +checksum = "6bf7ed1574b699f48bf17caab4e6e54c6d12bc3c006ab33d58b1e227c1c3559f" dependencies = [ "alloy-json-abi", "alloy-sol-macro-input", "const-hex", "heck 0.5.0", - "indexmap 2.6.0", + "indexmap 2.7.0", "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "syn-solidity", "tiny-keccak", ] [[package]] name = "alloy-sol-macro-input" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2c50e6a62ee2b4f7ab3c6d0366e5770a21cad426e109c2f40335a1b3aff3df" +checksum = "8c02997ccef5f34f9c099277d4145f183b422938ed5322dc57a089fe9b9ad9ee" dependencies = [ "alloy-json-abi", "const-hex", @@ -563,15 +564,15 @@ dependencies = [ "proc-macro2", "quote", "serde_json", - "syn 2.0.89", + "syn 2.0.90", "syn-solidity", ] [[package]] name = "alloy-sol-type-parser" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac17c6e89a50fb4a758012e4b409d9a0ba575228e69b539fe37d7a1bd507ca4a" +checksum = "ce13ff37285b0870d0a0746992a4ae48efaf34b766ae4c2640fa15e5305f8e73" dependencies = [ "serde", "winnow", @@ -579,9 +580,9 @@ dependencies = [ [[package]] name = "alloy-sol-types" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9dc0fffe397aa17628160e16b89f704098bf3c9d74d5d369ebc239575936de5" +checksum = "1174cafd6c6d810711b4e00383037bdb458efc4fe3dbafafa16567e0320c54d8" dependencies = [ "alloy-json-abi", "alloy-primitives", @@ -592,9 +593,9 @@ dependencies = [ [[package]] name = "alloy-transport" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90352f4cf78017905c3244f48b38fadc345970bbc9095087c0f985a580550488" +checksum = "d69d36982b9e46075ae6b792b0f84208c6c2c15ad49f6c500304616ef67b70e0" dependencies = [ "alloy-json-rpc", "base64 0.22.1", @@ -602,7 +603,7 @@ dependencies = [ "futures-utils-wasm", "serde", "serde_json", - "thiserror 2.0.3", + "thiserror 2.0.8", "tokio", "tower", "tracing", @@ -612,9 +613,9 @@ dependencies = [ [[package]] name = "alloy-transport-http" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d26c94d51fa8b1aee3d15db113dd0773776c02bb36dbaa2590b900dadd7e7d0" +checksum = "2e02ffd5d93ffc51d72786e607c97de3b60736ca3e636ead0ec1f7dce68ea3fd" dependencies = [ "alloy-json-rpc", "alloy-transport", @@ -627,9 +628,9 @@ dependencies = [ [[package]] name = "alloy-transport-ipc" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c498fcdec50650be6b6a22ce7928a1b2738086b4f94f31b132e83498d45bbb" +checksum = "1b6f8b87cb84bae6d81ae6604b37741c8116f84f9784a0ecc6038c302e679d23" dependencies = [ "alloy-json-rpc", "alloy-pubsub", @@ -646,9 +647,9 @@ dependencies = [ [[package]] name = "alloy-transport-ws" -version = "0.7.2" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd7b21335b55c9f715e2acca0228dc1d6880d961756916c13a9ce70f9f413e70" +checksum = "9c085c4e1e7680b723ffc558f61a22c061ed3f70eb3436f93f3936779c59cec1" dependencies = [ "alloy-pubsub", "alloy-transport", @@ -664,15 +665,16 @@ dependencies = [ [[package]] name = "alloy-trie" -version = "0.7.4" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6b2e366c0debf0af77766c23694a3f863b02633050e71e096e257ffbd395e50" +checksum = "3a5fd8fea044cc9a8c8a50bb6f28e31f0385d820f116c5b98f6f4e55d6e5590b" dependencies = [ "alloy-primitives", "alloy-rlp", "arrayvec", "derive_more", "nybbles", + "serde", "smallvec", "tracing", ] @@ -743,9 +745,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.93" +version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" +checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7" [[package]] name = "ark-ff" @@ -876,6 +878,9 @@ name = "arrayvec" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +dependencies = [ + "serde", +] [[package]] name = "ascii-canvas" @@ -911,7 +916,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -922,7 +927,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -950,7 +955,7 @@ checksum = "3c87f3f15e7794432337fc718554eaa4dc8f04c9677a950ffe366f20a162ae42" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -971,7 +976,7 @@ dependencies = [ "miniz_oxide", "object", "rustc-demangle", - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -1075,9 +1080,9 @@ dependencies = [ [[package]] name = "bstr" -version = "1.11.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a68f1f47cdf0ec8ee4b941b2eee2a80cb796db73118c0dd09ac63fbe405be22" +checksum = "786a307d683a5bf92e6fd5fd69a7eb613751668d1d8d67d802846dfe367c62c8" dependencies = [ "memchr", "serde", @@ -1127,9 +1132,9 @@ dependencies = [ [[package]] name = "cairo-lang-casm" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1e0dcdb6358bb639dd729546611bd99bada94c86e3f262c3637855abea9a972" +checksum = "3929a38c1d586e35e19dbdf7798b146fba3627b308417a6d373fea8939535b6b" dependencies = [ "cairo-lang-utils", "indoc", @@ -1141,9 +1146,9 @@ dependencies = [ [[package]] name = "cairo-lang-compiler" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8657f5a5611f341a85e80ba0b21848fc34bfdf391bfd93df0baf4516c3e4159" +checksum = "0bed098f0c3666b3ad3a93aef6293f91fc1119bef660ce994105f6d1bc2802cf" dependencies = [ "anyhow", "cairo-lang-defs", @@ -1160,25 +1165,25 @@ dependencies = [ "indoc", "rayon", "rust-analyzer-salsa", - "semver 1.0.23", + "semver 1.0.24", "smol_str", "thiserror 1.0.69", ] [[package]] name = "cairo-lang-debug" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0635aa554d297acefe6a35b495aba2795d0af5b7f97c4ab63829c7d62291ef41" +checksum = "d7763505dcfe15f36899074c27185bf7e3494875f63fd06350c6e3ed8d1f91d5" dependencies = [ "cairo-lang-utils", ] [[package]] name = "cairo-lang-defs" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b356e1c09898e8b8cfdd9731579d89365a13d8b4f7e717962e0cc7d125b83c" +checksum = "b4d29dc5a3cafe94ea4397d41b00cd54a9dffbe9bc3a3092a9ea617ea737bc6e" dependencies = [ "cairo-lang-debug", "cairo-lang-diagnostics", @@ -1193,9 +1198,9 @@ dependencies = [ [[package]] name = "cairo-lang-diagnostics" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dfe7c6ff96182da29012b707a3554e34a50f19cc96013ee45b0eb36dd396ec8" +checksum = "761d20ca9c3a3eb7025b2488aa6e0e5dc23c5d551dd95e83a989b5e87687f523" dependencies = [ "cairo-lang-debug", "cairo-lang-filesystem", @@ -1205,9 +1210,9 @@ dependencies = [ [[package]] name = "cairo-lang-eq-solver" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723d244465309d5409e297b5486d62cbec06f2c47b05044414bb640e3f14caab" +checksum = "d778ec864e92c82293370a512195715b12775b05981e14065d85eb5dd3dd96b6" dependencies = [ "cairo-lang-utils", "good_lp", @@ -1215,15 +1220,15 @@ dependencies = [ [[package]] name = "cairo-lang-filesystem" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "237030772ae5368f19a9247e1f63f753f8ad8de963477166e402f4825c0a141d" +checksum = "d9dc486c554e2df3be8e84c47e30fe55b59d2349b680fbe992bfba801ef93ff5" dependencies = [ "cairo-lang-debug", "cairo-lang-utils", "path-clean", "rust-analyzer-salsa", - "semver 1.0.23", + "semver 1.0.24", "serde", "smol_str", "toml", @@ -1231,9 +1236,9 @@ dependencies = [ [[package]] name = "cairo-lang-formatter" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b71f0eb3a36a6cb5f7f07843926783c4c17e44c9516b53171727a108782f3eb" +checksum = "675d281a3c9aa365055ce6e201d5dd91534dfccfd2929a41b7397f665c80293c" dependencies = [ "anyhow", "cairo-lang-diagnostics", @@ -1251,9 +1256,9 @@ dependencies = [ [[package]] name = "cairo-lang-lowering" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d095d78e2f1de499429c95655d6135a3d24c384b36d8de9f84e0aa4e07ee152" +checksum = "d880470c94f94fac08c2150bc0ce4af930b6760956a56966e47612de376d57ec" dependencies = [ "cairo-lang-debug", "cairo-lang-defs", @@ -1276,9 +1281,9 @@ dependencies = [ [[package]] name = "cairo-lang-parser" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb828af7f948a3ef7fa65de14e3f639daedefb046dfefcad6e3116d2cb0f89a0" +checksum = "37e2b488f659432c8b866bf540e54ab3696a24ac0f366faac33b860c5313e78c" dependencies = [ "cairo-lang-diagnostics", "cairo-lang-filesystem", @@ -1296,9 +1301,9 @@ dependencies = [ [[package]] name = "cairo-lang-plugins" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135a600043bf7030eacc6ebf2a609c2364d6ffeb04e1f3c809a2738f6b02c829" +checksum = "13cf34fd39a1efb997455fa38dbdb6bef489a125a2d17d77ebfea1ee580559f3" dependencies = [ "cairo-lang-defs", "cairo-lang-diagnostics", @@ -1313,36 +1318,41 @@ dependencies = [ "smol_str", ] +[[package]] +name = "cairo-lang-primitive-token" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "123ac0ecadf31bacae77436d72b88fa9caef2b8e92c89ce63a125ae911a12fae" + [[package]] name = "cairo-lang-proc-macros" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac857ec4b564712f3e16e3314e23cc0787ab1c05cdfee83f1c8f9989a6eee40f" +checksum = "b3c4a161868276ce022c44ac500afbfa0d7d8371106feb40dfca34ea7be97503" dependencies = [ "cairo-lang-debug", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] name = "cairo-lang-project" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23cc37b7f8889cdea631aeea3bcc70d5c86ac8fb1d98aabc83f16283d60f1643" +checksum = "fde3cc9777fff4daacbfd839a6fcefa29abd660068de47f72ac6d5883fa93ccd" dependencies = [ "cairo-lang-filesystem", "cairo-lang-utils", "serde", - "smol_str", "thiserror 1.0.69", "toml", ] [[package]] name = "cairo-lang-semantic" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c560cf4b4a89325d3a9594f490fffee38cf30e0990e808bb927619de9d0c973a" +checksum = "8af1f92ba601fd61a994c44d0c80d711fbb3d64b2b5a1e72905fc6f581b1fadd" dependencies = [ "cairo-lang-debug", "cairo-lang-defs", @@ -1360,15 +1370,16 @@ dependencies = [ "num-bigint", "num-traits", "rust-analyzer-salsa", + "sha3", "smol_str", "toml", ] [[package]] name = "cairo-lang-sierra" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8118f55ca7d567bfc60960b445d388564d04bf48335c983b1595cb35f67a01c5" +checksum = "075c6457642ada82b32cf657d871a8545ae7a9d61c78dd5588a794c8c905abdc" dependencies = [ "anyhow", "cairo-lang-utils", @@ -1393,9 +1404,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra-ap-change" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2716ef8d4ce0fb700f83ed3281f3656436570e60249d41c65c79dc1ca27be002" +checksum = "b69172fe8354b1dd564bba318ccb5233aa78f70d57145b8c92a0b1cf009fa0fc" dependencies = [ "cairo-lang-eq-solver", "cairo-lang-sierra", @@ -1409,9 +1420,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra-gas" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24a44da87a35845470c4f4c648225232a15e0875fe809045b6088464491f838b" +checksum = "42b571b73d9b02103f780aeee05dbf9a71d68d8a16341a04aa1dd581d0db3ad6" dependencies = [ "cairo-lang-eq-solver", "cairo-lang-sierra", @@ -1425,9 +1436,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra-generator" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15bc5cf9f3965a7030a114dfe3d31d183287fbfbfbf904deaaa2468cadb936aa" +checksum = "1d3857cd98a0cb35b32cc962e70c04e6ddfcd8bf61106ac37b6cf453ec76b878" dependencies = [ "cairo-lang-debug", "cairo-lang-defs", @@ -1449,9 +1460,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra-to-casm" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18b7616f1a3c41c4646094b5abf774e558428e9c1eda5d78d7b0638ec5c264e5" +checksum = "add264b156dfb01f18292282a6037070c078acca3bccde05787da1e1c997b78c" dependencies = [ "assert_matches", "cairo-lang-casm", @@ -1470,9 +1481,9 @@ dependencies = [ [[package]] name = "cairo-lang-sierra-type-size" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "871077dbc08df5d134dc3975538171c14b266ba405d1298085afdb227216f0a3" +checksum = "7bda5388ef862bc26388e999ac7ad62dd8ab3064720c3483b81fd761b051e627" dependencies = [ "cairo-lang-sierra", "cairo-lang-utils", @@ -1480,9 +1491,9 @@ dependencies = [ [[package]] name = "cairo-lang-starknet" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f21804eb8931d41e258e7a393afc8ee8858308e95b3ed2e9b6b469ef68a6a50" +checksum = "32d5ed4aa48fe739f643a8c503c14aec0858c31dc73ba4e6a335b77ca7438807" dependencies = [ "anyhow", "cairo-lang-compiler", @@ -1510,9 +1521,9 @@ dependencies = [ [[package]] name = "cairo-lang-starknet-classes" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2496bccd68fa0286b35b72c98439316a3a872ef7ec6d881f0dac90b17997490" +checksum = "fe691200b431e51e3d6cfa84f256a3dd2e8405f44d182843fbe124f803d085ff" dependencies = [ "cairo-lang-casm", "cairo-lang-sierra", @@ -1533,12 +1544,13 @@ dependencies = [ [[package]] name = "cairo-lang-syntax" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d77ea2e35d3610098ff13e373fc519aedc6a5096ed8547081aacfc104ef4422" +checksum = "0a38f1431f22a9487b9b0dd7aef098c9605fe6b8677e0f620547aa69195f7fb5" dependencies = [ "cairo-lang-debug", "cairo-lang-filesystem", + "cairo-lang-primitive-token", "cairo-lang-utils", "num-bigint", "num-traits", @@ -1549,9 +1561,9 @@ dependencies = [ [[package]] name = "cairo-lang-syntax-codegen" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b01d505ab26ca9ce829faf3a8dd097f5d7962d2eb8f136017a260694a6a72e8" +checksum = "fd7990586c9bb37eaa875ffeb218bdecf96f87881d03263ebf84fcd46514ca9f" dependencies = [ "genco", "xshell", @@ -1559,9 +1571,9 @@ dependencies = [ [[package]] name = "cairo-lang-test-utils" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb143a22f5a3510df8c4dec76e17c1e36bbcbddcd7915601f6a51a72418c454f" +checksum = "f2b76c55a742da177540d2a0eb39fa50d011998d0ccfdeae8b48ea0e2d7f077f" dependencies = [ "cairo-lang-formatter", "cairo-lang-utils", @@ -1572,12 +1584,12 @@ dependencies = [ [[package]] name = "cairo-lang-utils" -version = "2.9.0-dev.0" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35df943ebcf8e1db11ee9f4f46f843dde5b71639ca79ea0d8caa7973f91d8b12" +checksum = "ff5d7609abc99c15de7d7f90b8441b27e2bd52e930a3014c95a9b620e5d3211a" dependencies = [ "hashbrown 0.14.5", - "indexmap 2.6.0", + "indexmap 2.7.0", "itertools 0.12.1", "num-bigint", "num-traits", @@ -1588,11 +1600,11 @@ dependencies = [ [[package]] name = "cairo-type-derive" version = "0.1.0" -source = "git+https://github.com/keep-starknet-strange/snos.git#cb2a6d26faeb658492756fe100bbdf5b1600c768" +source = "git+https://github.com/keep-starknet-strange/snos.git#35a300a10d2107482ada440b5025ee2f651afbd4" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1634,9 +1646,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.2" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f34d93e62b03caf570cccc334cbc6c2fceca82f39211051345108adcba3eebdc" +checksum = "9157bbaa6b165880c27a4293a474c91cdcf265cc68cc829bf10be0964a391caf" dependencies = [ "shlex", ] @@ -1649,22 +1661,22 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.38" +version = "0.4.39" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +checksum = "7e36cc9d416881d2e24f9a963be5fb1cd90966419ac844274161d10488b3e825" dependencies = [ "android-tzdata", "iana-time-zone", "num-traits", "serde", - "windows-targets 0.52.6", + "windows-targets", ] [[package]] name = "clap" -version = "4.5.21" +version = "4.5.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb3b4b9e5a7c7514dfa52869339ee98b3156b0bfb4e8a77c4ff4babb64b1604f" +checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84" dependencies = [ "clap_builder", "clap_derive", @@ -1672,9 +1684,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.21" +version = "4.5.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b17a95aa67cc7b5ebd32aa5370189aa0d79069ef1c64ce893bd30fb24bff20ec" +checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838" dependencies = [ "anstream", "anstyle", @@ -1691,14 +1703,14 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] name = "clap_lex" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afb84c814227b90d6895e01398aee0d8033c00e7466aca416fb6a8e0eb19d8a7" +checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" [[package]] name = "colorchoice" @@ -1708,12 +1720,12 @@ checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" [[package]] name = "colored" -version = "2.1.0" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbf2150cce219b664a8a70df7a1f933836724b503f8a413af9365b4dcc4d90b8" +checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c" dependencies = [ "lazy_static", - "windows-sys 0.48.0", + "windows-sys 0.59.0", ] [[package]] @@ -1743,18 +1755,18 @@ checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" [[package]] name = "const_format" -version = "0.2.33" +version = "0.2.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50c655d81ff1114fb0dcdea9225ea9f0cc712a6f8d189378e82bdf62a473a64b" +checksum = "126f97965c8ad46d6d9163268ff28432e8f6a1196a55578867832e3049df63dd" dependencies = [ "const_format_proc_macros", ] [[package]] name = "const_format_proc_macros" -version = "0.2.33" +version = "0.2.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eff1a44b93f47b1bac19a27932f5c591e43d1ba357ee4f61526c8a25603f0eb1" +checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" dependencies = [ "proc-macro2", "quote", @@ -1806,9 +1818,9 @@ dependencies = [ [[package]] name = "crossbeam-deque" -version = "0.8.5" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -1825,9 +1837,9 @@ dependencies = [ [[package]] name = "crossbeam-utils" -version = "0.8.20" +version = "0.8.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" [[package]] name = "crunchy" @@ -1878,7 +1890,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1889,7 +1901,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -1960,7 +1972,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "unicode-xid", ] @@ -2029,7 +2041,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -2063,6 +2075,7 @@ dependencies = [ "starknet-crypto 0.7.3", "starknet-types-core", "strum_macros", + "syscall_handler", "thiserror 1.0.69", "tokio", "types", @@ -2167,9 +2180,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.2.0" +version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "486f806e73c5707928240ddc295403b1b93c96a02038563881c4a2fd84b81ac4" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "fastrlp" @@ -2182,6 +2195,17 @@ dependencies = [ "bytes", ] +[[package]] +name = "fastrlp" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce8dba4714ef14b8274c371879b175aa55b16b30f269663f19d576f380018dc4" +dependencies = [ + "arrayvec", + "auto_impl", + "bytes", +] + [[package]] name = "fetcher" version = "0.1.0" @@ -2334,7 +2358,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -2392,7 +2416,7 @@ checksum = "43eaff6bbc0b3a878361aced5ec6a2818ee7c541c5b33b5880dfa9a86c23e9e7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -2477,7 +2501,7 @@ dependencies = [ "futures-core", "futures-sink", "http", - "indexmap 2.6.0", + "indexmap 2.7.0", "slab", "tokio", "tokio-util", @@ -2591,9 +2615,9 @@ dependencies = [ [[package]] name = "http" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +checksum = "f16ca2af56261c99fba8bac40a10251ce8188205a4c448fbb745a2e4daa76fea" dependencies = [ "bytes", "fnv", @@ -2631,9 +2655,9 @@ checksum = "7d71d3574edd2771538b901e6549113b4006ece66150fb69c0fb6d9a2adae946" [[package]] name = "hyper" -version = "1.5.1" +version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97818827ef4f364230e16705d4706e2897df2bb60617d6ca15d598025a3c481f" +checksum = "256fb8d4bd6413123cc9d91832d78325c48ff41677595be797d90f42969beae0" dependencies = [ "bytes", "futures-channel", @@ -2839,7 +2863,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -2908,7 +2932,7 @@ checksum = "a0eb5a3343abf848c0984fe4604b2b105da9539376e24fc0a3b0007411ae4fd9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -2943,9 +2967,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.6.0" +version = "2.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" +checksum = "62f822373a4fe84d4bb149bf54e584a7f4abec90e072ed49cda0edea5b95471f" dependencies = [ "equivalent", "hashbrown 0.15.2", @@ -3132,9 +3156,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.166" +version = "0.2.168" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2ccc108bbc0b1331bd061864e7cd823c0cab660bbe6970e66e2c0614decde36" +checksum = "5aaeb2981e0606ca11d79718f8bb01164f1d6ed75080182d3abf017e6d244b6d" [[package]] name = "libm" @@ -3229,9 +3253,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "miniz_oxide" -version = "0.8.0" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" +checksum = "4ffbe83022cedc1d264172192511ae958937694cd57ce297164951b8b3568394" dependencies = [ "adler2", ] @@ -3405,7 +3429,7 @@ checksum = "af1844ef2428cc3e1cb900be36181049ef3d3193c63e43026cfe202983b27a56" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3414,7 +3438,10 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95f06be0417d97f81fe4e5c86d7d01b392655a9cac9c19a848aa033e18937b23" dependencies = [ + "alloy-rlp", "const-hex", + "proptest", + "serde", "smallvec", ] @@ -3462,7 +3489,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3491,29 +3518,28 @@ checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" [[package]] name = "parity-scale-codec" -version = "3.7.0" +version = "3.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be4817d39f3272f69c59fe05d0535ae6456c2dc2fa1ba02910296c7e0a5c590" +checksum = "306800abfa29c7f16596b5970a588435e3d5b3149683d00c12b699cc19f895ee" dependencies = [ "arrayvec", "bitvec", "byte-slice-cast", "impl-trait-for-tuples", "parity-scale-codec-derive", - "rustversion", "serde", ] [[package]] name = "parity-scale-codec-derive" -version = "3.7.0" +version = "3.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8781a75c6205af67215f382092b6e0a4ff3734798523e69073d4bcd294ec767b" +checksum = "d830939c76d294956402033aee57a6da7b438f2294eb94864c37b0569053a42c" dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.89", + "syn 1.0.109", ] [[package]] @@ -3536,7 +3562,7 @@ dependencies = [ "libc", "redox_syscall", "smallvec", - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -3559,12 +3585,12 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.14" +version = "2.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879952a81a83930934cbf1786752d6dedc3b1f29e8f8fb2ad1d0a36f377cf442" +checksum = "8b7cafe60d6cf8e62e1b9b2ea516a089c008945bb5a275416789e7db0bc199dc" dependencies = [ "memchr", - "thiserror 1.0.69", + "thiserror 2.0.8", "ucd-trie", ] @@ -3575,7 +3601,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" dependencies = [ "fixedbitset", - "indexmap 2.6.0", + "indexmap 2.7.0", ] [[package]] @@ -3620,7 +3646,7 @@ checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3736,7 +3762,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -3863,9 +3889,9 @@ checksum = "d3edd4d5d42c92f0a659926464d4cce56b562761267ecf0f469d85b7de384175" [[package]] name = "redox_syscall" -version = "0.5.7" +version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" +checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834" dependencies = [ "bitflags", ] @@ -3947,7 +3973,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sync_wrapper 1.0.2", + "sync_wrapper", "system-configuration", "tokio", "tokio-native-tls", @@ -3996,16 +4022,18 @@ dependencies = [ [[package]] name = "ruint" -version = "1.12.3" +version = "1.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c3cc4c2511671f327125da14133d0c5c5d137f006a1017a16f557bc85b16286" +checksum = "f5ef8fb1dd8de3870cb8400d51b4c2023854bbafd5431a3ac7e7317243e22d2f" dependencies = [ "alloy-rlp", "ark-ff 0.3.0", "ark-ff 0.4.2", "bytes", - "fastrlp", + "fastrlp 0.3.1", + "fastrlp 0.4.0", "num-bigint", + "num-integer", "num-traits", "parity-scale-codec", "primitive-types", @@ -4030,7 +4058,7 @@ version = "0.17.0-pre.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "719825638c59fd26a55412a24561c7c5bcf54364c88b9a7a04ba08a6eafaba8d" dependencies = [ - "indexmap 2.6.0", + "indexmap 2.7.0", "lock_api", "oorandom", "parking_lot", @@ -4050,7 +4078,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4102,27 +4130,27 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" dependencies = [ - "semver 1.0.23", + "semver 1.0.24", ] [[package]] name = "rustix" -version = "0.38.41" +version = "0.38.42" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7f649912bc1495e167a6edee79151c84b1bad49748cb4f1f1167f459f6224f6" +checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] name = "rustls" -version = "0.23.19" +version = "0.23.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "934b404430bb06b3fae2cba809eb45a1ab1aecd64491213d7c3301b88393f8d1" +checksum = "5065c3f250cbd332cd894be57c40fa52387247659b14a2d6041d121547903b1b" dependencies = [ "once_cell", "ring", @@ -4143,9 +4171,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.10.0" +version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16f1201b3c9a7ee8039bcadc17b7e605e2945b27eee7631788c1bd2b0643674b" +checksum = "d2bf47e6ff922db3825eb750c4e2ff784c6ff8fb9e13046ef6a1d1c5401b0b37" [[package]] name = "rustls-webpki" @@ -4222,7 +4250,7 @@ dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4271,9 +4299,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.12.1" +version = "2.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa39c7303dc58b5543c94d22c1766b0d31f2ee58306363ea622b10bbc075eaa2" +checksum = "1863fd3768cd83c56a7f60faa4dc0d403f1b6df0a38c3c25f44b7894e45370d5" dependencies = [ "core-foundation-sys", "libc", @@ -4290,9 +4318,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.23" +version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" +checksum = "3cb6eb87a131f756572d7fb904f6e7b68633f09cca868c5df1c4b8d1a694bbba" dependencies = [ "serde", ] @@ -4314,22 +4342,22 @@ checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" [[package]] name = "serde" -version = "1.0.215" +version = "1.0.216" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" +checksum = "0b9781016e935a97e8beecf0c933758c97a5520d32930e460142b4cd80c6338e" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.215" +version = "1.0.216" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" +checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4340,7 +4368,7 @@ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4412,7 +4440,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.6.0", + "indexmap 2.7.0", "serde", "serde_derive", "serde_json", @@ -4429,7 +4457,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4441,7 +4469,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4531,6 +4559,9 @@ name = "smallvec" version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" +dependencies = [ + "serde", +] [[package]] name = "smol_str" @@ -4650,7 +4681,7 @@ checksum = "bbc159a1934c7be9761c237333a57febe060ace2bc9e3b337a59a37af206d19f" dependencies = [ "starknet-curve 0.4.2", "starknet-ff", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4742,7 +4773,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4764,9 +4795,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.89" +version = "2.0.90" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d46482f1c1c87acd84dea20c1bf5ebff4c757009ed6bf19cfd36fb10e92c4e" +checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31" dependencies = [ "proc-macro2", "quote", @@ -4775,22 +4806,16 @@ dependencies = [ [[package]] name = "syn-solidity" -version = "0.8.14" +version = "0.8.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0523f59468a2696391f2a772edc089342aacd53c3caa2ac3264e598edf119b" +checksum = "219389c1ebe89f8333df8bdfb871f6631c552ff399c23cac02480b6088aad8f0" dependencies = [ "paste", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] -[[package]] -name = "sync_wrapper" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" - [[package]] name = "sync_wrapper" version = "1.0.2" @@ -4808,7 +4833,16 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", +] + +[[package]] +name = "syscall_handler" +version = "0.1.0" +dependencies = [ + "cairo-vm", + "thiserror 1.0.69", + "types", ] [[package]] @@ -4873,11 +4907,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.3" +version = "2.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c006c85c7651b3cf2ada4584faa36773bd07bac24acfb39f3c431b36d7e667aa" +checksum = "08f5383f3e0071702bf93ab5ee99b52d26936be9dedd9413067cbdcddcb6141a" dependencies = [ - "thiserror-impl 2.0.3", + "thiserror-impl 2.0.8", ] [[package]] @@ -4888,18 +4922,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] name = "thiserror-impl" -version = "2.0.3" +version = "2.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f077553d607adc1caf65430528a576c757a71ed73944b66ebb58ef2bbd243568" +checksum = "f2f357fcec90b3caef6623a099691be676d033b40a058ac95d2a6ade6fa0c943" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -4983,9 +5017,9 @@ dependencies = [ [[package]] name = "tokio" -version = "1.41.1" +version = "1.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33" +checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551" dependencies = [ "backtrace", "bytes", @@ -5007,7 +5041,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -5022,20 +5056,19 @@ dependencies = [ [[package]] name = "tokio-rustls" -version = "0.26.0" +version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" +checksum = "5f6d0975eaace0cf0fcadee4e4aaa5da15b5c079146f2cffb67c113be122bf37" dependencies = [ "rustls", - "rustls-pki-types", "tokio", ] [[package]] name = "tokio-stream" -version = "0.1.16" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f4e6ce100d0eb49a2734f8c0812bcd324cf357d21810932c5df6b96ef2b86f1" +checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" dependencies = [ "futures-core", "pin-project-lite", @@ -5061,9 +5094,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.12" +version = "0.7.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61e7c3654c13bcd040d4a03abee2c75b1d14a37b423cf5a813ceae1cc903ec6a" +checksum = "d7fcaa8d55a2bdd6b83ace262b016eca0d79ee02818c5c1bcdf0305114081078" dependencies = [ "bytes", "futures-core", @@ -5099,7 +5132,7 @@ version = "0.22.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5" dependencies = [ - "indexmap 2.6.0", + "indexmap 2.7.0", "serde", "serde_spanned", "toml_datetime", @@ -5108,14 +5141,14 @@ dependencies = [ [[package]] name = "tower" -version = "0.5.1" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2873938d487c3cfb9aed7546dc9f2711d867c9f90c46b889989a2cb84eba6b4f" +checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" dependencies = [ "futures-core", "futures-util", "pin-project-lite", - "sync_wrapper 0.1.2", + "sync_wrapper", "tower-layer", "tower-service", ] @@ -5134,9 +5167,9 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tracing" -version = "0.1.40" +version = "0.1.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" dependencies = [ "pin-project-lite", "tracing-attributes", @@ -5151,7 +5184,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -5389,7 +5422,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "wasm-bindgen-shared", ] @@ -5423,7 +5456,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5510,7 +5543,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -5521,7 +5554,7 @@ checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0" dependencies = [ "windows-result", "windows-strings", - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -5530,7 +5563,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -5540,16 +5573,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" dependencies = [ "windows-result", - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", + "windows-targets", ] [[package]] @@ -5558,7 +5582,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -5567,22 +5591,7 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", + "windows-targets", ] [[package]] @@ -5591,46 +5600,28 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", "windows_i686_gnullvm", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -5643,48 +5634,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -5781,7 +5748,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "synstructure", ] @@ -5803,7 +5770,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -5823,7 +5790,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", "synstructure", ] @@ -5844,7 +5811,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] @@ -5866,7 +5833,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.89", + "syn 2.0.90", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 08f99e2e..39ea4a4c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,16 +2,18 @@ resolver = "2" members = [ + "crates/dry_hint_processor", "crates/dry_run", "crates/fetcher", - "crates/dry_hint_processor", - "crates/indexer", "crates/hints", + "crates/indexer", + "crates/syscall_handler", "crates/types", ] [workspace.dependencies] alloy = { version = "0.7.2", features = ["full"] } +alloy-rlp = { version = "0.3.5", features = ["derive"] } bincode = { version = "2.0.0-rc.3", default-features = false, features = ["serde"] } cairo-lang-casm = { version = "2.9.0-dev.0", default-features = false } cairo-lang-starknet-classes = { version = "2.9.0-dev.0" } @@ -22,21 +24,21 @@ hex = "0.4.3" num-bigint = "0.4.6" num-traits = "0.2.19" rand = "0.8" +reqwest = "0.12.9" serde = "1.0.215" serde_json = "1.0.132" -sha3 = "0.10.8" -thiserror = "1.0.64" -tiny-keccak = { version = "2.0.2", features = ["keccak"] } -tokio = { version = "1.41.1", features = ["full"] } -alloy-rlp = { version = "0.3.5", features = ["derive"] } -strum_macros = "0.26.4" serde_with = { version = "3.11.0", features = ["hex"] } +sha3 = "0.10.8" starknet-core = { version = "0.11.1", default-features = false } starknet-crypto = { version = "0.7.1", default-features = false } starknet-types-core = { version = "0.1.5", default-features = false } -reqwest = "0.12.9" +strum_macros = "0.26.4" +thiserror = "1.0.64" +tiny-keccak = { version = "2.0.2", features = ["keccak"] } +tokio = { version = "1.41.1", features = ["full"] } dry_hint_processor = { path = "crates/dry_hint_processor" } +hints = { path = "crates/hints" } indexer = { path = "crates/indexer" } -types = { path = "crates/types" } -hints = { path = "crates/hints" } \ No newline at end of file +syscall_handler = { path = "crates/syscall_handler" } +types = { path = "crates/types" } \ No newline at end of file diff --git a/crates/dry_hint_processor/Cargo.toml b/crates/dry_hint_processor/Cargo.toml index 579f4d5e..4b4fe533 100644 --- a/crates/dry_hint_processor/Cargo.toml +++ b/crates/dry_hint_processor/Cargo.toml @@ -28,4 +28,5 @@ starknet-core.workspace = true indexer.workspace = true types.workspace = true -hints.workspace = true \ No newline at end of file +hints.workspace = true +syscall_handler.workspace = true \ No newline at end of file diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs index 4685a142..2479b9e6 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs @@ -1,11 +1,9 @@ -use crate::syscall_handler::{ - traits::CallHandler, - utils::{SyscallExecutionError, SyscallResult}, -}; use alloy::providers::{Provider, RootProvider}; use alloy::transports::http::reqwest::Url; use alloy::transports::http::{Client, Http}; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use syscall_handler::traits::CallHandler; +use syscall_handler::{SyscallExecutionError, SyscallResult}; use std::env; use types::{ cairo::{ diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs index 985a878a..0523d8b9 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs @@ -1,12 +1,10 @@ -use crate::syscall_handler::{ - traits::CallHandler, - utils::{SyscallExecutionError, SyscallResult}, -}; use alloy::providers::{Provider, RootProvider}; use alloy::rpc::types::BlockTransactionsKind; use alloy::transports::http::reqwest::Url; use alloy::transports::http::{Client, Http}; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use syscall_handler::traits::CallHandler; +use syscall_handler::{SyscallExecutionError, SyscallResult}; use std::env; use types::{ cairo::{ diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs index 9410a79d..cec2d29c 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs @@ -4,9 +4,6 @@ pub mod receipt; pub mod storage; pub mod transaction; -use crate::syscall_handler::traits::{self, CallHandler}; -use crate::syscall_handler::utils::{felt_from_ptr, SyscallExecutionError, SyscallResult, WriteResponseResult}; -use crate::syscall_handler::utils::{run_handler, SyscallSelector}; use cairo_vm::vm::errors::hint_errors::HintError; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use serde::{Deserialize, Serialize}; @@ -14,6 +11,8 @@ use std::rc::Rc; use std::sync::RwLock; use std::{collections::HashSet, hash::Hash}; use strum_macros::FromRepr; +use syscall_handler::traits::CallHandler; +use syscall_handler::{felt_from_ptr, run_handler, traits, SyscallExecutionError, SyscallResult, SyscallSelector, WriteResponseResult}; use types::cairo::new_syscalls::{CallContractRequest, CallContractResponse}; use types::cairo::traits::CairoType; use types::keys; diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs index afc728d0..4ffd48de 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs @@ -1,11 +1,9 @@ -use crate::syscall_handler::{ - traits::CallHandler, - utils::{SyscallExecutionError, SyscallResult}, -}; use alloy::providers::{Provider, RootProvider}; use alloy::transports::http::reqwest::Url; use alloy::transports::http::{Client, Http}; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use syscall_handler::traits::CallHandler; +use syscall_handler::{SyscallExecutionError, SyscallResult}; use std::env; use types::{ cairo::{ diff --git a/crates/dry_hint_processor/src/syscall_handler/mod.rs b/crates/dry_hint_processor/src/syscall_handler/mod.rs index 3e06610b..4c1d50ad 100644 --- a/crates/dry_hint_processor/src/syscall_handler/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/mod.rs @@ -10,8 +10,6 @@ use std::{any::Any, collections::HashMap}; pub mod evm; pub mod starknet; -pub mod traits; -pub mod utils; pub const SYSCALL_HANDLER_CREATE: &str = "if 'syscall_handler' not in globals():\n from contract_bootloader.syscall_handler import SyscallHandler\n syscall_handler = SyscallHandler(segments=segments, dict_manager=__dict_manager)"; diff --git a/crates/syscall_handler/Cargo.toml b/crates/syscall_handler/Cargo.toml new file mode 100644 index 00000000..57894c22 --- /dev/null +++ b/crates/syscall_handler/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "syscall_handler" +version = "0.1.0" +edition = "2021" + +[dependencies] +cairo-vm.workspace = true +thiserror.workspace = true + +types.workspace = true \ No newline at end of file diff --git a/crates/dry_hint_processor/src/syscall_handler/utils.rs b/crates/syscall_handler/src/lib.rs similarity index 97% rename from crates/dry_hint_processor/src/syscall_handler/utils.rs rename to crates/syscall_handler/src/lib.rs index a44223aa..33f0967d 100644 --- a/crates/dry_hint_processor/src/syscall_handler/utils.rs +++ b/crates/syscall_handler/src/lib.rs @@ -1,3 +1,5 @@ +pub mod traits; + use cairo_vm::{ types::{ errors::math_errors::MathError, @@ -10,8 +12,7 @@ use cairo_vm::{ Felt252, }; use thiserror::Error; - -use super::traits::SyscallHandler; +use traits::SyscallHandler; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum SyscallSelector { @@ -146,8 +147,6 @@ fn write_failure(gas_counter: Felt252, error_data: Vec, vm: &mut Virtua Ok(()) } -pub const OUT_OF_GAS_ERROR: &str = "0x000000000000000000000000000000000000000000004f7574206f6620676173"; - pub fn run_handler(syscall_handler: &mut impl SyscallHandler, syscall_ptr: &mut Relocatable, vm: &mut VirtualMachine) -> Result<(), HintError> { let remaining_gas = felt_from_ptr(vm, syscall_ptr)?; let request = syscall_handler.read_request(vm, syscall_ptr)?; diff --git a/crates/dry_hint_processor/src/syscall_handler/traits.rs b/crates/syscall_handler/src/traits.rs similarity index 94% rename from crates/dry_hint_processor/src/syscall_handler/traits.rs rename to crates/syscall_handler/src/traits.rs index 4bc8ac8a..325e351f 100644 --- a/crates/dry_hint_processor/src/syscall_handler/traits.rs +++ b/crates/syscall_handler/src/traits.rs @@ -1,7 +1,8 @@ -use super::utils::{SyscallResult, WriteResponseResult}; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use types::cairo::traits::CairoType; +use crate::{SyscallResult, WriteResponseResult}; + pub trait SyscallHandler { type Request; type Response; From 44ff743558d2426c9e83bbfb9d8e80604fe5b24e Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 18 Dec 2024 09:37:35 +0100 Subject: [PATCH 46/75] common hints extracted --- Cargo.lock | 31 +++ Cargo.toml | 1 + crates/dry_hint_processor/src/lib.rs | 80 +------- .../src/syscall_handler/evm/account.rs | 2 +- .../src/syscall_handler/evm/header.rs | 2 +- .../src/syscall_handler/evm/storage.rs | 2 +- crates/hints/src/lib.rs | 94 +++++++++ crates/sound_hint_processor/Cargo.toml | 32 +++ .../src/input.rs} | 4 +- crates/sound_hint_processor/src/lib.rs | 154 +++++++++++++++ crates/sound_hint_processor/src/output.rs | 32 +++ .../src/syscall_handler/evm/account.rs | 37 ++++ .../src/syscall_handler/evm/header.rs | 37 ++++ .../src/syscall_handler/evm/mod.rs | 187 ++++++++++++++++++ .../src/syscall_handler/evm/receipt.rs | 1 + .../src/syscall_handler/evm/storage.rs | 37 ++++ .../src/syscall_handler/evm/transaction.rs | 1 + .../src/syscall_handler/mod.rs | 57 ++++++ .../src/syscall_handler/starknet/mod.rs | 1 + crates/sound_hint_processor/src/tests/mod.rs | 15 ++ 20 files changed, 725 insertions(+), 82 deletions(-) create mode 100644 crates/sound_hint_processor/Cargo.toml rename crates/{dry_hint_processor/src/run_input.rs => sound_hint_processor/src/input.rs} (81%) create mode 100644 crates/sound_hint_processor/src/lib.rs create mode 100644 crates/sound_hint_processor/src/output.rs create mode 100644 crates/sound_hint_processor/src/syscall_handler/evm/account.rs create mode 100644 crates/sound_hint_processor/src/syscall_handler/evm/header.rs create mode 100644 crates/sound_hint_processor/src/syscall_handler/evm/mod.rs create mode 100644 crates/sound_hint_processor/src/syscall_handler/evm/receipt.rs create mode 100644 crates/sound_hint_processor/src/syscall_handler/evm/storage.rs create mode 100644 crates/sound_hint_processor/src/syscall_handler/evm/transaction.rs create mode 100644 crates/sound_hint_processor/src/syscall_handler/mod.rs create mode 100644 crates/sound_hint_processor/src/syscall_handler/starknet/mod.rs create mode 100644 crates/sound_hint_processor/src/tests/mod.rs diff --git a/Cargo.lock b/Cargo.lock index c79f9fc4..bab0408f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4582,6 +4582,37 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "sound_hint_processor" +version = "0.1.0" +dependencies = [ + "alloy", + "alloy-rlp", + "bincode", + "cairo-lang-casm", + "cairo-lang-starknet-classes", + "cairo-type-derive", + "cairo-vm", + "hex", + "hints", + "indexer", + "num-bigint", + "num-traits", + "rand", + "reqwest", + "serde", + "serde_json", + "serde_with 3.11.0", + "starknet-core", + "starknet-crypto 0.7.3", + "starknet-types-core", + "strum_macros", + "syscall_handler", + "thiserror 1.0.69", + "tokio", + "types", +] + [[package]] name = "spin" version = "0.9.8" diff --git a/Cargo.toml b/Cargo.toml index 39ea4a4c..fa4cc7cd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ resolver = "2" members = [ "crates/dry_hint_processor", + "crates/sound_hint_processor", "crates/dry_run", "crates/fetcher", "crates/hints", diff --git a/crates/dry_hint_processor/src/lib.rs b/crates/dry_hint_processor/src/lib.rs index ae8cc898..f60512f6 100644 --- a/crates/dry_hint_processor/src/lib.rs +++ b/crates/dry_hint_processor/src/lib.rs @@ -18,19 +18,11 @@ use cairo_vm::{ vm::{errors::hint_errors::HintError, runners::cairo_runner::ResourceTracker, vm_core::VirtualMachine}, Felt252, }; -use hints::{contract_bootloader, decoder, merkle, print, rlp, segments, vars, verifiers}; +use hints::{extensive_hints, hints, vars, ExtensiveHintImpl, HintImpl}; use starknet_types_core::felt::Felt; use std::{any::Any, collections::HashMap}; use syscall_handler::evm::SyscallHandlerWrapper; -pub type HintImpl = fn(&mut VirtualMachine, &mut ExecutionScopes, &HintProcessorData, &HashMap) -> Result<(), HintError>; - -/// Hint Extensions extend the current map of hints used by the VM. -/// This behaviour achieves what the `vm_load_data` primitive does for cairo-lang -/// and is needed to implement os hints like `vm_load_program`. -type ExtensiveHintImpl = - fn(&mut VirtualMachine, &mut ExecutionScopes, &HintProcessorData, &HashMap) -> Result; - pub struct CustomHintProcessor { private_inputs: serde_json::Value, builtin_hint_proc: BuiltinHintProcessor, @@ -58,72 +50,7 @@ impl CustomHintProcessor { #[rustfmt::skip] fn hints() -> HashMap { - let mut hints = HashMap::::new(); - hints.insert(contract_bootloader::contract_class::LOAD_CONTRACT_CLASS.into(), contract_bootloader::contract_class::load_contract_class); - hints.insert(contract_bootloader::dict_manager::DICT_MANAGER_CREATE.into(), contract_bootloader::dict_manager::dict_manager_create); - hints.insert(contract_bootloader::params::LOAD_PARMAS.into(), contract_bootloader::params::load_parmas); - hints.insert(contract_bootloader::builtins::UPDATE_BUILTIN_PTRS.into(), contract_bootloader::builtins::update_builtin_ptrs); - hints.insert(contract_bootloader::builtins::SELECTED_BUILTINS.into(), contract_bootloader::builtins::selected_builtins); - hints.insert(contract_bootloader::builtins::SELECT_BUILTIN.into(), contract_bootloader::builtins::select_builtin); - hints.insert(decoder::evm::has_type_prefix::HINT_HAS_TYPE_PREFIX.into(), decoder::evm::has_type_prefix::hint_has_type_prefix); - hints.insert(decoder::evm::is_byzantium::HINT_IS_BYZANTIUM.into(), decoder::evm::is_byzantium::hint_is_byzantium); - hints.insert(decoder::evm::v_is_encoded::HINT_V_IS_ENCODED.into(), decoder::evm::v_is_encoded::hint_v_is_encoded); - hints.insert(merkle::HINT_TARGET_TASK_HASH.into(), merkle::hint_target_task_hash); - hints.insert(merkle::HINT_IS_LEFT_SMALLER.into(), merkle::hint_is_left_smaller); - hints.insert(rlp::divmod::HINT_DIVMOD_VALUE.into(), rlp::divmod::hint_divmod_value); - hints.insert(rlp::divmod::HINT_DIVMOD_RLP.into(), rlp::divmod::hint_divmod_rlp); - hints.insert(rlp::item_type::HINT_IS_LONG.into(), rlp::item_type::hint_is_long); - hints.insert(rlp::item_type::HINT_ITEM_TYPE.into(), rlp::item_type::hint_item_type); - hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS.into(), rlp::processed_words::hint_processed_words); - hints.insert(print::PROGRAM_HASH.into(), print::program_hash); - hints.insert(segments::SEGMENTS_ADD.into(), segments::segments_add); - hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_SEGMENT_INDEX.into(), segments::segments_add_evm_memorizer_segment_index); - hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_OFFSET.into(), segments::segments_add_evm_memorizer_offset); - hints.insert(segments::SEGMENTS_ADD_EVM_STARKNET_MEMORIZER_INDEX.into(), segments::segments_add_evm_starknet_memorizer_index); - hints.insert(segments::SEGMENTS_ADD_STARKNET_MEMORIZER_OFFSET.into(), segments::segments_add_starknet_memorizer_offset); - hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY.into(), verifiers::evm::account_verifier::hint_account_key); - hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY_LEADING_ZEROS.into(), verifiers::evm::account_verifier::hint_account_key_leading_zeros); - hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_AT.into(), verifiers::evm::account_verifier::hint_account_proof_at); - hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BLOCK_NUMBER.into(), verifiers::evm::account_verifier::hint_account_proof_block_number); - hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BYTES_LEN.into(), verifiers::evm::account_verifier::hint_account_proof_bytes_len); - hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOFS_LEN.into(), verifiers::evm::account_verifier::hint_account_proofs_len); - hints.insert(verifiers::evm::account_verifier::HINT_BATCH_ACCOUNTS_LEN.into(), verifiers::evm::account_verifier::hint_batch_accounts_len); - hints.insert(verifiers::evm::account_verifier::HINT_GET_ACCOUNT_ADDRESS.into(), verifiers::evm::account_verifier::hint_get_account_address); - hints.insert(verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), verifiers::evm::account_verifier::hint_get_mpt_proof); - hints.insert(verifiers::evm::transaction_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), verifiers::evm::transaction_verifier::hint_batch_transactions_len); - hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX.into(), verifiers::evm::transaction_verifier::hint_set_tx); - hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY.into(), verifiers::evm::transaction_verifier::hint_set_tx_key); - hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY_LEADING_ZEROS.into(), verifiers::evm::transaction_verifier::hint_set_tx_key_leading_zeros); - hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_PROOF_LEN.into(), verifiers::evm::transaction_verifier::hint_set_tx_proof_len); - hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), verifiers::evm::transaction_verifier::hint_set_tx_block_number); - hints.insert(verifiers::evm::transaction_verifier::HINT_PROOF_BYTES_LEN.into(), verifiers::evm::transaction_verifier::hint_proof_bytes_len); - hints.insert(verifiers::evm::transaction_verifier::HINT_MPT_PROOF.into(), verifiers::evm::transaction_verifier::hint_mpt_proof); - hints.insert(verifiers::evm::header_verifier::HINT_LEAF_IDX.into(), verifiers::evm::header_verifier::hint_leaf_idx); - hints.insert(verifiers::evm::header_verifier::HINT_MMR_PATH_LEN.into(), verifiers::evm::header_verifier::hint_mmr_path_len); - hints.insert(verifiers::evm::header_verifier::HINT_MMR_PATH.into(), verifiers::evm::header_verifier::hint_mmr_path); - hints.insert(verifiers::evm::header_verifier::HINT_RLP_LEN.into(), verifiers::evm::header_verifier::hint_rlp_len); - hints.insert(verifiers::evm::header_verifier::HINT_SET_HEADER.into(), verifiers::evm::header_verifier::hint_set_header); - hints.insert(verifiers::evm::receipt_verifier::HINT_BATCH_RECEIPTS_LEN.into(), verifiers::evm::receipt_verifier::hint_batch_receipts_len); - hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_BLOCK_NUMBER.into(), verifiers::evm::receipt_verifier::hint_receipt_block_number); - hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY.into(), verifiers::evm::receipt_verifier::hint_receipt_key); - hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY_LEADING_ZEROS.into(), verifiers::evm::receipt_verifier::hint_receipt_key_leading_zeros); - hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_MPT_PROOF.into(), verifiers::evm::receipt_verifier::hint_receipt_mpt_proof); - hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_len); - hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_BYTES_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_bytes_len); - hints.insert(verifiers::evm::receipt_verifier::HINT_SET_RECEIPT.into(), verifiers::evm::receipt_verifier::hint_set_receipt); - hints.insert(verifiers::evm::storage_item_verifier::HINT_BATCH_STORAGES_LEN.into(), verifiers::evm::storage_item_verifier::hint_batch_storages_len); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_BATCH_STORAGES.into(), verifiers::evm::storage_item_verifier::hint_set_batch_storages); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_MPT_PROOF.into(), verifiers::evm::storage_item_verifier::hint_set_mpt_proof); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_proof_len); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BYTES_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_proof_bytes_len); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BLOCK_NUMBER.into(), verifiers::evm::storage_item_verifier::hint_set_proof_block_number); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY_LEADING_ZEROS.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key_leading_zeros); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOFS_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_storage_proofs_len); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOF_AT.into(), verifiers::evm::storage_item_verifier::hint_set_storage_proof_at); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_SLOT.into(), verifiers::evm::storage_item_verifier::hint_set_storage_slot); - hints.insert(verifiers::verify::HINT_VM_ENTER_SCOPE.into(), verifiers::verify::hint_vm_enter_scope); - hints.insert(verifiers::utils::HINT_PRINT_TASK_RESULT.into(), verifiers::utils::hint_print_task_result); + let mut hints = hints(); hints.insert(syscall_handler::DRY_RUN_SYSCALL_HANDLER_CREATE.into(), syscall_handler::dry_run_syscall_handler_create); hints.insert(syscall_handler::SYSCALL_HANDLER_CREATE.into(), syscall_handler::syscall_handler_create); hints.insert(syscall_handler::SYSCALL_HANDLER_SET_SYSCALL_PTR.into(), syscall_handler::syscall_handler_set_syscall_ptr); @@ -133,8 +60,7 @@ impl CustomHintProcessor { #[rustfmt::skip] fn extensive_hints() -> HashMap { - let mut hints = HashMap::::new(); - hints.insert(hints::contract_bootloader::program::LOAD_PROGRAM.into(), hints::contract_bootloader::program::load_program); + let hints = extensive_hints(); hints } } diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs index 2479b9e6..9ba4f3af 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs @@ -2,9 +2,9 @@ use alloy::providers::{Provider, RootProvider}; use alloy::transports::http::reqwest::Url; use alloy::transports::http::{Client, Http}; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use std::env; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; -use std::env; use types::{ cairo::{ evm::account::{CairoAccount, FunctionId}, diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs index 0523d8b9..38f38257 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs @@ -3,9 +3,9 @@ use alloy::rpc::types::BlockTransactionsKind; use alloy::transports::http::reqwest::Url; use alloy::transports::http::{Client, Http}; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use std::env; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; -use std::env; use types::{ cairo::{ evm::header::{CairoHeader, FunctionId}, diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs index 4ffd48de..083750be 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs @@ -2,9 +2,9 @@ use alloy::providers::{Provider, RootProvider}; use alloy::transports::http::reqwest::Url; use alloy::transports::http::{Client, Http}; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use std::env; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; -use std::env; use types::{ cairo::{ evm::storage::{CairoStorage, FunctionId}, diff --git a/crates/hints/src/lib.rs b/crates/hints/src/lib.rs index 118a1c61..221d7bd6 100644 --- a/crates/hints/src/lib.rs +++ b/crates/hints/src/lib.rs @@ -1,3 +1,11 @@ +use cairo_vm::{ + hint_processor::{builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData, hint_processor_definition::HintExtension}, + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use std::collections::HashMap; + pub mod contract_bootloader; pub mod decoder; pub mod merkle; @@ -7,3 +15,89 @@ pub mod segments; pub mod utils; pub mod vars; pub mod verifiers; + +pub type HintImpl = fn(&mut VirtualMachine, &mut ExecutionScopes, &HintProcessorData, &HashMap) -> Result<(), HintError>; + +/// Hint Extensions extend the current map of hints used by the VM. +/// This behaviour achieves what the `vm_load_data` primitive does for cairo-lang +/// and is needed to implement os hints like `vm_load_program`. +pub type ExtensiveHintImpl = + fn(&mut VirtualMachine, &mut ExecutionScopes, &HintProcessorData, &HashMap) -> Result; + +#[rustfmt::skip] +pub fn hints() -> HashMap { + let mut hints = HashMap::::new(); + hints.insert(contract_bootloader::contract_class::LOAD_CONTRACT_CLASS.into(), contract_bootloader::contract_class::load_contract_class); + hints.insert(contract_bootloader::dict_manager::DICT_MANAGER_CREATE.into(), contract_bootloader::dict_manager::dict_manager_create); + hints.insert(contract_bootloader::params::LOAD_PARMAS.into(), contract_bootloader::params::load_parmas); + hints.insert(contract_bootloader::builtins::UPDATE_BUILTIN_PTRS.into(), contract_bootloader::builtins::update_builtin_ptrs); + hints.insert(contract_bootloader::builtins::SELECTED_BUILTINS.into(), contract_bootloader::builtins::selected_builtins); + hints.insert(contract_bootloader::builtins::SELECT_BUILTIN.into(), contract_bootloader::builtins::select_builtin); + hints.insert(decoder::evm::has_type_prefix::HINT_HAS_TYPE_PREFIX.into(), decoder::evm::has_type_prefix::hint_has_type_prefix); + hints.insert(decoder::evm::is_byzantium::HINT_IS_BYZANTIUM.into(), decoder::evm::is_byzantium::hint_is_byzantium); + hints.insert(decoder::evm::v_is_encoded::HINT_V_IS_ENCODED.into(), decoder::evm::v_is_encoded::hint_v_is_encoded); + hints.insert(merkle::HINT_TARGET_TASK_HASH.into(), merkle::hint_target_task_hash); + hints.insert(merkle::HINT_IS_LEFT_SMALLER.into(), merkle::hint_is_left_smaller); + hints.insert(rlp::divmod::HINT_DIVMOD_VALUE.into(), rlp::divmod::hint_divmod_value); + hints.insert(rlp::divmod::HINT_DIVMOD_RLP.into(), rlp::divmod::hint_divmod_rlp); + hints.insert(rlp::item_type::HINT_IS_LONG.into(), rlp::item_type::hint_is_long); + hints.insert(rlp::item_type::HINT_ITEM_TYPE.into(), rlp::item_type::hint_item_type); + hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS.into(), rlp::processed_words::hint_processed_words); + hints.insert(print::PROGRAM_HASH.into(), print::program_hash); + hints.insert(segments::SEGMENTS_ADD.into(), segments::segments_add); + hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_SEGMENT_INDEX.into(), segments::segments_add_evm_memorizer_segment_index); + hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_OFFSET.into(), segments::segments_add_evm_memorizer_offset); + hints.insert(segments::SEGMENTS_ADD_EVM_STARKNET_MEMORIZER_INDEX.into(), segments::segments_add_evm_starknet_memorizer_index); + hints.insert(segments::SEGMENTS_ADD_STARKNET_MEMORIZER_OFFSET.into(), segments::segments_add_starknet_memorizer_offset); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY.into(), verifiers::evm::account_verifier::hint_account_key); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY_LEADING_ZEROS.into(), verifiers::evm::account_verifier::hint_account_key_leading_zeros); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_AT.into(), verifiers::evm::account_verifier::hint_account_proof_at); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BLOCK_NUMBER.into(), verifiers::evm::account_verifier::hint_account_proof_block_number); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BYTES_LEN.into(), verifiers::evm::account_verifier::hint_account_proof_bytes_len); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOFS_LEN.into(), verifiers::evm::account_verifier::hint_account_proofs_len); + hints.insert(verifiers::evm::account_verifier::HINT_BATCH_ACCOUNTS_LEN.into(), verifiers::evm::account_verifier::hint_batch_accounts_len); + hints.insert(verifiers::evm::account_verifier::HINT_GET_ACCOUNT_ADDRESS.into(), verifiers::evm::account_verifier::hint_get_account_address); + hints.insert(verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), verifiers::evm::account_verifier::hint_get_mpt_proof); + hints.insert(verifiers::evm::transaction_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), verifiers::evm::transaction_verifier::hint_batch_transactions_len); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX.into(), verifiers::evm::transaction_verifier::hint_set_tx); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY.into(), verifiers::evm::transaction_verifier::hint_set_tx_key); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY_LEADING_ZEROS.into(), verifiers::evm::transaction_verifier::hint_set_tx_key_leading_zeros); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_PROOF_LEN.into(), verifiers::evm::transaction_verifier::hint_set_tx_proof_len); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), verifiers::evm::transaction_verifier::hint_set_tx_block_number); + hints.insert(verifiers::evm::transaction_verifier::HINT_PROOF_BYTES_LEN.into(), verifiers::evm::transaction_verifier::hint_proof_bytes_len); + hints.insert(verifiers::evm::transaction_verifier::HINT_MPT_PROOF.into(), verifiers::evm::transaction_verifier::hint_mpt_proof); + hints.insert(verifiers::evm::header_verifier::HINT_LEAF_IDX.into(), verifiers::evm::header_verifier::hint_leaf_idx); + hints.insert(verifiers::evm::header_verifier::HINT_MMR_PATH_LEN.into(), verifiers::evm::header_verifier::hint_mmr_path_len); + hints.insert(verifiers::evm::header_verifier::HINT_MMR_PATH.into(), verifiers::evm::header_verifier::hint_mmr_path); + hints.insert(verifiers::evm::header_verifier::HINT_RLP_LEN.into(), verifiers::evm::header_verifier::hint_rlp_len); + hints.insert(verifiers::evm::header_verifier::HINT_SET_HEADER.into(), verifiers::evm::header_verifier::hint_set_header); + hints.insert(verifiers::evm::receipt_verifier::HINT_BATCH_RECEIPTS_LEN.into(), verifiers::evm::receipt_verifier::hint_batch_receipts_len); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_BLOCK_NUMBER.into(), verifiers::evm::receipt_verifier::hint_receipt_block_number); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY.into(), verifiers::evm::receipt_verifier::hint_receipt_key); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY_LEADING_ZEROS.into(), verifiers::evm::receipt_verifier::hint_receipt_key_leading_zeros); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_MPT_PROOF.into(), verifiers::evm::receipt_verifier::hint_receipt_mpt_proof); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_len); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_BYTES_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_bytes_len); + hints.insert(verifiers::evm::receipt_verifier::HINT_SET_RECEIPT.into(), verifiers::evm::receipt_verifier::hint_set_receipt); + hints.insert(verifiers::evm::storage_item_verifier::HINT_BATCH_STORAGES_LEN.into(), verifiers::evm::storage_item_verifier::hint_batch_storages_len); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_BATCH_STORAGES.into(), verifiers::evm::storage_item_verifier::hint_set_batch_storages); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_MPT_PROOF.into(), verifiers::evm::storage_item_verifier::hint_set_mpt_proof); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_proof_len); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BYTES_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_proof_bytes_len); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BLOCK_NUMBER.into(), verifiers::evm::storage_item_verifier::hint_set_proof_block_number); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY_LEADING_ZEROS.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key_leading_zeros); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOFS_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_storage_proofs_len); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOF_AT.into(), verifiers::evm::storage_item_verifier::hint_set_storage_proof_at); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_SLOT.into(), verifiers::evm::storage_item_verifier::hint_set_storage_slot); + hints.insert(verifiers::verify::HINT_VM_ENTER_SCOPE.into(), verifiers::verify::hint_vm_enter_scope); + hints.insert(verifiers::utils::HINT_PRINT_TASK_RESULT.into(), verifiers::utils::hint_print_task_result); + hints +} + +#[rustfmt::skip] +pub fn extensive_hints() -> HashMap { + let mut hints = HashMap::::new(); + hints.insert(contract_bootloader::program::LOAD_PROGRAM.into(), contract_bootloader::program::load_program); + hints +} diff --git a/crates/sound_hint_processor/Cargo.toml b/crates/sound_hint_processor/Cargo.toml new file mode 100644 index 00000000..bb46b444 --- /dev/null +++ b/crates/sound_hint_processor/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "sound_hint_processor" +version = "0.1.0" +edition = "2021" + +[dependencies] +alloy.workspace = true +alloy-rlp.workspace = true +bincode.workspace = true +cairo-lang-casm.workspace = true +cairo-lang-starknet-classes.workspace = true +cairo-type-derive.workspace = true +cairo-vm.workspace = true +hex.workspace = true +num-bigint.workspace = true +num-traits.workspace = true +rand.workspace = true +serde_json.workspace = true +serde.workspace = true +starknet-crypto.workspace = true +starknet-types-core.workspace = true +thiserror.workspace = true +tokio = { workspace = true } +serde_with.workspace = true +reqwest.workspace = true +strum_macros.workspace = true +starknet-core.workspace = true + +indexer.workspace = true +types.workspace = true +hints.workspace = true +syscall_handler.workspace = true \ No newline at end of file diff --git a/crates/dry_hint_processor/src/run_input.rs b/crates/sound_hint_processor/src/input.rs similarity index 81% rename from crates/dry_hint_processor/src/run_input.rs rename to crates/sound_hint_processor/src/input.rs index 8685af08..eea30381 100644 --- a/crates/dry_hint_processor/src/run_input.rs +++ b/crates/sound_hint_processor/src/input.rs @@ -10,10 +10,10 @@ use hints::vars; use std::collections::HashMap; use types::{param::Param, proofs::Proofs, HDPInput}; -pub const HINT_RUN_INPUT: &str = "from tools.py.schema import HDPInput\nrun_input = HDPInput.Schema().load(program_input)\nproofs = run_input.proofs\nparams = run_input.params\ncompiled_class = run_input.compiled_class"; +pub const HINT_INPUT: &str = "from tools.py.schema import HDPInput\nrun_input = HDPInput.Schema().load(program_input)\nproofs = run_input.proofs\nparams = run_input.params\ncompiled_class = run_input.compiled_class"; impl CustomHintProcessor { - pub fn hint_run_input( + pub fn hint_input( &mut self, _vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, diff --git a/crates/sound_hint_processor/src/lib.rs b/crates/sound_hint_processor/src/lib.rs new file mode 100644 index 00000000..5e9cf57e --- /dev/null +++ b/crates/sound_hint_processor/src/lib.rs @@ -0,0 +1,154 @@ +#![forbid(unsafe_code)] +#![allow(async_fn_in_trait)] +pub mod input; +pub mod output; +pub mod syscall_handler; + +use cairo_lang_casm::{ + hints::{Hint, StarknetHint}, + operand::{BinOpOperand, DerefOrImmediate, Operation, Register, ResOperand}, +}; +use cairo_vm::{ + hint_processor::{ + builtin_hint_processor::builtin_hint_processor_definition::{BuiltinHintProcessor, HintProcessorData}, + cairo_1_hint_processor::hint_processor::Cairo1HintProcessor, + hint_processor_definition::{HintExtension, HintProcessorLogic}, + }, + types::{exec_scope::ExecutionScopes, relocatable::Relocatable}, + vm::{errors::hint_errors::HintError, runners::cairo_runner::ResourceTracker, vm_core::VirtualMachine}, + Felt252, +}; +use hints::{extensive_hints, hints, vars, ExtensiveHintImpl, HintImpl}; +use starknet_types_core::felt::Felt; +use std::{any::Any, collections::HashMap}; +use syscall_handler::evm::SyscallHandlerWrapper; + +pub struct CustomHintProcessor { + private_inputs: serde_json::Value, + builtin_hint_proc: BuiltinHintProcessor, + cairo1_builtin_hint_proc: Cairo1HintProcessor, + hints: HashMap, + extensive_hints: HashMap, +} + +impl Default for CustomHintProcessor { + fn default() -> Self { + Self::new(serde_json::Value::default()) + } +} + +impl CustomHintProcessor { + pub fn new(private_inputs: serde_json::Value) -> Self { + Self { + private_inputs, + builtin_hint_proc: BuiltinHintProcessor::new_empty(), + cairo1_builtin_hint_proc: Cairo1HintProcessor::new(Default::default(), Default::default(), true), + hints: Self::hints(), + extensive_hints: Self::extensive_hints(), + } + } + + #[rustfmt::skip] + fn hints() -> HashMap { + let hints = hints(); + hints + } + + #[rustfmt::skip] + fn extensive_hints() -> HashMap { + let hints = extensive_hints(); + hints + } +} + +impl HintProcessorLogic for CustomHintProcessor { + fn execute_hint( + &mut self, + _vm: &mut VirtualMachine, + _exec_scopes: &mut ExecutionScopes, + _hint_data: &Box, + _constants: &HashMap, + ) -> Result<(), HintError> { + unreachable!(); + } + + fn execute_hint_extensive( + &mut self, + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &Box, + constants: &HashMap, + ) -> Result { + if let Some(hpd) = hint_data.downcast_ref::() { + let hint_code = hpd.code.as_str(); + + let res = match hint_code { + crate::input::HINT_INPUT => self.hint_input(vm, exec_scopes, hpd, constants), + crate::output::HINT_OUTPUT => self.hint_output(vm, exec_scopes, hpd, constants), + _ => Err(HintError::UnknownHint(hint_code.to_string().into_boxed_str())), + }; + + if !matches!(res, Err(HintError::UnknownHint(_))) { + return res.map(|_| HintExtension::default()); + } + + if let Some(hint_impl) = self.hints.get(hint_code) { + return hint_impl(vm, exec_scopes, hpd, constants).map(|_| HintExtension::default()); + } + + if let Some(hint_impl) = self.extensive_hints.get(hint_code) { + let r = hint_impl(vm, exec_scopes, hpd, constants); + return r; + } + + return self + .builtin_hint_proc + .execute_hint(vm, exec_scopes, hint_data, constants) + .map(|_| HintExtension::default()); + } + + if let Some(hint) = hint_data.downcast_ref::() { + if let Hint::Starknet(StarknetHint::SystemCall { system }) = hint { + let syscall_ptr = get_ptr_from_res_operand(vm, system)?; + let syscall_handler = exec_scopes.get_mut_ref::(vars::scopes::SYSCALL_HANDLER)?; + return syscall_handler.execute_syscall(vm, syscall_ptr).map(|_| HintExtension::default()); + } else { + return self + .cairo1_builtin_hint_proc + .execute(vm, exec_scopes, hint) + .map(|_| HintExtension::default()); + } + } + + Err(HintError::WrongHintData) + } +} + +impl ResourceTracker for CustomHintProcessor {} + +fn get_ptr_from_res_operand(vm: &mut VirtualMachine, res: &ResOperand) -> Result { + let (cell, base_offset) = match res { + ResOperand::Deref(cell) => (cell, Felt252::ZERO), + ResOperand::BinOp(BinOpOperand { + op: Operation::Add, + a, + b: DerefOrImmediate::Immediate(b), + }) => (a, Felt252::from(&b.value)), + _ => { + return Err(HintError::CustomHint( + "Failed to extract buffer, expected ResOperand of BinOp type to have Inmediate b value" + .to_owned() + .into_boxed_str(), + )); + } + }; + let base = match cell.register { + Register::AP => vm.get_ap(), + Register::FP => vm.get_fp(), + }; + let cell_reloc = (base + (i32::from(cell.offset)))?; + (vm.get_relocatable(cell_reloc)? + &base_offset).map_err(|e| e.into()) +} + +#[cfg(test)] +pub mod tests; diff --git a/crates/sound_hint_processor/src/output.rs b/crates/sound_hint_processor/src/output.rs new file mode 100644 index 00000000..b2c867f9 --- /dev/null +++ b/crates/sound_hint_processor/src/output.rs @@ -0,0 +1,32 @@ +use super::CustomHintProcessor; +use cairo_vm::{ + hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_relocatable_from_var_name}, + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use hints::vars; +use std::collections::HashMap; + +pub const HINT_OUTPUT: &str = "print(\"result\", [hex(ids.result.low), hex(ids.result.high)])"; + +impl CustomHintProcessor { + pub fn hint_output( + &mut self, + vm: &mut VirtualMachine, + _exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, + ) -> Result<(), HintError> { + let result_ptr = get_relocatable_from_var_name(vars::ids::RESULT, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + + let result = vm + .get_continuous_range(result_ptr, 2)? + .into_iter() + .map(|v| v.get_int().unwrap()) + .collect::>(); + + println!("result: {}, {}", result[0], result[1]); + Ok(()) + } +} diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs new file mode 100644 index 00000000..c88906e3 --- /dev/null +++ b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs @@ -0,0 +1,37 @@ +use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use syscall_handler::traits::CallHandler; +use syscall_handler::{SyscallExecutionError, SyscallResult}; +use types::{ + cairo::{evm::account::FunctionId, structs::Uint256, traits::CairoType}, + keys::account::{CairoKey, Key}, +}; + +pub struct AccountCallHandler; + +#[allow(refining_impl_trait)] +impl CallHandler for AccountCallHandler { + type Key = Key; + type Id = FunctionId; + type CallHandlerResult = Uint256; + + fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { + let ret = CairoKey::from_memory(vm, *ptr)?; + *ptr = (*ptr + CairoKey::n_fields())?; + ret.try_into().map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into())) + } + + fn derive_id(selector: Felt252) -> SyscallResult { + Self::Id::from_repr(selector.try_into().map_err(|e| SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: format!("{}", e), + })?) + .ok_or(SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: "Invalid function identifier".to_string(), + }) + } + + fn handle(_key: Self::Key, _function_id: Self::Id) -> SyscallResult { + todo!() + } +} diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs new file mode 100644 index 00000000..5c8059bf --- /dev/null +++ b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs @@ -0,0 +1,37 @@ +use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use syscall_handler::traits::CallHandler; +use syscall_handler::{SyscallExecutionError, SyscallResult}; +use types::{ + cairo::{evm::header::FunctionId, structs::Uint256, traits::CairoType}, + keys::header::{CairoKey, Key}, +}; + +pub struct HeaderCallHandler; + +#[allow(refining_impl_trait)] +impl CallHandler for HeaderCallHandler { + type Key = Key; + type Id = FunctionId; + type CallHandlerResult = Uint256; + + fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { + let ret = CairoKey::from_memory(vm, *ptr)?; + *ptr = (*ptr + CairoKey::n_fields())?; + ret.try_into().map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into())) + } + + fn derive_id(selector: Felt252) -> SyscallResult { + Self::Id::from_repr(selector.try_into().map_err(|e| SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: format!("{}", e), + })?) + .ok_or(SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: "Invalid function identifier".to_string(), + }) + } + + fn handle(_key: Self::Key, _function_id: Self::Id) -> SyscallResult { + todo!() + } +} diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs b/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs new file mode 100644 index 00000000..cec2d29c --- /dev/null +++ b/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs @@ -0,0 +1,187 @@ +pub mod account; +pub mod header; +pub mod receipt; +pub mod storage; +pub mod transaction; + +use cairo_vm::vm::errors::hint_errors::HintError; +use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use serde::{Deserialize, Serialize}; +use std::rc::Rc; +use std::sync::RwLock; +use std::{collections::HashSet, hash::Hash}; +use strum_macros::FromRepr; +use syscall_handler::traits::CallHandler; +use syscall_handler::{felt_from_ptr, run_handler, traits, SyscallExecutionError, SyscallResult, SyscallSelector, WriteResponseResult}; +use types::cairo::new_syscalls::{CallContractRequest, CallContractResponse}; +use types::cairo::traits::CairoType; +use types::keys; + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct SyscallHandler { + #[serde(skip)] + pub syscall_ptr: Option, + pub call_contract_handler: CallContractHandler, +} + +/// SyscallHandler is wrapped in Rc> in order +/// to clone the reference when entering and exiting vm scopes +#[derive(Debug, Clone, Default)] +pub struct SyscallHandlerWrapper { + pub syscall_handler: Rc>, +} + +#[derive(FromRepr)] +pub enum CallHandlerId { + Header = 0, + Account = 1, + Storage = 2, + Transaction = 3, + Receipt = 4, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct CallContractHandler { + pub key_set: HashSet, +} + +impl SyscallHandlerWrapper { + pub fn new() -> Self { + Self { + syscall_handler: Rc::new(RwLock::new(SyscallHandler::default())), + } + } + pub fn set_syscall_ptr(&self, syscall_ptr: Relocatable) { + let mut syscall_handler = self.syscall_handler.write().unwrap(); + syscall_handler.syscall_ptr = Some(syscall_ptr); + } + + pub fn syscall_ptr(&self) -> Option { + let syscall_handler = self.syscall_handler.read().unwrap(); + syscall_handler.syscall_ptr + } + + pub fn execute_syscall(&mut self, vm: &mut VirtualMachine, syscall_ptr: Relocatable) -> Result<(), HintError> { + let mut syscall_handler = self.syscall_handler.write().unwrap(); + let ptr = &mut syscall_handler + .syscall_ptr + .ok_or(HintError::CustomHint(Box::from("syscall_ptr is None")))?; + + assert_eq!(*ptr, syscall_ptr); + + match SyscallSelector::try_from(felt_from_ptr(vm, ptr)?)? { + SyscallSelector::CallContract => run_handler(&mut syscall_handler.call_contract_handler, ptr, vm), + }?; + + syscall_handler.syscall_ptr = Some(*ptr); + + Ok(()) + } +} + +impl traits::SyscallHandler for CallContractHandler { + type Request = CallContractRequest; + type Response = CallContractResponse; + + fn read_request(&mut self, vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { + let ret = Self::Request::from_memory(vm, *ptr)?; + *ptr = (*ptr + Self::Request::cairo_size())?; + Ok(ret) + } + + fn execute(&mut self, request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult { + let mut calldata = request.calldata_start; + + let call_handler_id = CallHandlerId::try_from(request.contract_address)?; + + let segment_index = felt_from_ptr(vm, &mut calldata)?; + let offset = felt_from_ptr(vm, &mut calldata)?; + + let _memorizer = Relocatable::from(( + segment_index + .try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + offset + .try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + )); + + let retdata_start = vm.add_temporary_segment(); + let mut retdata_end = retdata_start; + + match call_handler_id { + CallHandlerId::Header => { + let key = header::HeaderCallHandler::derive_key(vm, &mut calldata)?; + let function_id = header::HeaderCallHandler::derive_id(request.selector)?; + let result = header::HeaderCallHandler::handle(key.clone(), function_id)?; + self.key_set.insert(DryRunKey::Header(key)); + result.to_memory(vm, retdata_end)?; + retdata_end += ::CallHandlerResult::n_fields(); + } + CallHandlerId::Account => { + let key = account::AccountCallHandler::derive_key(vm, &mut calldata)?; + let function_id = account::AccountCallHandler::derive_id(request.selector)?; + let result = account::AccountCallHandler::handle(key.clone(), function_id)?; + self.key_set.insert(DryRunKey::Account(key)); + result.to_memory(vm, retdata_end)?; + retdata_end += ::CallHandlerResult::n_fields(); + } + CallHandlerId::Storage => { + let key = storage::StorageCallHandler::derive_key(vm, &mut calldata)?; + let function_id = storage::StorageCallHandler::derive_id(request.selector)?; + let result = storage::StorageCallHandler::handle(key.clone(), function_id)?; + self.key_set.insert(DryRunKey::Storage(key)); + result.to_memory(vm, retdata_end)?; + retdata_end += ::CallHandlerResult::n_fields(); + } + _ => {} + } + + Ok(Self::Response { retdata_start, retdata_end }) + } + + fn write_response(&mut self, response: Self::Response, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult { + response.to_memory(vm, *ptr)?; + *ptr = (*ptr + Self::Response::cairo_size())?; + Ok(()) + } +} + +impl TryFrom for CallHandlerId { + type Error = SyscallExecutionError; + fn try_from(value: Felt252) -> Result { + Self::from_repr(value.try_into().map_err(|e| Self::Error::InvalidSyscallInput { + input: value, + info: format!("{}", e), + })?) + .ok_or(Self::Error::InvalidSyscallInput { + input: value, + info: "Invalid function identifier".to_string(), + }) + } +} + +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "lowercase")] +pub enum DryRunKey { + Account(keys::account::Key), + Header(keys::header::Key), + Storage(keys::storage::Key), +} + +impl DryRunKey { + pub fn is_account(&self) -> bool { + matches!(self, Self::Account(_)) + } + + pub fn is_header(&self) -> bool { + matches!(self, Self::Header(_)) + } + + pub fn is_storage(&self) -> bool { + matches!(self, Self::Storage(_)) + } +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct DryRunKeySet(HashSet); diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/receipt.rs b/crates/sound_hint_processor/src/syscall_handler/evm/receipt.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/crates/sound_hint_processor/src/syscall_handler/evm/receipt.rs @@ -0,0 +1 @@ + diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs new file mode 100644 index 00000000..41b4e10e --- /dev/null +++ b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs @@ -0,0 +1,37 @@ +use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use syscall_handler::traits::CallHandler; +use syscall_handler::{SyscallExecutionError, SyscallResult}; +use types::{ + cairo::{evm::storage::FunctionId, structs::Uint256, traits::CairoType}, + keys::storage::{CairoKey, Key}, +}; + +pub struct StorageCallHandler; + +#[allow(refining_impl_trait)] +impl CallHandler for StorageCallHandler { + type Key = Key; + type Id = FunctionId; + type CallHandlerResult = Uint256; + + fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { + let ret = CairoKey::from_memory(vm, *ptr)?; + *ptr = (*ptr + CairoKey::n_fields())?; + ret.try_into().map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into())) + } + + fn derive_id(selector: Felt252) -> SyscallResult { + Self::Id::from_repr(selector.try_into().map_err(|e| SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: format!("{}", e), + })?) + .ok_or(SyscallExecutionError::InvalidSyscallInput { + input: selector, + info: "Invalid function identifier".to_string(), + }) + } + + fn handle(_key: Self::Key, _function_id: Self::Id) -> SyscallResult { + todo!() + } +} diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/transaction.rs b/crates/sound_hint_processor/src/syscall_handler/evm/transaction.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/crates/sound_hint_processor/src/syscall_handler/evm/transaction.rs @@ -0,0 +1 @@ + diff --git a/crates/sound_hint_processor/src/syscall_handler/mod.rs b/crates/sound_hint_processor/src/syscall_handler/mod.rs new file mode 100644 index 00000000..38fef207 --- /dev/null +++ b/crates/sound_hint_processor/src/syscall_handler/mod.rs @@ -0,0 +1,57 @@ +use cairo_vm::{ + hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_ptr_from_var_name}, + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use evm::SyscallHandlerWrapper; +use hints::vars; +use std::{any::Any, collections::HashMap}; + +pub mod evm; +pub mod starknet; + +pub const SYSCALL_HANDLER_CREATE: &str = "if 'syscall_handler' not in globals():\n from contract_bootloader.syscall_handler import SyscallHandler\n syscall_handler = SyscallHandler(segments=segments, dict_manager=__dict_manager)"; + +pub fn syscall_handler_create( + _vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + if let Err(HintError::VariableNotInScopeError(_)) = exec_scopes.get::(vars::scopes::SYSCALL_HANDLER) { + let syscall_handler = SyscallHandlerWrapper::new(); + exec_scopes.insert_value(vars::scopes::SYSCALL_HANDLER, syscall_handler); + } + + Ok(()) +} + +pub const SYSCALL_HANDLER_SET_SYSCALL_PTR: &str = "syscall_handler.set_syscall_ptr(syscall_ptr=ids.syscall_ptr)"; + +pub fn syscall_handler_set_syscall_ptr( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let syscall_ptr = get_ptr_from_var_name(vars::ids::SYSCALL_PTR, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + let syscall_handler = exec_scopes.get_mut_ref::(vars::scopes::SYSCALL_HANDLER)?; + syscall_handler.set_syscall_ptr(syscall_ptr); + + Ok(()) +} + +pub const ENTER_SCOPE_SYSCALL_HANDLER: &str = "vm_enter_scope({'syscall_handler': syscall_handler})"; + +pub fn enter_scope_syscall_handler( + _vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let syscall_handler: Box = Box::new(exec_scopes.get::(vars::scopes::SYSCALL_HANDLER)?); + exec_scopes.enter_scope(HashMap::from_iter([(vars::scopes::SYSCALL_HANDLER.to_string(), syscall_handler)])); + + Ok(()) +} diff --git a/crates/sound_hint_processor/src/syscall_handler/starknet/mod.rs b/crates/sound_hint_processor/src/syscall_handler/starknet/mod.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/crates/sound_hint_processor/src/syscall_handler/starknet/mod.rs @@ -0,0 +1 @@ + diff --git a/crates/sound_hint_processor/src/tests/mod.rs b/crates/sound_hint_processor/src/tests/mod.rs new file mode 100644 index 00000000..023df9af --- /dev/null +++ b/crates/sound_hint_processor/src/tests/mod.rs @@ -0,0 +1,15 @@ +use crate::CustomHintProcessor; +use cairo_vm::{ + cairo_run, + vm::{errors::cairo_run_errors::CairoRunError, runners::cairo_runner::CairoRunner}, +}; + +pub fn run_cairo_program(program_content: &[u8]) -> Result { + let cairo_run_config = cairo_run::CairoRunConfig { + layout: cairo_vm::types::layout_name::LayoutName::all_cairo, + allow_missing_builtins: Some(true), + ..Default::default() + }; + + cairo_run::cairo_run(program_content, &cairo_run_config, &mut CustomHintProcessor::default()) +} From b885b7c9ce15b0f230e658ad4821eab5cf89adde Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 18 Dec 2024 09:40:02 +0100 Subject: [PATCH 47/75] sound_run sketched --- Cargo.lock | 12 ++++ Cargo.toml | 2 + crates/sound_run/Cargo.toml | 13 +++++ crates/sound_run/src/main.rs | 104 +++++++++++++++++++++++++++++++++++ 4 files changed, 131 insertions(+) create mode 100644 crates/sound_run/Cargo.toml create mode 100644 crates/sound_run/src/main.rs diff --git a/Cargo.lock b/Cargo.lock index bab0408f..0cbeb6cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4613,6 +4613,18 @@ dependencies = [ "types", ] +[[package]] +name = "sound_run" +version = "0.1.0" +dependencies = [ + "cairo-vm", + "clap", + "hints", + "serde_json", + "sound_hint_processor", + "thiserror 1.0.69", +] + [[package]] name = "spin" version = "0.9.8" diff --git a/Cargo.toml b/Cargo.toml index fa4cc7cd..77c3c769 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "crates/dry_hint_processor", "crates/sound_hint_processor", "crates/dry_run", + "crates/sound_run", "crates/fetcher", "crates/hints", "crates/indexer", @@ -39,6 +40,7 @@ tiny-keccak = { version = "2.0.2", features = ["keccak"] } tokio = { version = "1.41.1", features = ["full"] } dry_hint_processor = { path = "crates/dry_hint_processor" } +sound_hint_processor = { path = "crates/sound_hint_processor" } hints = { path = "crates/hints" } indexer = { path = "crates/indexer" } syscall_handler = { path = "crates/syscall_handler" } diff --git a/crates/sound_run/Cargo.toml b/crates/sound_run/Cargo.toml new file mode 100644 index 00000000..7eee92a7 --- /dev/null +++ b/crates/sound_run/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "sound_run" +version = "0.1.0" +edition = "2021" + +[dependencies] +sound_hint_processor.workspace = true +cairo-vm.workspace = true +clap.workspace = true +thiserror.workspace = true +serde_json.workspace = true + +hints.workspace = true \ No newline at end of file diff --git a/crates/sound_run/src/main.rs b/crates/sound_run/src/main.rs new file mode 100644 index 00000000..8e0e36d4 --- /dev/null +++ b/crates/sound_run/src/main.rs @@ -0,0 +1,104 @@ +#![forbid(unsafe_code)] +#![allow(async_fn_in_trait)] +use cairo_vm::{ + cairo_run::CairoRunConfig, + types::{layout_name::LayoutName, program::Program}, + vm::{errors::vm_exception::VmException, runners::cairo_runner::CairoRunner}, +}; +use clap::{Parser, ValueHint}; +use hints::vars; +use sound_hint_processor::{ + syscall_handler::evm::{SyscallHandler, SyscallHandlerWrapper}, + CustomHintProcessor, +}; +use std::path::PathBuf; + +#[derive(Parser, Debug)] +#[clap(author, version, about, long_about = None)] +struct Args { + #[clap(value_parser, value_hint=ValueHint::FilePath)] + filename: PathBuf, + /// When using dynamic layout, it's parameters must be specified through a layout params file. + #[clap(long = "layout", default_value = "plain", value_enum)] + layout: LayoutName, + #[structopt(long = "proof_mode")] + proof_mode: bool, + #[structopt(long = "program_input")] + program_input: PathBuf, + #[structopt(long = "program_output")] + program_output: PathBuf, +} + +fn main() -> Result<(), HdpOsError> { + let args = Args::try_parse_from(std::env::args()).map_err(HdpOsError::Args)?; + + // Init CairoRunConfig + let cairo_run_config = CairoRunConfig { + layout: args.layout, + relocate_mem: true, + trace_enabled: true, + ..Default::default() + }; + + let program_file = std::fs::read(args.filename).map_err(HdpOsError::IO)?; + let program_inputs = std::fs::read(args.program_input).map_err(HdpOsError::IO)?; + + // Load the Program + let program = Program::from_bytes(&program_file, Some(cairo_run_config.entrypoint)).map_err(|e| HdpOsError::Runner(e.into()))?; + + // Init cairo runner + let mut cairo_runner = CairoRunner::new( + &program, + cairo_run_config.layout, + None, + cairo_run_config.proof_mode, + cairo_run_config.trace_enabled, + ) + .map_err(|e| HdpOsError::Runner(e.into()))?; + + // Init the Cairo VM + let end = cairo_runner + .initialize(cairo_run_config.allow_missing_builtins.unwrap_or(false)) + .map_err(|e| HdpOsError::Runner(e.into()))?; + + // Run the Cairo VM + let mut hint_processor = CustomHintProcessor::new(serde_json::from_slice(&program_inputs)?); + cairo_runner + .run_until_pc(end, &mut hint_processor) + .map_err(|err| VmException::from_vm_error(&cairo_runner, err)) + .map_err(|e| HdpOsError::Runner(e.into()))?; + + std::fs::write( + args.program_output, + serde_json::to_vec::( + &cairo_runner + .exec_scopes + .get::(vars::scopes::SYSCALL_HANDLER) + .unwrap() + .syscall_handler + .try_read() + .unwrap(), + ) + .map_err(|e| HdpOsError::IO(e.into()))?, + ) + .map_err(HdpOsError::IO)?; + + Ok(()) +} + +use cairo_vm::vm::errors::cairo_run_errors::CairoRunError; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum HdpOsError { + #[error(transparent)] + Args(#[from] clap::error::Error), + #[error("Runner Error: {0}")] + Runner(CairoRunError), + #[error("Output Error: {0}")] + Output(String), + #[error(transparent)] + IO(#[from] std::io::Error), + #[error(transparent)] + SerdeJson(#[from] serde_json::Error), +} From 7fb6fe977c8924868faad4470787625ddd209b1a Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Thu, 19 Dec 2024 17:49:05 +0100 Subject: [PATCH 48/75] header mmr proofs verified --- Cargo.lock | 21 + Cargo.toml | 3 +- crates/dry_hint_processor/src/input.rs | 7 +- crates/dry_hint_processor/src/lib.rs | 14 +- crates/dry_hint_processor/src/tests/mod.rs | 15 - crates/dry_run/Cargo.toml | 3 +- crates/dry_run/src/main.rs | 5 +- crates/fetcher/src/main.rs | 1 + crates/hints/Cargo.toml | 3 +- .../hints/src/decoder/evm/has_type_prefix.rs | 4 +- crates/hints/src/decoder/evm/is_byzantium.rs | 2 +- crates/hints/src/lib.rs | 18 + crates/hints/src/rlp/processed_words.rs | 20 +- crates/hints/src/segments.rs | 12 + crates/hints/src/vars.rs | 53 +- .../src/verifiers/evm/account_verifier.rs | 14 +- .../src/verifiers/evm/header_verifier.rs | 35 +- .../src/verifiers/evm/receipt_verifier.rs | 8 +- .../verifiers/evm/storage_item_verifier.rs | 14 +- .../src/verifiers/evm/transaction_verifier.rs | 10 +- crates/hints/src/verifiers/mmr_verifier.rs | 87 ++ crates/hints/src/verifiers/mod.rs | 1 + crates/hints/src/verifiers/verify.rs | 10 +- crates/sound_hint_processor/src/input.rs | 9 +- crates/sound_hint_processor/src/lib.rs | 14 +- crates/sound_hint_processor/src/tests/mod.rs | 15 - crates/sound_run/Cargo.toml | 1 + crates/sound_run/src/main.rs | 33 +- crates/types/src/lib.rs | 2 +- packages/eth_essentials | 2 +- src/hdp.cairo | 56 +- src/hdp_input.json | 1080 ----------------- src/utils/rlp.cairo | 19 +- src/verifiers/evm/account_verifier.cairo | 8 +- src/verifiers/evm/block_tx_verifier.cairo | 6 +- src/verifiers/evm/header_verifier.cairo | 14 +- src/verifiers/evm/receipt_verifier.cairo | 6 +- src/verifiers/evm/storage_item_verifier.cairo | 8 +- src/verifiers/evm/verify.cairo | 10 +- src/verifiers/mmr_verifier.cairo | 19 +- src/verifiers/starknet/header_verifier.cairo | 10 +- src/verifiers/starknet/storage_verifier.cairo | 2 +- src/verifiers/verify.cairo | 1 + tools/make/setup.sh | 2 +- 44 files changed, 370 insertions(+), 1307 deletions(-) delete mode 100644 crates/dry_hint_processor/src/tests/mod.rs create mode 100644 crates/hints/src/verifiers/mmr_verifier.rs delete mode 100644 crates/sound_hint_processor/src/tests/mod.rs delete mode 100644 src/hdp_input.json diff --git a/Cargo.lock b/Cargo.lock index 0cbeb6cc..2f2d0a9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2091,6 +2091,7 @@ dependencies = [ "hints", "serde_json", "thiserror 1.0.69", + "types", ] [[package]] @@ -2178,6 +2179,24 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "eth_essentials_cairo_vm_hints" +version = "0.1.0" +dependencies = [ + "bincode", + "cairo-vm", + "clap", + "hex", + "num-bigint", + "num-traits", + "rand", + "sha3", + "starknet-crypto 0.7.3", + "starknet-types-core", + "thiserror 1.0.69", + "tiny-keccak", +] + [[package]] name = "fastrand" version = "2.3.0" @@ -2587,6 +2606,7 @@ dependencies = [ "cairo-lang-starknet-classes", "cairo-type-derive", "cairo-vm", + "eth_essentials_cairo_vm_hints", "hex", "num-bigint", "num-traits", @@ -4623,6 +4643,7 @@ dependencies = [ "serde_json", "sound_hint_processor", "thiserror 1.0.69", + "types", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 77c3c769..67e56992 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,4 +44,5 @@ sound_hint_processor = { path = "crates/sound_hint_processor" } hints = { path = "crates/hints" } indexer = { path = "crates/indexer" } syscall_handler = { path = "crates/syscall_handler" } -types = { path = "crates/types" } \ No newline at end of file +types = { path = "crates/types" } +eth_essentials_cairo_vm_hints = { path = "packages/eth_essentials/cairo_vm_hints"} \ No newline at end of file diff --git a/crates/dry_hint_processor/src/input.rs b/crates/dry_hint_processor/src/input.rs index 1659493f..d87a132c 100644 --- a/crates/dry_hint_processor/src/input.rs +++ b/crates/dry_hint_processor/src/input.rs @@ -8,7 +8,7 @@ use cairo_vm::{ }; use hints::vars; use std::collections::HashMap; -use types::{param::Param, HDPDryRunInput}; +use types::param::Param; pub const HINT_INPUT: &str = "from tools.py.schema import HDPDryRunInput\ndry_run_input = HDPDryRunInput.Schema().load(program_input)\nparams = dry_run_input.params\ncompiled_class = dry_run_input.compiled_class"; @@ -20,9 +20,8 @@ impl CustomHintProcessor { _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let hdp_dry_run_input: HDPDryRunInput = serde_json::from_value(self.private_inputs.clone()).map_err(|_| HintError::WrongHintData)?; - exec_scopes.insert_value::>(vars::scopes::PARAMS, hdp_dry_run_input.params); - exec_scopes.insert_value::(vars::scopes::COMPILED_CLASS, hdp_dry_run_input.compiled_class); + exec_scopes.insert_value::>(vars::scopes::PARAMS, self.private_inputs.params.to_owned()); + exec_scopes.insert_value::(vars::scopes::COMPILED_CLASS, self.private_inputs.compiled_class.to_owned()); Ok(()) } } diff --git a/crates/dry_hint_processor/src/lib.rs b/crates/dry_hint_processor/src/lib.rs index f60512f6..eb384d5c 100644 --- a/crates/dry_hint_processor/src/lib.rs +++ b/crates/dry_hint_processor/src/lib.rs @@ -22,23 +22,18 @@ use hints::{extensive_hints, hints, vars, ExtensiveHintImpl, HintImpl}; use starknet_types_core::felt::Felt; use std::{any::Any, collections::HashMap}; use syscall_handler::evm::SyscallHandlerWrapper; +use types::HDPDryRunInput; pub struct CustomHintProcessor { - private_inputs: serde_json::Value, + private_inputs: HDPDryRunInput, builtin_hint_proc: BuiltinHintProcessor, cairo1_builtin_hint_proc: Cairo1HintProcessor, hints: HashMap, extensive_hints: HashMap, } -impl Default for CustomHintProcessor { - fn default() -> Self { - Self::new(serde_json::Value::default()) - } -} - impl CustomHintProcessor { - pub fn new(private_inputs: serde_json::Value) -> Self { + pub fn new(private_inputs: HDPDryRunInput) -> Self { Self { private_inputs, builtin_hint_proc: BuiltinHintProcessor::new_empty(), @@ -153,6 +148,3 @@ fn get_ptr_from_res_operand(vm: &mut VirtualMachine, res: &ResOperand) -> Result let cell_reloc = (base + (i32::from(cell.offset)))?; (vm.get_relocatable(cell_reloc)? + &base_offset).map_err(|e| e.into()) } - -#[cfg(test)] -pub mod tests; diff --git a/crates/dry_hint_processor/src/tests/mod.rs b/crates/dry_hint_processor/src/tests/mod.rs deleted file mode 100644 index 023df9af..00000000 --- a/crates/dry_hint_processor/src/tests/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -use crate::CustomHintProcessor; -use cairo_vm::{ - cairo_run, - vm::{errors::cairo_run_errors::CairoRunError, runners::cairo_runner::CairoRunner}, -}; - -pub fn run_cairo_program(program_content: &[u8]) -> Result { - let cairo_run_config = cairo_run::CairoRunConfig { - layout: cairo_vm::types::layout_name::LayoutName::all_cairo, - allow_missing_builtins: Some(true), - ..Default::default() - }; - - cairo_run::cairo_run(program_content, &cairo_run_config, &mut CustomHintProcessor::default()) -} diff --git a/crates/dry_run/Cargo.toml b/crates/dry_run/Cargo.toml index 6140100c..485e7473 100644 --- a/crates/dry_run/Cargo.toml +++ b/crates/dry_run/Cargo.toml @@ -10,4 +10,5 @@ clap.workspace = true thiserror.workspace = true serde_json.workspace = true -hints.workspace = true \ No newline at end of file +hints.workspace = true +types.workspace = true \ No newline at end of file diff --git a/crates/dry_run/src/main.rs b/crates/dry_run/src/main.rs index a0c1463a..406a6b14 100644 --- a/crates/dry_run/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -12,6 +12,7 @@ use dry_hint_processor::{ }; use hints::vars; use std::path::PathBuf; +use types::HDPDryRunInput; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] @@ -41,7 +42,7 @@ fn main() -> Result<(), HdpOsError> { }; let program_file = std::fs::read(args.filename).map_err(HdpOsError::IO)?; - let program_inputs = std::fs::read(args.program_input).map_err(HdpOsError::IO)?; + let program_inputs: HDPDryRunInput = serde_json::from_slice(&std::fs::read(args.program_input).map_err(HdpOsError::IO)?)?; // Load the Program let program = Program::from_bytes(&program_file, Some(cairo_run_config.entrypoint)).map_err(|e| HdpOsError::Runner(e.into()))?; @@ -62,7 +63,7 @@ fn main() -> Result<(), HdpOsError> { .map_err(|e| HdpOsError::Runner(e.into()))?; // Run the Cairo VM - let mut hint_processor = CustomHintProcessor::new(serde_json::from_slice(&program_inputs)?); + let mut hint_processor = CustomHintProcessor::new(program_inputs); cairo_runner .run_until_pc(end, &mut hint_processor) .map_err(|err| VmException::from_vm_error(&cairo_runner, err)) diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index 253bbb23..fa56e727 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -77,6 +77,7 @@ fn main() -> Result<(), FetcherError> { storages: storages.into_iter().collect(), ..Default::default() }; + fs::write(args.program_output, serde_json::to_vec(&proofs).map_err(|e| FetcherError::IO(e.into()))?)?; Ok(()) diff --git a/crates/hints/Cargo.toml b/crates/hints/Cargo.toml index 6fe90dc3..56d19937 100644 --- a/crates/hints/Cargo.toml +++ b/crates/hints/Cargo.toml @@ -26,4 +26,5 @@ reqwest.workspace = true strum_macros.workspace = true starknet-core.workspace = true -types.workspace = true \ No newline at end of file +types.workspace = true +eth_essentials_cairo_vm_hints.workspace = true \ No newline at end of file diff --git a/crates/hints/src/decoder/evm/has_type_prefix.rs b/crates/hints/src/decoder/evm/has_type_prefix.rs index e60992c7..cb270833 100644 --- a/crates/hints/src/decoder/evm/has_type_prefix.rs +++ b/crates/hints/src/decoder/evm/has_type_prefix.rs @@ -22,9 +22,9 @@ pub fn hint_has_type_prefix( let first_byte = get_integer_from_var_name("first_byte", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; let insert = if Felt252::ZERO < first_byte && first_byte < FELT_4 { - Felt252::ZERO - } else { Felt252::ONE + } else { + Felt252::ZERO }; insert_value_from_var_name( diff --git a/crates/hints/src/decoder/evm/is_byzantium.rs b/crates/hints/src/decoder/evm/is_byzantium.rs index 945513de..941d7c4a 100644 --- a/crates/hints/src/decoder/evm/is_byzantium.rs +++ b/crates/hints/src/decoder/evm/is_byzantium.rs @@ -21,8 +21,8 @@ pub fn hint_is_byzantium( ) -> Result<(), HintError> { let insert = match get_integer_from_var_name("block_number", vm, &hint_data.ids_data, &hint_data.ap_tracking)?.cmp(&BYZANTIUM_START_BLOCK_NUMBER) { - Ordering::Less => Felt252::ZERO, Ordering::Equal | Ordering::Greater => Felt252::ONE, + Ordering::Less => Felt252::ZERO, }; insert_value_from_var_name( diff --git a/crates/hints/src/lib.rs b/crates/hints/src/lib.rs index 221d7bd6..346fd66e 100644 --- a/crates/hints/src/lib.rs +++ b/crates/hints/src/lib.rs @@ -43,8 +43,10 @@ pub fn hints() -> HashMap { hints.insert(rlp::item_type::HINT_IS_LONG.into(), rlp::item_type::hint_is_long); hints.insert(rlp::item_type::HINT_ITEM_TYPE.into(), rlp::item_type::hint_item_type); hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS.into(), rlp::processed_words::hint_processed_words); + hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS_RLP.into(), rlp::processed_words::hint_processed_words_rlp); hints.insert(print::PROGRAM_HASH.into(), print::program_hash); hints.insert(segments::SEGMENTS_ADD.into(), segments::segments_add); + hints.insert(segments::SEGMENTS_ADD_FP.into(), segments::segments_add_fp); hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_SEGMENT_INDEX.into(), segments::segments_add_evm_memorizer_segment_index); hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_OFFSET.into(), segments::segments_add_evm_memorizer_offset); hints.insert(segments::SEGMENTS_ADD_EVM_STARKNET_MEMORIZER_INDEX.into(), segments::segments_add_evm_starknet_memorizer_index); @@ -66,6 +68,8 @@ pub fn hints() -> HashMap { hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), verifiers::evm::transaction_verifier::hint_set_tx_block_number); hints.insert(verifiers::evm::transaction_verifier::HINT_PROOF_BYTES_LEN.into(), verifiers::evm::transaction_verifier::hint_proof_bytes_len); hints.insert(verifiers::evm::transaction_verifier::HINT_MPT_PROOF.into(), verifiers::evm::transaction_verifier::hint_mpt_proof); + hints.insert(verifiers::evm::header_verifier::HINT_VM_ENTER_SCOPE.into(), verifiers::evm::header_verifier::hint_vm_enter_scope); + hints.insert(verifiers::evm::header_verifier::HINT_HEADERS_WITH_MMR_HEADERS_LEN.into(), verifiers::evm::header_verifier::hint_headers_with_mmr_headers_len); hints.insert(verifiers::evm::header_verifier::HINT_LEAF_IDX.into(), verifiers::evm::header_verifier::hint_leaf_idx); hints.insert(verifiers::evm::header_verifier::HINT_MMR_PATH_LEN.into(), verifiers::evm::header_verifier::hint_mmr_path_len); hints.insert(verifiers::evm::header_verifier::HINT_MMR_PATH.into(), verifiers::evm::header_verifier::hint_mmr_path); @@ -91,7 +95,21 @@ pub fn hints() -> HashMap { hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOF_AT.into(), verifiers::evm::storage_item_verifier::hint_set_storage_proof_at); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_SLOT.into(), verifiers::evm::storage_item_verifier::hint_set_storage_slot); hints.insert(verifiers::verify::HINT_VM_ENTER_SCOPE.into(), verifiers::verify::hint_vm_enter_scope); + hints.insert(verifiers::verify::HINT_HEADERS_WITH_MMR_LEN.into(), verifiers::verify::hint_headers_with_mmr_headers_len); + hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_PEAKS_LEN.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_peaks_len); + hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_ID.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_id); + hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_ROOT.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_root); + hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_SIZE.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_size); + hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_PEAKS.into(), verifiers::mmr_verifier::hint_headers_with_mmr_peaks); hints.insert(verifiers::utils::HINT_PRINT_TASK_RESULT.into(), verifiers::utils::hint_print_task_result); + + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mmr::bit_length::MMR_BIT_LENGTH.into(), eth_essentials_cairo_vm_hints::hints::lib::mmr::bit_length::mmr_bit_length); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mmr::left_child::MMR_LEFT_CHILD.into(), eth_essentials_cairo_vm_hints::hints::lib::mmr::left_child::mmr_left_child); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::bit_length::HINT_BIT_LENGTH.into(), eth_essentials_cairo_vm_hints::hints::lib::bit_length::hint_bit_length); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::assert::HINT_ASSERT_INTEGER_DIV.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::assert::hint_assert_integer_div); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::HINT_VALUE_DIV.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::hint_value_div); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::HINT_VALUE_8.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::hint_value_8); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_NEEDS_NEXT_WORD.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_needs_next_word); hints } diff --git a/crates/hints/src/rlp/processed_words.rs b/crates/hints/src/rlp/processed_words.rs index 9fa41828..776a66bf 100644 --- a/crates/hints/src/rlp/processed_words.rs +++ b/crates/hints/src/rlp/processed_words.rs @@ -19,7 +19,6 @@ pub fn hint_processed_words( _constants: &HashMap, ) -> Result<(), HintError> { let value_len = get_integer_from_var_name(vars::ids::VALUE_LEN, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let n_processed_words = get_integer_from_var_name(vars::ids::N_PROCESSED_WORDS, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; let insert = match (value_len - n_processed_words).cmp(&Felt252::ZERO) { @@ -29,3 +28,22 @@ pub fn hint_processed_words( insert_value_into_ap(vm, insert) } + +pub const HINT_PROCESSED_WORDS_RLP: &str = "memory[ap] = 1 if (ids.rlp_len - ids.n_processed_words == 0) else 0"; + +pub fn hint_processed_words_rlp( + vm: &mut VirtualMachine, + _exec_scope: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let rlp_len = get_integer_from_var_name(vars::ids::RLP_LEN, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + let n_processed_words = get_integer_from_var_name(vars::ids::N_PROCESSED_WORDS, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + + let insert = match (rlp_len - n_processed_words).cmp(&Felt252::ZERO) { + Ordering::Equal => Felt252::ONE, + _ => Felt252::ZERO, + }; + + insert_value_into_ap(vm, insert) +} diff --git a/crates/hints/src/segments.rs b/crates/hints/src/segments.rs index 3ac4f92c..20436224 100644 --- a/crates/hints/src/segments.rs +++ b/crates/hints/src/segments.rs @@ -21,6 +21,18 @@ pub fn segments_add( insert_value_into_ap(vm, segment) } +pub const SEGMENTS_ADD_FP: &str = "memory[fp + 0] = to_felt_or_relocatable(segments.add())"; +pub fn segments_add_fp( + vm: &mut VirtualMachine, + _exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let segment = vm.add_memory_segment(); + vm.insert_value((vm.get_fp() + 0)?, segment)?; + Ok(()) +} + pub const SEGMENTS_ADD_EVM_MEMORIZER_SEGMENT_INDEX: &str = "memory[ap] = to_felt_or_relocatable(ids.evm_memorizer.address_.segment_index)"; pub fn segments_add_evm_memorizer_segment_index( diff --git a/crates/hints/src/vars.rs b/crates/hints/src/vars.rs index 190e849a..cc5dd1ca 100644 --- a/crates/hints/src/vars.rs +++ b/crates/hints/src/vars.rs @@ -16,46 +16,49 @@ pub mod scopes { } pub mod ids { - pub const ADDRESS: &str = "ids.address"; + pub const PEAKS: &str = "peaks"; + pub const RLP_LEN: &str = "rlp_len"; + pub const ADDRESS: &str = "address"; pub const ALL_ENCODINGS: &str = "all_encodings"; pub const BATCH_LEN: &str = "batch_len"; pub const BUILTIN_PARAMS: &str = "builtin_params"; pub const BUILTIN_PTRS: &str = "builtin_ptrs"; pub const CHAIN_ID: &str = "chain_id"; pub const COMPILED_CLASS: &str = "compiled_class"; - pub const CURRENT_ITEM: &str = "ids.current_item"; - pub const DEVISOR: &str = "ids.devisor"; - pub const FIRST_BYTE: &str = "ids.first_byte"; - pub const I: &str = "ids.i"; - pub const IDX: &str = "ids.idx"; - pub const IS_LEFT_SMALLER: &str = "ids.is_left_smaller"; - pub const IS_LONG: &str = "ids.is_long"; - pub const ITEM_TYPE: &str = "ids.item_type"; - pub const KEY_LOW: &str = "ids.key_low"; - pub const KEY_LEADING_ZEROS: &str = "ids.key_leading_zeros"; - pub const KEY_HIGH: &str = "ids.key_high"; - pub const LEFT: &str = "ids.left"; - pub const MMR_PATH: &str = "ids.mmr_path"; - pub const MPT_PROOF: &str = "ids.mpt_proof"; - pub const PROOF_BYTES_LEN: &str = "ids.proof_bytes_len"; + pub const CURRENT_ITEM: &str = "current_item"; + pub const DEVISOR: &str = "devisor"; + pub const FIRST_BYTE: &str = "first_byte"; + pub const I: &str = "i"; + pub const IDX: &str = "idx"; + pub const MMR_META: &str = "mmr_meta"; + pub const IS_LEFT_SMALLER: &str = "is_left_smaller"; + pub const IS_LONG: &str = "is_long"; + pub const ITEM_TYPE: &str = "item_type"; + pub const KEY_LOW: &str = "key_low"; + pub const KEY_LEADING_ZEROS: &str = "key_leading_zeros"; + pub const KEY_HIGH: &str = "key_high"; + pub const LEFT: &str = "left"; + pub const MMR_PATH: &str = "mmr_path"; + pub const MPT_PROOF: &str = "mpt_proof"; + pub const PROOF_BYTES_LEN: &str = "proof_bytes_len"; pub const N_BUILTINS: &str = "n_builtins"; - pub const N_PROCESSED_WORDS: &str = "ids.n_processed_words"; + pub const N_PROCESSED_WORDS: &str = "n_processed_words"; pub const N_SELECTED_BUILTINS: &str = "n_selected_builtins"; pub const PARAMS_LEN: &str = "params_len"; pub const PARAMS: &str = "params"; pub const PROGRAM_HASH: &str = "program_hash"; - pub const Q: &str = "ids.q"; - pub const R: &str = "ids.r"; + pub const Q: &str = "q"; + pub const R: &str = "r"; pub const RESULT: &str = "result"; pub const RETURN_BUILTIN_PTRS: &str = "return_builtin_ptrs"; - pub const RIGHT: &str = "ids.right"; - pub const RLP: &str = "ids.rlp"; + pub const RIGHT: &str = "right"; + pub const RLP: &str = "rlp"; pub const SELECT_BUILTIN: &str = "select_builtin"; pub const SELECTED_ENCODINGS: &str = "selected_encodings"; pub const SELECTED_PTRS: &str = "selected_ptrs"; - pub const SLOT: &str = "ids.slot"; + pub const SLOT: &str = "slot"; pub const SYSCALL_PTR: &str = "syscall_ptr"; - pub const TASK_HASH: &str = "ids.task_hash"; - pub const VALUE_LEN: &str = "ids.value_len"; - pub const VALUE: &str = "ids.value"; + pub const TASK_HASH: &str = "task_hash"; + pub const VALUE_LEN: &str = "value_len"; + pub const VALUE: &str = "value"; } diff --git a/crates/hints/src/verifiers/evm/account_verifier.rs b/crates/hints/src/verifiers/evm/account_verifier.rs index cad56407..9ae5519d 100644 --- a/crates/hints/src/verifiers/evm/account_verifier.rs +++ b/crates/hints/src/verifiers/evm/account_verifier.rs @@ -43,7 +43,11 @@ pub fn hint_get_account_address( .try_into() .unwrap(); let account = batch.accounts[idx].clone(); - let address_le_chunks: Vec = account.address.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + let address_le_chunks: Vec = account + .address + .chunks(8) + .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) + .collect(); exec_scopes.insert_value::(vars::scopes::ACCOUNT, account); @@ -191,10 +195,14 @@ pub fn hint_get_mpt_proof( ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec> = proof + let proof_le_chunks: Vec> = proof .proof .into_iter() - .map(|p| p.chunks(8).map(Felt252::from_bytes_le_slice).collect()) + .map(|p| { + p.chunks(8) + .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) + .collect() + }) .collect(); vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; diff --git a/crates/hints/src/verifiers/evm/header_verifier.rs b/crates/hints/src/verifiers/evm/header_verifier.rs index 3bdb9e92..6afd813f 100644 --- a/crates/hints/src/verifiers/evm/header_verifier.rs +++ b/crates/hints/src/verifiers/evm/header_verifier.rs @@ -5,14 +5,14 @@ use cairo_vm::{ dict_manager::DictManager, hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_into_ap}, }, - types::exec_scope::ExecutionScopes, + types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; -use std::{any::Any, collections::HashMap}; +use std::{any::Any, cell::RefCell, collections::HashMap, rc::Rc}; use types::proofs::{header::Header, HeaderMmrMeta, Proofs}; -pub const HINT_VM_ENTER_SCOPE: &str = "vm_enter_scope({'header_with_mmr': batch.header_with_mmr[ids.idx], '__dict_manager': __dict_manager})"; +pub const HINT_VM_ENTER_SCOPE: &str = "vm_enter_scope({'header_with_mmr': batch.headers_with_mmr[ids.idx - 1], '__dict_manager': __dict_manager})"; pub fn hint_vm_enter_scope( vm: &mut VirtualMachine, @@ -25,8 +25,8 @@ pub fn hint_vm_enter_scope( .try_into() .unwrap(); - let headers_with_mmr: Box = Box::new(proofs.headers_with_mmr[idx].clone()); - let dict_manager: Box = Box::new(exec_scopes.get::(vars::scopes::DICT_MANAGER)?); + let headers_with_mmr: Box = Box::new(proofs.headers_with_mmr[idx - 1].clone()); + let dict_manager: Box = Box::new(exec_scopes.get::>>(vars::scopes::DICT_MANAGER)?); exec_scopes.enter_scope(HashMap::from([ (String::from(vars::scopes::HEADER_WITH_MMR), headers_with_mmr), (String::from(vars::scopes::DICT_MANAGER), dict_manager), @@ -35,7 +35,7 @@ pub fn hint_vm_enter_scope( Ok(()) } -pub const HINT_HEADERS_WITH_MMR_HEADERS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(headers_with_mmr.headers))"; +pub const HINT_HEADERS_WITH_MMR_HEADERS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(header_with_mmr.headers))"; pub fn hint_headers_with_mmr_headers_len( vm: &mut VirtualMachine, @@ -60,14 +60,19 @@ pub fn hint_set_header( let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? .try_into() .unwrap(); + let header = headers_with_mmr.headers[idx - 1].clone(); - let rlp_le_chunks: Vec = header.rlp.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + let rlp_le_chunks: Vec = header + .rlp + .chunks(8) + .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) + .collect(); exec_scopes.insert_value::
(vars::scopes::HEADER, header); let rlp_ptr = get_ptr_from_var_name(vars::ids::RLP, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.write_arg(rlp_ptr, &rlp_le_chunks)?; + vm.load_data(rlp_ptr, &rlp_le_chunks)?; Ok(()) } @@ -82,7 +87,7 @@ pub fn hint_rlp_len( ) -> Result<(), HintError> { let header = exec_scopes.get::
(vars::scopes::HEADER)?; - insert_value_into_ap(vm, Felt252::from(header.rlp.len())) + insert_value_into_ap(vm, Felt252::from(header.rlp.chunks(8).count())) } pub const HINT_LEAF_IDX: &str = "memory[ap] = to_felt_or_relocatable(len(header.proof.leaf_idx))"; @@ -121,9 +126,15 @@ pub fn hint_mmr_path( ) -> Result<(), HintError> { let header = exec_scopes.get::
(vars::scopes::HEADER)?; let mmr_path_ptr = get_ptr_from_var_name(vars::ids::MMR_PATH, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let mmr_path: Vec = header.proof.mmr_path.into_iter().map(|f| Felt252::from_bytes_be_slice(&f.0)).collect(); - - vm.write_arg(mmr_path_ptr, &mmr_path)?; + let mmr_path: Vec = header + .proof + .mmr_path + .into_iter() + .map(|f| Felt252::from_bytes_be_slice(&f)) + .map(MaybeRelocatable::from) + .collect(); + + vm.load_data(mmr_path_ptr, &mmr_path)?; Ok(()) } diff --git a/crates/hints/src/verifiers/evm/receipt_verifier.rs b/crates/hints/src/verifiers/evm/receipt_verifier.rs index 8438d022..4f12852d 100644 --- a/crates/hints/src/verifiers/evm/receipt_verifier.rs +++ b/crates/hints/src/verifiers/evm/receipt_verifier.rs @@ -150,11 +150,15 @@ pub fn hint_receipt_mpt_proof( ) -> Result<(), HintError> { let receipt = exec_scopes.get::(vars::scopes::RECEIPT)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec> = receipt + let proof_le_chunks: Vec> = receipt .proof .proof .into_iter() - .map(|p| p.chunks(8).map(Felt252::from_bytes_le_slice).collect()) + .map(|p| { + p.chunks(8) + .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) + .collect() + }) .collect(); vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; diff --git a/crates/hints/src/verifiers/evm/storage_item_verifier.rs b/crates/hints/src/verifiers/evm/storage_item_verifier.rs index 2baa452f..8c2756b2 100644 --- a/crates/hints/src/verifiers/evm/storage_item_verifier.rs +++ b/crates/hints/src/verifiers/evm/storage_item_verifier.rs @@ -58,7 +58,11 @@ pub fn hint_set_storage_slot( _constants: &HashMap, ) -> Result<(), HintError> { let storage = exec_scopes.get::(vars::scopes::STORAGE)?; - let slot_le_chunks: Vec = storage.slot.chunks(8).map(Felt252::from_bytes_le_slice).collect(); + let slot_le_chunks: Vec = storage + .slot + .chunks(8) + .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) + .collect(); let slot_ptr = get_ptr_from_var_name(vars::ids::SLOT, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; @@ -204,10 +208,14 @@ pub fn hint_set_mpt_proof( ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec> = proof + let proof_le_chunks: Vec> = proof .proof .into_iter() - .map(|p| p.chunks(8).map(Felt252::from_bytes_le_slice).collect()) + .map(|p| { + p.chunks(8) + .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) + .collect() + }) .collect(); vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; diff --git a/crates/hints/src/verifiers/evm/transaction_verifier.rs b/crates/hints/src/verifiers/evm/transaction_verifier.rs index c1ba2902..280a7230 100644 --- a/crates/hints/src/verifiers/evm/transaction_verifier.rs +++ b/crates/hints/src/verifiers/evm/transaction_verifier.rs @@ -7,7 +7,7 @@ use cairo_vm::{ builtin_hint_processor_definition::HintProcessorData, hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, }, - types::exec_scope::ExecutionScopes, + types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; @@ -150,11 +150,15 @@ pub fn hint_mpt_proof( ) -> Result<(), HintError> { let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec> = transaction + let proof_le_chunks: Vec> = transaction .proof .proof .into_iter() - .map(|p| p.chunks(8).map(Felt252::from_bytes_le_slice).collect()) + .map(|p| { + p.chunks(8) + .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) + .collect() + }) .collect(); vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; diff --git a/crates/hints/src/verifiers/mmr_verifier.rs b/crates/hints/src/verifiers/mmr_verifier.rs new file mode 100644 index 00000000..811769df --- /dev/null +++ b/crates/hints/src/verifiers/mmr_verifier.rs @@ -0,0 +1,87 @@ +use crate::vars; +use cairo_vm::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData; +use cairo_vm::hint_processor::builtin_hint_processor::hint_utils::{get_ptr_from_var_name, insert_value_into_ap}; +use cairo_vm::types::relocatable::MaybeRelocatable; +use cairo_vm::{ + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use std::collections::HashMap; +use types::proofs::HeaderMmrMeta; + +pub const HINT_HEADERS_WITH_MMR_META_PEAKS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(header_with_mmr.mmr_meta.peaks))"; + +pub fn hint_headers_with_mmr_meta_peaks_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let header_with_mmr = exec_scopes.get::(vars::scopes::HEADER_WITH_MMR)?; + + insert_value_into_ap(vm, Felt252::from(header_with_mmr.mmr_meta.peaks.len())) +} + +pub const HINT_HEADERS_WITH_MMR_META_ID: &str = "memory[ap] = to_felt_or_relocatable(header_with_mmr.mmr_meta.id)"; + +pub fn hint_headers_with_mmr_meta_id( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let header_with_mmr = exec_scopes.get::(vars::scopes::HEADER_WITH_MMR)?; + + insert_value_into_ap(vm, Felt252::from(header_with_mmr.mmr_meta.id)) +} + +pub const HINT_HEADERS_WITH_MMR_META_ROOT: &str = "memory[ap] = to_felt_or_relocatable(header_with_mmr.mmr_meta.root)"; + +pub fn hint_headers_with_mmr_meta_root( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let header_with_mmr = exec_scopes.get::(vars::scopes::HEADER_WITH_MMR)?; + + insert_value_into_ap(vm, Felt252::from_bytes_be_slice(&header_with_mmr.mmr_meta.root)) +} + +pub const HINT_HEADERS_WITH_MMR_META_SIZE: &str = "memory[ap] = to_felt_or_relocatable(header_with_mmr.mmr_meta.size)"; + +pub fn hint_headers_with_mmr_meta_size( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let header_with_mmr = exec_scopes.get::(vars::scopes::HEADER_WITH_MMR)?; + + insert_value_into_ap(vm, Felt252::from(header_with_mmr.mmr_meta.size)) +} + +pub const HINT_HEADERS_WITH_MMR_PEAKS: &str = "segments.write_arg(ids.peaks, header_with_mmr.mmr_meta.peaks)"; + +pub fn hint_headers_with_mmr_peaks( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let header_with_mmr = exec_scopes.get::(vars::scopes::HEADER_WITH_MMR)?; + let peaks_ptr = get_ptr_from_var_name(vars::ids::PEAKS, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + + vm.load_data( + peaks_ptr, + &header_with_mmr + .mmr_meta + .peaks + .into_iter() + .map(|f| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&f))) + .collect::>(), + )?; + + Ok(()) +} diff --git a/crates/hints/src/verifiers/mod.rs b/crates/hints/src/verifiers/mod.rs index 29ec1cdd..202a49f2 100644 --- a/crates/hints/src/verifiers/mod.rs +++ b/crates/hints/src/verifiers/mod.rs @@ -1,3 +1,4 @@ pub mod evm; +pub mod mmr_verifier; pub mod utils; pub mod verify; diff --git a/crates/hints/src/verifiers/verify.rs b/crates/hints/src/verifiers/verify.rs index ac4f6a5c..68392f82 100644 --- a/crates/hints/src/verifiers/verify.rs +++ b/crates/hints/src/verifiers/verify.rs @@ -1,6 +1,6 @@ use crate::vars; +use cairo_vm::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData; use cairo_vm::hint_processor::builtin_hint_processor::hint_utils::insert_value_into_ap; -use cairo_vm::hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, dict_manager::DictManager}; use cairo_vm::{ types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, @@ -17,10 +17,8 @@ pub fn hint_vm_enter_scope( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let proofs = exec_scopes.get::(vars::scopes::PROOFS)?; - - let batch: Box = Box::new(proofs); - let dict_manager: Box = Box::new(exec_scopes.get::(vars::scopes::DICT_MANAGER)?); + let batch: Box = Box::new(exec_scopes.get::(vars::scopes::PROOFS)?); + let dict_manager: Box = Box::new(exec_scopes.get_dict_manager()?); exec_scopes.enter_scope(HashMap::from([ (String::from(vars::scopes::BATCH), batch), (String::from(vars::scopes::DICT_MANAGER), dict_manager), @@ -37,7 +35,7 @@ pub fn hint_headers_with_mmr_headers_len( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let proofs = exec_scopes.get::(vars::scopes::PROOF)?; + let proofs = exec_scopes.get::(vars::scopes::BATCH)?; insert_value_into_ap(vm, Felt252::from(proofs.headers_with_mmr.len())) } diff --git a/crates/sound_hint_processor/src/input.rs b/crates/sound_hint_processor/src/input.rs index eea30381..a806386e 100644 --- a/crates/sound_hint_processor/src/input.rs +++ b/crates/sound_hint_processor/src/input.rs @@ -8,7 +8,7 @@ use cairo_vm::{ }; use hints::vars; use std::collections::HashMap; -use types::{param::Param, proofs::Proofs, HDPInput}; +use types::{param::Param, proofs::Proofs}; pub const HINT_INPUT: &str = "from tools.py.schema import HDPInput\nrun_input = HDPInput.Schema().load(program_input)\nproofs = run_input.proofs\nparams = run_input.params\ncompiled_class = run_input.compiled_class"; @@ -20,10 +20,9 @@ impl CustomHintProcessor { _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let hdp_input: HDPInput = serde_json::from_value(self.private_inputs.clone()).map_err(|_| HintError::WrongHintData)?; - exec_scopes.insert_value::>(vars::scopes::PROOFS, hdp_input.proofs); - exec_scopes.insert_value::>(vars::scopes::PARAMS, hdp_input.params); - exec_scopes.insert_value::(vars::scopes::COMPILED_CLASS, hdp_input.compiled_class); + exec_scopes.insert_value::(vars::scopes::PROOFS, self.private_inputs.proofs.to_owned()); + exec_scopes.insert_value::>(vars::scopes::PARAMS, self.private_inputs.params.to_owned()); + exec_scopes.insert_value::(vars::scopes::COMPILED_CLASS, self.private_inputs.compiled_class.to_owned()); Ok(()) } } diff --git a/crates/sound_hint_processor/src/lib.rs b/crates/sound_hint_processor/src/lib.rs index 5e9cf57e..35bb5dfc 100644 --- a/crates/sound_hint_processor/src/lib.rs +++ b/crates/sound_hint_processor/src/lib.rs @@ -22,23 +22,18 @@ use hints::{extensive_hints, hints, vars, ExtensiveHintImpl, HintImpl}; use starknet_types_core::felt::Felt; use std::{any::Any, collections::HashMap}; use syscall_handler::evm::SyscallHandlerWrapper; +use types::HDPInput; pub struct CustomHintProcessor { - private_inputs: serde_json::Value, + private_inputs: HDPInput, builtin_hint_proc: BuiltinHintProcessor, cairo1_builtin_hint_proc: Cairo1HintProcessor, hints: HashMap, extensive_hints: HashMap, } -impl Default for CustomHintProcessor { - fn default() -> Self { - Self::new(serde_json::Value::default()) - } -} - impl CustomHintProcessor { - pub fn new(private_inputs: serde_json::Value) -> Self { + pub fn new(private_inputs: HDPInput) -> Self { Self { private_inputs, builtin_hint_proc: BuiltinHintProcessor::new_empty(), @@ -149,6 +144,3 @@ fn get_ptr_from_res_operand(vm: &mut VirtualMachine, res: &ResOperand) -> Result let cell_reloc = (base + (i32::from(cell.offset)))?; (vm.get_relocatable(cell_reloc)? + &base_offset).map_err(|e| e.into()) } - -#[cfg(test)] -pub mod tests; diff --git a/crates/sound_hint_processor/src/tests/mod.rs b/crates/sound_hint_processor/src/tests/mod.rs deleted file mode 100644 index 023df9af..00000000 --- a/crates/sound_hint_processor/src/tests/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -use crate::CustomHintProcessor; -use cairo_vm::{ - cairo_run, - vm::{errors::cairo_run_errors::CairoRunError, runners::cairo_runner::CairoRunner}, -}; - -pub fn run_cairo_program(program_content: &[u8]) -> Result { - let cairo_run_config = cairo_run::CairoRunConfig { - layout: cairo_vm::types::layout_name::LayoutName::all_cairo, - allow_missing_builtins: Some(true), - ..Default::default() - }; - - cairo_run::cairo_run(program_content, &cairo_run_config, &mut CustomHintProcessor::default()) -} diff --git a/crates/sound_run/Cargo.toml b/crates/sound_run/Cargo.toml index 7eee92a7..27f0ba93 100644 --- a/crates/sound_run/Cargo.toml +++ b/crates/sound_run/Cargo.toml @@ -10,4 +10,5 @@ clap.workspace = true thiserror.workspace = true serde_json.workspace = true +types.workspace = true hints.workspace = true \ No newline at end of file diff --git a/crates/sound_run/src/main.rs b/crates/sound_run/src/main.rs index 8e0e36d4..599361de 100644 --- a/crates/sound_run/src/main.rs +++ b/crates/sound_run/src/main.rs @@ -6,12 +6,9 @@ use cairo_vm::{ vm::{errors::vm_exception::VmException, runners::cairo_runner::CairoRunner}, }; use clap::{Parser, ValueHint}; -use hints::vars; -use sound_hint_processor::{ - syscall_handler::evm::{SyscallHandler, SyscallHandlerWrapper}, - CustomHintProcessor, -}; +use sound_hint_processor::CustomHintProcessor; use std::path::PathBuf; +use types::{proofs::Proofs, HDPDryRunInput, HDPInput}; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] @@ -25,6 +22,8 @@ struct Args { proof_mode: bool, #[structopt(long = "program_input")] program_input: PathBuf, + #[structopt(long = "program_proofs")] + program_proofs: PathBuf, #[structopt(long = "program_output")] program_output: PathBuf, } @@ -41,7 +40,8 @@ fn main() -> Result<(), HdpOsError> { }; let program_file = std::fs::read(args.filename).map_err(HdpOsError::IO)?; - let program_inputs = std::fs::read(args.program_input).map_err(HdpOsError::IO)?; + let program_inputs: HDPDryRunInput = serde_json::from_slice(&std::fs::read(args.program_input).map_err(HdpOsError::IO)?)?; + let program_proofs: Proofs = serde_json::from_slice(&std::fs::read(args.program_proofs).map_err(HdpOsError::IO)?)?; // Load the Program let program = Program::from_bytes(&program_file, Some(cairo_run_config.entrypoint)).map_err(|e| HdpOsError::Runner(e.into()))?; @@ -62,27 +62,16 @@ fn main() -> Result<(), HdpOsError> { .map_err(|e| HdpOsError::Runner(e.into()))?; // Run the Cairo VM - let mut hint_processor = CustomHintProcessor::new(serde_json::from_slice(&program_inputs)?); + let mut hint_processor = CustomHintProcessor::new(HDPInput { + proofs: program_proofs, + params: program_inputs.params, + compiled_class: program_inputs.compiled_class, + }); cairo_runner .run_until_pc(end, &mut hint_processor) .map_err(|err| VmException::from_vm_error(&cairo_runner, err)) .map_err(|e| HdpOsError::Runner(e.into()))?; - std::fs::write( - args.program_output, - serde_json::to_vec::( - &cairo_runner - .exec_scopes - .get::(vars::scopes::SYSCALL_HANDLER) - .unwrap() - .syscall_handler - .try_read() - .unwrap(), - ) - .map_err(|e| HdpOsError::IO(e.into()))?, - ) - .map_err(HdpOsError::IO)?; - Ok(()) } diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 43a13215..d25d9c5e 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -18,7 +18,7 @@ pub struct HDPDryRunInput { #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct HDPInput { - pub proofs: Vec, + pub proofs: Proofs, pub params: Vec, pub compiled_class: CasmContractClass, } diff --git a/packages/eth_essentials b/packages/eth_essentials index 8fccbac6..6b2d5b0e 160000 --- a/packages/eth_essentials +++ b/packages/eth_essentials @@ -1 +1 @@ -Subproject commit 8fccbac6e0fa67ee6e1453134fdbb370950b0cc1 +Subproject commit 6b2d5b0e379005393784f1ce1113b14076046c9d diff --git a/src/hdp.cairo b/src/hdp.cairo index 96ba97b9..a0cfe719 100644 --- a/src/hdp.cairo +++ b/src/hdp.cairo @@ -102,34 +102,36 @@ func run{ let starknet_key_hasher_ptr = StarknetStateAccess.init(); let starknet_decoder_ptr = StarknetDecoder.init(); - let (program_hash, result) = compute_tasks{ - pedersen_ptr=pedersen_ptr, - range_check_ptr=range_check_ptr, - ecdsa_ptr=ecdsa_ptr, - bitwise_ptr=bitwise_ptr, - ec_op_ptr=ec_op_ptr, - keccak_ptr=keccak_ptr, - poseidon_ptr=poseidon_ptr, - pow2_array=pow2_array, - evm_memorizer=evm_memorizer, - evm_decoder_ptr=evm_decoder_ptr, - evm_key_hasher_ptr=evm_key_hasher_ptr, - starknet_memorizer=starknet_memorizer, - starknet_decoder_ptr=starknet_decoder_ptr, - starknet_key_hasher_ptr=starknet_key_hasher_ptr, - }(); - - // Post Verification Checks: Ensure dict consistency - default_dict_finalize(evm_memorizer_start, evm_memorizer, BareMemorizer.DEFAULT_VALUE); - default_dict_finalize( - starknet_memorizer_start, starknet_memorizer, BareMemorizer.DEFAULT_VALUE - ); - - write_output_ptr{output_ptr=output_ptr}( - mmr_metas=mmr_metas, mmr_metas_len=mmr_metas_len, program_hash=program_hash, result=result - ); - return (); + + // let (program_hash, result) = compute_tasks{ + // pedersen_ptr=pedersen_ptr, + // range_check_ptr=range_check_ptr, + // ecdsa_ptr=ecdsa_ptr, + // bitwise_ptr=bitwise_ptr, + // ec_op_ptr=ec_op_ptr, + // keccak_ptr=keccak_ptr, + // poseidon_ptr=poseidon_ptr, + // pow2_array=pow2_array, + // evm_memorizer=evm_memorizer, + // evm_decoder_ptr=evm_decoder_ptr, + // evm_key_hasher_ptr=evm_key_hasher_ptr, + // starknet_memorizer=starknet_memorizer, + // starknet_decoder_ptr=starknet_decoder_ptr, + // starknet_key_hasher_ptr=starknet_key_hasher_ptr, + // }(); + + // // Post Verification Checks: Ensure dict consistency + // default_dict_finalize(evm_memorizer_start, evm_memorizer, BareMemorizer.DEFAULT_VALUE); + // default_dict_finalize( + // starknet_memorizer_start, starknet_memorizer, BareMemorizer.DEFAULT_VALUE + // ); + + // write_output_ptr{output_ptr=output_ptr}( + // mmr_metas=mmr_metas, mmr_metas_len=mmr_metas_len, program_hash=program_hash, result=result + // ); + + // return (); } func compute_tasks{ diff --git a/src/hdp_input.json b/src/hdp_input.json deleted file mode 100644 index decfc267..00000000 --- a/src/hdp_input.json +++ /dev/null @@ -1,1080 +0,0 @@ -{ - "cairo_run_output_path": "cairo_run_output.json", - "task_root": "0xfc6af4432778751f9845728c9b9558d6c9b5badb455744b7c2a8c6a532c790c9", - "result_root": "0x86874987c512d8ca5007eb5590cb9da9c4e8962ffc50b9846618e9c526ffb830", - "proofs": [ - { - "chain_id": "0x000000000000534e5f5345504f4c4941", - "mmr_with_headers": [ - { - "mmr_meta": { - "id": 1, - "root": "0x3101d95c9dd1c45f3b50ce7355970113515bf65f45051695b96fe95e1100214", - "size": 1552535, - "peaks": [ - "0x6be91daacfef363375a01c5c5f318bbd4fb206a7da7aeeb410edeae91d3b1f4", - "0x6dc63def1c8f2330ec73ff7420794a39fa522d9802da5616ad54f5a0ab38ec5", - "0x42d3fa075877cc90abdfab3a417e5f5faa8fd377d4d769b346f9d5157818f67", - "0x6a529c60b841c3f64664f3b49001822df82bdce897d573cb2124ad7e9658281", - "0x1739d0b65e6e25fce2d32344778fe45733556fd3ec30030ba7b89ee14c1dd78", - "0x3c6de3b1b4fc0666cbe814c0376a5d43c22da924b96efcc073aa7fa47b126a7", - "0x00b8f52f8d274393b4da40bbcd4b1de5e08f68abb2e3e1a07bfff4ce1de872d", - "0x7e701495df90cfedc1ca280fbc6c5d8fbecdae328f6064158dff3b400956fec", - "0x1bc831e2e38d059a82ae2d1539ecc15f6270bcd13444b52145e3e274bdf6e9b" - ] - }, - "headers": [ - { - "fields": [ - "0x535441524b4e45545f424c4f434b5f4841534830", - "0x25fa3", - "0x476ce5db235461146bb61052164599953416ee9311f9a8f7efbc5984b3bceed", - "0x1176a1bd84444c89232ec27754698e5d2e7e1a7f1539f12027f28b23ec9f3d8", - "0x66d5fa27", - "0x1000000000000000300000000000000070000000000000000", - "0x587b45eeb1d8cc406e459d1afe936f1cc665f1d1196eb21646e803625901165", - "0x3c30a70617e6e1898700578cafbb8f6becfdf150fbcc7fde29a47fe8ddd44c0", - "0xc8f7f61795903b143358edec3e729725248621bf3ea386bc3c40935713cad6", - "0x2d053d1642d4646010044b9e0a8acb45bb33a8a565fa0da00cc6b30258d7d18", - "0x19f12cf7a", - "0x2ad7545dc686", - "0x3a051df217", - "0x5fd0a4b054b66", - "0x302e31332e32", - "0x0", - "0xbf02179065d10f6270cbf46de361d937f3d4535bd991670324e8a3094d94c3" - ], - "proof": { - "leaf_idx": 1414704, - "mmr_path": [ - "0x194f8cb66aced72cab474b2df3f9ddb58eac3544a60ccb1b03045ce457acb25", - "0x5dcf953e6c22d59ceaed0b1512e0f20c636b50cddebba24c8b4c0c14509a8bb", - "0x335ba994fddc83d34cbe1e33a8c318baa6b2f17fc80962e6c2201e3f65d760f", - "0x4aa327b80714722d6a8f7175f30fb390071955a18edaf9b1a4fbfa8ef23d425", - "0x39a69e3c8bd4101e6f04536ad29b6b8e0bb394920d3b310752938095dbdb9fc", - "0x526b883363cf998618b425ef9483724f3ef7c440d0bc6734d12349df80cccac", - "0x1ee0776e9bd848668fb3c22490aecd46f08f633055c049a20a2665f511f31dc", - "0x6e19587861ba3cec2c482eebb51840de46709e56a651960306be9553069a73a", - "0x66fe4f497cee76d4f93f2afe1e8a2506b84c689cade2c2e1674fb8ef8209c18", - "0x003b3ae3b62ffd708a6380bdbcf35b28dace4853cfaefec2ace368f85063f0e", - "0x5f3f4c85ac9d87774a6630db77dd6650c8e852611f490ccb93a61d4477fb533", - "0x57fda60c04c2b36e9887c947ab9e67e4b842e98df749742ac42e2ff20a698c4", - "0x0521b17643841eb4c0039abea631cdb60370827b16025aa2f62607350691091", - "0x648ecea005b75877c1d80a0a1ab82c9299809b7b1b3bc1a91f4a4977704a0a7", - "0x711451b1dd9a6652d86687f9364be3f124dd8deb6325fe46f15df7b35a2944e", - "0x5d8055602e5b5f8ec27d985a2791e0667bb4b3a04c48097bd01ee6ea43adc18" - ] - } - } - ] - } - ], - "storages": [] - } - ], - "tasks": [ - { - "type": "module", - "context": { - "encoded_task": [ - "0x599113521b579406", - "0xd298ed9c1ffab554", - "0x237f1fb7d3ec6c94", - "0xa68354b43adea258", - "0x0", - "0x0", - "0x0", - "0x4000000000000000", - "0x0", - "0x0", - "0x0", - "0x100000000000000", - "0x0", - "0x0", - "0x0", - "0xa35f020000000000" - ], - "task_bytes_len": 128, - "inputs": [ - { - "visibility": "public", - "value": "0x25fa3" - } - ], - "module_class": { - "prime": "0x800000000000011000000000000000000000000000000000000000000000001", - "compiler_version": "2.6.3", - "bytecode": [ - "0xa0680017fff8000", - "0x7", - "0x482680017ffa8000", - "0x100000000000000000000000000000000", - "0x400280007ff97fff", - "0x10780017fff7fff", - "0xb4", - "0x4825800180007ffa", - "0x0", - "0x400280007ff97fff", - "0x480a7ffc7fff8000", - "0x480a7ffd7fff8000", - "0x1104800180018000", - "0xbc", - "0x482680017ff98000", - "0x1", - "0x20680017fff7ffa", - "0x9b", - "0x48307ff880007ff9", - "0x20680017fff7fff", - "0x4", - "0x10780017fff7fff", - "0xa", - "0x482480017ff78000", - "0x1", - "0x48127ff77fff8000", - "0x480680017fff8000", - "0x0", - "0x48127ff47fff8000", - "0x10780017fff7fff", - "0x8", - "0x48127ff77fff8000", - "0x48127ff77fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x20680017fff7ffe", - "0x75", - "0x480080007fff8000", - "0xa0680017fff8000", - "0x12", - "0x4824800180007ffe", - "0x100000000", - "0x4844800180008002", - "0x8000000000000110000000000000000", - "0x4830800080017ffe", - "0x480080007ff57fff", - "0x482480017ffe8000", - "0xefffffffffffffde00000000ffffffff", - "0x480080017ff37fff", - "0x400080027ff27ffb", - "0x402480017fff7ffb", - "0xffffffffffffffffffffffffffffffff", - "0x20680017fff7fff", - "0x60", - "0x402780017fff7fff", - "0x1", - "0x400080007ff87ffe", - "0x482480017ffe8000", - "0xffffffffffffffffffffffff00000000", - "0x400080017ff77fff", - "0x482480017ff78000", - "0x2", - "0x48307ff880007ff9", - "0x20680017fff7fff", - "0x4", - "0x10780017fff7fff", - "0x10", - "0x40780017fff7fff", - "0x1", - "0x480680017fff8000", - "0x496e70757420746f6f206c6f6e6720666f7220617267756d656e7473", - "0x400080007ffe7fff", - "0x48127ffc7fff8000", - "0x48127fc87fff8000", - "0x480a7ffb7fff8000", - "0x480680017fff8000", - "0x1", - "0x48127ffa7fff8000", - "0x482480017ff98000", - "0x1", - "0x208b7fff7fff7ffe", - "0x1104800180018000", - "0x1a0", - "0x482480017fff8000", - "0x19f", - "0x480080007fff8000", - "0xa0680017fff8000", - "0x9", - "0x4824800180007fc6", - "0x3c64", - "0x482480017fff8000", - "0x100000000000000000000000000000000", - "0x400080007ff77fff", - "0x10780017fff7fff", - "0x28", - "0x4824800180007fc6", - "0x3c64", - "0x400080007ff87fff", - "0x482480017ff88000", - "0x1", - "0x48127ffe7fff8000", - "0x480a7ffb7fff8000", - "0x48127fea7fff8000", - "0x48127fea7fff8000", - "0x480680017fff8000", - "0xb", - "0x480680017fff8000", - "0x534e5f5345504f4c4941", - "0x48127fee7fff8000", - "0x1104800180018000", - "0x10e", - "0x20680017fff7ffd", - "0xe", - "0x40780017fff7fff", - "0x1", - "0x400080007fff7ffe", - "0x48127ff97fff8000", - "0x48127ff97fff8000", - "0x48127ff97fff8000", - "0x480680017fff8000", - "0x0", - "0x48127ffb7fff8000", - "0x482480017ffa8000", - "0x1", - "0x208b7fff7fff7ffe", - "0x48127ffa7fff8000", - "0x48127ffa7fff8000", - "0x48127ffa7fff8000", - "0x480680017fff8000", - "0x1", - "0x48127ffa7fff8000", - "0x48127ffa7fff8000", - "0x208b7fff7fff7ffe", - "0x40780017fff7fff", - "0x1", - "0x480680017fff8000", - "0x4f7574206f6620676173", - "0x400080007ffe7fff", - "0x482480017ff58000", - "0x1", - "0x48127fc17fff8000", - "0x480a7ffb7fff8000", - "0x480680017fff8000", - "0x1", - "0x48127ffa7fff8000", - "0x482480017ff98000", - "0x1", - "0x208b7fff7fff7ffe", - "0x482480017ff28000", - "0x3", - "0x10780017fff7fff", - "0x5", - "0x40780017fff7fff", - "0x8", - "0x48127ff27fff8000", - "0x40780017fff7fff", - "0x1", - "0x480680017fff8000", - "0x4661696c656420746f20646573657269616c697a6520706172616d202332", - "0x400080007ffe7fff", - "0x48127ffd7fff8000", - "0x48127fc47fff8000", - "0x480a7ffb7fff8000", - "0x480680017fff8000", - "0x1", - "0x48127ffa7fff8000", - "0x482480017ff98000", - "0x1", - "0x208b7fff7fff7ffe", - "0x40780017fff7fff", - "0x1", - "0x480680017fff8000", - "0x4661696c656420746f20646573657269616c697a6520706172616d202331", - "0x400080007ffe7fff", - "0x48127ffd7fff8000", - "0x48127fd27fff8000", - "0x480a7ffb7fff8000", - "0x480680017fff8000", - "0x1", - "0x48127ffa7fff8000", - "0x482480017ff98000", - "0x1", - "0x208b7fff7fff7ffe", - "0x40780017fff7fff", - "0x1", - "0x480680017fff8000", - "0x4f7574206f6620676173", - "0x400080007ffe7fff", - "0x482680017ff98000", - "0x1", - "0x480a7ffa7fff8000", - "0x480a7ffb7fff8000", - "0x480680017fff8000", - "0x1", - "0x48127ffa7fff8000", - "0x482480017ff98000", - "0x1", - "0x208b7fff7fff7ffe", - "0x48297ffc80007ffd", - "0x20680017fff7fff", - "0x4", - "0x10780017fff7fff", - "0xa", - "0x482680017ffc8000", - "0x1", - "0x480a7ffd7fff8000", - "0x480680017fff8000", - "0x0", - "0x480280007ffc8000", - "0x10780017fff7fff", - "0x8", - "0x480a7ffc7fff8000", - "0x480a7ffd7fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x20680017fff7ffe", - "0x29", - "0x48307ffc80007ffd", - "0x20680017fff7fff", - "0x4", - "0x10780017fff7fff", - "0xa", - "0x482480017ffb8000", - "0x1", - "0x48127ffb7fff8000", - "0x480680017fff8000", - "0x0", - "0x480080007ff88000", - "0x10780017fff7fff", - "0x8", - "0x48127ffb7fff8000", - "0x48127ffb7fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x20680017fff7ffe", - "0xa", - "0x48127ffc7fff8000", - "0x48127ffc7fff8000", - "0x480680017fff8000", - "0x0", - "0x48127ff77fff8000", - "0x48127ffb7fff8000", - "0x10780017fff7fff", - "0x16", - "0x48127ffc7fff8000", - "0x48127ffc7fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x10780017fff7fff", - "0xc", - "0x40780017fff7fff", - "0x5", - "0x48127ff77fff8000", - "0x48127ff77fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x20680017fff7ffd", - "0x60", - "0x48307ffb80007ffc", - "0x20680017fff7fff", - "0x4", - "0x10780017fff7fff", - "0xa", - "0x482480017ffa8000", - "0x1", - "0x48127ffa7fff8000", - "0x480680017fff8000", - "0x0", - "0x480080007ff78000", - "0x10780017fff7fff", - "0x8", - "0x48127ffa7fff8000", - "0x48127ffa7fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x20680017fff7ffe", - "0x29", - "0x48307ffc80007ffd", - "0x20680017fff7fff", - "0x4", - "0x10780017fff7fff", - "0xa", - "0x482480017ffb8000", - "0x1", - "0x48127ffb7fff8000", - "0x480680017fff8000", - "0x0", - "0x480080007ff88000", - "0x10780017fff7fff", - "0x8", - "0x48127ffb7fff8000", - "0x48127ffb7fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x20680017fff7ffe", - "0xa", - "0x48127ffc7fff8000", - "0x48127ffc7fff8000", - "0x480680017fff8000", - "0x0", - "0x48127ff77fff8000", - "0x48127ffb7fff8000", - "0x10780017fff7fff", - "0x16", - "0x48127ffc7fff8000", - "0x48127ffc7fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x10780017fff7fff", - "0xc", - "0x40780017fff7fff", - "0x5", - "0x48127ff77fff8000", - "0x48127ff77fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x20680017fff7ffd", - "0xb", - "0x48127ffb7fff8000", - "0x48127ffb7fff8000", - "0x480680017fff8000", - "0x0", - "0x48127fec7fff8000", - "0x48127fec7fff8000", - "0x48127ff97fff8000", - "0x48127ff97fff8000", - "0x208b7fff7fff7ffe", - "0x48127ffb7fff8000", - "0x48127ffb7fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x208b7fff7fff7ffe", - "0x40780017fff7fff", - "0xf", - "0x48127fec7fff8000", - "0x48127fec7fff8000", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x208b7fff7fff7ffe", - "0x480680017fff8000", - "0x0", - "0xa0680017fff8004", - "0xe", - "0x4824800180047ffe", - "0x800000000000000000000000000000000000000000000000000000000000000", - "0x484480017ffe8000", - "0x110000000000000000", - "0x48307ffe7fff8002", - "0x480280007ff67ffc", - "0x480280017ff67ffc", - "0x402480017ffb7ffd", - "0xffffffffffffffeeffffffffffffffff", - "0x400280027ff67ffd", - "0x10780017fff7fff", - "0x57", - "0x484480017fff8001", - "0x8000000000000000000000000000000", - "0x48307fff80007ffd", - "0x480280007ff67ffd", - "0x480280017ff67ffd", - "0x402480017ffc7ffe", - "0xf8000000000000000000000000000000", - "0x400280027ff67ffe", - "0x40780017fff7fff", - "0x1", - "0x400180007fff7ff9", - "0x400180017fff7ffa", - "0x400180027fff7ffc", - "0x400180037fff7ffd", - "0x48127fff7fff8000", - "0x482480017ffe8000", - "0x4", - "0x482680017ff68000", - "0x3", - "0x480680017fff8000", - "0x43616c6c436f6e7472616374", - "0x400280007ff87fff", - "0x400380017ff87ff7", - "0x400280027ff87ff5", - "0x400380037ff87ffb", - "0x400280047ff87ffc", - "0x400280057ff87ffd", - "0x480280077ff88000", - "0x20680017fff7fff", - "0x2e", - "0x480280087ff88000", - "0x480280097ff88000", - "0x480680017fff8000", - "0x0", - "0x480280067ff88000", - "0x482680017ff88000", - "0xa", - "0x48307ffb80007ffc", - "0xa0680017fff8000", - "0x6", - "0x48307ffe80007ffb", - "0x400080007ff57fff", - "0x10780017fff7fff", - "0x11", - "0x482480017ffb8000", - "0x1", - "0x48307fff80007ffd", - "0x400080007ff47fff", - "0x48307ff97ff78000", - "0x482480017ff38000", - "0x1", - "0x48127ff87fff8000", - "0x48127ff87fff8000", - "0x480680017fff8000", - "0x0", - "0x480680017fff8000", - "0x0", - "0x480080007ffa8000", - "0x208b7fff7fff7ffe", - "0x40780017fff7fff", - "0x1", - "0x480680017fff8000", - "0x496e646578206f7574206f6620626f756e6473", - "0x400080007ffe7fff", - "0x482480017ff38000", - "0x1", - "0x48127ff87fff8000", - "0x48127ff87fff8000", - "0x480680017fff8000", - "0x1", - "0x48127ffa7fff8000", - "0x482480017ff98000", - "0x1", - "0x208b7fff7fff7ffe", - "0x40780017fff7fff", - "0xa", - "0x48127ff37fff8000", - "0x480280067ff88000", - "0x482680017ff88000", - "0xa", - "0x480680017fff8000", - "0x1", - "0x480280087ff88000", - "0x480280097ff88000", - "0x208b7fff7fff7ffe", - "0x40780017fff7fff", - "0xd", - "0x40780017fff7fff", - "0x1", - "0x480680017fff8000", - "0x4f7074696f6e3a3a756e77726170206661696c65642e", - "0x400080007ffe7fff", - "0x482680017ff68000", - "0x3", - "0x480a7ff77fff8000", - "0x480a7ff87fff8000", - "0x480680017fff8000", - "0x1", - "0x48127ffa7fff8000", - "0x482480017ff98000", - "0x1", - "0x208b7fff7fff7ffe" - ], - "bytecode_segment_lengths": [ - 200, - 181, - 118 - ], - "hints": [ - [ - 0, - [ - { - "TestLessThanOrEqual": { - "lhs": { - "Immediate": "0x0" - }, - "rhs": { - "Deref": { - "register": "FP", - "offset": -6 - } - }, - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 40, - [ - { - "TestLessThan": { - "lhs": { - "BinOp": { - "op": "Add", - "a": { - "register": "AP", - "offset": -1 - }, - "b": { - "Immediate": "0x0" - } - } - }, - "rhs": { - "Immediate": "0x100000000" - }, - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 44, - [ - { - "LinearSplit": { - "value": { - "Deref": { - "register": "AP", - "offset": -1 - } - }, - "scalar": { - "Immediate": "0x8000000000000110000000000000000" - }, - "max_x": { - "Immediate": "0xfffffffffffffffffffffffffffffffe" - }, - "x": { - "register": "AP", - "offset": 0 - }, - "y": { - "register": "AP", - "offset": 1 - } - } - } - ] - ], - [ - 69, - [ - { - "AllocSegment": { - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 88, - [ - { - "TestLessThanOrEqual": { - "lhs": { - "Immediate": "0x3c64" - }, - "rhs": { - "Deref": { - "register": "AP", - "offset": -57 - } - }, - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 115, - [ - { - "AllocSegment": { - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 135, - [ - { - "AllocSegment": { - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 157, - [ - { - "AllocSegment": { - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 171, - [ - { - "AllocSegment": { - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 185, - [ - { - "AllocSegment": { - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 383, - [ - { - "TestLessThan": { - "lhs": { - "Deref": { - "register": "AP", - "offset": -1 - } - }, - "rhs": { - "Immediate": "0x800000000000000000000000000000000000000000000000000000000000000" - }, - "dst": { - "register": "AP", - "offset": 4 - } - } - } - ] - ], - [ - 387, - [ - { - "LinearSplit": { - "value": { - "Deref": { - "register": "AP", - "offset": 3 - } - }, - "scalar": { - "Immediate": "0x110000000000000000" - }, - "max_x": { - "Immediate": "0xffffffffffffffffffffffffffffffff" - }, - "x": { - "register": "AP", - "offset": -2 - }, - "y": { - "register": "AP", - "offset": -1 - } - } - } - ] - ], - [ - 397, - [ - { - "LinearSplit": { - "value": { - "Deref": { - "register": "AP", - "offset": -2 - } - }, - "scalar": { - "Immediate": "0x8000000000000000000000000000000" - }, - "max_x": { - "Immediate": "0xffffffffffffffffffffffffffffffff" - }, - "x": { - "register": "AP", - "offset": -1 - }, - "y": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 405, - [ - { - "AllocSegment": { - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 424, - [ - { - "SystemCall": { - "system": { - "Deref": { - "register": "FP", - "offset": -8 - } - } - } - } - ] - ], - [ - 435, - [ - { - "TestLessThan": { - "lhs": { - "Deref": { - "register": "AP", - "offset": -4 - } - }, - "rhs": { - "Deref": { - "register": "AP", - "offset": -1 - } - }, - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 456, - [ - { - "AllocSegment": { - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ], - [ - 484, - [ - { - "AllocSegment": { - "dst": { - "register": "AP", - "offset": 0 - } - } - } - ] - ] - ], - "pythonic_hints": [ - [ - 0, - [ - "memory[ap + 0] = 0 <= memory[fp + -6]" - ] - ], - [ - 40, - [ - "memory[ap + 0] = (memory[ap + -1] + 0) % PRIME < 4294967296" - ] - ], - [ - 44, - [ - "\n(value, scalar) = (memory[ap + -1], 10633823966279327296825105735305134080)\nx = min(value // scalar, 340282366920938463463374607431768211454)\ny = value - x * scalar\nmemory[ap + 0] = x\nmemory[ap + 1] = y\n" - ] - ], - [ - 69, - [ - "memory[ap + 0] = segments.add()" - ] - ], - [ - 88, - [ - "memory[ap + 0] = 15460 <= memory[ap + -57]" - ] - ], - [ - 115, - [ - "memory[ap + 0] = segments.add()" - ] - ], - [ - 135, - [ - "memory[ap + 0] = segments.add()" - ] - ], - [ - 157, - [ - "memory[ap + 0] = segments.add()" - ] - ], - [ - 171, - [ - "memory[ap + 0] = segments.add()" - ] - ], - [ - 185, - [ - "memory[ap + 0] = segments.add()" - ] - ], - [ - 383, - [ - "memory[ap + 4] = memory[ap + -1] < 3618502788666131106986593281521497120414687020801267626233049500247285301248" - ] - ], - [ - 387, - [ - "\n(value, scalar) = (memory[ap + 3], 313594649253062377472)\nx = min(value // scalar, 340282366920938463463374607431768211455)\ny = value - x * scalar\nmemory[ap + -2] = x\nmemory[ap + -1] = y\n" - ] - ], - [ - 397, - [ - "\n(value, scalar) = (memory[ap + -2], 10633823966279326983230456482242756608)\nx = min(value // scalar, 340282366920938463463374607431768211455)\ny = value - x * scalar\nmemory[ap + -1] = x\nmemory[ap + 0] = y\n" - ] - ], - [ - 405, - [ - "memory[ap + 0] = segments.add()" - ] - ], - [ - 424, - [ - "syscall_handler.syscall(syscall_ptr=memory[fp + -8])" - ] - ], - [ - 435, - [ - "memory[ap + 0] = memory[ap + -4] < memory[ap + -1]" - ] - ], - [ - 456, - [ - "memory[ap + 0] = segments.add()" - ] - ], - [ - 484, - [ - "memory[ap + 0] = segments.add()" - ] - ] - ], - "entry_points_by_type": { - "EXTERNAL": [ - { - "selector": "0xe2054f8a912367e38a22ce773328ff8aabf8082c4120bad9ef085e1dbf29a7", - "offset": 0, - "builtins": [ - "range_check" - ] - } - ], - "L1_HANDLER": [], - "CONSTRUCTOR": [] - } - } - } - } - ] -} \ No newline at end of file diff --git a/src/utils/rlp.cairo b/src/utils/rlp.cairo index ad024ad3..885130ec 100644 --- a/src/utils/rlp.cairo +++ b/src/utils/rlp.cairo @@ -375,18 +375,17 @@ func le_chunks_to_uint256{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, pow2_ar elements: felt*, elements_len: felt, bytes_len: felt ) -> Uint256 { alloc_locals; - local value: Uint256; if (elements_len == 1) { let high = elements[0] * pow2_array[(16 - bytes_len) * 8]; - assert value = Uint256(low=0, high=high); + return(Uint256(low=0, high=high)); } if (elements_len == 2) { - assert value = Uint256( + return(Uint256( low=0, high=(elements[1] * pow2_array[64] + elements[0]) * pow2_array[(16 - bytes_len) * 8], - ); + )); } // For values larger then 16 bytes, we need to shift the chunks to the left. @@ -394,19 +393,21 @@ func le_chunks_to_uint256{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, pow2_ar let (le_shifted) = right_shift_le_chunks(elements, elements_len, offset); if (elements_len == 3) { - assert value = Uint256( + return(Uint256( low=le_shifted[0] * pow2_array[64], high=le_shifted[2] * pow2_array[64] + le_shifted[1] - ); + )); } if (elements_len == 4) { - assert value = Uint256( + return(Uint256( low=le_shifted[1] * pow2_array[64] + le_shifted[0], high=le_shifted[3] * pow2_array[64] + le_shifted[2], - ); + )); } - return (value); + assert 0 = 1; + + return (Uint256(low=0, high=0)); } // This function is required when constructing a LE uint256 from LE chunks. diff --git a/src/verifiers/evm/account_verifier.cairo b/src/verifiers/evm/account_verifier.cairo index 480f7f57..7a50cd47 100644 --- a/src/verifiers/evm/account_verifier.cairo +++ b/src/verifiers/evm/account_verifier.cairo @@ -22,7 +22,7 @@ func verify_accounts{ }() { alloc_locals; - local n_accounts: felt = nondet %{ len(batch.accounts) %}; + tempvar n_accounts: felt = nondet %{ len(batch.accounts) %}; verify_accounts_inner(n_accounts, 0); return (); @@ -64,7 +64,7 @@ func verify_accounts_inner{ let (felt_address) = le_address_chunks_to_felt(address); - local n_proofs: felt = nondet %{ len(account.proofs) %}; + tempvar n_proofs: felt = nondet %{ len(account.proofs) %}; verify_account( address=felt_address, key=key, key_leading_zeros=key_leading_zeros, n_proofs=n_proofs, idx=0 ); @@ -87,8 +87,8 @@ func verify_account{ } %{ proof = account.proofs[ids.idx] %} - local proof_len: felt = nondet %{ len(proof.proof) %}; - local block_number: felt = nondet %{ proof.block_number %}; + tempvar proof_len: felt = nondet %{ len(proof.proof) %}; + tempvar block_number: felt = nondet %{ proof.block_number %}; let (proof_bytes_len: felt*) = alloc(); %{ segments.write_arg(ids.proof_bytes_len, proof.proof_bytes_len) %} diff --git a/src/verifiers/evm/block_tx_verifier.cairo b/src/verifiers/evm/block_tx_verifier.cairo index 1f5a55b1..00d7dbdf 100644 --- a/src/verifiers/evm/block_tx_verifier.cairo +++ b/src/verifiers/evm/block_tx_verifier.cairo @@ -29,7 +29,7 @@ func verify_block_tx_proofs{ }() { alloc_locals; - local n_tx_proofs: felt = nondet %{ len(batch.transactions) %}; + tempvar n_tx_proofs: felt = nondet %{ len(batch.transactions) %}; verify_block_tx_proofs_inner(n_tx_proofs, 0); return (); @@ -61,8 +61,8 @@ func verify_block_tx_proofs_inner{ local key_leading_zeros: felt; %{ ids.key_leading_zeros = len(transaction.key.lstrip("0x")) - len(transaction.key.lstrip("0x").lstrip("0")) %} - local proof_len: felt = nondet %{ len(transaction.proof) %}; - local block_number: felt = nondet %{ transaction.block_number %}; + tempvar proof_len: felt = nondet %{ len(transaction.proof) %}; + tempvar block_number: felt = nondet %{ transaction.block_number %}; let (proof_bytes_len: felt*) = alloc(); %{ segments.write_arg(ids.proof_bytes_len, transaction.proof_bytes_len) %} diff --git a/src/verifiers/evm/header_verifier.cairo b/src/verifiers/evm/header_verifier.cairo index 9655c7cc..9f1a5162 100644 --- a/src/verifiers/evm/header_verifier.cairo +++ b/src/verifiers/evm/header_verifier.cairo @@ -26,21 +26,21 @@ func verify_mmr_batches{ return (mmr_meta_idx=mmr_meta_idx); } - %{ vm_enter_scope({'header_with_mmr': batch.header_with_mmr[ids.idx], '__dict_manager': __dict_manager}) %} + %{ vm_enter_scope({'header_with_mmr': batch.headers_with_mmr[ids.idx - 1], '__dict_manager': __dict_manager}) %} let (mmr_meta, peaks_dict, peaks_dict_start) = validate_mmr_meta(); assert mmr_metas[mmr_meta_idx] = mmr_meta; - local n_header_proofs: felt = nondet %{ len(header_with_mmr.headers) %}; + tempvar n_header_proofs: felt = nondet %{ len(header_with_mmr.headers) %}; with mmr_meta, peaks_dict { verify_headers_with_mmr_peaks(n_header_proofs); } - %{ vm_exit_scope() %} - // Ensure the peaks dict for this batch is finalized default_dict_finalize(peaks_dict_start, peaks_dict, -1); + %{ vm_exit_scope() %} + return verify_mmr_batches(idx=idx - 1, mmr_meta_idx=mmr_meta_idx + 1); } @@ -71,8 +71,8 @@ func verify_headers_with_mmr_peaks{ segments.write_arg(ids.rlp, [int(x, 16) for x in header.rlp]) %} - local rlp_len: felt = nondet %{ len(header.rlp) %}; - local leaf_idx: felt = nondet %{ len(header.proof.leaf_idx) %}; + tempvar rlp_len: felt = nondet %{ len(header.rlp) %}; + tempvar leaf_idx: felt = nondet %{ len(header.proof.leaf_idx) %}; // compute the hash of the header let (poseidon_hash) = poseidon_hash_many(n=rlp_len, elements=rlp); @@ -92,7 +92,7 @@ func verify_headers_with_mmr_peaks{ } let (mmr_path) = alloc(); - local mmr_path_len: felt = nondet %{ len(header.proof.mmr_path) %}; + tempvar mmr_path_len: felt = nondet %{ len(header.proof.mmr_path) %}; %{ segments.write_arg(ids.mmr_path, [int(x, 16) for x in header.proof.mmr_path]) %} // compute the peak of the header diff --git a/src/verifiers/evm/receipt_verifier.cairo b/src/verifiers/evm/receipt_verifier.cairo index 3120d39b..4b133936 100644 --- a/src/verifiers/evm/receipt_verifier.cairo +++ b/src/verifiers/evm/receipt_verifier.cairo @@ -28,7 +28,7 @@ func verify_block_receipt_proofs{ }() { alloc_locals; - local n_receipts: felt = nondet %{ len(batch.receipts) %}; + tempvar n_receipts: felt = nondet %{ len(batch.receipts) %}; verify_block_receipt_proofs_inner(n_receipts, 0); return (); @@ -60,8 +60,8 @@ func verify_block_receipt_proofs_inner{ local key_leading_zeros: felt; %{ ids.key_leading_zeros = len(receipt.key.lstrip("0x")) - len(receipt.key.lstrip("0x").lstrip("0")) %} - local proof_len: felt = nondet %{ len(receipt.proof) %}; - local block_number: felt = nondet %{ receipt.block_number %}; + tempvar proof_len: felt = nondet %{ len(receipt.proof) %}; + tempvar block_number: felt = nondet %{ receipt.block_number %}; let (proof_bytes_len: felt*) = alloc(); %{ segments.write_arg(ids.proof_bytes_len, receipt.proof_bytes_len) %} diff --git a/src/verifiers/evm/storage_item_verifier.cairo b/src/verifiers/evm/storage_item_verifier.cairo index 49a5eff6..ddb2d0e8 100644 --- a/src/verifiers/evm/storage_item_verifier.cairo +++ b/src/verifiers/evm/storage_item_verifier.cairo @@ -28,7 +28,7 @@ func verify_storage_items{ }() { alloc_locals; - local n_storage_items: felt = nondet %{ len(batch.storages) %}; + tempvar n_storage_items: felt = nondet %{ len(batch.storages) %}; verify_storage_items_inner(n_storage_items, 0); return (); @@ -78,7 +78,7 @@ func verify_storage_items_inner{ let (felt_address) = le_address_chunks_to_felt(address); - local n_proofs: felt = nondet %{ len(storage.proofs) %}; + tempvar n_proofs: felt = nondet %{ len(storage.proofs) %}; verify_storage_item( address=felt_address, slot=slot_be, @@ -107,8 +107,8 @@ func verify_storage_item{ } %{ proof = storage.proofs[ids.idx] %} - local proof_len: felt = nondet %{ len(proof.proof) %}; - local block_number: felt = nondet %{ proof.block_number %}; + tempvar proof_len: felt = nondet %{ len(proof.proof) %}; + tempvar block_number: felt = nondet %{ proof.block_number %}; let (proof_bytes_len: felt*) = alloc(); %{ segments.write_arg(ids.proof_bytes_len, proof.proof_bytes_len) %} diff --git a/src/verifiers/evm/verify.cairo b/src/verifiers/evm/verify.cairo index a0205776..c3eedb24 100644 --- a/src/verifiers/evm/verify.cairo +++ b/src/verifiers/evm/verify.cairo @@ -22,20 +22,20 @@ func run_state_verification{ let (chain_info) = fetch_chain_info(11155111); with chain_info { // Step 1: Verify MMR and headers inclusion - local n_proofs: felt = nondet %{ len(batch.header_with_mmr) %}; + tempvar n_proofs: felt = nondet %{ len(batch.headers_with_mmr) %}; let (mmr_meta_idx) = verify_mmr_batches(n_proofs, mmr_meta_idx); // Step 2: Verify the accounts - verify_accounts(); + // verify_accounts(); // Step 3: Verify the storage items - verify_storage_items(); + // verify_storage_items(); // Step 4: Verify the block tx proofs - verify_block_tx_proofs(); + // verify_block_tx_proofs(); // Step 5: Verify the block receipt proofs - verify_block_receipt_proofs(); + // verify_block_receipt_proofs(); } return (mmr_meta_idx=mmr_meta_idx); diff --git a/src/verifiers/mmr_verifier.cairo b/src/verifiers/mmr_verifier.cairo index df4b151b..70082338 100644 --- a/src/verifiers/mmr_verifier.cairo +++ b/src/verifiers/mmr_verifier.cairo @@ -24,17 +24,16 @@ func validate_mmr_meta{range_check_ptr, poseidon_ptr: PoseidonBuiltin*, pow2_arr let (local dict: DictAccess*) = default_dict_new(default_value=-1); tempvar dict_start = dict; - local mmr_meta: MMRMeta; + local mmr_meta: MMRMeta = MMRMeta( + id=nondet %{ header_with_mmr.mmr_meta.id %}, + root=nondet %{ header_with_mmr.mmr_meta.root %}, + size=nondet %{ header_with_mmr.mmr_meta.size %}, + ); + + tempvar peaks_len: felt = nondet %{ len(header_with_mmr.mmr_meta.peaks) %}; + let (peaks: felt*) = alloc(); - local peaks_len: felt; - - %{ - memory[ids.mmr_meta._reference_value + 0] = header_with_mmr.mmr_meta.id - memory[ids.mmr_meta._reference_value + 1] = header_with_mmr.mmr_meta.root - memory[ids.mmr_meta._reference_value + 2] = header_with_mmr.mmr_meta.size - ids.peaks_len = len(header_with_mmr.mmr_meta.peaks) - segments.write_arg(ids.peaks, header_with_mmr.mmr_meta.peaks) - %} + %{ segments.write_arg(ids.peaks, header_with_mmr.mmr_meta.peaks) %} assert_mmr_size_is_valid(mmr_meta.size); diff --git a/src/verifiers/starknet/header_verifier.cairo b/src/verifiers/starknet/header_verifier.cairo index fb09152c..650199c9 100644 --- a/src/verifiers/starknet/header_verifier.cairo +++ b/src/verifiers/starknet/header_verifier.cairo @@ -24,7 +24,7 @@ func verify_mmr_batches{ let (mmr_meta, peaks_dict, peaks_dict_start) = validate_mmr_meta(); assert mmr_metas[mmr_meta_idx] = mmr_meta; - local n_header_proofs: felt = nondet %{ len(batch.header_with_mmr.headers) %}; + tempvar n_header_proofs: felt = nondet %{ len(header_with_mmr.headers) %}; with mmr_meta, peaks_dict { verify_headers_with_mmr_peaks(n_header_proofs); } @@ -57,12 +57,12 @@ func verify_headers_with_mmr_peaks{ let (fields) = alloc(); %{ - header = batch.header_with_mmr.headers[ids.idx - 1] + header = header_with_mmr.headers[ids.idx - 1] segments.write_arg(ids.fields, [int(x, 16) for x in header.fields]) %} - local fields_len: felt = nondet %{ len(header.fields) %}; - local leaf_idx: felt = nondet %{ len(header.proof.leaf_idx) %}; + tempvar fields_len: felt = nondet %{ len(header.fields) %}; + tempvar leaf_idx: felt = nondet %{ len(header.proof.leaf_idx) %}; // compute the hash of the header let (header_hash) = poseidon_hash_many(n=fields_len, elements=fields); @@ -82,7 +82,7 @@ func verify_headers_with_mmr_peaks{ } let (mmr_path) = alloc(); - local mmr_path_len: felt = nondet %{ len(header.proof.mmr_path) %}; + tempvar mmr_path_len: felt = nondet %{ len(header.proof.mmr_path) %}; %{ segments.write_arg(ids.mmr_path, [int(x, 16) for x in header.proof.mmr_path]) %} // compute the peak of the header diff --git a/src/verifiers/starknet/storage_verifier.cairo b/src/verifiers/starknet/storage_verifier.cairo index 06b31bd4..7f208ddf 100644 --- a/src/verifiers/starknet/storage_verifier.cairo +++ b/src/verifiers/starknet/storage_verifier.cairo @@ -29,7 +29,7 @@ func verify_proofs{ }() { alloc_locals; - local n_storage_items: felt = nondet %{ len(batch.storages) %}; + tempvar n_storage_items: felt = nondet %{ len(batch.storages) %}; verify_proofs_loop(n_storage_items, 0); return (); diff --git a/src/verifiers/verify.cairo b/src/verifiers/verify.cairo index ce73dd72..e4f8cc8a 100644 --- a/src/verifiers/verify.cairo +++ b/src/verifiers/verify.cairo @@ -26,6 +26,7 @@ func run_state_verification{ }() -> (mmr_metas_len: felt) { alloc_locals; + // batch abstraction will be usefull with multiple chains %{ vm_enter_scope({'batch': proofs, '__dict_manager': __dict_manager}) %} let (mmr_meta_idx) = evm_run_state_verification(0); diff --git a/tools/make/setup.sh b/tools/make/setup.sh index 75c0a098..ac7b864a 100755 --- a/tools/make/setup.sh +++ b/tools/make/setup.sh @@ -1,7 +1,7 @@ #!/bin/bash VENV_PATH=${1:-venv} -PYTHON_VERSION=${2:-3.10} +PYTHON_VERSION=${2:-3.9} echo "Setting up virtual environment at $VENV_PATH with Python $PYTHON_VERSION" From 0ac0c2d4eaeb2d0519556de65335464ce7a2889f Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 20 Dec 2024 15:09:50 +0100 Subject: [PATCH 49/75] tmp --- crates/hints/src/lib.rs | 2 ++ crates/hints/src/print.rs | 34 ++++++++++++++++++- crates/hints/src/rlp/divmod.rs | 2 ++ crates/hints/src/vars.rs | 3 +- .../src/verifiers/evm/account_verifier.rs | 26 ++++++-------- .../src/verifiers/evm/receipt_verifier.rs | 29 +++++++--------- .../verifiers/evm/storage_item_verifier.rs | 26 ++++++-------- .../src/verifiers/evm/transaction_verifier.rs | 25 ++++++-------- packages/eth_essentials | 2 +- src/utils/rlp.cairo | 2 ++ src/verifiers/evm/account_verifier.cairo | 30 ++++++++-------- src/verifiers/evm/verify.cairo | 2 +- 12 files changed, 99 insertions(+), 84 deletions(-) diff --git a/crates/hints/src/lib.rs b/crates/hints/src/lib.rs index 346fd66e..7f259730 100644 --- a/crates/hints/src/lib.rs +++ b/crates/hints/src/lib.rs @@ -45,6 +45,8 @@ pub fn hints() -> HashMap { hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS.into(), rlp::processed_words::hint_processed_words); hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS_RLP.into(), rlp::processed_words::hint_processed_words_rlp); hints.insert(print::PROGRAM_HASH.into(), print::program_hash); + hints.insert(print::PRINT1.into(), print::print1); + hints.insert(print::PRINT2.into(), print::print2); hints.insert(segments::SEGMENTS_ADD.into(), segments::segments_add); hints.insert(segments::SEGMENTS_ADD_FP.into(), segments::segments_add_fp); hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_SEGMENT_INDEX.into(), segments::segments_add_evm_memorizer_segment_index); diff --git a/crates/hints/src/print.rs b/crates/hints/src/print.rs index 4899fa60..28704522 100644 --- a/crates/hints/src/print.rs +++ b/crates/hints/src/print.rs @@ -1,6 +1,6 @@ use crate::vars; use cairo_vm::{ - hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_integer_from_var_name}, + hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::{get_integer_from_var_name, get_ptr_from_var_name}}, types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, @@ -21,3 +21,35 @@ pub fn program_hash( Ok(()) } + +pub const PRINT2: &str = "print2"; + +pub fn print2( + vm: &mut VirtualMachine, + _exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + println!("i: {}", get_integer_from_var_name("i", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); + println!("q: {}", get_integer_from_var_name("q", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); + println!("r: {}", get_integer_from_var_name("r", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); + println!("devisor: {}", get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); + + Ok(()) +} + +pub const PRINT1: &str = "print1"; + +pub fn print1( + vm: &mut VirtualMachine, + _exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + println!("i: {}", get_integer_from_var_name("i", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); + println!("devisor: {}", get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); + let ptr = get_ptr_from_var_name("value", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + println!("value[0] {}", vm.get_integer((ptr + 0)?)?); + + Ok(()) +} diff --git a/crates/hints/src/rlp/divmod.rs b/crates/hints/src/rlp/divmod.rs index 7c473f9a..d55cd00d 100644 --- a/crates/hints/src/rlp/divmod.rs +++ b/crates/hints/src/rlp/divmod.rs @@ -51,6 +51,8 @@ pub fn hint_divmod_value( .try_into() .unwrap(); + println!("{}", vm.get_integer((value + i)?)?); + let devisor = get_integer_from_var_name(vars::ids::DEVISOR, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; let (q, r) = vm.get_integer((value + i)?)?.div_rem(&NonZeroFelt::try_from(devisor).unwrap()); diff --git a/crates/hints/src/vars.rs b/crates/hints/src/vars.rs index cc5dd1ca..75e01e33 100644 --- a/crates/hints/src/vars.rs +++ b/crates/hints/src/vars.rs @@ -34,9 +34,8 @@ pub mod ids { pub const IS_LEFT_SMALLER: &str = "is_left_smaller"; pub const IS_LONG: &str = "is_long"; pub const ITEM_TYPE: &str = "item_type"; - pub const KEY_LOW: &str = "key_low"; + pub const KEY: &str = "key"; pub const KEY_LEADING_ZEROS: &str = "key_leading_zeros"; - pub const KEY_HIGH: &str = "key_high"; pub const LEFT: &str = "left"; pub const MMR_PATH: &str = "mmr_path"; pub const MPT_PROOF: &str = "mpt_proof"; diff --git a/crates/hints/src/verifiers/evm/account_verifier.rs b/crates/hints/src/verifiers/evm/account_verifier.rs index 9ae5519d..fe156db0 100644 --- a/crates/hints/src/verifiers/evm/account_verifier.rs +++ b/crates/hints/src/verifiers/evm/account_verifier.rs @@ -5,14 +5,13 @@ use crate::{ use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, - hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, + hint_utils::{get_address_from_var_name, get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, }, types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; use num_bigint::BigUint; -use num_traits::Num; use std::collections::HashMap; use types::proofs::{account::Account, mpt::MPTProof, Proofs}; @@ -67,22 +66,17 @@ pub fn hint_account_key( _constants: &HashMap, ) -> Result<(), HintError> { let account = exec_scopes.get::(vars::scopes::ACCOUNT)?; - let account_key = BigUint::from_str_radix(&account.account_key.to_string(), 16).unwrap(); - let (key_low, key_high) = split_128(&account_key); - insert_value_from_var_name( - vars::ids::KEY_LOW, - MaybeRelocatable::Int(Felt252::from(key_low)), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, + let (key_low, key_high) = split_128(&BigUint::from_bytes_be(account.account_key.as_slice())); + + let key_ptr = get_address_from_var_name(vars::ids::KEY, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.insert_value( + (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, + Felt252::try_from(key_low).map_err(|_| HintError::WrongHintData)?, )?; - insert_value_from_var_name( - vars::ids::KEY_HIGH, - MaybeRelocatable::Int(Felt252::from(key_high)), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, + vm.insert_value( + (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, + Felt252::try_from(key_high).map_err(|_| HintError::WrongHintData)?, )?; Ok(()) diff --git a/crates/hints/src/verifiers/evm/receipt_verifier.rs b/crates/hints/src/verifiers/evm/receipt_verifier.rs index 4f12852d..36514f7f 100644 --- a/crates/hints/src/verifiers/evm/receipt_verifier.rs +++ b/crates/hints/src/verifiers/evm/receipt_verifier.rs @@ -1,13 +1,14 @@ -use crate::{utils::count_leading_zero_nibbles_from_hex, vars}; +use crate::{utils::{count_leading_zero_nibbles_from_hex, split_128}, vars}; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, - hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, + hint_utils::{get_address_from_var_name, get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, }, types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; +use num_bigint::BigUint; use std::collections::HashMap; use types::proofs::{receipt::Receipt, Proofs}; @@ -52,23 +53,17 @@ pub fn hint_receipt_key( _constants: &HashMap, ) -> Result<(), HintError> { let receipt = exec_scopes.get::(vars::scopes::RECEIPT)?; - let key_as_limbs = receipt.key.as_limbs(); - let key_low = key_as_limbs[0] as u128 | ((key_as_limbs[1] as u128) << 64); - let key_high = key_as_limbs[2] as u128 | ((key_as_limbs[3] as u128) << 64); - insert_value_from_var_name( - vars::ids::KEY_LOW, - Felt252::from(key_low), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, + let (key_low, key_high) = split_128(&BigUint::from_bytes_be(&receipt.key.to_be_bytes_vec())); + + let key_ptr = get_address_from_var_name(vars::ids::KEY, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.insert_value( + (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, + Felt252::try_from(key_low).map_err(|_| HintError::WrongHintData)?, )?; - insert_value_from_var_name( - vars::ids::KEY_HIGH, - Felt252::from(key_high), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, + vm.insert_value( + (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, + Felt252::try_from(key_high).map_err(|_| HintError::WrongHintData)?, )?; Ok(()) diff --git a/crates/hints/src/verifiers/evm/storage_item_verifier.rs b/crates/hints/src/verifiers/evm/storage_item_verifier.rs index 8c2756b2..68a288c6 100644 --- a/crates/hints/src/verifiers/evm/storage_item_verifier.rs +++ b/crates/hints/src/verifiers/evm/storage_item_verifier.rs @@ -5,14 +5,13 @@ use crate::{ use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, - hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, + hint_utils::{get_address_from_var_name, get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, }, types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; use num_bigint::BigUint; -use num_traits::Num; use std::collections::HashMap; use types::proofs::{mpt::MPTProof, storage::Storage, Proofs}; @@ -80,22 +79,17 @@ pub fn hint_set_storage_key( _constants: &HashMap, ) -> Result<(), HintError> { let storage = exec_scopes.get::(vars::scopes::STORAGE)?; - let key = BigUint::from_str_radix(&storage.storage_key.to_string(), 16).unwrap(); - let (key_low, key_high) = split_128(&key); - insert_value_from_var_name( - vars::ids::KEY_LOW, - MaybeRelocatable::Int(Felt252::from(key_low)), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, + let (key_low, key_high) = split_128(&BigUint::from_bytes_be(storage.storage_key.as_slice())); + + let key_ptr = get_address_from_var_name(vars::ids::KEY, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.insert_value( + (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, + Felt252::try_from(key_low).map_err(|_| HintError::WrongHintData)?, )?; - insert_value_from_var_name( - vars::ids::KEY_HIGH, - MaybeRelocatable::Int(Felt252::from(key_high)), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, + vm.insert_value( + (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, + Felt252::try_from(key_high).map_err(|_| HintError::WrongHintData)?, )?; Ok(()) diff --git a/crates/hints/src/verifiers/evm/transaction_verifier.rs b/crates/hints/src/verifiers/evm/transaction_verifier.rs index 280a7230..f8cd44aa 100644 --- a/crates/hints/src/verifiers/evm/transaction_verifier.rs +++ b/crates/hints/src/verifiers/evm/transaction_verifier.rs @@ -5,7 +5,7 @@ use crate::{ use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, - hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, + hint_utils::{get_address_from_var_name, get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, }, types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, @@ -56,22 +56,17 @@ pub fn hint_set_tx_key( _constants: &HashMap, ) -> Result<(), HintError> { let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; - let key = BigUint::from_bytes_be(&transaction.key.to_be_bytes::<32>()); + + let (key_low, key_high) = split_128(&BigUint::from_bytes_be(&transaction.key.to_be_bytes_vec())); - let (key_low, key_high) = split_128(&key); - insert_value_from_var_name( - vars::ids::KEY_LOW, - Felt252::from(key_low), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, + let key_ptr = get_address_from_var_name(vars::ids::KEY, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + vm.insert_value( + (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, + Felt252::try_from(key_low).map_err(|_| HintError::WrongHintData)?, )?; - insert_value_from_var_name( - vars::ids::KEY_HIGH, - Felt252::from(key_high), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, + vm.insert_value( + (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, + Felt252::try_from(key_high).map_err(|_| HintError::WrongHintData)?, )?; Ok(()) diff --git a/packages/eth_essentials b/packages/eth_essentials index 6b2d5b0e..925de5ba 160000 --- a/packages/eth_essentials +++ b/packages/eth_essentials @@ -1 +1 @@ -Subproject commit 6b2d5b0e379005393784f1ce1113b14076046c9d +Subproject commit 925de5ba553ca35e45df402350787a26a30e129b diff --git a/src/utils/rlp.cairo b/src/utils/rlp.cairo index 885130ec..8802ba77 100644 --- a/src/utils/rlp.cairo +++ b/src/utils/rlp.cairo @@ -451,6 +451,7 @@ func right_shift_le_chunks{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, pow2_a jmp end_loop if [ap] != 0, ap++; // Inlined felt_divmod (unsigned_div_rem). + %{ print1 %} let q = [ap]; let r = [ap + 1]; %{ ids.q, ids.r = divmod(memory[ids.value + ids.i], ids.devisor) %} @@ -462,6 +463,7 @@ func right_shift_le_chunks{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, pow2_a assert [range_check_ptr + offset] = q; assert [range_check_ptr + offset + 1] = r; assert [range_check_ptr + offset + 2] = devisor - r - 1; + %{ print2 %} assert q * devisor + r = value[i]; // done inlining felt_divmod. diff --git a/src/verifiers/evm/account_verifier.cairo b/src/verifiers/evm/account_verifier.cairo index 7a50cd47..51ddfd2e 100644 --- a/src/verifiers/evm/account_verifier.cairo +++ b/src/verifiers/evm/account_verifier.cairo @@ -101,21 +101,21 @@ func verify_account{ let (header_rlp) = EvmMemorizer.get(key=memorizer_key); let state_root = HeaderDecoder.get_field(header_rlp, HeaderField.STATE_ROOT); - let (rlp: felt*, value_len: felt) = verify_mpt_proof( - mpt_proof=mpt_proof, - mpt_proof_bytes_len=proof_bytes_len, - mpt_proof_len=proof_len, - key_be=key, - key_be_leading_zeroes_nibbles=key_leading_zeros, - root=state_root, - pow2_array=pow2_array, - ); - - // add account to memorizer - let memorizer_key = EvmHashParams.account( - chain_id=chain_info.id, block_number=block_number, address=address - ); - EvmMemorizer.add(key=memorizer_key, data=rlp); + // let (rlp: felt*, value_len: felt) = verify_mpt_proof( + // mpt_proof=mpt_proof, + // mpt_proof_bytes_len=proof_bytes_len, + // mpt_proof_len=proof_len, + // key_be=key, + // key_be_leading_zeroes_nibbles=key_leading_zeros, + // root=state_root, + // pow2_array=pow2_array, + // ); + + // // add account to memorizer + // let memorizer_key = EvmHashParams.account( + // chain_id=chain_info.id, block_number=block_number, address=address + // ); + // EvmMemorizer.add(key=memorizer_key, data=rlp); return verify_account( address=address, diff --git a/src/verifiers/evm/verify.cairo b/src/verifiers/evm/verify.cairo index c3eedb24..c2a484da 100644 --- a/src/verifiers/evm/verify.cairo +++ b/src/verifiers/evm/verify.cairo @@ -26,7 +26,7 @@ func run_state_verification{ let (mmr_meta_idx) = verify_mmr_batches(n_proofs, mmr_meta_idx); // Step 2: Verify the accounts - // verify_accounts(); + verify_accounts(); // Step 3: Verify the storage items // verify_storage_items(); From bff0a05bd43f8761247a41144d159234e433f89d Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Sun, 22 Dec 2024 13:29:22 +0100 Subject: [PATCH 50/75] wip resolving memory issues --- crates/hints/src/lib.rs | 2 + crates/hints/src/print.rs | 42 +++++++++++++++-- crates/hints/src/rlp/divmod.rs | 47 +++++++++++++++---- .../src/verifiers/evm/account_verifier.rs | 5 +- .../verifiers/evm/storage_item_verifier.rs | 6 +-- src/utils/rlp.cairo | 11 ++--- 6 files changed, 89 insertions(+), 24 deletions(-) diff --git a/crates/hints/src/lib.rs b/crates/hints/src/lib.rs index 7f259730..17e17baf 100644 --- a/crates/hints/src/lib.rs +++ b/crates/hints/src/lib.rs @@ -40,6 +40,8 @@ pub fn hints() -> HashMap { hints.insert(merkle::HINT_IS_LEFT_SMALLER.into(), merkle::hint_is_left_smaller); hints.insert(rlp::divmod::HINT_DIVMOD_VALUE.into(), rlp::divmod::hint_divmod_value); hints.insert(rlp::divmod::HINT_DIVMOD_RLP.into(), rlp::divmod::hint_divmod_rlp); + hints.insert(rlp::divmod::HINT_DIVMOD_VALUE_INSERT_Q.into(), rlp::divmod::hint_divmod_value_insert_q); + hints.insert(rlp::divmod::HINT_DIVMOD_VALUE_INSERT_R.into(), rlp::divmod::hint_divmod_value_insert_r); hints.insert(rlp::item_type::HINT_IS_LONG.into(), rlp::item_type::hint_is_long); hints.insert(rlp::item_type::HINT_ITEM_TYPE.into(), rlp::item_type::hint_item_type); hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS.into(), rlp::processed_words::hint_processed_words); diff --git a/crates/hints/src/print.rs b/crates/hints/src/print.rs index 28704522..9dea8250 100644 --- a/crates/hints/src/print.rs +++ b/crates/hints/src/print.rs @@ -1,6 +1,9 @@ use crate::vars; use cairo_vm::{ - hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::{get_integer_from_var_name, get_ptr_from_var_name}}, + hint_processor::builtin_hint_processor::{ + builtin_hint_processor_definition::HintProcessorData, + hint_utils::{get_integer_from_var_name, get_ptr_from_var_name}, + }, types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, @@ -33,7 +36,27 @@ pub fn print2( println!("i: {}", get_integer_from_var_name("i", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); println!("q: {}", get_integer_from_var_name("q", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); println!("r: {}", get_integer_from_var_name("r", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); - println!("devisor: {}", get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); + println!( + "devisor: {}", + get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)? + ); + + let i: usize = get_integer_from_var_name("i", vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + println!("i: {}", i); + println!( + "devisor: {}", + get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)? + ); + let ptr = get_ptr_from_var_name("value", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + println!("value[i] {}", vm.get_integer((ptr + i)?)?); + println!( + "{}", + get_integer_from_var_name("q", vm, &hint_data.ids_data, &hint_data.ap_tracking)? + * get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)? + + get_integer_from_var_name("r", vm, &hint_data.ids_data, &hint_data.ap_tracking)? + ); Ok(()) } @@ -46,10 +69,19 @@ pub fn print1( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - println!("i: {}", get_integer_from_var_name("i", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); - println!("devisor: {}", get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); + let i: usize = get_integer_from_var_name("i", vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + println!("i: {}", i); + println!( + "devisor: {}", + get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)? + ); + let ptr = get_ptr_from_var_name("value", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + println!("value[i] {}", vm.get_integer((ptr + i)?)?); + let ptr = get_ptr_from_var_name("value", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - println!("value[0] {}", vm.get_integer((ptr + 0)?)?); + println!("ptr {}", ptr); Ok(()) } diff --git a/crates/hints/src/rlp/divmod.rs b/crates/hints/src/rlp/divmod.rs index d55cd00d..49b22f20 100644 --- a/crates/hints/src/rlp/divmod.rs +++ b/crates/hints/src/rlp/divmod.rs @@ -2,9 +2,9 @@ use crate::vars; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, - hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name}, + hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, }, - types::relocatable::MaybeRelocatable, + types::{exec_scope, relocatable::MaybeRelocatable}, }; use cairo_vm::{ types::exec_scope::ExecutionScopes, @@ -37,11 +37,11 @@ pub fn hint_divmod_rlp( insert_value_from_var_name(vars::ids::R, MaybeRelocatable::Int(r), vm, &hint_data.ids_data, &hint_data.ap_tracking) } -pub const HINT_DIVMOD_VALUE: &str = "ids.q, ids.r = divmod(memory[ids.value + ids.i], ids.devisor)"; +pub const HINT_DIVMOD_VALUE: &str = "q, r = divmod(memory[ids.value + ids.i], ids.devisor)"; pub fn hint_divmod_value( vm: &mut VirtualMachine, - _exec_scope: &mut ExecutionScopes, + exec_scope: &mut ExecutionScopes, hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { @@ -51,13 +51,44 @@ pub fn hint_divmod_value( .try_into() .unwrap(); - println!("{}", vm.get_integer((value + i)?)?); - let devisor = get_integer_from_var_name(vars::ids::DEVISOR, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; let (q, r) = vm.get_integer((value + i)?)?.div_rem(&NonZeroFelt::try_from(devisor).unwrap()); - insert_value_from_var_name(vars::ids::Q, MaybeRelocatable::Int(q), vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + exec_scope.insert_value("q", q); + exec_scope.insert_value("r", r); - insert_value_from_var_name(vars::ids::R, MaybeRelocatable::Int(r), vm, &hint_data.ids_data, &hint_data.ap_tracking) + Ok(()) + + // insert_value_from_var_name(vars::ids::Q, MaybeRelocatable::Int(q), vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + + // insert_value_from_var_name(vars::ids::R, MaybeRelocatable::Int(r), vm, &hint_data.ids_data, &hint_data.ap_tracking) + + // vm.insert_value((vm.get_ap() - 1)?, MaybeRelocatable::Int(q)).map_err(HintError::Memory)?; + + // vm.insert_value((vm.get_ap() + 0)?, MaybeRelocatable::Int(r)).map_err(HintError::Memory) } + +pub const HINT_DIVMOD_VALUE_INSERT_Q: &str = "memory[ap] = to_felt_or_relocatable(q)"; + +pub fn hint_divmod_value_insert_q( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let v = exec_scopes.get::("q")?; + insert_value_into_ap(vm, Felt252::from(v)) +} + +pub const HINT_DIVMOD_VALUE_INSERT_R: &str = "memory[ap] = to_felt_or_relocatable(r)"; + +pub fn hint_divmod_value_insert_r( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let v = exec_scopes.get::("r")?; + insert_value_into_ap(vm, Felt252::from(v)) +} \ No newline at end of file diff --git a/crates/hints/src/verifiers/evm/account_verifier.rs b/crates/hints/src/verifiers/evm/account_verifier.rs index fe156db0..4d0f6ebc 100644 --- a/crates/hints/src/verifiers/evm/account_verifier.rs +++ b/crates/hints/src/verifiers/evm/account_verifier.rs @@ -189,7 +189,7 @@ pub fn hint_get_mpt_proof( ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec> = proof + let proof_le_chunks: Vec = proof .proof .into_iter() .map(|p| { @@ -197,9 +197,10 @@ pub fn hint_get_mpt_proof( .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) .collect() }) + .flat_map(|f: Vec| f) .collect(); - vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; + vm.load_data(mpt_proof_ptr, &proof_le_chunks)?; Ok(()) } diff --git a/crates/hints/src/verifiers/evm/storage_item_verifier.rs b/crates/hints/src/verifiers/evm/storage_item_verifier.rs index 68a288c6..513ef5eb 100644 --- a/crates/hints/src/verifiers/evm/storage_item_verifier.rs +++ b/crates/hints/src/verifiers/evm/storage_item_verifier.rs @@ -202,7 +202,7 @@ pub fn hint_set_mpt_proof( ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec> = proof + let proof_le_chunks: Vec = proof .proof .into_iter() .map(|p| { @@ -210,9 +210,9 @@ pub fn hint_set_mpt_proof( .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) .collect() }) - .collect(); + .flat_map(|f: Vec| f).collect(); - vm.write_arg(mpt_proof_ptr, &proof_le_chunks)?; + vm.load_data(mpt_proof_ptr, &proof_le_chunks)?; Ok(()) } diff --git a/src/utils/rlp.cairo b/src/utils/rlp.cairo index 8802ba77..efae38bf 100644 --- a/src/utils/rlp.cairo +++ b/src/utils/rlp.cairo @@ -435,8 +435,8 @@ func right_shift_le_chunks{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, pow2_a assert [range_check_ptr + 1] = value_len - 1; let range_check_ptr = range_check_ptr + 2; - let devisor = pow2_array[offset * 8]; - let shifter = pow2_array[(8 - offset) * 8]; + local devisor = pow2_array[offset * 8]; + local shifter = pow2_array[(8 - offset) * 8]; tempvar current_word = 0; tempvar n_processed_words = 0; @@ -452,13 +452,12 @@ func right_shift_le_chunks{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, pow2_a // Inlined felt_divmod (unsigned_div_rem). %{ print1 %} - let q = [ap]; - let r = [ap + 1]; - %{ ids.q, ids.r = divmod(memory[ids.value + ids.i], ids.devisor) %} + %{ q, r = divmod(memory[ids.value + ids.i], ids.devisor) %} + tempvar q = nondet %{ q %}; + tempvar r = nondet %{ r %}; // %{ // #print(f"val={memory[ids.value + ids.i]} q={ids.q} r={ids.r} i={ids.i}") // %} - ap += 2; tempvar offset = 3 * n_processed_words; assert [range_check_ptr + offset] = q; assert [range_check_ptr + offset + 1] = r; From ee605b8e26dccc980a98976db133e3f147250770 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Sun, 22 Dec 2024 13:35:24 +0100 Subject: [PATCH 51/75] cleanuped working le_address_chunks_to_felt --- crates/hints/src/lib.rs | 4 --- crates/hints/src/print.rs | 66 +--------------------------------- crates/hints/src/rlp/divmod.rs | 44 +++-------------------- src/utils/rlp.cairo | 9 +++-- 4 files changed, 10 insertions(+), 113 deletions(-) diff --git a/crates/hints/src/lib.rs b/crates/hints/src/lib.rs index 17e17baf..346fd66e 100644 --- a/crates/hints/src/lib.rs +++ b/crates/hints/src/lib.rs @@ -40,15 +40,11 @@ pub fn hints() -> HashMap { hints.insert(merkle::HINT_IS_LEFT_SMALLER.into(), merkle::hint_is_left_smaller); hints.insert(rlp::divmod::HINT_DIVMOD_VALUE.into(), rlp::divmod::hint_divmod_value); hints.insert(rlp::divmod::HINT_DIVMOD_RLP.into(), rlp::divmod::hint_divmod_rlp); - hints.insert(rlp::divmod::HINT_DIVMOD_VALUE_INSERT_Q.into(), rlp::divmod::hint_divmod_value_insert_q); - hints.insert(rlp::divmod::HINT_DIVMOD_VALUE_INSERT_R.into(), rlp::divmod::hint_divmod_value_insert_r); hints.insert(rlp::item_type::HINT_IS_LONG.into(), rlp::item_type::hint_is_long); hints.insert(rlp::item_type::HINT_ITEM_TYPE.into(), rlp::item_type::hint_item_type); hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS.into(), rlp::processed_words::hint_processed_words); hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS_RLP.into(), rlp::processed_words::hint_processed_words_rlp); hints.insert(print::PROGRAM_HASH.into(), print::program_hash); - hints.insert(print::PRINT1.into(), print::print1); - hints.insert(print::PRINT2.into(), print::print2); hints.insert(segments::SEGMENTS_ADD.into(), segments::segments_add); hints.insert(segments::SEGMENTS_ADD_FP.into(), segments::segments_add_fp); hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_SEGMENT_INDEX.into(), segments::segments_add_evm_memorizer_segment_index); diff --git a/crates/hints/src/print.rs b/crates/hints/src/print.rs index 9dea8250..4899fa60 100644 --- a/crates/hints/src/print.rs +++ b/crates/hints/src/print.rs @@ -1,9 +1,6 @@ use crate::vars; use cairo_vm::{ - hint_processor::builtin_hint_processor::{ - builtin_hint_processor_definition::HintProcessorData, - hint_utils::{get_integer_from_var_name, get_ptr_from_var_name}, - }, + hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_integer_from_var_name}, types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, @@ -24,64 +21,3 @@ pub fn program_hash( Ok(()) } - -pub const PRINT2: &str = "print2"; - -pub fn print2( - vm: &mut VirtualMachine, - _exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - println!("i: {}", get_integer_from_var_name("i", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); - println!("q: {}", get_integer_from_var_name("q", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); - println!("r: {}", get_integer_from_var_name("r", vm, &hint_data.ids_data, &hint_data.ap_tracking)?); - println!( - "devisor: {}", - get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)? - ); - - let i: usize = get_integer_from_var_name("i", vm, &hint_data.ids_data, &hint_data.ap_tracking)? - .try_into() - .unwrap(); - println!("i: {}", i); - println!( - "devisor: {}", - get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)? - ); - let ptr = get_ptr_from_var_name("value", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - println!("value[i] {}", vm.get_integer((ptr + i)?)?); - println!( - "{}", - get_integer_from_var_name("q", vm, &hint_data.ids_data, &hint_data.ap_tracking)? - * get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)? - + get_integer_from_var_name("r", vm, &hint_data.ids_data, &hint_data.ap_tracking)? - ); - - Ok(()) -} - -pub const PRINT1: &str = "print1"; - -pub fn print1( - vm: &mut VirtualMachine, - _exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let i: usize = get_integer_from_var_name("i", vm, &hint_data.ids_data, &hint_data.ap_tracking)? - .try_into() - .unwrap(); - println!("i: {}", i); - println!( - "devisor: {}", - get_integer_from_var_name("devisor", vm, &hint_data.ids_data, &hint_data.ap_tracking)? - ); - let ptr = get_ptr_from_var_name("value", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - println!("value[i] {}", vm.get_integer((ptr + i)?)?); - - let ptr = get_ptr_from_var_name("value", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - println!("ptr {}", ptr); - - Ok(()) -} diff --git a/crates/hints/src/rlp/divmod.rs b/crates/hints/src/rlp/divmod.rs index 49b22f20..f78d3e33 100644 --- a/crates/hints/src/rlp/divmod.rs +++ b/crates/hints/src/rlp/divmod.rs @@ -4,7 +4,7 @@ use cairo_vm::{ builtin_hint_processor_definition::HintProcessorData, hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, }, - types::{exec_scope, relocatable::MaybeRelocatable}, + types::relocatable::MaybeRelocatable, }; use cairo_vm::{ types::exec_scope::ExecutionScopes, @@ -37,11 +37,11 @@ pub fn hint_divmod_rlp( insert_value_from_var_name(vars::ids::R, MaybeRelocatable::Int(r), vm, &hint_data.ids_data, &hint_data.ap_tracking) } -pub const HINT_DIVMOD_VALUE: &str = "q, r = divmod(memory[ids.value + ids.i], ids.devisor)"; +pub const HINT_DIVMOD_VALUE: &str = "ids.q, ids.r = divmod(memory[ids.value + ids.i], ids.devisor)"; pub fn hint_divmod_value( vm: &mut VirtualMachine, - exec_scope: &mut ExecutionScopes, + _exec_scope: &mut ExecutionScopes, hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { @@ -55,40 +55,6 @@ pub fn hint_divmod_value( let (q, r) = vm.get_integer((value + i)?)?.div_rem(&NonZeroFelt::try_from(devisor).unwrap()); - exec_scope.insert_value("q", q); - exec_scope.insert_value("r", r); - - Ok(()) - - // insert_value_from_var_name(vars::ids::Q, MaybeRelocatable::Int(q), vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - - // insert_value_from_var_name(vars::ids::R, MaybeRelocatable::Int(r), vm, &hint_data.ids_data, &hint_data.ap_tracking) - - // vm.insert_value((vm.get_ap() - 1)?, MaybeRelocatable::Int(q)).map_err(HintError::Memory)?; - - // vm.insert_value((vm.get_ap() + 0)?, MaybeRelocatable::Int(r)).map_err(HintError::Memory) -} - -pub const HINT_DIVMOD_VALUE_INSERT_Q: &str = "memory[ap] = to_felt_or_relocatable(q)"; - -pub fn hint_divmod_value_insert_q( - vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - _hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let v = exec_scopes.get::("q")?; - insert_value_into_ap(vm, Felt252::from(v)) + insert_value_from_var_name(vars::ids::Q, MaybeRelocatable::Int(q), vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + insert_value_from_var_name(vars::ids::R, MaybeRelocatable::Int(r), vm, &hint_data.ids_data, &hint_data.ap_tracking) } - -pub const HINT_DIVMOD_VALUE_INSERT_R: &str = "memory[ap] = to_felt_or_relocatable(r)"; - -pub fn hint_divmod_value_insert_r( - vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - _hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let v = exec_scopes.get::("r")?; - insert_value_into_ap(vm, Felt252::from(v)) -} \ No newline at end of file diff --git a/src/utils/rlp.cairo b/src/utils/rlp.cairo index efae38bf..7aa42019 100644 --- a/src/utils/rlp.cairo +++ b/src/utils/rlp.cairo @@ -451,10 +451,10 @@ func right_shift_le_chunks{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, pow2_a jmp end_loop if [ap] != 0, ap++; // Inlined felt_divmod (unsigned_div_rem). - %{ print1 %} - %{ q, r = divmod(memory[ids.value + ids.i], ids.devisor) %} - tempvar q = nondet %{ q %}; - tempvar r = nondet %{ r %}; + let q = [ap]; + let r = [ap + 1]; + %{ ids.q, ids.r = divmod(memory[ids.value + ids.i], ids.devisor) %} + ap += 2; // %{ // #print(f"val={memory[ids.value + ids.i]} q={ids.q} r={ids.r} i={ids.i}") // %} @@ -462,7 +462,6 @@ func right_shift_le_chunks{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, pow2_a assert [range_check_ptr + offset] = q; assert [range_check_ptr + offset + 1] = r; assert [range_check_ptr + offset + 2] = devisor - r - 1; - %{ print2 %} assert q * devisor + r = value[i]; // done inlining felt_divmod. From 4ecb1cf04566ae6cb23301e470225d10ef1e5b84 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 23 Dec 2024 14:59:59 +0100 Subject: [PATCH 52/75] hint fixes and impl fixes soundrun verifications working --- crates/dry_run/src/main.rs | 24 ++++--- crates/hints/src/lib.rs | 18 ++++-- crates/hints/src/rlp/divmod.rs | 11 +--- .../src/verifiers/evm/account_verifier.rs | 40 ++++++------ .../src/verifiers/evm/receipt_verifier.rs | 15 ++--- .../verifiers/evm/storage_item_verifier.rs | 64 ++++--------------- .../src/verifiers/evm/transaction_verifier.rs | 12 +--- crates/sound_run/src/main.rs | 28 +++++--- packages/eth_essentials | 2 +- src/utils/rlp.cairo | 33 ++++++---- src/verifiers/evm/account_verifier.cairo | 30 ++++----- src/verifiers/evm/verify.cairo | 6 +- src/verifiers/mmr_verifier.cairo | 2 +- 13 files changed, 130 insertions(+), 155 deletions(-) diff --git a/crates/dry_run/src/main.rs b/crates/dry_run/src/main.rs index 406a6b14..eeae736b 100644 --- a/crates/dry_run/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -3,7 +3,10 @@ use cairo_vm::{ cairo_run::CairoRunConfig, types::{layout_name::LayoutName, program::Program}, - vm::{errors::vm_exception::VmException, runners::cairo_runner::CairoRunner}, + vm::{ + errors::vm_exception::VmException, + runners::cairo_runner::{CairoRunner, RunnerMode}, + }, }; use clap::{Parser, ValueHint}; use dry_hint_processor::{ @@ -47,15 +50,15 @@ fn main() -> Result<(), HdpOsError> { // Load the Program let program = Program::from_bytes(&program_file, Some(cairo_run_config.entrypoint)).map_err(|e| HdpOsError::Runner(e.into()))?; + let runner_mode = if cairo_run_config.proof_mode { + RunnerMode::ProofModeCairo1 + } else { + RunnerMode::ExecutionMode + }; + // Init cairo runner - let mut cairo_runner = CairoRunner::new( - &program, - cairo_run_config.layout, - None, - cairo_run_config.proof_mode, - cairo_run_config.trace_enabled, - ) - .map_err(|e| HdpOsError::Runner(e.into()))?; + let mut cairo_runner = CairoRunner::new_v2(&program, cairo_run_config.layout, None, runner_mode, cairo_run_config.trace_enabled) + .map_err(|e| HdpOsError::Runner(e.into()))?; // Init the Cairo VM let end = cairo_runner @@ -69,6 +72,9 @@ fn main() -> Result<(), HdpOsError> { .map_err(|err| VmException::from_vm_error(&cairo_runner, err)) .map_err(|e| HdpOsError::Runner(e.into()))?; + cairo_runner.vm.compute_segments_effective_sizes(); + println!("{:?}", cairo_runner.get_execution_resources()); + std::fs::write( args.program_output, serde_json::to_vec::( diff --git a/crates/hints/src/lib.rs b/crates/hints/src/lib.rs index 346fd66e..39120f8f 100644 --- a/crates/hints/src/lib.rs +++ b/crates/hints/src/lib.rs @@ -60,6 +60,8 @@ pub fn hints() -> HashMap { hints.insert(verifiers::evm::account_verifier::HINT_BATCH_ACCOUNTS_LEN.into(), verifiers::evm::account_verifier::hint_batch_accounts_len); hints.insert(verifiers::evm::account_verifier::HINT_GET_ACCOUNT_ADDRESS.into(), verifiers::evm::account_verifier::hint_get_account_address); hints.insert(verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), verifiers::evm::account_verifier::hint_get_mpt_proof); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_LEN.into(), verifiers::evm::account_verifier::hint_account_proof_len); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOFS_LEN.into(), verifiers::evm::account_verifier::hint_account_proofs_len); hints.insert(verifiers::evm::transaction_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), verifiers::evm::transaction_verifier::hint_batch_transactions_len); hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX.into(), verifiers::evm::transaction_verifier::hint_set_tx); hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY.into(), verifiers::evm::transaction_verifier::hint_set_tx_key); @@ -67,7 +69,6 @@ pub fn hints() -> HashMap { hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_PROOF_LEN.into(), verifiers::evm::transaction_verifier::hint_set_tx_proof_len); hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), verifiers::evm::transaction_verifier::hint_set_tx_block_number); hints.insert(verifiers::evm::transaction_verifier::HINT_PROOF_BYTES_LEN.into(), verifiers::evm::transaction_verifier::hint_proof_bytes_len); - hints.insert(verifiers::evm::transaction_verifier::HINT_MPT_PROOF.into(), verifiers::evm::transaction_verifier::hint_mpt_proof); hints.insert(verifiers::evm::header_verifier::HINT_VM_ENTER_SCOPE.into(), verifiers::evm::header_verifier::hint_vm_enter_scope); hints.insert(verifiers::evm::header_verifier::HINT_HEADERS_WITH_MMR_HEADERS_LEN.into(), verifiers::evm::header_verifier::hint_headers_with_mmr_headers_len); hints.insert(verifiers::evm::header_verifier::HINT_LEAF_IDX.into(), verifiers::evm::header_verifier::hint_leaf_idx); @@ -79,15 +80,12 @@ pub fn hints() -> HashMap { hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_BLOCK_NUMBER.into(), verifiers::evm::receipt_verifier::hint_receipt_block_number); hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY.into(), verifiers::evm::receipt_verifier::hint_receipt_key); hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY_LEADING_ZEROS.into(), verifiers::evm::receipt_verifier::hint_receipt_key_leading_zeros); - hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_MPT_PROOF.into(), verifiers::evm::receipt_verifier::hint_receipt_mpt_proof); hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_len); hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_BYTES_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_bytes_len); hints.insert(verifiers::evm::receipt_verifier::HINT_SET_RECEIPT.into(), verifiers::evm::receipt_verifier::hint_set_receipt); hints.insert(verifiers::evm::storage_item_verifier::HINT_BATCH_STORAGES_LEN.into(), verifiers::evm::storage_item_verifier::hint_batch_storages_len); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_BATCH_STORAGES.into(), verifiers::evm::storage_item_verifier::hint_set_batch_storages); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_MPT_PROOF.into(), verifiers::evm::storage_item_verifier::hint_set_mpt_proof); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_proof_len); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BYTES_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_proof_bytes_len); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BLOCK_NUMBER.into(), verifiers::evm::storage_item_verifier::hint_set_proof_block_number); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY_LEADING_ZEROS.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key_leading_zeros); @@ -109,7 +107,19 @@ pub fn hints() -> HashMap { hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::assert::HINT_ASSERT_INTEGER_DIV.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::assert::hint_assert_integer_div); hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::HINT_VALUE_DIV.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::hint_value_div); hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::HINT_VALUE_8.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::hint_value_8); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::trailing_zeroes::HINT_TRAILING_ZEROES_BYTES.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::trailing_zeroes::hint_trailing_zeroes_bytes); hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_NEEDS_NEXT_WORD.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_needs_next_word); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_IS_ZERO.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_is_zero); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_NIBBLE_FROM_LOW.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_nibble_from_low); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_WORDS_LOOP.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_words_loop); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_NEEDS_NEXT_WORD_ENDING.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_needs_next_word_ending); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::leading_zeros::HINT_EXPECTED_NIBBLE.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::leading_zeros::hint_expected_nibble); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::assert::HINT_EXPECTED_NIBBLE.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::assert::hint_expected_nibble); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::divmod::HINT_POW_CUT.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::divmod::hint_pow_cut); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_LONG_SHORT_LIST.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_long_short_list); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_FIRST_ITEM_TYPE.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_first_item_type); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_SECOND_ITEM_TYPE.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_second_item_type); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_ITEM_TYPE.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_item_type); hints } diff --git a/crates/hints/src/rlp/divmod.rs b/crates/hints/src/rlp/divmod.rs index f78d3e33..e5099d2f 100644 --- a/crates/hints/src/rlp/divmod.rs +++ b/crates/hints/src/rlp/divmod.rs @@ -2,7 +2,7 @@ use crate::vars; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, - hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, + hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name}, }, types::relocatable::MaybeRelocatable, }; @@ -23,17 +23,13 @@ pub fn hint_divmod_rlp( _constants: &HashMap, ) -> Result<(), HintError> { let rlp = get_ptr_from_var_name(vars::ids::RLP, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let i: usize = get_integer_from_var_name(vars::ids::I, vm, &hint_data.ids_data, &hint_data.ap_tracking)? .try_into() .unwrap(); - let devisor = get_integer_from_var_name(vars::ids::DEVISOR, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let (q, r) = vm.get_integer((rlp + i)?)?.div_rem(&NonZeroFelt::try_from(devisor).unwrap()); insert_value_from_var_name(vars::ids::Q, MaybeRelocatable::Int(q), vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - insert_value_from_var_name(vars::ids::R, MaybeRelocatable::Int(r), vm, &hint_data.ids_data, &hint_data.ap_tracking) } @@ -46,15 +42,12 @@ pub fn hint_divmod_value( _constants: &HashMap, ) -> Result<(), HintError> { let value = get_ptr_from_var_name(vars::ids::VALUE, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let i: usize = get_integer_from_var_name(vars::ids::I, vm, &hint_data.ids_data, &hint_data.ap_tracking)? .try_into() .unwrap(); - let devisor = get_integer_from_var_name(vars::ids::DEVISOR, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let (q, r) = vm.get_integer((value + i)?)?.div_rem(&NonZeroFelt::try_from(devisor).unwrap()); - + insert_value_from_var_name(vars::ids::Q, MaybeRelocatable::Int(q), vm, &hint_data.ids_data, &hint_data.ap_tracking)?; insert_value_from_var_name(vars::ids::R, MaybeRelocatable::Int(r), vm, &hint_data.ids_data, &hint_data.ap_tracking) } diff --git a/crates/hints/src/verifiers/evm/account_verifier.rs b/crates/hints/src/verifiers/evm/account_verifier.rs index 4d0f6ebc..ff3a2b99 100644 --- a/crates/hints/src/verifiers/evm/account_verifier.rs +++ b/crates/hints/src/verifiers/evm/account_verifier.rs @@ -8,7 +8,10 @@ use cairo_vm::{ hint_utils::{get_address_from_var_name, get_integer_from_var_name, get_ptr_from_var_name, insert_value_from_var_name, insert_value_into_ap}, }, types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, - vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + vm::{ + errors::{hint_errors::HintError, memory_errors::MemoryError}, + vm_core::VirtualMachine, + }, Felt252, }; use num_bigint::BigUint; @@ -52,7 +55,7 @@ pub fn hint_get_account_address( let address_ptr = get_ptr_from_var_name(vars::ids::ADDRESS, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.write_arg(address_ptr, &address_le_chunks)?; + vm.load_data(address_ptr, &address_le_chunks)?; Ok(()) } @@ -70,14 +73,8 @@ pub fn hint_account_key( let (key_low, key_high) = split_128(&BigUint::from_bytes_be(account.account_key.as_slice())); let key_ptr = get_address_from_var_name(vars::ids::KEY, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.insert_value( - (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, - Felt252::try_from(key_low).map_err(|_| HintError::WrongHintData)?, - )?; - vm.insert_value( - (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, - Felt252::try_from(key_high).map_err(|_| HintError::WrongHintData)?, - )?; + vm.insert_value((key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, Felt252::from(key_low))?; + vm.insert_value((key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, Felt252::from(key_high))?; Ok(()) } @@ -169,14 +166,10 @@ pub fn hint_account_proof_bytes_len( _constants: &HashMap, ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; - - insert_value_from_var_name( - vars::ids::PROOF_BYTES_LEN, - MaybeRelocatable::Int(Felt252::from(proof.proof.len())), - vm, - &hint_data.ids_data, - &hint_data.ap_tracking, - ) + let proof_bytes_len_ptr = get_ptr_from_var_name(vars::ids::PROOF_BYTES_LEN, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + let proof_len: Vec = proof.proof.into_iter().map(|f| f.len().into()).collect(); + vm.load_data(proof_bytes_len_ptr, &proof_len)?; + Ok(()) } pub const HINT_GET_MPT_PROOF: &str = "segments.write_arg(ids.mpt_proof, [int(x, 16) for x in proof.proof])"; @@ -189,18 +182,21 @@ pub fn hint_get_mpt_proof( ) -> Result<(), HintError> { let proof = exec_scopes.get::(vars::scopes::PROOF)?; let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec = proof + let proof_le_chunks: Result, MemoryError> = proof .proof .into_iter() .map(|p| { p.chunks(8) .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) - .collect() + .collect::>() + }) + .map(|f| { + let segment = vm.add_memory_segment(); + vm.load_data(segment, &f).map(|_| MaybeRelocatable::from(segment)) }) - .flat_map(|f: Vec| f) .collect(); - vm.load_data(mpt_proof_ptr, &proof_le_chunks)?; + vm.load_data(mpt_proof_ptr, &proof_le_chunks?)?; Ok(()) } diff --git a/crates/hints/src/verifiers/evm/receipt_verifier.rs b/crates/hints/src/verifiers/evm/receipt_verifier.rs index 36514f7f..4950110c 100644 --- a/crates/hints/src/verifiers/evm/receipt_verifier.rs +++ b/crates/hints/src/verifiers/evm/receipt_verifier.rs @@ -1,4 +1,7 @@ -use crate::{utils::{count_leading_zero_nibbles_from_hex, split_128}, vars}; +use crate::{ + utils::{count_leading_zero_nibbles_from_hex, split_128}, + vars, +}; use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, @@ -57,14 +60,8 @@ pub fn hint_receipt_key( let (key_low, key_high) = split_128(&BigUint::from_bytes_be(&receipt.key.to_be_bytes_vec())); let key_ptr = get_address_from_var_name(vars::ids::KEY, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.insert_value( - (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, - Felt252::try_from(key_low).map_err(|_| HintError::WrongHintData)?, - )?; - vm.insert_value( - (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, - Felt252::try_from(key_high).map_err(|_| HintError::WrongHintData)?, - )?; + vm.insert_value((key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, Felt252::from(key_low))?; + vm.insert_value((key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, Felt252::from(key_high))?; Ok(()) } diff --git a/crates/hints/src/verifiers/evm/storage_item_verifier.rs b/crates/hints/src/verifiers/evm/storage_item_verifier.rs index 513ef5eb..134fd871 100644 --- a/crates/hints/src/verifiers/evm/storage_item_verifier.rs +++ b/crates/hints/src/verifiers/evm/storage_item_verifier.rs @@ -42,9 +42,18 @@ pub fn hint_set_batch_storages( .try_into() .unwrap(); let storage = batch.storages[idx].clone(); + let address_le_chunks: Vec = storage + .address + .chunks(8) + .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) + .collect(); exec_scopes.insert_value::(vars::scopes::STORAGE, storage); + let address_ptr = get_ptr_from_var_name(vars::ids::ADDRESS, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + + vm.load_data(address_ptr, &address_le_chunks)?; + Ok(()) } @@ -65,7 +74,7 @@ pub fn hint_set_storage_slot( let slot_ptr = get_ptr_from_var_name(vars::ids::SLOT, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.write_arg(slot_ptr, &slot_le_chunks)?; + vm.load_data(slot_ptr, &slot_le_chunks)?; Ok(()) } @@ -81,16 +90,10 @@ pub fn hint_set_storage_key( let storage = exec_scopes.get::(vars::scopes::STORAGE)?; let (key_low, key_high) = split_128(&BigUint::from_bytes_be(storage.storage_key.as_slice())); - + let key_ptr = get_address_from_var_name(vars::ids::KEY, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.insert_value( - (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, - Felt252::try_from(key_low).map_err(|_| HintError::WrongHintData)?, - )?; - vm.insert_value( - (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, - Felt252::try_from(key_high).map_err(|_| HintError::WrongHintData)?, - )?; + vm.insert_value((key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, Felt252::from(key_low))?; + vm.insert_value((key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, Felt252::from(key_high))?; Ok(()) } @@ -175,44 +178,3 @@ pub fn hint_set_proof_block_number( insert_value_into_ap(vm, Felt252::from(proof.block_number)) } - -pub const HINT_SET_PROOF_BYTES_LEN: &str = "segments.write_arg(ids.proof_bytes_len, proof.proof_bytes_len)"; - -pub fn hint_set_proof_bytes_len( - vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let proof = exec_scopes.get::(vars::scopes::PROOF)?; - let proof_bytes_len_ptr = get_ptr_from_var_name(vars::ids::PROOF_BYTES_LEN, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - - vm.insert_value(proof_bytes_len_ptr, Felt252::from(proof.proof.len()))?; - - Ok(()) -} - -pub const HINT_SET_MPT_PROOF: &str = "segments.write_arg(ids.mpt_proof, [int(x, 16) for x in proof.proof])"; - -pub fn hint_set_mpt_proof( - vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let proof = exec_scopes.get::(vars::scopes::PROOF)?; - let mpt_proof_ptr = get_ptr_from_var_name(vars::ids::MPT_PROOF, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - let proof_le_chunks: Vec = proof - .proof - .into_iter() - .map(|p| { - p.chunks(8) - .map(|chunk| MaybeRelocatable::from(Felt252::from_bytes_be_slice(&chunk.iter().rev().copied().collect::>()))) - .collect() - }) - .flat_map(|f: Vec| f).collect(); - - vm.load_data(mpt_proof_ptr, &proof_le_chunks)?; - - Ok(()) -} diff --git a/crates/hints/src/verifiers/evm/transaction_verifier.rs b/crates/hints/src/verifiers/evm/transaction_verifier.rs index f8cd44aa..cc3aa73e 100644 --- a/crates/hints/src/verifiers/evm/transaction_verifier.rs +++ b/crates/hints/src/verifiers/evm/transaction_verifier.rs @@ -56,18 +56,12 @@ pub fn hint_set_tx_key( _constants: &HashMap, ) -> Result<(), HintError> { let transaction = exec_scopes.get::(vars::scopes::TRANSACTION)?; - + let (key_low, key_high) = split_128(&BigUint::from_bytes_be(&transaction.key.to_be_bytes_vec())); let key_ptr = get_address_from_var_name(vars::ids::KEY, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - vm.insert_value( - (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, - Felt252::try_from(key_low).map_err(|_| HintError::WrongHintData)?, - )?; - vm.insert_value( - (key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, - Felt252::try_from(key_high).map_err(|_| HintError::WrongHintData)?, - )?; + vm.insert_value((key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 0)?, Felt252::from(key_low))?; + vm.insert_value((key_ptr.get_relocatable().ok_or(HintError::WrongHintData)? + 1)?, Felt252::from(key_high))?; Ok(()) } diff --git a/crates/sound_run/src/main.rs b/crates/sound_run/src/main.rs index 599361de..4f7ee3ed 100644 --- a/crates/sound_run/src/main.rs +++ b/crates/sound_run/src/main.rs @@ -3,7 +3,10 @@ use cairo_vm::{ cairo_run::CairoRunConfig, types::{layout_name::LayoutName, program::Program}, - vm::{errors::vm_exception::VmException, runners::cairo_runner::CairoRunner}, + vm::{ + errors::vm_exception::VmException, + runners::cairo_runner::{CairoRunner, RunnerMode}, + }, }; use clap::{Parser, ValueHint}; use sound_hint_processor::CustomHintProcessor; @@ -34,7 +37,9 @@ fn main() -> Result<(), HdpOsError> { // Init CairoRunConfig let cairo_run_config = CairoRunConfig { layout: args.layout, - relocate_mem: true, + allow_missing_builtins: Some(true), + proof_mode: false, + relocate_mem: false, trace_enabled: true, ..Default::default() }; @@ -46,15 +51,15 @@ fn main() -> Result<(), HdpOsError> { // Load the Program let program = Program::from_bytes(&program_file, Some(cairo_run_config.entrypoint)).map_err(|e| HdpOsError::Runner(e.into()))?; + let runner_mode = if cairo_run_config.proof_mode { + RunnerMode::ProofModeCairo1 + } else { + RunnerMode::ExecutionMode + }; + // Init cairo runner - let mut cairo_runner = CairoRunner::new( - &program, - cairo_run_config.layout, - None, - cairo_run_config.proof_mode, - cairo_run_config.trace_enabled, - ) - .map_err(|e| HdpOsError::Runner(e.into()))?; + let mut cairo_runner = CairoRunner::new_v2(&program, cairo_run_config.layout, None, runner_mode, cairo_run_config.trace_enabled) + .map_err(|e| HdpOsError::Runner(e.into()))?; // Init the Cairo VM let end = cairo_runner @@ -72,6 +77,9 @@ fn main() -> Result<(), HdpOsError> { .map_err(|err| VmException::from_vm_error(&cairo_runner, err)) .map_err(|e| HdpOsError::Runner(e.into()))?; + cairo_runner.vm.compute_segments_effective_sizes(); + println!("{:?}", cairo_runner.get_execution_resources()); + Ok(()) } diff --git a/packages/eth_essentials b/packages/eth_essentials index 925de5ba..c4b00359 160000 --- a/packages/eth_essentials +++ b/packages/eth_essentials @@ -1 +1 @@ -Subproject commit 925de5ba553ca35e45df402350787a26a30e129b +Subproject commit c4b00359393f14aedecde237c9330ea758b8d6dd diff --git a/src/utils/rlp.cairo b/src/utils/rlp.cairo index 7aa42019..731de828 100644 --- a/src/utils/rlp.cairo +++ b/src/utils/rlp.cairo @@ -378,14 +378,18 @@ func le_chunks_to_uint256{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, pow2_ar if (elements_len == 1) { let high = elements[0] * pow2_array[(16 - bytes_len) * 8]; - return(Uint256(low=0, high=high)); + return (Uint256(low=0, high=high)); } if (elements_len == 2) { - return(Uint256( - low=0, - high=(elements[1] * pow2_array[64] + elements[0]) * pow2_array[(16 - bytes_len) * 8], - )); + return ( + Uint256( + low=0, + high=(elements[1] * pow2_array[64] + elements[0]) * pow2_array[ + (16 - bytes_len) * 8 + ], + ) + ); } // For values larger then 16 bytes, we need to shift the chunks to the left. @@ -393,16 +397,21 @@ func le_chunks_to_uint256{range_check_ptr, bitwise_ptr: BitwiseBuiltin*, pow2_ar let (le_shifted) = right_shift_le_chunks(elements, elements_len, offset); if (elements_len == 3) { - return(Uint256( - low=le_shifted[0] * pow2_array[64], high=le_shifted[2] * pow2_array[64] + le_shifted[1] - )); + return ( + Uint256( + low=le_shifted[0] * pow2_array[64], + high=le_shifted[2] * pow2_array[64] + le_shifted[1], + ) + ); } if (elements_len == 4) { - return(Uint256( - low=le_shifted[1] * pow2_array[64] + le_shifted[0], - high=le_shifted[3] * pow2_array[64] + le_shifted[2], - )); + return ( + Uint256( + low=le_shifted[1] * pow2_array[64] + le_shifted[0], + high=le_shifted[3] * pow2_array[64] + le_shifted[2], + ) + ); } assert 0 = 1; diff --git a/src/verifiers/evm/account_verifier.cairo b/src/verifiers/evm/account_verifier.cairo index 51ddfd2e..7a50cd47 100644 --- a/src/verifiers/evm/account_verifier.cairo +++ b/src/verifiers/evm/account_verifier.cairo @@ -101,21 +101,21 @@ func verify_account{ let (header_rlp) = EvmMemorizer.get(key=memorizer_key); let state_root = HeaderDecoder.get_field(header_rlp, HeaderField.STATE_ROOT); - // let (rlp: felt*, value_len: felt) = verify_mpt_proof( - // mpt_proof=mpt_proof, - // mpt_proof_bytes_len=proof_bytes_len, - // mpt_proof_len=proof_len, - // key_be=key, - // key_be_leading_zeroes_nibbles=key_leading_zeros, - // root=state_root, - // pow2_array=pow2_array, - // ); - - // // add account to memorizer - // let memorizer_key = EvmHashParams.account( - // chain_id=chain_info.id, block_number=block_number, address=address - // ); - // EvmMemorizer.add(key=memorizer_key, data=rlp); + let (rlp: felt*, value_len: felt) = verify_mpt_proof( + mpt_proof=mpt_proof, + mpt_proof_bytes_len=proof_bytes_len, + mpt_proof_len=proof_len, + key_be=key, + key_be_leading_zeroes_nibbles=key_leading_zeros, + root=state_root, + pow2_array=pow2_array, + ); + + // add account to memorizer + let memorizer_key = EvmHashParams.account( + chain_id=chain_info.id, block_number=block_number, address=address + ); + EvmMemorizer.add(key=memorizer_key, data=rlp); return verify_account( address=address, diff --git a/src/verifiers/evm/verify.cairo b/src/verifiers/evm/verify.cairo index c2a484da..e434b436 100644 --- a/src/verifiers/evm/verify.cairo +++ b/src/verifiers/evm/verify.cairo @@ -29,13 +29,13 @@ func run_state_verification{ verify_accounts(); // Step 3: Verify the storage items - // verify_storage_items(); + verify_storage_items(); // Step 4: Verify the block tx proofs - // verify_block_tx_proofs(); + verify_block_tx_proofs(); // Step 5: Verify the block receipt proofs - // verify_block_receipt_proofs(); + verify_block_receipt_proofs(); } return (mmr_meta_idx=mmr_meta_idx); diff --git a/src/verifiers/mmr_verifier.cairo b/src/verifiers/mmr_verifier.cairo index 70082338..b861aa5d 100644 --- a/src/verifiers/mmr_verifier.cairo +++ b/src/verifiers/mmr_verifier.cairo @@ -31,7 +31,7 @@ func validate_mmr_meta{range_check_ptr, poseidon_ptr: PoseidonBuiltin*, pow2_arr ); tempvar peaks_len: felt = nondet %{ len(header_with_mmr.mmr_meta.peaks) %}; - + let (peaks: felt*) = alloc(); %{ segments.write_arg(ids.peaks, header_with_mmr.mmr_meta.peaks) %} From c1981ba9029ea3878e44ae0f01dab0d25e37045a Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 23 Dec 2024 15:16:31 +0100 Subject: [PATCH 53/75] celanup --- Cargo.lock | 35 -------------------------- crates/dry_hint_processor/Cargo.toml | 20 +++------------ crates/dry_hint_processor/src/lib.rs | 5 +++- crates/dry_run/Cargo.toml | 4 +-- crates/dry_run/src/main.rs | 5 +++- crates/fetcher/Cargo.toml | 8 +++--- crates/fetcher/src/lib.rs | 26 ------------------- crates/fetcher/src/main.rs | 32 ++++++++++++++++++++--- crates/hints/Cargo.toml | 14 +++++------ crates/hints/src/rlp/divmod.rs | 2 +- crates/indexer/Cargo.toml | 8 +++--- crates/indexer/src/lib.rs | 5 ++++ crates/sound_hint_processor/Cargo.toml | 20 ++------------- crates/sound_hint_processor/src/lib.rs | 5 +++- crates/sound_run/Cargo.toml | 7 +++--- crates/sound_run/src/main.rs | 5 +++- crates/syscall_handler/src/lib.rs | 5 ++++ crates/types/Cargo.toml | 8 +++--- crates/types/src/lib.rs | 5 ++++ 19 files changed, 89 insertions(+), 130 deletions(-) delete mode 100644 crates/fetcher/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 2f2d0a9b..d8fad24e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2055,28 +2055,14 @@ name = "dry_hint_processor" version = "0.1.0" dependencies = [ "alloy", - "alloy-rlp", - "bincode", "cairo-lang-casm", "cairo-lang-starknet-classes", - "cairo-type-derive", "cairo-vm", - "hex", "hints", - "indexer", - "num-bigint", - "num-traits", - "rand", - "reqwest", "serde", - "serde_json", - "serde_with 3.11.0", - "starknet-core", - "starknet-crypto 0.7.3", "starknet-types-core", "strum_macros", "syscall_handler", - "thiserror 1.0.69", "tokio", "types", ] @@ -2230,10 +2216,8 @@ name = "fetcher" version = "0.1.0" dependencies = [ "alloy", - "cairo-vm", "clap", "dry_hint_processor", - "hex", "indexer", "serde_json", "thiserror 1.0.69", @@ -4606,30 +4590,14 @@ dependencies = [ name = "sound_hint_processor" version = "0.1.0" dependencies = [ - "alloy", - "alloy-rlp", - "bincode", "cairo-lang-casm", "cairo-lang-starknet-classes", - "cairo-type-derive", "cairo-vm", - "hex", "hints", - "indexer", - "num-bigint", - "num-traits", - "rand", - "reqwest", "serde", - "serde_json", - "serde_with 3.11.0", - "starknet-core", - "starknet-crypto 0.7.3", "starknet-types-core", "strum_macros", "syscall_handler", - "thiserror 1.0.69", - "tokio", "types", ] @@ -4639,7 +4607,6 @@ version = "0.1.0" dependencies = [ "cairo-vm", "clap", - "hints", "serde_json", "sound_hint_processor", "thiserror 1.0.69", @@ -5308,7 +5275,6 @@ version = "0.1.0" dependencies = [ "alloy", "alloy-rlp", - "cairo-lang-casm", "cairo-lang-starknet-classes", "cairo-type-derive", "cairo-vm", @@ -5316,7 +5282,6 @@ dependencies = [ "serde_json", "serde_with 3.11.0", "starknet-crypto 0.7.3", - "starknet-types-core", "strum_macros", "thiserror 1.0.69", ] diff --git a/crates/dry_hint_processor/Cargo.toml b/crates/dry_hint_processor/Cargo.toml index 4b4fe533..0ef7b927 100644 --- a/crates/dry_hint_processor/Cargo.toml +++ b/crates/dry_hint_processor/Cargo.toml @@ -5,28 +5,14 @@ edition = "2021" [dependencies] alloy.workspace = true -alloy-rlp.workspace = true -bincode.workspace = true cairo-lang-casm.workspace = true cairo-lang-starknet-classes.workspace = true -cairo-type-derive.workspace = true cairo-vm.workspace = true -hex.workspace = true -num-bigint.workspace = true -num-traits.workspace = true -rand.workspace = true -serde_json.workspace = true serde.workspace = true -starknet-crypto.workspace = true starknet-types-core.workspace = true -thiserror.workspace = true -tokio = { workspace = true } -serde_with.workspace = true -reqwest.workspace = true strum_macros.workspace = true -starknet-core.workspace = true +tokio.workspace = true -indexer.workspace = true -types.workspace = true hints.workspace = true -syscall_handler.workspace = true \ No newline at end of file +syscall_handler.workspace = true +types.workspace = true \ No newline at end of file diff --git a/crates/dry_hint_processor/src/lib.rs b/crates/dry_hint_processor/src/lib.rs index eb384d5c..38d9cd75 100644 --- a/crates/dry_hint_processor/src/lib.rs +++ b/crates/dry_hint_processor/src/lib.rs @@ -1,5 +1,8 @@ -#![forbid(unsafe_code)] #![allow(async_fn_in_trait)] +#![warn(unused_extern_crates)] +#![warn(unused_crate_dependencies)] +#![forbid(unsafe_code)] + pub mod input; pub mod output; pub mod syscall_handler; diff --git a/crates/dry_run/Cargo.toml b/crates/dry_run/Cargo.toml index 485e7473..0c85b5ce 100644 --- a/crates/dry_run/Cargo.toml +++ b/crates/dry_run/Cargo.toml @@ -4,11 +4,11 @@ version = "0.1.0" edition = "2021" [dependencies] -dry_hint_processor.workspace = true cairo-vm.workspace = true clap.workspace = true -thiserror.workspace = true +dry_hint_processor.workspace = true serde_json.workspace = true +thiserror.workspace = true hints.workspace = true types.workspace = true \ No newline at end of file diff --git a/crates/dry_run/src/main.rs b/crates/dry_run/src/main.rs index eeae736b..08e5c34b 100644 --- a/crates/dry_run/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -1,5 +1,8 @@ -#![forbid(unsafe_code)] #![allow(async_fn_in_trait)] +#![warn(unused_extern_crates)] +#![warn(unused_crate_dependencies)] +#![forbid(unsafe_code)] + use cairo_vm::{ cairo_run::CairoRunConfig, types::{layout_name::LayoutName, program::Program}, diff --git a/crates/fetcher/Cargo.toml b/crates/fetcher/Cargo.toml index b01bd65e..fd166648 100644 --- a/crates/fetcher/Cargo.toml +++ b/crates/fetcher/Cargo.toml @@ -4,14 +4,12 @@ version = "0.1.0" edition = "2021" [dependencies] -dry_hint_processor.workspace = true -cairo-vm.workspace = true +alloy.workspace = true clap.workspace = true +dry_hint_processor.workspace = true +serde_json.workspace = true thiserror.workspace = true tokio.workspace = true -serde_json.workspace = true -alloy.workspace = true -hex.workspace = true indexer.workspace = true types.workspace = true \ No newline at end of file diff --git a/crates/fetcher/src/lib.rs b/crates/fetcher/src/lib.rs deleted file mode 100644 index 24550560..00000000 --- a/crates/fetcher/src/lib.rs +++ /dev/null @@ -1,26 +0,0 @@ -use alloy::hex::FromHexError; -use indexer::types::IndexerError; -use std::num::ParseIntError; -use thiserror::Error; - -pub mod proof_keys; - -#[derive(Error, Debug)] -pub enum FetcherError { - #[error(transparent)] - Args(#[from] clap::error::Error), - #[error("Output Error: {0}")] - Output(String), - #[error(transparent)] - IO(#[from] std::io::Error), - #[error(transparent)] - Indexer(#[from] IndexerError), - #[error(transparent)] - ParseIntError(#[from] ParseIntError), - #[error(transparent)] - FromHexError(#[from] FromHexError), - #[error(transparent)] - SerdeJson(#[from] serde_json::Error), - #[error("Internal Error: {0}")] - InternalError(String), -} diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index fa56e727..dfc2f529 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -1,9 +1,15 @@ -#![forbid(unsafe_code)] #![allow(async_fn_in_trait)] +#![warn(unused_extern_crates)] +#![warn(unused_crate_dependencies)] +#![forbid(unsafe_code)] + +use alloy::hex::FromHexError; use clap::{Parser, ValueHint}; use dry_hint_processor::syscall_handler::evm::{self, SyscallHandler}; -use fetcher::{proof_keys::ProofKeys, FetcherError}; -use std::{collections::HashSet, fs, path::PathBuf}; +use indexer::types::IndexerError; +use proof_keys::ProofKeys; +use std::{collections::HashSet, fs, num::ParseIntError, path::PathBuf}; +use thiserror::Error; use types::proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}; pub mod proof_keys; @@ -82,3 +88,23 @@ fn main() -> Result<(), FetcherError> { Ok(()) } + +#[derive(Error, Debug)] +pub enum FetcherError { + #[error(transparent)] + Args(#[from] clap::error::Error), + #[error("Output Error: {0}")] + Output(String), + #[error(transparent)] + IO(#[from] std::io::Error), + #[error(transparent)] + Indexer(#[from] IndexerError), + #[error(transparent)] + ParseIntError(#[from] ParseIntError), + #[error(transparent)] + FromHexError(#[from] FromHexError), + #[error(transparent)] + SerdeJson(#[from] serde_json::Error), + #[error("Internal Error: {0}")] + InternalError(String), +} diff --git a/crates/hints/Cargo.toml b/crates/hints/Cargo.toml index 56d19937..745e8e15 100644 --- a/crates/hints/Cargo.toml +++ b/crates/hints/Cargo.toml @@ -4,8 +4,8 @@ version = "0.1.0" edition = "2021" [dependencies] -alloy.workspace = true alloy-rlp.workspace = true +alloy.workspace = true bincode.workspace = true cairo-lang-casm.workspace = true cairo-lang-starknet-classes.workspace = true @@ -15,16 +15,16 @@ hex.workspace = true num-bigint.workspace = true num-traits.workspace = true rand.workspace = true +reqwest.workspace = true serde_json.workspace = true +serde_with.workspace = true serde.workspace = true +starknet-core.workspace = true starknet-crypto.workspace = true starknet-types-core.workspace = true +strum_macros.workspace = true thiserror.workspace = true tokio = { workspace = true } -serde_with.workspace = true -reqwest.workspace = true -strum_macros.workspace = true -starknet-core.workspace = true -types.workspace = true -eth_essentials_cairo_vm_hints.workspace = true \ No newline at end of file +eth_essentials_cairo_vm_hints.workspace = true +types.workspace = true \ No newline at end of file diff --git a/crates/hints/src/rlp/divmod.rs b/crates/hints/src/rlp/divmod.rs index e5099d2f..19253c7f 100644 --- a/crates/hints/src/rlp/divmod.rs +++ b/crates/hints/src/rlp/divmod.rs @@ -47,7 +47,7 @@ pub fn hint_divmod_value( .unwrap(); let devisor = get_integer_from_var_name(vars::ids::DEVISOR, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; let (q, r) = vm.get_integer((value + i)?)?.div_rem(&NonZeroFelt::try_from(devisor).unwrap()); - + insert_value_from_var_name(vars::ids::Q, MaybeRelocatable::Int(q), vm, &hint_data.ids_data, &hint_data.ap_tracking)?; insert_value_from_var_name(vars::ids::R, MaybeRelocatable::Int(r), vm, &hint_data.ids_data, &hint_data.ap_tracking) } diff --git a/crates/indexer/Cargo.toml b/crates/indexer/Cargo.toml index 5cf7efb8..021afea9 100644 --- a/crates/indexer/Cargo.toml +++ b/crates/indexer/Cargo.toml @@ -5,9 +5,11 @@ edition = "2021" [dependencies] alloy.workspace = true -tokio.workspace = true -serde.workspace = true +reqwest.workspace = true serde_json.workspace = true serde_with.workspace = true +serde.workspace = true thiserror.workspace = true -reqwest.workspace = true \ No newline at end of file + +[dev-dependencies] +tokio.workspace = true \ No newline at end of file diff --git a/crates/indexer/src/lib.rs b/crates/indexer/src/lib.rs index e04687fb..b1156d85 100644 --- a/crates/indexer/src/lib.rs +++ b/crates/indexer/src/lib.rs @@ -1,3 +1,8 @@ +#![allow(async_fn_in_trait)] +#![warn(unused_extern_crates)] +#![warn(unused_crate_dependencies)] +#![forbid(unsafe_code)] + pub mod types; use reqwest::Client; diff --git a/crates/sound_hint_processor/Cargo.toml b/crates/sound_hint_processor/Cargo.toml index bb46b444..73b93a95 100644 --- a/crates/sound_hint_processor/Cargo.toml +++ b/crates/sound_hint_processor/Cargo.toml @@ -4,29 +4,13 @@ version = "0.1.0" edition = "2021" [dependencies] -alloy.workspace = true -alloy-rlp.workspace = true -bincode.workspace = true cairo-lang-casm.workspace = true cairo-lang-starknet-classes.workspace = true -cairo-type-derive.workspace = true cairo-vm.workspace = true -hex.workspace = true -num-bigint.workspace = true -num-traits.workspace = true -rand.workspace = true -serde_json.workspace = true serde.workspace = true -starknet-crypto.workspace = true starknet-types-core.workspace = true -thiserror.workspace = true -tokio = { workspace = true } -serde_with.workspace = true -reqwest.workspace = true strum_macros.workspace = true -starknet-core.workspace = true -indexer.workspace = true -types.workspace = true hints.workspace = true -syscall_handler.workspace = true \ No newline at end of file +syscall_handler.workspace = true +types.workspace = true \ No newline at end of file diff --git a/crates/sound_hint_processor/src/lib.rs b/crates/sound_hint_processor/src/lib.rs index 35bb5dfc..e9417b7b 100644 --- a/crates/sound_hint_processor/src/lib.rs +++ b/crates/sound_hint_processor/src/lib.rs @@ -1,5 +1,8 @@ -#![forbid(unsafe_code)] #![allow(async_fn_in_trait)] +#![warn(unused_extern_crates)] +#![warn(unused_crate_dependencies)] +#![forbid(unsafe_code)] + pub mod input; pub mod output; pub mod syscall_handler; diff --git a/crates/sound_run/Cargo.toml b/crates/sound_run/Cargo.toml index 27f0ba93..451496e3 100644 --- a/crates/sound_run/Cargo.toml +++ b/crates/sound_run/Cargo.toml @@ -4,11 +4,10 @@ version = "0.1.0" edition = "2021" [dependencies] -sound_hint_processor.workspace = true cairo-vm.workspace = true clap.workspace = true -thiserror.workspace = true serde_json.workspace = true +sound_hint_processor.workspace = true +thiserror.workspace = true -types.workspace = true -hints.workspace = true \ No newline at end of file +types.workspace = true \ No newline at end of file diff --git a/crates/sound_run/src/main.rs b/crates/sound_run/src/main.rs index 4f7ee3ed..313dc9a8 100644 --- a/crates/sound_run/src/main.rs +++ b/crates/sound_run/src/main.rs @@ -1,5 +1,8 @@ -#![forbid(unsafe_code)] #![allow(async_fn_in_trait)] +#![warn(unused_extern_crates)] +#![warn(unused_crate_dependencies)] +#![forbid(unsafe_code)] + use cairo_vm::{ cairo_run::CairoRunConfig, types::{layout_name::LayoutName, program::Program}, diff --git a/crates/syscall_handler/src/lib.rs b/crates/syscall_handler/src/lib.rs index 33f0967d..d8ca7089 100644 --- a/crates/syscall_handler/src/lib.rs +++ b/crates/syscall_handler/src/lib.rs @@ -1,3 +1,8 @@ +#![allow(async_fn_in_trait)] +#![warn(unused_extern_crates)] +#![warn(unused_crate_dependencies)] +#![forbid(unsafe_code)] + pub mod traits; use cairo_vm::{ diff --git a/crates/types/Cargo.toml b/crates/types/Cargo.toml index 9654198a..5fe87fcf 100644 --- a/crates/types/Cargo.toml +++ b/crates/types/Cargo.toml @@ -4,16 +4,14 @@ version = "0.1.0" edition = "2021" [dependencies] +alloy-rlp.workspace = true alloy.workspace = true -cairo-lang-casm.workspace = true cairo-lang-starknet-classes.workspace = true cairo-type-derive.workspace = true cairo-vm.workspace = true serde_json.workspace = true serde_with.workspace = true serde.workspace = true -thiserror.workspace = true starknet-crypto.workspace = true -starknet-types-core.workspace = true -alloy-rlp.workspace = true -strum_macros.workspace = true \ No newline at end of file +strum_macros.workspace = true +thiserror.workspace = true \ No newline at end of file diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index d25d9c5e..561d4a9a 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -1,3 +1,8 @@ +#![allow(async_fn_in_trait)] +#![warn(unused_extern_crates)] +#![warn(unused_crate_dependencies)] +#![forbid(unsafe_code)] + pub mod cairo; pub mod keys; pub mod param; From b456b6410d52e6adb6bed769aff2e9a6a0096540 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 23 Dec 2024 17:05:28 +0100 Subject: [PATCH 54/75] automatic build --- Cargo.lock | 2 + crates/dry_run/Cargo.toml | 5 ++- crates/dry_run/build.rs | 80 ++++++++++++++++++++++++++++++++++++ crates/dry_run/src/main.rs | 13 +++--- crates/sound_run/Cargo.toml | 5 ++- crates/sound_run/build.rs | 80 ++++++++++++++++++++++++++++++++++++ crates/sound_run/src/main.rs | 14 +++---- 7 files changed, 184 insertions(+), 15 deletions(-) create mode 100644 crates/dry_run/build.rs create mode 100644 crates/sound_run/build.rs diff --git a/Cargo.lock b/Cargo.lock index d8fad24e..393a8598 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2076,6 +2076,7 @@ dependencies = [ "dry_hint_processor", "hints", "serde_json", + "sha2", "thiserror 1.0.69", "types", ] @@ -4608,6 +4609,7 @@ dependencies = [ "cairo-vm", "clap", "serde_json", + "sha2", "sound_hint_processor", "thiserror 1.0.69", "types", diff --git a/crates/dry_run/Cargo.toml b/crates/dry_run/Cargo.toml index 0c85b5ce..e0a923af 100644 --- a/crates/dry_run/Cargo.toml +++ b/crates/dry_run/Cargo.toml @@ -11,4 +11,7 @@ serde_json.workspace = true thiserror.workspace = true hints.workspace = true -types.workspace = true \ No newline at end of file +types.workspace = true + +[build-dependencies] +sha2 = "0.10.6" \ No newline at end of file diff --git a/crates/dry_run/build.rs b/crates/dry_run/build.rs new file mode 100644 index 00000000..b11cac15 --- /dev/null +++ b/crates/dry_run/build.rs @@ -0,0 +1,80 @@ +use sha2::{Digest, Sha256}; +use std::fs::File; +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::process::Command; +use std::{env, fs}; + +fn calculate_directory_hash(dir: &PathBuf) -> String { + let mut hasher = Sha256::new(); + let mut entries: Vec<_> = fs::read_dir(dir) + .unwrap() + .filter_map(Result::ok) + .filter(|entry| { + let path = entry.path(); + path.is_file() && path.extension().map_or(false, |ext| ext == "cairo") + }) + .collect(); + + entries.sort_by_key(|entry| entry.path()); + + for entry in entries { + let path = entry.path(); + let mut file = File::open(&path).unwrap(); + let mut buffer = Vec::new(); + file.read_to_end(&mut buffer).unwrap(); + hasher.update(buffer); + } + + format!("{:x}", hasher.finalize()) +} + +fn main() { + let workspace_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is not set")).join("../../"); + let python_path = workspace_root.join("venv/bin"); + let cairo_path = workspace_root.join("packages/eth_essentials"); + let src_dir = workspace_root.join("src"); + let entrypoint_path = src_dir.join("contract_bootloader").join("contract_dry_run.cairo"); + let output_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is not set")).join("cairo"); + let checksum_file = output_dir.join("checksum.txt"); + + // Calculate the current hash of the src directory + let current_hash = calculate_directory_hash(&src_dir); + + // Check if recompilation is necessary + if checksum_file.exists() { + let mut previous_hash = String::new(); + File::open(&checksum_file) + .expect("Failed to open checksum file") + .read_to_string(&mut previous_hash) + .expect("Failed to read checksum file"); + + if previous_hash == current_hash { + println!("No changes detected in src directory. Skipping compilation."); + return; + } + } + + // Create output directory + fs::create_dir_all(&output_dir).expect("Failed to create output directory"); + let output_file = output_dir.join("compiled.json"); + + // Run the cairo-compile command. + let status = Command::new(python_path.join("cairo-compile").to_str().expect("Failed to convert path to string")) + .arg(format!("--cairo_path={}:{}", workspace_root.display(), cairo_path.display())) + .arg(entrypoint_path.to_str().expect("Failed to convert path to string")) + .arg("--output") + .arg(output_file.to_str().expect("Failed to convert path to string")) + .status() + .expect("Failed to execute cairo-compile"); + + if !status.success() { + panic!("cairo-compile failed for file: {}", entrypoint_path.display()); + } + + // Save the new checksum + File::create(&checksum_file) + .expect("Failed to create checksum file") + .write_all(current_hash.as_bytes()) + .expect("Failed to write checksum file"); +} diff --git a/crates/dry_run/src/main.rs b/crates/dry_run/src/main.rs index 08e5c34b..1482ba58 100644 --- a/crates/dry_run/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -11,21 +11,18 @@ use cairo_vm::{ runners::cairo_runner::{CairoRunner, RunnerMode}, }, }; -use clap::{Parser, ValueHint}; +use clap::Parser; use dry_hint_processor::{ syscall_handler::evm::{SyscallHandler, SyscallHandlerWrapper}, CustomHintProcessor, }; use hints::vars; -use std::path::PathBuf; +use std::{env, path::PathBuf}; use types::HDPDryRunInput; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] struct Args { - #[clap(value_parser, value_hint=ValueHint::FilePath)] - filename: PathBuf, - /// When using dynamic layout, it's parameters must be specified through a layout params file. #[clap(long = "layout", default_value = "plain", value_enum)] layout: LayoutName, #[structopt(long = "proof_mode")] @@ -47,7 +44,11 @@ fn main() -> Result<(), HdpOsError> { ..Default::default() }; - let program_file = std::fs::read(args.filename).map_err(HdpOsError::IO)?; + // Locate the compiled program file in the `OUT_DIR` folder. + let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is not set")); + let program_file_path = out_dir.join("cairo").join("compiled.json"); + + let program_file = std::fs::read(program_file_path).map_err(HdpOsError::IO)?; let program_inputs: HDPDryRunInput = serde_json::from_slice(&std::fs::read(args.program_input).map_err(HdpOsError::IO)?)?; // Load the Program diff --git a/crates/sound_run/Cargo.toml b/crates/sound_run/Cargo.toml index 451496e3..96a5c3ee 100644 --- a/crates/sound_run/Cargo.toml +++ b/crates/sound_run/Cargo.toml @@ -10,4 +10,7 @@ serde_json.workspace = true sound_hint_processor.workspace = true thiserror.workspace = true -types.workspace = true \ No newline at end of file +types.workspace = true + +[build-dependencies] +sha2 = "0.10.6" \ No newline at end of file diff --git a/crates/sound_run/build.rs b/crates/sound_run/build.rs new file mode 100644 index 00000000..a9c28d73 --- /dev/null +++ b/crates/sound_run/build.rs @@ -0,0 +1,80 @@ +use sha2::{Digest, Sha256}; +use std::fs::File; +use std::io::{Read, Write}; +use std::path::PathBuf; +use std::process::Command; +use std::{env, fs}; + +fn calculate_directory_hash(dir: &PathBuf) -> String { + let mut hasher = Sha256::new(); + let mut entries: Vec<_> = fs::read_dir(dir) + .unwrap() + .filter_map(Result::ok) + .filter(|entry| { + let path = entry.path(); + path.is_file() && path.extension().map_or(false, |ext| ext == "cairo") + }) + .collect(); + + entries.sort_by_key(|entry| entry.path()); + + for entry in entries { + let path = entry.path(); + let mut file = File::open(&path).unwrap(); + let mut buffer = Vec::new(); + file.read_to_end(&mut buffer).unwrap(); + hasher.update(buffer); + } + + format!("{:x}", hasher.finalize()) +} + +fn main() { + let workspace_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is not set")).join("../../"); + let python_path = workspace_root.join("venv/bin"); + let cairo_path = workspace_root.join("packages/eth_essentials"); + let src_dir = workspace_root.join("src"); + let entrypoint_path = src_dir.join("hdp.cairo"); + let output_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is not set")).join("cairo"); + let checksum_file = output_dir.join("checksum.txt"); + + // Calculate the current hash of the src directory + let current_hash = calculate_directory_hash(&src_dir); + + // Check if recompilation is necessary + if checksum_file.exists() { + let mut previous_hash = String::new(); + File::open(&checksum_file) + .expect("Failed to open checksum file") + .read_to_string(&mut previous_hash) + .expect("Failed to read checksum file"); + + if previous_hash == current_hash { + println!("No changes detected in src directory. Skipping compilation."); + return; + } + } + + // Create output directory + fs::create_dir_all(&output_dir).expect("Failed to create output directory"); + let output_file = output_dir.join("compiled.json"); + + // Run the cairo-compile command. + let status = Command::new(python_path.join("cairo-compile").to_str().expect("Failed to convert path to string")) + .arg(format!("--cairo_path={}:{}", workspace_root.display(), cairo_path.display())) + .arg(entrypoint_path.to_str().expect("Failed to convert path to string")) + .arg("--output") + .arg(output_file.to_str().expect("Failed to convert path to string")) + .status() + .expect("Failed to execute cairo-compile"); + + if !status.success() { + panic!("cairo-compile failed for file: {}", entrypoint_path.display()); + } + + // Save the new checksum + File::create(&checksum_file) + .expect("Failed to create checksum file") + .write_all(current_hash.as_bytes()) + .expect("Failed to write checksum file"); +} diff --git a/crates/sound_run/src/main.rs b/crates/sound_run/src/main.rs index 313dc9a8..f17ae02c 100644 --- a/crates/sound_run/src/main.rs +++ b/crates/sound_run/src/main.rs @@ -11,17 +11,14 @@ use cairo_vm::{ runners::cairo_runner::{CairoRunner, RunnerMode}, }, }; -use clap::{Parser, ValueHint}; +use clap::Parser; use sound_hint_processor::CustomHintProcessor; -use std::path::PathBuf; +use std::{env, path::PathBuf}; use types::{proofs::Proofs, HDPDryRunInput, HDPInput}; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] struct Args { - #[clap(value_parser, value_hint=ValueHint::FilePath)] - filename: PathBuf, - /// When using dynamic layout, it's parameters must be specified through a layout params file. #[clap(long = "layout", default_value = "plain", value_enum)] layout: LayoutName, #[structopt(long = "proof_mode")] @@ -47,10 +44,13 @@ fn main() -> Result<(), HdpOsError> { ..Default::default() }; - let program_file = std::fs::read(args.filename).map_err(HdpOsError::IO)?; + // Locate the compiled program file in the `OUT_DIR` folder. + let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is not set")); + let program_file_path = out_dir.join("cairo").join("compiled.json"); + + let program_file = std::fs::read(program_file_path.as_path()).map_err(HdpOsError::IO)?; let program_inputs: HDPDryRunInput = serde_json::from_slice(&std::fs::read(args.program_input).map_err(HdpOsError::IO)?)?; let program_proofs: Proofs = serde_json::from_slice(&std::fs::read(args.program_proofs).map_err(HdpOsError::IO)?)?; - // Load the Program let program = Program::from_bytes(&program_file, Some(cairo_run_config.entrypoint)).map_err(|e| HdpOsError::Runner(e.into()))?; From b6d0c54399dfb556bc974b102037cde7cfec9363 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 24 Dec 2024 09:46:41 +0100 Subject: [PATCH 55/75] cairo1 folder rename --- {cairo1_syscall_binding => cairo1}/README.md | 0 {cairo1_syscall_binding => cairo1}/Scarb.toml | 0 {cairo1_syscall_binding => cairo1}/src/evm.cairo | 0 {cairo1_syscall_binding => cairo1}/src/evm/account.cairo | 0 {cairo1_syscall_binding => cairo1}/src/evm/block_receipt.cairo | 0 {cairo1_syscall_binding => cairo1}/src/evm/block_tx.cairo | 0 {cairo1_syscall_binding => cairo1}/src/evm/header.cairo | 0 {cairo1_syscall_binding => cairo1}/src/evm/storage.cairo | 0 {cairo1_syscall_binding => cairo1}/src/lib.cairo | 0 {cairo1_syscall_binding => cairo1}/src/starknet.cairo | 0 {cairo1_syscall_binding => cairo1}/src/starknet/header.cairo | 0 {cairo1_syscall_binding => cairo1}/src/starknet/storage.cairo | 0 12 files changed, 0 insertions(+), 0 deletions(-) rename {cairo1_syscall_binding => cairo1}/README.md (100%) rename {cairo1_syscall_binding => cairo1}/Scarb.toml (100%) rename {cairo1_syscall_binding => cairo1}/src/evm.cairo (100%) rename {cairo1_syscall_binding => cairo1}/src/evm/account.cairo (100%) rename {cairo1_syscall_binding => cairo1}/src/evm/block_receipt.cairo (100%) rename {cairo1_syscall_binding => cairo1}/src/evm/block_tx.cairo (100%) rename {cairo1_syscall_binding => cairo1}/src/evm/header.cairo (100%) rename {cairo1_syscall_binding => cairo1}/src/evm/storage.cairo (100%) rename {cairo1_syscall_binding => cairo1}/src/lib.cairo (100%) rename {cairo1_syscall_binding => cairo1}/src/starknet.cairo (100%) rename {cairo1_syscall_binding => cairo1}/src/starknet/header.cairo (100%) rename {cairo1_syscall_binding => cairo1}/src/starknet/storage.cairo (100%) diff --git a/cairo1_syscall_binding/README.md b/cairo1/README.md similarity index 100% rename from cairo1_syscall_binding/README.md rename to cairo1/README.md diff --git a/cairo1_syscall_binding/Scarb.toml b/cairo1/Scarb.toml similarity index 100% rename from cairo1_syscall_binding/Scarb.toml rename to cairo1/Scarb.toml diff --git a/cairo1_syscall_binding/src/evm.cairo b/cairo1/src/evm.cairo similarity index 100% rename from cairo1_syscall_binding/src/evm.cairo rename to cairo1/src/evm.cairo diff --git a/cairo1_syscall_binding/src/evm/account.cairo b/cairo1/src/evm/account.cairo similarity index 100% rename from cairo1_syscall_binding/src/evm/account.cairo rename to cairo1/src/evm/account.cairo diff --git a/cairo1_syscall_binding/src/evm/block_receipt.cairo b/cairo1/src/evm/block_receipt.cairo similarity index 100% rename from cairo1_syscall_binding/src/evm/block_receipt.cairo rename to cairo1/src/evm/block_receipt.cairo diff --git a/cairo1_syscall_binding/src/evm/block_tx.cairo b/cairo1/src/evm/block_tx.cairo similarity index 100% rename from cairo1_syscall_binding/src/evm/block_tx.cairo rename to cairo1/src/evm/block_tx.cairo diff --git a/cairo1_syscall_binding/src/evm/header.cairo b/cairo1/src/evm/header.cairo similarity index 100% rename from cairo1_syscall_binding/src/evm/header.cairo rename to cairo1/src/evm/header.cairo diff --git a/cairo1_syscall_binding/src/evm/storage.cairo b/cairo1/src/evm/storage.cairo similarity index 100% rename from cairo1_syscall_binding/src/evm/storage.cairo rename to cairo1/src/evm/storage.cairo diff --git a/cairo1_syscall_binding/src/lib.cairo b/cairo1/src/lib.cairo similarity index 100% rename from cairo1_syscall_binding/src/lib.cairo rename to cairo1/src/lib.cairo diff --git a/cairo1_syscall_binding/src/starknet.cairo b/cairo1/src/starknet.cairo similarity index 100% rename from cairo1_syscall_binding/src/starknet.cairo rename to cairo1/src/starknet.cairo diff --git a/cairo1_syscall_binding/src/starknet/header.cairo b/cairo1/src/starknet/header.cairo similarity index 100% rename from cairo1_syscall_binding/src/starknet/header.cairo rename to cairo1/src/starknet/header.cairo diff --git a/cairo1_syscall_binding/src/starknet/storage.cairo b/cairo1/src/starknet/storage.cairo similarity index 100% rename from cairo1_syscall_binding/src/starknet/storage.cairo rename to cairo1/src/starknet/storage.cairo From 564c72ae58b1ed64e90cd2bda134db663c643076 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 24 Dec 2024 10:03:15 +0100 Subject: [PATCH 56/75] build script native cargo support for changes --- crates/dry_run/build.rs | 51 +-------------------------------------- crates/sound_run/build.rs | 51 +-------------------------------------- 2 files changed, 2 insertions(+), 100 deletions(-) diff --git a/crates/dry_run/build.rs b/crates/dry_run/build.rs index b11cac15..d503b401 100644 --- a/crates/dry_run/build.rs +++ b/crates/dry_run/build.rs @@ -1,34 +1,7 @@ -use sha2::{Digest, Sha256}; -use std::fs::File; -use std::io::{Read, Write}; use std::path::PathBuf; use std::process::Command; use std::{env, fs}; -fn calculate_directory_hash(dir: &PathBuf) -> String { - let mut hasher = Sha256::new(); - let mut entries: Vec<_> = fs::read_dir(dir) - .unwrap() - .filter_map(Result::ok) - .filter(|entry| { - let path = entry.path(); - path.is_file() && path.extension().map_or(false, |ext| ext == "cairo") - }) - .collect(); - - entries.sort_by_key(|entry| entry.path()); - - for entry in entries { - let path = entry.path(); - let mut file = File::open(&path).unwrap(); - let mut buffer = Vec::new(); - file.read_to_end(&mut buffer).unwrap(); - hasher.update(buffer); - } - - format!("{:x}", hasher.finalize()) -} - fn main() { let workspace_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is not set")).join("../../"); let python_path = workspace_root.join("venv/bin"); @@ -36,24 +9,8 @@ fn main() { let src_dir = workspace_root.join("src"); let entrypoint_path = src_dir.join("contract_bootloader").join("contract_dry_run.cairo"); let output_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is not set")).join("cairo"); - let checksum_file = output_dir.join("checksum.txt"); - - // Calculate the current hash of the src directory - let current_hash = calculate_directory_hash(&src_dir); - // Check if recompilation is necessary - if checksum_file.exists() { - let mut previous_hash = String::new(); - File::open(&checksum_file) - .expect("Failed to open checksum file") - .read_to_string(&mut previous_hash) - .expect("Failed to read checksum file"); - - if previous_hash == current_hash { - println!("No changes detected in src directory. Skipping compilation."); - return; - } - } + println!("cargo::rerun-if-changed={}", src_dir.display()); // Create output directory fs::create_dir_all(&output_dir).expect("Failed to create output directory"); @@ -71,10 +28,4 @@ fn main() { if !status.success() { panic!("cairo-compile failed for file: {}", entrypoint_path.display()); } - - // Save the new checksum - File::create(&checksum_file) - .expect("Failed to create checksum file") - .write_all(current_hash.as_bytes()) - .expect("Failed to write checksum file"); } diff --git a/crates/sound_run/build.rs b/crates/sound_run/build.rs index a9c28d73..01e5ab57 100644 --- a/crates/sound_run/build.rs +++ b/crates/sound_run/build.rs @@ -1,34 +1,7 @@ -use sha2::{Digest, Sha256}; -use std::fs::File; -use std::io::{Read, Write}; use std::path::PathBuf; use std::process::Command; use std::{env, fs}; -fn calculate_directory_hash(dir: &PathBuf) -> String { - let mut hasher = Sha256::new(); - let mut entries: Vec<_> = fs::read_dir(dir) - .unwrap() - .filter_map(Result::ok) - .filter(|entry| { - let path = entry.path(); - path.is_file() && path.extension().map_or(false, |ext| ext == "cairo") - }) - .collect(); - - entries.sort_by_key(|entry| entry.path()); - - for entry in entries { - let path = entry.path(); - let mut file = File::open(&path).unwrap(); - let mut buffer = Vec::new(); - file.read_to_end(&mut buffer).unwrap(); - hasher.update(buffer); - } - - format!("{:x}", hasher.finalize()) -} - fn main() { let workspace_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is not set")).join("../../"); let python_path = workspace_root.join("venv/bin"); @@ -36,24 +9,8 @@ fn main() { let src_dir = workspace_root.join("src"); let entrypoint_path = src_dir.join("hdp.cairo"); let output_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is not set")).join("cairo"); - let checksum_file = output_dir.join("checksum.txt"); - - // Calculate the current hash of the src directory - let current_hash = calculate_directory_hash(&src_dir); - // Check if recompilation is necessary - if checksum_file.exists() { - let mut previous_hash = String::new(); - File::open(&checksum_file) - .expect("Failed to open checksum file") - .read_to_string(&mut previous_hash) - .expect("Failed to read checksum file"); - - if previous_hash == current_hash { - println!("No changes detected in src directory. Skipping compilation."); - return; - } - } + println!("cargo::rerun-if-changed={}", src_dir.display()); // Create output directory fs::create_dir_all(&output_dir).expect("Failed to create output directory"); @@ -71,10 +28,4 @@ fn main() { if !status.success() { panic!("cairo-compile failed for file: {}", entrypoint_path.display()); } - - // Save the new checksum - File::create(&checksum_file) - .expect("Failed to create checksum file") - .write_all(current_hash.as_bytes()) - .expect("Failed to write checksum file"); } From 002488781959b38f766fb1da3fa9af209535114c Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 24 Dec 2024 10:45:57 +0100 Subject: [PATCH 57/75] bootloader task execution in sound run --- Scarb.toml | 2 +- crates/dry_hint_processor/src/lib.rs | 1 - .../src/syscall_handler/mod.rs | 18 +----- .../src/contract_bootloader/dict_manager.rs | 2 +- crates/hints/src/lib.rs | 1 + crates/hints/src/segments.rs | 18 +++++- crates/sound_hint_processor/src/lib.rs | 5 +- .../src/syscall_handler/evm/account.rs | 2 +- .../src/syscall_handler/evm/header.rs | 2 +- .../src/syscall_handler/evm/storage.rs | 2 +- .../execute_syscalls.cairo | 58 +++++++++---------- src/hdp.cairo | 56 +++++++++--------- 12 files changed, 84 insertions(+), 83 deletions(-) diff --git a/Scarb.toml b/Scarb.toml index ade1ac06..6b0f84d7 100644 --- a/Scarb.toml +++ b/Scarb.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2023_11" members = [ - "cairo1_syscall_binding" + "cairo1" ] [workspace.dependencies] diff --git a/crates/dry_hint_processor/src/lib.rs b/crates/dry_hint_processor/src/lib.rs index 38d9cd75..bca618dc 100644 --- a/crates/dry_hint_processor/src/lib.rs +++ b/crates/dry_hint_processor/src/lib.rs @@ -49,7 +49,6 @@ impl CustomHintProcessor { #[rustfmt::skip] fn hints() -> HashMap { let mut hints = hints(); - hints.insert(syscall_handler::DRY_RUN_SYSCALL_HANDLER_CREATE.into(), syscall_handler::dry_run_syscall_handler_create); hints.insert(syscall_handler::SYSCALL_HANDLER_CREATE.into(), syscall_handler::syscall_handler_create); hints.insert(syscall_handler::SYSCALL_HANDLER_SET_SYSCALL_PTR.into(), syscall_handler::syscall_handler_set_syscall_ptr); hints.insert(syscall_handler::ENTER_SCOPE_SYSCALL_HANDLER.into(), syscall_handler::enter_scope_syscall_handler); diff --git a/crates/dry_hint_processor/src/syscall_handler/mod.rs b/crates/dry_hint_processor/src/syscall_handler/mod.rs index 4c1d50ad..f9bdf1f3 100644 --- a/crates/dry_hint_processor/src/syscall_handler/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/mod.rs @@ -11,29 +11,13 @@ use std::{any::Any, collections::HashMap}; pub mod evm; pub mod starknet; -pub const SYSCALL_HANDLER_CREATE: &str = "if 'syscall_handler' not in globals():\n from contract_bootloader.syscall_handler import SyscallHandler\n syscall_handler = SyscallHandler(segments=segments, dict_manager=__dict_manager)"; +pub const SYSCALL_HANDLER_CREATE: &str = "from contract_bootloader.dryrun_syscall_handler import DryRunSyscallHandler\nsyscall_handler = DryRunSyscallHandler(segments=segments, dict_manager=__dict_manager)"; pub fn syscall_handler_create( _vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, _hint_data: &HintProcessorData, _constants: &HashMap, -) -> Result<(), HintError> { - if let Err(HintError::VariableNotInScopeError(_)) = exec_scopes.get::(vars::scopes::SYSCALL_HANDLER) { - let syscall_handler = SyscallHandlerWrapper::new(); - exec_scopes.insert_value(vars::scopes::SYSCALL_HANDLER, syscall_handler); - } - - Ok(()) -} - -pub const DRY_RUN_SYSCALL_HANDLER_CREATE: &str = "from contract_bootloader.dryrun_syscall_handler import DryRunSyscallHandler\nsyscall_handler = DryRunSyscallHandler(segments=segments, dict_manager=__dict_manager)"; - -pub fn dry_run_syscall_handler_create( - _vm: &mut VirtualMachine, - exec_scopes: &mut ExecutionScopes, - _hint_data: &HintProcessorData, - _constants: &HashMap, ) -> Result<(), HintError> { let syscall_handler = SyscallHandlerWrapper::new(); exec_scopes.insert_value(vars::scopes::SYSCALL_HANDLER, syscall_handler); diff --git a/crates/hints/src/contract_bootloader/dict_manager.rs b/crates/hints/src/contract_bootloader/dict_manager.rs index 8758f02f..f9e66ec3 100644 --- a/crates/hints/src/contract_bootloader/dict_manager.rs +++ b/crates/hints/src/contract_bootloader/dict_manager.rs @@ -16,7 +16,7 @@ pub fn dict_manager_create( _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - if let Err(HintError::VariableNotInScopeError(_)) = exec_scopes.get::(vars::scopes::DICT_MANAGER) { + if let Err(HintError::VariableNotInScopeError(_)) = exec_scopes.get_dict_manager() { let dict_manager = DictManager::new(); exec_scopes.insert_value(vars::scopes::DICT_MANAGER, Rc::new(RefCell::new(dict_manager))); } diff --git a/crates/hints/src/lib.rs b/crates/hints/src/lib.rs index 39120f8f..03bdcf54 100644 --- a/crates/hints/src/lib.rs +++ b/crates/hints/src/lib.rs @@ -51,6 +51,7 @@ pub fn hints() -> HashMap { hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_OFFSET.into(), segments::segments_add_evm_memorizer_offset); hints.insert(segments::SEGMENTS_ADD_EVM_STARKNET_MEMORIZER_INDEX.into(), segments::segments_add_evm_starknet_memorizer_index); hints.insert(segments::SEGMENTS_ADD_STARKNET_MEMORIZER_OFFSET.into(), segments::segments_add_starknet_memorizer_offset); + hints.insert(segments::MMR_METAS_LEN_COUNTER.into(), segments::mmr_metas_len_counter); hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY.into(), verifiers::evm::account_verifier::hint_account_key); hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY_LEADING_ZEROS.into(), verifiers::evm::account_verifier::hint_account_key_leading_zeros); hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_AT.into(), verifiers::evm::account_verifier::hint_account_proof_at); diff --git a/crates/hints/src/segments.rs b/crates/hints/src/segments.rs index 20436224..c317ee2e 100644 --- a/crates/hints/src/segments.rs +++ b/crates/hints/src/segments.rs @@ -1,7 +1,7 @@ use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, - hint_utils::{get_relocatable_from_var_name, insert_value_into_ap}, + hint_utils::{get_integer_from_var_name, get_relocatable_from_var_name, insert_value_into_ap}, }, types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, @@ -80,3 +80,19 @@ pub fn segments_add_starknet_memorizer_offset( let memorizer = get_relocatable_from_var_name("starknet_memorizer", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; insert_value_into_ap(vm, Felt252::from(memorizer.offset)) } + +pub const MMR_METAS_LEN_COUNTER: &str = "memory[ap] = 1 if (ids.mmr_metas_len == ids.counter) else 0"; + +pub fn mmr_metas_len_counter( + vm: &mut VirtualMachine, + _exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let mmr_metas_len = get_integer_from_var_name("mmr_metas_len", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + let counter = get_integer_from_var_name("counter", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + + let insert = if mmr_metas_len == counter { Felt252::ONE } else { Felt252::ZERO }; + + insert_value_into_ap(vm, insert) +} diff --git a/crates/sound_hint_processor/src/lib.rs b/crates/sound_hint_processor/src/lib.rs index e9417b7b..330b14e7 100644 --- a/crates/sound_hint_processor/src/lib.rs +++ b/crates/sound_hint_processor/src/lib.rs @@ -48,7 +48,10 @@ impl CustomHintProcessor { #[rustfmt::skip] fn hints() -> HashMap { - let hints = hints(); + let mut hints = hints(); + hints.insert(syscall_handler::SYSCALL_HANDLER_CREATE.into(), syscall_handler::syscall_handler_create); + hints.insert(syscall_handler::SYSCALL_HANDLER_SET_SYSCALL_PTR.into(), syscall_handler::syscall_handler_set_syscall_ptr); + hints.insert(syscall_handler::ENTER_SCOPE_SYSCALL_HANDLER.into(), syscall_handler::enter_scope_syscall_handler); hints } diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs index c88906e3..847bf47b 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs @@ -32,6 +32,6 @@ impl CallHandler for AccountCallHandler { } fn handle(_key: Self::Key, _function_id: Self::Id) -> SyscallResult { - todo!() + Ok(Uint256::from(0_u64)) } } diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs index 5c8059bf..63cc4a18 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs @@ -32,6 +32,6 @@ impl CallHandler for HeaderCallHandler { } fn handle(_key: Self::Key, _function_id: Self::Id) -> SyscallResult { - todo!() + Ok(Uint256::from(0_u64)) } } diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs index 41b4e10e..ab43ac8e 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs @@ -32,6 +32,6 @@ impl CallHandler for StorageCallHandler { } fn handle(_key: Self::Key, _function_id: Self::Id) -> SyscallResult { - todo!() + Ok(Uint256::from(0_u64)) } } diff --git a/src/contract_bootloader/execute_syscalls.cairo b/src/contract_bootloader/execute_syscalls.cairo index c1cdea2e..49117d8a 100644 --- a/src/contract_bootloader/execute_syscalls.cairo +++ b/src/contract_bootloader/execute_syscalls.cairo @@ -105,35 +105,35 @@ func execute_call_contract{ let layout = chain_id_to_layout(call_contract_request.calldata_start[2]); let output_ptr = call_contract_response.retdata_start; - if (layout == Layout.EVM) { - with output_ptr { - let output_len = EvmStateAccess.read_and_decode( - params=call_contract_request.calldata_start + 2, - state_access_type=state_access_type, - field=field, - decoder_target=EvmDecoderTarget.UINT256, - ); - - return (); - } - } - - if (layout == Layout.STARKNET) { - with output_ptr { - let output_len = StarknetStateAccess.read_and_decode( - params=call_contract_request.calldata_start + 2, - state_access_type=state_access_type, - field=field, - decoder_target=StarknetDecoderTarget.FELT, - as_be=1, - ); - } - - return (); - } - - // Unknown DictId - assert 1 = 0; + // if (layout == Layout.EVM) { + // with output_ptr { + // let output_len = EvmStateAccess.read_and_decode( + // params=call_contract_request.calldata_start + 2, + // state_access_type=state_access_type, + // field=field, + // decoder_target=EvmDecoderTarget.UINT256, + // ); + + // return (); + // } + // } + + // if (layout == Layout.STARKNET) { + // with output_ptr { + // let output_len = StarknetStateAccess.read_and_decode( + // params=call_contract_request.calldata_start + 2, + // state_access_type=state_access_type, + // field=field, + // decoder_target=StarknetDecoderTarget.FELT, + // as_be=1, + // ); + // } + + // return (); + // } + + // // Unknown DictId + // assert 1 = 0; return (); } diff --git a/src/hdp.cairo b/src/hdp.cairo index a0cfe719..96ba97b9 100644 --- a/src/hdp.cairo +++ b/src/hdp.cairo @@ -102,36 +102,34 @@ func run{ let starknet_key_hasher_ptr = StarknetStateAccess.init(); let starknet_decoder_ptr = StarknetDecoder.init(); - return (); + let (program_hash, result) = compute_tasks{ + pedersen_ptr=pedersen_ptr, + range_check_ptr=range_check_ptr, + ecdsa_ptr=ecdsa_ptr, + bitwise_ptr=bitwise_ptr, + ec_op_ptr=ec_op_ptr, + keccak_ptr=keccak_ptr, + poseidon_ptr=poseidon_ptr, + pow2_array=pow2_array, + evm_memorizer=evm_memorizer, + evm_decoder_ptr=evm_decoder_ptr, + evm_key_hasher_ptr=evm_key_hasher_ptr, + starknet_memorizer=starknet_memorizer, + starknet_decoder_ptr=starknet_decoder_ptr, + starknet_key_hasher_ptr=starknet_key_hasher_ptr, + }(); - // let (program_hash, result) = compute_tasks{ - // pedersen_ptr=pedersen_ptr, - // range_check_ptr=range_check_ptr, - // ecdsa_ptr=ecdsa_ptr, - // bitwise_ptr=bitwise_ptr, - // ec_op_ptr=ec_op_ptr, - // keccak_ptr=keccak_ptr, - // poseidon_ptr=poseidon_ptr, - // pow2_array=pow2_array, - // evm_memorizer=evm_memorizer, - // evm_decoder_ptr=evm_decoder_ptr, - // evm_key_hasher_ptr=evm_key_hasher_ptr, - // starknet_memorizer=starknet_memorizer, - // starknet_decoder_ptr=starknet_decoder_ptr, - // starknet_key_hasher_ptr=starknet_key_hasher_ptr, - // }(); - - // // Post Verification Checks: Ensure dict consistency - // default_dict_finalize(evm_memorizer_start, evm_memorizer, BareMemorizer.DEFAULT_VALUE); - // default_dict_finalize( - // starknet_memorizer_start, starknet_memorizer, BareMemorizer.DEFAULT_VALUE - // ); - - // write_output_ptr{output_ptr=output_ptr}( - // mmr_metas=mmr_metas, mmr_metas_len=mmr_metas_len, program_hash=program_hash, result=result - // ); - - // return (); + // Post Verification Checks: Ensure dict consistency + default_dict_finalize(evm_memorizer_start, evm_memorizer, BareMemorizer.DEFAULT_VALUE); + default_dict_finalize( + starknet_memorizer_start, starknet_memorizer, BareMemorizer.DEFAULT_VALUE + ); + + write_output_ptr{output_ptr=output_ptr}( + mmr_metas=mmr_metas, mmr_metas_len=mmr_metas_len, program_hash=program_hash, result=result + ); + + return (); } func compute_tasks{ From 462b81bcbb4f420a74faaa5d30f2aad5c2285fba Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 24 Dec 2024 12:38:12 +0100 Subject: [PATCH 58/75] fixes --- crates/dry_hint_processor/src/lib.rs | 3 +- .../src/syscall_handler/mod.rs | 12 +++ crates/hints/src/lib.rs | 88 +++++++++---------- crates/sound_hint_processor/src/lib.rs | 2 +- 4 files changed, 59 insertions(+), 46 deletions(-) diff --git a/crates/dry_hint_processor/src/lib.rs b/crates/dry_hint_processor/src/lib.rs index bca618dc..8a2592f5 100644 --- a/crates/dry_hint_processor/src/lib.rs +++ b/crates/dry_hint_processor/src/lib.rs @@ -49,9 +49,10 @@ impl CustomHintProcessor { #[rustfmt::skip] fn hints() -> HashMap { let mut hints = hints(); + hints.insert(syscall_handler::ENTER_SCOPE_SYSCALL_HANDLER.into(), syscall_handler::enter_scope_syscall_handler); + hints.insert(syscall_handler::SYSCALL_HANDLER_CREATE_MOCK.into(), syscall_handler::syscall_handler_create_mock); hints.insert(syscall_handler::SYSCALL_HANDLER_CREATE.into(), syscall_handler::syscall_handler_create); hints.insert(syscall_handler::SYSCALL_HANDLER_SET_SYSCALL_PTR.into(), syscall_handler::syscall_handler_set_syscall_ptr); - hints.insert(syscall_handler::ENTER_SCOPE_SYSCALL_HANDLER.into(), syscall_handler::enter_scope_syscall_handler); hints } diff --git a/crates/dry_hint_processor/src/syscall_handler/mod.rs b/crates/dry_hint_processor/src/syscall_handler/mod.rs index f9bdf1f3..3972560b 100644 --- a/crates/dry_hint_processor/src/syscall_handler/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/mod.rs @@ -11,6 +11,18 @@ use std::{any::Any, collections::HashMap}; pub mod evm; pub mod starknet; +pub const SYSCALL_HANDLER_CREATE_MOCK: &str = "if 'syscall_handler' not in globals():\n from contract_bootloader.syscall_handler import SyscallHandler\n syscall_handler = SyscallHandler(segments=segments, dict_manager=__dict_manager)"; + +pub fn syscall_handler_create_mock( + _vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + exec_scopes.get::(vars::scopes::SYSCALL_HANDLER)?; + Ok(()) +} + pub const SYSCALL_HANDLER_CREATE: &str = "from contract_bootloader.dryrun_syscall_handler import DryRunSyscallHandler\nsyscall_handler = DryRunSyscallHandler(segments=segments, dict_manager=__dict_manager)"; pub fn syscall_handler_create( diff --git a/crates/hints/src/lib.rs b/crates/hints/src/lib.rs index 03bdcf54..fd800fd1 100644 --- a/crates/hints/src/lib.rs +++ b/crates/hints/src/lib.rs @@ -27,100 +27,100 @@ pub type ExtensiveHintImpl = #[rustfmt::skip] pub fn hints() -> HashMap { let mut hints = HashMap::::new(); + hints.insert(contract_bootloader::builtins::SELECT_BUILTIN.into(), contract_bootloader::builtins::select_builtin); + hints.insert(contract_bootloader::builtins::SELECTED_BUILTINS.into(), contract_bootloader::builtins::selected_builtins); + hints.insert(contract_bootloader::builtins::UPDATE_BUILTIN_PTRS.into(), contract_bootloader::builtins::update_builtin_ptrs); hints.insert(contract_bootloader::contract_class::LOAD_CONTRACT_CLASS.into(), contract_bootloader::contract_class::load_contract_class); hints.insert(contract_bootloader::dict_manager::DICT_MANAGER_CREATE.into(), contract_bootloader::dict_manager::dict_manager_create); hints.insert(contract_bootloader::params::LOAD_PARMAS.into(), contract_bootloader::params::load_parmas); - hints.insert(contract_bootloader::builtins::UPDATE_BUILTIN_PTRS.into(), contract_bootloader::builtins::update_builtin_ptrs); - hints.insert(contract_bootloader::builtins::SELECTED_BUILTINS.into(), contract_bootloader::builtins::selected_builtins); - hints.insert(contract_bootloader::builtins::SELECT_BUILTIN.into(), contract_bootloader::builtins::select_builtin); hints.insert(decoder::evm::has_type_prefix::HINT_HAS_TYPE_PREFIX.into(), decoder::evm::has_type_prefix::hint_has_type_prefix); hints.insert(decoder::evm::is_byzantium::HINT_IS_BYZANTIUM.into(), decoder::evm::is_byzantium::hint_is_byzantium); hints.insert(decoder::evm::v_is_encoded::HINT_V_IS_ENCODED.into(), decoder::evm::v_is_encoded::hint_v_is_encoded); - hints.insert(merkle::HINT_TARGET_TASK_HASH.into(), merkle::hint_target_task_hash); hints.insert(merkle::HINT_IS_LEFT_SMALLER.into(), merkle::hint_is_left_smaller); - hints.insert(rlp::divmod::HINT_DIVMOD_VALUE.into(), rlp::divmod::hint_divmod_value); + hints.insert(merkle::HINT_TARGET_TASK_HASH.into(), merkle::hint_target_task_hash); + hints.insert(print::PROGRAM_HASH.into(), print::program_hash); hints.insert(rlp::divmod::HINT_DIVMOD_RLP.into(), rlp::divmod::hint_divmod_rlp); + hints.insert(rlp::divmod::HINT_DIVMOD_VALUE.into(), rlp::divmod::hint_divmod_value); hints.insert(rlp::item_type::HINT_IS_LONG.into(), rlp::item_type::hint_is_long); hints.insert(rlp::item_type::HINT_ITEM_TYPE.into(), rlp::item_type::hint_item_type); - hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS.into(), rlp::processed_words::hint_processed_words); hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS_RLP.into(), rlp::processed_words::hint_processed_words_rlp); - hints.insert(print::PROGRAM_HASH.into(), print::program_hash); - hints.insert(segments::SEGMENTS_ADD.into(), segments::segments_add); - hints.insert(segments::SEGMENTS_ADD_FP.into(), segments::segments_add_fp); - hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_SEGMENT_INDEX.into(), segments::segments_add_evm_memorizer_segment_index); + hints.insert(rlp::processed_words::HINT_PROCESSED_WORDS.into(), rlp::processed_words::hint_processed_words); + hints.insert(segments::MMR_METAS_LEN_COUNTER.into(), segments::mmr_metas_len_counter); hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_OFFSET.into(), segments::segments_add_evm_memorizer_offset); + hints.insert(segments::SEGMENTS_ADD_EVM_MEMORIZER_SEGMENT_INDEX.into(), segments::segments_add_evm_memorizer_segment_index); hints.insert(segments::SEGMENTS_ADD_EVM_STARKNET_MEMORIZER_INDEX.into(), segments::segments_add_evm_starknet_memorizer_index); + hints.insert(segments::SEGMENTS_ADD_FP.into(), segments::segments_add_fp); hints.insert(segments::SEGMENTS_ADD_STARKNET_MEMORIZER_OFFSET.into(), segments::segments_add_starknet_memorizer_offset); - hints.insert(segments::MMR_METAS_LEN_COUNTER.into(), segments::mmr_metas_len_counter); - hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY.into(), verifiers::evm::account_verifier::hint_account_key); + hints.insert(segments::SEGMENTS_ADD.into(), segments::segments_add); hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY_LEADING_ZEROS.into(), verifiers::evm::account_verifier::hint_account_key_leading_zeros); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_KEY.into(), verifiers::evm::account_verifier::hint_account_key); hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_AT.into(), verifiers::evm::account_verifier::hint_account_proof_at); hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BLOCK_NUMBER.into(), verifiers::evm::account_verifier::hint_account_proof_block_number); hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_BYTES_LEN.into(), verifiers::evm::account_verifier::hint_account_proof_bytes_len); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_LEN.into(), verifiers::evm::account_verifier::hint_account_proof_len); + hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOFS_LEN.into(), verifiers::evm::account_verifier::hint_account_proofs_len); hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOFS_LEN.into(), verifiers::evm::account_verifier::hint_account_proofs_len); hints.insert(verifiers::evm::account_verifier::HINT_BATCH_ACCOUNTS_LEN.into(), verifiers::evm::account_verifier::hint_batch_accounts_len); hints.insert(verifiers::evm::account_verifier::HINT_GET_ACCOUNT_ADDRESS.into(), verifiers::evm::account_verifier::hint_get_account_address); hints.insert(verifiers::evm::account_verifier::HINT_GET_MPT_PROOF.into(), verifiers::evm::account_verifier::hint_get_mpt_proof); - hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOF_LEN.into(), verifiers::evm::account_verifier::hint_account_proof_len); - hints.insert(verifiers::evm::account_verifier::HINT_ACCOUNT_PROOFS_LEN.into(), verifiers::evm::account_verifier::hint_account_proofs_len); - hints.insert(verifiers::evm::transaction_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), verifiers::evm::transaction_verifier::hint_batch_transactions_len); - hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX.into(), verifiers::evm::transaction_verifier::hint_set_tx); - hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY.into(), verifiers::evm::transaction_verifier::hint_set_tx_key); - hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY_LEADING_ZEROS.into(), verifiers::evm::transaction_verifier::hint_set_tx_key_leading_zeros); - hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_PROOF_LEN.into(), verifiers::evm::transaction_verifier::hint_set_tx_proof_len); - hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), verifiers::evm::transaction_verifier::hint_set_tx_block_number); - hints.insert(verifiers::evm::transaction_verifier::HINT_PROOF_BYTES_LEN.into(), verifiers::evm::transaction_verifier::hint_proof_bytes_len); - hints.insert(verifiers::evm::header_verifier::HINT_VM_ENTER_SCOPE.into(), verifiers::evm::header_verifier::hint_vm_enter_scope); hints.insert(verifiers::evm::header_verifier::HINT_HEADERS_WITH_MMR_HEADERS_LEN.into(), verifiers::evm::header_verifier::hint_headers_with_mmr_headers_len); hints.insert(verifiers::evm::header_verifier::HINT_LEAF_IDX.into(), verifiers::evm::header_verifier::hint_leaf_idx); hints.insert(verifiers::evm::header_verifier::HINT_MMR_PATH_LEN.into(), verifiers::evm::header_verifier::hint_mmr_path_len); hints.insert(verifiers::evm::header_verifier::HINT_MMR_PATH.into(), verifiers::evm::header_verifier::hint_mmr_path); hints.insert(verifiers::evm::header_verifier::HINT_RLP_LEN.into(), verifiers::evm::header_verifier::hint_rlp_len); hints.insert(verifiers::evm::header_verifier::HINT_SET_HEADER.into(), verifiers::evm::header_verifier::hint_set_header); + hints.insert(verifiers::evm::header_verifier::HINT_VM_ENTER_SCOPE.into(), verifiers::evm::header_verifier::hint_vm_enter_scope); hints.insert(verifiers::evm::receipt_verifier::HINT_BATCH_RECEIPTS_LEN.into(), verifiers::evm::receipt_verifier::hint_batch_receipts_len); hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_BLOCK_NUMBER.into(), verifiers::evm::receipt_verifier::hint_receipt_block_number); - hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY.into(), verifiers::evm::receipt_verifier::hint_receipt_key); hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY_LEADING_ZEROS.into(), verifiers::evm::receipt_verifier::hint_receipt_key_leading_zeros); - hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_len); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY.into(), verifiers::evm::receipt_verifier::hint_receipt_key); hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_BYTES_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_bytes_len); + hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_PROOF_LEN.into(), verifiers::evm::receipt_verifier::hint_receipt_proof_len); hints.insert(verifiers::evm::receipt_verifier::HINT_SET_RECEIPT.into(), verifiers::evm::receipt_verifier::hint_set_receipt); hints.insert(verifiers::evm::storage_item_verifier::HINT_BATCH_STORAGES_LEN.into(), verifiers::evm::storage_item_verifier::hint_batch_storages_len); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_BATCH_STORAGES.into(), verifiers::evm::storage_item_verifier::hint_set_batch_storages); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_proof_len); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_BLOCK_NUMBER.into(), verifiers::evm::storage_item_verifier::hint_set_proof_block_number); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_PROOF_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_proof_len); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY_LEADING_ZEROS.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key_leading_zeros); - hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOFS_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_storage_proofs_len); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_KEY.into(), verifiers::evm::storage_item_verifier::hint_set_storage_key); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOF_AT.into(), verifiers::evm::storage_item_verifier::hint_set_storage_proof_at); + hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_PROOFS_LEN.into(), verifiers::evm::storage_item_verifier::hint_set_storage_proofs_len); hints.insert(verifiers::evm::storage_item_verifier::HINT_SET_STORAGE_SLOT.into(), verifiers::evm::storage_item_verifier::hint_set_storage_slot); - hints.insert(verifiers::verify::HINT_VM_ENTER_SCOPE.into(), verifiers::verify::hint_vm_enter_scope); - hints.insert(verifiers::verify::HINT_HEADERS_WITH_MMR_LEN.into(), verifiers::verify::hint_headers_with_mmr_headers_len); - hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_PEAKS_LEN.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_peaks_len); + hints.insert(verifiers::evm::transaction_verifier::HINT_BATCH_TRANSACTIONS_LEN.into(), verifiers::evm::transaction_verifier::hint_batch_transactions_len); + hints.insert(verifiers::evm::transaction_verifier::HINT_PROOF_BYTES_LEN.into(), verifiers::evm::transaction_verifier::hint_proof_bytes_len); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_BLOCK_NUMBER.into(), verifiers::evm::transaction_verifier::hint_set_tx_block_number); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY_LEADING_ZEROS.into(), verifiers::evm::transaction_verifier::hint_set_tx_key_leading_zeros); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_KEY.into(), verifiers::evm::transaction_verifier::hint_set_tx_key); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX_PROOF_LEN.into(), verifiers::evm::transaction_verifier::hint_set_tx_proof_len); + hints.insert(verifiers::evm::transaction_verifier::HINT_SET_TX.into(), verifiers::evm::transaction_verifier::hint_set_tx); hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_ID.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_id); + hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_PEAKS_LEN.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_peaks_len); hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_ROOT.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_root); hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_SIZE.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_size); hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_PEAKS.into(), verifiers::mmr_verifier::hint_headers_with_mmr_peaks); hints.insert(verifiers::utils::HINT_PRINT_TASK_RESULT.into(), verifiers::utils::hint_print_task_result); + hints.insert(verifiers::verify::HINT_HEADERS_WITH_MMR_LEN.into(), verifiers::verify::hint_headers_with_mmr_headers_len); + hints.insert(verifiers::verify::HINT_VM_ENTER_SCOPE.into(), verifiers::verify::hint_vm_enter_scope); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::bit_length::HINT_BIT_LENGTH.into(), eth_essentials_cairo_vm_hints::hints::lib::bit_length::hint_bit_length); hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mmr::bit_length::MMR_BIT_LENGTH.into(), eth_essentials_cairo_vm_hints::hints::lib::mmr::bit_length::mmr_bit_length); hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mmr::left_child::MMR_LEFT_CHILD.into(), eth_essentials_cairo_vm_hints::hints::lib::mmr::left_child::mmr_left_child); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::bit_length::HINT_BIT_LENGTH.into(), eth_essentials_cairo_vm_hints::hints::lib::bit_length::hint_bit_length); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::assert::HINT_ASSERT_INTEGER_DIV.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::assert::hint_assert_integer_div); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::HINT_VALUE_DIV.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::hint_value_div); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::HINT_VALUE_8.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::hint_value_8); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::trailing_zeroes::HINT_TRAILING_ZEROES_BYTES.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::trailing_zeroes::hint_trailing_zeroes_bytes); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_NEEDS_NEXT_WORD.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_needs_next_word); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_FIRST_ITEM_TYPE.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_first_item_type); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_ITEM_TYPE.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_item_type); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_LONG_SHORT_LIST.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_long_short_list); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_SECOND_ITEM_TYPE.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_second_item_type); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::assert::HINT_EXPECTED_NIBBLE.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::assert::hint_expected_nibble); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::divmod::HINT_POW_CUT.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::divmod::hint_pow_cut); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::leading_zeros::HINT_EXPECTED_NIBBLE.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::leading_zeros::hint_expected_nibble); hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_IS_ZERO.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_is_zero); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_NEEDS_NEXT_WORD_ENDING.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_needs_next_word_ending); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_NEEDS_NEXT_WORD.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_needs_next_word); hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_NIBBLE_FROM_LOW.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_nibble_from_low); hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_WORDS_LOOP.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_words_loop); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::HINT_NEEDS_NEXT_WORD_ENDING.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::nibbles::hint_needs_next_word_ending); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::leading_zeros::HINT_EXPECTED_NIBBLE.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::leading_zeros::hint_expected_nibble); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::assert::HINT_EXPECTED_NIBBLE.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::assert::hint_expected_nibble); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::rlp_little::divmod::HINT_POW_CUT.into(), eth_essentials_cairo_vm_hints::hints::lib::rlp_little::divmod::hint_pow_cut); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_LONG_SHORT_LIST.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_long_short_list); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_FIRST_ITEM_TYPE.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_first_item_type); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_SECOND_ITEM_TYPE.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_second_item_type); - hints.insert(eth_essentials_cairo_vm_hints::hints::lib::mpt::HINT_ITEM_TYPE.into(), eth_essentials_cairo_vm_hints::hints::lib::mpt::hint_item_type); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::assert::HINT_ASSERT_INTEGER_DIV.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::assert::hint_assert_integer_div); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::HINT_VALUE_8.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::hint_value_8); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::HINT_VALUE_DIV.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::divmod::hint_value_div); + hints.insert(eth_essentials_cairo_vm_hints::hints::lib::utils::trailing_zeroes::HINT_TRAILING_ZEROES_BYTES.into(), eth_essentials_cairo_vm_hints::hints::lib::utils::trailing_zeroes::hint_trailing_zeroes_bytes); hints } diff --git a/crates/sound_hint_processor/src/lib.rs b/crates/sound_hint_processor/src/lib.rs index 330b14e7..843b1e43 100644 --- a/crates/sound_hint_processor/src/lib.rs +++ b/crates/sound_hint_processor/src/lib.rs @@ -49,9 +49,9 @@ impl CustomHintProcessor { #[rustfmt::skip] fn hints() -> HashMap { let mut hints = hints(); + hints.insert(syscall_handler::ENTER_SCOPE_SYSCALL_HANDLER.into(), syscall_handler::enter_scope_syscall_handler); hints.insert(syscall_handler::SYSCALL_HANDLER_CREATE.into(), syscall_handler::syscall_handler_create); hints.insert(syscall_handler::SYSCALL_HANDLER_SET_SYSCALL_PTR.into(), syscall_handler::syscall_handler_set_syscall_ptr); - hints.insert(syscall_handler::ENTER_SCOPE_SYSCALL_HANDLER.into(), syscall_handler::enter_scope_syscall_handler); hints } From a213bda7a09219ee31bd615b3a841f36818219a3 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Tue, 24 Dec 2024 15:43:36 +0100 Subject: [PATCH 59/75] sound run syscall handler vip --- .../src/syscall_handler/evm/account.rs | 3 +- .../src/syscall_handler/evm/header.rs | 3 +- .../src/syscall_handler/evm/mod.rs | 6 +- .../src/syscall_handler/evm/storage.rs | 3 +- .../src/syscall_handler/evm/account.rs | 15 ++++- .../src/syscall_handler/evm/header.rs | 14 +++- .../src/syscall_handler/evm/mod.rs | 51 +++++++++----- .../src/syscall_handler/evm/storage.rs | 26 ++++++-- .../src/syscall_handler/mod.rs | 66 +++++++++++++++++-- crates/syscall_handler/src/traits.rs | 2 +- crates/types/src/keys/storage.rs | 15 ++++- .../execute_syscalls.cairo | 58 ++++++++-------- 12 files changed, 194 insertions(+), 68 deletions(-) diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs index 9ba4f3af..40631832 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs @@ -15,6 +15,7 @@ use types::{ RPC, }; +#[derive(Debug, Default)] pub struct AccountCallHandler; #[allow(refining_impl_trait)] @@ -40,7 +41,7 @@ impl CallHandler for AccountCallHandler { }) } - fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { + fn handle(&mut self, key: Self::Key, function_id: Self::Id) -> SyscallResult { let runtime = tokio::runtime::Runtime::new().unwrap(); let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let value = runtime diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs index 38f38257..dc074560 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs @@ -16,6 +16,7 @@ use types::{ RPC, }; +#[derive(Debug, Default)] pub struct HeaderCallHandler; #[allow(refining_impl_trait)] @@ -41,7 +42,7 @@ impl CallHandler for HeaderCallHandler { }) } - fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { + fn handle(&mut self, key: Self::Key, function_id: Self::Id) -> SyscallResult { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let runtime = tokio::runtime::Runtime::new().unwrap(); let value = runtime diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs index cec2d29c..e82c7e0a 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs @@ -113,7 +113,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Header => { let key = header::HeaderCallHandler::derive_key(vm, &mut calldata)?; let function_id = header::HeaderCallHandler::derive_id(request.selector)?; - let result = header::HeaderCallHandler::handle(key.clone(), function_id)?; + let result = header::HeaderCallHandler.handle(key.clone(), function_id)?; self.key_set.insert(DryRunKey::Header(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); @@ -121,7 +121,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Account => { let key = account::AccountCallHandler::derive_key(vm, &mut calldata)?; let function_id = account::AccountCallHandler::derive_id(request.selector)?; - let result = account::AccountCallHandler::handle(key.clone(), function_id)?; + let result = account::AccountCallHandler.handle(key.clone(), function_id)?; self.key_set.insert(DryRunKey::Account(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); @@ -129,7 +129,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Storage => { let key = storage::StorageCallHandler::derive_key(vm, &mut calldata)?; let function_id = storage::StorageCallHandler::derive_id(request.selector)?; - let result = storage::StorageCallHandler::handle(key.clone(), function_id)?; + let result = storage::StorageCallHandler.handle(key.clone(), function_id)?; self.key_set.insert(DryRunKey::Storage(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs index 083750be..7f3583cc 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs @@ -15,6 +15,7 @@ use types::{ RPC, }; +#[derive(Debug, Default)] pub struct StorageCallHandler; #[allow(refining_impl_trait)] @@ -40,7 +41,7 @@ impl CallHandler for StorageCallHandler { }) } - fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult { + fn handle(&mut self, key: Self::Key, function_id: Self::Id) -> SyscallResult { let runtime = tokio::runtime::Runtime::new().unwrap(); let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let value = runtime diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs index 847bf47b..dd4f8f0b 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs @@ -6,7 +6,18 @@ use types::{ keys::account::{CairoKey, Key}, }; -pub struct AccountCallHandler; +use crate::syscall_handler::Memorizer; + +#[derive(Debug)] +pub struct AccountCallHandler { + pub memorizer: Memorizer, +} + +impl AccountCallHandler { + pub fn new(memorizer: Memorizer) -> Self { + Self { memorizer } + } +} #[allow(refining_impl_trait)] impl CallHandler for AccountCallHandler { @@ -31,7 +42,7 @@ impl CallHandler for AccountCallHandler { }) } - fn handle(_key: Self::Key, _function_id: Self::Id) -> SyscallResult { + fn handle(&mut self, _key: Self::Key, _function_id: Self::Id) -> SyscallResult { Ok(Uint256::from(0_u64)) } } diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs index 63cc4a18..281dffd7 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs @@ -1,3 +1,4 @@ +use crate::syscall_handler::Memorizer; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; @@ -6,7 +7,16 @@ use types::{ keys::header::{CairoKey, Key}, }; -pub struct HeaderCallHandler; +#[derive(Debug)] +pub struct HeaderCallHandler { + pub memorizer: Memorizer, +} + +impl HeaderCallHandler { + pub fn new(memorizer: Memorizer) -> Self { + Self { memorizer } + } +} #[allow(refining_impl_trait)] impl CallHandler for HeaderCallHandler { @@ -31,7 +41,7 @@ impl CallHandler for HeaderCallHandler { }) } - fn handle(_key: Self::Key, _function_id: Self::Id) -> SyscallResult { + fn handle(&mut self, _key: Self::Key, _function_id: Self::Id) -> SyscallResult { Ok(Uint256::from(0_u64)) } } diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs b/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs index cec2d29c..faf7bcb4 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs @@ -4,9 +4,11 @@ pub mod receipt; pub mod storage; pub mod transaction; +use cairo_vm::hint_processor::builtin_hint_processor::dict_manager::DictManager; use cairo_vm::vm::errors::hint_errors::HintError; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use serde::{Deserialize, Serialize}; +use std::cell::RefCell; use std::rc::Rc; use std::sync::RwLock; use std::{collections::HashSet, hash::Hash}; @@ -17,6 +19,8 @@ use types::cairo::new_syscalls::{CallContractRequest, CallContractResponse}; use types::cairo::traits::CairoType; use types::keys; +use super::Memorizer; + #[derive(Debug, Default, Serialize, Deserialize)] pub struct SyscallHandler { #[serde(skip)] @@ -24,6 +28,15 @@ pub struct SyscallHandler { pub call_contract_handler: CallContractHandler, } +impl SyscallHandler { + pub fn new(dict_manager: Rc>) -> Self { + Self { + call_contract_handler: CallContractHandler::new(dict_manager), + ..Default::default() + } + } +} + /// SyscallHandler is wrapped in Rc> in order /// to clone the reference when entering and exiting vm scopes #[derive(Debug, Clone, Default)] @@ -42,13 +55,24 @@ pub enum CallHandlerId { #[derive(Debug, Default, Serialize, Deserialize)] pub struct CallContractHandler { + #[serde(skip)] + pub dict_manager: Rc>, pub key_set: HashSet, } +impl CallContractHandler { + pub fn new(dict_manager: Rc>) -> Self { + Self { + dict_manager, + ..Default::default() + } + } +} + impl SyscallHandlerWrapper { - pub fn new() -> Self { + pub fn new(dict_manager: Rc>) -> Self { Self { - syscall_handler: Rc::new(RwLock::new(SyscallHandler::default())), + syscall_handler: Rc::new(RwLock::new(SyscallHandler::new(dict_manager))), } } pub fn set_syscall_ptr(&self, syscall_ptr: Relocatable) { @@ -94,17 +118,7 @@ impl traits::SyscallHandler for CallContractHandler { let call_handler_id = CallHandlerId::try_from(request.contract_address)?; - let segment_index = felt_from_ptr(vm, &mut calldata)?; - let offset = felt_from_ptr(vm, &mut calldata)?; - - let _memorizer = Relocatable::from(( - segment_index - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - offset - .try_into() - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, - )); + let memorizer = Memorizer::derive(vm, &mut calldata)?; let retdata_start = vm.add_temporary_segment(); let mut retdata_end = retdata_start; @@ -113,7 +127,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Header => { let key = header::HeaderCallHandler::derive_key(vm, &mut calldata)?; let function_id = header::HeaderCallHandler::derive_id(request.selector)?; - let result = header::HeaderCallHandler::handle(key.clone(), function_id)?; + let result = header::HeaderCallHandler::new(memorizer).handle(key.clone(), function_id)?; self.key_set.insert(DryRunKey::Header(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); @@ -121,7 +135,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Account => { let key = account::AccountCallHandler::derive_key(vm, &mut calldata)?; let function_id = account::AccountCallHandler::derive_id(request.selector)?; - let result = account::AccountCallHandler::handle(key.clone(), function_id)?; + let result = account::AccountCallHandler::new(memorizer).handle(key.clone(), function_id)?; self.key_set.insert(DryRunKey::Account(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); @@ -129,8 +143,11 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Storage => { let key = storage::StorageCallHandler::derive_key(vm, &mut calldata)?; let function_id = storage::StorageCallHandler::derive_id(request.selector)?; - let result = storage::StorageCallHandler::handle(key.clone(), function_id)?; - self.key_set.insert(DryRunKey::Storage(key)); + let result = storage::StorageCallHandler::new(memorizer, self.dict_manager.clone()).handle(key.clone(), function_id)?; + self.key_set.insert(DryRunKey::Storage( + key.try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + )); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); } diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs index ab43ac8e..d7e394ff 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs @@ -1,23 +1,38 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use crate::syscall_handler::Memorizer; +use cairo_vm::hint_processor::builtin_hint_processor::dict_manager::DictManager; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; use types::{ cairo::{evm::storage::FunctionId, structs::Uint256, traits::CairoType}, - keys::storage::{CairoKey, Key}, + keys::storage::CairoKey, }; -pub struct StorageCallHandler; +#[derive(Debug)] +pub struct StorageCallHandler { + pub memorizer: Memorizer, + pub dict_manager: Rc>, +} + +impl StorageCallHandler { + pub fn new(memorizer: Memorizer, dict_manager: Rc>) -> Self { + Self { memorizer, dict_manager } + } +} #[allow(refining_impl_trait)] impl CallHandler for StorageCallHandler { - type Key = Key; + type Key = CairoKey; type Id = FunctionId; type CallHandlerResult = Uint256; fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { let ret = CairoKey::from_memory(vm, *ptr)?; *ptr = (*ptr + CairoKey::n_fields())?; - ret.try_into().map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into())) + Ok(ret) } fn derive_id(selector: Felt252) -> SyscallResult { @@ -31,7 +46,8 @@ impl CallHandler for StorageCallHandler { }) } - fn handle(_key: Self::Key, _function_id: Self::Id) -> SyscallResult { + fn handle(&mut self, key: Self::Key, _function_id: Self::Id) -> SyscallResult { + let _ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; Ok(Uint256::from(0_u64)) } } diff --git a/crates/sound_hint_processor/src/syscall_handler/mod.rs b/crates/sound_hint_processor/src/syscall_handler/mod.rs index 38fef207..1fb892ac 100644 --- a/crates/sound_hint_processor/src/syscall_handler/mod.rs +++ b/crates/sound_hint_processor/src/syscall_handler/mod.rs @@ -1,16 +1,72 @@ use cairo_vm::{ - hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_ptr_from_var_name}, - types::exec_scope::ExecutionScopes, - vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + hint_processor::builtin_hint_processor::{ + builtin_hint_processor_definition::HintProcessorData, dict_manager::DictManager, hint_utils::get_ptr_from_var_name, + }, + types::{ + exec_scope::ExecutionScopes, + relocatable::{MaybeRelocatable, Relocatable}, + }, + vm::{ + errors::{hint_errors::HintError, memory_errors::MemoryError}, + vm_core::VirtualMachine, + }, Felt252, }; use evm::SyscallHandlerWrapper; use hints::vars; -use std::{any::Any, collections::HashMap}; +use std::{any::Any, cell::RefCell, collections::HashMap, rc::Rc}; +use syscall_handler::SyscallResult; +use types::cairo::traits::CairoType; pub mod evm; pub mod starknet; +#[derive(Debug)] +pub struct Memorizer { + dict_ptr: Relocatable, +} + +impl Memorizer { + pub fn new(dict_ptr: Relocatable) -> Self { + Self { dict_ptr } + } + + pub fn derive(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { + let ret = Memorizer::from_memory(vm, *ptr)?; + *ptr = (*ptr + Memorizer::n_fields())?; + Ok(ret) + } + + pub fn read_key(&self, key: Felt252, dict_manager: Rc>) -> Result { + let key = MaybeRelocatable::from(key); + dict_manager + .borrow_mut() + .get_tracker_mut(self.dict_ptr)? + .get_value(&key)? + .get_int() + .ok_or(HintError::NoValueForKey(Box::new(key.clone()))) + } +} + +impl CairoType for Memorizer { + fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result { + let segment_index: isize = (*vm.get_integer((address + 0)?)?).try_into().unwrap(); + let offset: usize = (*vm.get_integer((address + 1)?)?).try_into().unwrap(); + + Ok(Self { + dict_ptr: Relocatable::from((segment_index, offset)), + }) + } + fn to_memory(&self, vm: &mut VirtualMachine, address: Relocatable) -> Result<(), MemoryError> { + vm.insert_value((address + 0)?, MaybeRelocatable::from(Felt252::from(self.dict_ptr.segment_index)))?; + vm.insert_value((address + 1)?, MaybeRelocatable::from(Felt252::from(self.dict_ptr.offset)))?; + Ok(()) + } + fn n_fields() -> usize { + 2 + } +} + pub const SYSCALL_HANDLER_CREATE: &str = "if 'syscall_handler' not in globals():\n from contract_bootloader.syscall_handler import SyscallHandler\n syscall_handler = SyscallHandler(segments=segments, dict_manager=__dict_manager)"; pub fn syscall_handler_create( @@ -20,7 +76,7 @@ pub fn syscall_handler_create( _constants: &HashMap, ) -> Result<(), HintError> { if let Err(HintError::VariableNotInScopeError(_)) = exec_scopes.get::(vars::scopes::SYSCALL_HANDLER) { - let syscall_handler = SyscallHandlerWrapper::new(); + let syscall_handler = SyscallHandlerWrapper::new(exec_scopes.get_dict_manager()?); exec_scopes.insert_value(vars::scopes::SYSCALL_HANDLER, syscall_handler); } diff --git a/crates/syscall_handler/src/traits.rs b/crates/syscall_handler/src/traits.rs index 325e351f..a92d2de1 100644 --- a/crates/syscall_handler/src/traits.rs +++ b/crates/syscall_handler/src/traits.rs @@ -18,5 +18,5 @@ pub trait CallHandler { fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult; fn derive_id(selector: Felt252) -> SyscallResult; - fn handle(key: Self::Key, function_id: Self::Id) -> SyscallResult; + fn handle(&mut self, key: Self::Key, function_id: Self::Id) -> SyscallResult; } diff --git a/crates/types/src/keys/storage.rs b/crates/types/src/keys/storage.rs index 33b67eb8..65d54284 100644 --- a/crates/types/src/keys/storage.rs +++ b/crates/types/src/keys/storage.rs @@ -7,8 +7,9 @@ use cairo_vm::{ Felt252, }; use serde::{Deserialize, Serialize}; +use starknet_crypto::poseidon_hash_many; -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct CairoKey { chain_id: Felt252, block_number: Felt252, @@ -17,6 +18,18 @@ pub struct CairoKey { storage_slot_low: Felt252, } +impl CairoKey { + pub fn hash(&self) -> Felt252 { + poseidon_hash_many(&[ + self.chain_id, + self.block_number, + self.address, + self.storage_slot_high, + self.storage_slot_low, + ]) + } +} + impl CairoType for CairoKey { fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result { Ok(Self { diff --git a/src/contract_bootloader/execute_syscalls.cairo b/src/contract_bootloader/execute_syscalls.cairo index 49117d8a..c1cdea2e 100644 --- a/src/contract_bootloader/execute_syscalls.cairo +++ b/src/contract_bootloader/execute_syscalls.cairo @@ -105,35 +105,35 @@ func execute_call_contract{ let layout = chain_id_to_layout(call_contract_request.calldata_start[2]); let output_ptr = call_contract_response.retdata_start; - // if (layout == Layout.EVM) { - // with output_ptr { - // let output_len = EvmStateAccess.read_and_decode( - // params=call_contract_request.calldata_start + 2, - // state_access_type=state_access_type, - // field=field, - // decoder_target=EvmDecoderTarget.UINT256, - // ); - - // return (); - // } - // } - - // if (layout == Layout.STARKNET) { - // with output_ptr { - // let output_len = StarknetStateAccess.read_and_decode( - // params=call_contract_request.calldata_start + 2, - // state_access_type=state_access_type, - // field=field, - // decoder_target=StarknetDecoderTarget.FELT, - // as_be=1, - // ); - // } - - // return (); - // } - - // // Unknown DictId - // assert 1 = 0; + if (layout == Layout.EVM) { + with output_ptr { + let output_len = EvmStateAccess.read_and_decode( + params=call_contract_request.calldata_start + 2, + state_access_type=state_access_type, + field=field, + decoder_target=EvmDecoderTarget.UINT256, + ); + + return (); + } + } + + if (layout == Layout.STARKNET) { + with output_ptr { + let output_len = StarknetStateAccess.read_and_decode( + params=call_contract_request.calldata_start + 2, + state_access_type=state_access_type, + field=field, + decoder_target=StarknetDecoderTarget.FELT, + as_be=1, + ); + } + + return (); + } + + // Unknown DictId + assert 1 = 0; return (); } From 5b2e6fd16fe6ec645747609205ae1c5168c80c4b Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 25 Dec 2024 13:37:11 +0100 Subject: [PATCH 60/75] sound run functional! --- Cargo.lock | 1 + .../src/syscall_handler/evm/account.rs | 2 +- .../src/syscall_handler/evm/header.rs | 2 +- .../src/syscall_handler/evm/mod.rs | 6 ++-- .../src/syscall_handler/evm/storage.rs | 2 +- crates/hints/src/segments.rs | 10 +++--- crates/sound_hint_processor/Cargo.toml | 1 + .../src/syscall_handler/evm/account.rs | 31 ++++++++++++++----- .../src/syscall_handler/evm/header.rs | 31 ++++++++++++++----- .../src/syscall_handler/evm/mod.rs | 16 +++++++--- .../src/syscall_handler/evm/storage.rs | 17 ++++++++-- .../src/syscall_handler/mod.rs | 4 +-- crates/syscall_handler/src/traits.rs | 2 +- crates/types/src/keys/account.rs | 9 +++++- crates/types/src/keys/header.rs | 9 +++++- 15 files changed, 105 insertions(+), 38 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 393a8598..9603ea21 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4591,6 +4591,7 @@ dependencies = [ name = "sound_hint_processor" version = "0.1.0" dependencies = [ + "alloy-rlp", "cairo-lang-casm", "cairo-lang-starknet-classes", "cairo-vm", diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs index 40631832..dc550715 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs @@ -41,7 +41,7 @@ impl CallHandler for AccountCallHandler { }) } - fn handle(&mut self, key: Self::Key, function_id: Self::Id) -> SyscallResult { + fn handle(&mut self, key: Self::Key, function_id: Self::Id, _vm: &VirtualMachine) -> SyscallResult { let runtime = tokio::runtime::Runtime::new().unwrap(); let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let value = runtime diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs index dc074560..d157d5de 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs @@ -42,7 +42,7 @@ impl CallHandler for HeaderCallHandler { }) } - fn handle(&mut self, key: Self::Key, function_id: Self::Id) -> SyscallResult { + fn handle(&mut self, key: Self::Key, function_id: Self::Id, _vm: &VirtualMachine) -> SyscallResult { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let runtime = tokio::runtime::Runtime::new().unwrap(); let value = runtime diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs index e82c7e0a..f05a5f13 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs @@ -113,7 +113,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Header => { let key = header::HeaderCallHandler::derive_key(vm, &mut calldata)?; let function_id = header::HeaderCallHandler::derive_id(request.selector)?; - let result = header::HeaderCallHandler.handle(key.clone(), function_id)?; + let result = header::HeaderCallHandler.handle(key.clone(), function_id, vm)?; self.key_set.insert(DryRunKey::Header(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); @@ -121,7 +121,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Account => { let key = account::AccountCallHandler::derive_key(vm, &mut calldata)?; let function_id = account::AccountCallHandler::derive_id(request.selector)?; - let result = account::AccountCallHandler.handle(key.clone(), function_id)?; + let result = account::AccountCallHandler.handle(key.clone(), function_id, vm)?; self.key_set.insert(DryRunKey::Account(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); @@ -129,7 +129,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Storage => { let key = storage::StorageCallHandler::derive_key(vm, &mut calldata)?; let function_id = storage::StorageCallHandler::derive_id(request.selector)?; - let result = storage::StorageCallHandler.handle(key.clone(), function_id)?; + let result = storage::StorageCallHandler.handle(key.clone(), function_id, vm)?; self.key_set.insert(DryRunKey::Storage(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs index 7f3583cc..ab687f10 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs @@ -41,7 +41,7 @@ impl CallHandler for StorageCallHandler { }) } - fn handle(&mut self, key: Self::Key, function_id: Self::Id) -> SyscallResult { + fn handle(&mut self, key: Self::Key, function_id: Self::Id, _vm: &VirtualMachine) -> SyscallResult { let runtime = tokio::runtime::Runtime::new().unwrap(); let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let value = runtime diff --git a/crates/hints/src/segments.rs b/crates/hints/src/segments.rs index c317ee2e..00b26587 100644 --- a/crates/hints/src/segments.rs +++ b/crates/hints/src/segments.rs @@ -1,7 +1,7 @@ use cairo_vm::{ hint_processor::builtin_hint_processor::{ builtin_hint_processor_definition::HintProcessorData, - hint_utils::{get_integer_from_var_name, get_relocatable_from_var_name, insert_value_into_ap}, + hint_utils::{get_integer_from_var_name, get_ptr_from_var_name, insert_value_into_ap}, }, types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, @@ -41,7 +41,7 @@ pub fn segments_add_evm_memorizer_segment_index( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let memorizer = get_relocatable_from_var_name("evm_memorizer", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + let memorizer = get_ptr_from_var_name("evm_memorizer", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; insert_value_into_ap(vm, Felt252::from(memorizer.segment_index)) } @@ -53,7 +53,7 @@ pub fn segments_add_evm_memorizer_offset( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let memorizer = get_relocatable_from_var_name("evm_memorizer", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + let memorizer = get_ptr_from_var_name("evm_memorizer", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; insert_value_into_ap(vm, Felt252::from(memorizer.offset)) } @@ -65,7 +65,7 @@ pub fn segments_add_evm_starknet_memorizer_index( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let memorizer = get_relocatable_from_var_name("starknet_memorizer", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + let memorizer = get_ptr_from_var_name("starknet_memorizer", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; insert_value_into_ap(vm, Felt252::from(memorizer.segment_index)) } @@ -77,7 +77,7 @@ pub fn segments_add_starknet_memorizer_offset( hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let memorizer = get_relocatable_from_var_name("starknet_memorizer", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + let memorizer = get_ptr_from_var_name("starknet_memorizer", vm, &hint_data.ids_data, &hint_data.ap_tracking)?; insert_value_into_ap(vm, Felt252::from(memorizer.offset)) } diff --git a/crates/sound_hint_processor/Cargo.toml b/crates/sound_hint_processor/Cargo.toml index 73b93a95..056daa2c 100644 --- a/crates/sound_hint_processor/Cargo.toml +++ b/crates/sound_hint_processor/Cargo.toml @@ -10,6 +10,7 @@ cairo-vm.workspace = true serde.workspace = true starknet-types-core.workspace = true strum_macros.workspace = true +alloy-rlp.workspace = true hints.workspace = true syscall_handler.workspace = true diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs index dd4f8f0b..d1073648 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs @@ -1,9 +1,14 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use cairo_vm::hint_processor::builtin_hint_processor::dict_manager::DictManager; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; +use types::cairo::evm::account::CairoAccount; use types::{ cairo::{evm::account::FunctionId, structs::Uint256, traits::CairoType}, - keys::account::{CairoKey, Key}, + keys::account::CairoKey, }; use crate::syscall_handler::Memorizer; @@ -11,24 +16,25 @@ use crate::syscall_handler::Memorizer; #[derive(Debug)] pub struct AccountCallHandler { pub memorizer: Memorizer, + pub dict_manager: Rc>, } impl AccountCallHandler { - pub fn new(memorizer: Memorizer) -> Self { - Self { memorizer } + pub fn new(memorizer: Memorizer, dict_manager: Rc>) -> Self { + Self { memorizer, dict_manager } } } #[allow(refining_impl_trait)] impl CallHandler for AccountCallHandler { - type Key = Key; + type Key = CairoKey; type Id = FunctionId; type CallHandlerResult = Uint256; fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { let ret = CairoKey::from_memory(vm, *ptr)?; *ptr = (*ptr + CairoKey::n_fields())?; - ret.try_into().map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into())) + Ok(ret) } fn derive_id(selector: Felt252) -> SyscallResult { @@ -42,7 +48,18 @@ impl CallHandler for AccountCallHandler { }) } - fn handle(&mut self, _key: Self::Key, _function_id: Self::Id) -> SyscallResult { - Ok(Uint256::from(0_u64)) + fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { + let ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; + let header = alloy_rlp::Header::decode(&mut vm.get_integer(ptr)?.to_bytes_le().as_slice()) + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?; + let length = header.payload_length + 1; + let rlp = vm + .get_integer_range(ptr, (length + 7) / 8)? + .into_iter() + .flat_map(|f| f.to_bytes_le().into_iter().take(8)) + .take(length) + .collect::>(); + + Ok(CairoAccount::rlp_decode(&rlp).handle(function_id)) } } diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs index 281dffd7..ac0fb474 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs @@ -1,33 +1,39 @@ +use std::cell::RefCell; +use std::rc::Rc; + use crate::syscall_handler::Memorizer; +use cairo_vm::hint_processor::builtin_hint_processor::dict_manager::DictManager; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; +use types::cairo::evm::header::CairoHeader; use types::{ cairo::{evm::header::FunctionId, structs::Uint256, traits::CairoType}, - keys::header::{CairoKey, Key}, + keys::header::CairoKey, }; #[derive(Debug)] pub struct HeaderCallHandler { pub memorizer: Memorizer, + pub dict_manager: Rc>, } impl HeaderCallHandler { - pub fn new(memorizer: Memorizer) -> Self { - Self { memorizer } + pub fn new(memorizer: Memorizer, dict_manager: Rc>) -> Self { + Self { memorizer, dict_manager } } } #[allow(refining_impl_trait)] impl CallHandler for HeaderCallHandler { - type Key = Key; + type Key = CairoKey; type Id = FunctionId; type CallHandlerResult = Uint256; fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult { let ret = CairoKey::from_memory(vm, *ptr)?; *ptr = (*ptr + CairoKey::n_fields())?; - ret.try_into().map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into())) + Ok(ret) } fn derive_id(selector: Felt252) -> SyscallResult { @@ -41,7 +47,18 @@ impl CallHandler for HeaderCallHandler { }) } - fn handle(&mut self, _key: Self::Key, _function_id: Self::Id) -> SyscallResult { - Ok(Uint256::from(0_u64)) + fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { + let ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; + let header = alloy_rlp::Header::decode(&mut vm.get_integer(ptr)?.to_bytes_le().as_slice()) + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?; + let length = header.payload_length + 1; + let rlp = vm + .get_integer_range(ptr, (length + 7) / 8)? + .into_iter() + .flat_map(|f| f.to_bytes_le().into_iter().take(8)) + .take(length) + .collect::>(); + + Ok(CairoHeader::rlp_decode(&rlp).handle(function_id)) } } diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs b/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs index faf7bcb4..bbc0386b 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs @@ -127,23 +127,29 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Header => { let key = header::HeaderCallHandler::derive_key(vm, &mut calldata)?; let function_id = header::HeaderCallHandler::derive_id(request.selector)?; - let result = header::HeaderCallHandler::new(memorizer).handle(key.clone(), function_id)?; - self.key_set.insert(DryRunKey::Header(key)); + let result = header::HeaderCallHandler::new(memorizer, self.dict_manager.clone()).handle(key.clone(), function_id, vm)?; + self.key_set.insert(DryRunKey::Header( + key.try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + )); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); } CallHandlerId::Account => { let key = account::AccountCallHandler::derive_key(vm, &mut calldata)?; let function_id = account::AccountCallHandler::derive_id(request.selector)?; - let result = account::AccountCallHandler::new(memorizer).handle(key.clone(), function_id)?; - self.key_set.insert(DryRunKey::Account(key)); + let result = account::AccountCallHandler::new(memorizer, self.dict_manager.clone()).handle(key.clone(), function_id, vm)?; + self.key_set.insert(DryRunKey::Account( + key.try_into() + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, + )); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); } CallHandlerId::Storage => { let key = storage::StorageCallHandler::derive_key(vm, &mut calldata)?; let function_id = storage::StorageCallHandler::derive_id(request.selector)?; - let result = storage::StorageCallHandler::new(memorizer, self.dict_manager.clone()).handle(key.clone(), function_id)?; + let result = storage::StorageCallHandler::new(memorizer, self.dict_manager.clone()).handle(key.clone(), function_id, vm)?; self.key_set.insert(DryRunKey::Storage( key.try_into() .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs index d7e394ff..402581bb 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs @@ -6,6 +6,7 @@ use cairo_vm::hint_processor::builtin_hint_processor::dict_manager::DictManager; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; +use types::cairo::evm::storage::CairoStorage; use types::{ cairo::{evm::storage::FunctionId, structs::Uint256, traits::CairoType}, keys::storage::CairoKey, @@ -46,8 +47,18 @@ impl CallHandler for StorageCallHandler { }) } - fn handle(&mut self, key: Self::Key, _function_id: Self::Id) -> SyscallResult { - let _ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; - Ok(Uint256::from(0_u64)) + fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { + let ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; + let header = alloy_rlp::Header::decode(&mut vm.get_integer(ptr)?.to_bytes_le().as_slice()) + .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?; + let length = header.payload_length + 1; + let rlp = vm + .get_integer_range(ptr, (length + 7) / 8)? + .into_iter() + .flat_map(|f| f.to_bytes_le().into_iter().take(8)) + .take(length) + .collect::>(); + + Ok(CairoStorage::rlp_decode(&rlp).handle(function_id)) } } diff --git a/crates/sound_hint_processor/src/syscall_handler/mod.rs b/crates/sound_hint_processor/src/syscall_handler/mod.rs index 1fb892ac..0d810bd3 100644 --- a/crates/sound_hint_processor/src/syscall_handler/mod.rs +++ b/crates/sound_hint_processor/src/syscall_handler/mod.rs @@ -37,13 +37,13 @@ impl Memorizer { Ok(ret) } - pub fn read_key(&self, key: Felt252, dict_manager: Rc>) -> Result { + pub fn read_key(&self, key: Felt252, dict_manager: Rc>) -> Result { let key = MaybeRelocatable::from(key); dict_manager .borrow_mut() .get_tracker_mut(self.dict_ptr)? .get_value(&key)? - .get_int() + .get_relocatable() .ok_or(HintError::NoValueForKey(Box::new(key.clone()))) } } diff --git a/crates/syscall_handler/src/traits.rs b/crates/syscall_handler/src/traits.rs index a92d2de1..b829c666 100644 --- a/crates/syscall_handler/src/traits.rs +++ b/crates/syscall_handler/src/traits.rs @@ -18,5 +18,5 @@ pub trait CallHandler { fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult; fn derive_id(selector: Felt252) -> SyscallResult; - fn handle(&mut self, key: Self::Key, function_id: Self::Id) -> SyscallResult; + fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult; } diff --git a/crates/types/src/keys/account.rs b/crates/types/src/keys/account.rs index 2e350e0d..fddb430f 100644 --- a/crates/types/src/keys/account.rs +++ b/crates/types/src/keys/account.rs @@ -7,14 +7,21 @@ use cairo_vm::{ Felt252, }; use serde::{Deserialize, Serialize}; +use starknet_crypto::poseidon_hash_many; -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct CairoKey { chain_id: Felt252, block_number: Felt252, address: Felt252, } +impl CairoKey { + pub fn hash(&self) -> Felt252 { + poseidon_hash_many(&[self.chain_id, self.block_number, self.address]) + } +} + impl CairoType for CairoKey { fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result { Ok(Self { diff --git a/crates/types/src/keys/header.rs b/crates/types/src/keys/header.rs index 09abe9bb..6e2e6d80 100644 --- a/crates/types/src/keys/header.rs +++ b/crates/types/src/keys/header.rs @@ -7,13 +7,20 @@ use cairo_vm::{ Felt252, }; use serde::{Deserialize, Serialize}; +use starknet_crypto::poseidon_hash_many; -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Clone)] pub struct CairoKey { chain_id: Felt252, block_number: Felt252, } +impl CairoKey { + pub fn hash(&self) -> Felt252 { + poseidon_hash_many(&[self.chain_id, self.block_number]) + } +} + impl CairoType for CairoKey { fn from_memory(vm: &VirtualMachine, address: Relocatable) -> Result { Ok(Self { From 891db4eb60aa58add7f3ec6b6db76b18db88ca99 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 25 Dec 2024 18:23:04 +0100 Subject: [PATCH 61/75] docs & example & concurrent fetcher --- .gitignore | 30 +- .nvmrc | 1 - Cargo.lock | 163 +-- Cargo.toml | 9 +- README.md | 22 +- crates/fetcher/Cargo.toml | 1 + crates/fetcher/src/main.rs | 54 +- crates/fetcher/src/proof_keys.rs | 38 +- examples/hdp_input.json | 2272 ++++++++++++++++++++++++++++++ tools/js/merkle.js | 24 - tools/js/package.json | 15 - 11 files changed, 2428 insertions(+), 201 deletions(-) delete mode 100644 .nvmrc create mode 100644 examples/hdp_input.json delete mode 100644 tools/js/merkle.js delete mode 100644 tools/js/package.json diff --git a/.gitignore b/.gitignore index ab714bcf..0b9f7a1a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ # Virtual Environment venv/ -.profiling/ # Python Artifacts __pycache__/ @@ -11,10 +10,6 @@ __pycache__/ build/ dist/ -# Data Files -/src/single_chunk_processor/data/*.json -/src/single_chunk_processor/data/*.zip - # Environment Files *.env @@ -30,35 +25,16 @@ out/ .gas-snapshot .encryptedKey broadcast/ - -# Node.js -node_modules/ -package-lock.json - -# System Files -.DS_Store -src/.DS_Store - -# Solidity Verifier -solidity-verifier/lib/* - -# Cairo VM -cairo-vm - -# HDP -hdp-test/ -hdp/ - *.memory *.trace # Whitelist - these files should not be ignored -!tests/cairo_programs/fixtures/*.json -!tools/js/package.json !*_contract.json !packages/cairo-lang-0.13.1.zip # Scarb & snfoundry target .snfoundry_cache/ -.cargo \ No newline at end of file +.cargo + +!examples/*.json \ No newline at end of file diff --git a/.nvmrc b/.nvmrc deleted file mode 100644 index 8d2a4516..00000000 --- a/.nvmrc +++ /dev/null @@ -1 +0,0 @@ -18.16.1 \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 9603ea21..8bfa2fd0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -72,9 +72,9 @@ dependencies = [ [[package]] name = "alloy-chains" -version = "0.1.48" +version = "0.1.51" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0161082e0edd9013d23083465cc04b20e44b7a15646d36ba7b0cdb7cd6fe18f" +checksum = "d4e0f0136c085132939da6b753452ebed4efaa73fe523bb855b10c199c2ebfaf" dependencies = [ "alloy-primitives", "num_enum", @@ -131,7 +131,7 @@ dependencies = [ "alloy-transport", "futures", "futures-util", - "thiserror 2.0.8", + "thiserror 2.0.9", ] [[package]] @@ -240,7 +240,7 @@ dependencies = [ "alloy-sol-types", "serde", "serde_json", - "thiserror 2.0.8", + "thiserror 2.0.9", "tracing", ] @@ -266,7 +266,7 @@ dependencies = [ "futures-utils-wasm", "serde", "serde_json", - "thiserror 2.0.8", + "thiserror 2.0.9", ] [[package]] @@ -343,7 +343,7 @@ dependencies = [ "schnellru", "serde", "serde_json", - "thiserror 2.0.8", + "thiserror 2.0.9", "tokio", "tracing", "url", @@ -388,7 +388,7 @@ checksum = "5a833d97bf8a5f0f878daf2c8451fff7de7f9de38baa5a45d936ec718d81255a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -499,7 +499,7 @@ dependencies = [ "auto_impl", "elliptic-curve", "k256", - "thiserror 2.0.8", + "thiserror 2.0.9", ] [[package]] @@ -515,7 +515,7 @@ dependencies = [ "async-trait", "k256", "rand", - "thiserror 2.0.8", + "thiserror 2.0.9", ] [[package]] @@ -529,7 +529,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -546,7 +546,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "syn-solidity", "tiny-keccak", ] @@ -564,7 +564,7 @@ dependencies = [ "proc-macro2", "quote", "serde_json", - "syn 2.0.90", + "syn 2.0.91", "syn-solidity", ] @@ -603,7 +603,7 @@ dependencies = [ "futures-utils-wasm", "serde", "serde_json", - "thiserror 2.0.8", + "thiserror 2.0.9", "tokio", "tower", "tracing", @@ -665,9 +665,9 @@ dependencies = [ [[package]] name = "alloy-trie" -version = "0.7.6" +version = "0.7.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a5fd8fea044cc9a8c8a50bb6f28e31f0385d820f116c5b98f6f4e55d6e5590b" +checksum = "1e428104b2445a4f929030891b3dbf8c94433a8349ba6480946bf6af7975c2f6" dependencies = [ "alloy-primitives", "alloy-rlp", @@ -745,9 +745,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7" +checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04" [[package]] name = "ark-ff" @@ -916,7 +916,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -927,7 +927,7 @@ checksum = "721cae7de5c34fbb2acd27e21e6d2cf7b886dce0c27388d46c4e6c47ea4318dd" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -955,7 +955,7 @@ checksum = "3c87f3f15e7794432337fc718554eaa4dc8f04c9677a950ffe366f20a162ae42" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1332,7 +1332,7 @@ checksum = "b3c4a161868276ce022c44ac500afbfa0d7d8371106feb40dfca34ea7be97503" dependencies = [ "cairo-lang-debug", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1600,11 +1600,11 @@ dependencies = [ [[package]] name = "cairo-type-derive" version = "0.1.0" -source = "git+https://github.com/keep-starknet-strange/snos.git#35a300a10d2107482ada440b5025ee2f651afbd4" +source = "git+https://github.com/keep-starknet-strange/snos.git?rev=35a300a10d2107482ada440b5025ee2f651afbd4#35a300a10d2107482ada440b5025ee2f651afbd4" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1646,9 +1646,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.4" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9157bbaa6b165880c27a4293a474c91cdcf265cc68cc829bf10be0964a391caf" +checksum = "c31a0499c1dc64f458ad13872de75c0eb7e3fdb0e67964610c914b034fc5956e" dependencies = [ "shlex", ] @@ -1703,7 +1703,7 @@ dependencies = [ "heck 0.5.0", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1890,7 +1890,7 @@ dependencies = [ "proc-macro2", "quote", "strsim", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1901,7 +1901,7 @@ checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ "darling_core", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -1972,7 +1972,7 @@ checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "unicode-xid", ] @@ -2041,7 +2041,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -2219,6 +2219,7 @@ dependencies = [ "alloy", "clap", "dry_hint_processor", + "futures", "indexer", "serde_json", "thiserror 1.0.69", @@ -2272,9 +2273,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] name = "foldhash" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f81ec6369c545a7d40e4589b5597581fa1c441fe1cce96dd1de43159910a36a2" +checksum = "a0d2fde1f7b3d48b8395d5f2de76c18a528bd6a9cdde438df747bfcba3e05d6f" [[package]] name = "foreign-types" @@ -2362,7 +2363,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -2420,7 +2421,7 @@ checksum = "43eaff6bbc0b3a878361aced5ec6a2818ee7c541c5b33b5880dfa9a86c23e9e7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -2680,9 +2681,9 @@ dependencies = [ [[package]] name = "hyper-rustls" -version = "0.27.3" +version = "0.27.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333" +checksum = "2d191583f3da1305256f22463b9bb0471acad48a4e534a5218b9963e9c1f59b2" dependencies = [ "futures-util", "http", @@ -2868,7 +2869,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -2937,7 +2938,7 @@ checksum = "a0eb5a3343abf848c0984fe4604b2b105da9539376e24fc0a3b0007411ae4fd9" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -3161,9 +3162,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.168" +version = "0.2.169" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaeb2981e0606ca11d79718f8bb01164f1d6ed75080182d3abf017e6d244b6d" +checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" [[package]] name = "libm" @@ -3236,9 +3237,9 @@ checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "microlp" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e0c5664f9959f1c3970d523a22f0319024282cb754358c2afc7e1d45280ae3" +checksum = "a4d5845c04529928925fd1abd6776813710ad57ef41cb31958b1d35622a7d8e9" dependencies = [ "log", "sprs", @@ -3434,14 +3435,14 @@ checksum = "af1844ef2428cc3e1cb900be36181049ef3d3193c63e43026cfe202983b27a56" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] name = "nybbles" -version = "0.2.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95f06be0417d97f81fe4e5c86d7d01b392655a9cac9c19a848aa033e18937b23" +checksum = "55a62e678a89501192cc5ebf47dcbc656b608ae5e1c61c9251fe35230f119fe3" dependencies = [ "alloy-rlp", "const-hex", @@ -3452,9 +3453,9 @@ dependencies = [ [[package]] name = "object" -version = "0.36.5" +version = "0.36.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" +checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" dependencies = [ "memchr", ] @@ -3494,7 +3495,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -3595,7 +3596,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b7cafe60d6cf8e62e1b9b2ea516a089c008945bb5a275416789e7db0bc199dc" dependencies = [ "memchr", - "thiserror 2.0.8", + "thiserror 2.0.9", "ucd-trie", ] @@ -3651,7 +3652,7 @@ checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -3767,7 +3768,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4083,7 +4084,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4255,7 +4256,7 @@ dependencies = [ "proc-macro2", "quote", "serde_derive_internals", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4362,7 +4363,7 @@ checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4373,14 +4374,14 @@ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] name = "serde_json" -version = "1.0.133" +version = "1.0.134" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" +checksum = "d00f4175c42ee48b15416f6193a959ba3a0d67fc699a0db9ad12df9f83991c7d" dependencies = [ "itoa", "memchr", @@ -4462,7 +4463,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4474,7 +4475,7 @@ dependencies = [ "darling", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4715,7 +4716,7 @@ checksum = "bbc159a1934c7be9761c237333a57febe060ace2bc9e3b337a59a37af206d19f" dependencies = [ "starknet-curve 0.4.2", "starknet-ff", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4807,7 +4808,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4829,9 +4830,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.90" +version = "2.0.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31" +checksum = "d53cbcb5a243bd33b7858b1d7f4aca2153490815872d86d955d6ea29f743c035" dependencies = [ "proc-macro2", "quote", @@ -4847,7 +4848,7 @@ dependencies = [ "paste", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4867,7 +4868,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -4941,11 +4942,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.8" +version = "2.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f5383f3e0071702bf93ab5ee99b52d26936be9dedd9413067cbdcddcb6141a" +checksum = "f072643fd0190df67a8bab670c20ef5d8737177d6ac6b2e9a236cb096206b2cc" dependencies = [ - "thiserror-impl 2.0.8", + "thiserror-impl 2.0.9", ] [[package]] @@ -4956,18 +4957,18 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] name = "thiserror-impl" -version = "2.0.8" +version = "2.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f357fcec90b3caef6623a099691be676d033b40a058ac95d2a6ade6fa0c943" +checksum = "7b50fa271071aae2e6ee85f842e2e28ba8cd2c5fb67f11fcb1fd70b276f9e7d4" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -5075,7 +5076,7 @@ checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -5218,7 +5219,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -5454,7 +5455,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "wasm-bindgen-shared", ] @@ -5488,7 +5489,7 @@ checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5780,7 +5781,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "synstructure", ] @@ -5802,7 +5803,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -5822,7 +5823,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", "synstructure", ] @@ -5843,7 +5844,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] @@ -5865,7 +5866,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.90", + "syn 2.0.91", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 67e56992..a6fc87d9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,9 +19,10 @@ alloy-rlp = { version = "0.3.5", features = ["derive"] } bincode = { version = "2.0.0-rc.3", default-features = false, features = ["serde"] } cairo-lang-casm = { version = "2.9.0-dev.0", default-features = false } cairo-lang-starknet-classes = { version = "2.9.0-dev.0" } -cairo-type-derive = { git = "https://github.com/keep-starknet-strange/snos.git" } +cairo-type-derive = { git = "https://github.com/keep-starknet-strange/snos.git", rev = "35a300a10d2107482ada440b5025ee2f651afbd4" } cairo-vm = { git = "https://github.com/lambdaclass/cairo-vm", rev = "388a4e51001377717b7e4c902c35f8e271c92ad7", features = ["extensive_hints", "clap", "cairo-1-hints"] } clap = { version = "4.3.10", features = ["derive"] } +futures = "0.3.31" hex = "0.4.3" num-bigint = "0.4.6" num-traits = "0.2.19" @@ -40,9 +41,9 @@ tiny-keccak = { version = "2.0.2", features = ["keccak"] } tokio = { version = "1.41.1", features = ["full"] } dry_hint_processor = { path = "crates/dry_hint_processor" } -sound_hint_processor = { path = "crates/sound_hint_processor" } +eth_essentials_cairo_vm_hints = { path = "packages/eth_essentials/cairo_vm_hints"} hints = { path = "crates/hints" } indexer = { path = "crates/indexer" } +sound_hint_processor = { path = "crates/sound_hint_processor" } syscall_handler = { path = "crates/syscall_handler" } -types = { path = "crates/types" } -eth_essentials_cairo_vm_hints = { path = "packages/eth_essentials/cairo_vm_hints"} \ No newline at end of file +types = { path = "crates/types" } \ No newline at end of file diff --git a/README.md b/README.md index c7e0816a..1231fc8a 100644 --- a/README.md +++ b/README.md @@ -18,24 +18,30 @@ source venv/bin/activate ## Running -Before running the program, prepare the input data. The inputs are provided via the `hdp_input.json` file located in the root directory of the HDP project. These inputs can be generated using the [HDP CLI](https://github.com/HerodotusDev/hdp). Example inputs are available in `tests/hdp/fixtures`. +Before running the program, prepare the input data. The inputs are provided via the `hdp_input.json` file located in the root directory of the HDP project. -To run the program, use: +To run the program, execute following steps: +Simulate Cairo1 module and collect info about proofs to fetch ```bash -cargo run --bin dry_run -- build/compiled_cairo_files/contract_dry_run.json --program_input rust_input.json --program_output a.json --layout all_cairo +cargo run --release --bin dry_run -- --program_input examples/hdp_input.json --program_output hdp_keys.json --layout starknet_with_keccak +``` + +Fetch the on-chain proofs needed for the HDP run: +```bash +cargo run --release --bin fetcher -- hdp_keys.json --program_output hdp_proofs.json +``` -cargo run --bin fetcher -- a.json --program_output b.json +Run Cairo1 module with verified onchain data +```bash +cargo run --release --bin sound_run -- --program_input examples/hdp_input.json --program_proofs hdp_proofs.json --program_output hdp_output.json --layout starknet_with_keccak ``` The program will output the results root and tasks root. These roots can be used to extract the results from the on-chain contract. ## How It Works -HDP Cairo is the repository containing the logic for verifying on-chain state via storage proofs, and then making that state available to custom Cairo1 contract modules. To enable this functionality, a custom syscall was designed, enabling dynamic access to the verified state. The syscalls are defined in `cairo1_syscall_binding` where we have some examples. - -### Architecture -The overall program is split into two main parts: +HDP Cairo is the repository containing the logic for verifying on-chain state via storage proofs, and then making that state available to custom Cairo1 contract modules. To enable this functionality, a custom syscall was designed, enabling dynamic access to the verified state. The syscalls are defined in `cairo1` where we have some examples. ### Architecture The overall program is split into two main parts: diff --git a/crates/fetcher/Cargo.toml b/crates/fetcher/Cargo.toml index fd166648..a3bca172 100644 --- a/crates/fetcher/Cargo.toml +++ b/crates/fetcher/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" alloy.workspace = true clap.workspace = true dry_hint_processor.workspace = true +futures.workspace = true serde_json.workspace = true thiserror.workspace = true tokio.workspace = true diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index dfc2f529..75741f8c 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -6,6 +6,7 @@ use alloy::hex::FromHexError; use clap::{Parser, ValueHint}; use dry_hint_processor::syscall_handler::evm::{self, SyscallHandler}; +use futures::{FutureExt, StreamExt}; use indexer::types::IndexerError; use proof_keys::ProofKeys; use std::{collections::HashSet, fs, num::ParseIntError, path::PathBuf}; @@ -14,6 +15,8 @@ use types::proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}; pub mod proof_keys; +const BUFFER_UNORDERED: usize = 10; + #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] struct Args { @@ -23,7 +26,8 @@ struct Args { program_output: PathBuf, } -fn main() -> Result<(), FetcherError> { +#[tokio::main] +async fn main() -> Result<(), FetcherError> { let args = Args::try_parse_from(std::env::args()).map_err(FetcherError::Args)?; let input_file = fs::read(args.filename)?; @@ -44,20 +48,28 @@ fn main() -> Result<(), FetcherError> { } } - let mut headers_with_mmr = proof_keys - .header_keys - .iter() - .map(ProofKeys::fetch_header_proof) - .collect::, FetcherError>>()?; + let mut headers_with_mmr: HashSet = HashSet::default(); + + while let Some(Ok(item)) = futures::stream::iter(proof_keys.header_keys.iter().map(ProofKeys::fetch_header_proof).map(|f| f.boxed_local())) + .buffer_unordered(BUFFER_UNORDERED) + .next() + .await + { + headers_with_mmr.insert(item); + } let mut accounts: HashSet = HashSet::default(); - for (header_with_mmr, account) in proof_keys - .account_keys - .iter() - .map(ProofKeys::fetch_account_proof) - .collect::, FetcherError>>()? - .into_iter() + while let Some(Ok((header_with_mmr, account))) = futures::stream::iter( + proof_keys + .account_keys + .iter() + .map(ProofKeys::fetch_account_proof) + .map(|f| f.boxed_local()), + ) + .buffer_unordered(BUFFER_UNORDERED) + .next() + .await { headers_with_mmr.insert(header_with_mmr); accounts.insert(account); @@ -65,14 +77,18 @@ fn main() -> Result<(), FetcherError> { let mut storages: HashSet = HashSet::default(); - for (header_with_mmr, account, storage) in proof_keys - .storage_keys - .iter() - .map(ProofKeys::fetch_storage_proof) - .collect::, FetcherError>>()? - .into_iter() + while let Some(Ok((header_with_mmr, account, storage))) = futures::stream::iter( + proof_keys + .storage_keys + .iter() + .map(ProofKeys::fetch_storage_proof) + .map(|f| f.boxed_local()), + ) + .buffer_unordered(BUFFER_UNORDERED) + .next() + .await { - headers_with_mmr.insert(header_with_mmr); + headers_with_mmr.insert(header_with_mmr.clone()); accounts.insert(account); storages.insert(storage); } diff --git a/crates/fetcher/src/proof_keys.rs b/crates/fetcher/src/proof_keys.rs index b5882d5c..895f2910 100644 --- a/crates/fetcher/src/proof_keys.rs +++ b/crates/fetcher/src/proof_keys.rs @@ -37,16 +37,13 @@ impl ProofKeys { format!("{:0>width$}", hex_str, width = (hex_str.len() + 1) / 2 * 2) } - pub fn fetch_header_proof(key: &keys::header::Key) -> Result { + pub async fn fetch_header_proof(key: &keys::header::Key) -> Result { let provider = Indexer::default(); - let runtime = tokio::runtime::Runtime::new().unwrap(); // Fetch proof response - let response = runtime.block_on(async { - provider - .get_headers_proof(IndexerQuery::new(key.chain_id, key.block_number, key.block_number)) - .await - })?; + let response = provider + .get_headers_proof(IndexerQuery::new(key.chain_id, key.block_number, key.block_number)) + .await?; // Extract MMR metadata let mmr_meta = MmrMeta { @@ -99,31 +96,28 @@ impl ProofKeys { }) } - pub fn fetch_account_proof(key: &keys::account::Key) -> Result<(HeaderMmrMeta, Account), FetcherError> { - let runtime = tokio::runtime::Runtime::new().unwrap(); + pub async fn fetch_account_proof(key: &keys::account::Key) -> Result<(HeaderMmrMeta, Account), FetcherError> { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let value = runtime - .block_on(async { provider.get_proof(key.address, vec![]).block_id(key.block_number.into()).await }) + let value = provider + .get_proof(key.address, vec![]) + .block_id(key.block_number.into()) + .await .map_err(|e| FetcherError::InternalError(e.to_string()))?; Ok(( - Self::fetch_header_proof(&key.to_owned().into())?, + Self::fetch_header_proof(&key.to_owned().into()).await?, Account::new(value.address, vec![MPTProof::new(key.block_number, value.account_proof)]), )) } - pub fn fetch_storage_proof(key: &keys::storage::Key) -> Result<(HeaderMmrMeta, Account, Storage), FetcherError> { - let runtime = tokio::runtime::Runtime::new().unwrap(); + pub async fn fetch_storage_proof(key: &keys::storage::Key) -> Result<(HeaderMmrMeta, Account, Storage), FetcherError> { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let value = runtime - .block_on(async { - provider - .get_proof(key.address, vec![key.storage_slot]) - .block_id(key.block_number.into()) - .await - }) + let value = provider + .get_proof(key.address, vec![key.storage_slot]) + .block_id(key.block_number.into()) + .await .map_err(|e| FetcherError::InternalError(e.to_string()))?; Ok(( - Self::fetch_header_proof(&key.to_owned().into())?, + Self::fetch_header_proof(&key.to_owned().into()).await?, Account::new(value.address, vec![MPTProof::new(key.block_number, value.account_proof)]), Storage::new( value.address, diff --git a/examples/hdp_input.json b/examples/hdp_input.json new file mode 100644 index 00000000..0d2d8f0b --- /dev/null +++ b/examples/hdp_input.json @@ -0,0 +1,2272 @@ +{ + "params": [ + { + "visibility": "public", + "value": "0x5222A4" + }, + { + "visibility": "public", + "value": "0x5249B4" + }, + { + "visibility": "public", + "value": "0x75cec1db9dceb703200eaa6595f66885c962b920" + }, + { + "visibility": "public", + "value": "0x1" + }, + { + "visibility": "public", + "value": "0x0" + } + ], + "compiled_class": { + "prime": "0x800000000000011000000000000000000000000000000000000000000000001", + "compiler_version": "2.8.4", + "bytecode": [ + "0xa0680017fff8000", + "0x7", + "0x482680017ffa8000", + "0xffffffffffffffffffffffffffffe5d4", + "0x400280007ff97fff", + "0x10780017fff7fff", + "0x1b9", + "0x4825800180007ffa", + "0x1a2c", + "0x400280007ff97fff", + "0x480a7ffc7fff8000", + "0x480a7ffd7fff8000", + "0x1104800180018000", + "0x1c1", + "0x482680017ff98000", + "0x1", + "0x20680017fff7ffa", + "0x1a0", + "0x48307ff880007ff9", + "0x20680017fff7fff", + "0x4", + "0x10780017fff7fff", + "0xa", + "0x482480017ff78000", + "0x1", + "0x48127ff77fff8000", + "0x480680017fff8000", + "0x0", + "0x48127ff47fff8000", + "0x10780017fff7fff", + "0x8", + "0x48127ff77fff8000", + "0x48127ff77fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffe", + "0x17a", + "0x480080007fff8000", + "0xa0680017fff8000", + "0x12", + "0x4824800180007ffe", + "0x100000000", + "0x4844800180008002", + "0x8000000000000110000000000000000", + "0x4830800080017ffe", + "0x480080007ff57fff", + "0x482480017ffe8000", + "0xefffffffffffffde00000000ffffffff", + "0x480080017ff37fff", + "0x400080027ff27ffb", + "0x402480017fff7ffb", + "0xffffffffffffffffffffffffffffffff", + "0x20680017fff7fff", + "0x165", + "0x402780017fff7fff", + "0x1", + "0x400080007ff87ffe", + "0x482480017ffe8000", + "0xffffffffffffffffffffffff00000000", + "0x400080017ff77fff", + "0x482480017ff78000", + "0x2", + "0x48307ff880007ff9", + "0x20680017fff7fff", + "0x4", + "0x10780017fff7fff", + "0xa", + "0x482480017ff78000", + "0x1", + "0x48127ff77fff8000", + "0x480680017fff8000", + "0x0", + "0x48127ff47fff8000", + "0x10780017fff7fff", + "0x8", + "0x48127ff77fff8000", + "0x48127ff77fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffe", + "0x137", + "0x480080007fff8000", + "0xa0680017fff8000", + "0x12", + "0x4824800180007ffe", + "0x100000000", + "0x4844800180008002", + "0x8000000000000110000000000000000", + "0x4830800080017ffe", + "0x480080007ff57fff", + "0x482480017ffe8000", + "0xefffffffffffffde00000000ffffffff", + "0x480080017ff37fff", + "0x400080027ff27ffb", + "0x402480017fff7ffb", + "0xffffffffffffffffffffffffffffffff", + "0x20680017fff7fff", + "0x122", + "0x402780017fff7fff", + "0x1", + "0x400080007ff87ffe", + "0x482480017ffe8000", + "0xffffffffffffffffffffffff00000000", + "0x400080017ff77fff", + "0x482480017ff78000", + "0x2", + "0x48307ff880007ff9", + "0x20680017fff7fff", + "0x4", + "0x10780017fff7fff", + "0xa", + "0x482480017ff78000", + "0x1", + "0x48127ff77fff8000", + "0x480680017fff8000", + "0x0", + "0x480080007ff48000", + "0x10780017fff7fff", + "0x8", + "0x48127ff77fff8000", + "0x48127ff77fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffe", + "0xf7", + "0x48307ffc80007ffd", + "0x20680017fff7fff", + "0x4", + "0x10780017fff7fff", + "0xa", + "0x482480017ffb8000", + "0x1", + "0x48127ffb7fff8000", + "0x480680017fff8000", + "0x0", + "0x48127ff87fff8000", + "0x10780017fff7fff", + "0x8", + "0x48127ffb7fff8000", + "0x48127ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffe", + "0x6c", + "0x480080007fff8000", + "0xa0680017fff8000", + "0x16", + "0x480080007ff38003", + "0x480080017ff28003", + "0x4844800180017ffe", + "0x100000000000000000000000000000000", + "0x483080017ffd7ffb", + "0x482480017fff7ffd", + "0x800000000000010fffffffffffffffff7ffffffffffffef0000000000000001", + "0x20680017fff7ffc", + "0x6", + "0x402480017fff7ffd", + "0xffffffffffffffffffffffffffffffff", + "0x10780017fff7fff", + "0x4", + "0x402480017ffe7ffd", + "0xf7ffffffffffffef0000000000000000", + "0x400080027fee7ffd", + "0x20680017fff7ffe", + "0x51", + "0x402780017fff7fff", + "0x1", + "0x400080007ff37ffe", + "0x482480017ff38000", + "0x1", + "0x48307ff980007ffa", + "0x20680017fff7fff", + "0x4", + "0x10780017fff7fff", + "0xa", + "0x482480017ff88000", + "0x1", + "0x48127ff87fff8000", + "0x480680017fff8000", + "0x0", + "0x48127ff57fff8000", + "0x10780017fff7fff", + "0x8", + "0x48127ff87fff8000", + "0x48127ff87fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffe", + "0x2a", + "0x480080007fff8000", + "0xa0680017fff8000", + "0x16", + "0x480080007ff88003", + "0x480080017ff78003", + "0x4844800180017ffe", + "0x100000000000000000000000000000000", + "0x483080017ffd7ffb", + "0x482480017fff7ffd", + "0x800000000000010fffffffffffffffff7ffffffffffffef0000000000000001", + "0x20680017fff7ffc", + "0x6", + "0x402480017fff7ffd", + "0xffffffffffffffffffffffffffffffff", + "0x10780017fff7fff", + "0x4", + "0x402480017ffe7ffd", + "0xf7ffffffffffffef0000000000000000", + "0x400080027ff37ffd", + "0x20680017fff7ffe", + "0x11", + "0x402780017fff7fff", + "0x1", + "0x400080007ff87ffe", + "0x40780017fff7fff", + "0x5", + "0x482480017ff38000", + "0x1", + "0x48127ff47fff8000", + "0x48127ff47fff8000", + "0x480680017fff8000", + "0x0", + "0x48127fed7fff8000", + "0x48127ff47fff8000", + "0x10780017fff7fff", + "0x24", + "0x482480017ff38000", + "0x3", + "0x10780017fff7fff", + "0x5", + "0x40780017fff7fff", + "0x7", + "0x48127ff37fff8000", + "0x48127ff47fff8000", + "0x48127ff47fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x10780017fff7fff", + "0x13", + "0x40780017fff7fff", + "0x8", + "0x482480017fe68000", + "0x3", + "0x10780017fff7fff", + "0x5", + "0x40780017fff7fff", + "0xf", + "0x48127fe67fff8000", + "0x48127fec7fff8000", + "0x48127fec7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffd", + "0x5d", + "0x48307ffb80007ffc", + "0x20680017fff7fff", + "0x4", + "0x10780017fff7fff", + "0x10", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x496e70757420746f6f206c6f6e6720666f7220617267756d656e7473", + "0x400080007ffe7fff", + "0x48127ff77fff8000", + "0x48127fa07fff8000", + "0x480a7ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x1104800180018000", + "0x31b", + "0x482480017fff8000", + "0x31a", + "0x480080007fff8000", + "0xa0680017fff8000", + "0x9", + "0x4824800180007f9e", + "0xad2", + "0x482480017fff8000", + "0x100000000000000000000000000000000", + "0x400080007ff27fff", + "0x10780017fff7fff", + "0x2d", + "0x4824800180007f9e", + "0xad2", + "0x400080007ff37fff", + "0x482480017ff38000", + "0x1", + "0x48127ffe7fff8000", + "0x480a7ffb7fff8000", + "0x48127fca7fff8000", + "0x48127fd27fff8000", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x48127fd77fff8000", + "0x48127fef7fff8000", + "0x48127fef7fff8000", + "0x48127fb97fff8000", + "0x48127fb97fff8000", + "0x1104800180018000", + "0x140", + "0x20680017fff7ffc", + "0xf", + "0x40780017fff7fff", + "0x1", + "0x400080007fff7ffc", + "0x400080017fff7ffd", + "0x48127ff87fff8000", + "0x48127ff87fff8000", + "0x48127ff87fff8000", + "0x480680017fff8000", + "0x0", + "0x48127ffb7fff8000", + "0x482480017ffa8000", + "0x2", + "0x208b7fff7fff7ffe", + "0x48127ff97fff8000", + "0x48127ff97fff8000", + "0x48127ff97fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x48127ffa7fff8000", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4f7574206f6620676173", + "0x400080007ffe7fff", + "0x482480017ff08000", + "0x1", + "0x48127f997fff8000", + "0x480a7ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4661696c656420746f20646573657269616c697a6520706172616d202335", + "0x400080007ffe7fff", + "0x48127ff87fff8000", + "0x48127fa17fff8000", + "0x480a7ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4661696c656420746f20646573657269616c697a6520706172616d202334", + "0x400080007ffe7fff", + "0x48127ff87fff8000", + "0x48127fbb7fff8000", + "0x480a7ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x482480017ff28000", + "0x3", + "0x10780017fff7fff", + "0x5", + "0x40780017fff7fff", + "0x8", + "0x48127ff27fff8000", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4661696c656420746f20646573657269616c697a6520706172616d202333", + "0x400080007ffe7fff", + "0x48127ffd7fff8000", + "0x48127fbb7fff8000", + "0x480a7ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x482480017ff28000", + "0x3", + "0x10780017fff7fff", + "0x5", + "0x40780017fff7fff", + "0x8", + "0x48127ff27fff8000", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4661696c656420746f20646573657269616c697a6520706172616d202332", + "0x400080007ffe7fff", + "0x48127ffd7fff8000", + "0x48127fc47fff8000", + "0x480a7ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4661696c656420746f20646573657269616c697a6520706172616d202331", + "0x400080007ffe7fff", + "0x48127ffd7fff8000", + "0x48127fd27fff8000", + "0x480a7ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4f7574206f6620676173", + "0x400080007ffe7fff", + "0x482680017ff98000", + "0x1", + "0x480a7ffa7fff8000", + "0x480a7ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x48297ffc80007ffd", + "0x20680017fff7fff", + "0x4", + "0x10780017fff7fff", + "0xa", + "0x482680017ffc8000", + "0x1", + "0x480a7ffd7fff8000", + "0x480680017fff8000", + "0x0", + "0x480280007ffc8000", + "0x10780017fff7fff", + "0x8", + "0x480a7ffc7fff8000", + "0x480a7ffd7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffe", + "0x29", + "0x48307ffc80007ffd", + "0x20680017fff7fff", + "0x4", + "0x10780017fff7fff", + "0xa", + "0x482480017ffb8000", + "0x1", + "0x48127ffb7fff8000", + "0x480680017fff8000", + "0x0", + "0x480080007ff88000", + "0x10780017fff7fff", + "0x8", + "0x48127ffb7fff8000", + "0x48127ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffe", + "0xa", + "0x48127ffc7fff8000", + "0x48127ffc7fff8000", + "0x480680017fff8000", + "0x0", + "0x48127ff77fff8000", + "0x48127ffb7fff8000", + "0x10780017fff7fff", + "0x16", + "0x48127ffc7fff8000", + "0x48127ffc7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x10780017fff7fff", + "0xc", + "0x40780017fff7fff", + "0x5", + "0x48127ff77fff8000", + "0x48127ff77fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffd", + "0x60", + "0x48307ffb80007ffc", + "0x20680017fff7fff", + "0x4", + "0x10780017fff7fff", + "0xa", + "0x482480017ffa8000", + "0x1", + "0x48127ffa7fff8000", + "0x480680017fff8000", + "0x0", + "0x480080007ff78000", + "0x10780017fff7fff", + "0x8", + "0x48127ffa7fff8000", + "0x48127ffa7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffe", + "0x29", + "0x48307ffc80007ffd", + "0x20680017fff7fff", + "0x4", + "0x10780017fff7fff", + "0xa", + "0x482480017ffb8000", + "0x1", + "0x48127ffb7fff8000", + "0x480680017fff8000", + "0x0", + "0x480080007ff88000", + "0x10780017fff7fff", + "0x8", + "0x48127ffb7fff8000", + "0x48127ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffe", + "0xa", + "0x48127ffc7fff8000", + "0x48127ffc7fff8000", + "0x480680017fff8000", + "0x0", + "0x48127ff77fff8000", + "0x48127ffb7fff8000", + "0x10780017fff7fff", + "0x16", + "0x48127ffc7fff8000", + "0x48127ffc7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x10780017fff7fff", + "0xc", + "0x40780017fff7fff", + "0x5", + "0x48127ff77fff8000", + "0x48127ff77fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x20680017fff7ffd", + "0xb", + "0x48127ffb7fff8000", + "0x48127ffb7fff8000", + "0x480680017fff8000", + "0x0", + "0x48127fec7fff8000", + "0x48127fec7fff8000", + "0x48127ff97fff8000", + "0x48127ff97fff8000", + "0x208b7fff7fff7ffe", + "0x48127ffb7fff8000", + "0x48127ffb7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0xf", + "0x48127fec7fff8000", + "0x48127fec7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x480680017fff8000", + "0x0", + "0x208b7fff7fff7ffe", + "0xa0680017fff8000", + "0x7", + "0x482680017ff38000", + "0xffffffffffffffffffffffffffff9f3e", + "0x400280007ff27fff", + "0x10780017fff7fff", + "0xb6", + "0x4825800180007ff3", + "0x60c2", + "0x400280007ff27fff", + "0x48297ff680017ff5", + "0xa0680017fff7fff", + "0x7", + "0x482480017fff8000", + "0x100000000000000000000000000000000", + "0x400280017ff27fff", + "0x10780017fff7fff", + "0xd", + "0x400280017ff27fff", + "0x482680017ff28000", + "0x2", + "0x48127ffc7fff8000", + "0x480a7ff47fff8000", + "0x480680017fff8000", + "0x0", + "0x480a7ff77fff8000", + "0x480a7ff87fff8000", + "0x480a7ff57fff8000", + "0x208b7fff7fff7ffe", + "0x482680017ff28000", + "0x2", + "0x48127ffb7fff8000", + "0x480a7ff47fff8000", + "0x480a7ffc7fff8000", + "0x480a7ffd7fff8000", + "0x480680017fff8000", + "0xaa36a7", + "0x480a7ff57fff8000", + "0x480a7ff97fff8000", + "0x480a7ffa7fff8000", + "0x480a7ffb7fff8000", + "0x1104800180018000", + "0xa3", + "0x20680017fff7ffd", + "0x86", + "0x48327fff7ff88001", + "0xa0680017fff7fff", + "0x7", + "0x4824800180007fff", + "0x100000000000000000000000000000000", + "0x400080007ff77fff", + "0x10780017fff7fff", + "0xc", + "0x400080007ff87fff", + "0x40780017fff7fff", + "0x1", + "0x482480017ff78000", + "0x1", + "0x48127ffd7fff8000", + "0x480680017fff8000", + "0x0", + "0x10780017fff7fff", + "0x7", + "0x482480017ff78000", + "0x1", + "0x48127ffe7fff8000", + "0x480680017fff8000", + "0x1", + "0x48327ff87ff78001", + "0xa0680017fff7fff", + "0x7", + "0x4824800180007fff", + "0x100000000000000000000000000000000", + "0x400080007ffa7fff", + "0x10780017fff7fff", + "0xc", + "0x400080007ffb7fff", + "0x40780017fff7fff", + "0x5", + "0x482480017ff68000", + "0x1", + "0x48127ff97fff8000", + "0x48127ff57fff8000", + "0x48127ff57fff8000", + "0x10780017fff7fff", + "0x1c", + "0x480680017fff8000", + "0x1", + "0x48307fff7ffa8001", + "0xa0680017fff7fff", + "0x7", + "0x4824800180007fff", + "0x100000000000000000000000000000000", + "0x400080017ff67fff", + "0x10780017fff7fff", + "0xc", + "0x400080017ff77fff", + "0x40780017fff7fff", + "0x1", + "0x482480017ff68000", + "0x2", + "0x48127ffa7fff8000", + "0x48127ffc7fff8000", + "0x48127ff57fff8000", + "0x10780017fff7fff", + "0x8", + "0x482480017ff68000", + "0x2", + "0x48127ffa7fff8000", + "0x48127ffd7fff8000", + "0x480680017fff8000", + "0x1", + "0x20680017fff7fff", + "0x31", + "0x480680017fff8000", + "0x1", + "0xa0680017fff8000", + "0x8", + "0x48327ffe7ff58000", + "0x4824800180007fff", + "0x100000000", + "0x400080007ff87fff", + "0x10780017fff7fff", + "0x16", + "0x48327ffe7ff58001", + "0x4824800180007fff", + "0xffffffffffffffffffffffff00000000", + "0x400080007ff87ffe", + "0x482480017ff88000", + "0x1", + "0x48127fe57fff8000", + "0x48127fe57fff8000", + "0x48127ffc7fff8000", + "0x480a7ff67fff8000", + "0x48127ff47fff8000", + "0x48127ff47fff8000", + "0x480a7ff97fff8000", + "0x480a7ffa7fff8000", + "0x480a7ffb7fff8000", + "0x480a7ffc7fff8000", + "0x480a7ffd7fff8000", + "0x1104800180018000", + "0x800000000000010ffffffffffffffffffffffffffffffffffffffffffffff74", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x7533325f616464204f766572666c6f77", + "0x400080007ffe7fff", + "0x482480017ff68000", + "0x1", + "0x48127fe37fff8000", + "0x48127fe37fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x48127ff97fff8000", + "0x482480017ff88000", + "0x1", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x753235365f616464204f766572666c6f77", + "0x400080007ffe7fff", + "0x48127ffa7fff8000", + "0x48127fe77fff8000", + "0x48127fe77fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x48127ff97fff8000", + "0x482480017ff88000", + "0x1", + "0x208b7fff7fff7ffe", + "0x48127ffa7fff8000", + "0x48127ffa7fff8000", + "0x48127ffa7fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x48127ff97fff8000", + "0x48127ff97fff8000", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4f7574206f6620676173", + "0x400080007ffe7fff", + "0x482680017ff28000", + "0x1", + "0x480a7ff37fff8000", + "0x480a7ff47fff8000", + "0x480680017fff8000", + "0x1", + "0x480680017fff8000", + "0x0", + "0x48127ff97fff8000", + "0x482480017ff88000", + "0x1", + "0x208b7fff7fff7ffe", + "0x480680017fff8000", + "0x2", + "0xa0680017fff8004", + "0xe", + "0x4824800180047ffe", + "0x800000000000000000000000000000000000000000000000000000000000000", + "0x484480017ffe8000", + "0x110000000000000000", + "0x48307ffe7fff8002", + "0x480280007ff47ffc", + "0x480280017ff47ffc", + "0x402480017ffb7ffd", + "0xffffffffffffffeeffffffffffffffff", + "0x400280027ff47ffd", + "0x10780017fff7fff", + "0xd0", + "0x484480017fff8001", + "0x8000000000000000000000000000000", + "0x48307fff80007ffd", + "0x480280007ff47ffd", + "0x480280017ff47ffd", + "0x402480017ffc7ffe", + "0xf8000000000000000000000000000000", + "0x400280027ff47ffe", + "0x40780017fff7fff", + "0x1", + "0x400180007fff7ff7", + "0x400180017fff7ff8", + "0x400180027fff7ff9", + "0x400180037fff7ffa", + "0x400180047fff7ffb", + "0x400180057fff7ffd", + "0x400180067fff7ffc", + "0x480680017fff8000", + "0x0", + "0x48127ffe7fff8000", + "0x482480017ffd8000", + "0x7", + "0x482680017ff48000", + "0x3", + "0x480680017fff8000", + "0x43616c6c436f6e7472616374", + "0x400280007ff67fff", + "0x400380017ff67ff5", + "0x400280027ff67ff4", + "0x400280037ff67ffb", + "0x400280047ff67ffc", + "0x400280057ff67ffd", + "0x480280077ff68000", + "0x20680017fff7fff", + "0xa2", + "0x480280087ff68000", + "0x480280097ff68000", + "0x480680017fff8000", + "0x0", + "0x480280067ff68000", + "0x482680017ff68000", + "0xa", + "0x480280087ff68000", + "0x480280097ff68000", + "0x48307ff980007ffa", + "0xa0680017fff8000", + "0x6", + "0x48307ffe80007ff9", + "0x400080007ff37fff", + "0x10780017fff7fff", + "0x81", + "0x482480017ff98000", + "0x1", + "0x48307fff80007ffd", + "0x400080007ff27fff", + "0x48307ff77ff58000", + "0x480080007fff8000", + "0xa0680017fff8000", + "0x16", + "0x480080017fef8003", + "0x480080027fee8003", + "0x4844800180017ffe", + "0x100000000000000000000000000000000", + "0x483080017ffd7ffb", + "0x482480017fff7ffd", + "0x800000000000010fffffffffffffffff7ffffffffffffef0000000000000001", + "0x20680017fff7ffc", + "0x6", + "0x402480017fff7ffd", + "0xffffffffffffffffffffffffffffffff", + "0x10780017fff7fff", + "0x4", + "0x402480017ffe7ffd", + "0xf7ffffffffffffef0000000000000000", + "0x400080037fea7ffd", + "0x20680017fff7ffe", + "0x56", + "0x402780017fff7fff", + "0x1", + "0x400080017fef7ffe", + "0x480680017fff8000", + "0x1", + "0x48307ff680007ff7", + "0xa0680017fff8000", + "0x6", + "0x48307ffe80007ffd", + "0x400080027feb7fff", + "0x10780017fff7fff", + "0x39", + "0x482480017ffd8000", + "0x1", + "0x48307fff80007ffd", + "0x400080027fea7fff", + "0x48307ffb7ff28000", + "0x480080007fff8000", + "0xa0680017fff8000", + "0x16", + "0x480080037fe78003", + "0x480080047fe68003", + "0x4844800180017ffe", + "0x100000000000000000000000000000000", + "0x483080017ffd7ffb", + "0x482480017fff7ffd", + "0x800000000000010fffffffffffffffff7ffffffffffffef0000000000000001", + "0x20680017fff7ffc", + "0x6", + "0x402480017fff7ffd", + "0xffffffffffffffffffffffffffffffff", + "0x10780017fff7fff", + "0x4", + "0x402480017ffe7ffd", + "0xf7ffffffffffffef0000000000000000", + "0x400080057fe27ffd", + "0x20680017fff7ffe", + "0x10", + "0x402780017fff7fff", + "0x1", + "0x400080037fe77ffe", + "0x40780017fff7fff", + "0x7", + "0x482480017fe08000", + "0x4", + "0x48127fe57fff8000", + "0x48127fe57fff8000", + "0x480680017fff8000", + "0x0", + "0x48127feb7fff8000", + "0x48127ff27fff8000", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4f7074696f6e3a3a756e77726170206661696c65642e", + "0x400080007ffe7fff", + "0x482480017fe08000", + "0x6", + "0x48127fe57fff8000", + "0x48127fe57fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x9", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x496e646578206f7574206f6620626f756e6473", + "0x400080007ffe7fff", + "0x482480017fe08000", + "0x3", + "0x48127fe57fff8000", + "0x48127fe57fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x8", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4f7074696f6e3a3a756e77726170206661696c65642e", + "0x400080007ffe7fff", + "0x482480017fe08000", + "0x4", + "0x48127fe57fff8000", + "0x48127fe57fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x11", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x496e646578206f7574206f6620626f756e6473", + "0x400080007ffe7fff", + "0x482480017fe08000", + "0x1", + "0x48127fe57fff8000", + "0x48127fe57fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x1d", + "0x48127fe07fff8000", + "0x480280067ff68000", + "0x482680017ff68000", + "0xa", + "0x480680017fff8000", + "0x1", + "0x480280087ff68000", + "0x480280097ff68000", + "0x208b7fff7fff7ffe", + "0x40780017fff7fff", + "0x21", + "0x40780017fff7fff", + "0x1", + "0x480680017fff8000", + "0x4f7074696f6e3a3a756e77726170206661696c65642e", + "0x400080007ffe7fff", + "0x482680017ff48000", + "0x3", + "0x480a7ff57fff8000", + "0x480a7ff67fff8000", + "0x480680017fff8000", + "0x1", + "0x48127ffa7fff8000", + "0x482480017ff98000", + "0x1", + "0x208b7fff7fff7ffe" + ], + "bytecode_segment_lengths": [ + 461, + 181, + 204, + 239 + ], + "hints": [ + [ + 0, + [ + { + "TestLessThanOrEqual": { + "lhs": { + "Immediate": "0x1a2c" + }, + "rhs": { + "Deref": { + "register": "FP", + "offset": -6 + } + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 40, + [ + { + "TestLessThan": { + "lhs": { + "BinOp": { + "op": "Add", + "a": { + "register": "AP", + "offset": -1 + }, + "b": { + "Immediate": "0x0" + } + } + }, + "rhs": { + "Immediate": "0x100000000" + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 44, + [ + { + "LinearSplit": { + "value": { + "Deref": { + "register": "AP", + "offset": -1 + } + }, + "scalar": { + "Immediate": "0x8000000000000110000000000000000" + }, + "max_x": { + "Immediate": "0xfffffffffffffffffffffffffffffffe" + }, + "x": { + "register": "AP", + "offset": 0 + }, + "y": { + "register": "AP", + "offset": 1 + } + } + } + ] + ], + [ + 86, + [ + { + "TestLessThan": { + "lhs": { + "BinOp": { + "op": "Add", + "a": { + "register": "AP", + "offset": -1 + }, + "b": { + "Immediate": "0x0" + } + } + }, + "rhs": { + "Immediate": "0x100000000" + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 90, + [ + { + "LinearSplit": { + "value": { + "Deref": { + "register": "AP", + "offset": -1 + } + }, + "scalar": { + "Immediate": "0x8000000000000110000000000000000" + }, + "max_x": { + "Immediate": "0xfffffffffffffffffffffffffffffffe" + }, + "x": { + "register": "AP", + "offset": 0 + }, + "y": { + "register": "AP", + "offset": 1 + } + } + } + ] + ], + [ + 153, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -1 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 155, + [ + { + "DivMod": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -2 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "quotient": { + "register": "AP", + "offset": 3 + }, + "remainder": { + "register": "AP", + "offset": 4 + } + } + } + ] + ], + [ + 200, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -1 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 202, + [ + { + "DivMod": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -2 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "quotient": { + "register": "AP", + "offset": 3 + }, + "remainder": { + "register": "AP", + "offset": 4 + } + } + } + ] + ], + [ + 276, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 295, + [ + { + "TestLessThanOrEqual": { + "lhs": { + "Immediate": "0xad2" + }, + "rhs": { + "Deref": { + "register": "AP", + "offset": -97 + } + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 326, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 347, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 362, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 376, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 397, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 418, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 432, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 446, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 642, + [ + { + "TestLessThanOrEqual": { + "lhs": { + "Immediate": "0x60c2" + }, + "rhs": { + "Deref": { + "register": "FP", + "offset": -13 + } + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 653, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": 0 + } + }, + "rhs": { + "Immediate": "0x100000000" + }, + "dst": { + "register": "AP", + "offset": -1 + } + } + } + ] + ], + [ + 688, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": 0 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "dst": { + "register": "AP", + "offset": -1 + } + } + } + ] + ], + [ + 711, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": 0 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "dst": { + "register": "AP", + "offset": -1 + } + } + } + ] + ], + [ + 731, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": 0 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "dst": { + "register": "AP", + "offset": -1 + } + } + } + ] + ], + [ + 758, + [ + { + "TestLessThan": { + "lhs": { + "BinOp": { + "op": "Add", + "a": { + "register": "FP", + "offset": -11 + }, + "b": { + "Deref": { + "register": "AP", + "offset": -1 + } + } + } + }, + "rhs": { + "Immediate": "0x100000000" + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 786, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 803, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 829, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 848, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -1 + } + }, + "rhs": { + "Immediate": "0x800000000000000000000000000000000000000000000000000000000000000" + }, + "dst": { + "register": "AP", + "offset": 4 + } + } + } + ] + ], + [ + 852, + [ + { + "LinearSplit": { + "value": { + "Deref": { + "register": "AP", + "offset": 3 + } + }, + "scalar": { + "Immediate": "0x110000000000000000" + }, + "max_x": { + "Immediate": "0xffffffffffffffffffffffffffffffff" + }, + "x": { + "register": "AP", + "offset": -2 + }, + "y": { + "register": "AP", + "offset": -1 + } + } + } + ] + ], + [ + 862, + [ + { + "LinearSplit": { + "value": { + "Deref": { + "register": "AP", + "offset": -2 + } + }, + "scalar": { + "Immediate": "0x8000000000000000000000000000000" + }, + "max_x": { + "Immediate": "0xffffffffffffffffffffffffffffffff" + }, + "x": { + "register": "AP", + "offset": -1 + }, + "y": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 870, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 894, + [ + { + "SystemCall": { + "system": { + "Deref": { + "register": "FP", + "offset": -10 + } + } + } + } + ] + ], + [ + 907, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -6 + } + }, + "rhs": { + "Deref": { + "register": "AP", + "offset": -1 + } + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 919, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -1 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 921, + [ + { + "DivMod": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -2 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "quotient": { + "register": "AP", + "offset": 3 + }, + "remainder": { + "register": "AP", + "offset": 4 + } + } + } + ] + ], + [ + 945, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -2 + } + }, + "rhs": { + "Deref": { + "register": "AP", + "offset": -1 + } + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 957, + [ + { + "TestLessThan": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -1 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 959, + [ + { + "DivMod": { + "lhs": { + "Deref": { + "register": "AP", + "offset": -2 + } + }, + "rhs": { + "Immediate": "0x100000000000000000000000000000000" + }, + "quotient": { + "register": "AP", + "offset": 3 + }, + "remainder": { + "register": "AP", + "offset": 4 + } + } + } + ] + ], + [ + 991, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 1008, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 1025, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 1042, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ], + [ + 1070, + [ + { + "AllocSegment": { + "dst": { + "register": "AP", + "offset": 0 + } + } + } + ] + ] + ], + "pythonic_hints": [ + [ + 0, + [ + "memory[ap + 0] = 6700 <= memory[fp + -6]" + ] + ], + [ + 40, + [ + "memory[ap + 0] = (memory[ap + -1] + 0) % PRIME < 4294967296" + ] + ], + [ + 44, + [ + "\n(value, scalar) = (memory[ap + -1], 10633823966279327296825105735305134080)\nx = min(value // scalar, 340282366920938463463374607431768211454)\ny = value - x * scalar\nmemory[ap + 0] = x\nmemory[ap + 1] = y\n" + ] + ], + [ + 86, + [ + "memory[ap + 0] = (memory[ap + -1] + 0) % PRIME < 4294967296" + ] + ], + [ + 90, + [ + "\n(value, scalar) = (memory[ap + -1], 10633823966279327296825105735305134080)\nx = min(value // scalar, 340282366920938463463374607431768211454)\ny = value - x * scalar\nmemory[ap + 0] = x\nmemory[ap + 1] = y\n" + ] + ], + [ + 153, + [ + "memory[ap + 0] = memory[ap + -1] < 340282366920938463463374607431768211456" + ] + ], + [ + 155, + [ + "(memory[ap + 3], memory[ap + 4]) = divmod(memory[ap + -2], 340282366920938463463374607431768211456)" + ] + ], + [ + 200, + [ + "memory[ap + 0] = memory[ap + -1] < 340282366920938463463374607431768211456" + ] + ], + [ + 202, + [ + "(memory[ap + 3], memory[ap + 4]) = divmod(memory[ap + -2], 340282366920938463463374607431768211456)" + ] + ], + [ + 276, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 295, + [ + "memory[ap + 0] = 2770 <= memory[ap + -97]" + ] + ], + [ + 326, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 347, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 362, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 376, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 397, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 418, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 432, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 446, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 642, + [ + "memory[ap + 0] = 24770 <= memory[fp + -13]" + ] + ], + [ + 653, + [ + "memory[ap + -1] = memory[ap + 0] < 4294967296" + ] + ], + [ + 688, + [ + "memory[ap + -1] = memory[ap + 0] < 340282366920938463463374607431768211456" + ] + ], + [ + 711, + [ + "memory[ap + -1] = memory[ap + 0] < 340282366920938463463374607431768211456" + ] + ], + [ + 731, + [ + "memory[ap + -1] = memory[ap + 0] < 340282366920938463463374607431768211456" + ] + ], + [ + 758, + [ + "memory[ap + 0] = (memory[fp + -11] + memory[ap + -1]) % PRIME < 4294967296" + ] + ], + [ + 786, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 803, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 829, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 848, + [ + "memory[ap + 4] = memory[ap + -1] < 3618502788666131106986593281521497120414687020801267626233049500247285301248" + ] + ], + [ + 852, + [ + "\n(value, scalar) = (memory[ap + 3], 313594649253062377472)\nx = min(value // scalar, 340282366920938463463374607431768211455)\ny = value - x * scalar\nmemory[ap + -2] = x\nmemory[ap + -1] = y\n" + ] + ], + [ + 862, + [ + "\n(value, scalar) = (memory[ap + -2], 10633823966279326983230456482242756608)\nx = min(value // scalar, 340282366920938463463374607431768211455)\ny = value - x * scalar\nmemory[ap + -1] = x\nmemory[ap + 0] = y\n" + ] + ], + [ + 870, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 894, + [ + "syscall_handler.syscall(syscall_ptr=memory[fp + -10])" + ] + ], + [ + 907, + [ + "memory[ap + 0] = memory[ap + -6] < memory[ap + -1]" + ] + ], + [ + 919, + [ + "memory[ap + 0] = memory[ap + -1] < 340282366920938463463374607431768211456" + ] + ], + [ + 921, + [ + "(memory[ap + 3], memory[ap + 4]) = divmod(memory[ap + -2], 340282366920938463463374607431768211456)" + ] + ], + [ + 945, + [ + "memory[ap + 0] = memory[ap + -2] < memory[ap + -1]" + ] + ], + [ + 957, + [ + "memory[ap + 0] = memory[ap + -1] < 340282366920938463463374607431768211456" + ] + ], + [ + 959, + [ + "(memory[ap + 3], memory[ap + 4]) = divmod(memory[ap + -2], 340282366920938463463374607431768211456)" + ] + ], + [ + 991, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 1008, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 1025, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 1042, + [ + "memory[ap + 0] = segments.add()" + ] + ], + [ + 1070, + [ + "memory[ap + 0] = segments.add()" + ] + ] + ], + "entry_points_by_type": { + "EXTERNAL": [ + { + "selector": "0xe2054f8a912367e38a22ce773328ff8aabf8082c4120bad9ef085e1dbf29a7", + "offset": 0, + "builtins": [ + "range_check" + ] + } + ], + "L1_HANDLER": [], + "CONSTRUCTOR": [] + } + } +} \ No newline at end of file diff --git a/tools/js/merkle.js b/tools/js/merkle.js deleted file mode 100644 index 46cf6ba7..00000000 --- a/tools/js/merkle.js +++ /dev/null @@ -1,24 +0,0 @@ -import { StandardMerkleTree } from "@openzeppelin/merkle-tree"; -import { create } from "domain"; -import fs from "fs"; - -function createMerkleTreeValues() { - const values = [ - ["0x0000000000000000000000000000000000000000000000000000000000000001"], - ["0x0000000000000000000000000000000000000000000000000000000000000002"], - ["0x000000000000000000000000000000000000000000000000000000000000007a"], - ["0x0000000000000000000000000000000000000000000000000000000000000004"], - ["0x0000000000000000000000000000000000000000000000000000000000000001"], - ]; - - let roots = []; - for(let i = 0; i < values.length; i++) { - const subset = values.slice(0, i + 1); - const tree = StandardMerkleTree.of(subset, ["bytes32"], {sortLeaves: false}); - roots.push(tree.root); - } - - console.log(roots); -} - -// createMerkleTreeValues(); \ No newline at end of file diff --git a/tools/js/package.json b/tools/js/package.json deleted file mode 100644 index 00df4053..00000000 --- a/tools/js/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "tools", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "type": "module", - "keywords": [], - "author": "", - "dependencies": { - "@openzeppelin/merkle-tree": "^1.0.6" - } -} From ec046f65edf8dd82b604abc148bf1185fd5f99bd Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 25 Dec 2024 19:23:06 +0100 Subject: [PATCH 62/75] example input fix --- examples/hdp_input.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/hdp_input.json b/examples/hdp_input.json index 0d2d8f0b..cf3f30dd 100644 --- a/examples/hdp_input.json +++ b/examples/hdp_input.json @@ -6,7 +6,7 @@ }, { "visibility": "public", - "value": "0x5249B4" + "value": "0x5222FF" }, { "visibility": "public", From 03b9fbbf22fe1a1e547dbd98e6f080e352e95054 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 25 Dec 2024 21:14:28 +0100 Subject: [PATCH 63/75] fetcher fix --- crates/fetcher/src/main.rs | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index 75741f8c..87e87e72 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -50,44 +50,41 @@ async fn main() -> Result<(), FetcherError> { let mut headers_with_mmr: HashSet = HashSet::default(); - while let Some(Ok(item)) = futures::stream::iter(proof_keys.header_keys.iter().map(ProofKeys::fetch_header_proof).map(|f| f.boxed_local())) - .buffer_unordered(BUFFER_UNORDERED) - .next() - .await - { + let mut headers_with_mmr_fut = futures::stream::iter(proof_keys.header_keys.iter().map(ProofKeys::fetch_header_proof).map(|f| f.boxed_local())) + .buffer_unordered(BUFFER_UNORDERED); + + while let Some(Ok(item)) = headers_with_mmr_fut.next().await { headers_with_mmr.insert(item); } let mut accounts: HashSet = HashSet::default(); - while let Some(Ok((header_with_mmr, account))) = futures::stream::iter( + let mut accounts_fut = futures::stream::iter( proof_keys .account_keys .iter() .map(ProofKeys::fetch_account_proof) .map(|f| f.boxed_local()), ) - .buffer_unordered(BUFFER_UNORDERED) - .next() - .await - { + .buffer_unordered(BUFFER_UNORDERED); + + while let Some(Ok((header_with_mmr, account))) = accounts_fut.next().await { headers_with_mmr.insert(header_with_mmr); accounts.insert(account); } let mut storages: HashSet = HashSet::default(); - while let Some(Ok((header_with_mmr, account, storage))) = futures::stream::iter( + let mut storages_fut = futures::stream::iter( proof_keys .storage_keys .iter() .map(ProofKeys::fetch_storage_proof) .map(|f| f.boxed_local()), ) - .buffer_unordered(BUFFER_UNORDERED) - .next() - .await - { + .buffer_unordered(BUFFER_UNORDERED); + + while let Some(Ok((header_with_mmr, account, storage))) = storages_fut.next().await { headers_with_mmr.insert(header_with_mmr.clone()); accounts.insert(account); storages.insert(storage); From af99553e2e11de6c6697580af4b4494bea6a5b22 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 25 Dec 2024 21:47:24 +0100 Subject: [PATCH 64/75] fetcher progress bars --- Cargo.lock | 55 ++++++++++++++++++++++++++++++++++++++ Cargo.toml | 1 + crates/fetcher/Cargo.toml | 1 + crates/fetcher/src/main.rs | 21 ++++++++++++++- 4 files changed, 77 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 8bfa2fd0..e4509d18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1728,6 +1728,19 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "console" +version = "0.15.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea3c6ecd8059b57859df5c69830340ed3c41d30e3da0c1cbed90a96ac853041b" +dependencies = [ + "encode_unicode", + "libc", + "once_cell", + "unicode-width", + "windows-sys 0.59.0", +] + [[package]] name = "const-fnv1a-hash" version = "1.1.0" @@ -2141,6 +2154,12 @@ dependencies = [ "log", ] +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + [[package]] name = "encoding_rs" version = "0.8.35" @@ -2221,6 +2240,7 @@ dependencies = [ "dry_hint_processor", "futures", "indexer", + "indicatif", "serde_json", "thiserror 1.0.69", "tokio", @@ -2982,6 +3002,19 @@ dependencies = [ "serde", ] +[[package]] +name = "indicatif" +version = "0.17.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbf675b85ed934d3c67b5c5469701eec7db22689d0a2139d856e0925fa28b281" +dependencies = [ + "console", + "number_prefix", + "portable-atomic", + "unicode-width", + "web-time", +] + [[package]] name = "indoc" version = "2.0.5" @@ -3438,6 +3471,12 @@ dependencies = [ "syn 2.0.91", ] +[[package]] +name = "number_prefix" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" + [[package]] name = "nybbles" version = "0.3.0" @@ -5335,6 +5374,12 @@ version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" +[[package]] +name = "unicode-width" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" + [[package]] name = "unicode-xid" version = "0.2.6" @@ -5524,6 +5569,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-roots" version = "0.26.7" diff --git a/Cargo.toml b/Cargo.toml index a6fc87d9..3de9231e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ strum_macros = "0.26.4" thiserror = "1.0.64" tiny-keccak = { version = "2.0.2", features = ["keccak"] } tokio = { version = "1.41.1", features = ["full"] } +indicatif = "0.17.9" dry_hint_processor = { path = "crates/dry_hint_processor" } eth_essentials_cairo_vm_hints = { path = "packages/eth_essentials/cairo_vm_hints"} diff --git a/crates/fetcher/Cargo.toml b/crates/fetcher/Cargo.toml index a3bca172..aab6f76d 100644 --- a/crates/fetcher/Cargo.toml +++ b/crates/fetcher/Cargo.toml @@ -11,6 +11,7 @@ futures.workspace = true serde_json.workspace = true thiserror.workspace = true tokio.workspace = true +indicatif.workspace = true indexer.workspace = true types.workspace = true \ No newline at end of file diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index 87e87e72..42998e6b 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -8,6 +8,7 @@ use clap::{Parser, ValueHint}; use dry_hint_processor::syscall_handler::evm::{self, SyscallHandler}; use futures::{FutureExt, StreamExt}; use indexer::types::IndexerError; +use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use proof_keys::ProofKeys; use std::{collections::HashSet, fs, num::ParseIntError, path::PathBuf}; use thiserror::Error; @@ -15,7 +16,7 @@ use types::proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}; pub mod proof_keys; -const BUFFER_UNORDERED: usize = 10; +const BUFFER_UNORDERED: usize = 50; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] @@ -30,6 +31,11 @@ struct Args { async fn main() -> Result<(), FetcherError> { let args = Args::try_parse_from(std::env::args()).map_err(FetcherError::Args)?; + let multi_progress = MultiProgress::new(); + let progress_style = ProgressStyle::with_template("[{elapsed_precise}] [{bar:40}] {pos}/{len} {msg}") + .unwrap() + .progress_chars("=> "); + let input_file = fs::read(args.filename)?; let syscall_handler = serde_json::from_slice::(&input_file)?; @@ -48,6 +54,16 @@ async fn main() -> Result<(), FetcherError> { } } + let pb_header_keys = multi_progress.add(ProgressBar::new(proof_keys.header_keys.len() as u64)); + let pb_account_keys = multi_progress.add(ProgressBar::new(proof_keys.account_keys.len() as u64)); + let pb_storage_keys = multi_progress.add(ProgressBar::new(proof_keys.storage_keys.len() as u64)); + pb_header_keys.set_style(progress_style.clone()); + pb_header_keys.set_message("header_keys"); + pb_account_keys.set_style(progress_style.clone()); + pb_account_keys.set_message("account_keys"); + pb_storage_keys.set_style(progress_style); + pb_storage_keys.set_message("storage_keys"); + let mut headers_with_mmr: HashSet = HashSet::default(); let mut headers_with_mmr_fut = futures::stream::iter(proof_keys.header_keys.iter().map(ProofKeys::fetch_header_proof).map(|f| f.boxed_local())) @@ -55,6 +71,7 @@ async fn main() -> Result<(), FetcherError> { while let Some(Ok(item)) = headers_with_mmr_fut.next().await { headers_with_mmr.insert(item); + pb_header_keys.inc(1); } let mut accounts: HashSet = HashSet::default(); @@ -71,6 +88,7 @@ async fn main() -> Result<(), FetcherError> { while let Some(Ok((header_with_mmr, account))) = accounts_fut.next().await { headers_with_mmr.insert(header_with_mmr); accounts.insert(account); + pb_account_keys.inc(1); } let mut storages: HashSet = HashSet::default(); @@ -88,6 +106,7 @@ async fn main() -> Result<(), FetcherError> { headers_with_mmr.insert(header_with_mmr.clone()); accounts.insert(account); storages.insert(storage); + pb_storage_keys.inc(1); } let proofs = Proofs { From 58c1d48d1bcd2bd7f588be9cd5f22c34f790290b Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Wed, 25 Dec 2024 21:49:15 +0100 Subject: [PATCH 65/75] sort --- Cargo.toml | 2 +- crates/fetcher/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3de9231e..ad3e678e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ cairo-vm = { git = "https://github.com/lambdaclass/cairo-vm", rev = "388a4e51001 clap = { version = "4.3.10", features = ["derive"] } futures = "0.3.31" hex = "0.4.3" +indicatif = "0.17.9" num-bigint = "0.4.6" num-traits = "0.2.19" rand = "0.8" @@ -39,7 +40,6 @@ strum_macros = "0.26.4" thiserror = "1.0.64" tiny-keccak = { version = "2.0.2", features = ["keccak"] } tokio = { version = "1.41.1", features = ["full"] } -indicatif = "0.17.9" dry_hint_processor = { path = "crates/dry_hint_processor" } eth_essentials_cairo_vm_hints = { path = "packages/eth_essentials/cairo_vm_hints"} diff --git a/crates/fetcher/Cargo.toml b/crates/fetcher/Cargo.toml index aab6f76d..18901adf 100644 --- a/crates/fetcher/Cargo.toml +++ b/crates/fetcher/Cargo.toml @@ -8,10 +8,10 @@ alloy.workspace = true clap.workspace = true dry_hint_processor.workspace = true futures.workspace = true +indicatif.workspace = true serde_json.workspace = true thiserror.workspace = true tokio.workspace = true -indicatif.workspace = true indexer.workspace = true types.workspace = true \ No newline at end of file From 905999a6ffde1b70726638f4c9c731708414d5f3 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Thu, 26 Dec 2024 10:10:54 +0100 Subject: [PATCH 66/75] tracing logger debug msgs --- Cargo.lock | 70 ++++++++++++++++--- Cargo.toml | 2 + crates/dry_run/Cargo.toml | 2 + crates/dry_run/src/main.rs | 5 +- crates/hints/Cargo.toml | 3 +- crates/hints/src/lib.rs | 2 +- crates/hints/src/print.rs | 36 +++++++++- crates/hints/src/verifiers/mod.rs | 1 - crates/hints/src/verifiers/utils.rs | 39 ----------- crates/sound_run/Cargo.toml | 2 + crates/sound_run/src/main.rs | 5 +- .../contract_dry_run.cairo | 2 +- 12 files changed, 112 insertions(+), 57 deletions(-) delete mode 100644 crates/hints/src/verifiers/utils.rs diff --git a/Cargo.lock b/Cargo.lock index e4509d18..9c11c0a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2091,6 +2091,8 @@ dependencies = [ "serde_json", "sha2", "thiserror 1.0.69", + "tracing", + "tracing-subscriber", "types", ] @@ -2620,13 +2622,14 @@ dependencies = [ "reqwest", "serde", "serde_json", - "serde_with 3.11.0", + "serde_with 3.12.0", "starknet-core", "starknet-crypto 0.7.3", "starknet-types-core", "strum_macros", "thiserror 1.0.69", "tokio", + "tracing", "types", ] @@ -2975,7 +2978,7 @@ dependencies = [ "reqwest", "serde", "serde_json", - "serde_with 3.11.0", + "serde_with 3.12.0", "thiserror 1.0.69", "tokio", ] @@ -3847,9 +3850,9 @@ checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" [[package]] name = "quote" -version = "1.0.37" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" dependencies = [ "proc-macro2", ] @@ -4477,9 +4480,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.11.0" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28bdad6db2b8340e449f7108f020b3b092e8583a9e3fb82713e1d4e71fe817" +checksum = "d6b6f7f2fcb69f747921f79f3926bd1e203fce4fef62c268dd3abfb6d86029aa" dependencies = [ "base64 0.22.1", "chrono", @@ -4489,7 +4492,7 @@ dependencies = [ "serde", "serde_derive", "serde_json", - "serde_with_macros 3.11.0", + "serde_with_macros 3.12.0", "time", ] @@ -4507,9 +4510,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.11.0" +version = "3.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d846214a9854ef724f3da161b426242d8de7c1fc7de2f89bb1efcb154dca79d" +checksum = "8d00caa5193a3c8362ac2b73be6b9e768aa5a4b2f721d8f4b339600c3cb51f8e" dependencies = [ "darling", "proc-macro2", @@ -4559,6 +4562,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "1.3.0" @@ -4653,6 +4665,8 @@ dependencies = [ "sha2", "sound_hint_processor", "thiserror 1.0.69", + "tracing", + "tracing-subscriber", "types", ] @@ -5030,6 +5044,16 @@ dependencies = [ "thiserror-impl-no-std", ] +[[package]] +name = "thread_local" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" +dependencies = [ + "cfg-if", + "once_cell", +] + [[package]] name = "threadpool" version = "1.8.1" @@ -5268,6 +5292,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008" +dependencies = [ + "nu-ansi-term", + "sharded-slab", + "smallvec", + "thread_local", + "tracing-core", + "tracing-log", ] [[package]] @@ -5323,7 +5373,7 @@ dependencies = [ "cairo-vm", "serde", "serde_json", - "serde_with 3.11.0", + "serde_with 3.12.0", "starknet-crypto 0.7.3", "strum_macros", "thiserror 1.0.69", diff --git a/Cargo.toml b/Cargo.toml index ad3e678e..ca48acdc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,8 @@ strum_macros = "0.26.4" thiserror = "1.0.64" tiny-keccak = { version = "2.0.2", features = ["keccak"] } tokio = { version = "1.41.1", features = ["full"] } +tracing = "0.1" +tracing-subscriber = "0.3" dry_hint_processor = { path = "crates/dry_hint_processor" } eth_essentials_cairo_vm_hints = { path = "packages/eth_essentials/cairo_vm_hints"} diff --git a/crates/dry_run/Cargo.toml b/crates/dry_run/Cargo.toml index e0a923af..4ea2d4b4 100644 --- a/crates/dry_run/Cargo.toml +++ b/crates/dry_run/Cargo.toml @@ -9,6 +9,8 @@ clap.workspace = true dry_hint_processor.workspace = true serde_json.workspace = true thiserror.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true hints.workspace = true types.workspace = true diff --git a/crates/dry_run/src/main.rs b/crates/dry_run/src/main.rs index 1482ba58..200faaab 100644 --- a/crates/dry_run/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -18,6 +18,7 @@ use dry_hint_processor::{ }; use hints::vars; use std::{env, path::PathBuf}; +use tracing::debug; use types::HDPDryRunInput; #[derive(Parser, Debug)] @@ -34,6 +35,8 @@ struct Args { } fn main() -> Result<(), HdpOsError> { + tracing_subscriber::fmt::init(); + let args = Args::try_parse_from(std::env::args()).map_err(HdpOsError::Args)?; // Init CairoRunConfig @@ -77,7 +80,7 @@ fn main() -> Result<(), HdpOsError> { .map_err(|e| HdpOsError::Runner(e.into()))?; cairo_runner.vm.compute_segments_effective_sizes(); - println!("{:?}", cairo_runner.get_execution_resources()); + debug!("{:?}", cairo_runner.get_execution_resources()); std::fs::write( args.program_output, diff --git a/crates/hints/Cargo.toml b/crates/hints/Cargo.toml index 745e8e15..6d47c90e 100644 --- a/crates/hints/Cargo.toml +++ b/crates/hints/Cargo.toml @@ -24,7 +24,8 @@ starknet-crypto.workspace = true starknet-types-core.workspace = true strum_macros.workspace = true thiserror.workspace = true -tokio = { workspace = true } +tokio.workspace = true +tracing.workspace = true eth_essentials_cairo_vm_hints.workspace = true types.workspace = true \ No newline at end of file diff --git a/crates/hints/src/lib.rs b/crates/hints/src/lib.rs index fd800fd1..3b615030 100644 --- a/crates/hints/src/lib.rs +++ b/crates/hints/src/lib.rs @@ -39,6 +39,7 @@ pub fn hints() -> HashMap { hints.insert(merkle::HINT_IS_LEFT_SMALLER.into(), merkle::hint_is_left_smaller); hints.insert(merkle::HINT_TARGET_TASK_HASH.into(), merkle::hint_target_task_hash); hints.insert(print::PROGRAM_HASH.into(), print::program_hash); + hints.insert(print::HINT_PRINT_TASK_RESULT.into(), print::hint_print_task_result); hints.insert(rlp::divmod::HINT_DIVMOD_RLP.into(), rlp::divmod::hint_divmod_rlp); hints.insert(rlp::divmod::HINT_DIVMOD_VALUE.into(), rlp::divmod::hint_divmod_value); hints.insert(rlp::item_type::HINT_IS_LONG.into(), rlp::item_type::hint_is_long); @@ -98,7 +99,6 @@ pub fn hints() -> HashMap { hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_ROOT.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_root); hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_SIZE.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_size); hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_PEAKS.into(), verifiers::mmr_verifier::hint_headers_with_mmr_peaks); - hints.insert(verifiers::utils::HINT_PRINT_TASK_RESULT.into(), verifiers::utils::hint_print_task_result); hints.insert(verifiers::verify::HINT_HEADERS_WITH_MMR_LEN.into(), verifiers::verify::hint_headers_with_mmr_headers_len); hints.insert(verifiers::verify::HINT_VM_ENTER_SCOPE.into(), verifiers::verify::hint_vm_enter_scope); diff --git a/crates/hints/src/print.rs b/crates/hints/src/print.rs index 4899fa60..0599490b 100644 --- a/crates/hints/src/print.rs +++ b/crates/hints/src/print.rs @@ -1,11 +1,16 @@ use crate::vars; use cairo_vm::{ - hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::get_integer_from_var_name}, + hint_processor::builtin_hint_processor::{ + builtin_hint_processor_definition::HintProcessorData, + hint_utils::{get_integer_from_var_name, get_relocatable_from_var_name}, + }, types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; +use num_bigint::BigUint; use std::collections::HashMap; +use tracing::debug; pub const PROGRAM_HASH: &str = "print(\"program_hash\", hex(ids.program_hash))"; @@ -17,7 +22,34 @@ pub fn program_hash( ) -> Result<(), HintError> { let program_hash = get_integer_from_var_name(vars::ids::PROGRAM_HASH, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - println!("program_hash: {}", program_hash); + debug!("program_hash: {}", program_hash); + + Ok(()) +} + +pub const HINT_PRINT_TASK_RESULT: &str = "print(f\"Task Result: {hex(ids.result.high * 2 ** 128 + ids.result.low)}\")"; + +pub fn hint_print_task_result( + vm: &mut VirtualMachine, + _exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let result_ptr = get_relocatable_from_var_name(vars::ids::RESULT, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; + + let result = vm + .get_continuous_range(result_ptr, 2)? + .into_iter() + .map(|v| v.get_int().unwrap()) + .collect::>(); + + let result_low = result[0].to_biguint(); + let result_high = result[1].to_biguint(); + let base = BigUint::from(2u32).pow(128); + + let result_value = result_high * base + result_low; + + debug!("Task Result: 0x{:x}", result_value); Ok(()) } diff --git a/crates/hints/src/verifiers/mod.rs b/crates/hints/src/verifiers/mod.rs index 202a49f2..51c61700 100644 --- a/crates/hints/src/verifiers/mod.rs +++ b/crates/hints/src/verifiers/mod.rs @@ -1,4 +1,3 @@ pub mod evm; pub mod mmr_verifier; -pub mod utils; pub mod verify; diff --git a/crates/hints/src/verifiers/utils.rs b/crates/hints/src/verifiers/utils.rs deleted file mode 100644 index c8e77e8e..00000000 --- a/crates/hints/src/verifiers/utils.rs +++ /dev/null @@ -1,39 +0,0 @@ -use crate::vars; -use cairo_vm::hint_processor::builtin_hint_processor::{ - builtin_hint_processor_definition::HintProcessorData, hint_utils::get_relocatable_from_var_name, -}; -use cairo_vm::{ - types::exec_scope::ExecutionScopes, - vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, - Felt252, -}; -use num_bigint::BigUint; -use std::collections::HashMap; - -pub const HINT_PRINT_TASK_RESULT: &str = "print(f\"Task Result: {hex(ids.result.high * 2 ** 128 + ids.result.low)}\")"; - -pub fn hint_print_task_result( - vm: &mut VirtualMachine, - _exec_scopes: &mut ExecutionScopes, - hint_data: &HintProcessorData, - _constants: &HashMap, -) -> Result<(), HintError> { - let result_ptr = get_relocatable_from_var_name(vars::ids::RESULT, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; - - let result = vm - .get_continuous_range(result_ptr, 2)? - .into_iter() - .map(|v| v.get_int().unwrap()) - .collect::>(); - - let result_low = result[0].to_biguint(); - let result_high = result[1].to_biguint(); - let base = BigUint::from(2u32).pow(128); - - let result_value = result_high * base + result_low; - - // TODO: add appropriate logger - println!("Task Result: 0x{:x}", result_value); - - Ok(()) -} diff --git a/crates/sound_run/Cargo.toml b/crates/sound_run/Cargo.toml index 96a5c3ee..6158adbc 100644 --- a/crates/sound_run/Cargo.toml +++ b/crates/sound_run/Cargo.toml @@ -9,6 +9,8 @@ clap.workspace = true serde_json.workspace = true sound_hint_processor.workspace = true thiserror.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true types.workspace = true diff --git a/crates/sound_run/src/main.rs b/crates/sound_run/src/main.rs index f17ae02c..5f6173d0 100644 --- a/crates/sound_run/src/main.rs +++ b/crates/sound_run/src/main.rs @@ -14,6 +14,7 @@ use cairo_vm::{ use clap::Parser; use sound_hint_processor::CustomHintProcessor; use std::{env, path::PathBuf}; +use tracing::debug; use types::{proofs::Proofs, HDPDryRunInput, HDPInput}; #[derive(Parser, Debug)] @@ -32,6 +33,8 @@ struct Args { } fn main() -> Result<(), HdpOsError> { + tracing_subscriber::fmt::init(); + let args = Args::try_parse_from(std::env::args()).map_err(HdpOsError::Args)?; // Init CairoRunConfig @@ -81,7 +84,7 @@ fn main() -> Result<(), HdpOsError> { .map_err(|e| HdpOsError::Runner(e.into()))?; cairo_runner.vm.compute_segments_effective_sizes(); - println!("{:?}", cairo_runner.get_execution_resources()); + debug!("{:?}", cairo_runner.get_execution_resources()); Ok(()) } diff --git a/src/contract_bootloader/contract_dry_run.cairo b/src/contract_bootloader/contract_dry_run.cairo index 82700f58..f507df76 100644 --- a/src/contract_bootloader/contract_dry_run.cairo +++ b/src/contract_bootloader/contract_dry_run.cairo @@ -119,7 +119,7 @@ func main{ assert retdata_size = 2; local result: Uint256 = Uint256(low=retdata[0], high=retdata[1]); - %{ print("result", [hex(ids.result.low), hex(ids.result.high)]) %} + %{ print(f"Task Result: {hex(ids.result.high * 2 ** 128 + ids.result.low)}") %} // Write DryRunOutput to output. assert [cast(output_ptr, DryRunOutput*)] = DryRunOutput( From 1c3d7f412d4e243e1a6c73b990a914e0870d454d Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Thu, 26 Dec 2024 17:24:37 +0100 Subject: [PATCH 67/75] multi support sketch --- Scarb.toml | 2 +- crates/fetcher/src/main.rs | 10 +- crates/hints/src/lib.rs | 6 +- crates/hints/src/vars.rs | 2 + crates/hints/src/verifiers/evm/mod.rs | 23 + crates/hints/src/verifiers/verify.rs | 57 +- crates/sound_hint_processor/src/input.rs | 6 +- crates/sound_run/src/main.rs | 6 +- crates/types/src/lib.rs | 18 +- {cairo1 => hdp_cairo}/README.md | 0 {cairo1 => hdp_cairo}/Scarb.toml | 0 {cairo1 => hdp_cairo}/src/evm.cairo | 0 {cairo1 => hdp_cairo}/src/evm/account.cairo | 0 .../src/evm/block_receipt.cairo | 0 {cairo1 => hdp_cairo}/src/evm/block_tx.cairo | 0 {cairo1 => hdp_cairo}/src/evm/header.cairo | 0 {cairo1 => hdp_cairo}/src/evm/storage.cairo | 0 {cairo1 => hdp_cairo}/src/lib.cairo | 0 {cairo1 => hdp_cairo}/src/starknet.cairo | 0 .../src/starknet/header.cairo | 0 .../src/starknet/storage.cairo | 0 src/hdp.cairo | 2 +- src/verifiers/evm/verify.cairo | 30 +- src/verifiers/verify.cairo | 30 +- tests/modules/Scarb.lock | 51 ++ tests/modules/Scarb.toml | 15 + tests/modules/account_modules/Scarb.toml | 21 + tests/modules/account_modules/src/lib.cairo | 71 ++ tests/modules/header_modules/Scarb.toml | 21 + tests/modules/header_modules/src/lib.cairo | 610 ++++++++++++++++++ tests/modules/receipt_modules/Scarb.toml | 21 + tests/modules/receipt_modules/src/lib.cairo | 39 ++ tests/modules/storage_modules/Scarb.toml | 21 + tests/modules/storage_modules/src/lib.cairo | 46 ++ tests/modules/transaction_modules/Scarb.toml | 21 + .../modules/transaction_modules/src/lib.cairo | 279 ++++++++ tools/make/cairo_format_check.sh | 2 +- tools/make/format_cairo_files.sh | 2 +- 38 files changed, 1357 insertions(+), 55 deletions(-) rename {cairo1 => hdp_cairo}/README.md (100%) rename {cairo1 => hdp_cairo}/Scarb.toml (100%) rename {cairo1 => hdp_cairo}/src/evm.cairo (100%) rename {cairo1 => hdp_cairo}/src/evm/account.cairo (100%) rename {cairo1 => hdp_cairo}/src/evm/block_receipt.cairo (100%) rename {cairo1 => hdp_cairo}/src/evm/block_tx.cairo (100%) rename {cairo1 => hdp_cairo}/src/evm/header.cairo (100%) rename {cairo1 => hdp_cairo}/src/evm/storage.cairo (100%) rename {cairo1 => hdp_cairo}/src/lib.cairo (100%) rename {cairo1 => hdp_cairo}/src/starknet.cairo (100%) rename {cairo1 => hdp_cairo}/src/starknet/header.cairo (100%) rename {cairo1 => hdp_cairo}/src/starknet/storage.cairo (100%) create mode 100644 tests/modules/Scarb.lock create mode 100644 tests/modules/Scarb.toml create mode 100644 tests/modules/account_modules/Scarb.toml create mode 100644 tests/modules/account_modules/src/lib.cairo create mode 100644 tests/modules/header_modules/Scarb.toml create mode 100644 tests/modules/header_modules/src/lib.cairo create mode 100644 tests/modules/receipt_modules/Scarb.toml create mode 100644 tests/modules/receipt_modules/src/lib.cairo create mode 100644 tests/modules/storage_modules/Scarb.toml create mode 100644 tests/modules/storage_modules/src/lib.cairo create mode 100644 tests/modules/transaction_modules/Scarb.toml create mode 100644 tests/modules/transaction_modules/src/lib.cairo diff --git a/Scarb.toml b/Scarb.toml index 6b0f84d7..734c930d 100644 --- a/Scarb.toml +++ b/Scarb.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2023_11" members = [ - "cairo1" + "hdp_cairo" ] [workspace.dependencies] diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index 42998e6b..49cdec4b 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -12,7 +12,10 @@ use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use proof_keys::ProofKeys; use std::{collections::HashSet, fs, num::ParseIntError, path::PathBuf}; use thiserror::Error; -use types::proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}; +use types::{ + proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}, + ChainProofs, +}; pub mod proof_keys; @@ -116,7 +119,10 @@ async fn main() -> Result<(), FetcherError> { ..Default::default() }; - fs::write(args.program_output, serde_json::to_vec(&proofs).map_err(|e| FetcherError::IO(e.into()))?)?; + fs::write( + args.program_output, + serde_json::to_vec::>(&vec![ChainProofs::EthereumSepolia(proofs)]).map_err(|e| FetcherError::IO(e.into()))?, + )?; Ok(()) } diff --git a/crates/hints/src/lib.rs b/crates/hints/src/lib.rs index 3b615030..0c7f3a45 100644 --- a/crates/hints/src/lib.rs +++ b/crates/hints/src/lib.rs @@ -38,8 +38,8 @@ pub fn hints() -> HashMap { hints.insert(decoder::evm::v_is_encoded::HINT_V_IS_ENCODED.into(), decoder::evm::v_is_encoded::hint_v_is_encoded); hints.insert(merkle::HINT_IS_LEFT_SMALLER.into(), merkle::hint_is_left_smaller); hints.insert(merkle::HINT_TARGET_TASK_HASH.into(), merkle::hint_target_task_hash); - hints.insert(print::PROGRAM_HASH.into(), print::program_hash); hints.insert(print::HINT_PRINT_TASK_RESULT.into(), print::hint_print_task_result); + hints.insert(print::PROGRAM_HASH.into(), print::program_hash); hints.insert(rlp::divmod::HINT_DIVMOD_RLP.into(), rlp::divmod::hint_divmod_rlp); hints.insert(rlp::divmod::HINT_DIVMOD_VALUE.into(), rlp::divmod::hint_divmod_value); hints.insert(rlp::item_type::HINT_IS_LONG.into(), rlp::item_type::hint_is_long); @@ -71,6 +71,7 @@ pub fn hints() -> HashMap { hints.insert(verifiers::evm::header_verifier::HINT_RLP_LEN.into(), verifiers::evm::header_verifier::hint_rlp_len); hints.insert(verifiers::evm::header_verifier::HINT_SET_HEADER.into(), verifiers::evm::header_verifier::hint_set_header); hints.insert(verifiers::evm::header_verifier::HINT_VM_ENTER_SCOPE.into(), verifiers::evm::header_verifier::hint_vm_enter_scope); + hints.insert(verifiers::evm::HINT_HEADERS_WITH_MMR_LEN.into(), verifiers::evm::hint_headers_with_mmr_headers_len); hints.insert(verifiers::evm::receipt_verifier::HINT_BATCH_RECEIPTS_LEN.into(), verifiers::evm::receipt_verifier::hint_batch_receipts_len); hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_BLOCK_NUMBER.into(), verifiers::evm::receipt_verifier::hint_receipt_block_number); hints.insert(verifiers::evm::receipt_verifier::HINT_RECEIPT_KEY_LEADING_ZEROS.into(), verifiers::evm::receipt_verifier::hint_receipt_key_leading_zeros); @@ -99,7 +100,8 @@ pub fn hints() -> HashMap { hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_ROOT.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_root); hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_META_SIZE.into(), verifiers::mmr_verifier::hint_headers_with_mmr_meta_size); hints.insert(verifiers::mmr_verifier::HINT_HEADERS_WITH_MMR_PEAKS.into(), verifiers::mmr_verifier::hint_headers_with_mmr_peaks); - hints.insert(verifiers::verify::HINT_HEADERS_WITH_MMR_LEN.into(), verifiers::verify::hint_headers_with_mmr_headers_len); + hints.insert(verifiers::verify::HINT_CHAIN_PROOFS_LEN.into(), verifiers::verify::hint_chain_proofs_len); + hints.insert(verifiers::verify::HINT_CHAIN_PROOFS_CHAIN_ID.into(), verifiers::verify::hint_chain_proofs_chain_id); hints.insert(verifiers::verify::HINT_VM_ENTER_SCOPE.into(), verifiers::verify::hint_vm_enter_scope); hints.insert(eth_essentials_cairo_vm_hints::hints::lib::bit_length::HINT_BIT_LENGTH.into(), eth_essentials_cairo_vm_hints::hints::lib::bit_length::hint_bit_length); diff --git a/crates/hints/src/vars.rs b/crates/hints/src/vars.rs index 75e01e33..f4fc0352 100644 --- a/crates/hints/src/vars.rs +++ b/crates/hints/src/vars.rs @@ -8,6 +8,7 @@ pub mod scopes { pub const PARAMS: &str = "params"; pub const PROOF: &str = "proof"; pub const PROOFS: &str = "proofs"; + pub const CHAIN_PROOFS: &str = "chain_proofs"; pub const RECEIPT: &str = "receipt"; pub const STORAGE: &str = "storage"; pub const SYSCALL_HANDLER: &str = "syscall_handler"; @@ -17,6 +18,7 @@ pub mod scopes { pub mod ids { pub const PEAKS: &str = "peaks"; + pub const CHAIN_PROOFS_LEN: &str = "chain_proofs_len"; pub const RLP_LEN: &str = "rlp_len"; pub const ADDRESS: &str = "address"; pub const ALL_ENCODINGS: &str = "all_encodings"; diff --git a/crates/hints/src/verifiers/evm/mod.rs b/crates/hints/src/verifiers/evm/mod.rs index a4c1c4a2..99d2963a 100644 --- a/crates/hints/src/verifiers/evm/mod.rs +++ b/crates/hints/src/verifiers/evm/mod.rs @@ -1,5 +1,28 @@ +use crate::vars; +use cairo_vm::{ + hint_processor::builtin_hint_processor::{builtin_hint_processor_definition::HintProcessorData, hint_utils::insert_value_into_ap}, + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, + Felt252, +}; +use std::collections::HashMap; +use types::proofs::Proofs; + pub mod account_verifier; pub mod header_verifier; pub mod receipt_verifier; pub mod storage_item_verifier; pub mod transaction_verifier; + +pub const HINT_HEADERS_WITH_MMR_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.headers_with_mmr))"; + +pub fn hint_headers_with_mmr_headers_len( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + _hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let proofs = exec_scopes.get::(vars::scopes::BATCH)?; + + insert_value_into_ap(vm, Felt252::from(proofs.headers_with_mmr.len())) +} diff --git a/crates/hints/src/verifiers/verify.rs b/crates/hints/src/verifiers/verify.rs index 68392f82..fa86a32a 100644 --- a/crates/hints/src/verifiers/verify.rs +++ b/crates/hints/src/verifiers/verify.rs @@ -1,41 +1,64 @@ use crate::vars; use cairo_vm::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData; -use cairo_vm::hint_processor::builtin_hint_processor::hint_utils::insert_value_into_ap; +use cairo_vm::hint_processor::builtin_hint_processor::hint_utils::{get_integer_from_var_name, insert_value_into_ap}; use cairo_vm::{ types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; use std::{any::Any, collections::HashMap}; -use types::proofs::Proofs; +use types::ChainProofs; -pub const HINT_VM_ENTER_SCOPE: &str = "vm_enter_scope({'batch': proofs, '__dict_manager': __dict_manager})"; +pub const HINT_CHAIN_PROOFS_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(chain_proofs))"; -pub fn hint_vm_enter_scope( - _vm: &mut VirtualMachine, +pub fn hint_chain_proofs_len( + vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let batch: Box = Box::new(exec_scopes.get::(vars::scopes::PROOFS)?); - let dict_manager: Box = Box::new(exec_scopes.get_dict_manager()?); - exec_scopes.enter_scope(HashMap::from([ - (String::from(vars::scopes::BATCH), batch), - (String::from(vars::scopes::DICT_MANAGER), dict_manager), - ])); + let chain_proofs = exec_scopes.get::>(vars::scopes::CHAIN_PROOFS)?; + insert_value_into_ap(vm, Felt252::from(chain_proofs.len())) +} - Ok(()) +pub const HINT_CHAIN_PROOFS_CHAIN_ID: &str = "memory[ap] = to_felt_or_relocatable(chain_proofs[ids.idx - 1].chain_id)"; + +pub fn hint_chain_proofs_chain_id( + vm: &mut VirtualMachine, + exec_scopes: &mut ExecutionScopes, + hint_data: &HintProcessorData, + _constants: &HashMap, +) -> Result<(), HintError> { + let chain_proofs = exec_scopes.get::>(vars::scopes::CHAIN_PROOFS)?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + insert_value_into_ap(vm, Felt252::from(chain_proofs[idx - 1].chain_id())) } -pub const HINT_HEADERS_WITH_MMR_LEN: &str = "memory[ap] = to_felt_or_relocatable(len(batch.headers_with_mmr))"; +pub const HINT_VM_ENTER_SCOPE: &str = "vm_enter_scope({'batch': chain_proofs[ids.idx - 1].value, '__dict_manager': __dict_manager})"; -pub fn hint_headers_with_mmr_headers_len( +pub fn hint_vm_enter_scope( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, - _hint_data: &HintProcessorData, + hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - let proofs = exec_scopes.get::(vars::scopes::BATCH)?; + let chain_proofs = exec_scopes.get::>(vars::scopes::CHAIN_PROOFS)?; + let idx: usize = get_integer_from_var_name(vars::ids::IDX, vm, &hint_data.ids_data, &hint_data.ap_tracking)? + .try_into() + .unwrap(); + + let batch: Box = match chain_proofs[idx - 1].clone() { + ChainProofs::EthereumMainnet(proofs) => Box::new(proofs), + ChainProofs::EthereumSepolia(proofs) => Box::new(proofs), + }; + let dict_manager: Box = Box::new(exec_scopes.get_dict_manager()?); - insert_value_into_ap(vm, Felt252::from(proofs.headers_with_mmr.len())) + exec_scopes.enter_scope(HashMap::from([ + (String::from(vars::scopes::BATCH), batch), + (String::from(vars::scopes::DICT_MANAGER), dict_manager), + ])); + + Ok(()) } diff --git a/crates/sound_hint_processor/src/input.rs b/crates/sound_hint_processor/src/input.rs index a806386e..a5474a30 100644 --- a/crates/sound_hint_processor/src/input.rs +++ b/crates/sound_hint_processor/src/input.rs @@ -8,9 +8,9 @@ use cairo_vm::{ }; use hints::vars; use std::collections::HashMap; -use types::{param::Param, proofs::Proofs}; +use types::{param::Param, ChainProofs}; -pub const HINT_INPUT: &str = "from tools.py.schema import HDPInput\nrun_input = HDPInput.Schema().load(program_input)\nproofs = run_input.proofs\nparams = run_input.params\ncompiled_class = run_input.compiled_class"; +pub const HINT_INPUT: &str = "from tools.py.schema import HDPInput\nrun_input = HDPInput.Schema().load(program_input)\nchain_proofs = run_input.proofs\nparams = run_input.params\ncompiled_class = run_input.compiled_class"; impl CustomHintProcessor { pub fn hint_input( @@ -20,7 +20,7 @@ impl CustomHintProcessor { _hint_data: &HintProcessorData, _constants: &HashMap, ) -> Result<(), HintError> { - exec_scopes.insert_value::(vars::scopes::PROOFS, self.private_inputs.proofs.to_owned()); + exec_scopes.insert_value::>(vars::scopes::CHAIN_PROOFS, self.private_inputs.chain_proofs.to_owned()); exec_scopes.insert_value::>(vars::scopes::PARAMS, self.private_inputs.params.to_owned()); exec_scopes.insert_value::(vars::scopes::COMPILED_CLASS, self.private_inputs.compiled_class.to_owned()); Ok(()) diff --git a/crates/sound_run/src/main.rs b/crates/sound_run/src/main.rs index 5f6173d0..1b94fe81 100644 --- a/crates/sound_run/src/main.rs +++ b/crates/sound_run/src/main.rs @@ -15,7 +15,7 @@ use clap::Parser; use sound_hint_processor::CustomHintProcessor; use std::{env, path::PathBuf}; use tracing::debug; -use types::{proofs::Proofs, HDPDryRunInput, HDPInput}; +use types::{ChainProofs, HDPDryRunInput, HDPInput}; #[derive(Parser, Debug)] #[clap(author, version, about, long_about = None)] @@ -53,7 +53,7 @@ fn main() -> Result<(), HdpOsError> { let program_file = std::fs::read(program_file_path.as_path()).map_err(HdpOsError::IO)?; let program_inputs: HDPDryRunInput = serde_json::from_slice(&std::fs::read(args.program_input).map_err(HdpOsError::IO)?)?; - let program_proofs: Proofs = serde_json::from_slice(&std::fs::read(args.program_proofs).map_err(HdpOsError::IO)?)?; + let program_proofs: Vec = serde_json::from_slice(&std::fs::read(args.program_proofs).map_err(HdpOsError::IO)?)?; // Load the Program let program = Program::from_bytes(&program_file, Some(cairo_run_config.entrypoint)).map_err(|e| HdpOsError::Runner(e.into()))?; @@ -74,7 +74,7 @@ fn main() -> Result<(), HdpOsError> { // Run the Cairo VM let mut hint_processor = CustomHintProcessor::new(HDPInput { - proofs: program_proofs, + chain_proofs: program_proofs, params: program_inputs.params, compiled_class: program_inputs.compiled_class, }); diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 561d4a9a..45bcf1d2 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -8,6 +8,7 @@ pub mod keys; pub mod param; pub mod proofs; +use alloy::primitives::ChainId; use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; use param::Param; use proofs::Proofs; @@ -23,7 +24,22 @@ pub struct HDPDryRunInput { #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct HDPInput { - pub proofs: Proofs, + pub chain_proofs: Vec, pub params: Vec, pub compiled_class: CasmContractClass, } + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub enum ChainProofs { + EthereumMainnet(Proofs), + EthereumSepolia(Proofs), +} + +impl ChainProofs { + pub fn chain_id(&self) -> ChainId { + match self { + ChainProofs::EthereumMainnet(_) => 1, + ChainProofs::EthereumSepolia(_) => 11155111, + } + } +} diff --git a/cairo1/README.md b/hdp_cairo/README.md similarity index 100% rename from cairo1/README.md rename to hdp_cairo/README.md diff --git a/cairo1/Scarb.toml b/hdp_cairo/Scarb.toml similarity index 100% rename from cairo1/Scarb.toml rename to hdp_cairo/Scarb.toml diff --git a/cairo1/src/evm.cairo b/hdp_cairo/src/evm.cairo similarity index 100% rename from cairo1/src/evm.cairo rename to hdp_cairo/src/evm.cairo diff --git a/cairo1/src/evm/account.cairo b/hdp_cairo/src/evm/account.cairo similarity index 100% rename from cairo1/src/evm/account.cairo rename to hdp_cairo/src/evm/account.cairo diff --git a/cairo1/src/evm/block_receipt.cairo b/hdp_cairo/src/evm/block_receipt.cairo similarity index 100% rename from cairo1/src/evm/block_receipt.cairo rename to hdp_cairo/src/evm/block_receipt.cairo diff --git a/cairo1/src/evm/block_tx.cairo b/hdp_cairo/src/evm/block_tx.cairo similarity index 100% rename from cairo1/src/evm/block_tx.cairo rename to hdp_cairo/src/evm/block_tx.cairo diff --git a/cairo1/src/evm/header.cairo b/hdp_cairo/src/evm/header.cairo similarity index 100% rename from cairo1/src/evm/header.cairo rename to hdp_cairo/src/evm/header.cairo diff --git a/cairo1/src/evm/storage.cairo b/hdp_cairo/src/evm/storage.cairo similarity index 100% rename from cairo1/src/evm/storage.cairo rename to hdp_cairo/src/evm/storage.cairo diff --git a/cairo1/src/lib.cairo b/hdp_cairo/src/lib.cairo similarity index 100% rename from cairo1/src/lib.cairo rename to hdp_cairo/src/lib.cairo diff --git a/cairo1/src/starknet.cairo b/hdp_cairo/src/starknet.cairo similarity index 100% rename from cairo1/src/starknet.cairo rename to hdp_cairo/src/starknet.cairo diff --git a/cairo1/src/starknet/header.cairo b/hdp_cairo/src/starknet/header.cairo similarity index 100% rename from cairo1/src/starknet/header.cairo rename to hdp_cairo/src/starknet/header.cairo diff --git a/cairo1/src/starknet/storage.cairo b/hdp_cairo/src/starknet/storage.cairo similarity index 100% rename from cairo1/src/starknet/storage.cairo rename to hdp_cairo/src/starknet/storage.cairo diff --git a/src/hdp.cairo b/src/hdp.cairo index 96ba97b9..e743928d 100644 --- a/src/hdp.cairo +++ b/src/hdp.cairo @@ -71,7 +71,7 @@ func run{ %{ from tools.py.schema import HDPInput run_input = HDPInput.Schema().load(program_input) - proofs = run_input.proofs + chain_proofs = run_input.proofs params = run_input.params compiled_class = run_input.compiled_class %} diff --git a/src/verifiers/evm/verify.cairo b/src/verifiers/evm/verify.cairo index e434b436..6609873b 100644 --- a/src/verifiers/evm/verify.cairo +++ b/src/verifiers/evm/verify.cairo @@ -16,27 +16,21 @@ func run_state_verification{ pow2_array: felt*, evm_memorizer: DictAccess*, mmr_metas: MMRMeta*, + chain_info: ChainInfo, }(mmr_meta_idx: felt) -> (mmr_meta_idx: felt) { alloc_locals; - let (chain_info) = fetch_chain_info(11155111); - with chain_info { - // Step 1: Verify MMR and headers inclusion - tempvar n_proofs: felt = nondet %{ len(batch.headers_with_mmr) %}; - let (mmr_meta_idx) = verify_mmr_batches(n_proofs, mmr_meta_idx); - - // Step 2: Verify the accounts - verify_accounts(); - - // Step 3: Verify the storage items - verify_storage_items(); - - // Step 4: Verify the block tx proofs - verify_block_tx_proofs(); - - // Step 5: Verify the block receipt proofs - verify_block_receipt_proofs(); - } + // Step 1: Verify MMR and headers inclusion + tempvar n_proofs: felt = nondet %{ len(batch.headers_with_mmr) %}; + let (mmr_meta_idx) = verify_mmr_batches(n_proofs, mmr_meta_idx); + // Step 2: Verify the accounts + verify_accounts(); + // Step 3: Verify the storage items + verify_storage_items(); + // Step 4: Verify the block tx proofs + verify_block_tx_proofs(); + // Step 5: Verify the block receipt proofs + verify_block_receipt_proofs(); return (mmr_meta_idx=mmr_meta_idx); } diff --git a/src/verifiers/verify.cairo b/src/verifiers/verify.cairo index e4f8cc8a..3f379445 100644 --- a/src/verifiers/verify.cairo +++ b/src/verifiers/verify.cairo @@ -24,14 +24,34 @@ func run_state_verification{ starknet_memorizer: DictAccess*, mmr_metas: MMRMeta*, }() -> (mmr_metas_len: felt) { - alloc_locals; + tempvar chain_proofs_len: felt = nondet %{ len(chain_proofs) %}; + let (mmr_meta_idx, _) = run_state_verification_inner(mmr_meta_idx=0, idx=chain_proofs_len); + return (mmr_metas_len=mmr_meta_idx); +} - // batch abstraction will be usefull with multiple chains - %{ vm_enter_scope({'batch': proofs, '__dict_manager': __dict_manager}) %} +func run_state_verification_inner{ + range_check_ptr, + pedersen_ptr: HashBuiltin*, + poseidon_ptr: PoseidonBuiltin*, + keccak_ptr: KeccakBuiltin*, + bitwise_ptr: BitwiseBuiltin*, + pow2_array: felt*, + evm_memorizer: DictAccess*, + starknet_memorizer: DictAccess*, + mmr_metas: MMRMeta*, +}(mmr_meta_idx: felt, idx: felt) -> (mmr_meta_idx: felt, idx: felt) { + if (idx == 0) { + return (mmr_meta_idx=mmr_meta_idx, idx=idx); + } - let (mmr_meta_idx) = evm_run_state_verification(0); + tempvar chain_id: felt = nondet %{ chain_proofs[ids.idx - 1].chain_id %}; + let (chain_info) = fetch_chain_info(chain_id); + %{ vm_enter_scope({'batch': chain_proofs[ids.idx - 1].value, '__dict_manager': __dict_manager}) %} + with chain_info { + let (mmr_meta_idx) = evm_run_state_verification(mmr_meta_idx); + } %{ vm_exit_scope() %} - return (mmr_metas_len=mmr_meta_idx); + return run_state_verification_inner(mmr_meta_idx=mmr_meta_idx, idx=idx - 1); } diff --git a/tests/modules/Scarb.lock b/tests/modules/Scarb.lock new file mode 100644 index 00000000..48b7fe55 --- /dev/null +++ b/tests/modules/Scarb.lock @@ -0,0 +1,51 @@ +# Code generated by scarb DO NOT EDIT. +version = 1 + +[[package]] +name = "account_modules" +version = "0.1.0" +dependencies = [ + "hdp_cairo", + "snforge_std", +] + +[[package]] +name = "hdp_cairo" +version = "0.1.0" + +[[package]] +name = "header_modules" +version = "0.1.0" +dependencies = [ + "hdp_cairo", + "snforge_std", +] + +[[package]] +name = "receipt_modules" +version = "0.1.0" +dependencies = [ + "hdp_cairo", + "snforge_std", +] + +[[package]] +name = "snforge_std" +version = "0.24.0" +source = "git+https://github.com/foundry-rs/starknet-foundry?tag=v0.24.0#95e9fb09cb91b3c05295915179ee1b55bf923653" + +[[package]] +name = "storage_modules" +version = "0.1.0" +dependencies = [ + "hdp_cairo", + "snforge_std", +] + +[[package]] +name = "transaction_modules" +version = "0.1.0" +dependencies = [ + "hdp_cairo", + "snforge_std", +] diff --git a/tests/modules/Scarb.toml b/tests/modules/Scarb.toml new file mode 100644 index 00000000..6130f954 --- /dev/null +++ b/tests/modules/Scarb.toml @@ -0,0 +1,15 @@ +[workspace] +name = "contracts" +version = "0.1.0" +edition = "2023_11" + +members = [ + "account_modules", + "header_modules", + "receipt_modules", + "storage_modules", + "transaction_modules", +] + +[workspace.dependencies] +hdp_cairo = { path = "../../." } diff --git a/tests/modules/account_modules/Scarb.toml b/tests/modules/account_modules/Scarb.toml new file mode 100644 index 00000000..2119a137 --- /dev/null +++ b/tests/modules/account_modules/Scarb.toml @@ -0,0 +1,21 @@ +[package] +name = "account_modules" +version = "0.1.0" +edition = "2023_11" + +# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html + +[dependencies] +starknet = "2.6.3" +hdp_cairo = { workspace = true } + +[dev-dependencies] +snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.24.0" } + +[[target.starknet-contract]] +sierra = true +casm = true +casm-add-pythonic-hints = true + +[scripts] +test = "snforge test" diff --git a/tests/modules/account_modules/src/lib.cairo b/tests/modules/account_modules/src/lib.cairo new file mode 100644 index 00000000..d625cee6 --- /dev/null +++ b/tests/modules/account_modules/src/lib.cairo @@ -0,0 +1,71 @@ +#[starknet::contract] +mod get_nonce { + use hdp_cairo::evm::account::AccountTrait; + use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, address: felt252) -> u256 { + hdp + .evm + .account_get_nonce( + AccountKey { chain_id: 11155111, block_number: block_number.into(), address } + ) + } +} + +#[starknet::contract] +mod get_balance { + use hdp_cairo::evm::account::AccountTrait; + use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, address: felt252) -> u256 { + hdp + .evm + .account_get_balance( + AccountKey { chain_id: 11155111, block_number: block_number.into(), address } + ) + } +} + +#[starknet::contract] +mod get_state_root { + use hdp_cairo::evm::account::AccountTrait; + use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, address: felt252) -> u256 { + hdp + .evm + .account_get_state_root( + AccountKey { chain_id: 11155111, block_number: block_number.into(), address } + ) + } +} + +#[starknet::contract] +mod get_code_hash { + use hdp_cairo::evm::account::AccountTrait; + use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, address: felt252) -> u256 { + hdp + .evm + .account_get_code_hash( + AccountKey { chain_id: 11155111, block_number: block_number.into(), address } + ) + } +} diff --git a/tests/modules/header_modules/Scarb.toml b/tests/modules/header_modules/Scarb.toml new file mode 100644 index 00000000..0fcc158c --- /dev/null +++ b/tests/modules/header_modules/Scarb.toml @@ -0,0 +1,21 @@ +[package] +name = "header_modules" +version = "0.1.0" +edition = "2023_11" + +# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html + +[dependencies] +starknet = "2.6.3" +hdp_cairo = { workspace = true } + +[dev-dependencies] +snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.24.0" } + +[[target.starknet-contract]] +sierra = true +casm = true +casm-add-pythonic-hints = true + +[scripts] +test = "snforge test" diff --git a/tests/modules/header_modules/src/lib.cairo b/tests/modules/header_modules/src/lib.cairo new file mode 100644 index 00000000..6edd2539 --- /dev/null +++ b/tests/modules/header_modules/src/lib.cairo @@ -0,0 +1,610 @@ +#[starknet::contract] +mod get_parent { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_parent(HeaderKey { chain_id: 11155111, block_number: block_number.into() }) + } +} + +#[starknet::contract] +mod get_uncle { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_uncle(HeaderKey { chain_id: 11155111, block_number: block_number.into() }) + } +} + +#[starknet::contract] +mod get_coinbase { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_coinbase( + HeaderKey { chain_id: 11155111, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod get_state_root { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_state_root( + HeaderKey { chain_id: 11155111, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod get_transaction_root { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_transaction_root( + HeaderKey { chain_id: 11155111, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod get_receipt_root { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_receipt_root( + HeaderKey { chain_id: 11155111, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod get_difficulty { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_difficulty( + HeaderKey { chain_id: 11155111, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod get_number { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_number(HeaderKey { chain_id: 11155111, block_number: block_number.into() }) + } +} + +#[starknet::contract] +mod get_gas_limit { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_gas_limit( + HeaderKey { chain_id: 11155111, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod get_gas_used { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_gas_used( + HeaderKey { chain_id: 11155111, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod get_mix_hash { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_mix_hash( + HeaderKey { chain_id: 11155111, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod get_nonce { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_nonce(HeaderKey { chain_id: 11155111, block_number: block_number.into() }) + } +} + +#[starknet::contract] +mod get_base_fee_per_gas { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { + hdp + .evm + .header_get_base_fee_per_gas( + HeaderKey { chain_id: 11155111, block_number: block_number.into() } + ) + } +} + + +#[starknet::contract] +mod starknet_get_block_number { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_block_number( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod starknet_get_state_root { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_state_root( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod starknet_get_sequencer_address { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_sequencer_address( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod starknet_get_block_timestamp { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_block_timestamp( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +// #[starknet::contract] +// mod starknet_get_transaction_count { +// use hdp_cairo::starknet::header::HeaderTrait; +// use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; +// use starknet::syscalls::call_contract_syscall; +// use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + +// #[storage] +// struct Storage {} + +// #[external(v0)] +// pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { +// hdp +// .starknet +// .header_get_transaction_count(HeaderKey { chain_id: 393402133025997798000961, +// block_number: block_number.into() }) +// } +// } + +#[starknet::contract] +mod starknet_get_transaction_commitment { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_transaction_commitment( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +// #[starknet::contract] +// mod starknet_get_event_count { +// use hdp_cairo::starknet::header::HeaderTrait; +// use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; +// use starknet::syscalls::call_contract_syscall; +// use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + +// #[storage] +// struct Storage {} + +// #[external(v0)] +// pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { +// hdp +// .starknet +// .header_get_event_count(HeaderKey { chain_id: 393402133025997798000961, block_number: +// block_number.into() }) +// } +// } + +#[starknet::contract] +mod starknet_get_event_commitment { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_event_commitment( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod starknet_get_parent_block_hash { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_parent_block_hash( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod starknet_get_state_diff_commitment { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_state_diff_commitment( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +// #[starknet::contract] +// mod starknet_get_state_diff_length { +// use hdp_cairo::starknet::header::HeaderTrait; +// use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; +// use starknet::syscalls::call_contract_syscall; +// use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + +// #[storage] +// struct Storage {} + +// #[external(v0)] +// pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { +// hdp +// .starknet +// .header_get_state_diff_length(HeaderKey { chain_id: 393402133025997798000961, +// block_number: block_number.into() }) +// } +// } + +#[starknet::contract] +mod starknet_get_l1_gas_price_in_wei { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_l1_gas_price_in_wei( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod starknet_get_l1_gas_price_in_fri { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_l1_gas_price_in_fri( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod starknet_get_l1_data_gas_price_in_wei { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_l1_data_gas_price_in_wei( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod starknet_get_l1_data_gas_price_in_fri { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_l1_data_gas_price_in_fri( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +#[starknet::contract] +mod starknet_get_receipts_commitment { + use hdp_cairo::starknet::header::HeaderTrait; + use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .header_get_receipts_commitment( + HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } + ) + } +} + +// #[starknet::contract] +// mod starknet_get_l1_data_mode { +// use hdp_cairo::starknet::header::HeaderTrait; +// use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; +// use starknet::syscalls::call_contract_syscall; +// use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + +// #[storage] +// struct Storage {} + +// #[external(v0)] +// pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { +// hdp +// .starknet +// .header_get_l1_data_mode(HeaderKey { chain_id: 393402133025997798000961, +// block_number: block_number.into() }) +// } +// } + +// #[starknet::contract] +// mod starknet_get_protocol_version { +// use hdp_cairo::starknet::header::HeaderTrait; +// use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; +// use starknet::syscalls::call_contract_syscall; +// use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + +// #[storage] +// struct Storage {} + +// #[external(v0)] +// pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { +// hdp +// .starknet +// .header_get_protocol_version(HeaderKey { chain_id: 393402133025997798000961, +// block_number: block_number.into() }) +// } +// } + +#[starknet::contract] +mod starknet_and_ethereum_get_storage { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{evm::header::{HeaderKey, HeaderImpl}}; + use hdp_cairo::starknet::storage::StorageTrait; + use hdp_cairo::{HDP, starknet::storage::{StorageKey, StorageImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + let _ = hdp + .evm + .header_get_nonce(HeaderKey { chain_id: 11155111, block_number: 5382820.into() }); + + hdp + .starknet + .storage_get_slot( + StorageKey { + chain_id: 393402133025997798000961, + block_number: block_number.into(), + address: 0x6b8838af5d2a023b24ec8a69720b152d72ae2e4528139c32e05d8a3b9d7d4e7, + storage_slot: 0x308cfbb7d2d38db3a215f9728501ac69445a6afbee328cdeae4e23db54b850a + } + ) + } +} diff --git a/tests/modules/receipt_modules/Scarb.toml b/tests/modules/receipt_modules/Scarb.toml new file mode 100644 index 00000000..07c03d37 --- /dev/null +++ b/tests/modules/receipt_modules/Scarb.toml @@ -0,0 +1,21 @@ +[package] +name = "receipt_modules" +version = "0.1.0" +edition = "2023_11" + +# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html + +[dependencies] +starknet = "2.6.3" +hdp_cairo = { workspace = true } + +[dev-dependencies] +snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.24.0" } + +[[target.starknet-contract]] +sierra = true +casm = true +casm-add-pythonic-hints = true + +[scripts] +test = "snforge test" diff --git a/tests/modules/receipt_modules/src/lib.cairo b/tests/modules/receipt_modules/src/lib.cairo new file mode 100644 index 00000000..14a91bb2 --- /dev/null +++ b/tests/modules/receipt_modules/src/lib.cairo @@ -0,0 +1,39 @@ +#[starknet::contract] +mod get_status { + use hdp_cairo::evm::block_receipt::BlockReceiptTrait; + use hdp_cairo::{HDP, evm::block_receipt::{BlockReceiptKey, BlockReceiptImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_receipt_get_status( + BlockReceiptKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_cumulative_gas_used { + use hdp_cairo::evm::block_receipt::BlockReceiptTrait; + use hdp_cairo::{HDP, evm::block_receipt::{BlockReceiptKey, BlockReceiptImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_receipt_get_cumulative_gas_used( + BlockReceiptKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} diff --git a/tests/modules/storage_modules/Scarb.toml b/tests/modules/storage_modules/Scarb.toml new file mode 100644 index 00000000..517e7f5d --- /dev/null +++ b/tests/modules/storage_modules/Scarb.toml @@ -0,0 +1,21 @@ +[package] +name = "storage_modules" +version = "0.1.0" +edition = "2023_11" + +# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html + +[dependencies] +starknet = "2.6.3" +hdp_cairo = { workspace = true } + +[dev-dependencies] +snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.24.0" } + +[[target.starknet-contract]] +sierra = true +casm = true +casm-add-pythonic-hints = true + +[scripts] +test = "snforge test" diff --git a/tests/modules/storage_modules/src/lib.cairo b/tests/modules/storage_modules/src/lib.cairo new file mode 100644 index 00000000..c3430a9a --- /dev/null +++ b/tests/modules/storage_modules/src/lib.cairo @@ -0,0 +1,46 @@ +#[starknet::contract] +mod get_slot { + use hdp_cairo::evm::storage::StorageTrait; + use hdp_cairo::{HDP, evm::storage::{StorageKey, StorageImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main( + ref self: ContractState, hdp: HDP, block_number: u32, address: felt252, storage_slot: u256 + ) -> u256 { + hdp + .evm + .storage_get_slot( + StorageKey { + chain_id: 11155111, block_number: block_number.into(), address, storage_slot + } + ) + } +} + +#[starknet::contract] +mod starknet_get_storage { + use hdp_cairo::starknet::storage::StorageTrait; + use hdp_cairo::{HDP, starknet::storage::{StorageKey, StorageImpl}}; + use starknet::syscalls::call_contract_syscall; + use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { + hdp + .starknet + .storage_get_slot( + StorageKey { + chain_id: 393402133025997798000961, + block_number: block_number.into(), + address: 0x6b8838af5d2a023b24ec8a69720b152d72ae2e4528139c32e05d8a3b9d7d4e7, + storage_slot: 0x308cfbb7d2d38db3a215f9728501ac69445a6afbee328cdeae4e23db54b850a + } + ) + } +} diff --git a/tests/modules/transaction_modules/Scarb.toml b/tests/modules/transaction_modules/Scarb.toml new file mode 100644 index 00000000..83e9d42f --- /dev/null +++ b/tests/modules/transaction_modules/Scarb.toml @@ -0,0 +1,21 @@ +[package] +name = "transaction_modules" +version = "0.1.0" +edition = "2023_11" + +# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html + +[dependencies] +starknet = "2.6.3" +hdp_cairo = { workspace = true } + +[dev-dependencies] +snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.24.0" } + +[[target.starknet-contract]] +sierra = true +casm = true +casm-add-pythonic-hints = true + +[scripts] +test = "snforge test" diff --git a/tests/modules/transaction_modules/src/lib.cairo b/tests/modules/transaction_modules/src/lib.cairo new file mode 100644 index 00000000..4fadbc2f --- /dev/null +++ b/tests/modules/transaction_modules/src/lib.cairo @@ -0,0 +1,279 @@ +#[starknet::contract] +mod get_nonce { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_nonce( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_gas_price { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_gas_price( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_gas_limit { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_gas_limit( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_receiver { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_receiver( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_value { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_value( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_v { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_v( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_r { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_r( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_s { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_s( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_chain_id { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_chain_id( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_max_fee_per_gas { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_max_fee_per_gas( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_max_priority_fee_per_gas { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_max_priority_fee_per_gas( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_max_fee_per_blob_gas { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_max_fee_per_blob_gas( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_tx_type { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_tx_type( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} + +#[starknet::contract] +mod get_sender { + use hdp_cairo::evm::block_tx::BlockTxTrait; + use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { + hdp + .evm + .block_tx_get_sender( + BlockTxKey { + chain_id: 11155111, block_number: block_number.into(), index: index.into() + } + ) + } +} diff --git a/tools/make/cairo_format_check.sh b/tools/make/cairo_format_check.sh index 6f6e4b02..34033f05 100755 --- a/tools/make/cairo_format_check.sh +++ b/tools/make/cairo_format_check.sh @@ -30,7 +30,7 @@ export -f format_scarb_project # Find all .cairo files and format them in parallel echo "Finding and formatting .cairo files..." -find ./src ./tests -name '*.cairo' ! -path "./src/cairo1/*" ! -path "./src/contracts/*" | parallel --halt soon,fail=1 format_file {} +find ./src ./tests -name '*.cairo' ! -path "./src/cairo1/*" ! -path "./src/contracts/*" ! -path "./tests/modules/*" | parallel --halt soon,fail=1 format_file {} # Capture the exit status of parallel for .cairo files exit_status_cairo_files=$? diff --git a/tools/make/format_cairo_files.sh b/tools/make/format_cairo_files.sh index 1dec6e05..e2fd2c19 100755 --- a/tools/make/format_cairo_files.sh +++ b/tools/make/format_cairo_files.sh @@ -34,7 +34,7 @@ export -f format_scarb_project # Find all .cairo files under src/ and tests/ directories and format them in parallel echo "Formatting .cairo files..." -find ./src ./tests ./packages/contract_bootloader/ -name '*.cairo' ! -path "./src/cairo1/*" ! -path "./src/contracts/*" | parallel --halt soon,fail=1 format_file {} +find ./src ./tests ./packages/contract_bootloader/ -name '*.cairo' ! -path "./src/cairo1/*" ! -path "./src/contracts/*" ! -path "./tests/modules/*" | parallel --halt soon,fail=1 format_file {} # Capture the exit status of parallel for .cairo files exit_status_cairo_files=$? From eda4b05612e4338dd827a9ab9c0f16ecee342297 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Thu, 26 Dec 2024 17:50:46 +0100 Subject: [PATCH 68/75] eth_getAccount depricated --- .../src/syscall_handler/evm/account.rs | 33 +++++++++++++++---- .../src/syscall_handler/evm/storage.rs | 19 +++++------ 2 files changed, 35 insertions(+), 17 deletions(-) diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs index dc550715..43568932 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs @@ -6,11 +6,7 @@ use std::env; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; use types::{ - cairo::{ - evm::account::{CairoAccount, FunctionId}, - structs::Uint256, - traits::CairoType, - }, + cairo::{evm::account::FunctionId, structs::Uint256, traits::CairoType}, keys::account::{CairoKey, Key}, RPC, }; @@ -45,8 +41,31 @@ impl CallHandler for AccountCallHandler { let runtime = tokio::runtime::Runtime::new().unwrap(); let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let value = runtime - .block_on(async { provider.get_account(key.address).block_id(key.block_number.into()).await }) + .block_on(async { + match function_id { + FunctionId::Balance => provider + .get_balance(key.address) + .block_id(key.block_number.into()) + .await + .map(Uint256::from), + FunctionId::Nonce => provider + .get_transaction_count(key.address) + .block_id(key.block_number.into()) + .await + .map(Uint256::from), + FunctionId::StateRoot => provider + .get_proof(key.address, vec![]) + .block_id(key.block_number.into()) + .await + .map(|f| Uint256::from(f.storage_hash)), + FunctionId::CodeHash => provider + .get_proof(key.address, vec![]) + .block_id(key.block_number.into()) + .await + .map(|f| Uint256::from(f.code_hash)), + } + }) .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(CairoAccount::from(value).handle(function_id)) + Ok(value) } } diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs index ab687f10..4e1b1436 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs @@ -6,11 +6,7 @@ use std::env; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; use types::{ - cairo::{ - evm::storage::{CairoStorage, FunctionId}, - structs::Uint256, - traits::CairoType, - }, + cairo::{evm::storage::FunctionId, structs::Uint256, traits::CairoType}, keys::storage::{CairoKey, Key}, RPC, }; @@ -46,12 +42,15 @@ impl CallHandler for StorageCallHandler { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); let value = runtime .block_on(async { - provider - .get_storage_at(key.address, key.storage_slot.into()) - .block_id(key.block_number.into()) - .await + match function_id { + FunctionId::Storage => provider + .get_storage_at(key.address, key.storage_slot.into()) + .block_id(key.block_number.into()) + .await + .map(Uint256::from), + } }) .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; - Ok(CairoStorage::from(value).handle(function_id)) + Ok(value) } } From 97162b4cc198825ec9cba0fbb78a997e4a5a4fc5 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 27 Dec 2024 01:01:45 +0100 Subject: [PATCH 69/75] rlp decoding fixes --- Cargo.lock | 10 ++++--- Scarb.toml | 4 +-- crates/hints/src/print.rs | 3 --- crates/sound_hint_processor/Cargo.toml | 2 +- .../src/syscall_handler/evm/account.rs | 15 +++++------ .../src/syscall_handler/evm/header.rs | 12 ++++----- .../src/syscall_handler/evm/storage.rs | 12 ++++----- src/contract_bootloader/contract.cairo | 25 ++++++++++++----- .../contract_dry_run.cairo | 20 ++++++++++++-- src/hdp.cairo | 27 +------------------ 10 files changed, 66 insertions(+), 64 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9c11c0a6..f294a128 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3992,9 +3992,9 @@ checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2" [[package]] name = "reqwest" -version = "0.12.9" +version = "0.12.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a77c62af46e79de0a562e1a9849205ffcb7fc1238876e9bd743357570e04046f" +checksum = "3d3536321cfc54baa8cf3e273d5e1f63f889067829c4b410fcdbac8ca7b80994" dependencies = [ "base64 0.22.1", "bytes", @@ -4025,6 +4025,7 @@ dependencies = [ "system-configuration", "tokio", "tokio-native-tls", + "tower", "tower-service", "url", "wasm-bindgen", @@ -4236,9 +4237,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" +checksum = "f7c45b9784283f1b2e7fb61b42047c2fd678ef0960d4f6f1eba131594cc369d4" [[package]] name = "rusty-fork" @@ -5247,6 +5248,7 @@ dependencies = [ "futures-util", "pin-project-lite", "sync_wrapper", + "tokio", "tower-layer", "tower-service", ] diff --git a/Scarb.toml b/Scarb.toml index 734c930d..bca74784 100644 --- a/Scarb.toml +++ b/Scarb.toml @@ -4,8 +4,8 @@ version = "0.1.0" edition = "2023_11" members = [ - "hdp_cairo" + "hdp_cairo", ] [workspace.dependencies] -hdp_cairo = { path = "cairo" } \ No newline at end of file +hdp_cairo = { path = "hdp_cairo" } \ No newline at end of file diff --git a/crates/hints/src/print.rs b/crates/hints/src/print.rs index 0599490b..584ea756 100644 --- a/crates/hints/src/print.rs +++ b/crates/hints/src/print.rs @@ -23,7 +23,6 @@ pub fn program_hash( let program_hash = get_integer_from_var_name(vars::ids::PROGRAM_HASH, vm, &hint_data.ids_data, &hint_data.ap_tracking)?; debug!("program_hash: {}", program_hash); - Ok(()) } @@ -46,10 +45,8 @@ pub fn hint_print_task_result( let result_low = result[0].to_biguint(); let result_high = result[1].to_biguint(); let base = BigUint::from(2u32).pow(128); - let result_value = result_high * base + result_low; debug!("Task Result: 0x{:x}", result_value); - Ok(()) } diff --git a/crates/sound_hint_processor/Cargo.toml b/crates/sound_hint_processor/Cargo.toml index 056daa2c..78369ecc 100644 --- a/crates/sound_hint_processor/Cargo.toml +++ b/crates/sound_hint_processor/Cargo.toml @@ -4,13 +4,13 @@ version = "0.1.0" edition = "2021" [dependencies] +alloy-rlp.workspace = true cairo-lang-casm.workspace = true cairo-lang-starknet-classes.workspace = true cairo-vm.workspace = true serde.workspace = true starknet-types-core.workspace = true strum_macros.workspace = true -alloy-rlp.workspace = true hints.workspace = true syscall_handler.workspace = true diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs index d1073648..28fc708a 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs @@ -1,8 +1,8 @@ -use std::cell::RefCell; -use std::rc::Rc; - +use crate::syscall_handler::Memorizer; use cairo_vm::hint_processor::builtin_hint_processor::dict_manager::DictManager; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use std::cell::RefCell; +use std::rc::Rc; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; use types::cairo::evm::account::CairoAccount; @@ -11,8 +11,6 @@ use types::{ keys::account::CairoKey, }; -use crate::syscall_handler::Memorizer; - #[derive(Debug)] pub struct AccountCallHandler { pub memorizer: Memorizer, @@ -50,9 +48,10 @@ impl CallHandler for AccountCallHandler { fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { let ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; - let header = alloy_rlp::Header::decode(&mut vm.get_integer(ptr)?.to_bytes_le().as_slice()) - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?; - let length = header.payload_length + 1; + let mut data = vm.get_integer(ptr)?.to_bytes_le().to_vec(); + data.resize(1024, 0); + let header = alloy_rlp::Header::decode(&mut data.as_slice()).map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?; + let length = header.length_with_payload(); let rlp = vm .get_integer_range(ptr, (length + 7) / 8)? .into_iter() diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs index ac0fb474..cfbb1f95 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs @@ -1,9 +1,8 @@ -use std::cell::RefCell; -use std::rc::Rc; - use crate::syscall_handler::Memorizer; use cairo_vm::hint_processor::builtin_hint_processor::dict_manager::DictManager; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use std::cell::RefCell; +use std::rc::Rc; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; use types::cairo::evm::header::CairoHeader; @@ -49,9 +48,10 @@ impl CallHandler for HeaderCallHandler { fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { let ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; - let header = alloy_rlp::Header::decode(&mut vm.get_integer(ptr)?.to_bytes_le().as_slice()) - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?; - let length = header.payload_length + 1; + let mut data = vm.get_integer(ptr)?.to_bytes_le().to_vec(); + data.resize(1024, 0); + let header = alloy_rlp::Header::decode(&mut data.as_slice()).map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?; + let length = header.length_with_payload(); let rlp = vm .get_integer_range(ptr, (length + 7) / 8)? .into_iter() diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs index 402581bb..8014c377 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs @@ -1,9 +1,8 @@ -use std::cell::RefCell; -use std::rc::Rc; - use crate::syscall_handler::Memorizer; use cairo_vm::hint_processor::builtin_hint_processor::dict_manager::DictManager; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; +use std::cell::RefCell; +use std::rc::Rc; use syscall_handler::traits::CallHandler; use syscall_handler::{SyscallExecutionError, SyscallResult}; use types::cairo::evm::storage::CairoStorage; @@ -49,9 +48,10 @@ impl CallHandler for StorageCallHandler { fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { let ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; - let header = alloy_rlp::Header::decode(&mut vm.get_integer(ptr)?.to_bytes_le().as_slice()) - .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?; - let length = header.payload_length + 1; + let mut data = vm.get_integer(ptr)?.to_bytes_le().to_vec(); + data.resize(1024, 0); + let header = alloy_rlp::Header::decode(&mut data.as_slice()).map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?; + let length = header.length_with_payload(); let rlp = vm .get_integer_range(ptr, (length + 7) / 8)? .into_iter() diff --git a/src/contract_bootloader/contract.cairo b/src/contract_bootloader/contract.cairo index 0978ceb5..9fa97f96 100644 --- a/src/contract_bootloader/contract.cairo +++ b/src/contract_bootloader/contract.cairo @@ -88,12 +88,25 @@ func compute_contract{ ); } + tempvar low; + tempvar high; + + if (retdata_size == 0) { + low = 0x0; + high = 0x0; + } if (retdata_size == 1) { - let result = felt_to_uint256(retdata[0]); - return (result=result, program_hash=program_hash); - } else { - assert retdata_size = 2; - let result = Uint256(low=retdata[0], high=retdata[1]); - return (result=result, program_hash=program_hash); + low = retdata[0]; + high = 0x0; + } + if (retdata_size == 2) { + low = retdata[0]; + high = retdata[1]; } + + local result: Uint256 = Uint256(low=low, high=high); + + %{ print(f"Task Result: {hex(ids.result.high * 2 ** 128 + ids.result.low)}") %} + + return (result=result, program_hash=program_hash); } diff --git a/src/contract_bootloader/contract_dry_run.cairo b/src/contract_bootloader/contract_dry_run.cairo index f507df76..92d2d725 100644 --- a/src/contract_bootloader/contract_dry_run.cairo +++ b/src/contract_bootloader/contract_dry_run.cairo @@ -116,8 +116,24 @@ func main{ compiled_class=compiled_class, calldata_size=calldata_size, calldata=calldata, dry_run=1 ); } - assert retdata_size = 2; - local result: Uint256 = Uint256(low=retdata[0], high=retdata[1]); + + tempvar low; + tempvar high; + + if (retdata_size == 0) { + low = 0x0; + high = 0x0; + } + if (retdata_size == 1) { + low = retdata[0]; + high = 0x0; + } + if (retdata_size == 2) { + low = retdata[0]; + high = retdata[1]; + } + + local result: Uint256 = Uint256(low=low, high=high); %{ print(f"Task Result: {hex(ids.result.high * 2 ** 128 + ids.result.low)}") %} diff --git a/src/hdp.cairo b/src/hdp.cairo index e743928d..52739fb2 100644 --- a/src/hdp.cairo +++ b/src/hdp.cairo @@ -102,7 +102,7 @@ func run{ let starknet_key_hasher_ptr = StarknetStateAccess.init(); let starknet_decoder_ptr = StarknetDecoder.init(); - let (program_hash, result) = compute_tasks{ + let (result, program_hash) = compute_contract{ pedersen_ptr=pedersen_ptr, range_check_ptr=range_check_ptr, ecdsa_ptr=ecdsa_ptr, @@ -131,28 +131,3 @@ func run{ return (); } - -func compute_tasks{ - pedersen_ptr: HashBuiltin*, - range_check_ptr, - ecdsa_ptr, - bitwise_ptr: BitwiseBuiltin*, - ec_op_ptr, - keccak_ptr: KeccakBuiltin*, - poseidon_ptr: PoseidonBuiltin*, - pow2_array: felt*, - evm_memorizer: DictAccess*, - evm_decoder_ptr: felt***, - evm_key_hasher_ptr: felt**, - starknet_memorizer: DictAccess*, - starknet_decoder_ptr: felt***, - starknet_key_hasher_ptr: felt**, -}() -> (program_hash: felt, result: Uint256) { - alloc_locals; - - let (result, program_hash) = compute_contract(); - - %{ print(f"Task Result: {hex(ids.result.high * 2 ** 128 + ids.result.low)}") %} - - return (program_hash=program_hash, result=result); -} From 6193a3e3c1216da5d6f5450d836b6a7126f04656 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 27 Dec 2024 12:06:57 +0100 Subject: [PATCH 70/75] tests & endianness fixes --- Cargo.lock | 19 ++ Cargo.toml | 4 +- Scarb.lock | 13 ++ Scarb.toml | 1 + crates/dry_hint_processor/src/lib.rs | 5 +- .../src/syscall_handler/evm/account.rs | 52 +++--- .../src/syscall_handler/evm/header.rs | 8 +- .../src/syscall_handler/evm/mod.rs | 27 +-- .../src/syscall_handler/evm/storage.rs | 22 +-- crates/dry_run/Cargo.toml | 3 +- crates/dry_run/src/main.rs | 3 +- crates/fetcher/src/lib.rs | 26 +++ crates/fetcher/src/main.rs | 27 +-- crates/sound_hint_processor/Cargo.toml | 1 + crates/sound_hint_processor/src/lib.rs | 5 +- .../src/syscall_handler/evm/account.rs | 2 +- .../src/syscall_handler/evm/header.rs | 2 +- .../src/syscall_handler/evm/mod.rs | 27 +-- .../src/syscall_handler/evm/storage.rs | 2 +- crates/sound_run/Cargo.toml | 3 +- crates/sound_run/src/main.rs | 3 +- crates/syscall_handler/src/lib.rs | 4 +- crates/syscall_handler/src/traits.rs | 4 +- crates/types/src/cairo/structs.rs | 10 +- packages/eth_essentials | 2 +- tests/modules/Cargo.toml | 18 ++ tests/modules/Scarb.lock | 51 ------ tests/modules/Scarb.toml | 28 +-- tests/modules/account_modules/Scarb.toml | 21 --- tests/modules/account_modules/src/lib.cairo | 71 -------- tests/modules/build.rs | 61 +++++++ tests/modules/src/lib.cairo | 1 + tests/modules/src/lib.rs | 7 + tests/modules/src/tests.cairo | 1 + tests/modules/src/tests/account_modules.cairo | 101 +++++++++++ tests/modules/src/tests/account_modules.rs | 29 ++++ tests/modules/src/tests/account_modules.sh | 34 ++++ tests/modules/src/tests/mod.rs | 163 ++++++++++++++++++ 38 files changed, 595 insertions(+), 266 deletions(-) create mode 100644 crates/fetcher/src/lib.rs create mode 100644 tests/modules/Cargo.toml delete mode 100644 tests/modules/Scarb.lock delete mode 100644 tests/modules/account_modules/Scarb.toml delete mode 100644 tests/modules/account_modules/src/lib.cairo create mode 100644 tests/modules/build.rs create mode 100644 tests/modules/src/lib.cairo create mode 100644 tests/modules/src/lib.rs create mode 100644 tests/modules/src/tests.cairo create mode 100644 tests/modules/src/tests/account_modules.cairo create mode 100644 tests/modules/src/tests/account_modules.rs create mode 100644 tests/modules/src/tests/account_modules.sh create mode 100644 tests/modules/src/tests/mod.rs diff --git a/Cargo.lock b/Cargo.lock index f294a128..657a9ae9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2091,6 +2091,7 @@ dependencies = [ "serde_json", "sha2", "thiserror 1.0.69", + "tokio", "tracing", "tracing-subscriber", "types", @@ -4653,6 +4654,7 @@ dependencies = [ "starknet-types-core", "strum_macros", "syscall_handler", + "tokio", "types", ] @@ -4666,6 +4668,7 @@ dependencies = [ "sha2", "sound_hint_processor", "thiserror 1.0.69", + "tokio", "tracing", "tracing-subscriber", "types", @@ -4985,6 +4988,22 @@ dependencies = [ "winapi", ] +[[package]] +name = "tests_modules" +version = "0.1.0" +dependencies = [ + "cairo-lang-starknet-classes", + "cairo-vm", + "dry_hint_processor", + "fetcher", + "futures", + "hints", + "serde_json", + "sound_hint_processor", + "tokio", + "types", +] + [[package]] name = "thiserror" version = "1.0.69" diff --git a/Cargo.toml b/Cargo.toml index ca48acdc..02d4f9a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ members = [ "crates/indexer", "crates/syscall_handler", "crates/types", + "tests/modules", ] [workspace.dependencies] @@ -18,7 +19,7 @@ alloy = { version = "0.7.2", features = ["full"] } alloy-rlp = { version = "0.3.5", features = ["derive"] } bincode = { version = "2.0.0-rc.3", default-features = false, features = ["serde"] } cairo-lang-casm = { version = "2.9.0-dev.0", default-features = false } -cairo-lang-starknet-classes = { version = "2.9.0-dev.0" } +cairo-lang-starknet-classes = "2.9.2" cairo-type-derive = { git = "https://github.com/keep-starknet-strange/snos.git", rev = "35a300a10d2107482ada440b5025ee2f651afbd4" } cairo-vm = { git = "https://github.com/lambdaclass/cairo-vm", rev = "388a4e51001377717b7e4c902c35f8e271c92ad7", features = ["extensive_hints", "clap", "cairo-1-hints"] } clap = { version = "4.3.10", features = ["derive"] } @@ -45,6 +46,7 @@ tracing-subscriber = "0.3" dry_hint_processor = { path = "crates/dry_hint_processor" } eth_essentials_cairo_vm_hints = { path = "packages/eth_essentials/cairo_vm_hints"} +fetcher = { path = "crates/fetcher" } hints = { path = "crates/hints" } indexer = { path = "crates/indexer" } sound_hint_processor = { path = "crates/sound_hint_processor" } diff --git a/Scarb.lock b/Scarb.lock index f1f02371..5f2932c9 100644 --- a/Scarb.lock +++ b/Scarb.lock @@ -4,3 +4,16 @@ version = 1 [[package]] name = "hdp_cairo" version = "0.1.0" + +[[package]] +name = "modules" +version = "0.1.0" +dependencies = [ + "hdp_cairo", + "snforge_std", +] + +[[package]] +name = "snforge_std" +version = "0.24.0" +source = "git+https://github.com/foundry-rs/starknet-foundry?tag=v0.24.0#95e9fb09cb91b3c05295915179ee1b55bf923653" diff --git a/Scarb.toml b/Scarb.toml index bca74784..1afacf6f 100644 --- a/Scarb.toml +++ b/Scarb.toml @@ -5,6 +5,7 @@ edition = "2023_11" members = [ "hdp_cairo", + "tests/modules", ] [workspace.dependencies] diff --git a/crates/dry_hint_processor/src/lib.rs b/crates/dry_hint_processor/src/lib.rs index 8a2592f5..585fa5f6 100644 --- a/crates/dry_hint_processor/src/lib.rs +++ b/crates/dry_hint_processor/src/lib.rs @@ -25,6 +25,7 @@ use hints::{extensive_hints, hints, vars, ExtensiveHintImpl, HintImpl}; use starknet_types_core::felt::Felt; use std::{any::Any, collections::HashMap}; use syscall_handler::evm::SyscallHandlerWrapper; +use tokio::{runtime::Handle, task}; use types::HDPDryRunInput; pub struct CustomHintProcessor { @@ -113,7 +114,9 @@ impl HintProcessorLogic for CustomHintProcessor { if let Hint::Starknet(StarknetHint::SystemCall { system }) = hint { let syscall_ptr = get_ptr_from_res_operand(vm, system)?; let syscall_handler = exec_scopes.get_mut_ref::(vars::scopes::SYSCALL_HANDLER)?; - return syscall_handler.execute_syscall(vm, syscall_ptr).map(|_| HintExtension::default()); + return task::block_in_place(|| { + Handle::current().block_on(async { syscall_handler.execute_syscall(vm, syscall_ptr).await.map(|_| HintExtension::default()) }) + }); } else { return self .cairo1_builtin_hint_proc diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs index 43568932..a2b5bdd1 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/account.rs @@ -37,35 +37,31 @@ impl CallHandler for AccountCallHandler { }) } - fn handle(&mut self, key: Self::Key, function_id: Self::Id, _vm: &VirtualMachine) -> SyscallResult { - let runtime = tokio::runtime::Runtime::new().unwrap(); + async fn handle(&mut self, key: Self::Key, function_id: Self::Id, _vm: &VirtualMachine) -> SyscallResult { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let value = runtime - .block_on(async { - match function_id { - FunctionId::Balance => provider - .get_balance(key.address) - .block_id(key.block_number.into()) - .await - .map(Uint256::from), - FunctionId::Nonce => provider - .get_transaction_count(key.address) - .block_id(key.block_number.into()) - .await - .map(Uint256::from), - FunctionId::StateRoot => provider - .get_proof(key.address, vec![]) - .block_id(key.block_number.into()) - .await - .map(|f| Uint256::from(f.storage_hash)), - FunctionId::CodeHash => provider - .get_proof(key.address, vec![]) - .block_id(key.block_number.into()) - .await - .map(|f| Uint256::from(f.code_hash)), - } - }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + let value = match function_id { + FunctionId::Balance => provider + .get_balance(key.address) + .block_id(key.block_number.into()) + .await + .map(Uint256::from), + FunctionId::Nonce => provider + .get_transaction_count(key.address) + .block_id(key.block_number.into()) + .await + .map(Uint256::from), + FunctionId::StateRoot => provider + .get_proof(key.address, vec![]) + .block_id(key.block_number.into()) + .await + .map(|f| Uint256::from(f.storage_hash)), + FunctionId::CodeHash => provider + .get_proof(key.address, vec![]) + .block_id(key.block_number.into()) + .await + .map(|f| Uint256::from(f.code_hash)), + } + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; Ok(value) } } diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs index d157d5de..edbd05a2 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/header.rs @@ -42,11 +42,11 @@ impl CallHandler for HeaderCallHandler { }) } - fn handle(&mut self, key: Self::Key, function_id: Self::Id, _vm: &VirtualMachine) -> SyscallResult { + async fn handle(&mut self, key: Self::Key, function_id: Self::Id, _vm: &VirtualMachine) -> SyscallResult { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let runtime = tokio::runtime::Runtime::new().unwrap(); - let value = runtime - .block_on(async { provider.get_block_by_number(key.block_number.into(), BlockTransactionsKind::Hashes).await }) + let value = provider + .get_block_by_number(key.block_number.into(), BlockTransactionsKind::Hashes) + .await .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))? .ok_or(SyscallExecutionError::InternalError("Block not found".into()))?; Ok(CairoHeader::from(value.header.inner).handle(function_id)) diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs index f05a5f13..4432593c 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/mod.rs @@ -8,16 +8,17 @@ use cairo_vm::vm::errors::hint_errors::HintError; use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Felt252}; use serde::{Deserialize, Serialize}; use std::rc::Rc; -use std::sync::RwLock; use std::{collections::HashSet, hash::Hash}; use strum_macros::FromRepr; use syscall_handler::traits::CallHandler; use syscall_handler::{felt_from_ptr, run_handler, traits, SyscallExecutionError, SyscallResult, SyscallSelector, WriteResponseResult}; +use tokio::sync::RwLock; +use tokio::task; use types::cairo::new_syscalls::{CallContractRequest, CallContractResponse}; use types::cairo::traits::CairoType; use types::keys; -#[derive(Debug, Default, Serialize, Deserialize)] +#[derive(Debug, Default, Serialize, Deserialize, Clone)] pub struct SyscallHandler { #[serde(skip)] pub syscall_ptr: Option, @@ -40,7 +41,7 @@ pub enum CallHandlerId { Receipt = 4, } -#[derive(Debug, Default, Serialize, Deserialize)] +#[derive(Debug, Default, Serialize, Deserialize, Clone)] pub struct CallContractHandler { pub key_set: HashSet, } @@ -52,17 +53,17 @@ impl SyscallHandlerWrapper { } } pub fn set_syscall_ptr(&self, syscall_ptr: Relocatable) { - let mut syscall_handler = self.syscall_handler.write().unwrap(); + let mut syscall_handler = task::block_in_place(|| self.syscall_handler.blocking_write()); syscall_handler.syscall_ptr = Some(syscall_ptr); } pub fn syscall_ptr(&self) -> Option { - let syscall_handler = self.syscall_handler.read().unwrap(); + let syscall_handler = task::block_in_place(|| self.syscall_handler.blocking_read()); syscall_handler.syscall_ptr } - pub fn execute_syscall(&mut self, vm: &mut VirtualMachine, syscall_ptr: Relocatable) -> Result<(), HintError> { - let mut syscall_handler = self.syscall_handler.write().unwrap(); + pub async fn execute_syscall(&mut self, vm: &mut VirtualMachine, syscall_ptr: Relocatable) -> Result<(), HintError> { + let mut syscall_handler = self.syscall_handler.write().await; let ptr = &mut syscall_handler .syscall_ptr .ok_or(HintError::CustomHint(Box::from("syscall_ptr is None")))?; @@ -70,7 +71,7 @@ impl SyscallHandlerWrapper { assert_eq!(*ptr, syscall_ptr); match SyscallSelector::try_from(felt_from_ptr(vm, ptr)?)? { - SyscallSelector::CallContract => run_handler(&mut syscall_handler.call_contract_handler, ptr, vm), + SyscallSelector::CallContract => run_handler(&mut syscall_handler.call_contract_handler, ptr, vm).await, }?; syscall_handler.syscall_ptr = Some(*ptr); @@ -89,7 +90,7 @@ impl traits::SyscallHandler for CallContractHandler { Ok(ret) } - fn execute(&mut self, request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult { + async fn execute(&mut self, request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult { let mut calldata = request.calldata_start; let call_handler_id = CallHandlerId::try_from(request.contract_address)?; @@ -113,7 +114,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Header => { let key = header::HeaderCallHandler::derive_key(vm, &mut calldata)?; let function_id = header::HeaderCallHandler::derive_id(request.selector)?; - let result = header::HeaderCallHandler.handle(key.clone(), function_id, vm)?; + let result = header::HeaderCallHandler.handle(key.clone(), function_id, vm).await?; self.key_set.insert(DryRunKey::Header(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); @@ -121,7 +122,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Account => { let key = account::AccountCallHandler::derive_key(vm, &mut calldata)?; let function_id = account::AccountCallHandler::derive_id(request.selector)?; - let result = account::AccountCallHandler.handle(key.clone(), function_id, vm)?; + let result = account::AccountCallHandler.handle(key.clone(), function_id, vm).await?; self.key_set.insert(DryRunKey::Account(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); @@ -129,7 +130,7 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Storage => { let key = storage::StorageCallHandler::derive_key(vm, &mut calldata)?; let function_id = storage::StorageCallHandler::derive_id(request.selector)?; - let result = storage::StorageCallHandler.handle(key.clone(), function_id, vm)?; + let result = storage::StorageCallHandler.handle(key.clone(), function_id, vm).await?; self.key_set.insert(DryRunKey::Storage(key)); result.to_memory(vm, retdata_end)?; retdata_end += ::CallHandlerResult::n_fields(); @@ -161,7 +162,7 @@ impl TryFrom for CallHandlerId { } } -#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone)] #[serde(rename_all = "lowercase")] pub enum DryRunKey { Account(keys::account::Key), diff --git a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs index 4e1b1436..c1ffbf73 100644 --- a/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/dry_hint_processor/src/syscall_handler/evm/storage.rs @@ -37,20 +37,16 @@ impl CallHandler for StorageCallHandler { }) } - fn handle(&mut self, key: Self::Key, function_id: Self::Id, _vm: &VirtualMachine) -> SyscallResult { - let runtime = tokio::runtime::Runtime::new().unwrap(); + async fn handle(&mut self, key: Self::Key, function_id: Self::Id, _vm: &VirtualMachine) -> SyscallResult { let provider = RootProvider::>::new_http(Url::parse(&env::var(RPC).unwrap()).unwrap()); - let value = runtime - .block_on(async { - match function_id { - FunctionId::Storage => provider - .get_storage_at(key.address, key.storage_slot.into()) - .block_id(key.block_number.into()) - .await - .map(Uint256::from), - } - }) - .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; + let value = match function_id { + FunctionId::Storage => provider + .get_storage_at(key.address, key.storage_slot.into()) + .block_id(key.block_number.into()) + .await + .map(Uint256::from), + } + .map_err(|e| SyscallExecutionError::InternalError(e.to_string().into()))?; Ok(value) } } diff --git a/crates/dry_run/Cargo.toml b/crates/dry_run/Cargo.toml index 4ea2d4b4..f0e46fa0 100644 --- a/crates/dry_run/Cargo.toml +++ b/crates/dry_run/Cargo.toml @@ -9,8 +9,9 @@ clap.workspace = true dry_hint_processor.workspace = true serde_json.workspace = true thiserror.workspace = true -tracing.workspace = true +tokio.workspace = true tracing-subscriber.workspace = true +tracing.workspace = true hints.workspace = true types.workspace = true diff --git a/crates/dry_run/src/main.rs b/crates/dry_run/src/main.rs index 200faaab..f98e755e 100644 --- a/crates/dry_run/src/main.rs +++ b/crates/dry_run/src/main.rs @@ -34,7 +34,8 @@ struct Args { program_output: PathBuf, } -fn main() -> Result<(), HdpOsError> { +#[tokio::main(flavor = "multi_thread", worker_threads = 1)] +async fn main() -> Result<(), HdpOsError> { tracing_subscriber::fmt::init(); let args = Args::try_parse_from(std::env::args()).map_err(HdpOsError::Args)?; diff --git a/crates/fetcher/src/lib.rs b/crates/fetcher/src/lib.rs new file mode 100644 index 00000000..24550560 --- /dev/null +++ b/crates/fetcher/src/lib.rs @@ -0,0 +1,26 @@ +use alloy::hex::FromHexError; +use indexer::types::IndexerError; +use std::num::ParseIntError; +use thiserror::Error; + +pub mod proof_keys; + +#[derive(Error, Debug)] +pub enum FetcherError { + #[error(transparent)] + Args(#[from] clap::error::Error), + #[error("Output Error: {0}")] + Output(String), + #[error(transparent)] + IO(#[from] std::io::Error), + #[error(transparent)] + Indexer(#[from] IndexerError), + #[error(transparent)] + ParseIntError(#[from] ParseIntError), + #[error(transparent)] + FromHexError(#[from] FromHexError), + #[error(transparent)] + SerdeJson(#[from] serde_json::Error), + #[error("Internal Error: {0}")] + InternalError(String), +} diff --git a/crates/fetcher/src/main.rs b/crates/fetcher/src/main.rs index 49cdec4b..5bce5439 100644 --- a/crates/fetcher/src/main.rs +++ b/crates/fetcher/src/main.rs @@ -3,15 +3,14 @@ #![warn(unused_crate_dependencies)] #![forbid(unsafe_code)] -use alloy::hex::FromHexError; use clap::{Parser, ValueHint}; use dry_hint_processor::syscall_handler::evm::{self, SyscallHandler}; +use fetcher::FetcherError; use futures::{FutureExt, StreamExt}; -use indexer::types::IndexerError; use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use proof_keys::ProofKeys; -use std::{collections::HashSet, fs, num::ParseIntError, path::PathBuf}; -use thiserror::Error; +use std::{collections::HashSet, fs, path::PathBuf}; +use thiserror as _; use types::{ proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}, ChainProofs, @@ -126,23 +125,3 @@ async fn main() -> Result<(), FetcherError> { Ok(()) } - -#[derive(Error, Debug)] -pub enum FetcherError { - #[error(transparent)] - Args(#[from] clap::error::Error), - #[error("Output Error: {0}")] - Output(String), - #[error(transparent)] - IO(#[from] std::io::Error), - #[error(transparent)] - Indexer(#[from] IndexerError), - #[error(transparent)] - ParseIntError(#[from] ParseIntError), - #[error(transparent)] - FromHexError(#[from] FromHexError), - #[error(transparent)] - SerdeJson(#[from] serde_json::Error), - #[error("Internal Error: {0}")] - InternalError(String), -} diff --git a/crates/sound_hint_processor/Cargo.toml b/crates/sound_hint_processor/Cargo.toml index 78369ecc..de5f3ce0 100644 --- a/crates/sound_hint_processor/Cargo.toml +++ b/crates/sound_hint_processor/Cargo.toml @@ -11,6 +11,7 @@ cairo-vm.workspace = true serde.workspace = true starknet-types-core.workspace = true strum_macros.workspace = true +tokio.workspace = true hints.workspace = true syscall_handler.workspace = true diff --git a/crates/sound_hint_processor/src/lib.rs b/crates/sound_hint_processor/src/lib.rs index 843b1e43..9425cf08 100644 --- a/crates/sound_hint_processor/src/lib.rs +++ b/crates/sound_hint_processor/src/lib.rs @@ -25,6 +25,7 @@ use hints::{extensive_hints, hints, vars, ExtensiveHintImpl, HintImpl}; use starknet_types_core::felt::Felt; use std::{any::Any, collections::HashMap}; use syscall_handler::evm::SyscallHandlerWrapper; +use tokio::{runtime::Handle, task}; use types::HDPInput; pub struct CustomHintProcessor { @@ -112,7 +113,9 @@ impl HintProcessorLogic for CustomHintProcessor { if let Hint::Starknet(StarknetHint::SystemCall { system }) = hint { let syscall_ptr = get_ptr_from_res_operand(vm, system)?; let syscall_handler = exec_scopes.get_mut_ref::(vars::scopes::SYSCALL_HANDLER)?; - return syscall_handler.execute_syscall(vm, syscall_ptr).map(|_| HintExtension::default()); + return task::block_in_place(|| { + Handle::current().block_on(async { syscall_handler.execute_syscall(vm, syscall_ptr).await.map(|_| HintExtension::default()) }) + }); } else { return self .cairo1_builtin_hint_proc diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs index 28fc708a..e9a0bf07 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/account.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/account.rs @@ -46,7 +46,7 @@ impl CallHandler for AccountCallHandler { }) } - fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { + async fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { let ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; let mut data = vm.get_integer(ptr)?.to_bytes_le().to_vec(); data.resize(1024, 0); diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs index cfbb1f95..9242066f 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/header.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/header.rs @@ -46,7 +46,7 @@ impl CallHandler for HeaderCallHandler { }) } - fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { + async fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { let ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; let mut data = vm.get_integer(ptr)?.to_bytes_le().to_vec(); data.resize(1024, 0); diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs b/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs index bbc0386b..1b23da2c 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/mod.rs @@ -10,11 +10,12 @@ use cairo_vm::{types::relocatable::Relocatable, vm::vm_core::VirtualMachine, Fel use serde::{Deserialize, Serialize}; use std::cell::RefCell; use std::rc::Rc; -use std::sync::RwLock; use std::{collections::HashSet, hash::Hash}; use strum_macros::FromRepr; use syscall_handler::traits::CallHandler; use syscall_handler::{felt_from_ptr, run_handler, traits, SyscallExecutionError, SyscallResult, SyscallSelector, WriteResponseResult}; +use tokio::sync::RwLock; +use tokio::task; use types::cairo::new_syscalls::{CallContractRequest, CallContractResponse}; use types::cairo::traits::CairoType; use types::keys; @@ -76,17 +77,17 @@ impl SyscallHandlerWrapper { } } pub fn set_syscall_ptr(&self, syscall_ptr: Relocatable) { - let mut syscall_handler = self.syscall_handler.write().unwrap(); + let mut syscall_handler = task::block_in_place(|| self.syscall_handler.blocking_write()); syscall_handler.syscall_ptr = Some(syscall_ptr); } pub fn syscall_ptr(&self) -> Option { - let syscall_handler = self.syscall_handler.read().unwrap(); + let syscall_handler = task::block_in_place(|| self.syscall_handler.blocking_read()); syscall_handler.syscall_ptr } - pub fn execute_syscall(&mut self, vm: &mut VirtualMachine, syscall_ptr: Relocatable) -> Result<(), HintError> { - let mut syscall_handler = self.syscall_handler.write().unwrap(); + pub async fn execute_syscall(&mut self, vm: &mut VirtualMachine, syscall_ptr: Relocatable) -> Result<(), HintError> { + let mut syscall_handler = self.syscall_handler.write().await; let ptr = &mut syscall_handler .syscall_ptr .ok_or(HintError::CustomHint(Box::from("syscall_ptr is None")))?; @@ -94,7 +95,7 @@ impl SyscallHandlerWrapper { assert_eq!(*ptr, syscall_ptr); match SyscallSelector::try_from(felt_from_ptr(vm, ptr)?)? { - SyscallSelector::CallContract => run_handler(&mut syscall_handler.call_contract_handler, ptr, vm), + SyscallSelector::CallContract => run_handler(&mut syscall_handler.call_contract_handler, ptr, vm).await, }?; syscall_handler.syscall_ptr = Some(*ptr); @@ -113,7 +114,7 @@ impl traits::SyscallHandler for CallContractHandler { Ok(ret) } - fn execute(&mut self, request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult { + async fn execute(&mut self, request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult { let mut calldata = request.calldata_start; let call_handler_id = CallHandlerId::try_from(request.contract_address)?; @@ -127,7 +128,9 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Header => { let key = header::HeaderCallHandler::derive_key(vm, &mut calldata)?; let function_id = header::HeaderCallHandler::derive_id(request.selector)?; - let result = header::HeaderCallHandler::new(memorizer, self.dict_manager.clone()).handle(key.clone(), function_id, vm)?; + let result = header::HeaderCallHandler::new(memorizer, self.dict_manager.clone()) + .handle(key.clone(), function_id, vm) + .await?; self.key_set.insert(DryRunKey::Header( key.try_into() .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, @@ -138,7 +141,9 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Account => { let key = account::AccountCallHandler::derive_key(vm, &mut calldata)?; let function_id = account::AccountCallHandler::derive_id(request.selector)?; - let result = account::AccountCallHandler::new(memorizer, self.dict_manager.clone()).handle(key.clone(), function_id, vm)?; + let result = account::AccountCallHandler::new(memorizer, self.dict_manager.clone()) + .handle(key.clone(), function_id, vm) + .await?; self.key_set.insert(DryRunKey::Account( key.try_into() .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, @@ -149,7 +154,9 @@ impl traits::SyscallHandler for CallContractHandler { CallHandlerId::Storage => { let key = storage::StorageCallHandler::derive_key(vm, &mut calldata)?; let function_id = storage::StorageCallHandler::derive_id(request.selector)?; - let result = storage::StorageCallHandler::new(memorizer, self.dict_manager.clone()).handle(key.clone(), function_id, vm)?; + let result = storage::StorageCallHandler::new(memorizer, self.dict_manager.clone()) + .handle(key.clone(), function_id, vm) + .await?; self.key_set.insert(DryRunKey::Storage( key.try_into() .map_err(|e| SyscallExecutionError::InternalError(format!("{}", e).into()))?, diff --git a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs index 8014c377..3b075234 100644 --- a/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs +++ b/crates/sound_hint_processor/src/syscall_handler/evm/storage.rs @@ -46,7 +46,7 @@ impl CallHandler for StorageCallHandler { }) } - fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { + async fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult { let ptr = self.memorizer.read_key(key.hash(), self.dict_manager.clone())?; let mut data = vm.get_integer(ptr)?.to_bytes_le().to_vec(); data.resize(1024, 0); diff --git a/crates/sound_run/Cargo.toml b/crates/sound_run/Cargo.toml index 6158adbc..72993f18 100644 --- a/crates/sound_run/Cargo.toml +++ b/crates/sound_run/Cargo.toml @@ -9,8 +9,9 @@ clap.workspace = true serde_json.workspace = true sound_hint_processor.workspace = true thiserror.workspace = true -tracing.workspace = true +tokio.workspace = true tracing-subscriber.workspace = true +tracing.workspace = true types.workspace = true diff --git a/crates/sound_run/src/main.rs b/crates/sound_run/src/main.rs index 1b94fe81..c208a6c1 100644 --- a/crates/sound_run/src/main.rs +++ b/crates/sound_run/src/main.rs @@ -32,7 +32,8 @@ struct Args { program_output: PathBuf, } -fn main() -> Result<(), HdpOsError> { +#[tokio::main(flavor = "multi_thread", worker_threads = 1)] +async fn main() -> Result<(), HdpOsError> { tracing_subscriber::fmt::init(); let args = Args::try_parse_from(std::env::args()).map_err(HdpOsError::Args)?; diff --git a/crates/syscall_handler/src/lib.rs b/crates/syscall_handler/src/lib.rs index d8ca7089..f470cfc1 100644 --- a/crates/syscall_handler/src/lib.rs +++ b/crates/syscall_handler/src/lib.rs @@ -152,10 +152,10 @@ fn write_failure(gas_counter: Felt252, error_data: Vec, vm: &mut Virtua Ok(()) } -pub fn run_handler(syscall_handler: &mut impl SyscallHandler, syscall_ptr: &mut Relocatable, vm: &mut VirtualMachine) -> Result<(), HintError> { +pub async fn run_handler(syscall_handler: &mut impl SyscallHandler, syscall_ptr: &mut Relocatable, vm: &mut VirtualMachine) -> Result<(), HintError> { let remaining_gas = felt_from_ptr(vm, syscall_ptr)?; let request = syscall_handler.read_request(vm, syscall_ptr)?; - let syscall_result = syscall_handler.execute(request, vm); + let syscall_result = syscall_handler.execute(request, vm).await; match syscall_result { Ok(response) => { write_felt(vm, syscall_ptr, remaining_gas)?; diff --git a/crates/syscall_handler/src/traits.rs b/crates/syscall_handler/src/traits.rs index b829c666..b8f54e9c 100644 --- a/crates/syscall_handler/src/traits.rs +++ b/crates/syscall_handler/src/traits.rs @@ -7,7 +7,7 @@ pub trait SyscallHandler { type Request; type Response; fn read_request(&mut self, vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult; - fn execute(&mut self, request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult; + async fn execute(&mut self, request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult; fn write_response(&mut self, response: Self::Response, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult; } @@ -18,5 +18,5 @@ pub trait CallHandler { fn derive_key(vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult; fn derive_id(selector: Felt252) -> SyscallResult; - fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult; + async fn handle(&mut self, key: Self::Key, function_id: Self::Id, vm: &VirtualMachine) -> SyscallResult; } diff --git a/crates/types/src/cairo/structs.rs b/crates/types/src/cairo/structs.rs index a3351708..6a790cc4 100644 --- a/crates/types/src/cairo/structs.rs +++ b/crates/types/src/cairo/structs.rs @@ -9,8 +9,8 @@ use cairo_vm::{ #[derive(FieldOffsetGetters, CairoType, Default, Debug)] pub struct Uint256 { - pub high: Felt252, pub low: Felt252, + pub high: Felt252, } impl From for Uint256 { @@ -36,8 +36,8 @@ impl From for Uint256 { fn from(value: U256) -> Self { let bytes: [u8; 32] = value.to_be_bytes(); Self { - low: Felt252::from_bytes_be_slice(&bytes[0..16]), - high: Felt252::from_bytes_be_slice(&bytes[16..32]), + low: Felt252::from_bytes_be_slice(&bytes[16..32]), + high: Felt252::from_bytes_be_slice(&bytes[0..16]), } } } @@ -46,8 +46,8 @@ impl From for Uint256 { fn from(value: B256) -> Self { let bytes: [u8; 32] = value.0; Self { - low: Felt252::from_bytes_be_slice(&bytes[0..16]), - high: Felt252::from_bytes_be_slice(&bytes[16..32]), + low: Felt252::from_bytes_be_slice(&bytes[16..32]), + high: Felt252::from_bytes_be_slice(&bytes[0..16]), } } } diff --git a/packages/eth_essentials b/packages/eth_essentials index c4b00359..cc05b4c5 160000 --- a/packages/eth_essentials +++ b/packages/eth_essentials @@ -1 +1 @@ -Subproject commit c4b00359393f14aedecde237c9330ea758b8d6dd +Subproject commit cc05b4c550b79e8296f319d35eeffbf999aff325 diff --git a/tests/modules/Cargo.toml b/tests/modules/Cargo.toml new file mode 100644 index 00000000..d5eaf946 --- /dev/null +++ b/tests/modules/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "tests_modules" +version = "0.1.0" +edition = "2021" + +[dependencies] + +[dev-dependencies] +cairo-lang-starknet-classes.workspace = true +cairo-vm.workspace = true +dry_hint_processor.workspace = true +fetcher.workspace = true +futures.workspace = true +hints.workspace = true +serde_json.workspace = true +sound_hint_processor.workspace = true +tokio.workspace = true +types.workspace = true \ No newline at end of file diff --git a/tests/modules/Scarb.lock b/tests/modules/Scarb.lock deleted file mode 100644 index 48b7fe55..00000000 --- a/tests/modules/Scarb.lock +++ /dev/null @@ -1,51 +0,0 @@ -# Code generated by scarb DO NOT EDIT. -version = 1 - -[[package]] -name = "account_modules" -version = "0.1.0" -dependencies = [ - "hdp_cairo", - "snforge_std", -] - -[[package]] -name = "hdp_cairo" -version = "0.1.0" - -[[package]] -name = "header_modules" -version = "0.1.0" -dependencies = [ - "hdp_cairo", - "snforge_std", -] - -[[package]] -name = "receipt_modules" -version = "0.1.0" -dependencies = [ - "hdp_cairo", - "snforge_std", -] - -[[package]] -name = "snforge_std" -version = "0.24.0" -source = "git+https://github.com/foundry-rs/starknet-foundry?tag=v0.24.0#95e9fb09cb91b3c05295915179ee1b55bf923653" - -[[package]] -name = "storage_modules" -version = "0.1.0" -dependencies = [ - "hdp_cairo", - "snforge_std", -] - -[[package]] -name = "transaction_modules" -version = "0.1.0" -dependencies = [ - "hdp_cairo", - "snforge_std", -] diff --git a/tests/modules/Scarb.toml b/tests/modules/Scarb.toml index 6130f954..85e5057b 100644 --- a/tests/modules/Scarb.toml +++ b/tests/modules/Scarb.toml @@ -1,15 +1,21 @@ -[workspace] -name = "contracts" +[package] +name = "modules" version = "0.1.0" edition = "2023_11" -members = [ - "account_modules", - "header_modules", - "receipt_modules", - "storage_modules", - "transaction_modules", -] +# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html -[workspace.dependencies] -hdp_cairo = { path = "../../." } +[dependencies] +starknet = "2.6.3" +hdp_cairo = { workspace = true } + +[dev-dependencies] +snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.24.0" } + +[[target.starknet-contract]] +sierra = true +casm = true +casm-add-pythonic-hints = true + +[scripts] +test = "snforge test" diff --git a/tests/modules/account_modules/Scarb.toml b/tests/modules/account_modules/Scarb.toml deleted file mode 100644 index 2119a137..00000000 --- a/tests/modules/account_modules/Scarb.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "account_modules" -version = "0.1.0" -edition = "2023_11" - -# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html - -[dependencies] -starknet = "2.6.3" -hdp_cairo = { workspace = true } - -[dev-dependencies] -snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.24.0" } - -[[target.starknet-contract]] -sierra = true -casm = true -casm-add-pythonic-hints = true - -[scripts] -test = "snforge test" diff --git a/tests/modules/account_modules/src/lib.cairo b/tests/modules/account_modules/src/lib.cairo deleted file mode 100644 index d625cee6..00000000 --- a/tests/modules/account_modules/src/lib.cairo +++ /dev/null @@ -1,71 +0,0 @@ -#[starknet::contract] -mod get_nonce { - use hdp_cairo::evm::account::AccountTrait; - use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, address: felt252) -> u256 { - hdp - .evm - .account_get_nonce( - AccountKey { chain_id: 11155111, block_number: block_number.into(), address } - ) - } -} - -#[starknet::contract] -mod get_balance { - use hdp_cairo::evm::account::AccountTrait; - use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, address: felt252) -> u256 { - hdp - .evm - .account_get_balance( - AccountKey { chain_id: 11155111, block_number: block_number.into(), address } - ) - } -} - -#[starknet::contract] -mod get_state_root { - use hdp_cairo::evm::account::AccountTrait; - use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, address: felt252) -> u256 { - hdp - .evm - .account_get_state_root( - AccountKey { chain_id: 11155111, block_number: block_number.into(), address } - ) - } -} - -#[starknet::contract] -mod get_code_hash { - use hdp_cairo::evm::account::AccountTrait; - use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, address: felt252) -> u256 { - hdp - .evm - .account_get_code_hash( - AccountKey { chain_id: 11155111, block_number: block_number.into(), address } - ) - } -} diff --git a/tests/modules/build.rs b/tests/modules/build.rs new file mode 100644 index 00000000..d9b10327 --- /dev/null +++ b/tests/modules/build.rs @@ -0,0 +1,61 @@ +use std::path::PathBuf; +use std::process::Command; +use std::{env, fs}; + +fn main() { + let workspace_root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is not set")).join("../../"); + let python_path = workspace_root.join("venv/bin"); + let cairo_path = workspace_root.join("packages/eth_essentials"); + let src_dir = workspace_root.join("src"); + let output_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is not set")).join("cairo"); + + println!("cargo::rerun-if-changed={}", src_dir.display()); + + // Create output directory + fs::create_dir_all(&output_dir).expect("Failed to create output directory"); + + // Run the cairo-compile command. + let status = Command::new(python_path.join("cairo-compile").to_str().expect("Failed to convert path to string")) + .arg(format!("--cairo_path={}:{}", workspace_root.display(), cairo_path.display())) + .arg( + src_dir + .join("contract_bootloader") + .join("contract_dry_run.cairo") + .to_str() + .expect("Failed to convert path to string"), + ) + .arg("--output") + .arg( + output_dir + .join("dry_run_compiled.json") + .to_str() + .expect("Failed to convert path to string"), + ) + .status() + .expect("Failed to execute cairo-compile"); + + if !status.success() { + panic!( + "cairo-compile failed for file: {}", + src_dir.join("contract_bootloader").join("contract_dry_run.cairo").display() + ); + } + + // Run the cairo-compile command. + let status = Command::new(python_path.join("cairo-compile").to_str().expect("Failed to convert path to string")) + .arg(format!("--cairo_path={}:{}", workspace_root.display(), cairo_path.display())) + .arg(src_dir.join("hdp.cairo").to_str().expect("Failed to convert path to string")) + .arg("--output") + .arg( + output_dir + .join("sound_run_compiled.json") + .to_str() + .expect("Failed to convert path to string"), + ) + .status() + .expect("Failed to execute cairo-compile"); + + if !status.success() { + panic!("cairo-compile failed for file: {}", src_dir.join("hdp.cairo").display()); + } +} diff --git a/tests/modules/src/lib.cairo b/tests/modules/src/lib.cairo new file mode 100644 index 00000000..3023529a --- /dev/null +++ b/tests/modules/src/lib.cairo @@ -0,0 +1 @@ +pub mod tests; \ No newline at end of file diff --git a/tests/modules/src/lib.rs b/tests/modules/src/lib.rs new file mode 100644 index 00000000..40794cfa --- /dev/null +++ b/tests/modules/src/lib.rs @@ -0,0 +1,7 @@ +#![allow(async_fn_in_trait)] +#![warn(unused_extern_crates)] +#![warn(unused_crate_dependencies)] +#![forbid(unsafe_code)] + +#[cfg(test)] +pub mod tests; diff --git a/tests/modules/src/tests.cairo b/tests/modules/src/tests.cairo new file mode 100644 index 00000000..2f8a5d5e --- /dev/null +++ b/tests/modules/src/tests.cairo @@ -0,0 +1 @@ +pub mod account_modules; \ No newline at end of file diff --git a/tests/modules/src/tests/account_modules.cairo b/tests/modules/src/tests/account_modules.cairo new file mode 100644 index 00000000..504b159d --- /dev/null +++ b/tests/modules/src/tests/account_modules.cairo @@ -0,0 +1,101 @@ +#[starknet::contract] +mod get_nonce { + use hdp_cairo::evm::account::AccountTrait; + use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .account_get_nonce( + AccountKey { + chain_id: 11155111, + block_number: 6000000, + address: 0xc6e2459991BfE27cca6d86722F35da23A1E4Cb97 + } + ) == u256 { low: 0x1, high: 0x0 } + ); + } +} + +#[starknet::contract] +mod get_balance { + use hdp_cairo::evm::account::AccountTrait; + use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .account_get_balance( + AccountKey { + chain_id: 11155111, + block_number: 6000000, + address: 0xc6e2459991BfE27cca6d86722F35da23A1E4Cb97 + } + ) == u256 { low: 0x1c4b9ada4bf56c21940, high: 0x0 } + ); + } +} + +#[starknet::contract] +mod get_state_root { + use hdp_cairo::evm::account::AccountTrait; + use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .account_get_state_root( + AccountKey { + chain_id: 11155111, + block_number: 6000000, + address: 0xc6e2459991BfE27cca6d86722F35da23A1E4Cb97 + } + ) == u256 { + low: 0x5b48e01b996cadc001622fb5e363b421, + high: 0x56e81f171bcc55a6ff8345e692c0f86e + } + ); + } +} + +#[starknet::contract] +mod get_code_hash { + use hdp_cairo::evm::account::AccountTrait; + use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .account_get_code_hash( + AccountKey { + chain_id: 11155111, + block_number: 6000000, + address: 0xc6e2459991BfE27cca6d86722F35da23A1E4Cb97 + } + ) == u256 { + low: 0xe500b653ca82273b7bfad8045d85a470, + high: 0xc5d2460186f7233c927e7db2dcc703c0 + } + ); + } +} diff --git a/tests/modules/src/tests/account_modules.rs b/tests/modules/src/tests/account_modules.rs new file mode 100644 index 00000000..7900be31 --- /dev/null +++ b/tests/modules/src/tests/account_modules.rs @@ -0,0 +1,29 @@ +use super::run; + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_balance() { + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_balance.compiled_contract_class.json")).unwrap()).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_code_hash() { + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_get_code_hash.compiled_contract_class.json" + )) + .unwrap()) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_nonce() { + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_nonce.compiled_contract_class.json")).unwrap()).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_state_root() { + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_get_state_root.compiled_contract_class.json" + )) + .unwrap()) + .await +} diff --git a/tests/modules/src/tests/account_modules.sh b/tests/modules/src/tests/account_modules.sh new file mode 100644 index 00000000..dd6b9171 --- /dev/null +++ b/tests/modules/src/tests/account_modules.sh @@ -0,0 +1,34 @@ +# Set the RPC environment variable + +# eth_getTransactionCount +curl -X POST \ + --url $RPC_URL \ + --header 'Content-Type: application/json' \ + --data '{ + "jsonrpc": "2.0", + "method": "eth_getTransactionCount", + "params": ["0xc6e2459991BfE27cca6d86722F35da23A1E4Cb97", "0x5B8D80"], + "id": 1 + }' + +# eth_getBalance +curl -X POST \ + --url $RPC_URL \ + --header 'Content-Type: application/json' \ + --data '{ + "jsonrpc": "2.0", + "method": "eth_getBalance", + "params": ["0xc6e2459991BfE27cca6d86722F35da23A1E4Cb97", "0x5B8D80"], + "id": 1 + }' + +# eth_getProof +curl -X POST \ + --url $RPC_URL \ + --header 'Content-Type: application/json' \ + --data '{ + "jsonrpc": "2.0", + "method": "eth_getProof", + "params": ["0xc6e2459991BfE27cca6d86722F35da23A1E4Cb97", [], "0x5B8D80"], + "id": 1 + }' diff --git a/tests/modules/src/tests/mod.rs b/tests/modules/src/tests/mod.rs new file mode 100644 index 00000000..e9a7b8d9 --- /dev/null +++ b/tests/modules/src/tests/mod.rs @@ -0,0 +1,163 @@ +use cairo_lang_starknet_classes::casm_contract_class::CasmContractClass; +use cairo_vm::{ + cairo_run::CairoRunConfig, + types::{layout_name::LayoutName, program::Program}, + vm::runners::cairo_runner::{CairoRunner, RunnerMode}, +}; +use dry_hint_processor::syscall_handler::evm::{self, SyscallHandler, SyscallHandlerWrapper}; +use fetcher::proof_keys::ProofKeys; +use futures::{FutureExt, StreamExt}; +use hints::vars; +use std::{collections::HashSet, env, path::PathBuf}; +use types::{ + proofs::{account::Account, storage::Storage, HeaderMmrMeta, Proofs}, + ChainProofs, HDPDryRunInput, HDPInput, +}; + +pub mod account_modules; + +const BUFFER_UNORDERED: usize = 50; + +async fn run(compiled_class: CasmContractClass) { + // Init CairoRunConfig + let cairo_run_config = CairoRunConfig { + layout: LayoutName::starknet_with_keccak, + relocate_mem: true, + trace_enabled: true, + ..Default::default() + }; + + let runner_mode = if cairo_run_config.proof_mode { + RunnerMode::ProofModeCairo1 + } else { + RunnerMode::ExecutionMode + }; + + // Locate the compiled program file in the `OUT_DIR` folder. + let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR is not set")); + + let program_inputs = HDPDryRunInput { + params: vec![], + compiled_class: compiled_class.clone(), + }; + + // Load the Program + let program = Program::from_bytes( + &std::fs::read(out_dir.join("cairo").join("dry_run_compiled.json")).unwrap(), + Some(cairo_run_config.entrypoint), + ) + .unwrap(); + + // Init cairo runner + let mut cairo_runner = CairoRunner::new_v2( + &program, + cairo_run_config.layout, + None, + runner_mode.clone(), + cairo_run_config.trace_enabled, + ) + .unwrap(); + + // Init the Cairo VM + let end = cairo_runner.initialize(cairo_run_config.allow_missing_builtins.unwrap_or(false)).unwrap(); + + // Run the Cairo VM + let mut hint_processor = dry_hint_processor::CustomHintProcessor::new(program_inputs); + cairo_runner.run_until_pc(end, &mut hint_processor).unwrap(); + + let syscall_handler: SyscallHandler = cairo_runner + .exec_scopes + .get::(vars::scopes::SYSCALL_HANDLER) + .unwrap() + .syscall_handler + .try_read() + .unwrap() + .clone(); + + let mut proof_keys = ProofKeys::default(); + for key in syscall_handler.call_contract_handler.key_set { + match key { + evm::DryRunKey::Account(value) => { + proof_keys.account_keys.insert(value); + } + evm::DryRunKey::Header(value) => { + proof_keys.header_keys.insert(value); + } + evm::DryRunKey::Storage(value) => { + proof_keys.storage_keys.insert(value); + } + } + } + + let mut headers_with_mmr: HashSet = HashSet::default(); + + let mut headers_with_mmr_fut = futures::stream::iter(proof_keys.header_keys.iter().map(ProofKeys::fetch_header_proof).map(|f| f.boxed_local())) + .buffer_unordered(BUFFER_UNORDERED); + + while let Some(Ok(item)) = headers_with_mmr_fut.next().await { + headers_with_mmr.insert(item); + } + + let mut accounts: HashSet = HashSet::default(); + + let mut accounts_fut = futures::stream::iter( + proof_keys + .account_keys + .iter() + .map(ProofKeys::fetch_account_proof) + .map(|f| f.boxed_local()), + ) + .buffer_unordered(BUFFER_UNORDERED); + + while let Some(Ok((header_with_mmr, account))) = accounts_fut.next().await { + headers_with_mmr.insert(header_with_mmr); + accounts.insert(account); + } + + let mut storages: HashSet = HashSet::default(); + + let mut storages_fut = futures::stream::iter( + proof_keys + .storage_keys + .iter() + .map(ProofKeys::fetch_storage_proof) + .map(|f| f.boxed_local()), + ) + .buffer_unordered(BUFFER_UNORDERED); + + while let Some(Ok((header_with_mmr, account, storage))) = storages_fut.next().await { + headers_with_mmr.insert(header_with_mmr.clone()); + accounts.insert(account); + storages.insert(storage); + } + + let proofs = Proofs { + headers_with_mmr: headers_with_mmr.into_iter().collect(), + accounts: accounts.into_iter().collect(), + storages: storages.into_iter().collect(), + ..Default::default() + }; + + let program_inputs = HDPInput { + chain_proofs: vec![ChainProofs::EthereumSepolia(proofs)], + params: vec![], + compiled_class, + }; + + // Load the Program + let program = Program::from_bytes( + &std::fs::read(out_dir.join("cairo").join("sound_run_compiled.json")).unwrap(), + Some(cairo_run_config.entrypoint), + ) + .unwrap(); + + // Init cairo runner + let mut cairo_runner = CairoRunner::new_v2(&program, cairo_run_config.layout, None, runner_mode, cairo_run_config.trace_enabled).unwrap(); + + // Init the Cairo VM + let end = cairo_runner.initialize(cairo_run_config.allow_missing_builtins.unwrap_or(false)).unwrap(); + + // Run the Cairo VM + let mut hint_processor = sound_hint_processor::CustomHintProcessor::new(program_inputs); + cairo_runner.run_until_pc(end, &mut hint_processor).unwrap(); +} From 4cd197397e0a6def515f35919adb4fbf1dd173ff Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 27 Dec 2024 14:45:01 +0100 Subject: [PATCH 71/75] tests --- crates/types/src/cairo/evm/header.rs | 2 + crates/types/src/cairo/structs.rs | 4 +- tests/modules/header_modules/Scarb.toml | 21 - tests/modules/header_modules/src/lib.cairo | 610 ------------------ tests/modules/receipt_modules/Scarb.toml | 21 - tests/modules/receipt_modules/src/lib.cairo | 39 -- tests/modules/src/lib.cairo | 2 +- tests/modules/src/tests.cairo | 4 +- tests/modules/src/tests/account_modules.sh | 18 +- tests/modules/src/tests/header_modules.cairo | 277 ++++++++ tests/modules/src/tests/header_modules.rs | 90 +++ tests/modules/src/tests/header_modules.sh | 12 + tests/modules/src/tests/mod.rs | 2 + tests/modules/src/tests/storage_modules.cairo | 24 + tests/modules/src/tests/storage_modules.rs | 6 + tests/modules/src/tests/storage_modules.sh | 16 + tests/modules/transaction_modules/Scarb.toml | 21 - .../modules/transaction_modules/src/lib.cairo | 279 -------- 18 files changed, 444 insertions(+), 1004 deletions(-) delete mode 100644 tests/modules/header_modules/Scarb.toml delete mode 100644 tests/modules/header_modules/src/lib.cairo delete mode 100644 tests/modules/receipt_modules/Scarb.toml delete mode 100644 tests/modules/receipt_modules/src/lib.cairo create mode 100644 tests/modules/src/tests/header_modules.cairo create mode 100644 tests/modules/src/tests/header_modules.rs create mode 100644 tests/modules/src/tests/header_modules.sh create mode 100644 tests/modules/src/tests/storage_modules.cairo create mode 100644 tests/modules/src/tests/storage_modules.rs create mode 100644 tests/modules/src/tests/storage_modules.sh delete mode 100644 tests/modules/transaction_modules/Scarb.toml delete mode 100644 tests/modules/transaction_modules/src/lib.cairo diff --git a/crates/types/src/cairo/evm/header.rs b/crates/types/src/cairo/evm/header.rs index 43b533cc..0c52ceca 100644 --- a/crates/types/src/cairo/evm/header.rs +++ b/crates/types/src/cairo/evm/header.rs @@ -98,6 +98,7 @@ impl CairoHeader { } pub fn base_fee_per_gas(&self) -> Option { + println!("dupa"); self.0.base_fee_per_gas.map(|f| f.into()) } @@ -146,6 +147,7 @@ impl CairoHeader { FunctionId::Timestamp => self.timestamp(), FunctionId::MixHash => self.mix_hash(), FunctionId::Nonce => self.nonce(), + FunctionId::BaseFeePerGas => self.base_fee_per_gas().unwrap(), _ => Uint256::default(), } } diff --git a/crates/types/src/cairo/structs.rs b/crates/types/src/cairo/structs.rs index 6a790cc4..fdeea4bd 100644 --- a/crates/types/src/cairo/structs.rs +++ b/crates/types/src/cairo/structs.rs @@ -56,8 +56,8 @@ impl From
for Uint256 { fn from(value: Address) -> Self { let bytes: [u8; 20] = *value.0; Self { - low: Felt252::from_bytes_be_slice(&bytes[0..16]), - high: Felt252::from_bytes_be_slice(&bytes[16..20]), + low: Felt252::from_bytes_be_slice(&bytes[4..20]), + high: Felt252::from_bytes_be_slice(&bytes[0..4]), } } } diff --git a/tests/modules/header_modules/Scarb.toml b/tests/modules/header_modules/Scarb.toml deleted file mode 100644 index 0fcc158c..00000000 --- a/tests/modules/header_modules/Scarb.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "header_modules" -version = "0.1.0" -edition = "2023_11" - -# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html - -[dependencies] -starknet = "2.6.3" -hdp_cairo = { workspace = true } - -[dev-dependencies] -snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.24.0" } - -[[target.starknet-contract]] -sierra = true -casm = true -casm-add-pythonic-hints = true - -[scripts] -test = "snforge test" diff --git a/tests/modules/header_modules/src/lib.cairo b/tests/modules/header_modules/src/lib.cairo deleted file mode 100644 index 6edd2539..00000000 --- a/tests/modules/header_modules/src/lib.cairo +++ /dev/null @@ -1,610 +0,0 @@ -#[starknet::contract] -mod get_parent { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_parent(HeaderKey { chain_id: 11155111, block_number: block_number.into() }) - } -} - -#[starknet::contract] -mod get_uncle { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_uncle(HeaderKey { chain_id: 11155111, block_number: block_number.into() }) - } -} - -#[starknet::contract] -mod get_coinbase { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_coinbase( - HeaderKey { chain_id: 11155111, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod get_state_root { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_state_root( - HeaderKey { chain_id: 11155111, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod get_transaction_root { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_transaction_root( - HeaderKey { chain_id: 11155111, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod get_receipt_root { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_receipt_root( - HeaderKey { chain_id: 11155111, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod get_difficulty { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_difficulty( - HeaderKey { chain_id: 11155111, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod get_number { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_number(HeaderKey { chain_id: 11155111, block_number: block_number.into() }) - } -} - -#[starknet::contract] -mod get_gas_limit { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_gas_limit( - HeaderKey { chain_id: 11155111, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod get_gas_used { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_gas_used( - HeaderKey { chain_id: 11155111, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod get_mix_hash { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_mix_hash( - HeaderKey { chain_id: 11155111, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod get_nonce { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_nonce(HeaderKey { chain_id: 11155111, block_number: block_number.into() }) - } -} - -#[starknet::contract] -mod get_base_fee_per_gas { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> u256 { - hdp - .evm - .header_get_base_fee_per_gas( - HeaderKey { chain_id: 11155111, block_number: block_number.into() } - ) - } -} - - -#[starknet::contract] -mod starknet_get_block_number { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_block_number( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod starknet_get_state_root { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_state_root( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod starknet_get_sequencer_address { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_sequencer_address( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod starknet_get_block_timestamp { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_block_timestamp( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -// #[starknet::contract] -// mod starknet_get_transaction_count { -// use hdp_cairo::starknet::header::HeaderTrait; -// use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; -// use starknet::syscalls::call_contract_syscall; -// use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - -// #[storage] -// struct Storage {} - -// #[external(v0)] -// pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { -// hdp -// .starknet -// .header_get_transaction_count(HeaderKey { chain_id: 393402133025997798000961, -// block_number: block_number.into() }) -// } -// } - -#[starknet::contract] -mod starknet_get_transaction_commitment { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_transaction_commitment( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -// #[starknet::contract] -// mod starknet_get_event_count { -// use hdp_cairo::starknet::header::HeaderTrait; -// use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; -// use starknet::syscalls::call_contract_syscall; -// use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - -// #[storage] -// struct Storage {} - -// #[external(v0)] -// pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { -// hdp -// .starknet -// .header_get_event_count(HeaderKey { chain_id: 393402133025997798000961, block_number: -// block_number.into() }) -// } -// } - -#[starknet::contract] -mod starknet_get_event_commitment { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_event_commitment( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod starknet_get_parent_block_hash { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_parent_block_hash( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod starknet_get_state_diff_commitment { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_state_diff_commitment( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -// #[starknet::contract] -// mod starknet_get_state_diff_length { -// use hdp_cairo::starknet::header::HeaderTrait; -// use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; -// use starknet::syscalls::call_contract_syscall; -// use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - -// #[storage] -// struct Storage {} - -// #[external(v0)] -// pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { -// hdp -// .starknet -// .header_get_state_diff_length(HeaderKey { chain_id: 393402133025997798000961, -// block_number: block_number.into() }) -// } -// } - -#[starknet::contract] -mod starknet_get_l1_gas_price_in_wei { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_l1_gas_price_in_wei( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod starknet_get_l1_gas_price_in_fri { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_l1_gas_price_in_fri( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod starknet_get_l1_data_gas_price_in_wei { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_l1_data_gas_price_in_wei( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod starknet_get_l1_data_gas_price_in_fri { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_l1_data_gas_price_in_fri( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -#[starknet::contract] -mod starknet_get_receipts_commitment { - use hdp_cairo::starknet::header::HeaderTrait; - use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; - use starknet::syscalls::call_contract_syscall; - use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - hdp - .starknet - .header_get_receipts_commitment( - HeaderKey { chain_id: 393402133025997798000961, block_number: block_number.into() } - ) - } -} - -// #[starknet::contract] -// mod starknet_get_l1_data_mode { -// use hdp_cairo::starknet::header::HeaderTrait; -// use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; -// use starknet::syscalls::call_contract_syscall; -// use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - -// #[storage] -// struct Storage {} - -// #[external(v0)] -// pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { -// hdp -// .starknet -// .header_get_l1_data_mode(HeaderKey { chain_id: 393402133025997798000961, -// block_number: block_number.into() }) -// } -// } - -// #[starknet::contract] -// mod starknet_get_protocol_version { -// use hdp_cairo::starknet::header::HeaderTrait; -// use hdp_cairo::{HDP, starknet::header::{HeaderKey, HeaderImpl}}; -// use starknet::syscalls::call_contract_syscall; -// use starknet::{ContractAddress, SyscallResult, SyscallResultTrait}; - -// #[storage] -// struct Storage {} - -// #[external(v0)] -// pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { -// hdp -// .starknet -// .header_get_protocol_version(HeaderKey { chain_id: 393402133025997798000961, -// block_number: block_number.into() }) -// } -// } - -#[starknet::contract] -mod starknet_and_ethereum_get_storage { - use hdp_cairo::evm::header::HeaderTrait; - use hdp_cairo::{evm::header::{HeaderKey, HeaderImpl}}; - use hdp_cairo::starknet::storage::StorageTrait; - use hdp_cairo::{HDP, starknet::storage::{StorageKey, StorageImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32) -> felt252 { - let _ = hdp - .evm - .header_get_nonce(HeaderKey { chain_id: 11155111, block_number: 5382820.into() }); - - hdp - .starknet - .storage_get_slot( - StorageKey { - chain_id: 393402133025997798000961, - block_number: block_number.into(), - address: 0x6b8838af5d2a023b24ec8a69720b152d72ae2e4528139c32e05d8a3b9d7d4e7, - storage_slot: 0x308cfbb7d2d38db3a215f9728501ac69445a6afbee328cdeae4e23db54b850a - } - ) - } -} diff --git a/tests/modules/receipt_modules/Scarb.toml b/tests/modules/receipt_modules/Scarb.toml deleted file mode 100644 index 07c03d37..00000000 --- a/tests/modules/receipt_modules/Scarb.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "receipt_modules" -version = "0.1.0" -edition = "2023_11" - -# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html - -[dependencies] -starknet = "2.6.3" -hdp_cairo = { workspace = true } - -[dev-dependencies] -snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.24.0" } - -[[target.starknet-contract]] -sierra = true -casm = true -casm-add-pythonic-hints = true - -[scripts] -test = "snforge test" diff --git a/tests/modules/receipt_modules/src/lib.cairo b/tests/modules/receipt_modules/src/lib.cairo deleted file mode 100644 index 14a91bb2..00000000 --- a/tests/modules/receipt_modules/src/lib.cairo +++ /dev/null @@ -1,39 +0,0 @@ -#[starknet::contract] -mod get_status { - use hdp_cairo::evm::block_receipt::BlockReceiptTrait; - use hdp_cairo::{HDP, evm::block_receipt::{BlockReceiptKey, BlockReceiptImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_receipt_get_status( - BlockReceiptKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_cumulative_gas_used { - use hdp_cairo::evm::block_receipt::BlockReceiptTrait; - use hdp_cairo::{HDP, evm::block_receipt::{BlockReceiptKey, BlockReceiptImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_receipt_get_cumulative_gas_used( - BlockReceiptKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} diff --git a/tests/modules/src/lib.cairo b/tests/modules/src/lib.cairo index 3023529a..15ab5605 100644 --- a/tests/modules/src/lib.cairo +++ b/tests/modules/src/lib.cairo @@ -1 +1 @@ -pub mod tests; \ No newline at end of file +pub mod tests; diff --git a/tests/modules/src/tests.cairo b/tests/modules/src/tests.cairo index 2f8a5d5e..28e5e5ba 100644 --- a/tests/modules/src/tests.cairo +++ b/tests/modules/src/tests.cairo @@ -1 +1,3 @@ -pub mod account_modules; \ No newline at end of file +pub mod account_modules; +pub mod header_modules; +pub mod storage_modules; diff --git a/tests/modules/src/tests/account_modules.sh b/tests/modules/src/tests/account_modules.sh index dd6b9171..30942e90 100644 --- a/tests/modules/src/tests/account_modules.sh +++ b/tests/modules/src/tests/account_modules.sh @@ -2,9 +2,9 @@ # eth_getTransactionCount curl -X POST \ - --url $RPC_URL \ - --header 'Content-Type: application/json' \ - --data '{ + --url $RPC_URL \ + --header 'Content-Type: application/json' \ + --data '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": ["0xc6e2459991BfE27cca6d86722F35da23A1E4Cb97", "0x5B8D80"], @@ -13,9 +13,9 @@ curl -X POST \ # eth_getBalance curl -X POST \ - --url $RPC_URL \ - --header 'Content-Type: application/json' \ - --data '{ + --url $RPC_URL \ + --header 'Content-Type: application/json' \ + --data '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": ["0xc6e2459991BfE27cca6d86722F35da23A1E4Cb97", "0x5B8D80"], @@ -24,9 +24,9 @@ curl -X POST \ # eth_getProof curl -X POST \ - --url $RPC_URL \ - --header 'Content-Type: application/json' \ - --data '{ + --url $RPC_URL \ + --header 'Content-Type: application/json' \ + --data '{ "jsonrpc": "2.0", "method": "eth_getProof", "params": ["0xc6e2459991BfE27cca6d86722F35da23A1E4Cb97", [], "0x5B8D80"], diff --git a/tests/modules/src/tests/header_modules.cairo b/tests/modules/src/tests/header_modules.cairo new file mode 100644 index 00000000..d2ba9579 --- /dev/null +++ b/tests/modules/src/tests/header_modules.cairo @@ -0,0 +1,277 @@ +#[starknet::contract] +mod get_parent { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_parent( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { + low: 0x5cfce27b38bbb87ab1be0318c5a6e312, + high: 0x21e65fc6e962d4c8d0a0fb7a9e3d3f71 + } + ) + } +} + +#[starknet::contract] +mod get_uncle { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_uncle( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { + low: 0xd312451b948a7413f0a142fd40d49347, + high: 0x1dcc4de8dec75d7aab85b567b6ccd41a + } + ) + } +} + +#[starknet::contract] +mod get_coinbase { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_coinbase( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { low: 0x88762ad8061c04d08c37902abc8acb87, high: 0x9b7e3350 } + ) + } +} + +#[starknet::contract] +mod get_state_root { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_state_root( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { + low: 0x817271e87d530571fd93beefe826af78, + high: 0x2378fe6355340aec33ac0a401efcd9b4 + } + ) + } +} + +#[starknet::contract] +mod get_transaction_root { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_transaction_root( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { + low: 0xe24369f85f9dcf8a53c2b7f93cdd4309, + high: 0xfdfa9ffadb4cf0f880207c17a0aaf854 + } + ) + } +} + +#[starknet::contract] +mod get_receipt_root { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_receipt_root( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { + low: 0x38f73a78b0e0a6f606e6c07fc0954733, + high: 0xa1221588b2b63fdc80106f1e11ccbe96 + } + ) + } +} + +#[starknet::contract] +mod get_difficulty { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_difficulty( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { low: 0x0, high: 0x0 } + ) + } +} + +#[starknet::contract] +mod get_number { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_number( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { low: 0x5b8d80, high: 0x0 } + ) + } +} + +#[starknet::contract] +mod get_gas_limit { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_gas_limit( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { low: 0x1c9c380, high: 0x0 } + ) + } +} + +#[starknet::contract] +mod get_gas_used { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_gas_used( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { low: 0x106170a, high: 0x0 } + ) + } +} + +#[starknet::contract] +mod get_mix_hash { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_mix_hash( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { + low: 0x989953cfee51aaee0e838f7c56a8c959, + high: 0x525eb521f3b6c59b369135daae3b715a + } + ) + } +} + +#[starknet::contract] +mod get_nonce { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_nonce( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { low: 0x0, high: 0x0 } + ) + } +} + +#[starknet::contract] +mod get_base_fee_per_gas { + use hdp_cairo::evm::header::HeaderTrait; + use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .header_get_base_fee_per_gas( + HeaderKey { chain_id: 11155111, block_number: 6000000 } + ) == u256 { low: 0x79820dc63, high: 0x0 } + ) + } +} diff --git a/tests/modules/src/tests/header_modules.rs b/tests/modules/src/tests/header_modules.rs new file mode 100644 index 00000000..57e697b6 --- /dev/null +++ b/tests/modules/src/tests/header_modules.rs @@ -0,0 +1,90 @@ +use super::run; + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_parent() { + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_parent.compiled_contract_class.json")).unwrap()).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_uncle() { + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_uncle.compiled_contract_class.json")).unwrap()).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_coinbase() { + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_coinbase.compiled_contract_class.json")).unwrap()).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_state_root() { + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_get_state_root.compiled_contract_class.json" + )) + .unwrap()) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_transaction_root() { + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_get_transaction_root.compiled_contract_class.json" + )) + .unwrap()) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_receipt_root() { + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_get_receipt_root.compiled_contract_class.json" + )) + .unwrap()) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_difficulty() { + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_get_difficulty.compiled_contract_class.json" + )) + .unwrap()) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_number() { + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_number.compiled_contract_class.json")).unwrap()).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_gas_limit() { + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_get_gas_limit.compiled_contract_class.json" + )) + .unwrap()) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_gas_used() { + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_gas_used.compiled_contract_class.json")).unwrap()).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_mix_hash() { + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_mix_hash.compiled_contract_class.json")).unwrap()).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_nonce() { + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_nonce.compiled_contract_class.json")).unwrap()).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_base_fee_per_gas() { + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_get_base_fee_per_gas.compiled_contract_class.json" + )) + .unwrap()) + .await +} diff --git a/tests/modules/src/tests/header_modules.sh b/tests/modules/src/tests/header_modules.sh new file mode 100644 index 00000000..d81e37da --- /dev/null +++ b/tests/modules/src/tests/header_modules.sh @@ -0,0 +1,12 @@ +# Set the RPC environment variable + +# eth_getBlockByNumber +curl -X POST \ + --url $RPC_URL \ + --header 'Content-Type: application/json' \ + --data '{ + "jsonrpc": "2.0", + "method": "eth_getBlockByNumber", + "params": ["0x5B8D80", false], + "id": 1 + }' diff --git a/tests/modules/src/tests/mod.rs b/tests/modules/src/tests/mod.rs index e9a7b8d9..e9cd1bd8 100644 --- a/tests/modules/src/tests/mod.rs +++ b/tests/modules/src/tests/mod.rs @@ -15,6 +15,8 @@ use types::{ }; pub mod account_modules; +pub mod header_modules; +pub mod storage_modules; const BUFFER_UNORDERED: usize = 50; diff --git a/tests/modules/src/tests/storage_modules.cairo b/tests/modules/src/tests/storage_modules.cairo new file mode 100644 index 00000000..b669e567 --- /dev/null +++ b/tests/modules/src/tests/storage_modules.cairo @@ -0,0 +1,24 @@ +#[starknet::contract] +mod get_slot { + use hdp_cairo::evm::storage::StorageTrait; + use hdp_cairo::{HDP, evm::storage::{StorageKey, StorageImpl}}; + + #[storage] + struct Storage {} + + #[external(v0)] + pub fn main(ref self: ContractState, hdp: HDP) { + assert!( + hdp + .evm + .storage_get_slot( + StorageKey { + chain_id: 11155111, + block_number: 6000000, + address: 0x75cec1db9dceb703200eaa6595f66885c962b920, + storage_slot: 0x1 + } + ) == u256 { low: 0x12309ce54000, high: 0x0 } + ) + } +} diff --git a/tests/modules/src/tests/storage_modules.rs b/tests/modules/src/tests/storage_modules.rs new file mode 100644 index 00000000..1fe38f8b --- /dev/null +++ b/tests/modules/src/tests/storage_modules.rs @@ -0,0 +1,6 @@ +use super::run; + +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn test_modules_get_slot() { + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_slot.compiled_contract_class.json")).unwrap()).await +} diff --git a/tests/modules/src/tests/storage_modules.sh b/tests/modules/src/tests/storage_modules.sh new file mode 100644 index 00000000..928b4ef4 --- /dev/null +++ b/tests/modules/src/tests/storage_modules.sh @@ -0,0 +1,16 @@ +# Set the RPC environment variable + +# eth_getStorageAt +curl -X POST \ + --url $RPC_URL \ + --header 'Content-Type: application/json' \ + --data '{ + "jsonrpc": "2.0", + "method": "eth_getStorageAt", + "params": [ + "0x75cec1db9dceb703200eaa6595f66885c962b920", + "0x1", + "0x5B8D80" + ], + "id": 1 + }' diff --git a/tests/modules/transaction_modules/Scarb.toml b/tests/modules/transaction_modules/Scarb.toml deleted file mode 100644 index 83e9d42f..00000000 --- a/tests/modules/transaction_modules/Scarb.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "transaction_modules" -version = "0.1.0" -edition = "2023_11" - -# See more keys and their definitions at https://docs.swmansion.com/scarb/docs/reference/manifest.html - -[dependencies] -starknet = "2.6.3" -hdp_cairo = { workspace = true } - -[dev-dependencies] -snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry", tag = "v0.24.0" } - -[[target.starknet-contract]] -sierra = true -casm = true -casm-add-pythonic-hints = true - -[scripts] -test = "snforge test" diff --git a/tests/modules/transaction_modules/src/lib.cairo b/tests/modules/transaction_modules/src/lib.cairo deleted file mode 100644 index 4fadbc2f..00000000 --- a/tests/modules/transaction_modules/src/lib.cairo +++ /dev/null @@ -1,279 +0,0 @@ -#[starknet::contract] -mod get_nonce { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_nonce( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_gas_price { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_gas_price( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_gas_limit { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_gas_limit( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_receiver { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_receiver( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_value { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_value( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_v { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_v( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_r { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_r( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_s { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_s( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_chain_id { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_chain_id( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_max_fee_per_gas { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_max_fee_per_gas( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_max_priority_fee_per_gas { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_max_priority_fee_per_gas( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_max_fee_per_blob_gas { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_max_fee_per_blob_gas( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_tx_type { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_tx_type( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} - -#[starknet::contract] -mod get_sender { - use hdp_cairo::evm::block_tx::BlockTxTrait; - use hdp_cairo::{HDP, evm::block_tx::{BlockTxKey, BlockTxImpl}}; - - #[storage] - struct Storage {} - - #[external(v0)] - pub fn main(ref self: ContractState, hdp: HDP, block_number: u32, index: u32) -> u256 { - hdp - .evm - .block_tx_get_sender( - BlockTxKey { - chain_id: 11155111, block_number: block_number.into(), index: index.into() - } - ) - } -} From 58598f29ffa1144c451ddbb3e73f3d6bc0c4b1a5 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 27 Dec 2024 15:11:24 +0100 Subject: [PATCH 72/75] header and storage testing --- tests/modules/src/tests/account_modules.cairo | 8 +++--- tests/modules/src/tests/account_modules.rs | 8 +++--- tests/modules/src/tests/header_modules.cairo | 26 +++++++++---------- tests/modules/src/tests/header_modules.rs | 26 +++++++++---------- tests/modules/src/tests/storage_modules.cairo | 2 +- tests/modules/src/tests/storage_modules.rs | 2 +- 6 files changed, 36 insertions(+), 36 deletions(-) diff --git a/tests/modules/src/tests/account_modules.cairo b/tests/modules/src/tests/account_modules.cairo index 504b159d..053844e5 100644 --- a/tests/modules/src/tests/account_modules.cairo +++ b/tests/modules/src/tests/account_modules.cairo @@ -1,5 +1,5 @@ #[starknet::contract] -mod get_nonce { +mod account_get_nonce { use hdp_cairo::evm::account::AccountTrait; use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; @@ -23,7 +23,7 @@ mod get_nonce { } #[starknet::contract] -mod get_balance { +mod account_get_balance { use hdp_cairo::evm::account::AccountTrait; use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; @@ -47,7 +47,7 @@ mod get_balance { } #[starknet::contract] -mod get_state_root { +mod account_get_state_root { use hdp_cairo::evm::account::AccountTrait; use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; @@ -74,7 +74,7 @@ mod get_state_root { } #[starknet::contract] -mod get_code_hash { +mod account_get_code_hash { use hdp_cairo::evm::account::AccountTrait; use hdp_cairo::{HDP, evm::account::{AccountKey, AccountImpl}}; diff --git a/tests/modules/src/tests/account_modules.rs b/tests/modules/src/tests/account_modules.rs index 7900be31..379506a6 100644 --- a/tests/modules/src/tests/account_modules.rs +++ b/tests/modules/src/tests/account_modules.rs @@ -2,13 +2,13 @@ use super::run; #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_balance() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_balance.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_account_get_balance.compiled_contract_class.json")).unwrap()).await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_code_hash() { run(serde_json::from_slice(include_bytes!( - "../../../../target/dev/modules_get_code_hash.compiled_contract_class.json" + "../../../../target/dev/modules_account_get_code_hash.compiled_contract_class.json" )) .unwrap()) .await @@ -16,13 +16,13 @@ async fn test_modules_get_code_hash() { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_nonce() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_nonce.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_account_get_nonce.compiled_contract_class.json")).unwrap()).await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_state_root() { run(serde_json::from_slice(include_bytes!( - "../../../../target/dev/modules_get_state_root.compiled_contract_class.json" + "../../../../target/dev/modules_account_get_state_root.compiled_contract_class.json" )) .unwrap()) .await diff --git a/tests/modules/src/tests/header_modules.cairo b/tests/modules/src/tests/header_modules.cairo index d2ba9579..408706e8 100644 --- a/tests/modules/src/tests/header_modules.cairo +++ b/tests/modules/src/tests/header_modules.cairo @@ -1,5 +1,5 @@ #[starknet::contract] -mod get_parent { +mod header_get_parent { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -22,7 +22,7 @@ mod get_parent { } #[starknet::contract] -mod get_uncle { +mod header_get_uncle { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -45,7 +45,7 @@ mod get_uncle { } #[starknet::contract] -mod get_coinbase { +mod header_get_coinbase { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -65,7 +65,7 @@ mod get_coinbase { } #[starknet::contract] -mod get_state_root { +mod header_get_state_root { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -88,7 +88,7 @@ mod get_state_root { } #[starknet::contract] -mod get_transaction_root { +mod header_get_transaction_root { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -111,7 +111,7 @@ mod get_transaction_root { } #[starknet::contract] -mod get_receipt_root { +mod header_get_receipt_root { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -134,7 +134,7 @@ mod get_receipt_root { } #[starknet::contract] -mod get_difficulty { +mod header_get_difficulty { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -154,7 +154,7 @@ mod get_difficulty { } #[starknet::contract] -mod get_number { +mod header_get_number { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -174,7 +174,7 @@ mod get_number { } #[starknet::contract] -mod get_gas_limit { +mod header_get_gas_limit { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -194,7 +194,7 @@ mod get_gas_limit { } #[starknet::contract] -mod get_gas_used { +mod header_get_gas_used { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -214,7 +214,7 @@ mod get_gas_used { } #[starknet::contract] -mod get_mix_hash { +mod header_get_mix_hash { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -237,7 +237,7 @@ mod get_mix_hash { } #[starknet::contract] -mod get_nonce { +mod header_get_nonce { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; @@ -257,7 +257,7 @@ mod get_nonce { } #[starknet::contract] -mod get_base_fee_per_gas { +mod header_get_base_fee_per_gas { use hdp_cairo::evm::header::HeaderTrait; use hdp_cairo::{HDP, evm::header::{HeaderKey, HeaderImpl}}; diff --git a/tests/modules/src/tests/header_modules.rs b/tests/modules/src/tests/header_modules.rs index 57e697b6..3bbec09a 100644 --- a/tests/modules/src/tests/header_modules.rs +++ b/tests/modules/src/tests/header_modules.rs @@ -2,23 +2,23 @@ use super::run; #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_parent() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_parent.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_parent.compiled_contract_class.json")).unwrap()).await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_uncle() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_uncle.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_uncle.compiled_contract_class.json")).unwrap()).await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_coinbase() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_coinbase.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_coinbase.compiled_contract_class.json")).unwrap()).await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_state_root() { run(serde_json::from_slice(include_bytes!( - "../../../../target/dev/modules_get_state_root.compiled_contract_class.json" + "../../../../target/dev/modules_header_get_state_root.compiled_contract_class.json" )) .unwrap()) .await @@ -27,7 +27,7 @@ async fn test_modules_get_state_root() { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_transaction_root() { run(serde_json::from_slice(include_bytes!( - "../../../../target/dev/modules_get_transaction_root.compiled_contract_class.json" + "../../../../target/dev/modules_header_get_transaction_root.compiled_contract_class.json" )) .unwrap()) .await @@ -36,7 +36,7 @@ async fn test_modules_get_transaction_root() { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_receipt_root() { run(serde_json::from_slice(include_bytes!( - "../../../../target/dev/modules_get_receipt_root.compiled_contract_class.json" + "../../../../target/dev/modules_header_get_receipt_root.compiled_contract_class.json" )) .unwrap()) .await @@ -45,7 +45,7 @@ async fn test_modules_get_receipt_root() { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_difficulty() { run(serde_json::from_slice(include_bytes!( - "../../../../target/dev/modules_get_difficulty.compiled_contract_class.json" + "../../../../target/dev/modules_header_get_difficulty.compiled_contract_class.json" )) .unwrap()) .await @@ -53,13 +53,13 @@ async fn test_modules_get_difficulty() { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_number() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_number.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_number.compiled_contract_class.json")).unwrap()).await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_gas_limit() { run(serde_json::from_slice(include_bytes!( - "../../../../target/dev/modules_get_gas_limit.compiled_contract_class.json" + "../../../../target/dev/modules_header_get_gas_limit.compiled_contract_class.json" )) .unwrap()) .await @@ -67,23 +67,23 @@ async fn test_modules_get_gas_limit() { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_gas_used() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_gas_used.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_gas_used.compiled_contract_class.json")).unwrap()).await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_mix_hash() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_mix_hash.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_mix_hash.compiled_contract_class.json")).unwrap()).await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_nonce() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_nonce.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_nonce.compiled_contract_class.json")).unwrap()).await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_base_fee_per_gas() { run(serde_json::from_slice(include_bytes!( - "../../../../target/dev/modules_get_base_fee_per_gas.compiled_contract_class.json" + "../../../../target/dev/modules_header_get_base_fee_per_gas.compiled_contract_class.json" )) .unwrap()) .await diff --git a/tests/modules/src/tests/storage_modules.cairo b/tests/modules/src/tests/storage_modules.cairo index b669e567..f6056389 100644 --- a/tests/modules/src/tests/storage_modules.cairo +++ b/tests/modules/src/tests/storage_modules.cairo @@ -1,5 +1,5 @@ #[starknet::contract] -mod get_slot { +mod storage_get_slot { use hdp_cairo::evm::storage::StorageTrait; use hdp_cairo::{HDP, evm::storage::{StorageKey, StorageImpl}}; diff --git a/tests/modules/src/tests/storage_modules.rs b/tests/modules/src/tests/storage_modules.rs index 1fe38f8b..a94f7ee3 100644 --- a/tests/modules/src/tests/storage_modules.rs +++ b/tests/modules/src/tests/storage_modules.rs @@ -2,5 +2,5 @@ use super::run; #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_slot() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_get_slot.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_storage_get_slot.compiled_contract_class.json")).unwrap()).await } From e253a2a963b5b04756ab73cf26e9db1306f25014 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 27 Dec 2024 15:12:00 +0100 Subject: [PATCH 73/75] fmt --- tests/modules/src/tests/account_modules.rs | 12 +++++-- tests/modules/src/tests/header_modules.rs | 42 ++++++++++++++++++---- tests/modules/src/tests/storage_modules.rs | 6 +++- 3 files changed, 50 insertions(+), 10 deletions(-) diff --git a/tests/modules/src/tests/account_modules.rs b/tests/modules/src/tests/account_modules.rs index 379506a6..fe69727f 100644 --- a/tests/modules/src/tests/account_modules.rs +++ b/tests/modules/src/tests/account_modules.rs @@ -2,7 +2,11 @@ use super::run; #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_balance() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_account_get_balance.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_account_get_balance.compiled_contract_class.json" + )) + .unwrap()) + .await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] @@ -16,7 +20,11 @@ async fn test_modules_get_code_hash() { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_nonce() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_account_get_nonce.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_account_get_nonce.compiled_contract_class.json" + )) + .unwrap()) + .await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] diff --git a/tests/modules/src/tests/header_modules.rs b/tests/modules/src/tests/header_modules.rs index 3bbec09a..d40d4c57 100644 --- a/tests/modules/src/tests/header_modules.rs +++ b/tests/modules/src/tests/header_modules.rs @@ -2,17 +2,29 @@ use super::run; #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_parent() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_parent.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_header_get_parent.compiled_contract_class.json" + )) + .unwrap()) + .await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_uncle() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_uncle.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_header_get_uncle.compiled_contract_class.json" + )) + .unwrap()) + .await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_coinbase() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_coinbase.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_header_get_coinbase.compiled_contract_class.json" + )) + .unwrap()) + .await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] @@ -53,7 +65,11 @@ async fn test_modules_get_difficulty() { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_number() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_number.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_header_get_number.compiled_contract_class.json" + )) + .unwrap()) + .await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] @@ -67,17 +83,29 @@ async fn test_modules_get_gas_limit() { #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_gas_used() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_gas_used.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_header_get_gas_used.compiled_contract_class.json" + )) + .unwrap()) + .await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_mix_hash() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_mix_hash.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_header_get_mix_hash.compiled_contract_class.json" + )) + .unwrap()) + .await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_nonce() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_header_get_nonce.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_header_get_nonce.compiled_contract_class.json" + )) + .unwrap()) + .await } #[tokio::test(flavor = "multi_thread", worker_threads = 1)] diff --git a/tests/modules/src/tests/storage_modules.rs b/tests/modules/src/tests/storage_modules.rs index a94f7ee3..fece5002 100644 --- a/tests/modules/src/tests/storage_modules.rs +++ b/tests/modules/src/tests/storage_modules.rs @@ -2,5 +2,9 @@ use super::run; #[tokio::test(flavor = "multi_thread", worker_threads = 1)] async fn test_modules_get_slot() { - run(serde_json::from_slice(include_bytes!("../../../../target/dev/modules_storage_get_slot.compiled_contract_class.json")).unwrap()).await + run(serde_json::from_slice(include_bytes!( + "../../../../target/dev/modules_storage_get_slot.compiled_contract_class.json" + )) + .unwrap()) + .await } From 9e848326766d35ec1617a57b34b3e238e0caa6a3 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 27 Dec 2024 15:21:01 +0100 Subject: [PATCH 74/75] README --- README.md | 61 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 34 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index 1231fc8a..06f9c312 100644 --- a/README.md +++ b/README.md @@ -20,48 +20,55 @@ source venv/bin/activate Before running the program, prepare the input data. The inputs are provided via the `hdp_input.json` file located in the root directory of the HDP project. -To run the program, execute following steps: +### Steps to Execute: -Simulate Cairo1 module and collect info about proofs to fetch -```bash -cargo run --release --bin dry_run -- --program_input examples/hdp_input.json --program_output hdp_keys.json --layout starknet_with_keccak -``` +1. **Simulate Cairo1 Module and Collect Proofs Information:** + ```bash + cargo run --release --bin dry_run -- --program_input examples/hdp_input.json --program_output hdp_keys.json --layout starknet_with_keccak + ``` -Fetch the on-chain proofs needed for the HDP run: -```bash -cargo run --release --bin fetcher -- hdp_keys.json --program_output hdp_proofs.json -``` +2. **Fetch On-Chain Proofs Needed for the HDP Run:** + ```bash + cargo run --release --bin fetcher -- hdp_keys.json --program_output hdp_proofs.json + ``` -Run Cairo1 module with verified onchain data -```bash -cargo run --release --bin sound_run -- --program_input examples/hdp_input.json --program_proofs hdp_proofs.json --program_output hdp_output.json --layout starknet_with_keccak -``` +3. **Run Cairo1 Module with Verified On-Chain Data:** + ```bash + cargo run --release --bin sound_run -- --program_input examples/hdp_input.json --program_proofs hdp_proofs.json --program_output hdp_output.json --layout starknet_with_keccak + ``` The program will output the results root and tasks root. These roots can be used to extract the results from the on-chain contract. ## How It Works -HDP Cairo is the repository containing the logic for verifying on-chain state via storage proofs, and then making that state available to custom Cairo1 contract modules. To enable this functionality, a custom syscall was designed, enabling dynamic access to the verified state. The syscalls are defined in `cairo1` where we have some examples. +HDP Cairo is the repository containing the logic for verifying on-chain state via storage proofs and making that state available to custom Cairo1 contract modules. To enable this functionality, a custom syscall was designed, enabling dynamic access to the verified state. The syscalls are defined in `cairo1`, where examples are provided. ### Architecture -The overall program is split into two main parts: - -![Architecture](.github/architecture.png) - +The overall program is split into two main parts: -### 1. Storage Proof Verification -In the first stage, we verify the storage proofs found in the `hdp_input.json` file. This file contains all the storage proof for the state required by the contracts execution. This file is generated in the Dry Run stage, where we mock the execution and extract the state that was accessed by the contract. This enables the dynamic access of state from the contract, while ensuring everything can be proven in a sound way. Once this stage is complete, all of the verified state is stored in the memorizers, allowing it to be queried via syscall. +1. **Storage Proof Verification** + - In the first stage, we verify the storage proofs found in the `hdp_input.json` file. This file contains all the storage proofs for the state required by the contract's execution. + - The `hdp_input.json` file is generated during the Dry Run stage, where execution is mocked, and the state accessed by the contract is extracted. + - Once this stage is complete, all the verified state is stored in memorizers, enabling it to be queried via syscall. -### 2. Bootloading -In this stage, we bootload the cairo1 contract. The contracts bytecode is read from the `hdp_input.json` file and now executed in the HDP bootloader. The bootloader now processes the bytecode, and invokes the contained syscalls. These syscalls are then proccessed, fetching and decoding the requested state from the memorizers and loading it into the contracts memory. This enables the seamless access of verified on-chain state in contracts. +2. **Bootloading** + - In this stage, we bootload the Cairo1 contract. + - The contract's bytecode is read from the `hdp_input.json` file and executed in the HDP bootloader. + - The bootloader processes the bytecode and invokes the contained syscalls, which fetch and decode the requested state from the memorizers, loading it into the contract's memory. + - This setup allows seamless access to verified on-chain state within contracts. ## Testing -Some tests require Ethereum Mainnet RPC calls. Ensure an environment variable named `RPC_URL_MAINNET` is set. +Some tests require Ethereum Mainnet RPC calls. Ensure an environment variable named `RPC` is set. -To run the tests (from the virtual environment), execute: +1. **Build Cairo1 Modules:** + ```bash + scarb build + ``` + +2. **Run Tests with [nextest](https://nexte.st/):** + ```bash + cargo nextest run + ``` -```bash -make test-full -``` From 5d92d4465e693c17d82768e300ae3fafbbd5c51f Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 27 Dec 2024 15:21:46 +0100 Subject: [PATCH 75/75] README fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 06f9c312..a222d1a3 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ The overall program is split into two main parts: ## Testing -Some tests require Ethereum Mainnet RPC calls. Ensure an environment variable named `RPC` is set. +Some tests require Ethereum Sepolia RPC calls. Ensure an environment variable named `RPC` is set. 1. **Build Cairo1 Modules:** ```bash