Skip to content

Commit 1a77fe4

Browse files
blockifier_reexecution: move execute single tx from utils
1 parent 956123f commit 1a77fe4

File tree

3 files changed

+61
-85
lines changed

3 files changed

+61
-85
lines changed

crates/blockifier_reexecution/src/main.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@ use blockifier_reexecution::state_reader::cli::{
1414
use blockifier_reexecution::state_reader::offline_state_reader::OfflineConsecutiveStateReaders;
1515
use blockifier_reexecution::state_reader::reexecution_state_reader::ConsecutiveReexecutionStateReaders;
1616
use blockifier_reexecution::state_reader::test_state_reader::ConsecutiveTestStateReaders;
17-
use blockifier_reexecution::state_reader::utils::{
18-
execute_single_transaction,
19-
write_block_reexecution_data_to_file,
20-
};
17+
use blockifier_reexecution::state_reader::utils::write_block_reexecution_data_to_file;
2118
use clap::Parser;
2219
use google_cloud_storage::client::{Client, ClientConfig};
2320
use google_cloud_storage::http::objects::download::Range;
@@ -101,19 +98,21 @@ async fn main() {
10198
rpc_args.node_url
10299
);
103100

104-
let (node_url, chain_id) = (rpc_args.node_url.clone(), rpc_args.parse_chain_id());
101+
let rpc_state_reader_config = RpcStateReaderConfig::from_url(rpc_args.node_url.clone());
102+
let chain_id = rpc_args.parse_chain_id();
105103

106104
// RPC calls are "synchronous IO" (see, e.g., https://stackoverflow.com/questions/74547541/when-should-you-use-tokios-spawn_blocking)
107105
// for details), so should be executed in a blocking thread.
108106
// TODO(Aner): make only the RPC calls blocking, not the whole function.
109107
tokio::task::spawn_blocking(move || {
110-
execute_single_transaction(
111-
BlockNumber(block_number),
112-
node_url,
108+
ConsecutiveTestStateReaders::new(
109+
BlockNumber(block_number - 1),
110+
Some(rpc_state_reader_config),
113111
chain_id,
114-
tx_input,
112+
false,
115113
contract_class_manager,
116114
)
115+
.execute_single_transaction(tx_input)
117116
})
118117
.await
119118
.unwrap()

crates/blockifier_reexecution/src/state_reader/test_state_reader.rs

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::collections::HashMap;
2+
use std::fs::read_to_string;
23
use std::sync::{Arc, Mutex};
34

45
use apollo_gateway::errors::{serde_err_to_state_err, RPCStateReaderError};
@@ -24,7 +25,7 @@ use blockifier::state::state_reader_and_contract_manager::{
2425
};
2526
use blockifier::transaction::transaction_execution::Transaction as BlockifierTransaction;
2627
use serde::Serialize;
27-
use serde_json::{json, to_value};
28+
use serde_json::{json, to_value, Value};
2829
use starknet_api::block::{
2930
BlockHash,
3031
BlockHashAndNumber,
@@ -41,6 +42,7 @@ use starknet_core::types::ContractClass as StarknetContractClass;
4142
use starknet_types_core::felt::Felt;
4243

4344
use crate::retry_request;
45+
use crate::state_reader::cli::TransactionInput;
4446
use crate::state_reader::compile::{
4547
legacy_to_contract_class_v0,
4648
sierra_to_versioned_contract_class_v1,
@@ -471,6 +473,54 @@ impl ConsecutiveTestStateReaders {
471473
)?,
472474
))
473475
}
476+
477+
/// Executes a single transaction from a JSON file or given a transaction hash, using RPC to
478+
/// fetch block context. Does not assert correctness, only prints the execution result.
479+
pub fn execute_single_transaction(self, tx_input: TransactionInput) -> ReexecutionResult<()> {
480+
let chain_id = self.next_block_state_reader.chain_id.clone();
481+
482+
// Get transaction and hash based on input method.
483+
let (transaction, transaction_hash) = match tx_input {
484+
TransactionInput::FromHash { tx_hash } => {
485+
// Fetch transaction from the next block (the block containing the transaction to
486+
// execute).
487+
let transaction = self.next_block_state_reader.get_tx_by_hash(&tx_hash)?;
488+
let transaction_hash = TransactionHash(Felt::from_hex_unchecked(&tx_hash));
489+
490+
(transaction, transaction_hash)
491+
}
492+
TransactionInput::FromFile { tx_path } => {
493+
// Load the transaction from a local JSON file.
494+
let json_content = read_to_string(&tx_path).unwrap_or_else(|_| {
495+
panic!("Failed to read transaction JSON file: {}.", tx_path)
496+
});
497+
let json_value: Value = serde_json::from_str(&json_content)?;
498+
let transaction = deserialize_transaction_json_to_starknet_api_tx(json_value)?;
499+
let transaction_hash = transaction.calculate_transaction_hash(&chain_id)?;
500+
501+
(transaction, transaction_hash)
502+
}
503+
};
504+
505+
// Convert transaction to BlockifierTransaction using api_txs_to_blockifier_txs_next_block.
506+
let blockifier_tx = self
507+
.next_block_state_reader
508+
.api_txs_to_blockifier_txs_next_block(vec![(transaction, transaction_hash)])?;
509+
510+
// Create transaction executor.
511+
let mut transaction_executor = self.pre_process_and_create_executor(None)?;
512+
513+
// Execute transaction (should be single element).
514+
let execution_results = transaction_executor.execute_txs(&blockifier_tx, None);
515+
516+
// We expect exactly one execution result since we executed a single transaction.
517+
let res =
518+
execution_results.first().expect("Expected exactly one execution result, but got none");
519+
520+
println!("Execution result: {:?}", res);
521+
522+
Ok(())
523+
}
474524
}
475525

