diff --git a/clarity/src/vm/clarity.rs b/clarity/src/vm/clarity.rs index 048801ffed..5b9669b54b 100644 --- a/clarity/src/vm/clarity.rs +++ b/clarity/src/vm/clarity.rs @@ -13,13 +13,26 @@ use crate::vm::events::StacksTransactionEvent; use crate::vm::types::{BuffData, PrincipalData, QualifiedContractIdentifier}; use crate::vm::{analysis, ast, ClarityVersion, ContractContext, SymbolicExpression, Value}; +/// Top-level error type for Clarity contract processing, encompassing errors from parsing, +/// type-checking, runtime evaluation, and transaction execution. #[derive(Debug)] -pub enum Error { +pub enum ClarityError { + /// Error during static type-checking or semantic analysis. + /// The `StaticCheckError` wraps the specific type-checking error, including diagnostic details. StaticCheck(StaticCheckError), + /// Error during lexical or syntactic parsing. + /// The `ParseError` wraps the specific parsing error, such as invalid syntax or tokens. Parse(ParseError), + /// Error during runtime evaluation in the virtual machine. + /// The `VmExecutionError` wraps the specific error, such as runtime errors or dynamic type-checking errors. Interpreter(InterpreterError), + /// Transaction is malformed or invalid due to blockchain-level issues. + /// The `String` wraps a human-readable description of the issue, such as incorrect format or invalid signatures. BadTransaction(String), + /// Transaction exceeds the allocated cost budget during execution. + /// The first `ExecutionCost` represents the total consumed cost, and the second represents the budget limit. CostError(ExecutionCost, ExecutionCost), + /// Transaction aborted by a callback (e.g., post-condition check or custom logic). AbortedByCallback { /// What the output value of the transaction would have been. /// This will be a Some for contract-calls, and None for contract initialization txs. @@ -33,85 +46,85 @@ pub enum Error { }, } -impl fmt::Display for Error { +impl fmt::Display for ClarityError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Error::CostError(ref a, ref b) => { + ClarityError::CostError(ref a, ref b) => { write!(f, "Cost Error: {a} cost exceeded budget of {b} cost") } - Error::StaticCheck(ref e) => fmt::Display::fmt(e, f), - Error::Parse(ref e) => fmt::Display::fmt(e, f), - Error::AbortedByCallback { reason, .. } => { + ClarityError::StaticCheck(ref e) => fmt::Display::fmt(e, f), + ClarityError::Parse(ref e) => fmt::Display::fmt(e, f), + ClarityError::AbortedByCallback { reason, .. } => { write!(f, "Post condition aborted transaction: {reason}") } - Error::Interpreter(ref e) => fmt::Display::fmt(e, f), - Error::BadTransaction(ref s) => fmt::Display::fmt(s, f), + ClarityError::Interpreter(ref e) => fmt::Display::fmt(e, f), + ClarityError::BadTransaction(ref s) => fmt::Display::fmt(s, f), } } } -impl std::error::Error for Error { +impl std::error::Error for ClarityError { fn cause(&self) -> Option<&dyn std::error::Error> { match *self { - Error::CostError(ref _a, ref _b) => None, - Error::AbortedByCallback { .. } => None, - Error::StaticCheck(ref e) => Some(e), - Error::Parse(ref e) => Some(e), - Error::Interpreter(ref e) => Some(e), - Error::BadTransaction(ref _s) => None, + ClarityError::CostError(ref _a, ref _b) => None, + ClarityError::AbortedByCallback { .. } => None, + ClarityError::StaticCheck(ref e) => Some(e), + ClarityError::Parse(ref e) => Some(e), + ClarityError::Interpreter(ref e) => Some(e), + ClarityError::BadTransaction(ref _s) => None, } } } -impl From for Error { +impl From for ClarityError { fn from(e: StaticCheckError) -> Self { match *e.err { CheckErrorKind::CostOverflow => { - Error::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) + ClarityError::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) } - CheckErrorKind::CostBalanceExceeded(a, b) => Error::CostError(a, b), + CheckErrorKind::CostBalanceExceeded(a, b) => ClarityError::CostError(a, b), CheckErrorKind::MemoryBalanceExceeded(_a, _b) => { - Error::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) + ClarityError::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) } CheckErrorKind::ExecutionTimeExpired => { - Error::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) + ClarityError::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) } - _ => Error::StaticCheck(e), + _ => ClarityError::StaticCheck(e), } } } -impl From for Error { +impl From for ClarityError { fn from(e: InterpreterError) -> Self { match &e { InterpreterError::Unchecked(CheckErrorKind::CostBalanceExceeded(a, b)) => { - Error::CostError(a.clone(), b.clone()) + ClarityError::CostError(a.clone(), b.clone()) } InterpreterError::Unchecked(CheckErrorKind::CostOverflow) => { - Error::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) + ClarityError::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) } InterpreterError::Unchecked(CheckErrorKind::ExecutionTimeExpired) => { - Error::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) + ClarityError::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) } - _ => Error::Interpreter(e), + _ => ClarityError::Interpreter(e), } } } -impl From for Error { +impl From for ClarityError { fn from(e: ParseError) -> Self { match *e.err { ParseErrors::CostOverflow => { - Error::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) + ClarityError::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) } - ParseErrors::CostBalanceExceeded(a, b) => Error::CostError(a, b), + ParseErrors::CostBalanceExceeded(a, b) => ClarityError::CostError(a, b), ParseErrors::MemoryBalanceExceeded(_a, _b) => { - Error::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) + ClarityError::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) } ParseErrors::ExecutionTimeExpired => { - Error::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) + ClarityError::CostError(ExecutionCost::max_value(), ExecutionCost::max_value()) } - _ => Error::Parse(e), + _ => ClarityError::Parse(e), } } } @@ -210,7 +223,7 @@ pub trait TransactionConnection: ClarityConnection { clarity_version: ClarityVersion, contract_content: &str, ast_rules: ASTRules, - ) -> Result<(ContractAST, ContractAnalysis), Error> { + ) -> Result<(ContractAST, ContractAnalysis), ClarityError> { let epoch_id = self.get_epoch(); self.with_analysis_db(|db, mut cost_track| { @@ -289,12 +302,12 @@ pub trait TransactionConnection: ClarityConnection { to: &PrincipalData, amount: u128, memo: &BuffData, - ) -> Result<(Value, AssetMap, Vec), Error> { + ) -> Result<(Value, AssetMap, Vec), ClarityError> { self.with_abort_callback( |vm_env| { vm_env .stx_transfer(from, to, amount, memo) - .map_err(Error::from) + .map_err(ClarityError::from) }, |_, _| None, ) @@ -316,7 +329,7 @@ pub trait TransactionConnection: ClarityConnection { args: &[Value], abort_call_back: F, max_execution_time: Option, - ) -> Result<(Value, AssetMap, Vec), Error> + ) -> Result<(Value, AssetMap, Vec), ClarityError> where F: FnOnce(&AssetMap, &mut ClarityDatabase) -> Option, { @@ -340,13 +353,13 @@ pub trait TransactionConnection: ClarityConnection { public_function, &expr_args, ) - .map_err(Error::from) + .map_err(ClarityError::from) }, abort_call_back, ) .and_then(|(value, assets_modified, tx_events, reason)| { if let Some(reason) = reason { - Err(Error::AbortedByCallback { + Err(ClarityError::AbortedByCallback { output: Some(Box::new(value)), assets_modified: Box::new(assets_modified), tx_events, @@ -373,7 +386,7 @@ pub trait TransactionConnection: ClarityConnection { sponsor: Option, abort_call_back: F, max_execution_time: Option, - ) -> Result<(AssetMap, Vec), Error> + ) -> Result<(AssetMap, Vec), ClarityError> where F: FnOnce(&AssetMap, &mut ClarityDatabase) -> Option, { @@ -392,12 +405,12 @@ pub trait TransactionConnection: ClarityConnection { contract_str, sponsor, ) - .map_err(Error::from) + .map_err(ClarityError::from) }, abort_call_back, )?; if let Some(reason) = reason { - Err(Error::AbortedByCallback { + Err(ClarityError::AbortedByCallback { output: None, assets_modified: Box::new(assets_modified), tx_events, diff --git a/stackslib/src/chainstate/stacks/boot/contract_tests.rs b/stackslib/src/chainstate/stacks/boot/contract_tests.rs index af33599ccb..ad85e767a3 100644 --- a/stackslib/src/chainstate/stacks/boot/contract_tests.rs +++ b/stackslib/src/chainstate/stacks/boot/contract_tests.rs @@ -32,7 +32,7 @@ use crate::chainstate::stacks::boot::{ use crate::chainstate::stacks::index::ClarityMarfTrieId; use crate::chainstate::stacks::{C32_ADDRESS_VERSION_TESTNET_SINGLESIG, *}; use crate::clarity_vm::clarity::{ - ClarityBlockConnection, ClarityMarfStore, ClarityMarfStoreTransaction, Error as ClarityError, + ClarityBlockConnection, ClarityError, ClarityMarfStore, ClarityMarfStoreTransaction, WritableMarfStore, }; use crate::clarity_vm::database::marf::MarfedKV; diff --git a/stackslib/src/chainstate/stacks/boot/mod.rs b/stackslib/src/chainstate/stacks/boot/mod.rs index 321a47934c..4087bc7e60 100644 --- a/stackslib/src/chainstate/stacks/boot/mod.rs +++ b/stackslib/src/chainstate/stacks/boot/mod.rs @@ -21,7 +21,7 @@ use std::sync::LazyLock; use clarity::types::Address; use clarity::vm::analysis::CheckErrorKind; use clarity::vm::ast::ASTRules; -use clarity::vm::clarity::{Error as ClarityError, TransactionConnection}; +use clarity::vm::clarity::{ClarityError, TransactionConnection}; use clarity::vm::costs::LimitedCostTracker; use clarity::vm::database::{ClarityDatabase, NULL_BURN_STATE_DB, NULL_HEADER_DB}; use clarity::vm::errors::Error as VmError; diff --git a/stackslib/src/chainstate/stacks/db/contracts.rs b/stackslib/src/chainstate/stacks/db/contracts.rs index 89aa37d56a..aeb344de02 100644 --- a/stackslib/src/chainstate/stacks/db/contracts.rs +++ b/stackslib/src/chainstate/stacks/db/contracts.rs @@ -32,7 +32,7 @@ impl StacksChainState { .with_clarity_db_readonly(|ref mut db| match db.get_contract(contract_id) { Ok(c) => Ok(Some(c)), Err(clarity_vm_error::Unchecked(CheckErrorKind::NoSuchContract(_))) => Ok(None), - Err(e) => Err(clarity_error::Interpreter(e)), + Err(e) => Err(ClarityError::Interpreter(e)), }) .map_err(Error::ClarityError) } @@ -50,7 +50,7 @@ impl StacksChainState { Err(clarity_vm_error::Unchecked(CheckErrorKind::NoSuchDataVariable(_))) => { Ok(None) } - Err(e) => Err(clarity_error::Interpreter(e)), + Err(e) => Err(ClarityError::Interpreter(e)), } }) .map_err(Error::ClarityError) diff --git a/stackslib/src/chainstate/stacks/db/mod.rs b/stackslib/src/chainstate/stacks/db/mod.rs index a217df5b14..26adeccda7 100644 --- a/stackslib/src/chainstate/stacks/db/mod.rs +++ b/stackslib/src/chainstate/stacks/db/mod.rs @@ -66,8 +66,8 @@ use crate::chainstate::stacks::{ C32_ADDRESS_VERSION_TESTNET_SINGLESIG, *, }; use crate::clarity_vm::clarity::{ - ClarityBlockConnection, ClarityConnection, ClarityInstance, ClarityReadOnlyConnection, - Error as clarity_error, PreCommitClarityBlock, + ClarityBlockConnection, ClarityConnection, ClarityError, ClarityInstance, + ClarityReadOnlyConnection, PreCommitClarityBlock, }; use crate::clarity_vm::database::marf::MarfedKV; use crate::clarity_vm::database::HeadersDBConn; @@ -545,7 +545,7 @@ impl<'a, 'b> ClarityTx<'a, 'b> { pub fn commit_mined_block( self, block_hash: &StacksBlockId, - ) -> Result { + ) -> Result { Ok(self.block.commit_mined_block(block_hash)?.get_total()) } @@ -1977,7 +1977,7 @@ impl StacksChainState { parent_id_bhh: &StacksBlockId, contract: &QualifiedContractIdentifier, code: &str, - ) -> Result { + ) -> Result { self.clarity_state.eval_read_only( parent_id_bhh, &HeadersDBConn(StacksDBConn::new(&self.state_index, ())), @@ -1998,7 +1998,7 @@ impl StacksChainState { contract: &QualifiedContractIdentifier, function: &str, args: &[Value], - ) -> Result { + ) -> Result { let headers_db = HeadersDBConn(StacksDBConn::new(&self.state_index, ())); let mut conn = self.clarity_state.read_only_connection_checked( parent_id_bhh, diff --git a/stackslib/src/chainstate/stacks/db/transactions.rs b/stackslib/src/chainstate/stacks/db/transactions.rs index d3d3aaee02..da631f42c4 100644 --- a/stackslib/src/chainstate/stacks/db/transactions.rs +++ b/stackslib/src/chainstate/stacks/db/transactions.rs @@ -34,9 +34,7 @@ use clarity::vm::types::{ use crate::chainstate::stacks::db::*; use crate::chainstate::stacks::miner::TransactionResult; use crate::chainstate::stacks::{Error, StacksMicroblockHeader}; -use crate::clarity_vm::clarity::{ - ClarityConnection, ClarityTransactionConnection, Error as clarity_error, -}; +use crate::clarity_vm::clarity::{ClarityConnection, ClarityError, ClarityTransactionConnection}; use crate::util_lib::strings::VecDisplay; /// This is a safe-to-hash Clarity value @@ -193,10 +191,10 @@ impl StacksTransactionReceipt { pub fn from_analysis_failure( tx: StacksTransaction, analysis_cost: ExecutionCost, - error: clarity::vm::clarity::Error, + error: ClarityError, ) -> StacksTransactionReceipt { let error_string = match error { - clarity_error::StaticCheck(ref check_error) => { + ClarityError::StaticCheck(ref check_error) => { if let Some(span) = check_error.diagnostic.spans.first() { format!( ":{}:{}: {}", @@ -206,7 +204,7 @@ impl StacksTransactionReceipt { check_error.diagnostic.message.to_string() } } - clarity_error::Parse(ref parse_error) => { + ClarityError::Parse(ref parse_error) => { if let Some(span) = parse_error.diagnostic.spans.first() { format!( ":{}:{}: {}", @@ -354,7 +352,7 @@ impl From for MemPoolRejection { pub enum ClarityRuntimeTxError { Acceptable { - error: clarity_error, + error: ClarityError, err_type: &'static str, }, AbortedByCallback { @@ -370,34 +368,34 @@ pub enum ClarityRuntimeTxError { }, CostError(ExecutionCost, ExecutionCost), AnalysisError(CheckErrorKind), - Rejectable(clarity_error), + Rejectable(ClarityError), } -pub fn handle_clarity_runtime_error(error: clarity_error) -> ClarityRuntimeTxError { +pub fn handle_clarity_runtime_error(error: ClarityError) -> ClarityRuntimeTxError { match error { // runtime errors are okay - clarity_error::Interpreter(InterpreterError::Runtime(_, _)) => { + ClarityError::Interpreter(InterpreterError::Runtime(_, _)) => { ClarityRuntimeTxError::Acceptable { error, err_type: "runtime error", } } - clarity_error::Interpreter(InterpreterError::EarlyReturn(_)) => { + ClarityError::Interpreter(InterpreterError::EarlyReturn(_)) => { ClarityRuntimeTxError::Acceptable { error, err_type: "short return/panic", } } - clarity_error::Interpreter(InterpreterError::Unchecked(check_error)) => { + ClarityError::Interpreter(InterpreterError::Unchecked(check_error)) => { if check_error.rejectable() { - ClarityRuntimeTxError::Rejectable(clarity_error::Interpreter( + ClarityRuntimeTxError::Rejectable(ClarityError::Interpreter( InterpreterError::Unchecked(check_error), )) } else { ClarityRuntimeTxError::AnalysisError(check_error) } } - clarity_error::AbortedByCallback { + ClarityError::AbortedByCallback { output, assets_modified, tx_events, @@ -408,7 +406,7 @@ pub fn handle_clarity_runtime_error(error: clarity_error) -> ClarityRuntimeTxErr tx_events, reason, }, - clarity_error::CostError(cost, budget) => ClarityRuntimeTxError::CostError(cost, budget), + ClarityError::CostError(cost, budget) => ClarityRuntimeTxError::CostError(cost, budget), unhandled_error => ClarityRuntimeTxError::Rejectable(unhandled_error), } } @@ -1212,7 +1210,7 @@ impl StacksChainState { "function_name" => %contract_call.function_name, "function_args" => %VecDisplay(&contract_call.function_args), "error" => %check_error); - return Err(Error::ClarityError(clarity_error::Interpreter( + return Err(Error::ClarityError(ClarityError::Interpreter( InterpreterError::Unchecked(check_error), ))); } @@ -1282,7 +1280,7 @@ impl StacksChainState { Ok(x) => x, Err(e) => { match e { - clarity_error::CostError(ref cost_after, ref budget) => { + ClarityError::CostError(ref cost_after, ref budget) => { warn!("Block compute budget exceeded on {}: cost before={}, after={}, budget={}", tx.txid(), &cost_before, cost_after, budget); return Err(Error::CostOverflowError( cost_before, @@ -1295,7 +1293,7 @@ impl StacksChainState { // a [Vary]ExpressionDepthTooDeep error in this situation // invalidates the block, since this should have prevented the // block from getting relayed in the first place - if let clarity_error::Parse(ref parse_error) = &other_error { + if let ClarityError::Parse(ref parse_error) = &other_error { match *parse_error.err { ParseErrors::ExpressionStackDepthTooDeep | ParseErrors::VaryExpressionStackDepthTooDeep => { @@ -1306,13 +1304,13 @@ impl StacksChainState { } } } - if let clarity_error::Parse(err) = &other_error { + if let ClarityError::Parse(err) = &other_error { if err.rejectable() { info!("Transaction {} is problematic and should have prevented this block from being relayed", tx.txid()); return Err(Error::ClarityError(other_error)); } } - if let clarity_error::StaticCheck(err) = &other_error { + if let ClarityError::StaticCheck(err) = &other_error { if err.err.rejectable() { info!("Transaction {} is problematic and should have prevented this block from being relayed", tx.txid()); return Err(Error::ClarityError(other_error)); @@ -1454,7 +1452,7 @@ impl StacksChainState { "txid" => %tx.txid(), "contract" => %contract_id, "error" => %check_error); - return Err(Error::ClarityError(clarity_error::Interpreter( + return Err(Error::ClarityError(ClarityError::Interpreter( InterpreterError::Unchecked(check_error), ))); } @@ -8507,7 +8505,7 @@ pub mod test { None, ) .unwrap_err(); - let Error::ClarityError(clarity_error::BadTransaction(msg)) = &err else { + let Error::ClarityError(ClarityError::BadTransaction(msg)) = &err else { panic!("Unexpected error type"); }; assert!(msg.find("never seen in this fork").is_some()); @@ -9814,7 +9812,7 @@ pub mod test { ASTRules::PrecheckSize, ) .unwrap_err(); - if let Error::ClarityError(clarity_error::Interpreter(InterpreterError::Unchecked( + if let Error::ClarityError(ClarityError::Interpreter(InterpreterError::Unchecked( _check_error, ))) = err { @@ -9871,7 +9869,7 @@ pub mod test { ASTRules::PrecheckSize, ) .unwrap_err(); - if let Error::ClarityError(clarity_error::Interpreter(InterpreterError::Unchecked( + if let Error::ClarityError(ClarityError::Interpreter(InterpreterError::Unchecked( _check_error, ))) = err { @@ -9926,7 +9924,7 @@ pub mod test { ASTRules::PrecheckSize, ) .unwrap_err(); - if let Error::ClarityError(clarity_error::Interpreter(InterpreterError::Unchecked( + if let Error::ClarityError(ClarityError::Interpreter(InterpreterError::Unchecked( _check_error, ))) = err { @@ -9982,7 +9980,7 @@ pub mod test { ASTRules::PrecheckSize, ) .unwrap_err(); - if let Error::ClarityError(clarity_error::Interpreter(InterpreterError::Unchecked( + if let Error::ClarityError(ClarityError::Interpreter(InterpreterError::Unchecked( _check_error, ))) = err { @@ -10506,7 +10504,7 @@ pub mod test { ASTRules::PrecheckSize, ) .unwrap_err(); - if let Error::ClarityError(clarity_error::Interpreter(InterpreterError::Unchecked( + if let Error::ClarityError(ClarityError::Interpreter(InterpreterError::Unchecked( check_error, ))) = err { @@ -10980,7 +10978,7 @@ pub mod test { ASTRules::PrecheckSize, ) .unwrap_err(); - if let Error::ClarityError(clarity_error::Interpreter(InterpreterError::Unchecked( + if let Error::ClarityError(ClarityError::Interpreter(InterpreterError::Unchecked( check_error, ))) = err { @@ -11095,7 +11093,7 @@ pub mod test { ASTRules::PrecheckSize, ) .unwrap_err(); - if let Error::ClarityError(clarity_error::Interpreter(InterpreterError::Unchecked( + if let Error::ClarityError(ClarityError::Interpreter(InterpreterError::Unchecked( check_error, ))) = err { diff --git a/stackslib/src/chainstate/stacks/miner.rs b/stackslib/src/chainstate/stacks/miner.rs index a6837e5c4f..20316d8677 100644 --- a/stackslib/src/chainstate/stacks/miner.rs +++ b/stackslib/src/chainstate/stacks/miner.rs @@ -51,7 +51,7 @@ use crate::chainstate::stacks::db::unconfirmed::UnconfirmedState; use crate::chainstate::stacks::db::{ChainstateTx, ClarityTx, StacksChainState}; use crate::chainstate::stacks::events::StacksTransactionReceipt; use crate::chainstate::stacks::{Error, StacksBlockHeader, StacksMicroblockHeader, *}; -use crate::clarity_vm::clarity::{ClarityInstance, Error as clarity_error}; +use crate::clarity_vm::clarity::{ClarityError, ClarityInstance}; use crate::core::mempool::*; use crate::core::*; use crate::monitoring::{ @@ -657,7 +657,7 @@ impl TransactionResult { } // recover original ClarityError ClarityRuntimeTxError::Acceptable { error, .. } => { - if let clarity_error::Parse(ref parse_err) = error { + if let ClarityError::Parse(ref parse_err) = error { info!("Parse error: {}", parse_err; "txid" => %tx.txid()); match *parse_err.err { ParseErrors::ExpressionStackDepthTooDeep @@ -671,10 +671,10 @@ impl TransactionResult { Error::ClarityError(error) } ClarityRuntimeTxError::CostError(cost, budget) => { - Error::ClarityError(clarity_error::CostError(cost, budget)) + Error::ClarityError(ClarityError::CostError(cost, budget)) } ClarityRuntimeTxError::AnalysisError(e) => { - let clarity_err = Error::ClarityError(clarity_error::Interpreter( + let clarity_err = Error::ClarityError(ClarityError::Interpreter( InterpreterError::Unchecked(e), )); if epoch_id < StacksEpochId::Epoch21 { @@ -690,7 +690,7 @@ impl TransactionResult { assets_modified, tx_events, reason, - } => Error::ClarityError(clarity_error::AbortedByCallback { + } => Error::ClarityError(ClarityError::AbortedByCallback { output: output.map(Box::new), assets_modified: Box::new(assets_modified), tx_events, diff --git a/stackslib/src/chainstate/stacks/mod.rs b/stackslib/src/chainstate/stacks/mod.rs index 7bf4d87c5d..447bcd7b36 100644 --- a/stackslib/src/chainstate/stacks/mod.rs +++ b/stackslib/src/chainstate/stacks/mod.rs @@ -43,7 +43,7 @@ use crate::chainstate::burn::ConsensusHash; use crate::chainstate::stacks::db::accounts::MinerReward; use crate::chainstate::stacks::db::{MinerRewardInfo, StacksHeaderInfo}; use crate::chainstate::stacks::index::Error as marf_error; -use crate::clarity_vm::clarity::Error as clarity_error; +use crate::clarity_vm::clarity::ClarityError; use crate::net::Error as net_error; use crate::util_lib::db::Error as db_error; use crate::util_lib::strings::StacksString; @@ -99,7 +99,7 @@ pub enum Error { MicroblockStreamTooLongError, IncompatibleSpendingConditionError, CostOverflowError(ExecutionCost, ExecutionCost, ExecutionCost), - ClarityError(clarity_error), + ClarityError(ClarityError), DBError(db_error), NetError(net_error), CodecError(codec_error), @@ -128,8 +128,8 @@ impl From for Error { } } -impl From for Error { - fn from(e: clarity_error) -> Error { +impl From for Error { + fn from(e: ClarityError) -> Error { Error::ClarityError(e) } } @@ -344,7 +344,7 @@ impl From for Error { impl From for Error { fn from(e: clarity_interpreter_error) -> Error { - Error::ClarityError(clarity_error::Interpreter(e)) + Error::ClarityError(ClarityError::Interpreter(e)) } } diff --git a/stackslib/src/clarity_vm/clarity.rs b/stackslib/src/clarity_vm/clarity.rs index 4ac343da08..39835bfa21 100644 --- a/stackslib/src/clarity_vm/clarity.rs +++ b/stackslib/src/clarity_vm/clarity.rs @@ -21,7 +21,7 @@ use clarity::consts::CHAIN_ID_TESTNET; use clarity::vm::analysis::AnalysisDatabase; use clarity::vm::ast::ASTRules; use clarity::vm::clarity::TransactionConnection; -pub use clarity::vm::clarity::{ClarityConnection, Error}; +pub use clarity::vm::clarity::{ClarityConnection, ClarityError}; use clarity::vm::contexts::{AssetMap, OwnedEnvironment}; use clarity::vm::costs::{CostTracker, ExecutionCost, LimitedCostTracker}; use clarity::vm::database::{ @@ -274,13 +274,15 @@ pub struct ClarityReadOnlyConnection<'a> { epoch: StacksEpochId, } -impl From for Error { +impl From for ClarityError { fn from(e: ChainstateError) -> Self { match e { - ChainstateError::InvalidStacksTransaction(msg, _) => Error::BadTransaction(msg), - ChainstateError::CostOverflowError(_, after, budget) => Error::CostError(after, budget), + ChainstateError::InvalidStacksTransaction(msg, _) => ClarityError::BadTransaction(msg), + ChainstateError::CostOverflowError(_, after, budget) => { + ClarityError::CostError(after, budget) + } ChainstateError::ClarityError(x) => x, - x => Error::BadTransaction(format!("{:?}", &x)), + x => ClarityError::BadTransaction(x.to_string()), } } } @@ -358,7 +360,7 @@ impl ClarityBlockConnection<'_, '_> { pub fn get_clarity_db_epoch_version( &mut self, burn_state_db: &dyn BurnStateDB, - ) -> Result { + ) -> Result { let mut db = self.datastore.as_clarity_db(self.header_db, burn_state_db); // NOTE: the begin/roll_back shouldn't be necessary with how this gets used in practice, // but is put here defensively. @@ -665,7 +667,7 @@ impl ClarityInstance { conn } - pub fn drop_unconfirmed_state(&mut self, block: &StacksBlockId) -> Result<(), Error> { + pub fn drop_unconfirmed_state(&mut self, block: &StacksBlockId) -> Result<(), ClarityError> { let datastore = self.datastore.begin_unconfirmed(block); datastore.drop_unconfirmed()?; Ok(()) @@ -765,7 +767,7 @@ impl ClarityInstance { at_block: &StacksBlockId, header_db: &'a dyn HeadersDB, burn_state_db: &'a dyn BurnStateDB, - ) -> Result, Error> { + ) -> Result, ClarityError> { let mut datastore = self.datastore.begin_read_only_checked(Some(at_block))?; let epoch = { let mut db = datastore.as_clarity_db(header_db, burn_state_db); @@ -798,7 +800,7 @@ impl ClarityInstance { contract: &QualifiedContractIdentifier, program: &str, ast_rules: ASTRules, - ) -> Result { + ) -> Result { let mut read_only_conn = self.datastore.begin_read_only(Some(at_block)); let mut clarity_db = read_only_conn.as_clarity_db(header_db, burn_state_db); let epoch_id = { @@ -811,7 +813,7 @@ impl ClarityInstance { let mut env = OwnedEnvironment::new_free(self.mainnet, self.chain_id, clarity_db, epoch_id); env.eval_read_only_with_rules(contract, program, ast_rules) .map(|(x, _, _)| x) - .map_err(Error::from) + .map_err(ClarityError::from) } pub fn destroy(self) -> MarfedKV { @@ -956,7 +958,10 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { /// before this saves, it updates the metadata headers in /// the sidestore so that they don't get stepped on after /// a miner re-executes a constructed block. - pub fn commit_mined_block(self, bhh: &StacksBlockId) -> Result { + pub fn commit_mined_block( + self, + bhh: &StacksBlockId, + ) -> Result { debug!("Commit mined Clarity datastore to {}", bhh); self.datastore.commit_to_mined_block(bhh)?; @@ -976,7 +981,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { } /// Get the boot code account - fn get_boot_code_account(&mut self) -> Result { + fn get_boot_code_account(&mut self) -> Result { let boot_code_address = boot_code_addr(self.mainnet); let boot_code_nonce = self.with_clarity_db_readonly(|db| { db.get_account_nonce(&boot_code_address.clone().into()) @@ -986,7 +991,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { Ok(boot_code_account) } - pub fn initialize_epoch_2_05(&mut self) -> Result { + pub fn initialize_epoch_2_05(&mut self) -> Result { // use the `using!` statement to ensure that the old cost_tracker is placed // back in all branches after initialization using!(self.cost_track, "cost tracker", |old_cost_tracker| { @@ -1070,7 +1075,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { }) } - pub fn initialize_epoch_2_1(&mut self) -> Result, Error> { + pub fn initialize_epoch_2_1(&mut self) -> Result, ClarityError> { // use the `using!` statement to ensure that the old cost_tracker is placed // back in all branches after initialization using!(self.cost_track, "cost tracker", |old_cost_tracker| { @@ -1258,7 +1263,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { }) } - pub fn initialize_epoch_2_2(&mut self) -> Result, Error> { + pub fn initialize_epoch_2_2(&mut self) -> Result, ClarityError> { // use the `using!` statement to ensure that the old cost_tracker is placed // back in all branches after initialization using!(self.cost_track, "cost tracker", |old_cost_tracker| { @@ -1285,7 +1290,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { }) } - pub fn initialize_epoch_2_3(&mut self) -> Result, Error> { + pub fn initialize_epoch_2_3(&mut self) -> Result, ClarityError> { // use the `using!` statement to ensure that the old cost_tracker is placed // back in all branches after initialization using!(self.cost_track, "cost tracker", |old_cost_tracker| { @@ -1314,7 +1319,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { }) } - pub fn initialize_epoch_2_4(&mut self) -> Result, Error> { + pub fn initialize_epoch_2_4(&mut self) -> Result, ClarityError> { // use the `using!` statement to ensure that the old cost_tracker is placed // back in all branches after initialization using!(self.cost_track, "cost tracker", |old_cost_tracker| { @@ -1445,7 +1450,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { }) } - pub fn initialize_epoch_2_5(&mut self) -> Result, Error> { + pub fn initialize_epoch_2_5(&mut self) -> Result, ClarityError> { // use the `using!` statement to ensure that the old cost_tracker is placed // back in all branches after initialization using!(self.cost_track, "cost tracker", |old_cost_tracker| { @@ -1688,7 +1693,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { }) } - pub fn initialize_epoch_3_0(&mut self) -> Result, Error> { + pub fn initialize_epoch_3_0(&mut self) -> Result, ClarityError> { // use the `using!` statement to ensure that the old cost_tracker is placed // back in all branches after initialization using!(self.cost_track, "cost tracker", |old_cost_tracker| { @@ -1714,7 +1719,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { }) } - pub fn initialize_epoch_3_1(&mut self) -> Result, Error> { + pub fn initialize_epoch_3_1(&mut self) -> Result, ClarityError> { // use the `using!` statement to ensure that the old cost_tracker is placed // back in all branches after initialization using!(self.cost_track, "cost tracker", |old_cost_tracker| { @@ -1740,7 +1745,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { }) } - pub fn initialize_epoch_3_2(&mut self) -> Result, Error> { + pub fn initialize_epoch_3_2(&mut self) -> Result, ClarityError> { // use the `using!` statement to ensure that the old cost_tracker is placed // back in all branches after initialization using!(self.cost_track, "cost tracker", |old_cost_tracker| { @@ -1846,7 +1851,7 @@ impl<'a, 'b> ClarityBlockConnection<'a, 'b> { }) } - pub fn initialize_epoch_3_3(&mut self) -> Result, Error> { + pub fn initialize_epoch_3_3(&mut self) -> Result, ClarityError> { // use the `using!` statement to ensure that the old cost_tracker is placed // back in all branches after initialization using!(self.cost_track, "cost tracker", |old_cost_tracker| { @@ -2138,9 +2143,9 @@ impl TransactionConnection for ClarityTransactionConnection<'_, '_> { impl ClarityTransactionConnection<'_, '_> { /// Do something to the underlying DB that involves writing. - pub fn with_clarity_db(&mut self, to_do: F) -> Result + pub fn with_clarity_db(&mut self, to_do: F) -> Result where - F: FnOnce(&mut ClarityDatabase) -> Result, + F: FnOnce(&mut ClarityDatabase) -> Result, { using!(self.log, "log", |log| { let rollback_wrapper = RollbackWrapper::from_persisted_log(self.store, log); @@ -2181,7 +2186,7 @@ impl ClarityTransactionConnection<'_, '_> { sender: &PrincipalData, mblock_header_1: &StacksMicroblockHeader, mblock_header_2: &StacksMicroblockHeader, - ) -> Result { + ) -> Result { self.with_abort_callback( |vm_env| { vm_env @@ -2194,7 +2199,7 @@ impl ClarityTransactionConnection<'_, '_> { ) }) }) - .map_err(Error::from) + .map_err(ClarityError::from) }, |_, _| None, ) @@ -2207,7 +2212,7 @@ impl ClarityTransactionConnection<'_, '_> { /// Commit the changes from the edit log. /// panics if there is more than one open savepoint - pub fn commit(mut self) -> Result<(), Error> { + pub fn commit(mut self) -> Result<(), ClarityError> { let log = self .log .take() @@ -2243,7 +2248,7 @@ impl ClarityTransactionConnection<'_, '_> { contract: &QualifiedContractIdentifier, method: &str, args: &[SymbolicExpression], - ) -> Result { + ) -> Result { let (result, _, _, _) = self.with_abort_callback( |vm_env| { vm_env @@ -2254,7 +2259,7 @@ impl ClarityTransactionConnection<'_, '_> { method, args, ) - .map_err(Error::from) + .map_err(ClarityError::from) }, |_, _| Some("read-only".to_string()), )?; @@ -2263,9 +2268,9 @@ impl ClarityTransactionConnection<'_, '_> { /// Evaluate a raw Clarity snippit #[cfg(test)] - pub fn clarity_eval_raw(&mut self, code: &str) -> Result { + pub fn clarity_eval_raw(&mut self, code: &str) -> Result { let (result, _, _, _) = self.with_abort_callback( - |vm_env| vm_env.eval_raw(code).map_err(Error::from), + |vm_env| vm_env.eval_raw(code).map_err(ClarityError::from), |_, _| None, )?; Ok(result) @@ -2276,9 +2281,13 @@ impl ClarityTransactionConnection<'_, '_> { &mut self, contract: &QualifiedContractIdentifier, code: &str, - ) -> Result { + ) -> Result { let (result, _, _, _) = self.with_abort_callback( - |vm_env| vm_env.eval_read_only(contract, code).map_err(Error::from), + |vm_env| { + vm_env + .eval_read_only(contract, code) + .map_err(ClarityError::from) + }, |_, _| None, )?; Ok(result) @@ -2960,7 +2969,7 @@ mod tests { ) }) .unwrap_err(); - let result_value = if let Error::AbortedByCallback { output, .. } = e { + let result_value = if let ClarityError::AbortedByCallback { output, .. } = e { output.unwrap() } else { panic!("Expects a AbortedByCallback error") @@ -3331,7 +3340,7 @@ mod tests { )) .unwrap_err() { - Error::CostError(total, limit) => { + ClarityError::CostError(total, limit) => { eprintln!("{}, {}", total, limit); limit.runtime == 100 && total.runtime > 100 } diff --git a/stackslib/src/clarity_vm/tests/analysis_costs.rs b/stackslib/src/clarity_vm/tests/analysis_costs.rs index e8180ef116..4dbe520f71 100644 --- a/stackslib/src/clarity_vm/tests/analysis_costs.rs +++ b/stackslib/src/clarity_vm/tests/analysis_costs.rs @@ -15,7 +15,7 @@ // along with this program. If not, see . use clarity::vm::ast::ASTRules; -use clarity::vm::clarity::{Error as ClarityError, TransactionConnection}; +use clarity::vm::clarity::{ClarityError, TransactionConnection}; use clarity::vm::costs::ExecutionCost; use clarity::vm::errors::CheckErrorKind; use clarity::vm::functions::NativeFunctions; diff --git a/stackslib/src/clarity_vm/tests/contracts.rs b/stackslib/src/clarity_vm/tests/contracts.rs index ebebff8339..9fc6f612a7 100644 --- a/stackslib/src/clarity_vm/tests/contracts.rs +++ b/stackslib/src/clarity_vm/tests/contracts.rs @@ -16,7 +16,7 @@ use clarity::types::StacksEpochId; use clarity::vm::ast::ASTRules; -use clarity::vm::clarity::Error as ClarityError; +use clarity::vm::clarity::ClarityError; use clarity::vm::errors::{CheckErrorKind, Error}; use clarity::vm::types::SequenceData::Buffer; use clarity::vm::types::{ @@ -304,7 +304,7 @@ fn publish_contract( contract_id: &QualifiedContractIdentifier, contract: &str, version: ClarityVersion, -) -> Result<(), clarity::vm::clarity::Error> { +) -> Result<(), ClarityError> { bc.as_transaction(|tx| { let (ast, analysis) = tx.analyze_smart_contract(contract_id, version, contract, ASTRules::PrecheckSize)?; diff --git a/stackslib/src/clarity_vm/tests/large_contract.rs b/stackslib/src/clarity_vm/tests/large_contract.rs index b90216bd96..287590b8d9 100644 --- a/stackslib/src/clarity_vm/tests/large_contract.rs +++ b/stackslib/src/clarity_vm/tests/large_contract.rs @@ -36,7 +36,7 @@ use stacks_common::types::StacksEpochId; use crate::chainstate::stacks::boot::{BOOT_CODE_COSTS_2, BOOT_CODE_COSTS_3, BOOT_CODE_COSTS_4}; use crate::chainstate::stacks::index::ClarityMarfTrieId; -use crate::clarity_vm::clarity::{ClarityBlockConnection, ClarityInstance, Error as ClarityError}; +use crate::clarity_vm::clarity::{ClarityBlockConnection, ClarityError, ClarityInstance}; use crate::clarity_vm::database::marf::MarfedKV; use crate::clarity_vm::database::MemoryBackingStore; use crate::util_lib::boot::boot_code_id; diff --git a/stackslib/src/net/api/postblock_proposal.rs b/stackslib/src/net/api/postblock_proposal.rs index 5447956f49..f04e371a13 100644 --- a/stackslib/src/net/api/postblock_proposal.rs +++ b/stackslib/src/net/api/postblock_proposal.rs @@ -46,7 +46,7 @@ use crate::chainstate::stacks::miner::{ use crate::chainstate::stacks::{ Error as ChainError, StacksTransaction, TenureChangeCause, TransactionPayload, }; -use crate::clarity_vm::clarity::Error as ClarityError; +use crate::clarity_vm::clarity::ClarityError; use crate::core::mempool::ProposalCallbackReceiver; use crate::net::http::{ http_reason, parse_json, Error, HttpContentType, HttpRequest, HttpRequestContents, diff --git a/stackslib/src/net/mod.rs b/stackslib/src/net/mod.rs index 1dd559c0cf..4523415c93 100644 --- a/stackslib/src/net/mod.rs +++ b/stackslib/src/net/mod.rs @@ -48,7 +48,7 @@ use crate::chainstate::stacks::{ Error as chainstate_error, Error as chain_error, StacksBlock, StacksMicroblock, StacksPublicKey, StacksTransaction, }; -use crate::clarity_vm::clarity::Error as clarity_error; +use crate::clarity_vm::clarity::ClarityError; use crate::core::mempool::*; use crate::cost_estimates::metrics::CostMetric; use crate::cost_estimates::{CostEstimator, FeeEstimator}; @@ -203,7 +203,7 @@ pub enum Error { /// MARF error, percolated up from chainstate MARFError(marf_error), /// Clarity VM error, percolated up from chainstate - ClarityError(clarity_error), + ClarityError(ClarityError), /// Catch-all for chainstate errors that don't map cleanly into network errors ChainstateError(String), /// Coordinator hung up @@ -527,8 +527,8 @@ impl From for Error { } } -impl From for Error { - fn from(e: clarity_error) -> Self { +impl From for Error { + fn from(e: ClarityError) -> Self { Error::ClarityError(e) } }