Skip to content

Commit

Permalink
flat input test
Browse files Browse the repository at this point in the history
  • Loading branch information
drspacemn committed Oct 11, 2023
1 parent af805a7 commit 0855921
Show file tree
Hide file tree
Showing 7 changed files with 143 additions and 43 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ hex = "0.4.3"
indexmap = "1.9.2"
log = "0.4.19"
num-bigint = "0.4.4"
num-integer = "0.1.45"
num-traits = "0.2.16"
reqwest = { version = "0.11.18", features = ["blocking", "json"] }
serde = { version = "1.0.188", features = ["derive"] }
Expand Down
3 changes: 3 additions & 0 deletions src/hints/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use cairo_vm::types::exec_scope::ExecutionScopes;
use cairo_vm::vm::{errors::hint_errors::HintError, vm_core::VirtualMachine};
use std::rc::Rc;

use crate::io::StarknetOsInput;

use cairo_vm::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::{
BuiltinHintProcessor, HintFunc,
};
Expand Down Expand Up @@ -43,6 +45,7 @@ pub fn starknet_os_input(
println!("Running hint {:?} {:?}", ids_data, _exec_scopes);

// Deserialize the program_input
let _os_input = StarknetOsInput::load("tests/common/os_input.json");

let initial_carried_outputs_ptr =
get_ptr_from_var_name("initial_carried_outputs", vm, ids_data, ap_tracking)?;
Expand Down
133 changes: 124 additions & 9 deletions src/io.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,45 @@
use std::collections::HashMap;

use cairo_felt::Felt252;
use serde::{Deserialize, Serialize};

use cairo_vm::serde::deserialize_program::deserialize_felt_hex;
use num_traits::Num;
use serde::Deserializer;
use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContractClass;
use starknet_api::transaction::{MessageToL1, MessageToL2};
use std::fs;
use std::path;

use crate::{
business_logic::transaction::types::InternalTransaction, config::StarknetGeneralConfig,
state::CommitmentInfo, state::ContractState,
};
use crate::config::StarknetGeneralConfig;

type CommitmentFacts = HashMap<Felt252, Vec<Felt252>>;

#[derive(Debug, Serialize, Deserialize)]
#[allow(unused)]
struct StarknetOsInput {
pub struct StarknetOsInput {
contract_state_commitment_info: CommitmentInfo,
contract_class_commitment_info: CommitmentInfo,
deprecated_compiled_classes: HashMap<Felt252, Felt252>, // TODO: Add contract_class module
compiled_classes: HashMap<Felt252, Felt252>, // TODO: Add contract_class module
contracts: HashMap<Felt252, ContractState>,
#[serde(deserialize_with = "parse_deprecated_classes")]
deprecated_compiled_classes: HashMap<Felt252, DeprecatedContractClass>, // TODO: Add contract_class module
#[serde(deserialize_with = "deserialize_felt_map")]
compiled_classes: HashMap<Felt252, Felt252>, // TODO: Add contract_class module
// contracts: HashMap<Felt252, ContractState>,
#[serde(deserialize_with = "deserialize_felt_map")]
class_hash_to_compiled_class_hash: HashMap<Felt252, Felt252>,
general_config: StarknetGeneralConfig,
transactions: Vec<InternalTransaction>,
// transactions: Vec<InternalTransaction>,
#[serde(deserialize_with = "deserialize_felt_hex")]
block_hash: Felt252,
}

impl StarknetOsInput {
pub fn load(path: &str) -> Self {
let raw_input = fs::read_to_string(path::PathBuf::from(path)).unwrap();
serde_json::from_str(&raw_input).unwrap()
}
}

pub struct StarknetOsOutput {
/// The state commitment before this block.
pub prev_state_root: Felt252,
Expand All @@ -38,3 +56,100 @@ pub struct StarknetOsOutput {
/// List of messages from L1 handled in this block
pub messages_to_l2: Vec<MessageToL2>,
}

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CommitmentInfo {
#[serde(deserialize_with = "deserialize_felt_hex")]
pub previous_root: Felt252,
#[serde(deserialize_with = "deserialize_felt_hex")]
pub updated_root: Felt252,
pub(crate) tree_height: usize,
#[serde(deserialize_with = "deserialize_felt_facts")]
pub(crate) commitment_facts: CommitmentFacts,
}

pub fn deserialize_felt_facts<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<CommitmentFacts, D::Error> {
let mut ret_map = CommitmentFacts::new();
let buf_map: HashMap<String, Vec<String>> = HashMap::deserialize(deserializer)?;
for (fact, commitments) in buf_map.into_iter() {
let fact = fact.strip_prefix("0x").unwrap();
ret_map.insert(
Felt252::from_str_radix(fact, 16).unwrap(),
commitments
.into_iter()
.map(|commit| {
Felt252::from_str_radix(commit.strip_prefix("0x").unwrap(), 16).unwrap()
})
.collect(),
);
}

Ok(ret_map)
}

pub fn parse_deprecated_classes<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<HashMap<Felt252, DeprecatedContractClass>, D::Error> {
let mut ret_map: HashMap<Felt252, DeprecatedContractClass> = HashMap::new();
let buf: HashMap<String, String> = HashMap::deserialize(deserializer)?;
for (k, v) in buf.into_iter() {
let class_hash = Felt252::from_str_radix(k.strip_prefix("0x").unwrap(), 16).unwrap();
let raw_class = fs::read_to_string(path::PathBuf::from(v)).unwrap();
let class = serde_json::from_str(&raw_class).unwrap();
ret_map.insert(class_hash, class);
}

Ok(ret_map)
}

pub fn deserialize_felt_map<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<HashMap<Felt252, Felt252>, D::Error> {
let mut ret_map = HashMap::new();
let buf_map: HashMap<String, String> = HashMap::deserialize(deserializer)?;
for (k, v) in buf_map.into_iter() {
let k = k.strip_prefix("0x").unwrap();
let v = v.strip_prefix("0x").unwrap();
ret_map.insert(
Felt252::from_str_radix(k, 16).unwrap(),
Felt252::from_str_radix(v, 16).unwrap(),
);
}

Ok(ret_map)
}

#[cfg(test)]
mod tests {
use super::*;

pub const TESTING_BLOCK_HASH: &str =
"59b01ba262c999f2617412ffbba780f80b0103d928cbce1aecbaa50de90abda";

#[test]
fn parse_os_input() {
let input = StarknetOsInput::load("tests/common/os_input.json");
assert_eq!(
Felt252::from_str_radix(TESTING_BLOCK_HASH, 16).unwrap(),
input.block_hash
);
assert_eq!(
Felt252::from_str_radix(
"473010ec333f16b84334f9924912d7a13ce8296b0809c2091563ddfb63011d",
16
)
.unwrap(),
input.contract_state_commitment_info.previous_root
);
assert_eq!(
Felt252::from_str_radix(
"482c9ce8a99afddc9777ff048520fcbfab6c0389f51584016c80a2e94ab8ca7",
16
)
.unwrap(),
input.contract_state_commitment_info.updated_root
);
}
}
16 changes: 5 additions & 11 deletions src/state/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use blockifier::state::cached_state::{CachedState, CommitmentStateDiff};
use blockifier::state::state_api::{State, StateReader};
use cairo_felt::Felt252;
use indexmap::{IndexMap, IndexSet};
use serde::Serialize;
use storage::TrieStorage;

use starknet_api::block::BlockNumber;
Expand All @@ -16,23 +17,16 @@ use starknet_api::deprecated_contract_class::ContractClass as DeprecatedContract
use starknet_api::hash::{StarkFelt, StarkHash};
use starknet_api::{patricia_key, stark_felt};

use serde::Deserialize;
use std::collections::HashMap;

use crate::config::DEFAULT_STORAGE_TREE_HEIGHT;
use crate::io::CommitmentInfo;
use crate::utils::{bits_from_felt, calculate_contract_state_hash, vm_class_to_api_v0};
use serde::{Deserialize, Serialize};
use trie::{MerkleTrie, PedersenHash};

type CommitmentFacts = HashMap<Felt252, Vec<Felt252>>;

#[derive(Debug, Default, Serialize, Deserialize)]
pub struct CommitmentInfo {
pub previous_root: Felt252,
pub updated_root: Felt252,
pub(crate) tree_height: usize,
pub(crate) commitment_facts: CommitmentFacts,
}
use trie::{MerkleTrie, PedersenHash};

#[derive(Serialize, Deserialize, Debug)]
pub struct ContractState {
_contract_hash: Felt252,
_storage_commitment_tree: Felt252,
Expand Down
1 change: 0 additions & 1 deletion src/state/storage.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use anyhow::Context;
use bitvec::{prelude::BitSlice, prelude::BitVec, prelude::Msb0};
use starknet_api::block::BlockNumber;
use starknet_api::hash::StarkFelt;

use super::trie::{MerkleTrie, StarkHasher};
Expand Down
11 changes: 3 additions & 8 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
pub mod utils;

use blockifier::state::state_api::StateReader;
use cairo_felt::felt_str;

use blockifier::abi::constants::N_STEPS_RESOURCE;
Expand All @@ -22,9 +21,7 @@ use cairo_vm::vm::vm_core::VirtualMachine;
use snos::config::{StarknetGeneralConfig, DEFAULT_FEE_TOKEN_ADDR};
use snos::state::SharedState;
use starknet_api::block::{BlockNumber, BlockTimestamp};
use starknet_api::core::{
calculate_contract_address, ClassHash, ContractAddress, Nonce, PatriciaKey,
};
use starknet_api::core::{calculate_contract_address, ClassHash, ContractAddress, PatriciaKey};
use starknet_api::hash::{StarkFelt, StarkHash};
use starknet_api::state::StorageKey;
use starknet_api::transaction::{
Expand All @@ -45,15 +42,13 @@ use blockifier::test_utils::{

pub const TESTING_FEE: u128 = 0x10000000000000000000000000;
pub const TESTING_TRANSFER_AMOUNT: u128 = 0x01000000000000000000000000000000;
pub const TESTING_BLOCK_HASH: &str =
"59b01ba262c999f2617412ffbba780f80b0103d928cbce1aecbaa50de90abda";

// Contract Addresses - 0.12.2
pub const _TOKEN_FOR_TESTING_ADDRESS_0_12_2: &str =
"572b6542feb4bf285b57a056b588d649e067b9cfab2a88c2b2df9ea6bae6049";
pub const DUMMY_ACCOUNT_ADDRESS_0_12_2: &str =
"5ca2b81086d3fbb4f4af2f1deba4b7fd35e8f4b2caee4e056005c51c05c3dd0";
pub const DUMMY_TOKEN_ADDRESS_0_12_2: &str =
pub const _DUMMY_TOKEN_ADDRESS_0_12_2: &str =
"3400a86fdc294a70fac1cf84f81a2127419359096b846be9814786d4fc056b8";

// Class Hashes - 0.12.2
Expand Down Expand Up @@ -557,7 +552,7 @@ pub fn prepare_os_test(
}

#[rstest]
fn validate_prepare(mut prepare_os_test: SharedState<DictStateReader>) {
fn validate_prepare(prepare_os_test: SharedState<DictStateReader>) {
let mut shared_state = prepare_os_test;
let diff = shared_state.cache.to_state_diff();

Expand Down
21 changes: 7 additions & 14 deletions tests/common/os_input.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"contract_state_commitment_info": {
"previous_root": "0x473010ec333f16b84334f9924912d7a13ce8296b0809c2091563ddfb63011d",
"updated_root": "0x0482c9ce8a99afddc9777ff048520fcbfab6c0389f51584016c80a2e94ab8ca7",
"updated_root": "0x482c9ce8a99afddc9777ff048520fcbfab6c0389f51584016c80a2e94ab8ca7",
"tree_height": 251,
"commitment_facts": {
"0x473010ec333f16b84334f9924912d7a13ce8296b0809c2091563ddfb63011d": ["0x78ae47e863b0eeac50620a21d7aa9f163b1a9f1dcb2a810cb0c49f8fd16afdc", "0x446868832abcc6f03f057ad04c55047d1c21165b14094249024ef6f3e6effe9"],
Expand All @@ -27,19 +27,12 @@
"tree_height": 251,
"commitment_facts": {}
},
"deprecated_compiled_classes_raw": {
"build/delegate_proxy.json": "0x1880d2c303f26b658392a2c92a0677f3939f5fdfb960ecf5912afa06ad0b9d9",
"build/test_contract2.json": "0x49bcc976d628b1b238aefc20e77303a251a14ba6c99cd543a86708513414057",
"build/dummy_account.json": "0x16dc3038da22dde8ad61a786ab9930699cc496c8bccb90d77cc8abee89803f7",
"build/test_contract.json": "0x7364bafc3d2c56bc84404a6d8be799f533e518b8808bce86395a9442e1e5160",
"build/dummy_token.json": "0x7cea4d7710723fa9e33472b6ceb71587a0ce4997ef486638dd0156bdb6c2daa"
},
"deprecated_compiled_classes": {
"0x1880d2c303f26b658392a2c92a0677f3939f5fdfb960ecf5912afa06ad0b9d9": {},
"0x49bcc976d628b1b238aefc20e77303a251a14ba6c99cd543a86708513414057": {},
"0x16dc3038da22dde8ad61a786ab9930699cc496c8bccb90d77cc8abee89803f7": {},
"0x7364bafc3d2c56bc84404a6d8be799f533e518b8808bce86395a9442e1e5160": {},
"0x7cea4d7710723fa9e33472b6ceb71587a0ce4997ef486638dd0156bdb6c2daa": {}
"0x1880d2c303f26b658392a2c92a0677f3939f5fdfb960ecf5912afa06ad0b9d9": "build/delegate_proxy.json",
"0x49bcc976d628b1b238aefc20e77303a251a14ba6c99cd543a86708513414057": "build/test_contract2.json",
"0x16dc3038da22dde8ad61a786ab9930699cc496c8bccb90d77cc8abee89803f7": "build/dummy_account.json",
"0x7364bafc3d2c56bc84404a6d8be799f533e518b8808bce86395a9442e1e5160": "build/test_contract.json",
"0x7cea4d7710723fa9e33472b6ceb71587a0ce4997ef486638dd0156bdb6c2daa": "build/dummy_token.json"
},
"compiled_classes": {},
"contracts": {
Expand Down Expand Up @@ -111,7 +104,7 @@
"class_hash_to_compiled_class_hash": {},
"general_config": {
"starknet_os_config": {
"chain_id": 1536727068981429685321,
"chain_id": "0x534e5f474f45524c49",
"fee_token_address": "0x3400a86fdc294a70fac1cf84f81a2127419359096b846be9814786d4fc056b8"
},
"contract_storage_commitment_tree_height": 251,
Expand Down

0 comments on commit 0855921

Please sign in to comment.