Skip to content

Commit

Permalink
key set
Browse files Browse the repository at this point in the history
  • Loading branch information
Okm165 committed Dec 11, 2024
1 parent 9cc0db7 commit f7102e3
Show file tree
Hide file tree
Showing 9 changed files with 125 additions and 140 deletions.
3 changes: 1 addition & 2 deletions cairo_vm_hints/src/hint_processor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,7 @@ impl HintProcessorLogic for CustomHintProcessor {
if let Some(hint) = hint_data.downcast_ref::<Hint>() {
if let Hint::Starknet(StarknetHint::SystemCall { system }) = hint {
let syscall_ptr = get_ptr_from_res_operand(vm, system)?;
let syscall_handler = exec_scopes.get::<SyscallHandlerWrapper>(vars::scopes::SYSCALL_HANDLER)?;

let syscall_handler = exec_scopes.get_mut_ref::<SyscallHandlerWrapper>(vars::scopes::SYSCALL_HANDLER)?;
return syscall_handler.execute_syscall(vm, syscall_ptr).map(|_| HintExtension::default());
} else {
return self
Expand Down
80 changes: 0 additions & 80 deletions cairo_vm_hints/src/syscall_handler/call_contract.rs

This file was deleted.

3 changes: 2 additions & 1 deletion cairo_vm_hints/src/syscall_handler/evm/dryrun/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 3 additions & 2 deletions cairo_vm_hints/src/syscall_handler/evm/dryrun/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -51,7 +52,7 @@ impl CallHandler for HeaderCallHandler {
}
}

#[derive(Debug)]
#[derive(Debug, Serialize, Deserialize)]
pub struct CairoKey {
chain_id: Felt252,
block_number: Felt252,
Expand All @@ -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,
Expand Down
98 changes: 96 additions & 2 deletions cairo_vm_hints/src/syscall_handler/evm/dryrun/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -18,6 +29,79 @@ pub enum CallHandlerId {
Receipt = 4,
}

#[derive(Debug, Default)]
pub struct CallContractHandler {
key_set: HashSet<DryRunKey>,
}

impl SyscallHandler for CallContractHandler {
type Request = CallContractRequest;
type Response = CallContractResponse;

fn read_request(&mut self, vm: &VirtualMachine, ptr: &mut Relocatable) -> SyscallResult<Self::Request> {
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<Self::Response> {
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 += <header::HeaderCallHandler as CallHandler>::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 += <account::AccountCallHandler as CallHandler>::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 += <storage::StorageCallHandler as CallHandler>::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<Felt252> for CallHandlerId {
type Error = SyscallExecutionError;
fn try_from(value: Felt252) -> Result<Self, Self::Error> {
Expand All @@ -31,3 +115,13 @@ impl TryFrom<Felt252> 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<DryRunKey>);
3 changes: 2 additions & 1 deletion cairo_vm_hints/src/syscall_handler/evm/dryrun/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
19 changes: 6 additions & 13 deletions cairo_vm_hints/src/syscall_handler/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
pub mod call_contract;
pub mod evm;
pub mod starknet;
pub mod traits;
Expand All @@ -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<Relocatable>,
call_contract_handler: evm::dryrun::CallContractHandler,
}

/// SyscallHandler is wrapped in Rc<RefCell<_>> 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<RwLock<HDPSyscallHandler>>,
}

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) {
Expand All @@ -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
Expand All @@ -58,7 +51,7 @@ impl SyscallHandlerWrapper {
assert_eq!(*ptr, syscall_ptr);

match SyscallSelector::try_from(felt_from_ptr(vm, ptr)?)? {
SyscallSelector::CallContract => run_handler::<CallContractHandler>(ptr, vm),
SyscallSelector::CallContract => run_handler(&mut syscall_handler.call_contract_handler, ptr, vm),
}?;

syscall_handler.syscall_ptr = Some(*ptr);
Expand Down
10 changes: 9 additions & 1 deletion cairo_vm_hints/src/syscall_handler/traits.rs
Original file line number Diff line number Diff line change
@@ -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<Self::Request>;
fn execute(&mut self, request: Self::Request, vm: &mut VirtualMachine) -> SyscallResult<Self::Response>;
fn write_response(&mut self, response: Self::Response, vm: &mut VirtualMachine, ptr: &mut Relocatable) -> WriteResponseResult;
}

pub trait CallHandler {
type Key;
type Id;
Expand Down
Loading

0 comments on commit f7102e3

Please sign in to comment.