Skip to content

Commit

Permalink
Merge pull request #42 from keep-starknet-strange/lucas/load-tx
Browse files Browse the repository at this point in the history
Lucas/load tx
  • Loading branch information
drspacemn committed Oct 23, 2023
2 parents 452b75e + 9bdf191 commit 6eff194
Show file tree
Hide file tree
Showing 11 changed files with 140 additions and 672 deletions.
2 changes: 1 addition & 1 deletion scripts/debug-hint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ else
echo -e "$1 sucessfully recompiled...\n"
fi

cargo test -q "$1_test" -- --nocapture
cargo test "$1_test" -- --nocapture
1 change: 1 addition & 0 deletions scripts/setup-tests.sh
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ cairo-compile tests/programs/fact.cairo --output build/programs/fact.json
cairo-compile tests/programs/load_deprecated_class.cairo --output build/programs/load_deprecated_class.json --cairo_path cairo-lang/src
cairo-compile tests/programs/initialize_state_changes.cairo --output build/programs/initialize_state_changes.json --cairo_path cairo-lang/src
cairo-compile tests/programs/get_block_mapping.cairo --output build/programs/get_block_mapping.json --cairo_path cairo-lang/src
cairo-compile tests/programs/load_next_tx.cairo --output build/programs/load_next_tx.json --cairo_path cairo-lang/src

# compile os with debug info
cairo-compile cairo-lang/src/starkware/starknet/core/os/os.cairo --output build/os_debug.json --cairo_path cairo-lang/src
Expand Down
8 changes: 8 additions & 0 deletions src/hints/hints_raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,11 @@ pub const ENTER_SYSCALL_SCOPES: &str =
"vm_enter_scope({\n '__deprecated_class_hashes': __deprecated_class_hashes,\n 'transactions': \
iter(os_input.transactions),\n 'execution_helper': execution_helper,\n 'deprecated_syscall_handler': \
deprecated_syscall_handler,\n 'syscall_handler': syscall_handler,\n '__dict_manager': __dict_manager,\n})";

pub const LOAD_NEXT_TX: &str = "tx = next(transactions)\ntx_type_bytes = \
tx.tx_type.name.encode(\"ascii\")\nids.tx_type = int.from_bytes(tx_type_bytes, \
\"big\")";

pub const LOAD_CONTRACT_ADDRESS: &str = "from starkware.starknet.business_logic.transaction.objects import \
InternalL1Handler\nids.contract_address = (\ntx.contract_address if \
isinstance(tx, InternalL1Handler) else tx.sender_address\n)";
29 changes: 27 additions & 2 deletions src/hints/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
pub mod block_context;
pub mod hints_raw;
// pub mod transaction_context;

use std::any::Any;
use std::collections::HashMap;
use std::rc::Rc;
use std::slice::Iter;

