Skip to content

Commit

Permalink
Add a global class cache to VM
Browse files Browse the repository at this point in the history
  • Loading branch information
omerfirmak committed Nov 2, 2023
1 parent 9737f21 commit fd1e70e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
2 changes: 2 additions & 0 deletions vm/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ cairo-lang-casm = "2.1.0"
cairo-lang-starknet = "2.1.0"
indexmap = "1.9.2"
starknet = { rev = "starknet-core/v0.4.0", git = "https://github.com/xJonathanLEI/starknet-rs" }
cached = "0.44.0"
once_cell = "1.18.0"

[lib]
crate-type = ["staticlib"]
18 changes: 16 additions & 2 deletions vm/rust/src/juno_state_reader.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{
ffi::{c_char, c_uchar, c_void, CStr},
slice,
slice, sync::Mutex,
};

use blockifier::{
Expand All @@ -10,9 +10,10 @@ use blockifier::{
use starknet_api::core::{ClassHash, CompiledClassHash, ContractAddress, Nonce};
use starknet_api::hash::StarkFelt;
use starknet_api::state::StorageKey;

use cached::{SizedCache, Cached};
use blockifier::execution::contract_class::ContractClass;
use blockifier::state::errors::StateError;
use once_cell::sync::Lazy;

extern "C" {
fn JunoFree(ptr: *const c_void);
Expand All @@ -34,6 +35,11 @@ extern "C" {
-> *const c_char;
}

static CLASS_CACHE: Lazy<Mutex<SizedCache<ClassHash, ContractClass>>> = Lazy::new(|| {
Mutex::new(SizedCache::with_size(128))
});


pub struct JunoStateReader {
pub handle: usize, // uintptr_t equivalent
}
Expand Down Expand Up @@ -108,13 +114,21 @@ impl StateReader for JunoStateReader {
&mut self,
class_hash: &ClassHash,
) -> StateResult<ContractClass> {
if let Some(cached_class) = CLASS_CACHE.lock().unwrap().cache_get(class_hash) {
return Ok(cached_class.clone())
}

let class_hash_bytes = felt_to_byte_array(&class_hash.0);
let ptr = unsafe { JunoStateGetCompiledClass(self.handle, class_hash_bytes.as_ptr()) };
if ptr.is_null() {
Err(StateError::UndeclaredClassHash(*class_hash))
} else {
let json_str = unsafe { CStr::from_ptr(ptr) }.to_str().unwrap();
let contract_class = contract_class_from_json_str(json_str);
if let Ok(class) = &contract_class {
CLASS_CACHE.lock().unwrap().cache_set(*class_hash, class.clone());
}

unsafe { JunoFree(ptr as *const c_void) };

contract_class.map_err(|_| {
Expand Down

0 comments on commit fd1e70e

Please sign in to comment.