476526
impl ConsecutiveReexecutionStateReaders<StateReaderAndContractManager<TestStateReader>>

crates/blockifier_reexecution/src/state_reader/utils.rs

Lines changed: 2 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use std::collections::{BTreeMap, HashMap};
22
use std::env;
3-
use std::fs::read_to_string;
43
use std::sync::{Arc, LazyLock};
54

65
use apollo_gateway_config::config::RpcStateReaderConfig;
@@ -15,26 +14,19 @@ use blockifier::state::state_api::StateResult;
1514
use indexmap::IndexMap;
1615
use pretty_assertions::assert_eq;
1716
use serde::{Deserialize, Serialize};
18-
use serde_json::Value;
1917
use starknet_api::block::BlockNumber;
2018
use starknet_api::contract_class::ContractClass;
2119
use starknet_api::core::{ChainId, ClassHash, CompiledClassHash, ContractAddress, Nonce};
2220
use starknet_api::state::{SierraContractClass, StorageKey};
23-
use starknet_api::transaction::TransactionHash;
2421
use starknet_types_core::felt::Felt;
2522

26-
use crate::state_reader::cli::TransactionInput;
27-
use crate::state_reader::errors::{ReexecutionError, ReexecutionResult};
23+
use crate::state_reader::errors::ReexecutionError;
2824
use crate::state_reader::offline_state_reader::{
2925
OfflineConsecutiveStateReaders,
3026
SerializableDataPrevBlock,
3127
SerializableOfflineReexecutionData,
3228
};
33-
use crate::state_reader::reexecution_state_reader::{
34-
ConsecutiveReexecutionStateReaders,
35-
ReexecutionStateReader,
36-
};
37-
use crate::state_reader::serde_utils::deserialize_transaction_json_to_starknet_api_tx;
29+
use crate::state_reader::reexecution_state_reader::ConsecutiveReexecutionStateReaders;
3830
use crate::state_reader::test_state_reader::ConsecutiveTestStateReaders;
3931

4032
pub static RPC_NODE_URL: LazyLock<String> = LazyLock::new(|| {
@@ -313,71 +305,6 @@ pub fn write_block_reexecution_data_to_file(
313305
println!("RPC replies required for reexecuting block {block_number} written to json file.");
314306
}
315307

316-
/// Executes a single transaction from a JSON file or given a transaction hash, using RPC to fetch
317-
/// block context. Does not assert correctness, only prints the execution result.
318-
pub fn execute_single_transaction(
319-
block_number: BlockNumber,
320-
node_url: String,
321-
chain_id: ChainId,
322-
tx_input: TransactionInput,
323-
contract_class_manager: ContractClassManager,
324-
) -> ReexecutionResult<()> {
325-
// Create RPC config.
326-
let config = RpcStateReaderConfig::from_url(node_url);
327-
328-
// Create ConsecutiveTestStateReaders first.
329-
let consecutive_state_readers = ConsecutiveTestStateReaders::new(
330-
block_number.prev().expect("Should not run with block 0"),
331-
Some(config),
332-
chain_id.clone(),
333-
false, // dump_mode = false
334-
contract_class_manager,
335-
);
336-
337-
// Get transaction and hash based on input method.
338-
let (transaction, transaction_hash) = match tx_input {
339-
TransactionInput::FromHash { tx_hash } => {
340-
// Fetch transaction from the next block (the block containing the transaction to
341-
// execute).
342-
let transaction =
343-
consecutive_state_readers.next_block_state_reader.get_tx_by_hash(&tx_hash)?;
344-
let transaction_hash = TransactionHash(Felt::from_hex_unchecked(&tx_hash));
345-
346-
(transaction, transaction_hash)
347-
}
348-
TransactionInput::FromFile { tx_path } => {
349-
// Load the transaction from a local JSON file.
350-
let json_content = read_to_string(&tx_path)
351-
.unwrap_or_else(|_| panic!("Failed to read transaction JSON file: {}.", tx_path));
352-
let json_value: Value = serde_json::from_str(&json_content)?;
353-
let transaction = deserialize_transaction_json_to_starknet_api_tx(json_value)?;
354-
let transaction_hash = transaction.calculate_transaction_hash(&chain_id)?;
355-
356-
(transaction, transaction_hash)
357-
}
358-
};
359-
360-
// Convert transaction to BlockifierTransaction using api_txs_to_blockifier_txs_next_block.
361-
let blockifier_tx = consecutive_state_readers
362-
.next_block_state_reader
363-
.api_txs_to_blockifier_txs_next_block(vec![(transaction, transaction_hash)])?;
364-
365-
// Create transaction executor.
366-
let mut transaction_executor =
367-
consecutive_state_readers.pre_process_and_create_executor(None)?;
368-
369-
// Execute transaction (should be single element).
370-
let execution_results = transaction_executor.execute_txs(&blockifier_tx, None);
371-
372-
// We expect exactly one execution result since we executed a single transaction.
373-
let res =
374-
execution_results.first().expect("Expected exactly one execution result, but got none");
375-
376-
println!("Execution result: {:?}", res);
377-
378-
Ok(())
379-
}
380-
381308
/// Asserts equality between two `CommitmentStateDiff` structs, ignoring insertion order.
382309
#[macro_export]
383310
macro_rules! assert_eq_state_diff {

0 commit comments

Comments
 (0)