Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement run resources funcs #1175

Merged
merged 24 commits into from
Jun 6, 2023
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
9f81313
Add RunResources structure
mmsc2 May 17, 2023
07ecb2d
Modify changelog
mmsc2 May 17, 2023
0699590
Merge branch 'main' into RunResources
mmsc2 May 19, 2023
a1f9eba
change data type of n_steps from u64 to usize
mmsc2 May 19, 2023
a6231da
merge main
mmsc2 May 22, 2023
d3440f2
Implement run resources functions
mmsc2 May 22, 2023
f4e770e
Fix tests
mmsc2 May 22, 2023
19e17e7
set comment about calculation in cairo_run
mmsc2 May 22, 2023
7fe4382
Change CHangelog and remove option from RunResources
mmsc2 May 23, 2023
300911a
Fix clippy
mmsc2 May 23, 2023
98046ab
Add clone trait to run resources
mmsc2 May 23, 2023
b177834
Add debug and default traits to RunResources
mmsc2 May 23, 2023
fd23227
Fix error in while loop inside run_until_pc
mmsc2 May 24, 2023
5a4ea36
Merge branch 'main' into ImplementRunResourcesFuncs
mmsc2 May 29, 2023
ba797f9
Add helper function for clarity in run_until_pc loop
mmsc2 May 29, 2023
fdd9e99
Merge branch 'main' into ImplementRunResourcesFuncs
pefontana May 30, 2023
75a25fe
Merge branch 'main' into ImplementRunResourcesFuncs
pefontana May 30, 2023
4f3c4e6
Add test for cairo 0 contracts
pefontana May 31, 2023
4abed1c
Add tests with Cairo 1 contracts
pefontana May 31, 2023
66809fd
Move RunResources struct to vm::runners::cairo_runner::RunResources
pefontana May 31, 2023
1078e42
Merge branch 'main' into ImplementRunResourcesFuncs
pefontana May 31, 2023
4ca1b89
Update CHANGELOG.md
pefontana May 31, 2023
5a9418f
Fix wasm and no-std compilation
pefontana May 31, 2023
2a8a8a8
Merge branch 'main' into ImplementRunResourcesFuncs
pefontana Jun 5, 2023
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: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
#### Upcoming Changes
* fix: Handle the deserialization of serde_json::Number with scientific notation (e.g.: Number(1e27)) in felt_from_number function [#1188](https://github.com/lambdaclass/cairo-rs/pull/1188)

* feat: Add RunResources Struct [#1175](https://github.com/lambdaclass/cairo-rs/pull/1175)
* BREAKING: Modify `CairoRunner::run_until_pc` arity. Add `run_resources: &mut Option<RunResources>` input
* BREAKING: Modify `CairoRunner::run_from_entrypoint` arity. Add `run_resources: &mut Option<RunResources>` input

* bugfix: Use cairo constants in `ASSERT_250_BIT` hint [#1187](https://github.com/lambdaclass/cairo-rs/pull/1187)

* bugfix: Fix `EC_DOUBLE_ASSIGN_NEW_X_V2` hint not taking `SECP_P` value from the current execution scope [#1186](https://github.com/lambdaclass/cairo-rs/pull/1186)
Expand Down
11 changes: 7 additions & 4 deletions src/cairo_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,14 @@ pub fn cairo_run(
cairo_run_config.layout,
cairo_run_config.proof_mode,
)?;

let mut vm = VirtualMachine::new(cairo_run_config.trace_enabled);
let end = cairo_runner.initialize(&mut vm)?;
// check step calculation
let mut run_resources = None;

cairo_runner
.run_until_pc(end, &mut vm, hint_executor)
.run_until_pc(end, &mut run_resources, &mut vm, hint_executor)
.map_err(|err| VmException::from_vm_error(&cairo_runner, &vm, err))?;
cairo_runner.end_run(false, false, &mut vm, hint_executor)?;

Expand Down Expand Up @@ -153,7 +156,7 @@ mod tests {
.map_err(CairoRunError::Runner)?;

assert!(cairo_runner
.run_until_pc(end, &mut vm, hint_processor)
.run_until_pc(end, &mut None, &mut vm, hint_processor)
.is_ok());

Ok((cairo_runner, vm))
Expand All @@ -173,7 +176,7 @@ mod tests {

let end = cairo_runner.initialize(&mut vm).unwrap();
assert!(cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.is_ok());
assert!(cairo_runner.relocate(&mut vm, true).is_ok());
// `main` returns without doing nothing, but `not_main` sets `[ap]` to `1`
Expand Down Expand Up @@ -293,7 +296,7 @@ mod tests {
let mut vm = vm!();
let end = cairo_runner.initialize(&mut vm).unwrap();
assert!(cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.is_ok());
assert!(cairo_runner.relocate(&mut vm, false).is_ok());
assert!(vm.get_relocated_trace().is_err());
Expand Down
58 changes: 58 additions & 0 deletions src/tests/cairo_1_run_from_entrypoint_tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::tests::*;
use assert_matches::assert_matches;

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
Expand Down Expand Up @@ -558,3 +559,60 @@ fn uint512_div_mod_test() {
&[],
);
}

// ================
// Tests run cairo 1 entrypoint with RunResources
// ================

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn fibonacci_with_run_resources_ok() {
let program_data = include_bytes!("../../cairo_programs/cairo-1-contracts/fib.casm");
let mut resources = Some(RunResources::new(621));
// Program takes 621 steps
assert_matches!(
run_cairo_1_entrypoint_with_run_resources(
program_data.as_slice(),
0,
&mut resources,
&[1_usize.into(), 1_usize.into(), 20_usize.into()],
),
Ok(x) if x == [10946_usize.into()]
);

assert_eq!(resources, Some(RunResources::new(0)));
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn fibonacci_with_run_resources_2_ok() {
let program_data = include_bytes!("../../cairo_programs/cairo-1-contracts/fib.casm");
let mut resources = Some(RunResources::new(1000));
// Program takes 621 steps
assert_matches!(
run_cairo_1_entrypoint_with_run_resources(
program_data.as_slice(),
0,
&mut resources,
&[1_usize.into(), 1_usize.into(), 20_usize.into()],
),
Ok(x) if x == [10946_usize.into()]
);
assert_eq!(resources, Some(RunResources::new(1000 - 621)));
}

#[test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
fn fibonacci_with_run_resources_error() {
let program_data = include_bytes!("../../cairo_programs/cairo-1-contracts/fib.casm");
let mut resources = Some(RunResources::new(100));
// Program takes 621 steps
assert!(run_cairo_1_entrypoint_with_run_resources(
program_data.as_slice(),
0,
&mut resources,
&[1_usize.into(), 1_usize.into(), 20_usize.into()],
)
.is_err());
assert_eq!(resources, Some(RunResources::new(0)));
}
109 changes: 109 additions & 0 deletions src/tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
#[cfg(feature = "cairo-1-hints")]
use crate::vm::errors::cairo_run_errors::CairoRunError;
#[cfg(feature = "cairo-1-hints")]
use crate::vm::runners::cairo_runner::RunResources;
#[cfg(feature = "cairo-1-hints")]
use crate::{
hint_processor::cairo_1_hint_processor::hint_processor::Cairo1HintProcessor,
serde::deserialize_program::BuiltinName,
Expand Down Expand Up @@ -186,6 +190,7 @@ pub(self) fn run_cairo_1_entrypoint(
.run_from_entrypoint(
entrypoint_offset,
&entrypoint_args,
&mut None,
true,
Some(runner.program.shared_program_data.data.len() + program_extra_data.len()),
&mut vm,
Expand All @@ -206,6 +211,110 @@ pub(self) fn run_cairo_1_entrypoint(
assert_eq!(expected_retdata, &retdata);
}

#[cfg(feature = "cairo-1-hints")]
/// Equals to fn run_cairo_1_entrypoint
/// But with run_resources as an input
pub(self) fn run_cairo_1_entrypoint_with_run_resources(
program_content: &[u8],
entrypoint_offset: usize,
run_resources: &mut Option<RunResources>,
args: &[MaybeRelocatable],
) -> Result<Vec<Felt252>, CairoRunError> {
let contract_class: CasmContractClass = serde_json::from_slice(program_content).unwrap();
let mut hint_processor = Cairo1HintProcessor::new(&contract_class.hints);

let mut runner = CairoRunner::new(
&(contract_class.clone().try_into().unwrap()),
"all_cairo",
false,
)
.unwrap();
let mut vm = VirtualMachine::new(false);

let program_builtins = get_casm_contract_builtins(&contract_class, entrypoint_offset);
runner
.initialize_function_runner_cairo_1(&mut vm, &program_builtins)
.unwrap();

// Implicit Args
let syscall_segment = MaybeRelocatable::from(vm.add_memory_segment());

let builtins: Vec<&'static str> = runner
.get_program_builtins()
.iter()
.map(|b| b.name())
.collect();

let builtin_segment: Vec<MaybeRelocatable> = vm
.get_builtin_runners()
.iter()
.filter(|b| builtins.contains(&b.name()))
.flat_map(|b| b.initial_stack())
.collect();

let initial_gas = MaybeRelocatable::from(usize::MAX);

let mut implicit_args = builtin_segment;
implicit_args.extend([initial_gas]);
implicit_args.extend([syscall_segment]);

// Other args

// Load builtin costs
let builtin_costs: Vec<MaybeRelocatable> =
vec![0.into(), 0.into(), 0.into(), 0.into(), 0.into()];
let builtin_costs_ptr = vm.add_memory_segment();
vm.load_data(builtin_costs_ptr, &builtin_costs).unwrap();

// Load extra data
let core_program_end_ptr =
(runner.program_base.unwrap() + runner.program.shared_program_data.data.len()).unwrap();
let program_extra_data: Vec<MaybeRelocatable> =
vec![0x208B7FFF7FFF7FFE.into(), builtin_costs_ptr.into()];
vm.load_data(core_program_end_ptr, &program_extra_data)
.unwrap();

// Load calldata
let calldata_start = vm.add_memory_segment();
let calldata_end = vm.load_data(calldata_start, &args.to_vec()).unwrap();

// Create entrypoint_args

let mut entrypoint_args: Vec<CairoArg> = implicit_args
.iter()
.map(|m| CairoArg::from(m.clone()))
.collect();
entrypoint_args.extend([
MaybeRelocatable::from(calldata_start).into(),
MaybeRelocatable::from(calldata_end).into(),
]);
let entrypoint_args: Vec<&CairoArg> = entrypoint_args.iter().collect();

// Run contract entrypoint

runner.run_from_entrypoint(
entrypoint_offset,
&entrypoint_args,
run_resources,
true,
Some(runner.program.shared_program_data.data.len() + program_extra_data.len()),
&mut vm,
&mut hint_processor,
)?;

// Check return values
let return_values = vm.get_return_values(5).unwrap();
let retdata_start = return_values[3].get_relocatable().unwrap();
let retdata_end = return_values[4].get_relocatable().unwrap();
let retdata: Vec<Felt252> = vm
.get_integer_range(retdata_start, (retdata_end - retdata_start).unwrap())
.unwrap()
.iter()
.map(|c| c.clone().into_owned())
.collect();
Ok(retdata)
}

#[cfg(feature = "cairo-1-hints")]
fn get_casm_contract_builtins(
contract_class: &CasmContractClass,
Expand Down
2 changes: 2 additions & 0 deletions src/vm/errors/vm_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ pub enum VirtualMachineError {
EndOfProgram(usize),
#[error("Could not reach the end of the program. Executed steps: {0}.")]
StepsLimit(u64),
#[error("Could not reach the end of the program. RunResources has no remaining steps.")]
UnfinishedExecution,
#[error(transparent)]
TracerError(#[from] TraceError),
#[error(transparent)]
Expand Down
10 changes: 5 additions & 5 deletions src/vm/errors/vm_exception.rs
Original file line number Diff line number Diff line change
Expand Up @@ -643,7 +643,7 @@ mod test {

let end = cairo_runner.initialize(&mut vm).unwrap();
assert!(cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.is_err());

#[cfg(all(feature = "std"))]
Expand All @@ -657,7 +657,7 @@ mod test {

let end = cairo_runner.initialize(&mut vm).unwrap();
assert!(cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.is_err());
assert_eq!(get_traceback(&vm, &cairo_runner), Some(expected_traceback));
}
Expand Down Expand Up @@ -695,7 +695,7 @@ cairo_programs/bad_programs/bad_usort.cairo:64:5: (pc=0:60)

let end = cairo_runner.initialize(&mut vm).unwrap();
assert!(cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.is_err());
assert_eq!(
get_traceback(&vm, &cairo_runner),
Expand Down Expand Up @@ -854,7 +854,7 @@ cairo_programs/bad_programs/bad_range_check.cairo:11:5: (pc=0:6)

let end = cairo_runner.initialize(&mut vm).unwrap();
let error = cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.unwrap_err();
let vm_excepction = VmException::from_vm_error(&cairo_runner, &vm, error);
assert_eq!(vm_excepction.to_string(), expected_error_string);
Expand Down Expand Up @@ -899,7 +899,7 @@ cairo_programs/bad_programs/bad_usort.cairo:64:5: (pc=0:60)

let end = cairo_runner.initialize(&mut vm).unwrap();
let error = cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.unwrap_err();
let vm_excepction = VmException::from_vm_error(&cairo_runner, &vm, error);
assert_eq!(vm_excepction.to_string(), expected_error_string);
Expand Down
10 changes: 5 additions & 5 deletions src/vm/hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ mod tests {

let end = cairo_runner.initialize(&mut vm).unwrap();
assert!(cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.is_ok());
}

Expand Down Expand Up @@ -194,7 +194,7 @@ mod tests {

let end = cairo_runner.initialize(&mut vm).unwrap();
assert!(cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.is_err());

// Pre step fail
Expand All @@ -205,7 +205,7 @@ mod tests {

let end = cairo_runner.initialize(&mut vm).unwrap();
assert!(cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.is_err());

// Post step fail
Expand All @@ -216,7 +216,7 @@ mod tests {

let end = cairo_runner.initialize(&mut vm).unwrap();
assert!(cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.is_err());
}

Expand Down Expand Up @@ -267,7 +267,7 @@ mod tests {

let end = cairo_runner.initialize(&mut vm).unwrap();
assert!(cairo_runner
.run_until_pc(end, &mut vm, &mut hint_processor)
.run_until_pc(end, &mut None, &mut vm, &mut hint_processor)
.is_ok());
}
}
4 changes: 2 additions & 2 deletions src/vm/runners/builtin_runner/bitwise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ mod tests {
let address = cairo_runner.initialize(&mut vm).unwrap();

cairo_runner
.run_until_pc(address, &mut vm, &mut hint_processor)
.run_until_pc(address, &mut None, &mut vm, &mut hint_processor)
.unwrap();

assert_eq!(builtin.get_used_cells_and_allocated_size(&vm), Ok((0, 5)));
Expand Down Expand Up @@ -404,7 +404,7 @@ mod tests {
let address = cairo_runner.initialize(&mut vm).unwrap();

cairo_runner
.run_until_pc(address, &mut vm, &mut hint_processor)
.run_until_pc(address, &mut None, &mut vm, &mut hint_processor)
.unwrap();

assert_eq!(builtin.get_allocated_memory_units(&vm), Ok(5));
Expand Down
4 changes: 2 additions & 2 deletions src/vm/runners/builtin_runner/ec_op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ mod tests {
let address = cairo_runner.initialize(&mut vm).unwrap();

cairo_runner
.run_until_pc(address, &mut vm, &mut hint_processor)
.run_until_pc(address, &mut None, &mut vm, &mut hint_processor)
.unwrap();

assert_eq!(builtin.get_used_cells_and_allocated_size(&vm), Ok((0, 7)));
Expand Down Expand Up @@ -491,7 +491,7 @@ mod tests {
let address = cairo_runner.initialize(&mut vm).unwrap();

cairo_runner
.run_until_pc(address, &mut vm, &mut hint_processor)
.run_until_pc(address, &mut None, &mut vm, &mut hint_processor)
.unwrap();

assert_eq!(builtin.get_allocated_memory_units(&vm), Ok(7));
Expand Down
Loading