From 1ec36b89b97b643c7ce33d63ae59c9237cce0a47 Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Mon, 16 Dec 2024 23:52:08 +0100 Subject: [PATCH] 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";