Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions crates/core/generate-pie/src/block_processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,6 @@ pub struct BlockInfoResult {
pub accessed_classes: HashSet<ClassHash>,
/// Storage keys accessed by each contract address.
pub accessed_keys_by_address: HashMap<ContractAddress, HashSet<StorageKey>>,
/// The previous block ID (if any).
#[allow(dead_code)]
pub previous_block_id: Option<BlockId>,
/// Classes migrated from Poseidon to BLAKE hash (SNIP-34).
pub migrated_compiled_classes: HashMap<ClassHash, CompiledClassHash>,
}
Expand Down Expand Up @@ -168,7 +165,6 @@ pub async fn collect_single_block_info(
accessed_addresses,
accessed_classes,
accessed_keys_by_address,
previous_block_id: if block_number == 0 { None } else { Some(BlockId::Number(block_number - 1)) },
migrated_compiled_classes,
})
}
Expand Down
61 changes: 0 additions & 61 deletions crates/core/generate-pie/src/utils/misc.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
use log::info;
use num_traits::cast::ToPrimitive;
use serde::Serialize;
use starknet_api::block::{GasPrice, GasPriceVector, NonzeroGasPrice};
use std::fs::File;
use std::io::Write;
use std::path::Path;

use crate::error::FeltConversionError;
Expand All @@ -29,64 +26,6 @@ pub fn felt_to_u128(felt: &Felt) -> Result<u128, FeltConversionError> {
felt.to_u128().ok_or(FeltConversionError::OverflowError)
}

