diff --git a/CHANGELOG.md b/CHANGELOG.md index d7a00ce998..e49d0e47fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,4 +20,9 @@ * Default implementation of compile_hint [#680](https://github.com/lambdaclass/cairo-rs/pull/680) * Internal changes: - * Make the `compile_hint` implementation which was in the `BuiltinHintProcessor` the default implementation in the trait. \ No newline at end of file + * Make the `compile_hint` implementation which was in the `BuiltinHintProcessor` the default implementation in the trait. + +* Add new error type `HintError` [#676](https://github.com/lambdaclass/cairo-rs/pull/676) + * Public Api changes: + * `HintProcessor::execute_hint()` now returns a `HintError` instead of a `VirtualMachineError` + * helper functions on `hint_processor_utils.rs` now return a `HintError` diff --git a/custom_hint_example/Cargo.lock b/custom_hint_example/Cargo.lock index da13d2547c..10a3882182 100644 --- a/custom_hint_example/Cargo.lock +++ b/custom_hint_example/Cargo.lock @@ -79,6 +79,17 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +[[package]] +name = "bigdecimal" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aaf33151a6429fe9211d1b276eafdf70cdff28b071e76c0b0e1503221ea3744" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "bincode" version = "1.3.3" @@ -134,6 +145,7 @@ dependencies = [ "num-integer", "num-traits", "parse-hyperlinks", + "rand_core", "serde", "serde_bytes", "serde_json", @@ -333,15 +345,6 @@ dependencies = [ "digest 0.9.0", ] -[[package]] -name = "html-escape" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e7479fa1ef38eb49fb6a42c426be515df2d063f06cb8efd3e50af073dbc26c" -dependencies = [ - "utf8-width", -] - [[package]] name = "indexmap" version = "1.9.1" @@ -487,10 +490,7 @@ checksum = "9ff7415e9ae3fff1225851df9e0d9e4e5479f947619774677a63572e55e80eff" name = "parse-hyperlinks" version = "0.23.4" dependencies = [ - "html-escape", "nom", - "percent-encoding", - "thiserror", ] [[package]] @@ -499,12 +499,6 @@ version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9423e2b32f7a043629287a536f21951e8c6a82482d0acb1eeebfc90bc2225b22" -[[package]] -name = "percent-encoding" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" - [[package]] name = "pest" version = "2.3.0" @@ -585,9 +579,9 @@ dependencies = [ [[package]] name = "rand_core" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ "getrandom", ] @@ -712,9 +706,9 @@ dependencies = [ [[package]] name = "starknet-crypto" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92d5ba05430fcd7c107ad9e4433bb3958722b13d97a44fd07a18dcf0eb6da667" +checksum = "be7d6b2c959fde2a10dbc31d54bdd0307eecb7ef6c05c23a0263e65b57b3e18a" dependencies = [ "crypto-bigint", "hex", @@ -724,21 +718,45 @@ dependencies = [ "num-traits", "rfc6979", "sha2 0.9.9", + "starknet-crypto-codegen", + "starknet-curve", "starknet-ff", "thiserror", "zeroize", ] [[package]] -name = "starknet-ff" +name = "starknet-crypto-codegen" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a80865f37a0dcd198f427356d939f1495144c26ed5123b1418ef33a63f82655" +checksum = "6569d70430f0f6edc41f6820d00acf63356e6308046ca01e57eeac22ad258c47" +dependencies = [ + "starknet-curve", + "starknet-ff", + "syn", +] + +[[package]] +name = "starknet-curve" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84be6079d3060fdbd8b5335574fef3d3783fa2f7ee6474d08ae0c1e4b0a29ba4" +dependencies = [ + "starknet-ff", +] + +[[package]] +name = "starknet-ff" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5874510620214ebeac50915b01d67437d8ca10a6682b1de85b93cd01157b58eb" dependencies = [ "ark-ff", + "bigdecimal", "crypto-bigint", "getrandom", "hex", + "num-bigint", "serde", "thiserror", ] @@ -837,12 +855,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" -[[package]] -name = "utf8-width" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5190c9442dcdaf0ddd50f37420417d219ae5261bbf5db120d0f9bab996c9cba1" - [[package]] name = "version_check" version = "0.9.4" diff --git a/custom_hint_example/src/main.rs b/custom_hint_example/src/main.rs index c2da588a1c..8b102d263e 100644 --- a/custom_hint_example/src/main.rs +++ b/custom_hint_example/src/main.rs @@ -6,10 +6,11 @@ use cairo_rs::hint_processor::builtin_hint_processor::hint_utils::get_integer_fr use cairo_rs::hint_processor::hint_processor_definition::HintReference; use cairo_rs::types::exec_scope::ExecutionScopes; use cairo_rs::serde::deserialize_program::ApTracking; -use cairo_rs::vm::{errors::vm_errors::VirtualMachineError, vm_core::VirtualMachine}; +use cairo_rs::vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}; use num_bigint::BigInt; use std::collections::HashMap; use std::path::Path; +use std::rc::Rc; // Create the function that implements the custom hint fn print_a_hint( @@ -18,7 +19,7 @@ fn print_a_hint( ids_data: &HashMap, ap_tracking: &ApTracking, _constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a = get_integer_from_var_name("a", vm, ids_data, ap_tracking)?; println!("{}", a); Ok(()) @@ -32,7 +33,7 @@ fn main() { let mut hint_processor = BuiltinHintProcessor::new_empty(); //Add the custom hint, together with the Python code - hint_processor.add_hint(String::from("print(ids.a)"), hint); + hint_processor.add_hint(String::from("print(ids.a)"), Rc::new(hint)); //Run the cairo program cairo_run( @@ -40,6 +41,8 @@ fn main() { "main", false, false, + "all", + false, &mut hint_processor, ) .expect("Couldn't run program"); diff --git a/src/hint_processor/builtin_hint_processor/blake2s_utils.rs b/src/hint_processor/builtin_hint_processor/blake2s_utils.rs index 38ed5730c7..9cc983b35d 100644 --- a/src/hint_processor/builtin_hint_processor/blake2s_utils.rs +++ b/src/hint_processor/builtin_hint_processor/blake2s_utils.rs @@ -6,6 +6,7 @@ use crate::hint_processor::builtin_hint_processor::hint_utils::{ }; use crate::hint_processor::hint_processor_definition::HintReference; use crate::hint_processor::hint_processor_utils::bigint_to_u32; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use num_traits::ToPrimitive; use std::borrow::Cow; @@ -18,14 +19,14 @@ use num_bigint::BigInt; fn get_fixed_size_u32_array( h_range: &Vec>, -) -> Result<[u32; T], VirtualMachineError> { +) -> Result<[u32; T], HintError> { let mut u32_vec = Vec::::with_capacity(h_range.len()); for num in h_range { - u32_vec.push(num.to_u32().ok_or(VirtualMachineError::BigintToU32Fail)?); + u32_vec.push(num.to_u32().ok_or(HintError::BigintToU32Fail)?); } u32_vec .try_into() - .map_err(|_| VirtualMachineError::FixedSizeArrayFail(T)) + .map_err(|_| HintError::FixedSizeArrayFail(T)) } fn get_maybe_relocatable_array_from_u32(array: &Vec) -> Vec { @@ -44,10 +45,7 @@ Computes the blake2s compress function and fills the value in the right position output_ptr should point to the middle of an instance, right after initial_state, message, t, f, which should all have a value at this point, and right before the output portion which will be written by this function.*/ -fn compute_blake2s_func( - vm: &mut VirtualMachine, - output_rel: Relocatable, -) -> Result<(), VirtualMachineError> { +fn compute_blake2s_func(vm: &mut VirtualMachine, output_rel: Relocatable) -> Result<(), HintError> { let h = get_fixed_size_u32_array::<8>(&vm.get_integer_range(&(output_rel.sub(26)?), 8)?)?; let message = get_fixed_size_u32_array::<16>(&vm.get_integer_range(&(output_rel.sub(18)?), 16)?)?; @@ -69,7 +67,7 @@ pub fn compute_blake2s( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let output = get_ptr_from_var_name("output", vm, ids_data, ap_tracking)?; compute_blake2s_func(vm, output) } @@ -100,7 +98,7 @@ pub fn finalize_blake2s( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { const N_PACKED_INSTANCES: usize = 7; let blake2s_ptr_end = get_ptr_from_var_name("blake2s_ptr_end", vm, ids_data, ap_tracking)?; let message: [u32; 16] = [0; 16]; @@ -132,7 +130,7 @@ pub fn blake2s_add_uint256( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Get variables from ids let data_ptr = get_ptr_from_var_name("data", vm, ids_data, ap_tracking)?; let low_addr = get_relocatable_from_var_name("low", vm, ids_data, ap_tracking)?; @@ -179,7 +177,7 @@ pub fn blake2s_add_uint256_bigend( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Get variables from ids let data_ptr = get_ptr_from_var_name("data", vm, ids_data, ap_tracking)?; let low_addr = get_relocatable_from_var_name("low", vm, ids_data, ap_tracking)?; @@ -225,6 +223,7 @@ mod tests { use crate::relocatable; use crate::types::exec_scope::ExecutionScopes; use crate::utils::test_utils::*; + use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use crate::vm::vm_memory::memory::Memory; use crate::{bigint, vm::errors::memory_errors::MemoryError}; @@ -247,7 +246,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::CantSubOffset(5, 26)) + Err(HintError::Internal(VirtualMachineError::CantSubOffset( + 5, 26 + ))) ); } @@ -266,9 +267,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((2, 0)) - )) + ))) ); } @@ -286,8 +287,8 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedRelocatable( - MaybeRelocatable::from((1, 0)) + Err(HintError::Internal( + VirtualMachineError::ExpectedRelocatable(MaybeRelocatable::from((1, 0))) )) ); } @@ -316,7 +317,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::BigintToU32Fail) + Err(HintError::BigintToU32Fail) ); } @@ -334,9 +335,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((2, 0)) - )) + ))) ); } @@ -398,13 +399,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((2, 0)), MaybeRelocatable::from((2, 0)), MaybeRelocatable::from(bigint!(1795745351)) ) - )) + ))) ); } @@ -418,7 +419,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, HashMap::new(), hint_code), - Err(VirtualMachineError::FailedToGetIds) + Err(HintError::FailedToGetIds) ); } diff --git a/src/hint_processor/builtin_hint_processor/builtin_hint_processor_definition.rs b/src/hint_processor/builtin_hint_processor/builtin_hint_processor_definition.rs index f37e67939a..1064a314fd 100644 --- a/src/hint_processor/builtin_hint_processor/builtin_hint_processor_definition.rs +++ b/src/hint_processor/builtin_hint_processor/builtin_hint_processor_definition.rs @@ -33,7 +33,7 @@ use crate::hint_processor::builtin_hint_processor::uint256_utils::{ use crate::hint_processor::hint_processor_definition::{HintProcessor, HintReference}; use crate::serde::deserialize_program::ApTracking; use crate::types::exec_scope::ExecutionScopes; -use crate::vm::errors::vm_errors::VirtualMachineError; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use num_bigint::BigInt; use std::any::Any; @@ -90,7 +90,7 @@ pub struct HintFunc( &HashMap, &ApTracking, &HashMap, - ) -> Result<(), VirtualMachineError> + ) -> Result<(), HintError> + Sync, >, ); @@ -120,10 +120,10 @@ impl HintProcessor for BuiltinHintProcessor { exec_scopes: &mut ExecutionScopes, hint_data: &Box, constants: &HashMap, - ) -> Result<(), VirtualMachineError> { + ) -> Result<(), HintError> { let hint_data = hint_data .downcast_ref::() - .ok_or(VirtualMachineError::WrongHintData)?; + .ok_or(HintError::WrongHintData)?; if let Some(hint_func) = self.extra_hints.get(&hint_data.code) { return hint_func.0( @@ -434,7 +434,7 @@ impl HintProcessor for BuiltinHintProcessor { hint_code::TEMPORARY_ARRAY => { temporary_array(vm, &hint_data.ids_data, &hint_data.ap_tracking) } - code => Err(VirtualMachineError::UnknownHint(code.to_string())), + code => Err(HintError::UnknownHint(code.to_string())), } } } @@ -444,6 +444,7 @@ mod tests { use crate::types::exec_scope::ExecutionScopes; use crate::types::relocatable::MaybeRelocatable; use crate::utils::test_utils::*; + use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::errors::{exec_scope_errors::ExecScopeError, memory_errors::MemoryError}; use crate::vm::vm_core::VirtualMachine; use crate::vm::vm_memory::memory::Memory; @@ -494,13 +495,13 @@ mod tests { //ids and references are not needed for this test assert_eq!( run_hint!(vm, HashMap::new(), hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 6)), MaybeRelocatable::from((1, 6)), MaybeRelocatable::from((3, 0)) ) - )) + ))) ); } @@ -510,7 +511,7 @@ mod tests { let mut vm = vm!(); assert_eq!( run_hint!(vm, HashMap::new(), hint_code), - Err(VirtualMachineError::UnknownHint(hint_code.to_string())), + Err(HintError::UnknownHint(hint_code.to_string())), ); } @@ -543,9 +544,9 @@ mod tests { let ids_data = ids_data!["len"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 1)) - )) + ))) ); } @@ -580,9 +581,7 @@ mod tests { let ids_data = ids_data!["continue_copying"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::VariableNotInScopeError( - "n".to_string() - )) + Err(HintError::VariableNotInScopeError("n".to_string())) ); } @@ -603,13 +602,13 @@ mod tests { let ids_data = ids_data!["continue_copying"]; assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 1)), MaybeRelocatable::from(bigint!(5)), MaybeRelocatable::from(bigint!(0)) ) - )) + ))) ); } @@ -635,7 +634,7 @@ mod tests { add_segments!(vm, 1); assert_eq!( run_hint!(vm, HashMap::new(), hint_code), - Err(VirtualMachineError::MainScopeError( + Err(HintError::FromScopeError( ExecScopeError::ExitMainScopeError )) ); @@ -700,7 +699,7 @@ mod tests { let mut exec_scopes = scope![("__keccak_max_size", bigint!(2))]; assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::KeccakMaxSize(bigint!(5), bigint!(2))) + Err(HintError::KeccakMaxSize(bigint!(5), bigint!(2))) ); } @@ -746,7 +745,7 @@ mod tests { let mut exec_scopes = scope![("__keccak_max_size", bigint!(10))]; assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::InvalidWordSize(bigint!(-1))) + Err(HintError::InvalidWordSize(bigint!(-1))) ); } @@ -788,7 +787,7 @@ mod tests { let ids_data = non_continuous_ids_data![("keccak_state", -7), ("high", -3), ("low", -2)]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::NoneInMemoryRange) + Err(HintError::Internal(VirtualMachineError::NoneInMemoryRange)) ); } @@ -818,7 +817,7 @@ mod tests { _ids_data: &HashMap, _ap_tracking: &ApTracking, _constants: &HashMap, - ) -> Result<(), VirtualMachineError> { + ) -> Result<(), HintError> { exec_scopes.enter_scope(HashMap::new()); Ok(()) } diff --git a/src/hint_processor/builtin_hint_processor/cairo_keccak/keccak_hints.rs b/src/hint_processor/builtin_hint_processor/cairo_keccak/keccak_hints.rs index 7c8e07238d..3264922b5b 100644 --- a/src/hint_processor/builtin_hint_processor/cairo_keccak/keccak_hints.rs +++ b/src/hint_processor/builtin_hint_processor/cairo_keccak/keccak_hints.rs @@ -1,6 +1,7 @@ use crate::hint_processor::builtin_hint_processor::hint_utils::get_integer_from_var_name; use crate::hint_processor::builtin_hint_processor::hint_utils::get_ptr_from_var_name; use crate::hint_processor::builtin_hint_processor::hint_utils::insert_value_into_ap; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use crate::{ bigint, hint_processor::hint_processor_definition::HintReference, @@ -34,7 +35,7 @@ pub fn keccak_write_args( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let inputs_ptr = get_ptr_from_var_name("inputs", vm, ids_data, ap_tracking)?; let low = get_integer_from_var_name("low", vm, ids_data, ap_tracking)?; @@ -69,7 +70,7 @@ pub fn compare_bytes_in_word_nondet( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let n_bytes = get_integer_from_var_name("n_bytes", vm, ids_data, ap_tracking)?; let n_bytes = n_bytes.as_ref(); @@ -80,7 +81,7 @@ pub fn compare_bytes_in_word_nondet( // bigint!(BYTES_INTO_WORD) into a lazy_static! let bytes_in_word = constants .get(BYTES_IN_WORD) - .ok_or(VirtualMachineError::MissingConstant(BYTES_IN_WORD))?; + .ok_or(HintError::MissingConstant(BYTES_IN_WORD))?; let value = bigint!((n_bytes < bytes_in_word) as usize); insert_value_into_ap(vm, value) } @@ -98,16 +99,13 @@ pub fn compare_keccak_full_rate_in_bytes_nondet( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let n_bytes = get_integer_from_var_name("n_bytes", vm, ids_data, ap_tracking)?; let n_bytes = n_bytes.as_ref(); - let keccak_full_rate_in_bytes = - constants - .get(KECCAK_FULL_RATE_IN_BYTES) - .ok_or(VirtualMachineError::MissingConstant( - KECCAK_FULL_RATE_IN_BYTES, - ))?; + let keccak_full_rate_in_bytes = constants + .get(KECCAK_FULL_RATE_IN_BYTES) + .ok_or(HintError::MissingConstant(KECCAK_FULL_RATE_IN_BYTES))?; let value = bigint!((n_bytes >= keccak_full_rate_in_bytes) as usize); insert_value_into_ap(vm, value) } @@ -129,16 +127,13 @@ pub fn block_permutation( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { - let keccak_state_size_felts = - constants - .get(KECCAK_STATE_SIZE_FELTS) - .ok_or(VirtualMachineError::MissingConstant( - KECCAK_STATE_SIZE_FELTS, - ))?; +) -> Result<(), HintError> { + let keccak_state_size_felts = constants + .get(KECCAK_STATE_SIZE_FELTS) + .ok_or(HintError::MissingConstant(KECCAK_STATE_SIZE_FELTS))?; if keccak_state_size_felts >= &bigint!(100) { - return Err(VirtualMachineError::InvalidKeccakStateSizeFelts( + return Err(HintError::InvalidKeccakStateSizeFelts( keccak_state_size_felts.clone(), )); } @@ -186,25 +181,22 @@ pub fn cairo_keccak_finalize( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { - let keccak_state_size_felts = - constants - .get(KECCAK_STATE_SIZE_FELTS) - .ok_or(VirtualMachineError::MissingConstant( - KECCAK_STATE_SIZE_FELTS, - ))?; +) -> Result<(), HintError> { + let keccak_state_size_felts = constants + .get(KECCAK_STATE_SIZE_FELTS) + .ok_or(HintError::MissingConstant(KECCAK_STATE_SIZE_FELTS))?; let block_size = constants .get(BLOCK_SIZE) - .ok_or(VirtualMachineError::MissingConstant(BLOCK_SIZE))?; + .ok_or(HintError::MissingConstant(BLOCK_SIZE))?; if keccak_state_size_felts >= &bigint!(100) { - return Err(VirtualMachineError::InvalidKeccakStateSizeFelts( + return Err(HintError::InvalidKeccakStateSizeFelts( keccak_state_size_felts.clone(), )); } if block_size >= &bigint!(10) { - return Err(VirtualMachineError::InvalidBlockSize(block_size.clone())); + return Err(HintError::InvalidBlockSize(block_size.clone())); } let keccak_state_size_felts = keccak_state_size_felts.to_usize().unwrap(); @@ -236,7 +228,7 @@ pub fn cairo_keccak_finalize( // of u64. Raises error if there are None's or if MaybeRelocatables are not Bigints. pub(crate) fn maybe_reloc_vec_to_u64_array( vec: &[Option>], -) -> Result, VirtualMachineError> { +) -> Result, HintError> { let array = vec .iter() .map(|n| match n { @@ -302,7 +294,10 @@ mod tests { //Create ids let ids_data = ids_data!["low", "high", "inputs"]; let error = run_hint!(vm, ids_data, hint_code); - assert!(matches!(error, Err(VirtualMachineError::MemoryError(_)))); + assert!(matches!( + error, + Err(HintError::Internal(VirtualMachineError::MemoryError(_))) + )); } #[test] diff --git a/src/hint_processor/builtin_hint_processor/dict_hint_utils.rs b/src/hint_processor/builtin_hint_processor/dict_hint_utils.rs index 4d8b9afe26..990bc712ca 100644 --- a/src/hint_processor/builtin_hint_processor/dict_hint_utils.rs +++ b/src/hint_processor/builtin_hint_processor/dict_hint_utils.rs @@ -1,4 +1,7 @@ -use crate::{types::exec_scope::ExecutionScopes, vm::vm_core::VirtualMachine}; +use crate::{ + types::exec_scope::ExecutionScopes, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, +}; use std::{any::Any, cell::RefCell, collections::HashMap, rc::Rc}; use num_bigint::BigInt; @@ -13,7 +16,6 @@ use crate::{ hint_processor_definition::HintReference, }, serde::deserialize_program::ApTracking, - vm::errors::vm_errors::VirtualMachineError, }; use super::dict_manager::DictManager; @@ -45,9 +47,9 @@ is not available pub fn dict_new( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Get initial dictionary from scope (defined by an earlier hint) - let initial_dict = copy_initial_dict(exec_scopes).ok_or(VirtualMachineError::NoInitialDict)?; + let initial_dict = copy_initial_dict(exec_scopes).ok_or(HintError::NoInitialDict)?; //Check if there is a dict manager in scope, create it if there isnt one let base = if let Ok(dict_manager) = exec_scopes.get_dict_manager() { dict_manager.borrow_mut().new_dict(vm, initial_dict)? @@ -75,7 +77,7 @@ pub fn default_dict_new( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Check that ids contains the reference id for each variable used by the hint let default_value = get_integer_from_var_name("default_value", vm, ids_data, ap_tracking)?.into_owned(); @@ -105,7 +107,7 @@ pub fn dict_read( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let key = get_integer_from_var_name("key", vm, ids_data, ap_tracking)?; let key = key.as_ref(); let dict_ptr = get_ptr_from_var_name("dict_ptr", vm, ids_data, ap_tracking)?; @@ -128,7 +130,7 @@ pub fn dict_write( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let key = get_integer_from_var_name("key", vm, ids_data, ap_tracking)?; let new_value = get_integer_from_var_name("new_value", vm, ids_data, ap_tracking)?; let key = key.as_ref(); @@ -169,7 +171,7 @@ pub fn dict_update( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let key = get_integer_from_var_name("key", vm, ids_data, ap_tracking)?; let prev_value = get_integer_from_var_name("prev_value", vm, ids_data, ap_tracking)?; let new_value = get_integer_from_var_name("new_value", vm, ids_data, ap_tracking)?; @@ -182,7 +184,7 @@ pub fn dict_update( //Check that prev_value is equal to the current value at the given key let current_value = tracker.get_value(key.as_ref())?; if current_value != prev_value.as_ref() { - return Err(VirtualMachineError::WrongPrevValue( + return Err(HintError::WrongPrevValue( prev_value.into_owned(), current_value.clone(), key.into_owned(), @@ -209,7 +211,7 @@ pub fn dict_squash_copy_dict( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let dict_accesses_end = get_ptr_from_var_name("dict_accesses_end", vm, ids_data, ap_tracking)?; let dict_manager_ref = exec_scopes.get_dict_manager()?; let dict_manager = dict_manager_ref.borrow(); @@ -238,7 +240,7 @@ pub fn dict_squash_update_ptr( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let squashed_dict_start = get_ptr_from_var_name("squashed_dict_start", vm, ids_data, ap_tracking)?; let squashed_dict_end = get_ptr_from_var_name("squashed_dict_end", vm, ids_data, ap_tracking)?; @@ -257,6 +259,7 @@ mod tests { use crate::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData; use crate::hint_processor::hint_processor_definition::HintProcessor; use crate::types::exec_scope::ExecutionScopes; + use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::vm_memory::memory::Memory; use std::collections::HashMap; @@ -307,7 +310,7 @@ mod tests { //ids and references are not needed for this test assert_eq!( run_hint!(vm, HashMap::new(), hint_code), - Err(VirtualMachineError::NoInitialDict) + Err(HintError::NoInitialDict) ); } @@ -320,13 +323,13 @@ mod tests { //ids and references are not needed for this test assert_eq!( run_hint!(vm, HashMap::new(), hint_code, &mut exec_scopes), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 0)), MaybeRelocatable::from(bigint!(1)), MaybeRelocatable::from((0, 0)) ) - )) + ))) ); } @@ -371,7 +374,7 @@ mod tests { dict_manager!(&mut exec_scopes, 2, (5, 12)); assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::NoValueForKey(bigint!(6))) + Err(HintError::NoValueForKey(bigint!(6))) ); } #[test] @@ -390,7 +393,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::NoDictTracker(2)) + Err(HintError::NoDictTracker(2)) ); } @@ -434,9 +437,9 @@ mod tests { let ids_data = ids_data!["default_value"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 0)) - )) + ))) ); } @@ -542,7 +545,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::NoValueForKey(bigint!(5))) + Err(HintError::NoValueForKey(bigint!(5))) ); } @@ -613,7 +616,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::WrongPrevValue( + Err(HintError::WrongPrevValue( bigint!(11), bigint!(10), bigint!(5) @@ -640,7 +643,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::NoValueForKey(bigint!(6),)) + Err(HintError::NoValueForKey(bigint!(6),)) ); } @@ -711,7 +714,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::WrongPrevValue( + Err(HintError::WrongPrevValue( bigint!(11), bigint!(10), bigint!(5) @@ -738,7 +741,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::WrongPrevValue( + Err(HintError::WrongPrevValue( bigint!(10), bigint!(17), bigint!(6) @@ -845,7 +848,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::NoDictTracker(2)) + Err(HintError::NoDictTracker(2)) ); } @@ -865,7 +868,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::NoDictTracker(2)) + Err(HintError::NoDictTracker(2)) ); } @@ -903,7 +906,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::MismatchedDictPtr( + Err(HintError::MismatchedDictPtr( relocatable!(2, 0), relocatable!(2, 3) )) diff --git a/src/hint_processor/builtin_hint_processor/dict_manager.rs b/src/hint_processor/builtin_hint_processor/dict_manager.rs index 249b35349b..1357457d5e 100644 --- a/src/hint_processor/builtin_hint_processor/dict_manager.rs +++ b/src/hint_processor/builtin_hint_processor/dict_manager.rs @@ -7,7 +7,9 @@ use num_traits::Signed; use crate::{ types::relocatable::{MaybeRelocatable, Relocatable}, vm::{ - errors::{memory_errors::MemoryError, vm_errors::VirtualMachineError}, + errors::{ + hint_errors::HintError, memory_errors::MemoryError, vm_errors::VirtualMachineError, + }, vm_core::VirtualMachine, }, }; @@ -76,18 +78,18 @@ impl DictManager { &mut self, vm: &mut VirtualMachine, initial_dict: HashMap, - ) -> Result { + ) -> Result { let base = vm.add_memory_segment(); if self.trackers.contains_key(&base.segment_index) { - return Err(VirtualMachineError::CantCreateDictionaryOnTakenSegment( + return Err(HintError::CantCreateDictionaryOnTakenSegment( base.segment_index, )); } if base.segment_index < 0 { - return Err(VirtualMachineError::MemoryError( + Err(VirtualMachineError::MemoryError( MemoryError::AddressInTemporarySegment(base.segment_index), - )); + ))?; }; let floored_initial = initial_dict @@ -117,10 +119,10 @@ impl DictManager { vm: &mut VirtualMachine, default_value: &BigInt, initial_dict: Option>, - ) -> Result { + ) -> Result { let base = vm.add_memory_segment(); if self.trackers.contains_key(&base.segment_index) { - return Err(VirtualMachineError::CantCreateDictionaryOnTakenSegment( + return Err(HintError::CantCreateDictionaryOnTakenSegment( base.segment_index, )); } @@ -135,31 +137,25 @@ impl DictManager { pub fn get_tracker_mut( &mut self, dict_ptr: &Relocatable, - ) -> Result<&mut DictTracker, VirtualMachineError> { + ) -> Result<&mut DictTracker, HintError> { let tracker = self .trackers .get_mut(&dict_ptr.segment_index) - .ok_or(VirtualMachineError::NoDictTracker(dict_ptr.segment_index))?; + .ok_or(HintError::NoDictTracker(dict_ptr.segment_index))?; if tracker.current_ptr != *dict_ptr { - return Err(VirtualMachineError::MismatchedDictPtr( - tracker.current_ptr, - *dict_ptr, - )); + return Err(HintError::MismatchedDictPtr(tracker.current_ptr, *dict_ptr)); } Ok(tracker) } //Returns the tracker which's current_ptr matches with the given dict_ptr - pub fn get_tracker(&self, dict_ptr: &Relocatable) -> Result<&DictTracker, VirtualMachineError> { + pub fn get_tracker(&self, dict_ptr: &Relocatable) -> Result<&DictTracker, HintError> { let tracker = self .trackers .get(&dict_ptr.segment_index) - .ok_or(VirtualMachineError::NoDictTracker(dict_ptr.segment_index))?; + .ok_or(HintError::NoDictTracker(dict_ptr.segment_index))?; if tracker.current_ptr != *dict_ptr { - return Err(VirtualMachineError::MismatchedDictPtr( - tracker.current_ptr, - *dict_ptr, - )); + return Err(HintError::MismatchedDictPtr(tracker.current_ptr, *dict_ptr)); } Ok(tracker) } @@ -215,10 +211,10 @@ impl DictTracker { } } - pub fn get_value(&mut self, key: &BigInt) -> Result<&BigInt, VirtualMachineError> { + pub fn get_value(&mut self, key: &BigInt) -> Result<&BigInt, HintError> { self.data .get(key) - .ok_or_else(|| VirtualMachineError::NoValueForKey(key.clone())) + .ok_or_else(|| HintError::NoValueForKey(key.clone())) } pub fn insert_value(&mut self, key: &BigInt, val: &BigInt) { @@ -342,7 +338,7 @@ mod tests { let mut vm = vm!(); assert_eq!( dict_manager.new_dict(&mut vm, HashMap::new()), - Err(VirtualMachineError::CantCreateDictionaryOnTakenSegment(0)) + Err(HintError::CantCreateDictionaryOnTakenSegment(0)) ); } @@ -356,7 +352,7 @@ mod tests { let mut vm = vm!(); assert_eq!( dict_manager.new_dict(&mut vm, HashMap::new()), - Err(VirtualMachineError::CantCreateDictionaryOnTakenSegment(0)) + Err(HintError::CantCreateDictionaryOnTakenSegment(0)) ); } diff --git a/src/hint_processor/builtin_hint_processor/find_element_hint.rs b/src/hint_processor/builtin_hint_processor/find_element_hint.rs index 19cdd59f57..33d125bd64 100644 --- a/src/hint_processor/builtin_hint_processor/find_element_hint.rs +++ b/src/hint_processor/builtin_hint_processor/find_element_hint.rs @@ -10,7 +10,10 @@ use crate::{ }, serde::deserialize_program::ApTracking, types::exec_scope::ExecutionScopes, - vm::{errors::vm_errors::VirtualMachineError, vm_core::VirtualMachine}, + vm::{ + errors::{hint_errors::HintError, vm_errors::VirtualMachineError}, + vm_core::VirtualMachine, + }, }; use num_bigint::BigInt; use num_traits::{Signed, ToPrimitive}; @@ -21,7 +24,7 @@ pub fn find_element( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let key = get_integer_from_var_name("key", vm, ids_data, ap_tracking)?; let elm_size_bigint = get_integer_from_var_name("elm_size", vm, ids_data, ap_tracking)?; let n_elms = get_integer_from_var_name("n_elms", vm, ids_data, ap_tracking)?; @@ -29,21 +32,19 @@ pub fn find_element( let find_element_index = exec_scopes.get::("find_element_index").ok(); let elm_size = elm_size_bigint .to_usize() - .ok_or_else(|| VirtualMachineError::ValueOutOfRange(elm_size_bigint.as_ref().clone()))?; + .ok_or_else(|| HintError::ValueOutOfRange(elm_size_bigint.as_ref().clone()))?; if elm_size == 0 { - return Err(VirtualMachineError::ValueOutOfRange( - elm_size_bigint.into_owned(), - )); + return Err(HintError::ValueOutOfRange(elm_size_bigint.into_owned())); } if let Some(find_element_index_value) = find_element_index { let find_element_index_usize = bigint_to_usize(&find_element_index_value)?; let found_key = vm .get_integer(&(array_start + (elm_size * find_element_index_usize))) - .map_err(|_| VirtualMachineError::KeyNotFound)?; + .map_err(|_| HintError::KeyNotFound)?; if found_key.as_ref() != key.as_ref() { - return Err(VirtualMachineError::InvalidIndex( + return Err(HintError::InvalidIndex( find_element_index_value, key.into_owned(), found_key.into_owned(), @@ -54,12 +55,12 @@ pub fn find_element( Ok(()) } else { if n_elms.is_negative() { - return Err(VirtualMachineError::ValueOutOfRange(n_elms.into_owned())); + return Err(HintError::ValueOutOfRange(n_elms.into_owned())); } if let Ok(find_element_max_size) = exec_scopes.get_ref::("find_element_max_size") { if n_elms.as_ref() > find_element_max_size { - return Err(VirtualMachineError::FindElemMaxSize( + return Err(HintError::FindElemMaxSize( find_element_max_size.clone(), n_elms.into_owned(), )); @@ -72,14 +73,14 @@ pub fn find_element( for i in 0..n_elms_iter { let iter_key = vm .get_integer(&(array_start + (elm_size * i as usize))) - .map_err(|_| VirtualMachineError::KeyNotFound)?; + .map_err(|_| HintError::KeyNotFound)?; if iter_key.as_ref() == key.as_ref() { return insert_value_from_var_name("index", bigint!(i), vm, ids_data, ap_tracking); } } - Err(VirtualMachineError::NoValueForKey(key.into_owned())) + Err(HintError::NoValueForKey(key.into_owned())) } } @@ -88,7 +89,7 @@ pub fn search_sorted_lower( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let find_element_max_size = exec_scopes.get::("find_element_max_size"); let n_elms = get_integer_from_var_name("n_elms", vm, ids_data, ap_tracking)?; let rel_array_ptr = get_relocatable_from_var_name("array_ptr", vm, ids_data, ap_tracking)?; @@ -96,16 +97,16 @@ pub fn search_sorted_lower( let key = get_integer_from_var_name("key", vm, ids_data, ap_tracking)?; if !elm_size.is_positive() { - return Err(VirtualMachineError::ValueOutOfRange(elm_size.into_owned())); + return Err(HintError::ValueOutOfRange(elm_size.into_owned())); } if n_elms.is_negative() { - return Err(VirtualMachineError::ValueOutOfRange(n_elms.into_owned())); + return Err(HintError::ValueOutOfRange(n_elms.into_owned())); } if let Ok(find_element_max_size) = find_element_max_size { if n_elms.as_ref() > &find_element_max_size { - return Err(VirtualMachineError::FindElemMaxSize( + return Err(HintError::FindElemMaxSize( find_element_max_size, n_elms.into_owned(), )); @@ -113,10 +114,8 @@ pub fn search_sorted_lower( } let mut array_iter = vm.get_relocatable(&rel_array_ptr)?; - let n_elms_usize = n_elms.to_usize().ok_or(VirtualMachineError::KeyNotFound)?; - let elm_size_usize = elm_size - .to_usize() - .ok_or(VirtualMachineError::KeyNotFound)?; + let n_elms_usize = n_elms.to_usize().ok_or(HintError::KeyNotFound)?; + let elm_size_usize = elm_size.to_usize().ok_or(HintError::KeyNotFound)?; for i in 0..n_elms_usize { let value = vm.get_integer(&array_iter)?; @@ -239,7 +238,7 @@ mod tests { )])); assert_eq!( run_hint!(vm, ids_data, hint_code::FIND_ELEMENT), - Err(VirtualMachineError::NoValueForKey(bigint!(7))) + Err(HintError::NoValueForKey(bigint!(7))) ); } @@ -249,7 +248,7 @@ mod tests { let mut exec_scopes = scope![("find_element_index", bigint!(2))]; assert_eq!( run_hint!(vm, ids_data, hint_code::FIND_ELEMENT, &mut exec_scopes), - Err(VirtualMachineError::KeyNotFound) + Err(HintError::KeyNotFound) ); } @@ -260,9 +259,9 @@ mod tests { let ids_data = ids_data!["array_ptr", "elm_size", "n_elms", "index", "key"]; assert_eq!( run_hint!(vm, ids_data, hint_code::FIND_ELEMENT), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 4)) - )) + ))) ); } @@ -274,9 +273,9 @@ mod tests { )])); assert_eq!( run_hint!(vm, ids_data, hint_code::FIND_ELEMENT), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 1)) - )) + ))) ); } @@ -288,7 +287,7 @@ mod tests { )])); assert_eq!( run_hint!(vm, ids_data, hint_code::FIND_ELEMENT), - Err(VirtualMachineError::ValueOutOfRange(bigint!(0))) + Err(HintError::ValueOutOfRange(bigint!(0))) ); } @@ -300,7 +299,7 @@ mod tests { )])); assert_eq!( run_hint!(vm, ids_data, hint_code::FIND_ELEMENT), - Err(VirtualMachineError::ValueOutOfRange(bigint!(-1))) + Err(HintError::ValueOutOfRange(bigint!(-1))) ); } @@ -311,7 +310,9 @@ mod tests { init_vm_ids_data(HashMap::from([("n_elms".to_string(), relocatable.clone())])); assert_eq!( run_hint!(vm, ids_data, hint_code::FIND_ELEMENT), - Err(VirtualMachineError::ExpectedInteger(relocatable)) + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( + relocatable + ))) ); } @@ -323,7 +324,7 @@ mod tests { )])); assert_eq!( run_hint!(vm, ids_data, hint_code::FIND_ELEMENT), - Err(VirtualMachineError::ValueOutOfRange(bigint!(-1))) + Err(HintError::ValueOutOfRange(bigint!(-1))) ); } @@ -339,7 +340,7 @@ mod tests { let mut exec_scopes = scope![("find_element_max_size", bigint!(1))]; assert_eq!( run_hint!(vm, ids_data, hint_code::FIND_ELEMENT, &mut exec_scopes), - Err(VirtualMachineError::FindElemMaxSize(bigint!(1), bigint!(2))) + Err(HintError::FindElemMaxSize(bigint!(1), bigint!(2))) ); } @@ -350,7 +351,9 @@ mod tests { init_vm_ids_data(HashMap::from([("key".to_string(), relocatable.clone())])); assert_eq!( run_hint!(vm, ids_data, hint_code::FIND_ELEMENT), - Err(VirtualMachineError::ExpectedInteger(relocatable)) + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( + relocatable + ))) ); } @@ -386,9 +389,9 @@ mod tests { )])); assert_eq!( run_hint!(vm, ids_data, hint_code::SEARCH_SORTED_LOWER), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 1)) - )) + ))) ); } @@ -400,7 +403,7 @@ mod tests { )])); assert_eq!( run_hint!(vm, ids_data, hint_code::SEARCH_SORTED_LOWER), - Err(VirtualMachineError::ValueOutOfRange(bigint!(0))) + Err(HintError::ValueOutOfRange(bigint!(0))) ); } @@ -412,7 +415,7 @@ mod tests { )])); assert_eq!( run_hint!(vm, ids_data, hint_code::SEARCH_SORTED_LOWER), - Err(VirtualMachineError::ValueOutOfRange(bigint!(-1))) + Err(HintError::ValueOutOfRange(bigint!(-1))) ); } @@ -424,9 +427,9 @@ mod tests { )])); assert_eq!( run_hint!(vm, ids_data, hint_code::SEARCH_SORTED_LOWER), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 2)) - )) + ))) ); } @@ -438,7 +441,7 @@ mod tests { )])); assert_eq!( run_hint!(vm, ids_data, hint_code::SEARCH_SORTED_LOWER), - Err(VirtualMachineError::ValueOutOfRange(bigint!(-1))) + Err(HintError::ValueOutOfRange(bigint!(-1))) ); } @@ -462,7 +465,7 @@ mod tests { hint_code::SEARCH_SORTED_LOWER, &mut exec_scopes ), - Err(VirtualMachineError::FindElemMaxSize(bigint!(1), bigint!(2))) + Err(HintError::FindElemMaxSize(bigint!(1), bigint!(2))) ); } } diff --git a/src/hint_processor/builtin_hint_processor/hint_utils.rs b/src/hint_processor/builtin_hint_processor/hint_utils.rs index b2cf857a94..54c98dfb32 100644 --- a/src/hint_processor/builtin_hint_processor/hint_utils.rs +++ b/src/hint_processor/builtin_hint_processor/hint_utils.rs @@ -4,7 +4,7 @@ use crate::hint_processor::hint_processor_utils::get_integer_from_reference; use crate::serde::deserialize_program::ApTracking; use crate::types::relocatable::MaybeRelocatable; use crate::types::relocatable::Relocatable; -use crate::vm::errors::vm_errors::VirtualMachineError; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use num_bigint::BigInt; use std::borrow::Cow; @@ -17,17 +17,19 @@ pub fn insert_value_from_var_name( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let var_address = get_relocatable_from_var_name(var_name, vm, ids_data, ap_tracking)?; vm.insert_value(&var_address, value) + .map_err(HintError::Internal) } //Inserts value into ap pub fn insert_value_into_ap( vm: &mut VirtualMachine, value: impl Into, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { vm.insert_value(&vm.get_ap(), value) + .map_err(HintError::Internal) } //Returns the Relocatable value stored in the given ids variable @@ -36,12 +38,12 @@ pub fn get_ptr_from_var_name( vm: &VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result { +) -> Result { let var_addr = get_relocatable_from_var_name(var_name, vm, ids_data, ap_tracking)?; //Add immediate if present in reference let hint_reference = ids_data .get(&String::from(var_name)) - .ok_or(VirtualMachineError::FailedToGetIds)?; + .ok_or(HintError::FailedToGetIds)?; if hint_reference.dereference { let value = vm.get_relocatable(&var_addr)?; Ok(value) @@ -56,11 +58,9 @@ pub fn get_address_from_var_name( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result { +) -> Result { Ok(MaybeRelocatable::from(compute_addr_from_reference( - ids_data - .get(var_name) - .ok_or(VirtualMachineError::FailedToGetIds)?, + ids_data.get(var_name).ok_or(HintError::FailedToGetIds)?, vm, ap_tracking, )?)) @@ -72,11 +72,9 @@ pub fn get_relocatable_from_var_name( vm: &VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result { +) -> Result { compute_addr_from_reference( - ids_data - .get(var_name) - .ok_or(VirtualMachineError::FailedToGetIds)?, + ids_data.get(var_name).ok_or(HintError::FailedToGetIds)?, vm, ap_tracking, ) @@ -90,7 +88,7 @@ pub fn get_integer_from_var_name<'a>( vm: &'a VirtualMachine, ids_data: &'a HashMap, ap_tracking: &ApTracking, -) -> Result, VirtualMachineError> { +) -> Result, HintError> { let reference = get_reference_from_var_name(var_name, ids_data)?; get_integer_from_reference(vm, reference, ap_tracking) } @@ -98,10 +96,8 @@ pub fn get_integer_from_var_name<'a>( pub fn get_reference_from_var_name<'a>( var_name: &str, ids_data: &'a HashMap, -) -> Result<&'a HintReference, VirtualMachineError> { - ids_data - .get(var_name) - .ok_or(VirtualMachineError::FailedToGetIds) +) -> Result<&'a HintReference, HintError> { + ids_data.get(var_name).ok_or(HintError::FailedToGetIds) } #[cfg(test)] diff --git a/src/hint_processor/builtin_hint_processor/keccak_utils.rs b/src/hint_processor/builtin_hint_processor/keccak_utils.rs index fcdf62bb54..369c4b84f4 100644 --- a/src/hint_processor/builtin_hint_processor/keccak_utils.rs +++ b/src/hint_processor/builtin_hint_processor/keccak_utils.rs @@ -11,7 +11,10 @@ use crate::{ exec_scope::ExecutionScopes, relocatable::{MaybeRelocatable, Relocatable}, }, - vm::{errors::vm_errors::VirtualMachineError, vm_core::VirtualMachine}, + vm::{ + errors::{hint_errors::HintError, vm_errors::VirtualMachineError}, + vm_core::VirtualMachine, + }, }; use num_bigint::{BigInt, Sign}; use num_traits::Signed; @@ -47,12 +50,12 @@ pub fn unsafe_keccak( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let length = get_integer_from_var_name("length", vm, ids_data, ap_tracking)?; if let Ok(keccak_max_size) = exec_scopes.get::("__keccak_max_size") { if length.as_ref() > &keccak_max_size { - return Err(VirtualMachineError::KeccakMaxSize( + return Err(HintError::KeccakMaxSize( length.into_owned(), keccak_max_size, )); @@ -68,7 +71,7 @@ pub fn unsafe_keccak( // transform to u64 to make ranges cleaner in the for loop below let u64_length = length .to_u64() - .ok_or_else(|| VirtualMachineError::InvalidKeccakInputLength(length.into_owned()))?; + .ok_or_else(|| HintError::InvalidKeccakInputLength(length.into_owned()))?; let mut keccak_input = Vec::new(); for (word_i, byte_i) in (0..u64_length).step_by(16).enumerate() { @@ -81,7 +84,7 @@ pub fn unsafe_keccak( let n_bytes = cmp::min(16, u64_length - byte_i); if word.is_negative() || word.as_ref() >= &bigint!(1).shl(8 * (n_bytes as u32)) { - return Err(VirtualMachineError::InvalidWordSize(word.into_owned())); + return Err(HintError::InvalidWordSize(word.into_owned())); } let (_, mut bytes) = word.to_bytes_be(); @@ -102,7 +105,8 @@ pub fn unsafe_keccak( let low = BigInt::from_bytes_be(Sign::Plus, &hashed[16..32]); vm.insert_value(&high_addr, &high)?; - vm.insert_value(&low_addr, &low) + vm.insert_value(&low_addr, &low)?; + Ok(()) } /* @@ -124,7 +128,7 @@ pub fn unsafe_keccak_finalize( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { /* ----------------------------- Just for reference (cairo code): struct KeccakState: @@ -189,7 +193,8 @@ pub fn unsafe_keccak_finalize( let low = BigInt::from_bytes_be(Sign::Plus, &hashed[16..32]); vm.insert_value(&high_addr, &high)?; - vm.insert_value(&low_addr, &low) + vm.insert_value(&low_addr, &low)?; + Ok(()) } fn left_pad(bytes_vector: &mut [u8], n_zeros: usize) -> Vec { diff --git a/src/hint_processor/builtin_hint_processor/math_utils.rs b/src/hint_processor/builtin_hint_processor/math_utils.rs index 80a740ebaa..4b56a49869 100644 --- a/src/hint_processor/builtin_hint_processor/math_utils.rs +++ b/src/hint_processor/builtin_hint_processor/math_utils.rs @@ -10,7 +10,10 @@ use crate::{ math_utils::{as_int, isqrt}, serde::deserialize_program::ApTracking, types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, - vm::{errors::vm_errors::VirtualMachineError, vm_core::VirtualMachine}, + vm::{ + errors::{hint_errors::HintError, vm_errors::VirtualMachineError}, + vm_core::VirtualMachine, + }, }; use std::{ @@ -28,7 +31,7 @@ pub fn is_nn( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a = get_integer_from_var_name("a", vm, ids_data, ap_tracking)?; let range_check_builtin = vm.get_range_check_builtin()?; //Main logic (assert a is not negative and within the expected range) @@ -47,7 +50,7 @@ pub fn is_nn_out_of_range( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a = get_integer_from_var_name("a", vm, ids_data, ap_tracking)?; let a = a.as_ref(); let range_check_builtin = vm.get_range_check_builtin()?; @@ -74,16 +77,16 @@ pub fn assert_le_felt( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { const PRIME_OVER_3_HIGH: &str = "starkware.cairo.common.math.assert_le_felt.PRIME_OVER_3_HIGH"; const PRIME_OVER_2_HIGH: &str = "starkware.cairo.common.math.assert_le_felt.PRIME_OVER_2_HIGH"; let prime_over_3_high = constants .get(PRIME_OVER_3_HIGH) - .ok_or(VirtualMachineError::MissingConstant(PRIME_OVER_3_HIGH))?; + .ok_or(HintError::MissingConstant(PRIME_OVER_3_HIGH))?; let prime_over_2_high = constants .get(PRIME_OVER_2_HIGH) - .ok_or(VirtualMachineError::MissingConstant(PRIME_OVER_2_HIGH))?; + .ok_or(HintError::MissingConstant(PRIME_OVER_2_HIGH))?; let a = &get_integer_from_var_name("a", vm, ids_data, ap_tracking)? .clone() .into_owned(); @@ -93,7 +96,7 @@ pub fn assert_le_felt( let range_check_ptr = get_ptr_from_var_name("range_check_ptr", vm, ids_data, ap_tracking)?; if a.mod_floor(vm.get_prime()) > b.mod_floor(vm.get_prime()) { - return Err(VirtualMachineError::NonLeFelt(a.clone(), b.clone())); + return Err(HintError::NonLeFelt(a.clone(), b.clone())); } let arc1 = b - a; @@ -103,7 +106,7 @@ pub fn assert_le_felt( if lengths_and_indices[0].0 > &(vm.get_prime() / 3) || lengths_and_indices[1].0 > &(vm.get_prime() / 2) { - return Err(VirtualMachineError::ArcTooBig( + return Err(HintError::ArcTooBig( lengths_and_indices[0].0.clone(), vm.get_prime() / 3, lengths_and_indices[1].0.clone(), @@ -120,16 +123,15 @@ pub fn assert_le_felt( vm.insert_value(&(&range_check_ptr + 1), q_0)?; vm.insert_value(&range_check_ptr, r_0)?; vm.insert_value(&(&range_check_ptr + 3), q_1)?; - vm.insert_value(&(&range_check_ptr + 2), r_1) + vm.insert_value(&(&range_check_ptr + 2), r_1)?; + Ok(()) } -pub fn assert_le_felt_excluded_2( - exec_scopes: &mut ExecutionScopes, -) -> Result<(), VirtualMachineError> { +pub fn assert_le_felt_excluded_2(exec_scopes: &mut ExecutionScopes) -> Result<(), HintError> { let excluded: BigInt = exec_scopes.get("excluded")?; if excluded != bigint!(2) { - Err(VirtualMachineError::ExcludedNot2(excluded)) + Err(HintError::ExcludedNot2(excluded)) } else { Ok(()) } @@ -138,7 +140,7 @@ pub fn assert_le_felt_excluded_2( pub fn assert_le_felt_excluded_1( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let excluded: BigInt = exec_scopes.get("excluded")?; if excluded != bigint!(1) { @@ -151,7 +153,7 @@ pub fn assert_le_felt_excluded_1( pub fn assert_le_felt_excluded_0( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let excluded: BigInt = exec_scopes.get("excluded")?; if !excluded.is_zero() { @@ -167,7 +169,7 @@ pub fn is_le_felt( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a_mod = get_integer_from_var_name("a", vm, ids_data, ap_tracking)?.mod_floor(vm.get_prime()); let b_mod = @@ -192,7 +194,7 @@ pub fn assert_not_equal( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a_addr = get_address_from_var_name("a", vm, ids_data, ap_tracking)?; let b_addr = get_address_from_var_name("b", vm, ids_data, ap_tracking)?; //Check that the ids are in memory @@ -203,7 +205,7 @@ pub fn assert_not_equal( match (maybe_rel_a, maybe_rel_b) { (MaybeRelocatable::Int(a), MaybeRelocatable::Int(b)) => { if (&a - &b).is_multiple_of(vm.get_prime()) { - return Err(VirtualMachineError::AssertNotEqualFail( + return Err(HintError::AssertNotEqualFail( MaybeRelocatable::Int(a), MaybeRelocatable::Int(b), )); @@ -212,10 +214,10 @@ pub fn assert_not_equal( } (MaybeRelocatable::RelocatableValue(a), MaybeRelocatable::RelocatableValue(b)) => { if a.segment_index != b.segment_index { - return Err(VirtualMachineError::DiffIndexComp(a, b)); + Err(VirtualMachineError::DiffIndexComp(a, b))?; }; if a.offset == b.offset { - return Err(VirtualMachineError::AssertNotEqualFail( + return Err(HintError::AssertNotEqualFail( MaybeRelocatable::RelocatableValue(a), MaybeRelocatable::RelocatableValue(b), )); @@ -225,10 +227,10 @@ pub fn assert_not_equal( (maybe_rel_a, maybe_rel_b) => Err(VirtualMachineError::DiffTypeComparison( maybe_rel_a, maybe_rel_b, - )), + ))?, } } - _ => Err(VirtualMachineError::FailedToGetIds), + _ => Err(HintError::FailedToGetIds), } } @@ -242,13 +244,13 @@ pub fn assert_nn( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a = get_integer_from_var_name("a", vm, ids_data, ap_tracking)?; let range_check_builtin = vm.get_range_check_builtin()?; // assert 0 <= ids.a % PRIME < range_check_builtin.bound // as prime > 0, a % prime will always be > 0 if a.mod_floor(vm.get_prime()) >= range_check_builtin._bound { - return Err(VirtualMachineError::ValueOutOfRange(a.into_owned())); + return Err(HintError::AssertNNValueOutOfRange(a.into_owned())); }; Ok(()) } @@ -263,10 +265,10 @@ pub fn assert_not_zero( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let value = get_integer_from_var_name("value", vm, ids_data, ap_tracking)?; if value.is_multiple_of(vm.get_prime()) { - return Err(VirtualMachineError::AssertNotZero( + return Err(HintError::AssertNotZero( value.into_owned(), vm.get_prime().clone(), )); @@ -279,11 +281,11 @@ pub fn split_int_assert_range( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let value = get_integer_from_var_name("value", vm, ids_data, ap_tracking)?; //Main logic (assert value == 0) if !value.is_zero() { - return Err(VirtualMachineError::SplitIntNotZero); + return Err(HintError::SplitIntNotZero); } Ok(()) } @@ -294,7 +296,7 @@ pub fn split_int( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let value = get_integer_from_var_name("value", vm, ids_data, ap_tracking)?; let base = get_integer_from_var_name("base", vm, ids_data, ap_tracking)?; let bound = get_integer_from_var_name("bound", vm, ids_data, ap_tracking)?; @@ -304,9 +306,9 @@ pub fn split_int( //Main Logic let res = (value.mod_floor(vm.get_prime())).mod_floor(base); if &res > bound { - return Err(VirtualMachineError::SplitIntLimbOutOfRange(res)); + return Err(HintError::SplitIntLimbOutOfRange(res)); } - vm.insert_value(&output, res) + vm.insert_value(&output, res).map_err(HintError::Internal) } //from starkware.cairo.common.math_utils import is_positive @@ -316,14 +318,14 @@ pub fn is_positive( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let value = get_integer_from_var_name("value", vm, ids_data, ap_tracking)?; let value = value.as_ref(); let range_check_builtin = vm.get_range_check_builtin()?; //Main logic (assert a is positive) let int_value = as_int(value, vm.get_prime()); if int_value.abs() > range_check_builtin._bound { - return Err(VirtualMachineError::ValueOutsideValidRange(int_value)); + return Err(HintError::ValueOutsideValidRange(int_value)); } let result = if int_value.is_positive() { bigint!(1) @@ -346,7 +348,7 @@ pub fn split_felt( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let value = get_integer_from_var_name("value", vm, ids_data, ap_tracking)?; let value = value.as_ref(); //Main logic @@ -368,12 +370,12 @@ pub fn sqrt( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let mod_value = get_integer_from_var_name("value", vm, ids_data, ap_tracking)?.mod_floor(vm.get_prime()); //This is equal to mod_value > bigint!(2).pow(250) if (&mod_value).shr(250_i32).is_positive() { - return Err(VirtualMachineError::ValueOutside250BitRange(mod_value)); + return Err(HintError::ValueOutside250BitRange(mod_value)); } insert_value_from_var_name("root", isqrt(&mod_value)?, vm, ids_data, ap_tracking) } @@ -382,7 +384,7 @@ pub fn signed_div_rem( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let div = get_integer_from_var_name("div", vm, ids_data, ap_tracking)?; let value = get_integer_from_var_name("value", vm, ids_data, ap_tracking)?; let value = value.as_ref(); @@ -390,14 +392,14 @@ pub fn signed_div_rem( let builtin = vm.get_range_check_builtin()?; // Main logic if !div.is_positive() || div.as_ref() > &(vm.get_prime() / &builtin._bound) { - return Err(VirtualMachineError::OutOfValidRange( + return Err(HintError::OutOfValidRange( div.into_owned(), vm.get_prime() / &builtin._bound, )); } // Divide by 2 if bound.as_ref() > &(&builtin._bound).shr(1_i32) { - return Err(VirtualMachineError::OutOfValidRange( + return Err(HintError::OutOfValidRange( bound.into_owned(), (&builtin._bound).shr(1_i32), )); @@ -406,7 +408,7 @@ pub fn signed_div_rem( let int_value = &as_int(value, vm.get_prime()); let (q, r) = int_value.div_mod_floor(div.as_ref()); if bound.as_ref().neg() > q || &q >= bound.as_ref() { - return Err(VirtualMachineError::OutOfValidRange(q, bound.into_owned())); + return Err(HintError::OutOfValidRange(q, bound.into_owned())); } let biased_q = q + bound.as_ref(); insert_value_from_var_name("r", r, vm, ids_data, ap_tracking)?; @@ -426,13 +428,13 @@ pub fn unsigned_div_rem( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let div = get_integer_from_var_name("div", vm, ids_data, ap_tracking)?; let value = get_integer_from_var_name("value", vm, ids_data, ap_tracking)?; let builtin = vm.get_range_check_builtin()?; // Main logic if !div.is_positive() || div.as_ref() > &(vm.get_prime() / &builtin._bound) { - return Err(VirtualMachineError::OutOfValidRange( + return Err(HintError::OutOfValidRange( div.into_owned(), vm.get_prime() / &builtin._bound, )); @@ -452,7 +454,7 @@ pub fn assert_250_bit( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Declare constant values let upper_bound = bigint!(1).shl(250_i32); let shift = bigint!(1).shl(128_i32); @@ -460,7 +462,7 @@ pub fn assert_250_bit( //Main logic let int_value = as_int(value.as_ref(), vm.get_prime()).mod_floor(vm.get_prime()); if int_value > upper_bound { - return Err(VirtualMachineError::ValueOutside250BitRange(int_value)); + return Err(HintError::ValueOutside250BitRange(int_value)); } let (high, low) = int_value.div_rem(&shift); insert_value_from_var_name("high", high, vm, ids_data, ap_tracking)?; @@ -481,7 +483,7 @@ pub fn assert_lt_felt( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a = get_integer_from_var_name("a", vm, ids_data, ap_tracking)?; let b = get_integer_from_var_name("b", vm, ids_data, ap_tracking)?; // Main logic @@ -490,10 +492,7 @@ pub fn assert_lt_felt( // assert (ids.a % PRIME) < (ids.b % PRIME), \ // f'a = {ids.a % PRIME} is not less than b = {ids.b % PRIME}.' if a.mod_floor(vm.get_prime()) >= b.mod_floor(vm.get_prime()) { - return Err(VirtualMachineError::AssertLtFelt( - a.into_owned(), - b.into_owned(), - )); + return Err(HintError::AssertLtFelt(a.into_owned(), b.into_owned())); }; Ok(()) } @@ -592,7 +591,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::NoRangeCheckBuiltin) + Err(HintError::Internal( + VirtualMachineError::NoRangeCheckBuiltin + )) ); } @@ -607,7 +608,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::FailedToGetIds) + Err(HintError::FailedToGetIds) ); } @@ -624,9 +625,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 4)) - )) + ))) ); } @@ -643,9 +644,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 4)) - )) + ))) ); } @@ -706,13 +707,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 0)), MaybeRelocatable::Int(bigint!(1)), MaybeRelocatable::Int(bigint!(0)) ) - )) + ))) ); } @@ -726,7 +727,7 @@ mod tests { let ids_data = ids_data!["a", "c"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::FailedToGetIds) + Err(HintError::FailedToGetIds) ); } @@ -758,7 +759,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ValueOutOfRange(bigint!(-1))) + Err(HintError::AssertNNValueOutOfRange(bigint!(-1))) ); } @@ -774,7 +775,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::FailedToGetIds), + Err(HintError::FailedToGetIds), ); } @@ -790,9 +791,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 3)) - )) + ))) ); } @@ -808,7 +809,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::NoRangeCheckBuiltin) + Err(HintError::Internal( + VirtualMachineError::NoRangeCheckBuiltin + )) ); } @@ -823,9 +826,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 3)) - )) + ))) ); } @@ -852,7 +855,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes, &constants), - Err(VirtualMachineError::NonLeFelt(bigint!(2), bigint!(1))) + Err(HintError::NonLeFelt(bigint!(2), bigint!(1))) ); } @@ -878,9 +881,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes, &constants), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 0)) - )) + ))) ); } @@ -906,9 +909,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes, &constants), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 1)) - )) + ))) ); } @@ -957,7 +960,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::AssertNotEqualFail( + Err(HintError::AssertNotEqualFail( MaybeRelocatable::from(bigint!(1)), MaybeRelocatable::from(bigint!(1)) )) @@ -999,7 +1002,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::AssertNotEqualFail( + Err(HintError::AssertNotEqualFail( MaybeRelocatable::from(bigint!(-1)), MaybeRelocatable::from(bigint_str!( b"3618502788666131213697322783095070105623107215331596699973092056135872020480" @@ -1020,7 +1023,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::AssertNotEqualFail( + Err(HintError::AssertNotEqualFail( MaybeRelocatable::from((1, 0)), MaybeRelocatable::from((1, 0)) )) @@ -1052,10 +1055,10 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::DiffIndexComp( + Err(HintError::Internal(VirtualMachineError::DiffIndexComp( relocatable!(2, 0), relocatable!(1, 0) - )) + ))) ); } @@ -1071,9 +1074,11 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::DiffTypeComparison( - MaybeRelocatable::from((1, 0)), - MaybeRelocatable::from(bigint!(1)) + Err(HintError::Internal( + VirtualMachineError::DiffTypeComparison( + MaybeRelocatable::from((1, 0)), + MaybeRelocatable::from(bigint!(1)) + ) )) ); } @@ -1106,7 +1111,7 @@ mod tests { let ids_data = ids_data!["value"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::AssertNotZero(bigint!(0), vm.prime)) + Err(HintError::AssertNotZero(bigint!(0), vm.prime)) ); } @@ -1130,10 +1135,7 @@ mod tests { let ids_data = ids_data!["value"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::AssertNotZero( - vm.prime.clone(), - vm.prime - )) + Err(HintError::AssertNotZero(vm.prime.clone(), vm.prime)) ); } @@ -1150,7 +1152,7 @@ mod tests { let ids_data = ids_data!["incorrect_id"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::FailedToGetIds) + Err(HintError::FailedToGetIds) ); } @@ -1167,9 +1169,9 @@ mod tests { let ids_data = ids_data!["value"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 4)) - )) + ))) ); } @@ -1185,7 +1187,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::SplitIntNotZero) + Err(HintError::SplitIntNotZero) ); } @@ -1235,7 +1237,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::SplitIntLimbOutOfRange(bigint!(100))) + Err(HintError::SplitIntLimbOutOfRange(bigint!(100))) ); } @@ -1294,7 +1296,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ValueOutsideValidRange(as_int( + Err(HintError::ValueOutsideValidRange(as_int( &BigInt::new(Sign::Plus, vec![1, 0, 0, 0, 0, 0, 17, 134217727]), &vm.prime ))) @@ -1314,13 +1316,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 1)), MaybeRelocatable::from(bigint!(4)), MaybeRelocatable::from(bigint!(1)) ) - )) + ))) ); } @@ -1353,7 +1355,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ValueOutside250BitRange(bigint_str!( + Err(HintError::ValueOutside250BitRange(bigint_str!( b"3618502788666131213697322783095070105623107215331596699973092056135872020400" ))) ); @@ -1372,13 +1374,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 1)), MaybeRelocatable::from(bigint!(7)), MaybeRelocatable::from(bigint!(9)) ) - )) + ))) ); } @@ -1410,7 +1412,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::OutOfValidRange( + Err(HintError::OutOfValidRange( bigint!(-5), bigint_str!(b"10633823966279327296825105735305134080") )) @@ -1429,7 +1431,9 @@ mod tests { let ids_data = ids_data!["r", "q", "div", "value"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::NoRangeCheckBuiltin) + Err(HintError::Internal( + VirtualMachineError::NoRangeCheckBuiltin + )) ); } @@ -1446,13 +1450,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 0)), MaybeRelocatable::Int(bigint!(5)), MaybeRelocatable::Int(bigint!(2)) ) - )) + ))) ); } @@ -1469,7 +1473,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::FailedToGetIds) + Err(HintError::FailedToGetIds) ) } @@ -1516,7 +1520,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::OutOfValidRange( + Err(HintError::OutOfValidRange( bigint!(-5), bigint_str!(b"10633823966279327296825105735305134080") )) @@ -1535,7 +1539,9 @@ mod tests { let ids_data = ids_data!["r", "biased_q", "range_check_ptr", "div", "value", "bound"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::NoRangeCheckBuiltin) + Err(HintError::Internal( + VirtualMachineError::NoRangeCheckBuiltin + )) ); } @@ -1552,13 +1558,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 1)), MaybeRelocatable::Int(bigint!(10)), MaybeRelocatable::Int(bigint!(31)) ) - )) + ))) ); } @@ -1575,7 +1581,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::FailedToGetIds) + Err(HintError::FailedToGetIds) ) } @@ -1616,9 +1622,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ValueOutside250BitRange( - bigint!(1).shl(251i32) - )) + Err(HintError::ValueOutside250BitRange(bigint!(1).shl(251i32))) ); } @@ -1667,7 +1671,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::FailedToGetIds) + Err(HintError::FailedToGetIds) ); } @@ -1693,13 +1697,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((2, 0)), MaybeRelocatable::from(bigint!(99)), MaybeRelocatable::from(bigint_str!(b"189509265092725080168209675610990602697")) ) - )) + ))) ); } @@ -1725,13 +1729,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((2, 1)), MaybeRelocatable::from(bigint!(99)), MaybeRelocatable::from(bigint!(21)) ) - )) + ))) ); } @@ -1752,9 +1756,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 3)) - )) + ))) ); } @@ -1785,7 +1789,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::AssertLtFelt(bigint!(3), bigint!(2))) + Err(HintError::AssertLtFelt(bigint!(3), bigint!(2))) ); } @@ -1802,7 +1806,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::FailedToGetIds) + Err(HintError::FailedToGetIds) ); } @@ -1818,9 +1822,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 1)) - )) + ))) ); } @@ -1836,9 +1840,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 2)) - )) + ))) ); } @@ -1855,9 +1859,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 2)) - )) + ))) ); } } diff --git a/src/hint_processor/builtin_hint_processor/memcpy_hint_utils.rs b/src/hint_processor/builtin_hint_processor/memcpy_hint_utils.rs index d2168cee35..db6d6333b5 100644 --- a/src/hint_processor/builtin_hint_processor/memcpy_hint_utils.rs +++ b/src/hint_processor/builtin_hint_processor/memcpy_hint_utils.rs @@ -8,30 +8,28 @@ use crate::{ }, serde::deserialize_program::ApTracking, types::exec_scope::ExecutionScopes, - vm::{errors::vm_errors::VirtualMachineError, vm_core::VirtualMachine}, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, }; use num_bigint::BigInt; use num_traits::Signed; use std::{any::Any, collections::HashMap}; //Implements hint: memory[ap] = segments.add() -pub fn add_segment(vm: &mut VirtualMachine) -> Result<(), VirtualMachineError> { +pub fn add_segment(vm: &mut VirtualMachine) -> Result<(), HintError> { let new_segment_base = vm.add_memory_segment(); insert_value_into_ap(vm, new_segment_base) } //Implements hint: vm_enter_scope() -pub fn enter_scope(exec_scopes: &mut ExecutionScopes) -> Result<(), VirtualMachineError> { +pub fn enter_scope(exec_scopes: &mut ExecutionScopes) -> Result<(), HintError> { exec_scopes.enter_scope(HashMap::new()); Ok(()) } // Implements hint: // %{ vm_exit_scope() %} -pub fn exit_scope(exec_scopes: &mut ExecutionScopes) -> Result<(), VirtualMachineError> { - exec_scopes - .exit_scope() - .map_err(VirtualMachineError::MainScopeError) +pub fn exit_scope(exec_scopes: &mut ExecutionScopes) -> Result<(), HintError> { + exec_scopes.exit_scope().map_err(HintError::FromScopeError) } // Implements hint: @@ -41,7 +39,7 @@ pub fn memcpy_enter_scope( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let len: Box = Box::new(get_integer_from_var_name("len", vm, ids_data, ap_tracking)?.into_owned()); exec_scopes.enter_scope(HashMap::from([(String::from("n"), len)])); @@ -58,7 +56,7 @@ pub fn memcpy_continue_copying( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { // get `n` variable from vm scope let n = exec_scopes.get_ref::("n")?; // this variable will hold the value of `n - 1` @@ -81,6 +79,7 @@ mod tests { use crate::types::relocatable::MaybeRelocatable; use crate::utils::test_utils::*; use crate::vm::errors::memory_errors::MemoryError; + use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::vm_core::VirtualMachine; use crate::vm::vm_memory::memory::Memory; use num_bigint::BigInt; @@ -128,9 +127,9 @@ mod tests { assert_eq!( get_integer_from_var_name(var_name, &vm, &ids_data, &ApTracking::default()), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 0)) - )) + ))) ); } } diff --git a/src/hint_processor/builtin_hint_processor/memset_utils.rs b/src/hint_processor/builtin_hint_processor/memset_utils.rs index 17c400ae85..08410dd782 100644 --- a/src/hint_processor/builtin_hint_processor/memset_utils.rs +++ b/src/hint_processor/builtin_hint_processor/memset_utils.rs @@ -8,7 +8,7 @@ use crate::{ }, serde::deserialize_program::ApTracking, types::exec_scope::ExecutionScopes, - vm::{errors::vm_errors::VirtualMachineError, vm_core::VirtualMachine}, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, }; use num_bigint::BigInt; use num_traits::Signed; @@ -21,7 +21,7 @@ pub fn memset_enter_scope( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let n: Box = Box::new(get_integer_from_var_name("n", vm, ids_data, ap_tracking)?.into_owned()); exec_scopes.enter_scope(HashMap::from([(String::from("n"), n)])); @@ -39,7 +39,7 @@ pub fn memset_continue_loop( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { // get `n` variable from vm scope let n = exec_scopes.get_ref::("n")?; // this variable will hold the value of `n - 1` @@ -63,6 +63,8 @@ mod tests { use crate::hint_processor::hint_processor_definition::HintProcessor; use crate::types::exec_scope::ExecutionScopes; use crate::utils::test_utils::*; + use crate::vm::errors::hint_errors::HintError; + use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::vm_memory::memory::Memory; use crate::{ types::relocatable::MaybeRelocatable, @@ -94,9 +96,9 @@ mod tests { let ids_data = ids_data!["n"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 1)) - )) + ))) ); } @@ -152,9 +154,7 @@ mod tests { let ids_data = ids_data!["continue_loop"]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::VariableNotInScopeError( - "n".to_string() - )) + Err(HintError::VariableNotInScopeError("n".to_string())) ); } @@ -172,13 +172,13 @@ mod tests { let ids_data = ids_data!["continue_loop"]; assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 0)), MaybeRelocatable::from(bigint!(5)), MaybeRelocatable::from(bigint!(0)) ) - )) + ))) ); } } diff --git a/src/hint_processor/builtin_hint_processor/pow_utils.rs b/src/hint_processor/builtin_hint_processor/pow_utils.rs index f2eb5e8ee5..fb16d2b360 100644 --- a/src/hint_processor/builtin_hint_processor/pow_utils.rs +++ b/src/hint_processor/builtin_hint_processor/pow_utils.rs @@ -2,7 +2,7 @@ use crate::hint_processor::builtin_hint_processor::hint_utils::{ get_relocatable_from_var_name, insert_value_from_var_name, }; use crate::serde::deserialize_program::ApTracking; -use crate::vm::errors::vm_errors::VirtualMachineError; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use crate::{bigint, hint_processor::hint_processor_definition::HintReference}; use num_bigint::BigInt; @@ -17,7 +17,7 @@ pub fn pow( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let prev_locs_addr = get_relocatable_from_var_name("prev_locs", vm, ids_data, ap_tracking)?; let prev_locs_exp = vm.get_integer(&(&prev_locs_addr + 4))?; let locs_bit = prev_locs_exp.mod_floor(vm.get_prime()) & bigint!(1); @@ -36,6 +36,7 @@ mod tests { use crate::types::relocatable::MaybeRelocatable; use crate::utils::test_utils::*; use crate::vm::errors::memory_errors::MemoryError; + use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::vm_core::VirtualMachine; use crate::vm::vm_memory::memory::Memory; use crate::{bigint, vm::runners::builtin_runner::RangeCheckBuiltinRunner}; @@ -69,7 +70,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::FailedToGetIds) + Err(HintError::FailedToGetIds) ); } @@ -85,9 +86,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 10)) - )) + ))) ); } @@ -105,9 +106,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 10)) - )) + ))) ); } @@ -124,13 +125,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 11)), MaybeRelocatable::from(bigint!(3)), MaybeRelocatable::from(bigint!(1)) ) - )) + ))) ); } } diff --git a/src/hint_processor/builtin_hint_processor/secp/bigint_utils.rs b/src/hint_processor/builtin_hint_processor/secp/bigint_utils.rs index 373b0af814..d75cf30aed 100644 --- a/src/hint_processor/builtin_hint_processor/secp/bigint_utils.rs +++ b/src/hint_processor/builtin_hint_processor/secp/bigint_utils.rs @@ -8,6 +8,7 @@ use crate::hint_processor::hint_processor_definition::HintReference; use crate::serde::deserialize_program::ApTracking; use crate::types::exec_scope::ExecutionScopes; use crate::types::relocatable::MaybeRelocatable; +use crate::vm::errors::hint_errors::HintError; use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::vm_core::VirtualMachine; @@ -28,7 +29,7 @@ pub fn nondet_bigint3( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let res_reloc = get_relocatable_from_var_name("res", vm, ids_data, ap_tracking)?; let value = exec_scopes.get_ref::("value")?; let arg: Vec = split(value, constants)? @@ -47,7 +48,7 @@ pub fn bigint_to_uint256( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let x_struct = get_relocatable_from_var_name("x", vm, ids_data, ap_tracking)?; let d0 = vm.get_integer(&x_struct)?; let d1 = vm.get_integer(&(&x_struct + 1))?; @@ -55,7 +56,7 @@ pub fn bigint_to_uint256( let d1 = d1.as_ref(); let base_86 = constants .get(BASE_86) - .ok_or(VirtualMachineError::MissingConstant(BASE_86))?; + .ok_or(HintError::MissingConstant(BASE_86))?; let low = (d0 + d1 * &*base_86) & bigint!(u128::MAX); insert_value_from_var_name("low", low, vm, ids_data, ap_tracking) } @@ -125,9 +126,7 @@ mod tests { let ids_data = non_continuous_ids_data![("res", 5)]; assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::VariableNotInScopeError( - "value".to_string() - )) + Err(HintError::VariableNotInScopeError("value".to_string())) ); } @@ -142,7 +141,7 @@ mod tests { let ids_data = non_continuous_ids_data![("res", 5)]; assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::SecpSplitNegative(bigint!(-1))) + Err(HintError::SecpSplitNegative(bigint!(-1))) ); } } diff --git a/src/hint_processor/builtin_hint_processor/secp/ec_utils.rs b/src/hint_processor/builtin_hint_processor/secp/ec_utils.rs index 2020d2ed17..011a90af46 100644 --- a/src/hint_processor/builtin_hint_processor/secp/ec_utils.rs +++ b/src/hint_processor/builtin_hint_processor/secp/ec_utils.rs @@ -7,7 +7,7 @@ use crate::hint_processor::hint_processor_definition::HintReference; use crate::math_utils::{ec_double_slope, line_slope}; use crate::serde::deserialize_program::ApTracking; use crate::types::exec_scope::ExecutionScopes; -use crate::vm::errors::vm_errors::VirtualMachineError; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use num_bigint::BigInt; use num_integer::Integer; @@ -32,11 +32,11 @@ pub fn ec_negate( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; //ids.point let point_y = get_relocatable_from_var_name("point", vm, ids_data, ap_tracking)? + 3; @@ -64,11 +64,11 @@ pub fn compute_doubling_slope( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; //ids.point let point_reloc = get_relocatable_from_var_name("point", vm, ids_data, ap_tracking)?; @@ -115,11 +115,11 @@ pub fn compute_slope( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; //ids.point0 let point0_reloc = get_relocatable_from_var_name("point0", vm, ids_data, ap_tracking)?; @@ -199,11 +199,11 @@ pub fn ec_double_assign_new_x( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; //ids.slope let slope_reloc = get_relocatable_from_var_name("slope", vm, ids_data, ap_tracking)?; @@ -253,11 +253,11 @@ Implements hint: pub fn ec_double_assign_new_y( exec_scopes: &mut ExecutionScopes, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; //Get variables from vm scope let (slope, x, new_x, y) = ( @@ -292,11 +292,11 @@ pub fn fast_ec_add_assign_new_x( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; //ids.slope let slope_reloc = get_relocatable_from_var_name("slope", vm, ids_data, ap_tracking)?; @@ -372,11 +372,11 @@ Implements hint: pub fn fast_ec_add_assign_new_y( exec_scopes: &mut ExecutionScopes, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; //Get variables from vm scope let (slope, x0, new_x, y0) = ( @@ -400,7 +400,7 @@ pub fn ec_mul_inner( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //(ids.scalar % PRIME) % 2 let scalar = get_integer_from_var_name("scalar", vm, ids_data, ap_tracking)? .mod_floor(vm.get_prime()) diff --git a/src/hint_processor/builtin_hint_processor/secp/field_utils.rs b/src/hint_processor/builtin_hint_processor/secp/field_utils.rs index db84ddb0a8..629a524a38 100644 --- a/src/hint_processor/builtin_hint_processor/secp/field_utils.rs +++ b/src/hint_processor/builtin_hint_processor/secp/field_utils.rs @@ -7,7 +7,7 @@ use crate::hint_processor::hint_processor_definition::HintReference; use crate::math_utils::div_mod; use crate::serde::deserialize_program::ApTracking; use crate::types::exec_scope::ExecutionScopes; -use crate::vm::errors::vm_errors::VirtualMachineError; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use num_bigint::BigInt; use num_integer::Integer; @@ -32,17 +32,17 @@ pub fn verify_zero( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; let val = pack_from_var_name("val", vm, ids_data, ap_tracking)?; let (q, r) = val.div_rem(&secp_p); if !r.is_zero() { - return Err(VirtualMachineError::SecpVerifyZero(val)); + return Err(HintError::SecpVerifyZero(val)); } insert_value_from_var_name("q", q.mod_floor(vm.get_prime()), vm, ids_data, ap_tracking) @@ -62,11 +62,11 @@ pub fn reduce( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; let value = pack_from_var_name("x", vm, ids_data, ap_tracking)?.mod_floor(&secp_p); exec_scopes.insert_value("value", value); @@ -87,11 +87,11 @@ pub fn is_zero_pack( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; let x_packed = pack_from_var_name("x", vm, ids_data, ap_tracking)?; let x = x_packed.mod_floor(&secp_p); @@ -110,7 +110,7 @@ On .json compiled program pub fn is_zero_nondet( vm: &mut VirtualMachine, exec_scopes: &mut ExecutionScopes, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Get `x` variable from vm scope let x = exec_scopes.get::("x")?; @@ -130,11 +130,11 @@ Implements hint: pub fn is_zero_assign_scope_variables( exec_scopes: &mut ExecutionScopes, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; //Get `x` variable from vm scope let x = exec_scopes.get::("x")?; @@ -159,6 +159,7 @@ mod tests { use crate::types::relocatable::Relocatable; use crate::utils::test_utils::*; use crate::vm::errors::memory_errors::MemoryError; + use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::runners::builtin_runner::RangeCheckBuiltinRunner; use crate::vm::vm_core::VirtualMachine; use crate::vm::vm_memory::memory::Memory; @@ -235,7 +236,7 @@ mod tests { .map(|(k, v)| (k.to_string(), v)) .collect() ), - Err(VirtualMachineError::SecpVerifyZero(bigint_str!( + Err(HintError::SecpVerifyZero(bigint_str!( b"897946605976106752944343961220884287276604954404454400" ),)) ); @@ -274,13 +275,13 @@ mod tests { .map(|(k, v)| (k.to_string(), v)) .collect() ), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 9)), MaybeRelocatable::from(bigint!(55)), MaybeRelocatable::from(bigint!(0)) ) - )) + ))) ); } @@ -369,9 +370,9 @@ mod tests { .map(|(k, v)| (k.to_string(), v)) .collect() ), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 20)) - )) + ))) ); } @@ -464,9 +465,9 @@ mod tests { .map(|(k, v)| (k.to_string(), v)) .collect() ), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 10)) - )) + ))) ); } @@ -538,9 +539,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, HashMap::new(), hint_code), - Err(VirtualMachineError::VariableNotInScopeError( - "x".to_string() - )) + Err(HintError::VariableNotInScopeError("x".to_string())) ); } @@ -561,13 +560,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, HashMap::new(), hint_code, &mut exec_scopes), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from(vm.run_context.get_ap()), MaybeRelocatable::from(bigint!(55i32)), MaybeRelocatable::from(bigint!(1i32)) ) - )) + ))) ); } @@ -651,9 +650,7 @@ mod tests { .map(|(k, v)| (k.to_string(), v)) .collect() ), - Err(VirtualMachineError::VariableNotInScopeError( - "x".to_string() - )) + Err(HintError::VariableNotInScopeError("x".to_string())) ); } } diff --git a/src/hint_processor/builtin_hint_processor/secp/secp_utils.rs b/src/hint_processor/builtin_hint_processor/secp/secp_utils.rs index 6d92abfba5..6fb3b721cf 100644 --- a/src/hint_processor/builtin_hint_processor/secp/secp_utils.rs +++ b/src/hint_processor/builtin_hint_processor/secp/secp_utils.rs @@ -2,7 +2,7 @@ use crate::hint_processor::hint_processor_definition::HintReference; use crate::math_utils::as_int; use crate::serde::deserialize_program::ApTracking; use crate::types::relocatable::Relocatable; -use crate::vm::errors::vm_errors::VirtualMachineError; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use crate::{ bigint, hint_processor::builtin_hint_processor::hint_utils::get_relocatable_from_var_name, @@ -30,14 +30,14 @@ where BASE = 2**86. pub fn split( integer: &BigInt, constants: &HashMap, -) -> Result<[BigInt; 3], VirtualMachineError> { +) -> Result<[BigInt; 3], HintError> { if integer.is_negative() { - return Err(VirtualMachineError::SecpSplitNegative(integer.clone())); + return Err(HintError::SecpSplitNegative(integer.clone())); } let base_86_max = constants .get(BASE_86) - .ok_or(VirtualMachineError::MissingConstant(BASE_86))? + .ok_or(HintError::MissingConstant(BASE_86))? - &bigint!(1); let mut num = integer.clone(); @@ -47,7 +47,7 @@ pub fn split( num >>= 86_usize; } if !num.is_zero() { - return Err(VirtualMachineError::SecpSplitutOfRange(integer.clone())); + return Err(HintError::SecpSplitutOfRange(integer.clone())); } Ok(canonical_repr) } @@ -73,7 +73,7 @@ pub fn pack_from_var_name( vm: &VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result { +) -> Result { let to_pack = get_relocatable_from_var_name(name, vm, ids_data, ap_tracking)?; let d0 = vm.get_integer(&to_pack)?; @@ -83,10 +83,7 @@ pub fn pack_from_var_name( Ok(pack(d0.as_ref(), d1.as_ref(), d2.as_ref(), vm.get_prime())) } -pub fn pack_from_relocatable( - rel: Relocatable, - vm: &VirtualMachine, -) -> Result { +pub fn pack_from_relocatable(rel: Relocatable, vm: &VirtualMachine) -> Result { let d0 = vm.get_integer(&rel)?; let d1 = vm.get_integer(&(&rel + 1))?; let d2 = vm.get_integer(&(&rel + 2))?; @@ -129,13 +126,10 @@ mod tests { bigint_str!(b"1292469707114105") ]) ); - assert_eq!( - array_4, - Err(VirtualMachineError::SecpSplitNegative(bigint!(-1))) - ); + assert_eq!(array_4, Err(HintError::SecpSplitNegative(bigint!(-1)))); assert_eq!( array_5, - Err(VirtualMachineError::SecpSplitutOfRange(bigint_str!( + Err(HintError::SecpSplitutOfRange(bigint_str!( b"773712524553362671811952647737125245533626718119526477371252455336267181195264" ))) ); diff --git a/src/hint_processor/builtin_hint_processor/secp/signature.rs b/src/hint_processor/builtin_hint_processor/secp/signature.rs index f33f8be23d..7789353d25 100644 --- a/src/hint_processor/builtin_hint_processor/secp/signature.rs +++ b/src/hint_processor/builtin_hint_processor/secp/signature.rs @@ -2,13 +2,13 @@ use super::secp_utils::{BASE_86, BETA, N0, N1, N2, SECP_REM}; use crate::hint_processor::builtin_hint_processor::hint_utils::get_integer_from_var_name; use crate::hint_processor::builtin_hint_processor::secp::secp_utils::pack_from_var_name; use crate::hint_processor::hint_processor_definition::HintReference; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use crate::{ bigint, math_utils::{div_mod, safe_div}, serde::deserialize_program::ApTracking, types::exec_scope::ExecutionScopes, - vm::errors::vm_errors::VirtualMachineError, }; use num_bigint::BigInt; use num_integer::Integer; @@ -29,23 +29,17 @@ pub fn div_mod_n_packed_divmod( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a = pack_from_var_name("a", vm, ids_data, ap_tracking)?; let b = pack_from_var_name("b", vm, ids_data, ap_tracking)?; let n = { let base = constants .get(BASE_86) - .ok_or(VirtualMachineError::MissingConstant(BASE_86))?; - let n0 = constants - .get(N0) - .ok_or(VirtualMachineError::MissingConstant(N0))?; - let n1 = constants - .get(N1) - .ok_or(VirtualMachineError::MissingConstant(N1))?; - let n2 = constants - .get(N2) - .ok_or(VirtualMachineError::MissingConstant(N2))?; + .ok_or(HintError::MissingConstant(BASE_86))?; + let n0 = constants.get(N0).ok_or(HintError::MissingConstant(N0))?; + let n1 = constants.get(N1).ok_or(HintError::MissingConstant(N1))?; + let n2 = constants.get(N2).ok_or(HintError::MissingConstant(N2))?; (n2 * base * base) | (n1 * base) | n0 }; @@ -63,7 +57,7 @@ pub fn div_mod_n_packed_divmod( pub fn div_mod_n_safe_div( exec_scopes: &mut ExecutionScopes, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a = exec_scopes.get_ref::("a")?; let b = exec_scopes.get_ref::("b")?; let res = exec_scopes.get_ref::("res")?; @@ -71,16 +65,10 @@ pub fn div_mod_n_safe_div( let n = { let base = constants .get(BASE_86) - .ok_or(VirtualMachineError::MissingConstant(BASE_86))?; - let n0 = constants - .get(N0) - .ok_or(VirtualMachineError::MissingConstant(N0))?; - let n1 = constants - .get(N1) - .ok_or(VirtualMachineError::MissingConstant(N1))?; - let n2 = constants - .get(N2) - .ok_or(VirtualMachineError::MissingConstant(N2))?; + .ok_or(HintError::MissingConstant(BASE_86))?; + let n0 = constants.get(N0).ok_or(HintError::MissingConstant(N0))?; + let n1 = constants.get(N1).ok_or(HintError::MissingConstant(N1))?; + let n2 = constants.get(N2).ok_or(HintError::MissingConstant(N2))?; n2 * base * base + n1 * base + n0 }; @@ -97,14 +85,14 @@ pub fn get_point_from_x( ids_data: &HashMap, ap_tracking: &ApTracking, constants: &HashMap, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let beta = constants .get(BETA) - .ok_or(VirtualMachineError::MissingConstant(BETA))?; + .ok_or(HintError::MissingConstant(BETA))?; let secp_p = bigint!(1).shl(256usize) - constants .get(SECP_REM) - .ok_or(VirtualMachineError::MissingConstant(SECP_REM))?; + .ok_or(HintError::MissingConstant(SECP_REM))?; let x_cube_int = pack_from_var_name("x_cube", vm, ids_data, ap_tracking)?.mod_floor(&secp_p); let y_cube_int = (x_cube_int + beta).mod_floor(&secp_p); @@ -126,6 +114,7 @@ mod tests { use crate::hint_processor::builtin_hint_processor::builtin_hint_processor_definition::HintProcessorData; use crate::hint_processor::builtin_hint_processor::hint_code; use crate::hint_processor::hint_processor_definition::HintProcessor; + use crate::vm::errors::vm_errors::VirtualMachineError; use crate::{ bigint, bigint_str, types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, @@ -175,11 +164,11 @@ mod tests { let mut exec_scopes = scope![("a", bigint!(0)), ("b", bigint!(1)), ("res", bigint!(1))]; assert_eq!( Err( - VirtualMachineError::SafeDivFail( + HintError::Internal(VirtualMachineError::SafeDivFail( bigint!(1_usize), bigint_str!(b"115792089237316195423570985008687907852837564279074904382605163141518161494337"), ) - ), + )), div_mod_n_safe_div( &mut exec_scopes, &[ diff --git a/src/hint_processor/builtin_hint_processor/segments.rs b/src/hint_processor/builtin_hint_processor/segments.rs index 3f62bceabf..e00a8fe844 100644 --- a/src/hint_processor/builtin_hint_processor/segments.rs +++ b/src/hint_processor/builtin_hint_processor/segments.rs @@ -5,6 +5,7 @@ use crate::hint_processor::{ use crate::serde::deserialize_program::ApTracking; +use crate::vm::errors::hint_errors::HintError; use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::vm_core::VirtualMachine; @@ -20,11 +21,12 @@ pub fn relocate_segment( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let src_ptr = get_ptr_from_var_name("src_ptr", vm, ids_data, ap_tracking)?; let dest_ptr = get_ptr_from_var_name("dest_ptr", vm, ids_data, ap_tracking)?; - vm.add_relocation_rule(src_ptr, dest_ptr)?; + vm.add_relocation_rule(src_ptr, dest_ptr) + .map_err(VirtualMachineError::MemoryError)?; Ok(()) } @@ -39,7 +41,7 @@ pub fn temporary_array( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let temp_segment = vm.add_temporary_segment(); insert_value_from_var_name("temporary_array", temp_segment, vm, ids_data, ap_tracking)?; diff --git a/src/hint_processor/builtin_hint_processor/set.rs b/src/hint_processor/builtin_hint_processor/set.rs index 67732d2585..42fc0ed4ef 100644 --- a/src/hint_processor/builtin_hint_processor/set.rs +++ b/src/hint_processor/builtin_hint_processor/set.rs @@ -1,6 +1,7 @@ use crate::bigint; use crate::serde::deserialize_program::ApTracking; use crate::types::relocatable::MaybeRelocatable; +use crate::vm::errors::hint_errors::HintError; use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::vm_core::VirtualMachine; use num_bigint::BigInt; @@ -16,7 +17,7 @@ pub fn set_add( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let set_ptr = get_ptr_from_var_name("set_ptr", vm, ids_data, ap_tracking)?; let elm_size = get_integer_from_var_name("elm_size", vm, ids_data, ap_tracking)? .to_usize() @@ -25,14 +26,14 @@ pub fn set_add( let set_end_ptr = get_ptr_from_var_name("set_end_ptr", vm, ids_data, ap_tracking)?; if elm_size.is_zero() { - return Err(VirtualMachineError::ValueNotPositive(bigint!(elm_size))); + Err(VirtualMachineError::ValueNotPositive(bigint!(elm_size)))?; } let elm = vm .get_range(&MaybeRelocatable::from(elm_ptr), elm_size) .map_err(VirtualMachineError::MemoryError)?; if set_ptr > set_end_ptr { - return Err(VirtualMachineError::InvalidSetRange( + return Err(HintError::InvalidSetRange( MaybeRelocatable::from(set_ptr), MaybeRelocatable::from(set_end_ptr), )); @@ -142,7 +143,7 @@ mod tests { let (mut vm, ids_data) = init_vm_ids_data(None, Some(-2), None, None); assert_eq!( run_hint!(vm, ids_data, HINT_CODE), - Err(VirtualMachineError::BigintToUsizeFail) + Err(HintError::Internal(VirtualMachineError::BigintToUsizeFail)) ); } @@ -152,7 +153,9 @@ mod tests { let (mut vm, ids_data) = init_vm_ids_data(None, Some(0), None, None); assert_eq!( run_hint!(vm, ids_data, HINT_CODE), - Err(VirtualMachineError::ValueNotPositive(int)) + Err(HintError::Internal(VirtualMachineError::ValueNotPositive( + int + ))) ); } #[test] @@ -160,7 +163,7 @@ mod tests { let (mut vm, ids_data) = init_vm_ids_data(Some((2, 3)), None, None, None); assert_eq!( run_hint!(vm, ids_data, HINT_CODE), - Err(VirtualMachineError::InvalidSetRange( + Err(HintError::InvalidSetRange( MaybeRelocatable::from((2, 3)), MaybeRelocatable::from((2, 2)), )) diff --git a/src/hint_processor/builtin_hint_processor/sha256_utils.rs b/src/hint_processor/builtin_hint_processor/sha256_utils.rs index eddeb44bca..6bde14c66c 100644 --- a/src/hint_processor/builtin_hint_processor/sha256_utils.rs +++ b/src/hint_processor/builtin_hint_processor/sha256_utils.rs @@ -3,6 +3,7 @@ use crate::hint_processor::builtin_hint_processor::hint_utils::get_ptr_from_var_ use crate::hint_processor::builtin_hint_processor::hint_utils::insert_value_from_var_name; use crate::hint_processor::hint_processor_utils::bigint_to_u32; use crate::types::relocatable::MaybeRelocatable; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use crate::{ bigint, serde::deserialize_program::ApTracking, vm::errors::vm_errors::VirtualMachineError, @@ -27,7 +28,7 @@ pub fn sha256_input( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let n_bytes = get_integer_from_var_name("n_bytes", vm, ids_data, ap_tracking)?; let n_bytes = n_bytes.as_ref(); @@ -48,7 +49,7 @@ pub fn sha256_main( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let input_ptr = get_ptr_from_var_name("sha256_start", vm, ids_data, ap_tracking)?; let mut message: Vec = Vec::with_capacity(4 * SHA256_INPUT_CHUNK_SIZE_FELTS); @@ -80,7 +81,7 @@ pub fn sha256_finalize( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let message: Vec = vec![0; 64]; let mut iv = IV; diff --git a/src/hint_processor/builtin_hint_processor/squash_dict_utils.rs b/src/hint_processor/builtin_hint_processor/squash_dict_utils.rs index 498be23f8f..b5e451c36b 100644 --- a/src/hint_processor/builtin_hint_processor/squash_dict_utils.rs +++ b/src/hint_processor/builtin_hint_processor/squash_dict_utils.rs @@ -1,5 +1,6 @@ use crate::hint_processor::hint_processor_definition::HintReference; use crate::types::exec_scope::ExecutionScopes; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use num_bigint::BigInt; use num_integer::Integer; @@ -18,7 +19,7 @@ use crate::{ fn get_access_indices( exec_scopes: &mut ExecutionScopes, -) -> Result<&HashMap>, VirtualMachineError> { +) -> Result<&HashMap>, HintError> { let mut access_indices: Option<&HashMap>> = None; if let Some(variable) = exec_scopes .get_local_variables_mut()? @@ -28,8 +29,7 @@ fn get_access_indices( access_indices = Some(py_access_indices); } } - access_indices - .ok_or_else(|| VirtualMachineError::VariableNotInScopeError("access_indices".to_string())) + access_indices.ok_or_else(|| HintError::VariableNotInScopeError("access_indices".to_string())) } /*Implements hint: @@ -42,7 +42,7 @@ pub fn squash_dict_inner_first_iteration( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Check that access_indices and key are in scope let key = exec_scopes.get::("key")?; let range_check_ptr = get_ptr_from_var_name("range_check_ptr", vm, ids_data, ap_tracking)?; @@ -50,19 +50,20 @@ pub fn squash_dict_inner_first_iteration( //Get current_indices from access_indices let mut current_access_indices = access_indices .get(&key) - .ok_or_else(|| VirtualMachineError::NoKeyInAccessIndices(key.clone()))? + .ok_or_else(|| HintError::NoKeyInAccessIndices(key.clone()))? .clone(); current_access_indices.sort(); current_access_indices.reverse(); //Get current_access_index let first_val = current_access_indices .pop() - .ok_or(VirtualMachineError::EmptyCurrentAccessIndices)?; + .ok_or(HintError::EmptyCurrentAccessIndices)?; //Store variables in scope exec_scopes.insert_value("current_access_indices", current_access_indices); exec_scopes.insert_value("current_access_index", first_val.clone()); //Insert current_accesss_index into range_check_ptr vm.insert_value(&range_check_ptr, first_val) + .map_err(HintError::Internal) } // Implements Hint: ids.should_skip_loop = 0 if current_access_indices else 1 @@ -71,7 +72,7 @@ pub fn squash_dict_inner_skip_loop( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Check that current_access_indices is in scope let current_access_indices = exec_scopes.get_list_ref::("current_access_indices")?; //Main Logic @@ -99,7 +100,7 @@ pub fn squash_dict_inner_check_access_index( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Check that current_access_indices and current_access_index are in scope let current_access_index = exec_scopes.get::("current_access_index")?; let current_access_indices = @@ -107,7 +108,7 @@ pub fn squash_dict_inner_check_access_index( //Main Logic let new_access_index = current_access_indices .pop() - .ok_or(VirtualMachineError::EmptyCurrentAccessIndices)?; + .ok_or(HintError::EmptyCurrentAccessIndices)?; let index_delta_minus1 = new_access_index.clone() - current_access_index - bigint!(1); //loop_temps.delta_minus1 = loop_temps + 0 as it is the first field of the struct //Insert loop_temps.delta_minus1 into memory @@ -123,7 +124,7 @@ pub fn squash_dict_inner_continue_loop( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Check that ids contains the reference id for each variable used by the hint //Get addr for ids variables let loop_temps_addr = get_relocatable_from_var_name("loop_temps", vm, ids_data, ap_tracking)?; @@ -139,16 +140,15 @@ pub fn squash_dict_inner_continue_loop( //Insert loop_temps.delta_minus1 into memory let should_continue_addr = loop_temps_addr + 3; vm.insert_value(&should_continue_addr, should_continue) + .map_err(HintError::Internal) } // Implements Hint: assert len(current_access_indices) == 0 -pub fn squash_dict_inner_len_assert( - exec_scopes: &mut ExecutionScopes, -) -> Result<(), VirtualMachineError> { +pub fn squash_dict_inner_len_assert(exec_scopes: &mut ExecutionScopes) -> Result<(), HintError> { //Check that current_access_indices is in scope let current_access_indices = exec_scopes.get_list_ref::("current_access_indices")?; if !current_access_indices.is_empty() { - return Err(VirtualMachineError::CurrentAccessIndicesNotEmpty); + return Err(HintError::CurrentAccessIndicesNotEmpty); } Ok(()) } @@ -159,17 +159,17 @@ pub fn squash_dict_inner_used_accesses_assert( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let key = exec_scopes.get::("key")?; let n_used_accesses = get_integer_from_var_name("n_used_accesses", vm, ids_data, ap_tracking)?; let access_indices = get_access_indices(exec_scopes)?; //Main Logic let access_indices_at_key = access_indices .get(&key) - .ok_or_else(|| VirtualMachineError::NoKeyInAccessIndices(key.clone()))?; + .ok_or_else(|| HintError::NoKeyInAccessIndices(key.clone()))?; if n_used_accesses.as_ref() != &bigint!(access_indices_at_key.len()) { - return Err(VirtualMachineError::NumUsedAccessesAssertFail( + return Err(HintError::NumUsedAccessesAssertFail( n_used_accesses.into_owned(), access_indices_at_key.len(), key, @@ -181,11 +181,11 @@ pub fn squash_dict_inner_used_accesses_assert( // Implements Hint: assert len(keys) == 0 pub fn squash_dict_inner_assert_len_keys( exec_scopes: &mut ExecutionScopes, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Check that current_access_indices is in scope let keys = exec_scopes.get_list_ref::("keys")?; if !keys.is_empty() { - return Err(VirtualMachineError::KeysNotEmpty); + return Err(HintError::KeysNotEmpty); }; Ok(()) } @@ -198,10 +198,10 @@ pub fn squash_dict_inner_next_key( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Check that current_access_indices is in scope let keys = exec_scopes.get_mut_list_ref::("keys")?; - let next_key = keys.pop().ok_or(VirtualMachineError::EmptyKeys)?; + let next_key = keys.pop().ok_or(HintError::EmptyKeys)?; //Insert next_key into ids.next_keys insert_value_from_var_name("next_key", next_key.clone(), vm, ids_data, ap_tracking)?; //Update local variables @@ -235,7 +235,7 @@ pub fn squash_dict( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { //Get necessary variables addresses from ids let address = get_ptr_from_var_name("dict_accesses", vm, ids_data, ap_tracking)?; let ptr_diff = get_integer_from_var_name("ptr_diff", vm, ids_data, ap_tracking)?; @@ -245,12 +245,12 @@ pub fn squash_dict( let range_check_bound = range_check_builtin._bound.clone(); //Main Logic if ptr_diff.mod_floor(&bigint!(DICT_ACCESS_SIZE)) != bigint!(0) { - return Err(VirtualMachineError::PtrDiffNotDivisibleByDictAccessSize); + return Err(HintError::PtrDiffNotDivisibleByDictAccessSize); } let squash_dict_max_size = exec_scopes.get::("__squash_dict_max_size"); if let Ok(max_size) = squash_dict_max_size { if n_accesses.as_ref() > &max_size { - return Err(VirtualMachineError::SquashDictMaxSizeExceeded( + return Err(HintError::SquashDictMaxSizeExceeded( max_size, n_accesses.into_owned(), )); @@ -258,7 +258,7 @@ pub fn squash_dict( }; let n_accesses_usize = n_accesses .to_usize() - .ok_or_else(|| VirtualMachineError::NAccessesTooBig(n_accesses.into_owned()))?; + .ok_or_else(|| HintError::NAccessesTooBig(n_accesses.into_owned()))?; //A map from key to the list of indices accessing it. let mut access_indices = HashMap::>::new(); for i in 0..n_accesses_usize { @@ -282,7 +282,7 @@ pub fn squash_dict( bigint!(0) }; insert_value_from_var_name("big_keys", big_keys, vm, ids_data, ap_tracking)?; - let key = keys.pop().ok_or(VirtualMachineError::EmptyKeys)?; + let key = keys.pop().ok_or(HintError::EmptyKeys)?; insert_value_from_var_name("first_key", key.clone(), vm, ids_data, ap_tracking)?; //Insert local variables into scope exec_scopes.insert_value("access_indices", access_indices); @@ -376,7 +376,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::EmptyCurrentAccessIndices) + Err(HintError::EmptyCurrentAccessIndices) ); } @@ -395,9 +395,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::VariableNotInScopeError(String::from( - "key" - ))) + Err(HintError::VariableNotInScopeError(String::from("key"))) ); } @@ -494,7 +492,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::EmptyCurrentAccessIndices) + Err(HintError::EmptyCurrentAccessIndices) ); } @@ -560,7 +558,7 @@ mod tests { //Hint should produce an error if assertion fails assert_eq!( run_hint!(vm, HashMap::new(), hint_code, &mut exec_scopes), - Err(VirtualMachineError::CurrentAccessIndicesNotEmpty) + Err(HintError::CurrentAccessIndicesNotEmpty) ); } @@ -606,7 +604,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::NumUsedAccessesAssertFail( + Err(HintError::NumUsedAccessesAssertFail( bigint!(5), 4, bigint!(5) @@ -634,9 +632,9 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::ExpectedInteger( + Err(HintError::Internal(VirtualMachineError::ExpectedInteger( MaybeRelocatable::from((1, 0)) - )) + ))) ); } @@ -664,7 +662,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, HashMap::new(), hint_code, &mut exec_scopes), - Err(VirtualMachineError::KeysNotEmpty) + Err(HintError::KeysNotEmpty) ); } @@ -676,9 +674,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, HashMap::new(), hint_code), - Err(VirtualMachineError::VariableNotInScopeError(String::from( - "keys" - ))) + Err(HintError::VariableNotInScopeError(String::from("keys"))) ); } @@ -719,7 +715,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::EmptyKeys) + Err(HintError::EmptyKeys) ); } @@ -909,10 +905,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code, &mut exec_scopes), - Err(VirtualMachineError::SquashDictMaxSizeExceeded( - bigint!(1), - bigint!(2) - )) + Err(HintError::SquashDictMaxSizeExceeded(bigint!(1), bigint!(2))) ); } @@ -947,7 +940,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::PtrDiffNotDivisibleByDictAccessSize) + Err(HintError::PtrDiffNotDivisibleByDictAccessSize) ); } #[test] @@ -987,7 +980,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::NAccessesTooBig(bigint_str!( + Err(HintError::NAccessesTooBig(bigint_str!( b"3618502761706184546546682988428055018603476541694452277432519575032261771265" ))) ); diff --git a/src/hint_processor/builtin_hint_processor/uint256_utils.rs b/src/hint_processor/builtin_hint_processor/uint256_utils.rs index 9e86abefca..c9f3faa697 100644 --- a/src/hint_processor/builtin_hint_processor/uint256_utils.rs +++ b/src/hint_processor/builtin_hint_processor/uint256_utils.rs @@ -4,7 +4,7 @@ use crate::hint_processor::builtin_hint_processor::hint_utils::{ }; use crate::math_utils::isqrt; use crate::serde::deserialize_program::ApTracking; -use crate::vm::errors::vm_errors::VirtualMachineError; +use crate::vm::errors::hint_errors::HintError; use crate::vm::vm_core::VirtualMachine; use num_bigint::BigInt; use num_integer::{div_rem, Integer}; @@ -30,7 +30,7 @@ pub fn uint256_add( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let shift: BigInt = bigint!(2).pow(128); let a_relocatable = get_relocatable_from_var_name("a", vm, ids_data, ap_tracking)?; @@ -76,7 +76,7 @@ pub fn split_64( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a = get_integer_from_var_name("a", vm, ids_data, ap_tracking)?; let mut digits = a.iter_u64_digits(); let low = bigint!(digits.next().unwrap_or(0u64)); @@ -104,7 +104,7 @@ pub fn uint256_sqrt( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let n_addr = get_relocatable_from_var_name("n", vm, ids_data, ap_tracking)?; let root_addr = get_relocatable_from_var_name("root", vm, ids_data, ap_tracking)?; let n_low = vm.get_integer(&n_addr)?; @@ -123,13 +123,14 @@ pub fn uint256_sqrt( let root = isqrt(&(n_high.shl(128_usize) + n_low))?; if root.is_negative() || root >= bigint!(1).shl(128) { - return Err(VirtualMachineError::AssertionFailed(format!( + return Err(HintError::AssertionFailed(format!( "assert 0 <= {} < 2 ** 128", &root ))); } vm.insert_value(&root_addr, root)?; vm.insert_value(&(root_addr + 1), bigint!(0)) + .map_err(HintError::Internal) } /* @@ -140,7 +141,7 @@ pub fn uint256_signed_nn( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a_addr = get_relocatable_from_var_name("a", vm, ids_data, ap_tracking)?; let a_high = vm.get_integer(&(a_addr + 1))?; //Main logic @@ -171,7 +172,7 @@ pub fn uint256_unsigned_div_rem( vm: &mut VirtualMachine, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let a_addr = get_relocatable_from_var_name("a", vm, ids_data, ap_tracking)?; let div_addr = get_relocatable_from_var_name("div", vm, ids_data, ap_tracking)?; let quotient_addr = get_relocatable_from_var_name("quotient", vm, ids_data, ap_tracking)?; @@ -215,7 +216,8 @@ pub fn uint256_unsigned_div_rem( //Insert ids.remainder.low vm.insert_value(&remainder_addr, remainder_low)?; //Insert ids.remainder.high - vm.insert_value(&(remainder_addr + 1), remainder_high) + vm.insert_value(&(remainder_addr + 1), remainder_high)?; + Ok(()) } #[cfg(test)] @@ -231,6 +233,7 @@ mod tests { use crate::types::relocatable::Relocatable; use crate::utils::test_utils::*; use crate::vm::errors::memory_errors::MemoryError; + use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::vm_core::VirtualMachine; use crate::vm::vm_memory::memory::Memory; use crate::{bigint, vm::runners::builtin_runner::RangeCheckBuiltinRunner}; @@ -280,13 +283,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 12)), MaybeRelocatable::from(bigint!(2)), MaybeRelocatable::from(bigint!(0)) ) - )) + ))) ); } @@ -349,13 +352,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 10)), MaybeRelocatable::from(bigint!(0)), MaybeRelocatable::from(bigint_str!(b"7249717543555297151")) ) - )) + ))) ); } @@ -390,7 +393,7 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::AssertionFailed(String::from( + Err(HintError::AssertionFailed(String::from( "assert 0 <= 340282366920938463463374607431768211456 < 2 ** 128" ))) ); @@ -409,13 +412,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 5)), MaybeRelocatable::from(bigint!(1)), MaybeRelocatable::from(bigint_str!(b"48805497317890012913")), ) - )) + ))) ); } @@ -477,13 +480,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 5)), MaybeRelocatable::from(bigint!(55)), MaybeRelocatable::from(bigint!(1)), ) - )) + ))) ); } @@ -531,13 +534,13 @@ mod tests { //Execute the hint assert_eq!( run_hint!(vm, ids_data, hint_code), - Err(VirtualMachineError::MemoryError( + Err(HintError::Internal(VirtualMachineError::MemoryError( MemoryError::InconsistentMemory( MaybeRelocatable::from((1, 10)), MaybeRelocatable::from(bigint!(0)), MaybeRelocatable::from(bigint!(10)), ) - )) + ))) ); } } diff --git a/src/hint_processor/builtin_hint_processor/usort.rs b/src/hint_processor/builtin_hint_processor/usort.rs index 8e86742121..fc1b0e7020 100644 --- a/src/hint_processor/builtin_hint_processor/usort.rs +++ b/src/hint_processor/builtin_hint_processor/usort.rs @@ -8,14 +8,14 @@ use crate::{ }, serde::deserialize_program::ApTracking, types::exec_scope::ExecutionScopes, - vm::{errors::vm_errors::VirtualMachineError, vm_core::VirtualMachine}, + vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, }; use num_bigint::BigInt; use num_traits::ToPrimitive; use std::{any::Any, collections::HashMap}; -pub fn usort_enter_scope(exec_scopes: &mut ExecutionScopes) -> Result<(), VirtualMachineError> { +pub fn usort_enter_scope(exec_scopes: &mut ExecutionScopes) -> Result<(), HintError> { if let Ok(usort_max_size) = exec_scopes.get::("usort_max_size") { let boxed_max_size: Box = Box::new(usort_max_size); exec_scopes.enter_scope(HashMap::from([( @@ -33,17 +33,15 @@ pub fn usort_body( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let input_ptr = get_ptr_from_var_name("input", vm, ids_data, ap_tracking)?; let usort_max_size = exec_scopes.get::("usort_max_size"); let input_len = get_integer_from_var_name("input_len", vm, ids_data, ap_tracking)?; - let input_len_u64 = input_len - .to_u64() - .ok_or(VirtualMachineError::BigintToUsizeFail)?; + let input_len_u64 = input_len.to_u64().ok_or(HintError::BigintToUsizeFail)?; if let Ok(usort_max_size) = usort_max_size { if input_len_u64 > usort_max_size { - return Err(VirtualMachineError::UsortOutOfRange( + return Err(HintError::UsortOutOfRange( usort_max_size, input_len.into_owned(), )); @@ -84,7 +82,8 @@ pub fn usort_body( vm, ids_data, ap_tracking, - ) + )?; + Ok(()) } pub fn verify_usort( @@ -92,26 +91,24 @@ pub fn verify_usort( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let value = get_integer_from_var_name("value", vm, ids_data, ap_tracking)?.clone(); let mut positions = exec_scopes .get_mut_dict_ref::>("positions_dict")? .remove(&value) - .ok_or(VirtualMachineError::UnexpectedPositionsDictFail)?; + .ok_or(HintError::UnexpectedPositionsDictFail)?; positions.reverse(); exec_scopes.insert_value("positions", positions); exec_scopes.insert_value("last_pos", bigint!(0)); Ok(()) } -pub fn verify_multiplicity_assert( - exec_scopes: &mut ExecutionScopes, -) -> Result<(), VirtualMachineError> { +pub fn verify_multiplicity_assert(exec_scopes: &mut ExecutionScopes) -> Result<(), HintError> { let positions_len = exec_scopes.get_list_ref::("positions")?.len(); if positions_len == 0 { Ok(()) } else { - Err(VirtualMachineError::PositionsLengthNotZero) + Err(HintError::PositionsLengthNotZero) } } @@ -120,11 +117,11 @@ pub fn verify_multiplicity_body( exec_scopes: &mut ExecutionScopes, ids_data: &HashMap, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let current_pos = exec_scopes .get_mut_list_ref::("positions")? .pop() - .ok_or(VirtualMachineError::CouldntPopPositions)?; + .ok_or(HintError::CouldntPopPositions)?; let pos_diff = bigint!(current_pos) - exec_scopes.get::("last_pos")?; insert_value_from_var_name("next_item_index", pos_diff, vm, ids_data, ap_tracking)?; exec_scopes.insert_value("last_pos", bigint!(current_pos + 1)); @@ -169,7 +166,7 @@ mod tests { let mut exec_scopes = scope![("usort_max_size", 1_u64)]; assert_eq!( run_hint!(vm, ids_data, USORT_BODY, &mut exec_scopes), - Err(VirtualMachineError::UsortOutOfRange(1, bigint!(5))) + Err(HintError::UsortOutOfRange(1, bigint!(5))) ); } } diff --git a/src/hint_processor/hint_processor_definition.rs b/src/hint_processor/hint_processor_definition.rs index 1dc282a2fb..18e8e182bb 100644 --- a/src/hint_processor/hint_processor_definition.rs +++ b/src/hint_processor/hint_processor_definition.rs @@ -3,6 +3,7 @@ use crate::serde::deserialize_program::ApTracking; use crate::serde::deserialize_program::OffsetValue; use crate::types::exec_scope::ExecutionScopes; use crate::types::instruction::Register; +use crate::vm::errors::hint_errors::HintError; use crate::vm::errors::vm_errors::VirtualMachineError; use crate::vm::vm_core::VirtualMachine; use num_bigint::BigInt; @@ -25,7 +26,7 @@ pub trait HintProcessor { hint_data: &Box, //Constant values extracted from the program specification. constants: &HashMap, - ) -> Result<(), VirtualMachineError>; + ) -> Result<(), HintError>; //Transforms hint data outputed by the VM into whichever format will be later used by execute_hint fn compile_hint( @@ -57,12 +58,12 @@ fn get_ids_data( let name = path .rsplit('.') .next() - .ok_or(VirtualMachineError::FailedToGetIds)?; + .ok_or(VirtualMachineError::Unexpected)?; ids_data.insert( name.to_string(), references .get(ref_id) - .ok_or(VirtualMachineError::FailedToGetIds)? + .ok_or(VirtualMachineError::Unexpected)? .clone(), ); } diff --git a/src/hint_processor/hint_processor_utils.rs b/src/hint_processor/hint_processor_utils.rs index aa611f52d6..28cd5f1395 100644 --- a/src/hint_processor/hint_processor_utils.rs +++ b/src/hint_processor/hint_processor_utils.rs @@ -9,7 +9,10 @@ use crate::{ instruction::Register, relocatable::{MaybeRelocatable, Relocatable}, }, - vm::{errors::vm_errors::VirtualMachineError, vm_core::VirtualMachine}, + vm::{ + errors::{hint_errors::HintError, vm_errors::VirtualMachineError}, + vm_core::VirtualMachine, + }, }; use super::hint_processor_definition::HintReference; @@ -20,9 +23,10 @@ pub fn insert_value_from_reference( vm: &mut VirtualMachine, hint_reference: &HintReference, ap_tracking: &ApTracking, -) -> Result<(), VirtualMachineError> { +) -> Result<(), HintError> { let var_addr = compute_addr_from_reference(hint_reference, vm, ap_tracking)?; vm.insert_value(&var_addr, value) + .map_err(HintError::Internal) } ///Returns the Integer value stored in the given ids variable @@ -30,7 +34,7 @@ pub fn get_integer_from_reference<'a>( vm: &'a VirtualMachine, hint_reference: &'a HintReference, ap_tracking: &ApTracking, -) -> Result, VirtualMachineError> { +) -> Result, HintError> { // if the reference register is none, this means it is an immediate value and we // should return that value. @@ -39,7 +43,7 @@ pub fn get_integer_from_reference<'a>( } let var_addr = compute_addr_from_reference(hint_reference, vm, ap_tracking)?; - vm.get_integer(&var_addr) + vm.get_integer(&var_addr).map_err(HintError::Internal) } ///Returns the Relocatable value stored in the given ids variable @@ -47,7 +51,7 @@ pub fn get_ptr_from_reference( vm: &VirtualMachine, hint_reference: &HintReference, ap_tracking: &ApTracking, -) -> Result { +) -> Result { let var_addr = compute_addr_from_reference(hint_reference, vm, ap_tracking)?; if hint_reference.dereference { Ok(vm.get_relocatable(&var_addr)?) @@ -63,7 +67,7 @@ pub fn compute_addr_from_reference( vm: &VirtualMachine, //ApTracking of the Hint itself hint_ap_tracking: &ApTracking, -) -> Result { +) -> Result { let offset1 = if let OffsetValue::Reference(_register, _offset, _deref) = &hint_reference.offset1 { get_offset_value_reference( @@ -74,7 +78,7 @@ pub fn compute_addr_from_reference( )? .get_relocatable()? } else { - return Err(VirtualMachineError::NoRegisterInReference); + return Err(HintError::NoRegisterInReference); }; match &hint_reference.offset2 { @@ -91,7 +95,7 @@ pub fn compute_addr_from_reference( Ok(offset1 + bigint_to_usize(value.get_int_ref()?)?) } OffsetValue::Value(value) => Ok(offset1 + *value), - _ => Err(VirtualMachineError::NoRegisterInReference), + _ => Err(HintError::NoRegisterInReference), } } @@ -99,16 +103,16 @@ fn apply_ap_tracking_correction( ap: &Relocatable, ref_ap_tracking: &ApTracking, hint_ap_tracking: &ApTracking, -) -> Result { +) -> Result { // check that both groups are the same if ref_ap_tracking.group != hint_ap_tracking.group { - return Err(VirtualMachineError::InvalidTrackingGroup( + return Err(HintError::InvalidTrackingGroup( ref_ap_tracking.group, hint_ap_tracking.group, )); } let ap_diff = hint_ap_tracking.offset - ref_ap_tracking.offset; - ap.sub(ap_diff) + ap.sub(ap_diff).map_err(HintError::Internal) } //Tries to convert a BigInt value to usize @@ -128,15 +132,15 @@ fn get_offset_value_reference( hint_reference: &HintReference, hint_ap_tracking: &ApTracking, offset_value: &OffsetValue, -) -> Result { +) -> Result { // let (register, offset , deref) = if let OffsetValue::Reference(register, offset ,deref ) = offset_value { // (register, offset_value, deref) // } else { - // return Err(VirtualMachineError::FailedToGetIds); + // return Err(HintError::FailedToGetIds); // }; let (register, offset, deref) = match offset_value { OffsetValue::Reference(register, offset, deref) => (register, offset, deref), - _ => return Err(VirtualMachineError::FailedToGetIds), + _ => return Err(HintError::FailedToGetIds), }; let base_addr = if register == &Register::FP { @@ -145,20 +149,20 @@ fn get_offset_value_reference( let var_ap_trackig = hint_reference .ap_tracking_data .as_ref() - .ok_or(VirtualMachineError::NoneApTrackingData)?; + .ok_or(HintError::NoneApTrackingData)?; apply_ap_tracking_correction(&vm.get_ap(), var_ap_trackig, hint_ap_tracking)? }; if offset.is_negative() && base_addr.offset < offset.abs() as usize { - return Err(VirtualMachineError::FailedToGetIds); + return Err(HintError::FailedToGetIds); } if *deref { Ok(vm .get_maybe(&(base_addr + *offset)) - .map_err(|_| VirtualMachineError::FailedToGetIds)? - .ok_or(VirtualMachineError::FailedToGetIds)?) + .map_err(|_| HintError::FailedToGetIds)? + .ok_or(HintError::FailedToGetIds)?) } else { Ok((base_addr + *offset).into()) } @@ -243,7 +247,7 @@ mod tests { assert_eq!( compute_addr_from_reference(&hint_reference, &vm, &ApTracking::new()), - Err(VirtualMachineError::NoRegisterInReference) + Err(HintError::NoRegisterInReference) ); } @@ -257,7 +261,7 @@ mod tests { assert_eq!( compute_addr_from_reference(&hint_reference, &vm, &ApTracking::new()), - Err(VirtualMachineError::FailedToGetIds) + Err(HintError::FailedToGetIds) ); } @@ -270,7 +274,7 @@ mod tests { assert_eq!( apply_ap_tracking_correction(&relocatable!(1, 0), &ref_ap_tracking, &hint_ap_tracking), - Err(VirtualMachineError::InvalidTrackingGroup(1, 2)) + Err(HintError::InvalidTrackingGroup(1, 2)) ); } } diff --git a/src/main.rs b/src/main.rs index 03f78f38a4..c56dcc20a0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -57,7 +57,10 @@ fn main() -> Result<(), CairoRunError> { &mut hint_executor, ) { Ok(runner) => runner, - Err(error) => return Err(error), + Err(error) => { + println!("{}", error); + return Err(error); + } }; if let Some(trace_path) = args.trace_file { diff --git a/src/types/exec_scope.rs b/src/types/exec_scope.rs index 1d9a1c7556..20559ecf6c 100644 --- a/src/types/exec_scope.rs +++ b/src/types/exec_scope.rs @@ -1,7 +1,7 @@ use crate::{ any_box, hint_processor::builtin_hint_processor::dict_manager::DictManager, - vm::errors::{exec_scope_errors::ExecScopeError, vm_errors::VirtualMachineError}, + vm::errors::{exec_scope_errors::ExecScopeError, hint_errors::HintError}, }; use std::{any::Any, cell::RefCell, collections::HashMap, rc::Rc}; @@ -32,21 +32,17 @@ impl ExecutionScopes { ///Returns a mutable reference to the dictionary containing the variables present in the current scope pub fn get_local_variables_mut( &mut self, - ) -> Result<&mut HashMap>, VirtualMachineError> { + ) -> Result<&mut HashMap>, HintError> { self.data .last_mut() - .ok_or(VirtualMachineError::MainScopeError( - ExecScopeError::NoScopeError, - )) + .ok_or(HintError::FromScopeError(ExecScopeError::NoScopeError)) } ///Returns a dictionary containing the variables present in the current scope - pub fn get_local_variables( - &self, - ) -> Result<&HashMap>, VirtualMachineError> { - self.data.last().ok_or(VirtualMachineError::MainScopeError( - ExecScopeError::NoScopeError, - )) + pub fn get_local_variables(&self) -> Result<&HashMap>, HintError> { + self.data + .last() + .ok_or(HintError::FromScopeError(ExecScopeError::NoScopeError)) } ///Removes a variable from the current scope given its name @@ -64,120 +60,110 @@ impl ExecutionScopes { } ///Returns the value in the current execution scope that matches the name and is of the given generic type - pub fn get(&self, name: &str) -> Result { + pub fn get(&self, name: &str) -> Result { let mut val: Option = None; if let Some(variable) = self.get_local_variables()?.get(name) { if let Some(int) = variable.downcast_ref::() { val = Some(int.clone()); } } - val.ok_or_else(|| VirtualMachineError::VariableNotInScopeError(name.to_string())) + val.ok_or_else(|| HintError::VariableNotInScopeError(name.to_string())) } ///Returns a reference to the value in the current execution scope that matches the name and is of the given generic type - pub fn get_ref(&self, name: &str) -> Result<&T, VirtualMachineError> { + pub fn get_ref(&self, name: &str) -> Result<&T, HintError> { let mut val: Option<&T> = None; if let Some(variable) = self.get_local_variables()?.get(name) { if let Some(int) = variable.downcast_ref::() { val = Some(int); } } - val.ok_or_else(|| VirtualMachineError::VariableNotInScopeError(name.to_string())) + val.ok_or_else(|| HintError::VariableNotInScopeError(name.to_string())) } ///Returns a mutable reference to the value in the current execution scope that matches the name and is of the given generic type - pub fn get_mut_ref(&mut self, name: &str) -> Result<&mut T, VirtualMachineError> { + pub fn get_mut_ref(&mut self, name: &str) -> Result<&mut T, HintError> { let mut val: Option<&mut T> = None; if let Some(variable) = self.get_local_variables_mut()?.get_mut(name) { if let Some(int) = variable.downcast_mut::() { val = Some(int); } } - val.ok_or_else(|| VirtualMachineError::VariableNotInScopeError(name.to_string())) + val.ok_or_else(|| HintError::VariableNotInScopeError(name.to_string())) } ///Returns the value in the current execution scope that matches the name - pub fn get_any_boxed_ref(&self, name: &str) -> Result<&Box, VirtualMachineError> { + pub fn get_any_boxed_ref(&self, name: &str) -> Result<&Box, HintError> { if let Some(variable) = self.get_local_variables()?.get(name) { return Ok(variable); } - Err(VirtualMachineError::VariableNotInScopeError( - name.to_string(), - )) + Err(HintError::VariableNotInScopeError(name.to_string())) } ///Returns the value in the current execution scope that matches the name - pub fn get_any_boxed_mut( - &mut self, - name: &str, - ) -> Result<&mut Box, VirtualMachineError> { + pub fn get_any_boxed_mut(&mut self, name: &str) -> Result<&mut Box, HintError> { if let Some(variable) = self.get_local_variables_mut()?.get_mut(name) { return Ok(variable); } - Err(VirtualMachineError::VariableNotInScopeError( - name.to_string(), - )) + Err(HintError::VariableNotInScopeError(name.to_string())) } ///Returns the value in the current execution scope that matches the name and is of type List - pub fn get_list(&self, name: &str) -> Result, VirtualMachineError> { + pub fn get_list(&self, name: &str) -> Result, HintError> { let mut val: Option> = None; if let Some(variable) = self.get_local_variables()?.get(name) { if let Some(list) = variable.downcast_ref::>() { val = Some(list.clone()); } } - val.ok_or_else(|| VirtualMachineError::VariableNotInScopeError(name.to_string())) + val.ok_or_else(|| HintError::VariableNotInScopeError(name.to_string())) } ///Returns a reference to the value in the current execution scope that matches the name and is of type List - pub fn get_list_ref(&self, name: &str) -> Result<&Vec, VirtualMachineError> { + pub fn get_list_ref(&self, name: &str) -> Result<&Vec, HintError> { let mut val: Option<&Vec> = None; if let Some(variable) = self.get_local_variables()?.get(name) { if let Some(list) = variable.downcast_ref::>() { val = Some(list); } } - val.ok_or_else(|| VirtualMachineError::VariableNotInScopeError(name.to_string())) + val.ok_or_else(|| HintError::VariableNotInScopeError(name.to_string())) } ///Returns a mutable reference to the value in the current execution scope that matches the name and is of type List - pub fn get_mut_list_ref( - &mut self, - name: &str, - ) -> Result<&mut Vec, VirtualMachineError> { + pub fn get_mut_list_ref(&mut self, name: &str) -> Result<&mut Vec, HintError> { let mut val: Option<&mut Vec> = None; if let Some(variable) = self.get_local_variables_mut()?.get_mut(name) { if let Some(list) = variable.downcast_mut::>() { val = Some(list); } } - val.ok_or_else(|| VirtualMachineError::VariableNotInScopeError(name.to_string())) + val.ok_or_else(|| HintError::VariableNotInScopeError(name.to_string())) } ///Returns the value in the dict manager - pub fn get_dict_manager(&self) -> Result>, VirtualMachineError> { + pub fn get_dict_manager(&self) -> Result>, HintError> { let mut val: Option>> = None; if let Some(variable) = self.get_local_variables()?.get("dict_manager") { if let Some(dict_manager) = variable.downcast_ref::>>() { val = Some(dict_manager.clone()); } } - val.ok_or_else(|| VirtualMachineError::VariableNotInScopeError("dict_manager".to_string())) + val.ok_or_else(|| HintError::VariableNotInScopeError("dict_manager".to_string())) } ///Returns a mutable reference to the value in the current execution scope that matches the name and is of the given type pub fn get_mut_dict_ref( &mut self, name: &str, - ) -> Result<&mut HashMap, VirtualMachineError> { + ) -> Result<&mut HashMap, HintError> { let mut val: Option<&mut HashMap> = None; if let Some(variable) = self.get_local_variables_mut()?.get_mut(name) { if let Some(dict) = variable.downcast_mut::>() { val = Some(dict); } } - val.ok_or_else(|| VirtualMachineError::VariableNotInScopeError(name.to_string())) + val.ok_or_else(|| HintError::VariableNotInScopeError(name.to_string())) } ///Inserts the boxed value into the current scope @@ -394,7 +380,7 @@ mod tests { assert_eq!( scopes.get_list::("no_variable"), - Err(VirtualMachineError::VariableNotInScopeError( + Err(HintError::VariableNotInScopeError( "no_variable".to_string() )) ); @@ -413,13 +399,13 @@ mod tests { assert_eq!( scopes.get_mut_ref::("no_variable"), - Err(VirtualMachineError::VariableNotInScopeError( + Err(HintError::VariableNotInScopeError( "no_variable".to_string() )) ); assert_eq!( scopes.get_ref::("no_variable"), - Err(VirtualMachineError::VariableNotInScopeError( + Err(HintError::VariableNotInScopeError( "no_variable".to_string() )) ); diff --git a/src/vm/errors/hint_errors.rs b/src/vm/errors/hint_errors.rs new file mode 100644 index 0000000000..8e9e246471 --- /dev/null +++ b/src/vm/errors/hint_errors.rs @@ -0,0 +1,142 @@ +use num_bigint::BigInt; +use thiserror::Error; + +use crate::types::relocatable::{MaybeRelocatable, Relocatable}; + +use super::{exec_scope_errors::ExecScopeError, vm_errors::VirtualMachineError}; + +#[derive(Debug, PartialEq, Error)] +pub enum HintError { + #[error("HintProcessor failed retrieve the compiled data necessary for hint execution")] + WrongHintData, + #[error("Failed to get ids for hint execution")] + FailedToGetIds, + #[error("Tried to compute an address but there was no register in the reference.")] + NoRegisterInReference, + #[error("Custom Hint Error: {0}")] + CustomHint(String), + #[error("Missing constant: {0}")] + MissingConstant(&'static str), + #[error("Fail to get constants for hint execution")] + FailedToGetConstant, + #[error("Arc too big, {0} must be <= {1} and {2} <= {3}")] + ArcTooBig(BigInt, BigInt, BigInt, BigInt), + #[error("Excluded is supposed to be 2, got {0}")] + ExcludedNot2(BigInt), + #[error("Value: {0} is outside of the range [0, 2**250)")] + ValueOutside250BitRange(BigInt), + #[error("Failed to get scope variables")] + ScopeError, + #[error("Variable {0} not present in current execution scope")] + VariableNotInScopeError(String), + #[error("DictManagerError: Tried to create tracker for a dictionary on segment: {0} when there is already a tracker for a dictionary on this segment")] + CantCreateDictionaryOnTakenSegment(isize), + #[error("Dict Error: No dict tracker found for segment {0}")] + NoDictTracker(isize), + #[error("ict Error: No value found for key: {0}")] + NoValueForKey(BigInt), + #[error("Assertion failed, a = {0} % PRIME is not less than b = {1} % PRIME")] + AssertLtFelt(BigInt, BigInt), + #[error("find_element() can only be used with n_elms <= {0}.\nGot: n_elms = {1}")] + FindElemMaxSize(BigInt, BigInt), + #[error( + "Invalid index found in find_element_index. Index: {0}.\nExpected key: {1}, found_key {2}" + )] + InvalidIndex(BigInt, BigInt, BigInt), + #[error("Found Key is None")] + KeyNotFound, + #[error("AP tracking data is None; could not apply correction to address")] + NoneApTrackingData, + #[error("Tracking groups should be the same, got {0} and {1}")] + InvalidTrackingGroup(usize, usize), + #[error("Expected relocatable for ap, got {0}")] + InvalidApValue(MaybeRelocatable), + #[error("Dict Error: Tried to create a dict whithout an initial dict")] + NoInitialDict, + #[error("squash_dict_inner fail: couldnt find key {0} in accesses_indices")] + NoKeyInAccessIndices(BigInt), + #[error("squash_dict_inner fail: local accessed_indices is empty")] + EmptyAccessIndices, + #[error("squash_dict_inner fail: local current_accessed_indices is empty")] + EmptyCurrentAccessIndices, + #[error("squash_dict_inner fail: local current_accessed_indices not empty, loop ended with remaining unaccounted elements")] + CurrentAccessIndicesNotEmpty, + #[error("Dict Error: Got the wrong value for dict_update, expected value: {0}, got: {1} for key: {2}")] + WrongPrevValue(BigInt, BigInt, BigInt), + #[error("squash_dict_inner fail: Number of used accesses:{0} doesnt match the lengh: {1} of the access_indices at key: {2}")] + NumUsedAccessesAssertFail(BigInt, usize, BigInt), + #[error("squash_dict_inner fail: local keys is not empty")] + KeysNotEmpty, + #[error("squash_dict_inner fail: No keys left but remaining_accesses > 0")] + EmptyKeys, + #[error("squash_dict fail: Accesses array size must be divisible by DictAccess.SIZE")] + PtrDiffNotDivisibleByDictAccessSize, + #[error("squash_dict() can only be used with n_accesses<={0}. ' \nGot: n_accesses={1}")] + SquashDictMaxSizeExceeded(BigInt, BigInt), + #[error("squash_dict fail: n_accesses: {0} is too big to be converted into an iterator")] + NAccessesTooBig(BigInt), + #[error(transparent)] + Internal(#[from] VirtualMachineError), + #[error("Couldn't convert BigInt to usize")] + BigintToUsizeFail, + #[error("usort() can only be used with input_len<={0}. Got: input_len={1}.")] + UsortOutOfRange(u64, BigInt), + #[error("unexpected usort fail: positions_dict or key value pair not found")] + UnexpectedPositionsDictFail, + #[error("unexpected verify multiplicity fail: positions not found")] + PositionsNotFound, + #[error("unexpected verify multiplicity fail: positions length != 0")] + PositionsLengthNotZero, + #[error("unexpected verify multiplicity fail: couldn't pop positions")] + CouldntPopPositions, + #[error("unexpected verify multiplicity fail: last_pos not found")] + LastPosNotFound, + #[error("Set's starting point {0} is bigger it's ending point {1}")] + InvalidSetRange(MaybeRelocatable, MaybeRelocatable), + #[error("Failed to construct a fixed size array of size: {0}")] + FixedSizeArrayFail(usize), + #[error("{0}")] + AssertionFailed(String), + #[error("Wrong dict pointer supplied. Got {0}, expected {1}.")] + MismatchedDictPtr(Relocatable, Relocatable), + #[error("Integer must be postive or zero, got: {0}")] + SecpSplitNegative(BigInt), + #[error("Integer: {0} out of range")] + SecpSplitutOfRange(BigInt), + #[error("verify_zero: Invalid input {0}")] + SecpVerifyZero(BigInt), + #[error("unsafe_keccak() can only be used with length<={0}. Got: length={1}")] + KeccakMaxSize(BigInt, BigInt), + #[error("Invalid word size: {0}")] + InvalidWordSize(BigInt), + #[error("Invalid input length, Got: length={0}")] + InvalidKeccakInputLength(BigInt), + #[error(transparent)] + FromScopeError(#[from] ExecScopeError), + #[error("assert_not_equal failed: {0} = {1}")] + AssertNotEqualFail(MaybeRelocatable, MaybeRelocatable), + #[error("split_int(): value is out of range")] + SplitIntNotZero, + #[error("split_int(): Limb {0} is out of range.")] + SplitIntLimbOutOfRange(BigInt), + #[error("Expected size to be in the range from [0, 100), got: {0}")] + InvalidKeccakStateSizeFelts(BigInt), + #[error("Expected size to be in range from [0, 10), got: {0}")] + InvalidBlockSize(BigInt), + #[error("Couldn't convert BigInt to u32")] + BigintToU32Fail, + #[error("Value of of range {0}")] + ValueOutOfRange(BigInt), + #[error("Assertion failed, 0 <= ids.a % PRIME < range_check_builtin.bound \n a = {0} is out of range")] + AssertNNValueOutOfRange(BigInt), + #[error("Assertion failed, {0} % {1} is equal to 0")] + AssertNotZero(BigInt, BigInt), + #[error("Div out of range: 0 < {0} <= {1}")] + OutOfValidRange(BigInt, BigInt), + #[error("Value: {0} is outside valid range")] + ValueOutsideValidRange(BigInt), + #[error("Assertion failed, {0}, is not less or equal to {1}")] + NonLeFelt(BigInt, BigInt), + #[error("Unknown Hint: {0}")] + UnknownHint(String), +} diff --git a/src/vm/errors/mod.rs b/src/vm/errors/mod.rs index d6b3dbad00..552f9217d5 100644 --- a/src/vm/errors/mod.rs +++ b/src/vm/errors/mod.rs @@ -1,5 +1,6 @@ pub mod cairo_run_errors; pub mod exec_scope_errors; +pub mod hint_errors; pub mod memory_errors; pub mod runner_errors; pub mod trace_errors; diff --git a/src/vm/errors/vm_errors.rs b/src/vm/errors/vm_errors.rs index 917197a731..90ea9cebbd 100644 --- a/src/vm/errors/vm_errors.rs +++ b/src/vm/errors/vm_errors.rs @@ -1,4 +1,5 @@ use super::exec_scope_errors::ExecScopeError; +use super::hint_errors::HintError; use super::trace_errors::TraceError; use crate::types::relocatable::{MaybeRelocatable, Relocatable}; use crate::vm::errors::memory_errors::MemoryError; @@ -28,6 +29,8 @@ pub enum VirtualMachineError { UnconstrainedResJumpRel, #[error("Res.UNCONSTRAINED cannot be used with Opcode.ASSERT_EQ")] UnconstrainedResAssertEq, + #[error("Couldn't compute operand {0} at address {1}")] + FailedToComputeOperands(String, Relocatable), #[error("An ASSERT_EQ instruction failed: {0} != {1}.")] DiffAssertValues(MaybeRelocatable, MaybeRelocatable), #[error("Call failed to write return-pc (inconsistent op0): {0} != {1}. Did you forget to increment ap?")] @@ -68,96 +71,14 @@ pub enum VirtualMachineError { ExpectedInteger(MaybeRelocatable), #[error("Expected relocatable at address {0}")] ExpectedRelocatable(MaybeRelocatable), - #[error("Failed to get ids for hint execution")] - FailedToGetIds, - #[error("Assertion failed, {0}, is not less or equal to {1}")] - NonLeFelt(BigInt, BigInt), - #[error("Div out of range: 0 < {0} <= {1}")] - OutOfValidRange(BigInt, BigInt), - #[error("Assertion failed, 0 <= ids.a % PRIME < range_check_builtin.bound \n a = {0} is out of range")] - ValueOutOfRange(BigInt), #[error("Value: {0} should be positive")] ValueNotPositive(BigInt), - #[error("Unknown Hint: {0}")] - UnknownHint(String), - #[error("Value: {0} is outside valid range")] - ValueOutsideValidRange(BigInt), - #[error("split_int(): value is out of range")] - SplitIntNotZero, - #[error("split_int(): Limb {0} is out of range.")] - SplitIntLimbOutOfRange(BigInt), + #[error("Div out of range: 0 < {0} <= {1}")] + OutOfValidRange(BigInt, BigInt), #[error("Failed to compare {0} and {1}, cant compare a relocatable to an integer value")] DiffTypeComparison(MaybeRelocatable, MaybeRelocatable), - #[error("assert_not_equal failed: {0} = {1}")] - AssertNotEqualFail(MaybeRelocatable, MaybeRelocatable), #[error("Failed to compare {0} and {1}, cant compare two relocatable values of different segment indexes")] DiffIndexComp(Relocatable, Relocatable), - #[error("Value: {0} is outside of the range [0, 2**250)")] - ValueOutside250BitRange(BigInt), - #[error("Can't calculate the square root of negative number: {0})")] - SqrtNegative(BigInt), - #[error("{0} is not divisible by {1}")] - SafeDivFail(BigInt, BigInt), - #[error("{0} is not divisible by {1}")] - SafeDivFailUsize(usize, usize), - #[error("Attempted to divide by zero")] - DividedByZero, - #[error("Failed to calculate the square root of: {0})")] - FailedToGetSqrt(BigInt), - #[error("Assertion failed, {0} % {1} is equal to 0")] - AssertNotZero(BigInt, BigInt), - #[error(transparent)] - MainScopeError(#[from] ExecScopeError), - #[error("Failed to get scope variables")] - ScopeError, - #[error("Variable {0} not present in current execution scope")] - VariableNotInScopeError(String), - #[error("DictManagerError: Tried to create tracker for a dictionary on segment: {0} when there is already a tracker for a dictionary on this segment")] - CantCreateDictionaryOnTakenSegment(isize), - #[error("Dict Error: No dict tracker found for segment {0}")] - NoDictTracker(isize), - #[error("ict Error: No value found for key: {0}")] - NoValueForKey(BigInt), - #[error("Assertion failed, a = {0} % PRIME is not less than b = {1} % PRIME")] - AssertLtFelt(BigInt, BigInt), - #[error("find_element() can only be used with n_elms <= {0}.\nGot: n_elms = {1}")] - FindElemMaxSize(BigInt, BigInt), - #[error( - "Invalid index found in find_element_index. Index: {0}.\nExpected key: {1}, found_key {2}" - )] - InvalidIndex(BigInt, BigInt, BigInt), - #[error("Found Key is None")] - KeyNotFound, - #[error("AP tracking data is None; could not apply correction to address")] - NoneApTrackingData, - #[error("Tracking groups should be the same, got {0} and {1}")] - InvalidTrackingGroup(usize, usize), - #[error("Expected relocatable for ap, got {0}")] - InvalidApValue(MaybeRelocatable), - #[error("Dict Error: Tried to create a dict whithout an initial dict")] - NoInitialDict, - #[error("squash_dict_inner fail: couldnt find key {0} in accesses_indices")] - NoKeyInAccessIndices(BigInt), - #[error("squash_dict_inner fail: local accessed_indices is empty")] - EmptyAccessIndices, - #[error("squash_dict_inner fail: local current_accessed_indices is empty")] - EmptyCurrentAccessIndices, - #[error("squash_dict_inner fail: local current_accessed_indices not empty, loop ended with remaining unaccounted elements")] - CurrentAccessIndicesNotEmpty, - #[error("Dict Error: Got the wrong value for dict_update, expected value: {0}, got: {1} for key: {2}")] - WrongPrevValue(BigInt, BigInt, BigInt), - #[error("squash_dict_inner fail: Number of used accesses:{0} doesnt match the lengh: {1} of the access_indices at key: {2}")] - NumUsedAccessesAssertFail(BigInt, usize, BigInt), - #[error("squash_dict_inner fail: local keys is not empty")] - KeysNotEmpty, - #[error("squash_dict_inner fail: No keys left but remaining_accesses > 0")] - EmptyKeys, - #[error("squash_dict fail: Accesses array size must be divisible by DictAccess.SIZE")] - PtrDiffNotDivisibleByDictAccessSize, - #[error("squash_dict() can only be used with n_accesses<={0}. ' \nGot: n_accesses={1}")] - SquashDictMaxSizeExceeded(BigInt, BigInt), - #[error("squash_dict fail: n_accesses: {0} is too big to be converted into an iterator")] - NAccessesTooBig(BigInt), #[error("Couldn't convert BigInt to usize")] BigintToUsizeFail, #[error("Couldn't convert BigInt to u64")] @@ -166,74 +87,34 @@ pub enum VirtualMachineError { BigintToU32Fail, #[error("Couldn't convert usize to u32")] UsizeToU32Fail, - #[error("usort() can only be used with input_len<={0}. Got: input_len={1}.")] - UsortOutOfRange(u64, BigInt), - #[error("unexpected usort fail: positions_dict or key value pair not found")] - UnexpectedPositionsDictFail, - #[error("unexpected verify multiplicity fail: positions not found")] - PositionsNotFound, - #[error("unexpected verify multiplicity fail: positions length != 0")] - PositionsLengthNotZero, - #[error("unexpected verify multiplicity fail: couldn't pop positions")] - CouldntPopPositions, - #[error("unexpected verify multiplicity fail: last_pos not found")] - LastPosNotFound, - #[error("Set's starting point {0} is bigger it's ending point {1}")] - InvalidSetRange(MaybeRelocatable, MaybeRelocatable), - #[error("Failed to construct a fixed size array of size: {0}")] - FixedSizeArrayFail(usize), - #[error("{0}")] - AssertionFailed(String), - #[error("Wrong dict pointer supplied. Got {0}, expected {1}.")] - MismatchedDictPtr(Relocatable, Relocatable), - #[error("Integer must be postive or zero, got: {0}")] - SecpSplitNegative(BigInt), - #[error("Integer: {0} out of range")] - SecpSplitutOfRange(BigInt), - #[error("verify_zero: Invalid input {0}")] - SecpVerifyZero(BigInt), - #[error("Cant substract {0} from offset {1}, offsets cant be negative")] - CantSubOffset(usize, usize), - #[error("unsafe_keccak() can only be used with length<={0}. Got: length={1}")] - KeccakMaxSize(BigInt, BigInt), - #[error("Invalid word size: {0}")] - InvalidWordSize(BigInt), - #[error("Invalid input length, Got: length={0}")] - InvalidKeccakInputLength(BigInt), #[error("None value was found in memory range cell")] NoneInMemoryRange, + #[error("Can't calculate the square root of negative number: {0})")] + SqrtNegative(BigInt), + #[error("{0} is not divisible by {1}")] + SafeDivFail(BigInt, BigInt), + #[error("{0} is not divisible by {1}")] + SafeDivFailUsize(usize, usize), + #[error("Attempted to divide by zero")] + DividedByZero, + #[error("Failed to calculate the square root of: {0})")] + FailedToGetSqrt(BigInt), #[error("Expected integer, found: {0:?}")] ExpectedIntAtRange(Option), - #[error("Expected size to be in the range from [0, 100), got: {0}")] - InvalidKeccakStateSizeFelts(BigInt), - #[error("Expected size to be in range from [0, 10), got: {0}")] - InvalidBlockSize(BigInt), #[error("Could not convert slice to array")] SliceToArrayError, - #[error("HintProcessor failed retrieve the compiled data necessary for hint execution")] - WrongHintData, #[error("Failed to compile hint: {0}")] CompileHintFail(String), #[error("op1_addr is Op1Addr.IMM, but no immediate was given")] NoImm, - #[error("Tried to compute an address but there was no register in the reference.")] - NoRegisterInReference, - #[error("Couldn't compute operand {0} at address {1}")] - FailedToComputeOperands(String, Relocatable), - #[error("Custom Hint Error: {0}")] - CustomHint(String), - #[error("Arc too big, {0} must be <= {1} and {2} <= {3}")] - ArcTooBig(BigInt, BigInt, BigInt, BigInt), - #[error("Excluded is supposed to be 2, got {0}")] - ExcludedNot2(BigInt), + #[error("Cant substract {0} from offset {1}, offsets cant be negative")] + CantSubOffset(usize, usize), #[error("Execution reached the end of the program. Requested remaining steps: {0}.")] EndOfProgram(usize), - #[error("Missing constant: {0}")] - MissingConstant(&'static str), - #[error("Fail to get constants for hint execution")] - FailedToGetConstant, #[error(transparent)] TracerError(#[from] TraceError), + #[error(transparent)] + MainScopeError(#[from] ExecScopeError), #[error("Current run is not finished")] RunNotFinished, #[error("Invalid argument count, expected {0} but got {1}")] @@ -241,5 +122,7 @@ pub enum VirtualMachineError { #[error("{0}, {1}")] ErrorMessageAttribute(String, Box), #[error("Got an exception while executing a hint: {1}")] - Hint(usize, Box), + Hint(usize, Box), + #[error("Unexpected Failure")] + Unexpected, } diff --git a/src/vm/errors/vm_exception.rs b/src/vm/errors/vm_exception.rs index 905247114f..2c284ba53d 100644 --- a/src/vm/errors/vm_exception.rs +++ b/src/vm/errors/vm_exception.rs @@ -78,7 +78,6 @@ pub fn get_traceback(vm: &VirtualMachine, runner: &CairoRunner) -> Option traceback.push_str(&format!( "{}\n", @@ -214,12 +213,12 @@ mod test { let vm_excep = VmException { pc, inst_location: Some(location), - inner_exc: VirtualMachineError::CouldntPopPositions, + inner_exc: VirtualMachineError::NoImm, error_attr_value: None, traceback: None, }; assert_eq!( - VmException::from_vm_error(&runner, &vm!(), VirtualMachineError::CouldntPopPositions,), + VmException::from_vm_error(&runner, &vm!(), VirtualMachineError::NoImm,), vm_excep ) }