diff --git a/clarity-types/src/errors/mod.rs b/clarity-types/src/errors/mod.rs index bab0f4f594..200b76ad87 100644 --- a/clarity-types/src/errors/mod.rs +++ b/clarity-types/src/errors/mod.rs @@ -33,8 +33,12 @@ use crate::types::{FunctionIdentifier, Value}; pub type StackTrace = Vec; +/// Wraps error types that do not implement [`PartialEq`], enabling their +/// use in enums that implement the trait. Any two `IncomparableError` values +/// are always considered unequal. #[derive(Debug)] pub struct IncomparableError { + /// The wrapped error value. pub err: T, } @@ -44,28 +48,68 @@ pub enum Error { /// TypeChecker and other check passes. Test executions may /// trigger these errors. Unchecked(CheckErrorKind), - Interpreter(InterpreterError), + /// A critical, unrecoverable bug within the VM's internal logic. + /// + /// The presence of this error indicates a violation of one of the VM's + /// invariants or a corrupted state. This is **not** an error in the user's + /// Clarity code, but a bug in the VM's Rust implementation. + /// + /// # Example + /// The VM's evaluation loop attempts to `pop` from an empty internal call stack, + /// indicating a mismatch in function entry/exit logic. + Internal(VmInternalError), Runtime(RuntimeErrorType, Option), EarlyReturn(EarlyReturnError), } -/// InterpreterErrors are errors that *should never* occur. -/// Test executions may trigger these errors. +/// Represents an internal, unrecoverable error within the Clarity VM. +/// +/// These errors signify a bug in the VM's logic or a violation of its internal +/// invariants. They are not meant to be caught or handled by Clarity contracts. #[derive(Debug, PartialEq)] -pub enum InterpreterError { +pub enum VmInternalError { + /// Raised when the VM encounters an invalid or malformed `SymbolicExpression` + /// e.g., bad variable name or missing argument. + /// The `String` provides a message describing the specific issue. BadSymbolicRepresentation(String), - InterpreterError(String), + /// A generic, unexpected internal error, indicating a logic failure within + /// the VM. + /// The `String` provides a message describing the specific failure. + InvariantViolation(String), // TODO: merge with VmInternalError::Expect + /// The VM failed to produce the final `AssetMap` when finalizing the + /// execution environment for a transaction. FailedToConstructAssetTable, + /// The VM failed to produce the final `EventBatch` when finalizing the + /// execution environment for a transaction. FailedToConstructEventBatch, + /// An error occurred during an interaction with the database. + /// The parameter contains the corresponding SQLite error. #[cfg(feature = "rusqlite")] SqliteError(IncomparableError), + /// The file path provided for the MARF database is invalid because it + /// contains non-UTF-8 characters. BadFileName, + /// The VM failed to create the necessary directory for the MARF persistent + /// storage. Likely due to a file system permissions error or an invalid path FailedToCreateDataDirectory, + /// A failure occurred within the MARF implementation. + /// The `String` provides a message describing the specific failure. MarfFailure(String), + /// Failed to construct a tuple value from provided data because it did not + /// match the expected type signature. FailureConstructingTupleWithType, + /// Failed to construct a list value from provided data because it + /// did not match the expected type signature. FailureConstructingListWithType, + /// An STX transfer failed due to insufficient balance. InsufficientBalance, + /// A generic error occurred during a database operation. + /// The `String` represents a descriptive message detailing the specific issue. DBError(String), + /// An internal expectation or assertion failed. This is used for conditions + /// that are believed to be unreachable but are handled gracefully to prevent + /// a panic. + /// The `String` provides a message describing the failed expectation. Expect(String), } @@ -130,7 +174,7 @@ impl PartialEq for Error { (Error::Runtime(x, _), Error::Runtime(y, _)) => x == y, (Error::Unchecked(x), Error::Unchecked(y)) => x == y, (Error::EarlyReturn(x), Error::EarlyReturn(y)) => x == y, - (Error::Interpreter(x), Error::Interpreter(y)) => x == y, + (Error::Internal(x), Error::Internal(y)) => x == y, _ => false, } } @@ -175,7 +219,7 @@ impl error::Error for RuntimeErrorType { impl From for Error { fn from(err: ParseError) -> Self { match *err.err { - ParseErrors::InterpreterFailure => Error::from(InterpreterError::Expect( + ParseErrors::InterpreterFailure => Error::from(VmInternalError::Expect( "Unexpected interpreter failure during parsing".into(), )), _ => Error::from(RuntimeErrorType::ASTError(Box::new(err))), @@ -186,10 +230,10 @@ impl From for Error { impl From for Error { fn from(err: CostErrors) -> Self { match err { - CostErrors::InterpreterFailure => Error::from(InterpreterError::Expect( + CostErrors::InterpreterFailure => Error::from(VmInternalError::Expect( "Interpreter failure during cost calculation".into(), )), - CostErrors::Expect(s) => Error::from(InterpreterError::Expect(format!( + CostErrors::Expect(s) => Error::from(VmInternalError::Expect(format!( "Interpreter failure during cost calculation: {s}" ))), other_err => Error::from(CheckErrorKind::from(other_err)), @@ -221,9 +265,9 @@ impl From for Error { } } -impl From for Error { - fn from(err: InterpreterError) -> Self { - Error::Interpreter(err) +impl From for Error { + fn from(err: VmInternalError) -> Self { + Error::Internal(err) } } @@ -252,12 +296,12 @@ mod test { Error::EarlyReturn(EarlyReturnError::UnwrapFailed(Box::new(Value::Bool(true)))) ); assert_eq!( - Error::Interpreter(InterpreterError::InterpreterError("".to_string())), - Error::Interpreter(InterpreterError::InterpreterError("".to_string())) + Error::Internal(VmInternalError::InvariantViolation("".to_string())), + Error::Internal(VmInternalError::InvariantViolation("".to_string())) ); assert!( Error::EarlyReturn(EarlyReturnError::UnwrapFailed(Box::new(Value::Bool(true)))) - != Error::Interpreter(InterpreterError::InterpreterError("".to_string())) + != Error::Internal(VmInternalError::InvariantViolation("".to_string())) ); } } diff --git a/clarity-types/src/tests/types/mod.rs b/clarity-types/src/tests/types/mod.rs index 819395c9b6..816aaa28cb 100644 --- a/clarity-types/src/tests/types/mod.rs +++ b/clarity-types/src/tests/types/mod.rs @@ -19,7 +19,7 @@ use rstest::rstest; use stacks_common::types::StacksEpochId; use crate::Error; -use crate::errors::{CheckErrorKind, InterpreterError, RuntimeErrorType}; +use crate::errors::{CheckErrorKind, RuntimeErrorType, VmInternalError}; use crate::types::{ ASCIIData, BuffData, CharType, ListTypeData, MAX_VALUE_SIZE, PrincipalData, QualifiedContractIdentifier, SequenceData, SequencedValue as _, StandardPrincipalData, @@ -34,7 +34,7 @@ fn test_constructors() { vec![Value::Int(5), Value::Int(2)], ListTypeData::new_list(TypeSignature::BoolType, 3).unwrap() ), - Err(InterpreterError::FailureConstructingListWithType.into()) + Err(VmInternalError::FailureConstructingListWithType.into()) ); assert_eq!( ListTypeData::new_list(TypeSignature::IntType, MAX_VALUE_SIZE), @@ -289,7 +289,7 @@ fn test_principal_data_parse_standard_principal_returns_runtime_error( ))] #[case::invalid_contract_name("SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G.1nvalid-name", RuntimeErrorType::BadNameValue("ContractName", "1nvalid-name".into()))] -fn test_qualified_contract_identifier_parse_returns_interpreter_error( +fn test_qualified_contract_identifier_parse_returns_vm_internal_error( #[case] input: &str, #[case] expected_err: RuntimeErrorType, ) { @@ -336,58 +336,58 @@ fn test_trait_identifier_parse_fully_qualified_returns_runtime_error( assert_eq!(Error::from(expected_err), err); } -/// The returned InterpreterError is consensus-critical. +/// The returned VMInternalError is consensus-critical. #[test] -fn test_standard_principal_data_new_returns_interpreter_error_consensus_critical() { +fn test_standard_principal_data_new_returns_vm_internal_error_consensus_critical() { let result = StandardPrincipalData::new(32, [0; 20]); let err = result.expect_err("Unexpected principal data"); assert_eq!( - Error::from(InterpreterError::Expect("Unexpected principal data".into())), + Error::from(VmInternalError::Expect("Unexpected principal data".into())), err.into(), ); } -/// The returned InterpreterError is consensus-critical. +/// The returned VMInternalError is consensus-critical. #[test] -fn test_sequence_data_element_at_returns_interpreter_error_consensus_critical() { +fn test_sequence_data_element_at_returns_vm_internal_error_consensus_critical() { let buff = SequenceData::String(CharType::ASCII(ASCIIData { data: vec![1] })); let err = buff.element_at(0).unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect( + Error::from(VmInternalError::Expect( "BUG: failed to initialize single-byte ASCII buffer".into() )), err ); } -/// The returned InterpreterError is consensus-critical. +/// The returned VMInternalError is consensus-critical. #[test] -fn test_ascii_data_to_value_returns_interpreter_error_consensus_critical() { +fn test_ascii_data_to_value_returns_vm_internal_error_consensus_critical() { let err = ASCIIData::to_value(&1).unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect( + Error::from(VmInternalError::Expect( "ERROR: Invalid ASCII string successfully constructed".into() )), err ); } -/// The returned InterpreterError is consensus-critical. +/// The returned VMInternalError is consensus-critical. #[test] -fn test_utf8_data_to_value_returns_interpreter_error_consensus_critical() { +fn test_utf8_data_to_value_returns_vm_internal_error_consensus_critical() { let err = UTF8Data::to_value(&vec![0xED, 0xA0, 0x80]).unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect( + Error::from(VmInternalError::Expect( "ERROR: Invalid UTF8 string successfully constructed".into() )), err ); } -/// The returned InterpreterError is consensus-critical. +/// The returned VMInternalError is consensus-critical. #[test] -fn test_tuple_data_from_data_typed_returns_interpreter_error_consensus_critical() { +fn test_tuple_data_from_data_typed_returns_vm_internal_error_consensus_critical() { let tuple_type = TupleTypeSignature::try_from(vec![("a".into(), TypeSignature::IntType)]).unwrap(); let err = TupleData::from_data_typed( @@ -397,159 +397,159 @@ fn test_tuple_data_from_data_typed_returns_interpreter_error_consensus_critical( ) .unwrap_err(); assert_eq!( - Error::from(InterpreterError::FailureConstructingTupleWithType), + Error::from(VmInternalError::FailureConstructingTupleWithType), err ); } #[rstest] -#[case::not_a_string(Value::none(), InterpreterError::Expect("Expected ASCII string".to_string()))] -#[case::invalid_utf8(Value::Sequence(SequenceData::String(CharType::ASCII(ASCIIData { data: vec![0xED, 0xA0, 0x80] }))), InterpreterError::Expect("Non UTF-8 data in string".to_string()))] -fn test_value_expect_ascii_returns_interpreter_error( +#[case::not_a_string(Value::none(), VmInternalError::Expect("Expected ASCII string".to_string()))] +#[case::invalid_utf8(Value::Sequence(SequenceData::String(CharType::ASCII(ASCIIData { data: vec![0xED, 0xA0, 0x80] }))), VmInternalError::Expect("Non UTF-8 data in string".to_string()))] +fn test_value_expect_ascii_returns_vm_internal_error( #[case] value: Value, - #[case] expected_err: InterpreterError, + #[case] expected_err: VmInternalError, ) { let err = value.expect_ascii().unwrap_err(); assert_eq!(Error::from(expected_err), err); } -/// The returned InterpreterError is consensus-critical. +/// The returned VMInternalError is consensus-critical. #[test] -fn test_value_expect_u128_returns_interpreter_error_consensus_critical() { +fn test_value_expect_u128_returns_vm_internal_error_consensus_critical() { let err = Value::none().expect_u128().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect("Expected u128".to_string())), + Error::from(VmInternalError::Expect("Expected u128".to_string())), err ); } #[test] -fn test_value_expect_i128_returns_interpreter_error() { +fn test_value_expect_i128_returns_vm_internal_error() { let err = Value::none().expect_i128().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect("Expected i128".to_string())), + Error::from(VmInternalError::Expect("Expected i128".to_string())), err ); } #[rstest] -#[case::not_a_buffer(Value::none(), InterpreterError::Expect("Expected buff".to_string()))] -#[case::too_small(Value::buff_from(vec![1, 2, 3, 4]).unwrap(), InterpreterError::Expect("Unexpected buff length".to_string()))] -fn test_value_expect_buff_returns_interpreter_error( +#[case::not_a_buffer(Value::none(), VmInternalError::Expect("Expected buff".to_string()))] +#[case::too_small(Value::buff_from(vec![1, 2, 3, 4]).unwrap(), VmInternalError::Expect("Unexpected buff length".to_string()))] +fn test_value_expect_buff_returns_vm_internal_error( #[case] value: Value, - #[case] expected_err: InterpreterError, + #[case] expected_err: VmInternalError, ) { let err = value.expect_buff(1).unwrap_err(); assert_eq!(Error::from(expected_err), err); } #[test] -fn test_value_expect_tuple_returns_interpreter_error() { +fn test_value_expect_tuple_returns_vm_internal_error() { let err = Value::none().expect_tuple().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect("Expected tuple".to_string())), + Error::from(VmInternalError::Expect("Expected tuple".to_string())), err ); } #[test] -fn test_value_expect_list_returns_interpreter_error() { +fn test_value_expect_list_returns_vm_internal_error() { let err = Value::none().expect_list().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect("Expected list".to_string())), + Error::from(VmInternalError::Expect("Expected list".to_string())), err ); } #[test] -fn test_value_expect_buff_padded_returns_interpreter_error() { +fn test_value_expect_buff_padded_returns_vm_internal_error() { let err = Value::none().expect_buff_padded(10, 0).unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect("Expected buff".to_string())), + Error::from(VmInternalError::Expect("Expected buff".to_string())), err ); } #[test] -fn test_value_expect_bool_returns_interpreter_error() { +fn test_value_expect_bool_returns_vm_internal_error() { let err = Value::none().expect_bool().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect("Expected bool".to_string())), + Error::from(VmInternalError::Expect("Expected bool".to_string())), err ); } -/// The returned InterpreterError is consensus-critical. +/// The returned VMInternalError is consensus-critical. #[test] -fn test_value_expect_optional_returns_interpreter_error_consensus_critical() { +fn test_value_expect_optional_returns_vm_internal_error_consensus_critical() { let err = Value::okay_true().expect_optional().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect("Expected optional".to_string())), + Error::from(VmInternalError::Expect("Expected optional".to_string())), err ); } -/// The returned InterpreterError is consensus-critical. +/// The returned VMInternalError is consensus-critical. #[test] -fn test_value_expect_principal_returns_interpreter_error_consensus_critical() { +fn test_value_expect_principal_returns_vm_internal_error_consensus_critical() { let err = Value::none().expect_principal().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect("Expected principal".to_string())), + Error::from(VmInternalError::Expect("Expected principal".to_string())), err ); } -/// The returned InterpreterError is consensus-critical. +/// The returned VMInternalError is consensus-critical. #[test] -fn test_value_expect_callable_returns_interpreter_error_consensus_critical() { +fn test_value_expect_callable_returns_vm_internal_error_consensus_critical() { let err = Value::none().expect_callable().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect("Expected callable".to_string())), + Error::from(VmInternalError::Expect("Expected callable".to_string())), err ); } #[test] -fn test_value_expect_result_returns_interpreter_error() { +fn test_value_expect_result_returns_vm_internal_error() { let err = Value::none().expect_result().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect("Expected response".to_string())), + Error::from(VmInternalError::Expect("Expected response".to_string())), err ); } #[rstest] -#[case::not_a_response(Value::none(), InterpreterError::Expect("Expected response".to_string()))] -#[case::not_an_ok_response(Value::error(Value::Int(1)).unwrap(), InterpreterError::Expect("Expected ok response".to_string()))] -fn test_value_expect_result_ok_returns_interpreter_error( +#[case::not_a_response(Value::none(), VmInternalError::Expect("Expected response".to_string()))] +#[case::not_an_ok_response(Value::error(Value::Int(1)).unwrap(), VmInternalError::Expect("Expected ok response".to_string()))] +fn test_value_expect_result_ok_returns_vm_internal_error( #[case] value: Value, - #[case] expected_err: InterpreterError, + #[case] expected_err: VmInternalError, ) { let err = value.expect_result_ok().unwrap_err(); assert_eq!(Error::from(expected_err), err); } #[rstest] -#[case::not_a_response(Value::none(), InterpreterError::Expect("Expected response".to_string()))] -#[case::not_an_err_response(Value::okay_true(), InterpreterError::Expect("Expected err response".to_string()))] -fn test_value_expect_result_err_returns_interpreter_error( +#[case::not_a_response(Value::none(), VmInternalError::Expect("Expected response".to_string()))] +#[case::not_an_err_response(Value::okay_true(), VmInternalError::Expect("Expected err response".to_string()))] +fn test_value_expect_result_err_returns_vm_internal_error( #[case] value: Value, - #[case] expected_err: InterpreterError, + #[case] expected_err: VmInternalError, ) { let err = value.expect_result_err().unwrap_err(); assert_eq!(Error::from(expected_err), err); } -/// The returned InterpreterError is consensus-critical. +/// The returned VMInternalError is consensus-critical. #[test] -fn test_buff_data_len_returns_interpreter_error_consensus_critical() { +fn test_buff_data_len_returns_vm_internal_error_consensus_critical() { let err = BuffData { data: vec![1; MAX_VALUE_SIZE as usize + 1], } .len() .unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect( + Error::from(VmInternalError::Expect( "Data length should be valid".into() )), err @@ -557,14 +557,14 @@ fn test_buff_data_len_returns_interpreter_error_consensus_critical() { } #[test] -fn test_ascii_data_len_returns_interpreter_error() { +fn test_ascii_data_len_returns_vm_internal_error() { let err = ASCIIData { data: vec![1; MAX_VALUE_SIZE as usize + 1], } .len() .unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect( + Error::from(VmInternalError::Expect( "Data length should be valid".into() )), err @@ -572,14 +572,14 @@ fn test_ascii_data_len_returns_interpreter_error() { } #[test] -fn test_utf8_data_len_returns_interpreter_error() { +fn test_utf8_data_len_returns_vm_internal_error() { let err = UTF8Data { data: vec![vec![]; MAX_VALUE_SIZE as usize + 1], } .len() .unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect( + Error::from(VmInternalError::Expect( "Data length should be valid".into() )), err diff --git a/clarity-types/src/tests/types/serialization.rs b/clarity-types/src/tests/types/serialization.rs index 2349b937c9..21eee275da 100644 --- a/clarity-types/src/tests/types/serialization.rs +++ b/clarity-types/src/tests/types/serialization.rs @@ -15,7 +15,7 @@ use std::io::Write; use crate::Error; -use crate::errors::{CheckErrorKind, InterpreterError}; +use crate::errors::{CheckErrorKind, VmInternalError}; use crate::types::serialization::SerializationError; use crate::types::{ ASCIIData, CharType, MAX_VALUE_SIZE, PrincipalData, QualifiedContractIdentifier, SequenceData, @@ -416,30 +416,30 @@ fn test_principals() { test_bad_expectation(standard_p, TypeSignature::BoolType); } -/// The returned InterpreterError is consensus-critical. +/// The returned VmInternalError is consensus-critical. #[test] -fn test_serialize_to_vec_returns_interpreter_error_consensus_critical() { +fn test_serialize_to_vec_returns_vm_internal_error_consensus_critical() { let value = Value::Sequence(SequenceData::String(CharType::ASCII(ASCIIData { data: vec![0; MAX_VALUE_SIZE as usize + 1], }))); let err = value.serialize_to_vec().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect( + Error::from(VmInternalError::Expect( "IOError filling byte buffer.".into() )), err.into() ); } -/// The returned InterpreterError is consensus-critical. +/// The returned VmInternalError is consensus-critical. #[test] -fn test_serialize_to_hex_returns_interpreter_error_consensus_critical() { +fn test_serialize_to_hex_returns_vm_internal_error_consensus_critical() { let value = Value::Sequence(SequenceData::String(CharType::ASCII(ASCIIData { data: vec![0; MAX_VALUE_SIZE as usize + 1], }))); let err = value.serialize_to_hex().unwrap_err(); assert_eq!( - Error::from(InterpreterError::Expect( + Error::from(VmInternalError::Expect( "IOError filling byte buffer.".into() )), err.into() diff --git a/clarity-types/src/types/mod.rs b/clarity-types/src/types/mod.rs index 6a5549a763..bcfd0f65f5 100644 --- a/clarity-types/src/types/mod.rs +++ b/clarity-types/src/types/mod.rs @@ -38,7 +38,7 @@ pub use self::signatures::{ TypeSignature, }; use crate::errors::{ - CheckErrorKind, InterpreterError, InterpreterResult as Result, RuntimeErrorType, + CheckErrorKind, InterpreterResult as Result, RuntimeErrorType, VmInternalError, }; use crate::representations::{ClarityName, ContractName, SymbolicExpression}; // use crate::vm::ClarityVersion; @@ -83,9 +83,9 @@ impl StandardPrincipalData { } impl StandardPrincipalData { - pub fn new(version: u8, bytes: [u8; 20]) -> std::result::Result { + pub fn new(version: u8, bytes: [u8; 20]) -> std::result::Result { if version >= 32 { - return Err(InterpreterError::Expect("Unexpected principal data".into())); + return Err(VmInternalError::Expect("Unexpected principal data".into())); } Ok(Self(version, bytes)) } @@ -374,7 +374,7 @@ impl SequenceData { SequenceData::List(mut data) => data.data.remove(index), SequenceData::String(CharType::ASCII(data)) => { Value::string_ascii_from_bytes(vec![data.data[index]]).map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "BUG: failed to initialize single-byte ASCII buffer".into(), ) })? @@ -772,7 +772,7 @@ impl SequencedValue for ASCIIData { fn to_value(v: &u8) -> Result { Value::string_ascii_from_bytes(vec![*v]).map_err(|_| { - InterpreterError::Expect("ERROR: Invalid ASCII string successfully constructed".into()) + VmInternalError::Expect("ERROR: Invalid ASCII string successfully constructed".into()) .into() }) } @@ -798,7 +798,7 @@ impl SequencedValue> for UTF8Data { fn to_value(v: &Vec) -> Result { Value::string_utf8_from_bytes(v.clone()).map_err(|_| { - InterpreterError::Expect("ERROR: Invalid UTF8 string successfully constructed".into()) + VmInternalError::Expect("ERROR: Invalid UTF8 string successfully constructed".into()) .into() }) } @@ -932,7 +932,7 @@ impl Value { // be greater than MAX_VALUE_SIZE (they error on such constructions) // so we do not need to perform that check here. if (expected_type.get_max_len() as usize) < list_data.len() { - return Err(InterpreterError::FailureConstructingListWithType.into()); + return Err(VmInternalError::FailureConstructingListWithType.into()); } { @@ -940,7 +940,7 @@ impl Value { for item in &list_data { if !expected_item_type.admits(epoch, item)? { - return Err(InterpreterError::FailureConstructingListWithType.into()); + return Err(VmInternalError::FailureConstructingListWithType.into()); } } } @@ -1018,7 +1018,7 @@ impl Value { pub fn string_utf8_from_string_utf8_literal(tokenized_str: String) -> Result { let wrapped_codepoints_matcher = Regex::new("^\\\\u\\{(?P[[:xdigit:]]+)\\}") - .map_err(|_| InterpreterError::Expect("Bad regex".into()))?; + .map_err(|_| VmInternalError::Expect("Bad regex".into()))?; let mut window = tokenized_str.as_str(); let mut cursor = 0; let mut data: Vec> = vec![]; @@ -1026,7 +1026,7 @@ impl Value { if let Some(captures) = wrapped_codepoints_matcher.captures(window) { let matched = captures .name("value") - .ok_or_else(|| InterpreterError::Expect("Expected capture".into()))?; + .ok_or_else(|| VmInternalError::Expect("Expected capture".into()))?; let scalar_value = window[matched.start()..matched.end()].to_string(); let unicode_char = { let u = u32::from_str_radix(&scalar_value, 16) @@ -1079,10 +1079,10 @@ impl Value { pub fn expect_ascii(self) -> Result { if let Value::Sequence(SequenceData::String(CharType::ASCII(ASCIIData { data }))) = self { Ok(String::from_utf8(data) - .map_err(|_| InterpreterError::Expect("Non UTF-8 data in string".into()))?) + .map_err(|_| VmInternalError::Expect("Non UTF-8 data in string".into()))?) } else { error!("Value '{self:?}' is not an ASCII string"); - Err(InterpreterError::Expect("Expected ASCII string".into()).into()) + Err(VmInternalError::Expect("Expected ASCII string".into()).into()) } } @@ -1091,7 +1091,7 @@ impl Value { Ok(inner) } else { error!("Value '{self:?}' is not a u128"); - Err(InterpreterError::Expect("Expected u128".into()).into()) + Err(VmInternalError::Expect("Expected u128".into()).into()) } } @@ -1100,7 +1100,7 @@ impl Value { Ok(inner) } else { error!("Value '{self:?}' is not an i128"); - Err(InterpreterError::Expect("Expected i128".into()).into()) + Err(VmInternalError::Expect("Expected i128".into()).into()) } } @@ -1113,11 +1113,11 @@ impl Value { "Value buffer has len {}, expected {sz}", buffdata.data.len() ); - Err(InterpreterError::Expect("Unexpected buff length".into()).into()) + Err(VmInternalError::Expect("Unexpected buff length".into()).into()) } } else { error!("Value '{self:?}' is not a buff"); - Err(InterpreterError::Expect("Expected buff".into()).into()) + Err(VmInternalError::Expect("Expected buff".into()).into()) } } @@ -1126,7 +1126,7 @@ impl Value { Ok(listdata.data) } else { error!("Value '{self:?}' is not a list"); - Err(InterpreterError::Expect("Expected list".into()).into()) + Err(VmInternalError::Expect("Expected list".into()).into()) } } @@ -1145,7 +1145,7 @@ impl Value { Ok(b) } else { error!("Value '{self:?}' is not a bool"); - Err(InterpreterError::Expect("Expected bool".into()).into()) + Err(VmInternalError::Expect("Expected bool".into()).into()) } } @@ -1154,7 +1154,7 @@ impl Value { Ok(data) } else { error!("Value '{self:?}' is not a tuple"); - Err(InterpreterError::Expect("Expected tuple".into()).into()) + Err(VmInternalError::Expect("Expected tuple".into()).into()) } } @@ -1166,7 +1166,7 @@ impl Value { } } else { error!("Value '{self:?}' is not an optional"); - Err(InterpreterError::Expect("Expected optional".into()).into()) + Err(VmInternalError::Expect("Expected optional".into()).into()) } } @@ -1175,7 +1175,7 @@ impl Value { Ok(p) } else { error!("Value '{self:?}' is not a principal"); - Err(InterpreterError::Expect("Expected principal".into()).into()) + Err(VmInternalError::Expect("Expected principal".into()).into()) } } @@ -1184,7 +1184,7 @@ impl Value { Ok(t) } else { error!("Value '{self:?}' is not a callable contract"); - Err(InterpreterError::Expect("Expected callable".into()).into()) + Err(VmInternalError::Expect("Expected callable".into()).into()) } } @@ -1197,7 +1197,7 @@ impl Value { } } else { error!("Value '{self:?}' is not a response"); - Err(InterpreterError::Expect("Expected response".into()).into()) + Err(VmInternalError::Expect("Expected response".into()).into()) } } @@ -1207,11 +1207,11 @@ impl Value { Ok(*res_data.data) } else { error!("Value is not a (ok ..)"); - Err(InterpreterError::Expect("Expected ok response".into()).into()) + Err(VmInternalError::Expect("Expected ok response".into()).into()) } } else { error!("Value '{self:?}' is not a response"); - Err(InterpreterError::Expect("Expected response".into()).into()) + Err(VmInternalError::Expect("Expected response".into()).into()) } } @@ -1221,11 +1221,11 @@ impl Value { Ok(*res_data.data) } else { error!("Value is not a (err ..)"); - Err(InterpreterError::Expect("Expected err response".into()).into()) + Err(VmInternalError::Expect("Expected err response".into()).into()) } } else { error!("Value '{self:?}' is not a response"); - Err(InterpreterError::Expect("Expected response".into()).into()) + Err(VmInternalError::Expect("Expected response".into()).into()) } } } @@ -1235,7 +1235,7 @@ impl BuffData { self.data .len() .try_into() - .map_err(|_| InterpreterError::Expect("Data length should be valid".into()).into()) + .map_err(|_| VmInternalError::Expect("Data length should be valid".into()).into()) } pub fn as_slice(&self) -> &[u8] { @@ -1256,7 +1256,7 @@ impl ListData { self.data .len() .try_into() - .map_err(|_| InterpreterError::Expect("Data length should be valid".into()).into()) + .map_err(|_| VmInternalError::Expect("Data length should be valid".into()).into()) } pub fn is_empty(&self) -> bool { @@ -1288,7 +1288,7 @@ impl ASCIIData { self.data .len() .try_into() - .map_err(|_| InterpreterError::Expect("Data length should be valid".into()).into()) + .map_err(|_| VmInternalError::Expect("Data length should be valid".into()).into()) } } @@ -1301,7 +1301,7 @@ impl UTF8Data { self.data .len() .try_into() - .map_err(|_| InterpreterError::Expect("Data length should be valid".into()).into()) + .map_err(|_| VmInternalError::Expect("Data length should be valid".into()).into()) } } @@ -1575,9 +1575,9 @@ impl TupleData { for (name, value) in data.into_iter() { let expected_type = expected .field_type(&name) - .ok_or(InterpreterError::FailureConstructingTupleWithType)?; + .ok_or(VmInternalError::FailureConstructingTupleWithType)?; if !expected_type.admits(epoch, &value)? { - return Err(InterpreterError::FailureConstructingTupleWithType.into()); + return Err(VmInternalError::FailureConstructingTupleWithType.into()); } data_map.insert(name, value); } diff --git a/clarity-types/src/types/serialization.rs b/clarity-types/src/types/serialization.rs index f5356a6639..929b2e4313 100644 --- a/clarity-types/src/types/serialization.rs +++ b/clarity-types/src/types/serialization.rs @@ -23,7 +23,7 @@ use stacks_common::util::hash::{hex_bytes, to_hex}; use stacks_common::util::retry::BoundReader; use super::{ListTypeData, TupleTypeSignature}; -use crate::errors::{CheckErrorKind, IncomparableError, InterpreterError}; +use crate::errors::{CheckErrorKind, IncomparableError, VmInternalError}; use crate::representations::{ClarityName, ContractName, MAX_STRING_LEN}; use crate::types::{ BOUND_VALUE_SERIALIZATION_BYTES, BufferLength, CallableData, CharType, MAX_TYPE_DEPTH, @@ -1215,15 +1215,15 @@ impl Write for WriteCounter { } impl Value { - pub fn serialize_to_vec(&self) -> Result, InterpreterError> { + pub fn serialize_to_vec(&self) -> Result, VmInternalError> { let mut byte_serialization = Vec::new(); self.serialize_write(&mut byte_serialization) - .map_err(|_| InterpreterError::Expect("IOError filling byte buffer.".into()))?; + .map_err(|_| VmInternalError::Expect("IOError filling byte buffer.".into()))?; Ok(byte_serialization) } /// This does *not* perform any data sanitization - pub fn serialize_to_hex(&self) -> Result { + pub fn serialize_to_hex(&self) -> Result { let byte_serialization = self.serialize_to_vec()?; Ok(to_hex(byte_serialization.as_slice())) } diff --git a/clarity/src/vm/callables.rs b/clarity/src/vm/callables.rs index 0f02509819..e74b402192 100644 --- a/clarity/src/vm/callables.rs +++ b/clarity/src/vm/callables.rs @@ -21,7 +21,7 @@ pub use clarity_types::types::FunctionIdentifier; use stacks_common::types::StacksEpochId; use super::costs::{CostErrors, CostOverflowingMath}; -use super::errors::InterpreterError; +use super::errors::VmInternalError; use super::types::signatures::CallableSubtype; use super::ClarityVersion; use crate::vm::analysis::errors::CheckErrorKind; @@ -89,17 +89,17 @@ impl NativeHandle { check_argument_count(1, &args)?; function( args.pop() - .ok_or_else(|| InterpreterError::Expect("Unexpected list length".into()))?, + .ok_or_else(|| VmInternalError::Expect("Unexpected list length".into()))?, ) } Self::DoubleArg(function) => { check_argument_count(2, &args)?; let second = args .pop() - .ok_or_else(|| InterpreterError::Expect("Unexpected list length".into()))?; + .ok_or_else(|| VmInternalError::Expect("Unexpected list length".into()))?; let first = args .pop() - .ok_or_else(|| InterpreterError::Expect("Unexpected list length".into()))?; + .ok_or_else(|| VmInternalError::Expect("Unexpected list length".into()))?; function(first, second) } Self::MoreArg(function) => function(args), diff --git a/clarity/src/vm/contexts.rs b/clarity/src/vm/contexts.rs index 59105ee5d6..67201f5dfa 100644 --- a/clarity/src/vm/contexts.rs +++ b/clarity/src/vm/contexts.rs @@ -37,7 +37,7 @@ use crate::vm::database::{ NonFungibleTokenMetadata, }; use crate::vm::errors::{ - CheckErrorKind, InterpreterError, InterpreterResult as Result, RuntimeErrorType, + CheckErrorKind, InterpreterResult as Result, RuntimeErrorType, VmInternalError, }; use crate::vm::events::*; use crate::vm::representations::SymbolicExpression; @@ -441,7 +441,7 @@ impl AssetMap { for principal in self.burn_map.keys() { total = total .checked_add(*self.burn_map.get(principal).unwrap_or(&0u128)) - .ok_or_else(|| InterpreterError::Expect("BURN OVERFLOW".into()))?; + .ok_or_else(|| VmInternalError::Expect("BURN OVERFLOW".into()))?; } Ok(total) } @@ -798,8 +798,8 @@ impl<'a, 'hooks> OwnedEnvironment<'a, 'hooks> { pub fn commit(&mut self) -> Result<(AssetMap, EventBatch)> { let (asset_map, event_batch) = self.context.commit()?; - let asset_map = asset_map.ok_or(InterpreterError::FailedToConstructAssetTable)?; - let event_batch = event_batch.ok_or(InterpreterError::FailedToConstructEventBatch)?; + let asset_map = asset_map.ok_or(VmInternalError::FailedToConstructAssetTable)?; + let event_batch = event_batch.ok_or(VmInternalError::FailedToConstructEventBatch)?; Ok((asset_map, event_batch)) } @@ -1126,7 +1126,7 @@ impl<'a, 'b, 'hooks> Environment<'a, 'b, 'hooks> { let args: Result> = args.iter() .map(|arg| { let value = arg.match_atom_value() - .ok_or_else(|| InterpreterError::InterpreterError(format!("Passed non-value expression to exec_tx on {tx_name}!")))?; + .ok_or_else(|| VmInternalError::InvariantViolation(format!("Passed non-value expression to exec_tx on {tx_name}!")))?; // sanitize contract-call inputs in epochs >= 2.4 // testing todo: ensure sanitize_value() preserves trait callability! let expected_type = TypeSignature::type_of(value)?; @@ -1230,7 +1230,7 @@ impl<'a, 'b, 'hooks> Environment<'a, 'b, 'hooks> { .database .set_block_hash(prior_bhh, true) .map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "ERROR: Failed to restore prior active block after time-shifted evaluation." .into()) })?; @@ -1355,7 +1355,7 @@ impl<'a, 'b, 'hooks> Environment<'a, 'b, 'hooks> { } Err(_) => { self.global_context.roll_back()?; - Err(InterpreterError::InsufficientBalance.into()) + Err(VmInternalError::InsufficientBalance.into()) } }, Err(e) => { @@ -1583,7 +1583,7 @@ impl<'a, 'hooks> GlobalContext<'a, 'hooks> { fn get_asset_map(&mut self) -> Result<&mut AssetMap> { self.asset_maps .last_mut() - .ok_or_else(|| InterpreterError::Expect("Failed to obtain asset map".into()).into()) + .ok_or_else(|| VmInternalError::Expect("Failed to obtain asset map".into()).into()) } pub fn log_asset_transfer( @@ -1700,10 +1700,10 @@ impl<'a, 'hooks> GlobalContext<'a, 'hooks> { trace!("Calling commit"); self.read_only.pop(); let asset_map = self.asset_maps.pop().ok_or_else(|| { - InterpreterError::Expect("ERROR: Committed non-nested context.".into()) + VmInternalError::Expect("ERROR: Committed non-nested context.".into()) })?; let mut event_batch = self.event_batches.pop().ok_or_else(|| { - InterpreterError::Expect("ERROR: Committed non-nested context.".into()) + VmInternalError::Expect("ERROR: Committed non-nested context.".into()) })?; let out_map = match self.asset_maps.last_mut() { @@ -1732,15 +1732,15 @@ impl<'a, 'hooks> GlobalContext<'a, 'hooks> { pub fn roll_back(&mut self) -> Result<()> { let popped = self.asset_maps.pop(); if popped.is_none() { - return Err(InterpreterError::Expect("Expected entry to rollback".into()).into()); + return Err(VmInternalError::Expect("Expected entry to rollback".into()).into()); } let popped = self.read_only.pop(); if popped.is_none() { - return Err(InterpreterError::Expect("Expected entry to rollback".into()).into()); + return Err(VmInternalError::Expect("Expected entry to rollback".into()).into()); } let popped = self.event_batches.pop(); if popped.is_none() { - return Err(InterpreterError::Expect("Expected entry to rollback".into()).into()); + return Err(VmInternalError::Expect("Expected entry to rollback".into()).into()); } self.database.roll_back() @@ -1961,20 +1961,20 @@ impl CallStack { pub fn remove(&mut self, function: &FunctionIdentifier, tracked: bool) -> Result<()> { if let Some(removed) = self.stack.pop() { if removed != *function { - return Err(InterpreterError::InterpreterError( + return Err(VmInternalError::InvariantViolation( "Tried to remove item from empty call stack.".to_string(), ) .into()); } if tracked && !self.set.remove(function) { - return Err(InterpreterError::InterpreterError( + return Err(VmInternalError::InvariantViolation( "Tried to remove tracked function from call stack, but could not find in current context.".into() ) .into()); } Ok(()) } else { - Err(InterpreterError::InterpreterError( + Err(VmInternalError::InvariantViolation( "Tried to remove item from empty call stack.".to_string(), ) .into()) @@ -2175,7 +2175,7 @@ mod test { &BuffData::empty(), ) .unwrap_err(); - assert_eq!(e.to_string(), "Interpreter(InsufficientBalance)"); + assert_eq!(e.to_string(), "Internal(InsufficientBalance)"); } #[test] diff --git a/clarity/src/vm/database/clarity_db.rs b/clarity/src/vm/database/clarity_db.rs index f7e375edf0..076fd6010a 100644 --- a/clarity/src/vm/database/clarity_db.rs +++ b/clarity/src/vm/database/clarity_db.rs @@ -38,7 +38,7 @@ use crate::vm::database::structures::{ }; use crate::vm::database::{ClarityBackingStore, RollbackWrapper}; use crate::vm::errors::{ - CheckErrorKind, Error, InterpreterError, InterpreterResult as Result, RuntimeErrorType, + CheckErrorKind, Error, InterpreterResult as Result, RuntimeErrorType, VmInternalError, }; use crate::vm::representations::ClarityName; use crate::vm::types::serialization::NONE_SERIALIZATION_LEN; @@ -548,7 +548,7 @@ impl<'a> ClarityDatabase<'a> { let serialized = if sanitize { let value_size = value .serialized_size() - .map_err(|e| InterpreterError::Expect(e.to_string()))? + .map_err(|e| VmInternalError::Expect(e.to_string()))? as u64; let (sanitized_value, did_sanitize) = @@ -578,7 +578,7 @@ impl<'a> ClarityDatabase<'a> { ) -> Result> { self.store .get_value(key, expected, epoch) - .map_err(|e| InterpreterError::DBError(e.to_string()).into()) + .map_err(|e| VmInternalError::DBError(e.to_string()).into()) } pub fn get_data_with_proof(&mut self, key: &str) -> Result)>> @@ -706,7 +706,7 @@ impl<'a> ClarityDatabase<'a> { data: &T, ) -> Result<()> { if self.store.has_metadata_entry(contract_identifier, key) { - Err(InterpreterError::Expect(format!( + Err(VmInternalError::Expect(format!( "Metadata entry '{key}' already exists for contract: {contract_identifier}" )) .into()) @@ -779,7 +779,7 @@ impl<'a> ClarityDatabase<'a> { let contract_size: u64 = self.fetch_metadata(contract_identifier, &key)? .ok_or_else(|| { - InterpreterError::Expect( + VmInternalError::Expect( "Failed to read non-consensus contract metadata, even though contract exists in MARF." .into()) })?; @@ -790,7 +790,7 @@ impl<'a> ClarityDatabase<'a> { let data_size: u64 = self .fetch_metadata(contract_identifier, &key)? .ok_or_else(|| { - InterpreterError::Expect( + VmInternalError::Expect( "Failed to read non-consensus contract metadata, even though contract exists in MARF." .into()) })?; @@ -812,7 +812,7 @@ impl<'a> ClarityDatabase<'a> { let contract_size: u64 = self.fetch_metadata(contract_identifier, &key)? .ok_or_else(|| { - InterpreterError::Expect( + VmInternalError::Expect( "Failed to read non-consensus contract metadata, even though contract exists in MARF." .into()) })?; @@ -856,7 +856,7 @@ impl<'a> ClarityDatabase<'a> { ContractDataVarName::Contract.as_str(), ); let mut data: Contract = self.fetch_metadata(contract_identifier, &key)? - .ok_or_else(|| InterpreterError::Expect( + .ok_or_else(|| VmInternalError::Expect( "Failed to read non-consensus contract metadata, even though contract exists in MARF." .into()))?; data.canonicalize_types(&self.get_clarity_epoch_version()?); @@ -874,7 +874,7 @@ impl<'a> ClarityDatabase<'a> { pub fn get_clarity_epoch_version(&mut self) -> Result { let out = match self.get_data(Self::clarity_state_epoch_key())? { Some(x) => u32::try_into(x).map_err(|_| { - InterpreterError::Expect("Bad Clarity epoch version in stored Clarity state".into()) + VmInternalError::Expect("Bad Clarity epoch version in stored Clarity state".into()) })?, None => StacksEpochId::Epoch20, }; @@ -892,7 +892,7 @@ impl<'a> ClarityDatabase<'a> { let epoch = self.get_clarity_epoch_version()?; if epoch.uses_marfed_block_time() { let block_time = block_time.ok_or_else(|| { - InterpreterError::Expect( + VmInternalError::Expect( "FATAL: Marfed block time not provided to Clarity DB setup".into(), ) })?; @@ -918,7 +918,7 @@ impl<'a> ClarityDatabase<'a> { &epoch, ) .map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "FATAL: failed to load ustx_liquid_supply Clarity key".into(), ) })? @@ -935,7 +935,7 @@ impl<'a> ClarityDatabase<'a> { &StacksEpochId::Epoch21, ) .map_err(|_| { - InterpreterError::Expect("FATAL: Failed to store STX liquid supply".into()).into() + VmInternalError::Expect("FATAL: Failed to store STX liquid supply".into()).into() }) } @@ -969,11 +969,11 @@ impl<'a> ClarityDatabase<'a> { self.get_data(TENURE_HEIGHT_KEY)? .ok_or_else(|| { - InterpreterError::Expect("No tenure height in stored Clarity state".into()).into() + VmInternalError::Expect("No tenure height in stored Clarity state".into()).into() }) .and_then(|x| { u32::try_into(x).map_err(|_| { - InterpreterError::Expect("Bad tenure height in stored Clarity state".into()) + VmInternalError::Expect("Bad tenure height in stored Clarity state".into()) .into() }) }) @@ -984,7 +984,7 @@ impl<'a> ClarityDatabase<'a> { /// transactions in the block. pub fn set_tenure_height(&mut self, height: u32) -> Result<()> { if self.get_clarity_epoch_version()? < StacksEpochId::Epoch30 { - return Err(Error::Interpreter(InterpreterError::Expect( + return Err(Error::Internal(VmInternalError::Expect( "Setting tenure height in Clarity state is not supported before epoch 3.0".into(), ))); } @@ -1012,7 +1012,7 @@ impl ClarityDatabase<'_> { // the caller is responsible for ensuring that the block_height given // is < current_block_height, so this should _always_ return a value. .ok_or_else(|| { - InterpreterError::Expect( + VmInternalError::Expect( "Block header hash must return for provided block height".into(), ) .into() @@ -1115,7 +1115,7 @@ impl ClarityDatabase<'_> { self.get_burnchain_block_height(&last_mined_bhh) .ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "Block header hash '{last_mined_bhh}' must return for provided stacks block height {cur_stacks_height}" )) .into() @@ -1125,7 +1125,7 @@ impl ClarityDatabase<'_> { self.burn_state_db .get_tip_burn_block_height() .ok_or_else(|| { - InterpreterError::Expect("Failed to get burnchain tip height.".into()).into() + VmInternalError::Expect("Failed to get burnchain tip height.".into()).into() }) } } @@ -1135,7 +1135,7 @@ impl ClarityDatabase<'_> { let epoch = self.get_stacks_epoch_for_block(&id_bhh)?; self.headers_db .get_stacks_block_header_hash_for_block(&id_bhh, &epoch) - .ok_or_else(|| InterpreterError::Expect("Failed to get block data.".into()).into()) + .ok_or_else(|| VmInternalError::Expect("Failed to get block data.".into()).into()) } pub fn get_burn_block_time( @@ -1150,7 +1150,7 @@ impl ClarityDatabase<'_> { let epoch = self.get_stacks_epoch_for_block(&id_bhh)?; self.headers_db .get_burn_block_time_for_block(&id_bhh, Some(&epoch)) - .ok_or_else(|| InterpreterError::Expect("Failed to get block data.".into()).into()) + .ok_or_else(|| VmInternalError::Expect("Failed to get block data.".into()).into()) } pub fn get_block_time(&mut self, block_height: u32) -> Result { @@ -1162,7 +1162,7 @@ impl ClarityDatabase<'_> { self.headers_db .get_stacks_block_time_for_block(&id_bhh) - .ok_or_else(|| InterpreterError::Expect("Failed to get block data.".into()).into()) + .ok_or_else(|| VmInternalError::Expect("Failed to get block data.".into()).into()) } pub fn get_burnchain_block_header_hash( @@ -1172,7 +1172,7 @@ impl ClarityDatabase<'_> { let id_bhh = self.get_index_block_header_hash(block_height)?; self.headers_db .get_burn_header_hash_for_block(&id_bhh) - .ok_or_else(|| InterpreterError::Expect("Failed to get block data.".into()).into()) + .ok_or_else(|| VmInternalError::Expect("Failed to get block data.".into()).into()) } /// In Epoch 2.x: @@ -1205,7 +1205,7 @@ impl ClarityDatabase<'_> { .headers_db .get_consensus_hash_for_block(&parent_id_bhh, &epoch) .ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "FATAL: no consensus hash found for StacksBlockId {parent_id_bhh}" )) })?; @@ -1215,7 +1215,7 @@ impl ClarityDatabase<'_> { .burn_state_db .get_sortition_id_from_consensus_hash(&consensus_hash) .ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "FATAL: no SortitionID found for consensus hash {consensus_hash}" )) })?; @@ -1270,7 +1270,7 @@ impl ClarityDatabase<'_> { let epoch = self.get_stacks_epoch_for_block(&id_bhh)?; self.headers_db .get_vrf_seed_for_block(&id_bhh, &epoch) - .ok_or_else(|| InterpreterError::Expect("Failed to get block data.".into()).into()) + .ok_or_else(|| VmInternalError::Expect("Failed to get block data.".into()).into()) } pub fn get_miner_address(&mut self, block_height: u32) -> Result { @@ -1279,7 +1279,7 @@ impl ClarityDatabase<'_> { Ok(self .headers_db .get_miner_address(&id_bhh, &epoch) - .ok_or_else(|| InterpreterError::Expect("Failed to get block data.".into()))? + .ok_or_else(|| VmInternalError::Expect("Failed to get block data.".into()))? .into()) } @@ -1294,7 +1294,7 @@ impl ClarityDatabase<'_> { .headers_db .get_burnchain_tokens_spent_for_winning_block(&id_bhh, &epoch) .ok_or_else(|| { - InterpreterError::Expect( + VmInternalError::Expect( "FATAL: no winning burnchain token spend record for block".into(), ) })?) @@ -1311,7 +1311,7 @@ impl ClarityDatabase<'_> { .headers_db .get_burnchain_tokens_spent_for_block(&id_bhh, &epoch) .ok_or_else(|| { - InterpreterError::Expect( + VmInternalError::Expect( "FATAL: no total burnchain token spend record for block".into(), ) })?) @@ -1336,7 +1336,7 @@ impl ClarityDatabase<'_> { .headers_db .get_tokens_earned_for_block(&id_bhh, &epoch) .ok_or_else(|| { - InterpreterError::Expect("FATAL: matured block has no recorded reward".into()) + VmInternalError::Expect("FATAL: matured block has no recorded reward".into()) })?; Ok(Some(reward)) @@ -1390,22 +1390,22 @@ impl ClarityDatabase<'_> { TupleData::from_data(vec![ ( ClarityName::try_from("reporter").map_err(|_| { - InterpreterError::Expect("BUG: valid string representation".into()) + VmInternalError::Expect("BUG: valid string representation".into()) })?, Value::Principal(PrincipalData::Standard(reporter.clone())), ), ( ClarityName::try_from("sequence").map_err(|_| { - InterpreterError::Expect("BUG: valid string representation".into()) + VmInternalError::Expect("BUG: valid string representation".into()) })?, Value::UInt(seq as u128), ), ]) - .map_err(|_| InterpreterError::Expect("BUG: valid tuple representation".into()))?, + .map_err(|_| VmInternalError::Expect("BUG: valid tuple representation".into()))?, ); let mut value_bytes = vec![]; value.serialize_write(&mut value_bytes).map_err(|_| { - InterpreterError::Expect("BUG: valid tuple representation did not serialize".into()) + VmInternalError::Expect("BUG: valid tuple representation did not serialize".into()) })?; let value_str = to_hex(&value_bytes); @@ -1420,7 +1420,7 @@ impl ClarityDatabase<'_> { self.get_data(&key)? .map(|height_str: String| { height_str.parse::().map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "BUG: inserted non-u32 as height of microblock pubkey hash".into(), ) .into() @@ -1439,7 +1439,7 @@ impl ClarityDatabase<'_> { .map(|reporter_hex_str: String| { let reporter_value = Value::try_deserialize_hex_untyped(&reporter_hex_str) .map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "BUG: failed to decode serialized poison-microblock reporter".into(), ) })?; @@ -1447,7 +1447,7 @@ impl ClarityDatabase<'_> { let reporter_value = tuple_data .get("reporter") .map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "BUG: poison-microblock report has no 'reporter'".into(), ) })? @@ -1455,7 +1455,7 @@ impl ClarityDatabase<'_> { let seq_value = tuple_data .get("sequence") .map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "BUG: poison-microblock report has no 'sequence'".into(), ) })? @@ -1466,11 +1466,11 @@ impl ClarityDatabase<'_> { let seq: u16 = seq_u128 .try_into() - .map_err(|_| InterpreterError::Expect("BUG: seq exceeds u16 max".into()))?; + .map_err(|_| VmInternalError::Expect("BUG: seq exceeds u16 max".into()))?; if let PrincipalData::Standard(principal_data) = reporter_principal { Ok((principal_data, seq)) } else { - Err(InterpreterError::Expect( + Err(VmInternalError::Expect( "BUG: poison-microblock report principal is not a standard principal" .into(), ) @@ -1767,7 +1767,7 @@ impl ClarityDatabase<'_> { serialized_byte_len: serialized_byte_len .checked_add(byte_len_of_serialization(&key_serialized)) .ok_or_else(|| { - InterpreterError::Expect("Overflowed Clarity key/value size".into()) + VmInternalError::Expect("Overflowed Clarity key/value size".into()) })?, }), } @@ -1922,7 +1922,7 @@ impl ClarityDatabase<'_> { serialized_byte_len: key_serialized_byte_len .checked_add(placed_size) .ok_or_else(|| { - InterpreterError::Expect("Overflowed Clarity key/value size".into()) + VmInternalError::Expect("Overflowed Clarity key/value size".into()) })?, }) } @@ -1969,7 +1969,7 @@ impl ClarityDatabase<'_> { serialized_byte_len: key_serialized_byte_len .checked_add(*NONE_SERIALIZATION_LEN) .ok_or_else(|| { - InterpreterError::Expect("Overflowed Clarity key/value size".into()) + VmInternalError::Expect("Overflowed Clarity key/value size".into()) })?, }) } @@ -2052,7 +2052,7 @@ impl ClarityDatabase<'_> { token_name, ); let current_supply: u128 = self.get_data(&key)?.ok_or_else(|| { - InterpreterError::Expect("ERROR: Clarity VM failed to track token supply.".into()) + VmInternalError::Expect("ERROR: Clarity VM failed to track token supply.".into()) })?; let new_supply = current_supply @@ -2080,7 +2080,7 @@ impl ClarityDatabase<'_> { token_name, ); let current_supply: u128 = self.get_data(&key)?.ok_or_else(|| { - InterpreterError::Expect("ERROR: Clarity VM failed to track token supply.".into()) + VmInternalError::Expect("ERROR: Clarity VM failed to track token supply.".into()) })?; if amount > current_supply { @@ -2144,7 +2144,7 @@ impl ClarityDatabase<'_> { token_name, ); let supply = self.get_data(&key)?.ok_or_else(|| { - InterpreterError::Expect("ERROR: Clarity VM failed to track token supply.".into()) + VmInternalError::Expect("ERROR: Clarity VM failed to track token supply.".into()) })?; Ok(supply) } @@ -2175,7 +2175,7 @@ impl ClarityDatabase<'_> { let value: Option = self.get_value( &key, &TypeSignature::new_option(TypeSignature::PrincipalType) - .map_err(|_| InterpreterError::Expect("Unexpected type failure".into()))?, + .map_err(|_| VmInternalError::Expect("Unexpected type failure".into()))?, &epoch, )?; let owner = match value { @@ -2381,13 +2381,13 @@ impl ClarityDatabase<'_> { pub fn get_stacks_epoch_for_block(&self, id_bhh: &StacksBlockId) -> Result { let burn_block = self.get_burnchain_block_height(id_bhh).ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "FATAL: no burnchain block height found for Stacks block {id_bhh}" )) })?; let epoch = self .get_stacks_epoch(burn_block) - .ok_or_else(|| InterpreterError::Expect("Failed to get block data.".into()))?; + .ok_or_else(|| VmInternalError::Expect("Failed to get block data.".into()))?; Ok(epoch.epoch_id) } } diff --git a/clarity/src/vm/database/clarity_store.rs b/clarity/src/vm/database/clarity_store.rs index e1d6dacaee..c3d388aa43 100644 --- a/clarity/src/vm/database/clarity_store.rs +++ b/clarity/src/vm/database/clarity_store.rs @@ -24,7 +24,7 @@ use crate::vm::contexts::GlobalContext; use crate::vm::database::{ ClarityDatabase, ClarityDeserializable, ClaritySerializable, NULL_BURN_STATE_DB, NULL_HEADER_DB, }; -use crate::vm::errors::{InterpreterError, InterpreterResult as Result}; +use crate::vm::errors::{InterpreterResult as Result, VmInternalError}; use crate::vm::types::{PrincipalData, QualifiedContractIdentifier}; use crate::vm::Value; @@ -160,17 +160,17 @@ impl ClaritySerializable for ContractCommitment { impl ClarityDeserializable for ContractCommitment { fn deserialize(input: &str) -> Result { if input.len() != 72 { - return Err(InterpreterError::Expect("Unexpected input length".into()).into()); + return Err(VmInternalError::Expect("Unexpected input length".into()).into()); } let hash = Sha512Trunc256Sum::from_hex(&input[0..64]) - .map_err(|_| InterpreterError::Expect("Hex decode fail.".into()))?; + .map_err(|_| VmInternalError::Expect("Hex decode fail.".into()))?; let height_bytes = hex_bytes(&input[64..72]) - .map_err(|_| InterpreterError::Expect("Hex decode fail.".into()))?; + .map_err(|_| VmInternalError::Expect("Hex decode fail.".into()))?; let block_height = u32::from_be_bytes( height_bytes .as_slice() .try_into() - .map_err(|_| InterpreterError::Expect("Block height decode fail.".into()))?, + .map_err(|_| VmInternalError::Expect("Block height decode fail.".into()))?, ); Ok(ContractCommitment { hash, block_height }) } diff --git a/clarity/src/vm/database/key_value_wrapper.rs b/clarity/src/vm/database/key_value_wrapper.rs index 5578ac549d..236a7d0cfb 100644 --- a/clarity/src/vm/database/key_value_wrapper.rs +++ b/clarity/src/vm/database/key_value_wrapper.rs @@ -24,7 +24,7 @@ use stacks_common::util::hash::Sha512Trunc256Sum; use super::clarity_store::SpecialCaseHandler; use super::{ClarityBackingStore, ClarityDeserializable}; use crate::vm::database::clarity_store::{make_contract_hash_key, ContractCommitment}; -use crate::vm::errors::{InterpreterError, InterpreterResult}; +use crate::vm::errors::{InterpreterResult, VmInternalError}; use crate::vm::types::serialization::SerializationError; use crate::vm::types::{QualifiedContractIdentifier, TypeSignature}; use crate::vm::Value; @@ -49,7 +49,7 @@ fn rollback_edits_push(edits: &mut Vec<(T, RollbackValueCheck)>, key: T, _val fn rollback_check_pre_bottom_commit( edits: Vec<(T, RollbackValueCheck)>, lookup_map: &mut HashMap>, -) -> Result, InterpreterError> +) -> Result, VmInternalError> where T: Eq + Hash + Clone, { @@ -86,7 +86,7 @@ where fn rollback_check_pre_bottom_commit( edits: Vec<(T, RollbackValueCheck)>, lookup_map: &mut HashMap>, -) -> Result, InterpreterError> +) -> Result, VmInternalError> where T: Eq + Hash + Clone, { @@ -179,19 +179,19 @@ fn rollback_lookup_map( key: &T, value: &RollbackValueCheck, lookup_map: &mut HashMap>, -) -> Result +) -> Result where T: Eq + Hash + Clone, { let popped_value; let remove_edit_deque = { let key_edit_history = lookup_map.get_mut(key).ok_or_else(|| { - InterpreterError::Expect( + VmInternalError::Expect( "ERROR: Clarity VM had edit log entry, but not lookup_map entry".into(), ) })?; popped_value = key_edit_history.pop().ok_or_else(|| { - InterpreterError::Expect("ERROR: expected value in edit history".into()) + VmInternalError::Expect("ERROR: expected value in edit history".into()) })?; rollback_value_check(&popped_value, value); key_edit_history.is_empty() @@ -240,9 +240,9 @@ impl<'a> RollbackWrapper<'a> { // Rollback the child's edits. // this clears all edits from the child's edit queue, // and removes any of those edits from the lookup map. - pub fn rollback(&mut self) -> Result<(), InterpreterError> { + pub fn rollback(&mut self) -> Result<(), VmInternalError> { let mut last_item = self.stack.pop().ok_or_else(|| { - InterpreterError::Expect("ERROR: Clarity VM attempted to commit past the stack.".into()) + VmInternalError::Expect("ERROR: Clarity VM attempted to commit past the stack.".into()) })?; last_item.edits.reverse(); @@ -263,9 +263,9 @@ impl<'a> RollbackWrapper<'a> { self.stack.len() } - pub fn commit(&mut self) -> Result<(), InterpreterError> { + pub fn commit(&mut self) -> Result<(), VmInternalError> { let mut last_item = self.stack.pop().ok_or_else(|| { - InterpreterError::Expect("ERROR: Clarity VM attempted to commit past the stack.".into()) + VmInternalError::Expect("ERROR: Clarity VM attempted to commit past the stack.".into()) })?; if let Some(next_up) = self.stack.last_mut() { @@ -283,7 +283,7 @@ impl<'a> RollbackWrapper<'a> { rollback_check_pre_bottom_commit(last_item.edits, &mut self.lookup_map)?; if !all_edits.is_empty() { self.store.put_all_data(all_edits).map_err(|e| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: Failed to commit data to sql store: {e:?}" )) })?; @@ -295,7 +295,7 @@ impl<'a> RollbackWrapper<'a> { )?; if !metadata_edits.is_empty() { self.store.put_all_metadata(metadata_edits).map_err(|e| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: Failed to commit data to sql store: {e:?}" )) })?; @@ -322,9 +322,7 @@ fn inner_put_data( impl RollbackWrapper<'_> { pub fn put_data(&mut self, key: &str, value: &str) -> InterpreterResult<()> { let current = self.stack.last_mut().ok_or_else(|| { - InterpreterError::Expect( - "ERROR: Clarity VM attempted PUT on non-nested context.".into(), - ) + VmInternalError::Expect("ERROR: Clarity VM attempted PUT on non-nested context.".into()) })?; inner_put_data( @@ -387,9 +385,7 @@ impl RollbackWrapper<'_> { T: ClarityDeserializable, { self.stack.last().ok_or_else(|| { - InterpreterError::Expect( - "ERROR: Clarity VM attempted GET on non-nested context.".into(), - ) + VmInternalError::Expect("ERROR: Clarity VM attempted GET on non-nested context.".into()) })?; if self.query_pending_data { @@ -503,11 +499,9 @@ impl RollbackWrapper<'_> { contract: &QualifiedContractIdentifier, key: &str, value: &str, - ) -> Result<(), InterpreterError> { + ) -> Result<(), VmInternalError> { let current = self.stack.last_mut().ok_or_else(|| { - InterpreterError::Expect( - "ERROR: Clarity VM attempted PUT on non-nested context.".into(), - ) + VmInternalError::Expect("ERROR: Clarity VM attempted PUT on non-nested context.".into()) })?; let metadata_key = (contract.clone(), key.to_string()); @@ -529,9 +523,7 @@ impl RollbackWrapper<'_> { key: &str, ) -> InterpreterResult> { self.stack.last().ok_or_else(|| { - InterpreterError::Expect( - "ERROR: Clarity VM attempted GET on non-nested context.".into(), - ) + VmInternalError::Expect("ERROR: Clarity VM attempted GET on non-nested context.".into()) })?; // This is THEORETICALLY a spurious clone, but it's hard to turn something like @@ -560,9 +552,7 @@ impl RollbackWrapper<'_> { key: &str, ) -> InterpreterResult> { self.stack.last().ok_or_else(|| { - InterpreterError::Expect( - "ERROR: Clarity VM attempted GET on non-nested context.".into(), - ) + VmInternalError::Expect("ERROR: Clarity VM attempted GET on non-nested context.".into()) })?; // This is THEORETICALLY a spurious clone, but it's hard to turn something like @@ -584,9 +574,7 @@ impl RollbackWrapper<'_> { pub fn has_entry(&mut self, key: &str) -> InterpreterResult { self.stack.last().ok_or_else(|| { - InterpreterError::Expect( - "ERROR: Clarity VM attempted GET on non-nested context.".into(), - ) + VmInternalError::Expect("ERROR: Clarity VM attempted GET on non-nested context.".into()) })?; if self.query_pending_data && self.lookup_map.contains_key(key) { Ok(true) diff --git a/clarity/src/vm/database/sqlite.rs b/clarity/src/vm/database/sqlite.rs index aec7e37c65..a32703634b 100644 --- a/clarity/src/vm/database/sqlite.rs +++ b/clarity/src/vm/database/sqlite.rs @@ -27,7 +27,7 @@ use super::{ }; use crate::vm::analysis::{AnalysisDatabase, CheckErrorKind}; use crate::vm::errors::{ - IncomparableError, InterpreterError, InterpreterResult as Result, RuntimeErrorType, + IncomparableError, InterpreterResult as Result, RuntimeErrorType, VmInternalError, }; use crate::vm::types::QualifiedContractIdentifier; @@ -43,7 +43,7 @@ fn sqlite_put(conn: &Connection, key: &str, value: &str) -> Result<()> { Ok(_) => Ok(()), Err(e) => { error!("Failed to insert/replace ({key},{value}): {e:?}"); - Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()) + Err(VmInternalError::DBError(SQL_FAIL_MESSAGE.into()).into()) } } } @@ -62,7 +62,7 @@ fn sqlite_get(conn: &Connection, key: &str) -> Result> { Ok(x) => Ok(x), Err(e) => { error!("Failed to query '{key}': {e:?}"); - Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()) + Err(VmInternalError::DBError(SQL_FAIL_MESSAGE.into()).into()) } }; @@ -88,7 +88,7 @@ pub fn sqlite_get_contract_hash( hash: contract_hash, } = contract_commitment?; let bhh = store.get_block_at_height(block_height) - .ok_or_else(|| InterpreterError::Expect("Should always be able to map from height to block hash when looking up contract information.".into()))?; + .ok_or_else(|| VmInternalError::Expect("Should always be able to map from height to block hash when looking up contract information.".into()))?; Ok((bhh, contract_hash)) } @@ -154,7 +154,7 @@ impl SqliteConnection { params, ) { error!("Failed to insert ({bhh},{key},{value}): {e:?}"); - return Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()); + return Err(VmInternalError::DBError(SQL_FAIL_MESSAGE.into()).into()); } Ok(()) } @@ -170,7 +170,7 @@ impl SqliteConnection { params, ) { error!("Failed to update {from} to {to}: {e:?}"); - return Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()); + return Err(VmInternalError::DBError(SQL_FAIL_MESSAGE.into()).into()); } Ok(()) } @@ -181,7 +181,7 @@ impl SqliteConnection { params![from], ) { error!("Failed to drop metadata from {from}: {e:?}"); - return Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()); + return Err(VmInternalError::DBError(SQL_FAIL_MESSAGE.into()).into()); } Ok(()) } @@ -206,7 +206,7 @@ impl SqliteConnection { Ok(x) => Ok(x), Err(e) => { error!("Failed to query ({bhh},{key}): {e:?}"); - Err(InterpreterError::DBError(SQL_FAIL_MESSAGE.into()).into()) + Err(VmInternalError::DBError(SQL_FAIL_MESSAGE.into()).into()) } } } @@ -219,14 +219,14 @@ impl SqliteConnection { impl SqliteConnection { pub fn initialize_conn(conn: &Connection) -> Result<()> { conn.query_row("PRAGMA journal_mode = WAL;", NO_PARAMS, |_row| Ok(())) - .map_err(|x| InterpreterError::SqliteError(IncomparableError { err: x }))?; + .map_err(|x| VmInternalError::SqliteError(IncomparableError { err: x }))?; conn.execute( "CREATE TABLE IF NOT EXISTS data_table (key TEXT PRIMARY KEY, value TEXT)", NO_PARAMS, ) - .map_err(|x| InterpreterError::SqliteError(IncomparableError { err: x }))?; + .map_err(|x| VmInternalError::SqliteError(IncomparableError { err: x }))?; conn.execute( "CREATE TABLE IF NOT EXISTS metadata_table @@ -234,13 +234,13 @@ impl SqliteConnection { UNIQUE (key, blockhash))", NO_PARAMS, ) - .map_err(|x| InterpreterError::SqliteError(IncomparableError { err: x }))?; + .map_err(|x| VmInternalError::SqliteError(IncomparableError { err: x }))?; conn.execute( "CREATE INDEX IF NOT EXISTS md_blockhashes ON metadata_table(blockhash)", NO_PARAMS, ) - .map_err(|x| InterpreterError::SqliteError(IncomparableError { err: x }))?; + .map_err(|x| VmInternalError::SqliteError(IncomparableError { err: x }))?; Self::check_schema(conn)?; @@ -257,22 +257,22 @@ impl SqliteConnection { let sql = "SELECT sql FROM sqlite_master WHERE name=?"; let _: String = conn .query_row(sql, params!["data_table"], |row| row.get(0)) - .map_err(|x| InterpreterError::SqliteError(IncomparableError { err: x }))?; + .map_err(|x| VmInternalError::SqliteError(IncomparableError { err: x }))?; let _: String = conn .query_row(sql, params!["metadata_table"], |row| row.get(0)) - .map_err(|x| InterpreterError::SqliteError(IncomparableError { err: x }))?; + .map_err(|x| VmInternalError::SqliteError(IncomparableError { err: x }))?; let _: String = conn .query_row(sql, params!["md_blockhashes"], |row| row.get(0)) - .map_err(|x| InterpreterError::SqliteError(IncomparableError { err: x }))?; + .map_err(|x| VmInternalError::SqliteError(IncomparableError { err: x }))?; Ok(()) } fn inner_open(filename: &str) -> Result { let conn = Connection::open(filename) - .map_err(|x| InterpreterError::SqliteError(IncomparableError { err: x }))?; + .map_err(|x| VmInternalError::SqliteError(IncomparableError { err: x }))?; conn.busy_handler(Some(tx_busy_handler)) - .map_err(|x| InterpreterError::SqliteError(IncomparableError { err: x }))?; + .map_err(|x| VmInternalError::SqliteError(IncomparableError { err: x }))?; Ok(conn) } diff --git a/clarity/src/vm/database/structures.rs b/clarity/src/vm/database/structures.rs index c4fec9f382..a106bfc105 100644 --- a/clarity/src/vm/database/structures.rs +++ b/clarity/src/vm/database/structures.rs @@ -22,7 +22,7 @@ use stacks_common::util::hash::{hex_bytes, to_hex}; use crate::vm::analysis::ContractAnalysis; use crate::vm::contracts::Contract; use crate::vm::database::ClarityDatabase; -use crate::vm::errors::{Error, InterpreterError, RuntimeErrorType}; +use crate::vm::errors::{Error, RuntimeErrorType, VmInternalError}; use crate::vm::types::{PrincipalData, TypeSignature}; pub trait ClaritySerializable { @@ -63,13 +63,13 @@ macro_rules! clarity_serializable { // this will instead spill to the heap let deserializer = serde_stacker::Deserializer::new(&mut deserializer); Deserialize::deserialize(deserializer).map_err(|_| { - InterpreterError::Expect("Failed to deserialize vm.Value".into()).into() + VmInternalError::Expect("Failed to deserialize vm.Value".into()).into() }) } #[cfg(target_family = "wasm")] fn deserialize(json: &str) -> Result { serde_json::from_str(json).map_err(|_| { - InterpreterError::Expect("Failed to deserialize vm.Value".into()).into() + VmInternalError::Expect("Failed to deserialize vm.Value".into()).into() }) } } @@ -259,21 +259,21 @@ impl ClaritySerializable for STXBalance { impl ClarityDeserializable for STXBalance { fn deserialize(input: &str) -> Result { let bytes = hex_bytes(input).map_err(|_| { - InterpreterError::Expect("STXBalance deserialization: failed decoding bytes.".into()) + VmInternalError::Expect("STXBalance deserialization: failed decoding bytes.".into()) })?; let result = if bytes.len() == STXBalance::unlocked_and_v1_size { let amount_unlocked = u128::from_be_bytes(bytes[0..16].try_into().map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "STXBalance deserialization: failed reading amount_unlocked.".into(), ) })?); let amount_locked = u128::from_be_bytes(bytes[16..32].try_into().map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "STXBalance deserialization: failed reading amount_locked.".into(), ) })?); let unlock_height = u64::from_be_bytes(bytes[32..40].try_into().map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "STXBalance deserialization: failed reading unlock_height.".into(), ) })?); @@ -295,23 +295,23 @@ impl ClarityDeserializable for STXBalance { && version != &STXBalance::pox_3_version && version != &STXBalance::pox_4_version { - return Err(InterpreterError::Expect(format!( + return Err(VmInternalError::Expect(format!( "Bad version byte in STX Balance serialization = {version}" )) .into()); } let amount_unlocked = u128::from_be_bytes(bytes[1..17].try_into().map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "STXBalance deserialization: failed reading amount_unlocked.".into(), ) })?); let amount_locked = u128::from_be_bytes(bytes[17..33].try_into().map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "STXBalance deserialization: failed reading amount_locked.".into(), ) })?); let unlock_height = u64::from_be_bytes(bytes[33..41].try_into().map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "STXBalance deserialization: failed reading unlock_height.".into(), ) })?); @@ -339,13 +339,13 @@ impl ClarityDeserializable for STXBalance { unlock_height, } } else { - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "Version is checked for pox_3 or pox_2 version compliance above".into(), ) .into()); } } else { - return Err(InterpreterError::Expect(format!( + return Err(VmInternalError::Expect(format!( "Bad STX Balance serialization size = {}", bytes.len() )) @@ -381,7 +381,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { pub fn transfer_to(mut self, recipient: &PrincipalData, amount: u128) -> Result<(), Error> { if !self.can_transfer(amount)? { - return Err(InterpreterError::InsufficientBalance.into()); + return Err(VmInternalError::InsufficientBalance.into()); } let recipient_key = ClarityDatabase::make_key_for_account_balance(recipient); @@ -472,7 +472,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { self.balance .checked_add_unlocked_amount(amount) - .ok_or_else(|| InterpreterError::Expect("STX balance overflow".into()))?; + .ok_or_else(|| VmInternalError::Expect("STX balance overflow".into()))?; Ok(()) } @@ -495,7 +495,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if unlock_burn_height <= self.burn_block_height { // caller needs to have checked this - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "FATAL: cannot set a lock with expired unlock burn height".into(), ) .into()); @@ -503,10 +503,9 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if self.has_locked_tokens()? { // caller needs to have checked this - return Err(InterpreterError::Expect( - "FATAL: account already has locked tokens".into(), - ) - .into()); + return Err( + VmInternalError::Expect("FATAL: account already has locked tokens".into()).into(), + ); } // from `unlock_available_tokens_if_any` call above, `self.balance` should @@ -516,7 +515,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { .balance .get_total_balance()? .checked_sub(amount_to_lock) - .ok_or_else(|| InterpreterError::Expect("STX underflow".into()))?; + .ok_or_else(|| VmInternalError::Expect("STX underflow".into()))?; self.balance = STXBalance::LockedPoxOne { amount_unlocked: new_amount_unlocked, @@ -547,7 +546,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if !self.has_locked_tokens()? { // caller needs to have checked this - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "FATAL: account does not have locked tokens".into(), ) .into()); @@ -556,12 +555,12 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if !self.is_v2_locked()? { // caller needs to have checked this return Err( - InterpreterError::Expect("FATAL: account must be locked by pox-2".into()).into(), + VmInternalError::Expect("FATAL: account must be locked by pox-2".into()).into(), ); } if self.balance.amount_locked() > new_total_locked { - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "FATAL: account must lock more after `increase_lock_v2`".into(), ) .into()); @@ -571,9 +570,9 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { .balance .amount_unlocked() .checked_add(self.balance.amount_locked()) - .ok_or_else(|| InterpreterError::Expect("STX balance overflowed u128".into()))?; + .ok_or_else(|| VmInternalError::Expect("STX balance overflowed u128".into()))?; let amount_unlocked = total_amount.checked_sub(new_total_locked).ok_or_else(|| { - InterpreterError::Expect("STX underflow: more is locked than total balance".into()) + VmInternalError::Expect("STX underflow: more is locked than total balance".into()) })?; self.balance = STXBalance::LockedPoxTwo { @@ -596,7 +595,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if !self.has_locked_tokens()? { // caller needs to have checked this - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "FATAL: account does not have locked tokens".into(), ) .into()); @@ -604,7 +603,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if unlock_burn_height <= self.burn_block_height { // caller needs to have checked this - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "FATAL: cannot set a lock with expired unlock burn height".into(), ) .into()); @@ -633,12 +632,12 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { // caller needs to have checked this if amount_to_lock == 0 { - return Err(InterpreterError::Expect("BUG: cannot lock 0 tokens".into()).into()); + return Err(VmInternalError::Expect("BUG: cannot lock 0 tokens".into()).into()); } if unlock_burn_height <= self.burn_block_height { // caller needs to have checked this - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "FATAL: cannot set a lock with expired unlock burn height".into(), ) .into()); @@ -646,10 +645,9 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if self.has_locked_tokens()? { // caller needs to have checked this - return Err(InterpreterError::Expect( - "FATAL: account already has locked tokens".into(), - ) - .into()); + return Err( + VmInternalError::Expect("FATAL: account already has locked tokens".into()).into(), + ); } // from `unlock_available_tokens_if_any` call above, `self.balance` should @@ -659,7 +657,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { .balance .get_total_balance()? .checked_sub(amount_to_lock) - .ok_or_else(|| InterpreterError::Expect("STX underflow".into()))?; + .ok_or_else(|| VmInternalError::Expect("STX underflow".into()))?; self.balance = STXBalance::LockedPoxTwo { amount_unlocked: new_amount_unlocked, @@ -689,7 +687,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if unlock_burn_height <= self.burn_block_height { // caller needs to have checked this - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "FATAL: cannot set a lock with expired unlock burn height".into(), ) .into()); @@ -697,10 +695,9 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if self.has_locked_tokens()? { // caller needs to have checked this - return Err(InterpreterError::Expect( - "FATAL: account already has locked tokens".into(), - ) - .into()); + return Err( + VmInternalError::Expect("FATAL: account already has locked tokens".into()).into(), + ); } // from `unlock_available_tokens_if_any` call above, `self.balance` should @@ -711,7 +708,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { .get_total_balance()? .checked_sub(amount_to_lock) .ok_or_else(|| { - InterpreterError::Expect( + VmInternalError::Expect( "FATAL: account locks more STX than balance possessed".into(), ) })?; @@ -736,7 +733,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if !self.has_locked_tokens()? { // caller needs to have checked this - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "FATAL: account does not have locked tokens".into(), ) .into()); @@ -744,7 +741,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if unlock_burn_height <= self.burn_block_height { // caller needs to have checked this - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "FATAL: cannot set a lock with expired unlock burn height".into(), ) .into()); @@ -768,7 +765,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if !self.has_locked_tokens()? { // caller needs to have checked this - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "FATAL: account does not have locked tokens".into(), ) .into()); @@ -777,7 +774,7 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { if !self.is_v3_locked()? { // caller needs to have checked this return Err( - InterpreterError::Expect("FATAL: account must be locked by pox-3".into()).into(), + VmInternalError::Expect("FATAL: account must be locked by pox-3".into()).into(), ); } @@ -790,9 +787,9 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { .balance .amount_unlocked() .checked_add(self.balance.amount_locked()) - .ok_or_else(|| InterpreterError::Expect("STX balance overflowed u128".into()))?; + .ok_or_else(|| VmInternalError::Expect("STX balance overflowed u128".into()))?; let amount_unlocked = total_amount.checked_sub(new_total_locked).ok_or_else(|| { - InterpreterError::Expect("STX underflow: more is locked than total balance".into()) + VmInternalError::Expect("STX underflow: more is locked than total balance".into()) })?; self.balance = STXBalance::LockedPoxThree { @@ -947,10 +944,10 @@ impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> { self.balance = match self.balance { STXBalance::Unlocked { amount } => STXBalance::Unlocked { amount }, STXBalance::LockedPoxOne { .. } => { - return Err(InterpreterError::Expect( + return Err(VmInternalError::Expect( "Attempted to accelerate the unlock of a lockup created by PoX-1".into(), ) - .into()) + .into()); } STXBalance::LockedPoxTwo { amount_unlocked, @@ -1121,7 +1118,7 @@ impl STXBalance { } => { *amount_unlocked = amount_unlocked .checked_sub(delta) - .ok_or_else(|| InterpreterError::Expect("STX underflow".into()))?; + .ok_or_else(|| VmInternalError::Expect("STX underflow".into()))?; Ok(()) } } @@ -1283,7 +1280,7 @@ impl STXBalance { }; unlocked .checked_add(locked) - .ok_or_else(|| InterpreterError::Expect("STX overflow".into()).into()) + .ok_or_else(|| VmInternalError::Expect("STX overflow".into()).into()) } pub fn was_locked_by_v1(&self) -> bool { diff --git a/clarity/src/vm/errors.rs b/clarity/src/vm/errors.rs index a322ec1be3..de97e05a4c 100644 --- a/clarity/src/vm/errors.rs +++ b/clarity/src/vm/errors.rs @@ -15,8 +15,8 @@ // along with this program. If not, see . pub use clarity_types::errors::{ - EarlyReturnError, Error, IncomparableError, InterpreterError, InterpreterResult, - RuntimeErrorType, + EarlyReturnError, Error, IncomparableError, InterpreterResult, RuntimeErrorType, + VmInternalError, }; pub use crate::vm::analysis::errors::{ diff --git a/clarity/src/vm/functions/arithmetic.rs b/clarity/src/vm/functions/arithmetic.rs index 61a57d3644..f5366e5286 100644 --- a/clarity/src/vm/functions/arithmetic.rs +++ b/clarity/src/vm/functions/arithmetic.rs @@ -21,7 +21,7 @@ use integer_sqrt::IntegerSquareRoot; use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::runtime_cost; use crate::vm::errors::{ - check_argument_count, CheckErrorKind, InterpreterError, InterpreterResult, RuntimeErrorType, + check_argument_count, CheckErrorKind, InterpreterResult, RuntimeErrorType, VmInternalError, }; use crate::vm::representations::SymbolicExpression; use crate::vm::types::{ @@ -586,7 +586,7 @@ pub fn native_mod(a: Value, b: Value) -> InterpreterResult { pub fn native_bitwise_left_shift(input: Value, pos: Value) -> InterpreterResult { if let Value::UInt(u128_val) = pos { let shamt = u32::try_from(u128_val & 0x7f).map_err(|_| { - InterpreterError::Expect("FATAL: lower 32 bits did not convert to u32".into()) + VmInternalError::Expect("FATAL: lower 32 bits did not convert to u32".into()) })?; match input { @@ -612,7 +612,7 @@ pub fn native_bitwise_left_shift(input: Value, pos: Value) -> InterpreterResult< pub fn native_bitwise_right_shift(input: Value, pos: Value) -> InterpreterResult { if let Value::UInt(u128_val) = pos { let shamt = u32::try_from(u128_val & 0x7f).map_err(|_| { - InterpreterError::Expect("FATAL: lower 32 bits did not convert to u32".into()) + VmInternalError::Expect("FATAL: lower 32 bits did not convert to u32".into()) })?; match input { diff --git a/clarity/src/vm/functions/assets.rs b/clarity/src/vm/functions/assets.rs index 0a32c700a4..abb11be722 100644 --- a/clarity/src/vm/functions/assets.rs +++ b/clarity/src/vm/functions/assets.rs @@ -20,8 +20,8 @@ use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::{runtime_cost, CostTracker}; use crate::vm::database::STXBalance; use crate::vm::errors::{ - check_argument_count, CheckErrorKind, Error, InterpreterError, InterpreterResult as Result, - RuntimeErrorType, + check_argument_count, CheckErrorKind, Error, InterpreterResult as Result, RuntimeErrorType, + VmInternalError, }; use crate::vm::representations::SymbolicExpression; use crate::vm::types::{ @@ -245,19 +245,19 @@ pub fn special_stx_account( ( "unlocked" .try_into() - .map_err(|_| InterpreterError::Expect("Bad special tuple name".into()))?, + .map_err(|_| VmInternalError::Expect("Bad special tuple name".into()))?, Value::UInt(stx_balance.amount_unlocked()), ), ( "locked" .try_into() - .map_err(|_| InterpreterError::Expect("Bad special tuple name".into()))?, + .map_err(|_| VmInternalError::Expect("Bad special tuple name".into()))?, Value::UInt(stx_balance.amount_locked()), ), ( "unlock-height" .try_into() - .map_err(|_| InterpreterError::Expect("Bad special tuple name".into()))?, + .map_err(|_| VmInternalError::Expect("Bad special tuple name".into()))?, Value::UInt(u128::from(stx_balance.effective_unlock_height( v1_unlock_ht, v2_unlock_ht, @@ -354,7 +354,7 @@ pub fn special_mint_token( let final_to_bal = to_bal .checked_add(amount) - .ok_or_else(|| InterpreterError::Expect("STX overflow".into()))?; + .ok_or_else(|| VmInternalError::Expect("STX overflow".into()))?; env.add_memory(TypeSignature::PrincipalType.size()? as u64)?; env.add_memory(TypeSignature::UIntType.size()? as u64)?; @@ -474,7 +474,7 @@ pub fn special_mint_asset_v205( let asset_size = asset .serialized_size() - .map_err(|e| InterpreterError::Expect(e.to_string()))? as u64; + .map_err(|e| VmInternalError::Expect(e.to_string()))? as u64; runtime_cost(ClarityCostFunction::NftMint, env, asset_size)?; if !expected_asset_type.admits(env.epoch(), &asset)? { @@ -642,7 +642,7 @@ pub fn special_transfer_asset_v205( let asset_size = asset .serialized_size() - .map_err(|e| InterpreterError::Expect(e.to_string()))? as u64; + .map_err(|e| VmInternalError::Expect(e.to_string()))? as u64; runtime_cost(ClarityCostFunction::NftTransfer, env, asset_size)?; if !expected_asset_type.admits(env.epoch(), &asset)? { @@ -887,7 +887,7 @@ pub fn special_get_owner_v200( expected_asset_type, ) { Ok(owner) => Ok(Value::some(Value::Principal(owner)).map_err(|_| { - InterpreterError::Expect("Principal should always fit in optional.".into()) + VmInternalError::Expect("Principal should always fit in optional.".into()) })?), Err(Error::Runtime(RuntimeErrorType::NoSuchToken, _)) => Ok(Value::none()), Err(e) => Err(e), @@ -916,7 +916,7 @@ pub fn special_get_owner_v205( let asset_size = asset .serialized_size() - .map_err(|e| InterpreterError::Expect(e.to_string()))? as u64; + .map_err(|e| VmInternalError::Expect(e.to_string()))? as u64; runtime_cost(ClarityCostFunction::NftOwner, env, asset_size)?; if !expected_asset_type.admits(env.epoch(), &asset)? { @@ -934,7 +934,7 @@ pub fn special_get_owner_v205( expected_asset_type, ) { Ok(owner) => Ok(Value::some(Value::Principal(owner)).map_err(|_| { - InterpreterError::Expect("Principal should always fit in optional.".into()) + VmInternalError::Expect("Principal should always fit in optional.".into()) })?), Err(Error::Runtime(RuntimeErrorType::NoSuchToken, _)) => Ok(Value::none()), Err(e) => Err(e), @@ -1139,7 +1139,7 @@ pub fn special_burn_asset_v205( let asset_size = asset .serialized_size() - .map_err(|e| InterpreterError::Expect(e.to_string()))? as u64; + .map_err(|e| VmInternalError::Expect(e.to_string()))? as u64; runtime_cost(ClarityCostFunction::NftBurn, env, asset_size)?; if !expected_asset_type.admits(env.epoch(), &asset)? { diff --git a/clarity/src/vm/functions/conversions.rs b/clarity/src/vm/functions/conversions.rs index 319e1d368e..5f3e803362 100644 --- a/clarity/src/vm/functions/conversions.rs +++ b/clarity/src/vm/functions/conversions.rs @@ -19,7 +19,7 @@ use clarity_types::types::serialization::SerializationError; use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::runtime_cost; use crate::vm::errors::{ - check_argument_count, CheckErrorKind, InterpreterError, InterpreterResult as Result, + check_argument_count, CheckErrorKind, InterpreterResult as Result, VmInternalError, }; use crate::vm::representations::SymbolicExpression; use crate::vm::types::signatures::TO_ASCII_MAX_BUFF; @@ -55,12 +55,12 @@ pub fn buff_to_int_generic( Value::Sequence(SequenceData::Buffer(ref sequence_data)) => { if sequence_data.len()? > BufferLength::try_from(16_u32) - .map_err(|_| InterpreterError::Expect("Failed to construct".into()))? + .map_err(|_| VmInternalError::Expect("Failed to construct".into()))? { Err(CheckErrorKind::TypeValueError( Box::new(SequenceType(BufferType( BufferLength::try_from(16_u32) - .map_err(|_| InterpreterError::Expect("Failed to construct".into()))?, + .map_err(|_| VmInternalError::Expect("Failed to construct".into()))?, ))), Box::new(value), ) @@ -86,7 +86,7 @@ pub fn buff_to_int_generic( _ => Err(CheckErrorKind::TypeValueError( Box::new(SequenceType(BufferType( BufferLength::try_from(16_u32) - .map_err(|_| InterpreterError::Expect("Failed to construct".into()))?, + .map_err(|_| VmInternalError::Expect("Failed to construct".into()))?, ))), Box::new(value), ) @@ -196,13 +196,13 @@ pub fn native_int_to_string_generic( Value::Int(ref int_value) => { let as_string = int_value.to_string(); Ok(bytes_to_value_fn(as_string.into()).map_err(|_| { - InterpreterError::Expect("Unexpected error converting Int to string.".into()) + VmInternalError::Expect("Unexpected error converting Int to string.".into()) })?) } Value::UInt(ref uint_value) => { let as_string = uint_value.to_string(); Ok(bytes_to_value_fn(as_string.into()).map_err(|_| { - InterpreterError::Expect("Unexpected error converting UInt to string.".into()) + VmInternalError::Expect("Unexpected error converting UInt to string.".into()) })?) } _ => Err(CheckErrorKind::UnionTypeValueError( @@ -227,7 +227,7 @@ pub fn native_int_to_utf8(value: Value) -> Result { /// This should only fail due to system errors, not conversion failures fn convert_string_to_ascii_ok(s: String) -> Result { let ascii_value = Value::string_ascii_from_bytes(s.into_bytes()).map_err(|_| { - InterpreterError::Expect("Unexpected error converting string to ASCII".into()) + VmInternalError::Expect("Unexpected error converting string to ASCII".into()) })?; Value::okay(ascii_value) } @@ -293,7 +293,7 @@ pub fn to_consensus_buff(value: Value) -> Result { let mut clar_buff_serialized = vec![]; value .serialize_write(&mut clar_buff_serialized) - .map_err(|_| InterpreterError::Expect("FATAL: failed to serialize to vec".into()))?; + .map_err(|_| VmInternalError::Expect("FATAL: failed to serialize to vec".into()))?; let clar_buff_serialized = match Value::buff_from(clar_buff_serialized) { Ok(x) => x, diff --git a/clarity/src/vm/functions/crypto.rs b/clarity/src/vm/functions/crypto.rs index 4879b59cf7..d52ff19dde 100644 --- a/clarity/src/vm/functions/crypto.rs +++ b/clarity/src/vm/functions/crypto.rs @@ -24,7 +24,7 @@ use stacks_common::util::secp256k1::{secp256k1_recover, secp256k1_verify, Secp25 use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::runtime_cost; use crate::vm::errors::{ - check_argument_count, CheckErrorKind, InterpreterError, InterpreterResult as Result, + check_argument_count, CheckErrorKind, InterpreterResult as Result, VmInternalError, }; use crate::vm::representations::SymbolicExpression; use crate::vm::types::{BuffData, SequenceData, TypeSignature, Value, BUFF_32, BUFF_33, BUFF_65}; @@ -67,7 +67,7 @@ fn pubkey_to_address_v1(pub_key: Secp256k1PublicKey) -> Result { 1, &vec![pub_key], ) - .ok_or_else(|| InterpreterError::Expect("Failed to create address from pubkey".into()).into()) + .ok_or_else(|| VmInternalError::Expect("Failed to create address from pubkey".into()).into()) } // Note: Clarity1 had a bug in how the address is computed (issues/2619). @@ -84,7 +84,7 @@ fn pubkey_to_address_v2(pub_key: Secp256k1PublicKey, is_mainnet: bool) -> Result 1, &vec![pub_key], ) - .ok_or_else(|| InterpreterError::Expect("Failed to create address from pubkey".into()).into()) + .ok_or_else(|| VmInternalError::Expect("Failed to create address from pubkey".into()).into()) } pub fn special_principal_of( @@ -127,7 +127,7 @@ pub fn special_principal_of( }; let principal = addr.into(); Ok(Value::okay(Value::Principal(principal)) - .map_err(|_| InterpreterError::Expect("Failed to construct ok".into()))?) + .map_err(|_| VmInternalError::Expect("Failed to construct ok".into()))?) } else { Ok(Value::err_uint(1)) } @@ -190,9 +190,9 @@ pub fn special_secp256k1_recover( { Ok(pubkey) => Ok(Value::okay( Value::buff_from(pubkey.to_vec()) - .map_err(|_| InterpreterError::Expect("Failed to construct buff".into()))?, + .map_err(|_| VmInternalError::Expect("Failed to construct buff".into()))?, ) - .map_err(|_| InterpreterError::Expect("Failed to construct ok".into()))?), + .map_err(|_| VmInternalError::Expect("Failed to construct ok".into()))?), _ => Ok(Value::err_uint(1)), } } diff --git a/clarity/src/vm/functions/database.rs b/clarity/src/vm/functions/database.rs index bf4e39f425..38524da120 100644 --- a/clarity/src/vm/functions/database.rs +++ b/clarity/src/vm/functions/database.rs @@ -22,8 +22,8 @@ use crate::vm::callables::DefineType; use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::{constants as cost_constants, runtime_cost, CostTracker, MemoryConsumer}; use crate::vm::errors::{ - check_argument_count, check_arguments_at_least, CheckErrorKind, InterpreterError, - InterpreterResult as Result, RuntimeErrorType, + check_argument_count, check_arguments_at_least, CheckErrorKind, InterpreterResult as Result, + RuntimeErrorType, VmInternalError, }; use crate::vm::representations::{SymbolicExpression, SymbolicExpressionType}; use crate::vm::types::{ @@ -963,7 +963,7 @@ pub fn special_get_burn_block_info( env.epoch(), ) .map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "FATAL: could not convert address list to Value".into(), ) })?, @@ -971,12 +971,12 @@ pub fn special_get_burn_block_info( ("payout".into(), Value::UInt(payout)), ]) .map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "FATAL: failed to build pox addrs and payout tuple".into(), ) })?, )) - .map_err(|_| InterpreterError::Expect("FATAL: could not build Some(..)".into()))?), + .map_err(|_| VmInternalError::Expect("FATAL: could not build Some(..)".into()))?), None => Ok(Value::none()), } } diff --git a/clarity/src/vm/functions/mod.rs b/clarity/src/vm/functions/mod.rs index 48e0ff3651..b27e6384fd 100644 --- a/clarity/src/vm/functions/mod.rs +++ b/clarity/src/vm/functions/mod.rs @@ -65,7 +65,7 @@ macro_rules! switch_on_global_epoch { }; } -use super::errors::InterpreterError; +use super::errors::VmInternalError; use crate::vm::ClarityVersion; mod arithmetic; @@ -610,7 +610,7 @@ fn special_print( context: &LocalContext, ) -> Result { let arg = args.first().ok_or_else(|| { - InterpreterError::BadSymbolicRepresentation("Print should have an argument".into()) + VmInternalError::BadSymbolicRepresentation("Print should have an argument".into()) })?; let input = eval(arg, env, context)?; @@ -777,7 +777,7 @@ fn special_let( last_result.replace(body_result); } // last_result should always be Some(...), because of the arg len check above. - last_result.ok_or_else(|| InterpreterError::Expect("Failed to get let result".into()).into()) + last_result.ok_or_else(|| VmInternalError::Expect("Failed to get let result".into()).into()) }) } diff --git a/clarity/src/vm/functions/options.rs b/clarity/src/vm/functions/options.rs index 50774053a4..96d4979334 100644 --- a/clarity/src/vm/functions/options.rs +++ b/clarity/src/vm/functions/options.rs @@ -18,8 +18,8 @@ use crate::vm::contexts::{Environment, LocalContext}; use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::{runtime_cost, CostTracker, MemoryConsumer}; use crate::vm::errors::{ - check_arguments_at_least, CheckErrorKind, EarlyReturnError, InterpreterError, - InterpreterResult as Result, RuntimeErrorType, + check_arguments_at_least, CheckErrorKind, EarlyReturnError, InterpreterResult as Result, + RuntimeErrorType, VmInternalError, }; use crate::vm::types::{CallableData, OptionalData, ResponseData, TypeSignature, Value}; use crate::vm::Value::CallableContract; @@ -97,7 +97,7 @@ pub fn native_try_ret(input: Value) -> Result { Ok(*data.data) } else { let short_return_val = Value::error(*data.data).map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "BUG: Failed to construct new response type from old response type".into(), ) })?; diff --git a/clarity/src/vm/functions/principals.rs b/clarity/src/vm/functions/principals.rs index a8fdf739b7..55098aa251 100644 --- a/clarity/src/vm/functions/principals.rs +++ b/clarity/src/vm/functions/principals.rs @@ -8,7 +8,7 @@ use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::runtime_cost; use crate::vm::errors::{ check_argument_count, check_arguments_at_least, check_arguments_at_most, CheckErrorKind, - InterpreterError, InterpreterResult as Result, + InterpreterResult as Result, VmInternalError, }; use crate::vm::representations::{ SymbolicExpression, CONTRACT_MAX_NAME_LENGTH, CONTRACT_MIN_NAME_LENGTH, @@ -102,7 +102,7 @@ fn create_principal_destruct_tuple( }), ), ]) - .map_err(|_| InterpreterError::Expect("FAIL: Failed to initialize tuple.".into()))?, + .map_err(|_| VmInternalError::Expect("FAIL: Failed to initialize tuple.".into()))?, )) } @@ -116,10 +116,10 @@ fn create_principal_true_error_response(error_int: PrincipalConstructErrorCode) ("error_code".into(), Value::UInt(error_int as u128)), ("value".into(), Value::none()), ]) - .map_err(|_| InterpreterError::Expect("FAIL: Failed to initialize tuple.".into()))?, + .map_err(|_| VmInternalError::Expect("FAIL: Failed to initialize tuple.".into()))?, )) .map_err(|_| { - InterpreterError::Expect("FAIL: Failed to initialize (err ..) response".into()).into() + VmInternalError::Expect("FAIL: Failed to initialize (err ..) response".into()).into() }) } @@ -138,14 +138,14 @@ fn create_principal_value_error_response( ( "value".into(), Value::some(value).map_err(|_| { - InterpreterError::Expect("Unexpected problem creating Value.".into()) + VmInternalError::Expect("Unexpected problem creating Value.".into()) })?, ), ]) - .map_err(|_| InterpreterError::Expect("FAIL: Failed to initialize tuple.".into()))?, + .map_err(|_| VmInternalError::Expect("FAIL: Failed to initialize tuple.".into()))?, )) .map_err(|_| { - InterpreterError::Expect("FAIL: Failed to initialize (err ..) response".into()).into() + VmInternalError::Expect("FAIL: Failed to initialize (err ..) response".into()).into() }) } @@ -310,7 +310,7 @@ pub fn special_principal_construct( // it here at runtime. If it's not valid, then it warrants this function evaluating to // (err ..). let name_string = String::from_utf8(name_bytes.data).map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "FAIL: could not convert bytes of type (string-ascii 40) back to a UTF-8 string" .into(), ) @@ -337,7 +337,7 @@ pub fn special_principal_construct( if version_byte_is_valid { Ok(Value::okay(principal).map_err(|_| { - InterpreterError::Expect("FAIL: failed to build an (ok ..) response".into()) + VmInternalError::Expect("FAIL: failed to build an (ok ..) response".into()) })?) } else { create_principal_value_error_response(PrincipalConstructErrorCode::VERSION_BYTE, principal) diff --git a/clarity/src/vm/functions/tuples.rs b/clarity/src/vm/functions/tuples.rs index bc5778ebea..325bef9d45 100644 --- a/clarity/src/vm/functions/tuples.rs +++ b/clarity/src/vm/functions/tuples.rs @@ -16,8 +16,8 @@ use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::runtime_cost; use crate::vm::errors::{ - check_argument_count, check_arguments_at_least, CheckErrorKind, InterpreterError, - InterpreterResult as Result, SyntaxBindingErrorType, + check_argument_count, check_arguments_at_least, CheckErrorKind, InterpreterResult as Result, + SyntaxBindingErrorType, VmInternalError, }; use crate::vm::representations::SymbolicExpression; use crate::vm::types::{TupleData, TypeSignature, Value}; @@ -60,7 +60,7 @@ pub fn tuple_get( if let Value::Tuple(tuple_data) = *data { runtime_cost(ClarityCostFunction::TupleGet, env, tuple_data.len())?; Ok(Value::some(tuple_data.get_owned(arg_name)?).map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "Tuple contents should *always* fit in a some wrapper".into(), ) })?) diff --git a/clarity/src/vm/mod.rs b/clarity/src/vm/mod.rs index 0e38f511e9..90bd422976 100644 --- a/clarity/src/vm/mod.rs +++ b/clarity/src/vm/mod.rs @@ -73,7 +73,7 @@ use crate::vm::costs::{ // publish the non-generic StacksEpoch form for use throughout module pub use crate::vm::database::clarity_db::StacksEpoch; use crate::vm::errors::{ - CheckErrorKind, Error, InterpreterError, InterpreterResult as Result, RuntimeErrorType, + CheckErrorKind, Error, InterpreterResult as Result, RuntimeErrorType, VmInternalError, }; use crate::vm::events::StacksTransactionEvent; use crate::vm::functions::define::DefineResult; @@ -164,10 +164,10 @@ pub trait EvalHook { fn lookup_variable(name: &str, context: &LocalContext, env: &mut Environment) -> Result { if name.starts_with(char::is_numeric) || name.starts_with('\'') { - Err(InterpreterError::BadSymbolicRepresentation(format!( - "Unexpected variable name: {name}" - )) - .into()) + Err( + VmInternalError::BadSymbolicRepresentation(format!("Unexpected variable name: {name}")) + .into(), + ) } else if let Some(value) = variables::lookup_reserved_variable(name, context, env)? { Ok(value) } else { @@ -292,7 +292,7 @@ pub fn apply( .and_then(|_| function.apply(evaluated_args, env)) } CallableType::UserFunction(function) => function.apply(&evaluated_args, env), - _ => return Err(InterpreterError::Expect("Should be unreachable.".into()).into()), + _ => return Err(VmInternalError::Expect("Should be unreachable.".into()).into()), }; add_stack_trace(&mut resp, env); env.drop_memory(used_memory)?; @@ -350,7 +350,7 @@ pub fn eval( apply(&f, rest, env, context) } TraitReference(_, _) | Field(_) => { - return Err(InterpreterError::BadSymbolicRepresentation( + return Err(VmInternalError::BadSymbolicRepresentation( "Unexpected trait reference".into(), ) .into()) @@ -414,7 +414,7 @@ pub fn eval_all( contract_context.persisted_names.insert(name.clone()); global_context.add_memory(value_type.type_size() - .map_err(|_| InterpreterError::Expect("Type size should be realizable".into()))? as u64)?; + .map_err(|_| VmInternalError::Expect("Type size should be realizable".into()))? as u64)?; global_context.add_memory(value.size()? as u64)?; @@ -430,9 +430,9 @@ pub fn eval_all( contract_context.persisted_names.insert(name.clone()); global_context.add_memory(key_type.type_size() - .map_err(|_| InterpreterError::Expect("Type size should be realizable".into()))? as u64)?; + .map_err(|_| VmInternalError::Expect("Type size should be realizable".into()))? as u64)?; global_context.add_memory(value_type.type_size() - .map_err(|_| InterpreterError::Expect("Type size should be realizable".into()))? as u64)?; + .map_err(|_| VmInternalError::Expect("Type size should be realizable".into()))? as u64)?; let data_type = global_context.database.create_map(&contract_context.contract_identifier, &name, key_type, value_type)?; @@ -443,7 +443,7 @@ pub fn eval_all( contract_context.persisted_names.insert(name.clone()); global_context.add_memory(TypeSignature::UIntType.type_size() - .map_err(|_| InterpreterError::Expect("Type size should be realizable".into()))? as u64)?; + .map_err(|_| VmInternalError::Expect("Type size should be realizable".into()))? as u64)?; let data_type = global_context.database.create_fungible_token(&contract_context.contract_identifier, &name, &total_supply)?; @@ -454,7 +454,7 @@ pub fn eval_all( contract_context.persisted_names.insert(name.clone()); global_context.add_memory(asset_type.type_size() - .map_err(|_| InterpreterError::Expect("Type size should be realizable".into()))? as u64)?; + .map_err(|_| VmInternalError::Expect("Type size should be realizable".into()))? as u64)?; let data_type = global_context.database.create_non_fungible_token(&contract_context.contract_identifier, &name, &asset_type)?; diff --git a/clarity/src/vm/types/serialization.rs b/clarity/src/vm/types/serialization.rs index 16e62f2409..b83f752e29 100644 --- a/clarity/src/vm/types/serialization.rs +++ b/clarity/src/vm/types/serialization.rs @@ -22,7 +22,7 @@ pub use clarity_types::types::serialization::{ use stacks_common::util::hash::{hex_bytes, to_hex}; use crate::vm::database::{ClarityDeserializable, ClaritySerializable}; -use crate::vm::errors::{Error as ClarityError, InterpreterError}; +use crate::vm::errors::{Error as ClarityError, VmInternalError}; impl ClaritySerializable for u32 { fn serialize(&self) -> String { @@ -33,11 +33,11 @@ impl ClaritySerializable for u32 { impl ClarityDeserializable for u32 { fn deserialize(input: &str) -> Result { let bytes = hex_bytes(input).map_err(|_| { - InterpreterError::Expect("u32 deserialization: failed decoding bytes.".into()) + VmInternalError::Expect("u32 deserialization: failed decoding bytes.".into()) })?; assert_eq!(bytes.len(), 4); Ok(u32::from_be_bytes(bytes[0..4].try_into().map_err( - |_| InterpreterError::Expect("u32 deserialization: failed reading.".into()), + |_| VmInternalError::Expect("u32 deserialization: failed reading.".into()), )?)) } } diff --git a/clarity/src/vm/variables.rs b/clarity/src/vm/variables.rs index cb84336dc9..aa4de45162 100644 --- a/clarity/src/vm/variables.rs +++ b/clarity/src/vm/variables.rs @@ -17,7 +17,7 @@ use clarity_types::types::PrincipalData; use stacks_common::types::StacksEpochId; -use super::errors::InterpreterError; +use super::errors::VmInternalError; use crate::vm::contexts::{Environment, LocalContext}; use crate::vm::costs::cost_functions::ClarityCostFunction; use crate::vm::costs::runtime_cost; @@ -75,7 +75,7 @@ pub fn lookup_reserved_variable( let sponsor = match env.sponsor.clone() { None => Value::none(), Some(p) => Value::some(Value::Principal(p)).map_err(|_| { - InterpreterError::Expect( + VmInternalError::Expect( "ERROR: principal should be a valid Clarity object".into(), ) })?, diff --git a/stackslib/src/chainstate/stacks/db/transactions.rs b/stackslib/src/chainstate/stacks/db/transactions.rs index d3d3aaee02..c6bf37ccc7 100644 --- a/stackslib/src/chainstate/stacks/db/transactions.rs +++ b/stackslib/src/chainstate/stacks/db/transactions.rs @@ -49,7 +49,7 @@ impl TryFrom for HashableClarityValue { fn try_from(value: Value) -> Result { // check that serialization _will_ be successful when hashed let _bytes = value.serialize_to_vec().map_err(|_| { - InterpreterError::Interpreter(clarity::vm::errors::InterpreterError::Expect( + InterpreterError::Internal(clarity::vm::errors::VmInternalError::Expect( "Failed to serialize asset in NFT during post-condition checks".into(), )) })?; diff --git a/stackslib/src/clarity_vm/database/ephemeral.rs b/stackslib/src/clarity_vm/database/ephemeral.rs index eb6ac7ce53..41ea4057a5 100644 --- a/stackslib/src/clarity_vm/database/ephemeral.rs +++ b/stackslib/src/clarity_vm/database/ephemeral.rs @@ -21,7 +21,7 @@ use clarity::vm::database::sqlite::{ sqlite_insert_metadata, }; use clarity::vm::database::{ClarityBackingStore, SpecialCaseHandler, SqliteConnection}; -use clarity::vm::errors::{InterpreterError, InterpreterResult, RuntimeErrorType}; +use clarity::vm::errors::{InterpreterResult, RuntimeErrorType, VmInternalError}; use clarity::vm::types::QualifiedContractIdentifier; use rusqlite; use rusqlite::Connection; @@ -67,7 +67,7 @@ impl ClarityMarfStoreTransaction for EphemeralMarfStore<'_> { /// disappear when this instance is dropped /// /// Returns Ok(()) on success - /// Returns Err(InterpreterError(..)) on sqlite failure + /// Returns Err(VmInternalError(..)) on sqlite failure fn commit_metadata_for_trie(&mut self, target: &StacksBlockId) -> InterpreterResult<()> { if let Some(tip) = self.ephemeral_marf.get_open_chain_tip() { self.teardown_views(); @@ -85,7 +85,7 @@ impl ClarityMarfStoreTransaction for EphemeralMarfStore<'_> { /// unless the RAM-only sqlite DB is experiencing problems (which is probably not recoverable). /// /// Returns Ok(()) on success - /// Returns Err(InterpreterError(..)) on sqlite failure + /// Returns Err(VmInternalError(..)) on sqlite failure fn drop_metadata_for_trie(&mut self, target: &StacksBlockId) -> InterpreterResult<()> { self.teardown_views(); let res = SqliteConnection::drop_metadata(self.ephemeral_marf.sqlite_tx(), target); @@ -111,7 +111,7 @@ impl ClarityMarfStoreTransaction for EphemeralMarfStore<'_> { /// transaction, so no disk I/O will be performed. /// /// Returns Ok(()) on success - /// Returns Err(InterpreterError(..)) on sqlite failure + /// Returns Err(VmInternalError(..)) on sqlite failure fn drop_unconfirmed(mut self) -> InterpreterResult<()> { if let Some(tip) = self.ephemeral_marf.get_open_chain_tip().cloned() { debug!("Drop unconfirmed MARF trie {}", tip); @@ -127,13 +127,13 @@ impl ClarityMarfStoreTransaction for EphemeralMarfStore<'_> { /// motions just in case any errors would be reported. /// /// Returns Ok(()) on success - /// Returns Err(InterpreterError(..)) on sqlite failure + /// Returns Err(VmInternalError(..)) on sqlite failure fn commit_to_processed_block(mut self, target: &StacksBlockId) -> InterpreterResult<()> { if self.ephemeral_marf.get_open_chain_tip().is_some() { self.commit_metadata_for_trie(target)?; let _ = self.ephemeral_marf.commit_to(target).map_err(|e| { error!("Failed to commit to ephemeral MARF block {target}: {e:?}",); - InterpreterError::Expect("Failed to commit to MARF block".into()) + VmInternalError::Expect("Failed to commit to MARF block".into()) })?; } Ok(()) @@ -145,7 +145,7 @@ impl ClarityMarfStoreTransaction for EphemeralMarfStore<'_> { /// motions just in case any errors would be reported. /// /// Returns Ok(()) on success - /// Returns Err(InterpreterError(..)) on sqlite failure + /// Returns Err(VmInternalError(..)) on sqlite failure fn commit_to_mined_block(mut self, target: &StacksBlockId) -> InterpreterResult<()> { if let Some(tip) = self.ephemeral_marf.get_open_chain_tip().cloned() { // rollback the side_store @@ -156,7 +156,7 @@ impl ClarityMarfStoreTransaction for EphemeralMarfStore<'_> { self.drop_metadata_for_trie(&tip)?; let _ = self.ephemeral_marf.commit_mined(target).map_err(|e| { error!("Failed to commit to mined MARF block {target}: {e:?}",); - InterpreterError::Expect("Failed to commit to MARF block".into()) + VmInternalError::Expect("Failed to commit to MARF block".into()) })?; } Ok(()) @@ -246,11 +246,11 @@ impl<'a> EphemeralMarfStore<'a> { } /// Test to see if a given tip is in the ephemeral MARF - fn is_ephemeral_tip(&mut self, tip: &StacksBlockId) -> Result { + fn is_ephemeral_tip(&mut self, tip: &StacksBlockId) -> Result { match self.ephemeral_marf.get_root_hash_at(tip) { Ok(_) => Ok(true), Err(Error::NotFoundError) => Ok(false), - Err(e) => Err(InterpreterError::MarfFailure(e.to_string())), + Err(e) => Err(VmInternalError::MarfFailure(e.to_string())), } } @@ -321,7 +321,7 @@ impl<'a> EphemeralMarfStore<'a> { trace!("Ephemeral MarfedKV get not found",); Ok(None) } - Err(e) => Err(InterpreterError::Expect(format!( + Err(e) => Err(VmInternalError::Expect(format!( "ERROR: Unexpected MARF failure: {e:?}" )) .into()), @@ -334,7 +334,7 @@ impl<'a> EphemeralMarfStore<'a> { /// /// Returns Ok(Some(V)) if the key was mapped in eiher MARF /// Returns Ok(None) if the key was not mapped in either MARF - /// Returns Err(InterpreterError(..)) on failure. + /// Returns Err(VmInternalError(..)) on failure. fn get_with_fn( &mut self, key: Key, @@ -441,7 +441,7 @@ impl ClarityBackingStore for EphemeralMarfStore<'_> { let side_key = marf_value.to_hex(); let data = SqliteConnection::get(ephemeral_marf.sqlite_conn(), &side_key)? .ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {side_key}", )) })?; @@ -477,7 +477,7 @@ impl ClarityBackingStore for EphemeralMarfStore<'_> { ); let data = SqliteConnection::get(ephemeral_marf.sqlite_conn(), &side_key)? .ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: Ephemeral MARF contained value_hash not found in side storage: {}", side_key )) @@ -509,7 +509,7 @@ impl ClarityBackingStore for EphemeralMarfStore<'_> { let side_key = marf_value.to_hex(); let data = SqliteConnection::get(ephemeral_marf.sqlite_conn(), &side_key)? .ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {}", side_key )) @@ -544,7 +544,7 @@ impl ClarityBackingStore for EphemeralMarfStore<'_> { let side_key = marf_value.to_hex(); let data = SqliteConnection::get(ephemeral_marf.sqlite_conn(), &side_key)? .ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {}", side_key )) diff --git a/stackslib/src/clarity_vm/database/marf.rs b/stackslib/src/clarity_vm/database/marf.rs index c5832fda6a..18f2710622 100644 --- a/stackslib/src/clarity_vm/database/marf.rs +++ b/stackslib/src/clarity_vm/database/marf.rs @@ -25,7 +25,7 @@ use clarity::vm::database::sqlite::{ }; use clarity::vm::database::{ClarityBackingStore, SpecialCaseHandler, SqliteConnection}; use clarity::vm::errors::{ - IncomparableError, InterpreterError, InterpreterResult, RuntimeErrorType, + IncomparableError, InterpreterResult, RuntimeErrorType, VmInternalError, }; use clarity::vm::types::QualifiedContractIdentifier; use rusqlite; @@ -70,13 +70,12 @@ impl MarfedKV { ) -> InterpreterResult> { let mut path = PathBuf::from(path_str); - std::fs::create_dir_all(&path) - .map_err(|_| InterpreterError::FailedToCreateDataDirectory)?; + std::fs::create_dir_all(&path).map_err(|_| VmInternalError::FailedToCreateDataDirectory)?; path.push("marf.sqlite"); let marf_path = path .to_str() - .ok_or_else(|| InterpreterError::BadFileName)? + .ok_or_else(|| VmInternalError::BadFileName)? .to_string(); let mut marf_opts = marf_opts.unwrap_or(MARFOpenOpts::default()); @@ -84,10 +83,10 @@ impl MarfedKV { let mut marf: MARF = if unconfirmed { MARF::from_path_unconfirmed(&marf_path, marf_opts) - .map_err(|err| InterpreterError::MarfFailure(err.to_string()))? + .map_err(|err| VmInternalError::MarfFailure(err.to_string()))? } else { MARF::from_path(&marf_path, marf_opts) - .map_err(|err| InterpreterError::MarfFailure(err.to_string()))? + .map_err(|err| VmInternalError::MarfFailure(err.to_string()))? }; if SqliteConnection::check_schema(marf.sqlite_conn()).is_ok() { @@ -97,11 +96,11 @@ impl MarfedKV { let tx = marf .storage_tx() - .map_err(|err| InterpreterError::DBError(err.to_string()))?; + .map_err(|err| VmInternalError::DBError(err.to_string()))?; SqliteConnection::initialize_conn(&tx)?; tx.commit() - .map_err(|err| InterpreterError::SqliteError(IncomparableError { err }))?; + .map_err(|err| VmInternalError::SqliteError(IncomparableError { err }))?; Ok(marf) } @@ -207,7 +206,7 @@ impl MarfedKV { "Failed to open read only connection at {}: {:?}", at_block, &e ); - InterpreterError::MarfFailure(Error::NotFoundError.to_string()) + VmInternalError::MarfFailure(Error::NotFoundError.to_string()) })?; at_block.clone() } else { @@ -297,7 +296,7 @@ impl MarfedKV { "Failed to open read only connection at {}: {:?}", &base_tip, &e ); - InterpreterError::MarfFailure(Error::NotFoundError.to_string()) + VmInternalError::MarfFailure(Error::NotFoundError.to_string()) })?; // set up ephemeral MARF @@ -306,17 +305,17 @@ impl MarfedKV { MARFOpenOpts::new(TrieHashCalculationMode::Deferred, "noop", false), ) .map_err(|e| { - InterpreterError::Expect(format!("Failed to instantiate ephemeral MARF: {:?}", &e)) + VmInternalError::Expect(format!("Failed to instantiate ephemeral MARF: {:?}", &e)) })?; let mut ephemeral_marf = MARF::from_storage(ephemeral_marf_storage); let tx = ephemeral_marf .storage_tx() - .map_err(|err| InterpreterError::DBError(err.to_string()))?; + .map_err(|err| VmInternalError::DBError(err.to_string()))?; SqliteConnection::initialize_conn(&tx)?; tx.commit() - .map_err(|err| InterpreterError::SqliteError(IncomparableError { err }))?; + .map_err(|err| VmInternalError::SqliteError(IncomparableError { err }))?; self.ephemeral_marf = Some(ephemeral_marf); @@ -333,7 +332,7 @@ impl MarfedKV { // attach the disk-backed MARF to the ephemeral MARF EphemeralMarfStore::attach_read_only_marf(&ephemeral_marf, &read_only_marf).map_err( |e| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "Failed to attach read-only MARF to ephemeral MARF: {:?}", &e )) @@ -341,19 +340,19 @@ impl MarfedKV { )?; let mut tx = ephemeral_marf.begin_tx().map_err(|e| { - InterpreterError::Expect(format!("Failed to open ephemeral MARF tx: {:?}", &e)) + VmInternalError::Expect(format!("Failed to open ephemeral MARF tx: {:?}", &e)) })?; tx.begin(&StacksBlockId::sentinel(), ephemeral_next) .map_err(|e| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "Failed to begin first ephemeral MARF block: {:?}", &e )) })?; let ephemeral_marf_store = EphemeralMarfStore::new(read_only_marf, tx).map_err(|e| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "Failed to instantiate ephemeral MARF store: {:?}", &e )) @@ -406,7 +405,7 @@ impl ClarityMarfStoreTransaction for PersistentWritableMarfStore<'_> { /// metadata rows with `self.chain_tip` as their block identifier to have `target` instead. /// /// Returns Ok(()) on success - /// Returns Err(InterpreterError(..)) on sqlite failure + /// Returns Err(VmInternalError(..)) on sqlite failure fn commit_metadata_for_trie(&mut self, target: &StacksBlockId) -> InterpreterResult<()> { SqliteConnection::commit_metadata_to(self.marf.sqlite_tx(), &self.chain_tip, target) } @@ -415,7 +414,7 @@ impl ClarityMarfStoreTransaction for PersistentWritableMarfStore<'_> { /// as their block identifier. /// /// Returns Ok(()) on success - /// Returns Err(InterpreterError(..)) on sqlite failure + /// Returns Err(VmInternalError(..)) on sqlite failure fn drop_metadata_for_trie(&mut self, target: &StacksBlockId) -> InterpreterResult<()> { SqliteConnection::drop_metadata(self.marf.sqlite_tx(), target) } @@ -438,7 +437,7 @@ impl ClarityMarfStoreTransaction for PersistentWritableMarfStore<'_> { /// also any unconfirmed trie data from the sqlite DB as well as its associated metadata. /// /// Returns Ok(()) on success - /// Returns Err(InterpreterError(..)) on sqlite failure + /// Returns Err(VmInternalError(..)) on sqlite failure fn drop_unconfirmed(mut self) -> InterpreterResult<()> { let chain_tip = self.chain_tip.clone(); debug!("Drop unconfirmed MARF trie {}", &chain_tip); @@ -452,13 +451,13 @@ impl ClarityMarfStoreTransaction for PersistentWritableMarfStore<'_> { /// drops this MARF store. /// /// Returns Ok(()) on success - /// Returns Err(InterpreterError(..)) on sqlite failure + /// Returns Err(VmInternalError(..)) on sqlite failure fn commit_to_processed_block(mut self, target: &StacksBlockId) -> InterpreterResult<()> { debug!("commit_to({})", target); self.commit_metadata_for_trie(target)?; let _ = self.marf.commit_to(target).map_err(|e| { error!("Failed to commit to MARF block {target}: {e:?}"); - InterpreterError::Expect("Failed to commit to MARF block".into()) + VmInternalError::Expect("Failed to commit to MARF block".into()) })?; Ok(()) } @@ -468,7 +467,7 @@ impl ClarityMarfStoreTransaction for PersistentWritableMarfStore<'_> { /// the transaction and drops this MARF store. /// /// Returns Ok(()) on success - /// Returns Err(InterpreterError(..)) on sqlite failure + /// Returns Err(VmInternalError(..)) on sqlite failure fn commit_to_mined_block(mut self, target: &StacksBlockId) -> InterpreterResult<()> { debug!("commit_mined_block: ({}->{})", &self.chain_tip, target); // rollback the side_store @@ -480,7 +479,7 @@ impl ClarityMarfStoreTransaction for PersistentWritableMarfStore<'_> { self.drop_metadata_for_trie(&chain_tip)?; let _ = self.marf.commit_mined(target).map_err(|e| { error!("Failed to commit to mined MARF block {target}: {e:?}",); - InterpreterError::Expect("Failed to commit to MARF block".into()) + VmInternalError::Expect("Failed to commit to MARF block".into()) })?; Ok(()) } @@ -636,12 +635,12 @@ impl ClarityBackingStore for ReadOnlyMarfStore<'_> { Error::NotFoundError => Ok(None), _ => Err(e), }) - .map_err(|_| InterpreterError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? + .map_err(|_| VmInternalError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? .map(|(marf_value, proof)| { let side_key = marf_value.to_hex(); let data = SqliteConnection::get(self.get_side_store(), &side_key)?.ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {}", side_key )) @@ -661,12 +660,12 @@ impl ClarityBackingStore for ReadOnlyMarfStore<'_> { Error::NotFoundError => Ok(None), _ => Err(e), }) - .map_err(|_| InterpreterError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? + .map_err(|_| VmInternalError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? .map(|(marf_value, proof)| { let side_key = marf_value.to_hex(); let data = SqliteConnection::get(self.get_side_store(), &side_key)?.ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {}", side_key )) @@ -698,11 +697,11 @@ impl ClarityBackingStore for ReadOnlyMarfStore<'_> { Err(e) } }) - .map_err(|_| InterpreterError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? + .map_err(|_| VmInternalError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? .map(|marf_value| { let side_key = marf_value.to_hex(); SqliteConnection::get(self.get_side_store(), &side_key)?.ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {}", side_key )) @@ -727,12 +726,12 @@ impl ClarityBackingStore for ReadOnlyMarfStore<'_> { } _ => Err(e), }) - .map_err(|_| InterpreterError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? + .map_err(|_| VmInternalError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? .map(|marf_value| { let side_key = marf_value.to_hex(); trace!("MarfedKV get side-key for {:?}: {:?}", hash, &side_key); SqliteConnection::get(self.get_side_store(), &side_key)?.ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {}", side_key )) @@ -836,12 +835,12 @@ impl ClarityBackingStore for PersistentWritableMarfStore<'_> { } _ => Err(e), }) - .map_err(|_| InterpreterError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? + .map_err(|_| VmInternalError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? .map(|marf_value| { let side_key = marf_value.to_hex(); trace!("MarfedKV get side-key for {:?}: {:?}", key, &side_key); SqliteConnection::get(self.marf.sqlite_tx(), &side_key)?.ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {}", side_key )) @@ -866,12 +865,12 @@ impl ClarityBackingStore for PersistentWritableMarfStore<'_> { } _ => Err(e), }) - .map_err(|_| InterpreterError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? + .map_err(|_| VmInternalError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? .map(|marf_value| { let side_key = marf_value.to_hex(); trace!("MarfedKV get side-key for {:?}: {:?}", hash, &side_key); SqliteConnection::get(self.marf.sqlite_tx(), &side_key)?.ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {}", side_key )) @@ -888,12 +887,12 @@ impl ClarityBackingStore for PersistentWritableMarfStore<'_> { Error::NotFoundError => Ok(None), _ => Err(e), }) - .map_err(|_| InterpreterError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? + .map_err(|_| VmInternalError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? .map(|(marf_value, proof)| { let side_key = marf_value.to_hex(); let data = SqliteConnection::get(self.marf.sqlite_tx(), &side_key)?.ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {}", side_key )) @@ -913,12 +912,12 @@ impl ClarityBackingStore for PersistentWritableMarfStore<'_> { Error::NotFoundError => Ok(None), _ => Err(e), }) - .map_err(|_| InterpreterError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? + .map_err(|_| VmInternalError::Expect("ERROR: Unexpected MARF Failure on GET".into()))? .map(|(marf_value, proof)| { let side_key = marf_value.to_hex(); let data = SqliteConnection::get(self.marf.sqlite_tx(), &side_key)?.ok_or_else(|| { - InterpreterError::Expect(format!( + VmInternalError::Expect(format!( "ERROR: MARF contained value_hash not found in side storage: {}", side_key )) @@ -1002,7 +1001,7 @@ impl ClarityBackingStore for PersistentWritableMarfStore<'_> { } self.marf .insert_batch(&keys, values) - .map_err(|_| InterpreterError::Expect("ERROR: Unexpected MARF Failure".into()).into()) + .map_err(|_| VmInternalError::Expect("ERROR: Unexpected MARF Failure".into()).into()) } fn get_contract_hash(