/// Generic function to serialize any serializable object and write it to a file
///
/// # Arguments
/// * `object` - Any object that implements the Serialize trait
/// * `file_path` - Path where the file should be written
/// * `format` - Optional format specification ("json", "yaml", etc.). Defaults to JSON.
///
/// # Returns
/// * `Result<(), Box<dyn std::error::Error>>` - Ok(()) on success, error on failure
///
/// # Examples
/// ```
/// let data = vec![1, 2, 3, 4, 5];
/// write_serializable_to_file(&data, "output/numbers.json", Some("json"))?;
///
/// let traces = get_transaction_traces();
/// write_serializable_to_file(&traces, "debug/traces.json", None)?;
/// ```
#[allow(dead_code)]
pub fn write_serializable_to_file<T>(
object: &T,
file_path: &str,
format: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>>
where
T: Serialize,
{
// Create a directory if it doesn't exist
if let Some(parent) = Path::new(file_path).parent() {
std::fs::create_dir_all(parent)?;
}

let mut file = File::create(file_path)?;

match format.unwrap_or("json") {
"json" => {
let json_string = serde_json::to_string_pretty(object)?;
file.write_all(json_string.as_bytes())?;
}
"json-compact" => {
let json_string = serde_json::to_string(object)?;
file.write_all(json_string.as_bytes())?;
}
#[cfg(feature = "yaml")]
"yaml" => {
let yaml_string = serde_yaml::to_string(object)?;
file.write_all(yaml_string.as_bytes())?;
}
_ => {
return Err(format!("Unsupported format: {}", format.unwrap_or("json")).into());
}
}

file.flush()?;
info!("Successfully wrote serialized data to: {}", file_path);
Ok(())
}

/// Loads versioned constants from a file path if provided.
///
/// This function handles loading versioned constants from a JSON file.
Expand Down
1 change: 0 additions & 1 deletion crates/core/generate-pie/src/utils/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use starknet_types_core::felt::Felt;
use std::collections::{HashMap, HashSet};

/// Comprehensive structure that captures all access information from transaction execution
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct BlockAccessInfo {
/// Storage keys accessed per contract address
Expand Down
193 changes: 1 addition & 192 deletions crates/core/generate-pie/src/utils/serialization.rs
Original file line number Diff line number Diff line change
@@ -1,201 +1,10 @@
//! Utilities for serialization and contract class processing.
//!
//! This module contains helper functions for:
//! - Serializing OS hints to JSON format
//! - Processing and normalizing deprecated contract classes
//! - JSON manipulation utilities for contract compatibility

use log::{debug, info};
use serde_json::json;
use starknet_os::io::os_input::OsHints;

use crate::error::PieGenerationError;

// ================================================================================================
// OS Hints Serialization
// ================================================================================================

/// Serializes OsHints to JSON format with complete data representation.
///
/// Since OsHints may not implement Serialize directly, this function creates a comprehensive
/// custom serializable representation including all nested structures and metadata.
///
/// # Arguments
///
/// * `os_hints` - The OS hints structure to serialize
/// * `output_path` - Path where the JSON file should be written
///
/// # Returns
///
/// Returns `Ok(())` on success or `PieGenerationError` on failure.
///
/// # Example
///
/// ```rust
/// use generate_pie::utils::serialization::serialize_os_hints_to_json;
///
/// let output_path = "os_hints_block_123.json";
/// serialize_os_hints_to_json(&os_hints, output_path)?;
/// ```
#[allow(dead_code)]
pub fn serialize_os_hints_to_json(os_hints: &OsHints, output_path: &str) -> Result<(), PieGenerationError> {
info!("Serializing OS hints to JSON file: {}", output_path);

// Serialize OS hints config
let os_hints_config_json = json!({
"debug_mode": os_hints.os_hints_config.debug_mode,
"full_output": os_hints.os_hints_config.full_output,
"use_kzg_da": os_hints.os_hints_config.use_kzg_da,
"chain_info": {
"chain_id": format!("{:?}", os_hints.os_hints_config.chain_info.chain_id),
"strk_fee_token_address": format!("{:#x}", os_hints.os_hints_config.chain_info.strk_fee_token_address.0.key())
}
});

// Serialize block inputs completely
let block_inputs_json: Vec<serde_json::Value> = os_hints.os_input.os_block_inputs.iter()
.map(|block_input| {
json!({
"block_info": {
"block_number": block_input.block_info.block_number,
"sequencer_address": format!("{:#x}", block_input.block_info.sequencer_address.0.key()),
"block_timestamp": block_input.block_info.block_timestamp.0,
"use_kzg_da": block_input.block_info.use_kzg_da,
"gas_prices": {
"eth_gas_prices": format!("{:#?}", block_input.block_info.gas_prices.eth_gas_prices),
"strk_gas_prices": format!("{:#?}", block_input.block_info.gas_prices.strk_gas_prices),
}
},
"transactions": block_input.transactions.iter().map(|tx| {
// Use Debug format for comprehensive transaction serialization
format!("{:#?}", tx)
}).collect::<Vec<_>>(),
"tx_execution_infos": block_input.tx_execution_infos.iter().map(|exec_info| {
format!("{:#?}", exec_info)
}).collect::<Vec<_>>(),
"contract_state_commitment_info": format!("{:#?}", block_input.contract_state_commitment_info),
"contract_class_commitment_info": format!("{:#?}", block_input.contract_class_commitment_info),
"address_to_storage_commitment_info": block_input.address_to_storage_commitment_info.iter().map(|(addr, commitment_info)| {
json!({
"address": format!("{:#x}", addr.0.key()),
"commitment_info": format!("{:#?}", commitment_info)
})
}).collect::<Vec<_>>(),
"declared_class_hash_to_component_hashes": block_input.declared_class_hash_to_component_hashes.iter().map(|(class_hash, component_hashes)| {
json!({
"class_hash": format!("{:#x}", class_hash.0),
"component_hashes": format!("{:#?}", component_hashes)
})
}).collect::<Vec<_>>(),
"prev_block_hash": format!("{:#x}", block_input.prev_block_hash.0),
"new_block_hash": format!("{:#x}", block_input.new_block_hash.0),
"old_block_number_and_hash": block_input.old_block_number_and_hash.as_ref().map(|(block_number, block_hash)| {
json!({
"block_number": block_number.0,
"block_hash": format!("{:#x}", block_hash.0)
})
})
})
}).collect();

// Serialize cached state inputs completely
let cached_state_inputs_json: Vec<serde_json::Value> = os_hints.os_input.cached_state_inputs.iter()
.map(|cached_state| {
json!({
"storage": cached_state.storage.iter().map(|(addr, storage_map)| {
json!({
"address": format!("{:#x}", addr.0.key()),
"storage": storage_map.iter().map(|(key, value)| {
json!({
"key": format!("{:#x}", key.0.key()),
"value": format!("{:#x}", value)
})
}).collect::<Vec<_>>()
})
}).collect::<Vec<_>>(),
"address_to_class_hash": cached_state.address_to_class_hash.iter().map(|(addr, class_hash)| {
json!({
"address": format!("{:#x}", addr.0.key()),
"class_hash": format!("{:#x}", class_hash.0)
})
}).collect::<Vec<_>>(),
"address_to_nonce": cached_state.address_to_nonce.iter().map(|(addr, nonce)| {
json!({
"address": format!("{:#x}", addr.0.key()),
"nonce": format!("{:#x}", nonce.0)
})
}).collect::<Vec<_>>(),
"class_hash_to_compiled_class_hash": cached_state.class_hash_to_compiled_class_hash.iter().map(|(class_hash, compiled_hash)| {
json!({
"class_hash": format!("{:#x}", class_hash.0),
"compiled_class_hash": format!("{:#x}", compiled_hash.0)
})
}).collect::<Vec<_>>()
})
}).collect();

// Serialize compiled classes completely
let compiled_classes_json: Vec<serde_json::Value> = os_hints
.os_input
.compiled_classes
.iter()
.map(|(class_hash, compiled_class)| {
json!({
"class_hash": format!("{:#x}", class_hash.0),
"compiled_class": format!("{:#?}", compiled_class)
})
})
.collect();

// Serialize deprecated compiled classes completely
let deprecated_compiled_classes_json: Vec<serde_json::Value> = os_hints
.os_input
.deprecated_compiled_classes
.iter()
.map(|(class_hash, deprecated_compiled_class)| {
json!({
"class_hash": format!("{:#x}", class_hash.0),
"deprecated_compiled_class": format!("{:#?}", deprecated_compiled_class)
})
})
.collect();

// Create the complete serializable representation
let complete_os_hints = json!({
"os_hints_config": os_hints_config_json,
"os_input": {
"os_block_inputs": block_inputs_json,
"cached_state_inputs": cached_state_inputs_json,
"compiled_classes": compiled_classes_json,
"deprecated_compiled_classes": deprecated_compiled_classes_json
},
"metadata": {
"serialization_timestamp": chrono::Utc::now().to_rfc3339(),
"serialization_note": "Complete serialization of OsHints including all nested structures and data.",
"statistics": {
"num_blocks": os_hints.os_input.os_block_inputs.len(),
"num_cached_states": os_hints.os_input.cached_state_inputs.len(),
"num_compiled_classes": os_hints.os_input.compiled_classes.len(),
"num_deprecated_compiled_classes": os_hints.os_input.deprecated_compiled_classes.len(),
"total_transactions": os_hints.os_input.os_block_inputs.iter()
.map(|block| block.transactions.len())
.sum::<usize>(),
"block_numbers": os_hints.os_input.os_block_inputs.iter()
.map(|block_input| block_input.block_info.block_number)
.collect::<Vec<_>>()
}
}
});

// Write to file
let json_string = serde_json::to_string_pretty(&complete_os_hints)
.map_err(|e| PieGenerationError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, e)))?;

std::fs::write(output_path, json_string)?;
info!("Complete OS hints successfully serialized to: {}", output_path);

Ok(())
}
use log::debug;