use cairo_vm::felt::Felt252;
use cairo_vm::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::{
Expand All @@ -17,7 +20,7 @@ use cairo_vm::vm::errors::hint_errors::HintError;
use cairo_vm::vm::vm_core::VirtualMachine;

use crate::config::DEFAULT_INPUT_PATH;
use crate::io::StarknetOsInput;
use crate::io::{InternalTransaction, StarknetOsInput};

pub fn sn_hint_processor() -> BuiltinHintProcessor {
let mut hint_processor = BuiltinHintProcessor::new_empty();
Expand Down Expand Up @@ -233,10 +236,32 @@ pub fn transactions_len(
/// })
pub fn enter_syscall_scopes(
_vm: &mut VirtualMachine,
_exec_scopes: &mut ExecutionScopes,
exec_scopes: &mut ExecutionScopes,
_ids_data: &HashMap<String, HintReference>,
_ap_tracking: &ApTracking,
_constants: &HashMap<String, Felt252>,
) -> Result<(), HintError> {
let os_input = exec_scopes.get::<StarknetOsInput>("os_input").unwrap();
let transactions: Box<dyn Any> = Box::new([os_input.transactions.into_iter()].into_iter());
exec_scopes.enter_scope(HashMap::from_iter([(String::from("transactions"), transactions)]));
Ok(())
}

/// Implements hint:
///
/// tx = next(transactions)
/// tx_type_bytes = tx.tx_type.name.encode("ascii")
/// ids.tx_type = int.from_bytes(tx_type_bytes, "big")
pub fn load_next_tx(
vm: &mut VirtualMachine,
exec_scopes: &mut ExecutionScopes,
ids_data: &HashMap<String, HintReference>,
ap_tracking: &ApTracking,
_constants: &HashMap<String, Felt252>,
) -> Result<(), HintError> {
let mut transactions = exec_scopes.get::<Iter<InternalTransaction>>("transactions")?;
// Safe to unwrap because the remaining number of txs is checked in the cairo code.
let tx = transactions.next().unwrap();
exec_scopes.insert_value("transactions", transactions);
insert_value_from_var_name("tx_type", Felt252::from_bytes_be(tx.r#type.as_bytes()), vm, ids_data, ap_tracking)
}
21 changes: 21 additions & 0 deletions src/hints/transaction_context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use crate::io::InternalTransaction;

/// Implements hint:
///
/// from starkware.starknet.business_logic.transaction.objects import InternalL1Handler
/// ids.contract_address = (
/// tx.contract_address if isinstance(tx, InternalL1Handler) else tx.sender_address
/// )
pub fn load_transaction_context(
vm: &mut VirtualMachine,
exec_scopes: &mut ExecutionScopes,
ids_data: &HashMap<String, HintReference>,
ap_tracking: &ApTracking,
_constants: &HashMap<String, Felt252>,
) -> Result<(), HintError> {
let mut transactions = exec_scopes.get::<Iter<InternalTransaction>>("transactions")?;
// Safe to unwrap because the remaining number of txs is checked in the cairo code.
let tx = transactions.next().unwrap();
exec_scopes.insert_value("transactions", transactions);
insert_value_from_var_name("tx_type", Felt252::from_bytes_be(tx.r#type.as_bytes()), vm, ids_data, ap_tracking)
}
3 changes: 2 additions & 1 deletion src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ pub struct StorageCommitment {
}

#[serde_as]
#[derive(Deserialize, Clone, Debug, Serialize)]
#[derive(Deserialize, Clone, Debug, Serialize, Default)]
pub struct InternalTransaction {
#[serde_as(as = "Felt252Str")]
pub hash_value: Felt252,
Expand Down Expand Up @@ -106,6 +106,7 @@ pub struct InternalTransaction {
pub r#type: String,
}

#[derive(Debug)]
pub struct StarknetOsOutput {
/// The state commitment before this block.
pub prev_state_root: Felt252,
Expand Down
14 changes: 9 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ impl SnOsRunner {
.run_until_pc(end, &mut vm, &mut sn_hint_processor)
.map_err(|err| VmException::from_vm_error(&cairo_runner, &vm, err))
.map_err(|e| SnOsError::Runner(e.into()))?;

// End the Cairo VM run
cairo_runner
.end_run(cairo_run_config.disable_trace_padding, false, &mut vm, &mut sn_hint_processor)
.map_err(|e| SnOsError::Runner(e.into()))?;
Expand Down Expand Up @@ -118,27 +120,28 @@ impl SnOsRunner {
}
})
.collect();

let prev_state_root = os_output[0].clone();
let new_state_root = os_output[1].clone();
let block_number = os_output[2].clone();
let block_hash = os_output[3].clone();
let config_hash = os_output[4].clone();
let os_output = &os_output[5..];
let messages_to_l1_size = <usize>::from_be_bytes(os_output[0].to_be_bytes()[..8].try_into().unwrap());
let messages_to_l1 = os_output[1..messages_to_l1_size].to_vec();
let messages_to_l1 = os_output[1..1 + messages_to_l1_size].to_vec();

let os_output = &os_output[messages_to_l1_size + 1..];
let messages_to_l2_size = <usize>::from_be_bytes(os_output[0].to_be_bytes()[..8].try_into().unwrap());
let messages_to_l2 = os_output[1..messages_to_l2_size].to_vec();
let messages_to_l2 = os_output[1..1 + messages_to_l2_size].to_vec();
let os_output = &os_output[messages_to_l2_size + 1..];

let state_updates_size = <usize>::from_be_bytes(os_output[0].to_be_bytes()[..8].try_into().unwrap());
let state_updates = os_output[1..state_updates_size].to_vec();
let state_updates = os_output[1..1 + state_updates_size].to_vec();
let os_output = &os_output[state_updates_size + 1..];

let contract_class_diff_size = <usize>::from_be_bytes(os_output[0].to_be_bytes()[..8].try_into().unwrap());
let contract_class_diff = os_output[1..contract_class_diff_size].to_vec();
StarknetOsOutput::new(
let contract_class_diff = os_output[1..1 + contract_class_diff_size].to_vec();
let real_output = StarknetOsOutput::new(
prev_state_root,
new_state_root,
block_number,
Expand All @@ -149,6 +152,7 @@ impl SnOsRunner {
state_updates,
contract_class_diff,
);
println!("{:?}", real_output);

vm.verify_auto_deductions().map_err(|e| SnOsError::Runner(e.into()))?;
cairo_runner.read_return_values(&mut vm).map_err(|e| SnOsError::Runner(e.into()))?;
Expand Down
Loading

0 comments on commit 6eff194

Please sign in to comment.