// ================================================================================================
// Contract Class Processing
Expand Down
26 changes: 2 additions & 24 deletions crates/rpc-client/src/types/proofs/class.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,13 @@
use serde::{Deserialize, Serialize};
use starknet_core::types::StorageProof;
use starknet_types_core::felt::Felt;

use crate::error::ProofVerificationError;
use crate::types::{PoseidonHash, TrieNode};
use crate::types::TrieNode;

#[allow(dead_code)]
#[derive(Clone, Deserialize, Serialize)]
pub struct ClassProof {
pub class_commitment: Felt,
pub class_proof: Vec<TrieNode>,
}

// Implementations for ClassProof
impl ClassProof {
/// Gets the "class_commitment" which is aka the root node of the class Merkle tree.
///
/// Proof always starts with the root node, which means all we have to do is hash the
/// first node in the proof to get the same thing.
#[allow(clippy::result_large_err)]
pub fn class_commitment(&self) -> Result<Felt, ProofVerificationError> {
if !self.class_proof.is_empty() {
let hash = self.class_proof[0].calculate_node_hash::<PoseidonHash>();
Ok(hash)
} else {
Err(ProofVerificationError::EmptyProof)
}
}
}

impl From<StorageProof> for ClassProof {
fn from(proof: StorageProof) -> Self {
let class_proof = proof
Expand All @@ -41,7 +20,6 @@ impl From<StorageProof> for ClassProof {
trie_node
})
.collect();
let class_commitment = proof.global_roots.classes_tree_root;
ClassProof { class_commitment, class_proof }
ClassProof { class_proof }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ pub struct GenericDeprecatedCompiledClass {
/// Lazy-initialized StarknetAPI contract class.
starknet_api_contract_class: OnceCell<Arc<StarknetApiDeprecatedClass>>,
/// Lazy-initialized StarknetCore contract class.
#[allow(dead_code)]
starknet_core_contract_class: OnceCell<Arc<StarknetCoreDeprecatedClass>>,
/// Lazy-initialized serialized contract class bytes.
serialized_class: OnceCell<Vec<u8>>,
Expand Down