1use crate::types::{ScriptGroup, ScriptGroupType};
2use ckb_error::{Error, ErrorKind, InternalErrorKind, prelude::*};
3use ckb_types::core::{Cycle, ScriptHashType};
4use ckb_types::packed::{Byte32, Script};
5use ckb_vm::Error as VMInternalError;
6use std::{error::Error as StdError, fmt};
7
8#[derive(Error, Debug, PartialEq, Eq, Clone)]
10pub enum ScriptError {
11 #[error("ScriptNotFound: code_hash: {0}")]
13 ScriptNotFound(Byte32),
14
15 #[error("ExceededMaximumCycles: expect cycles <= {0}")]
17 ExceededMaximumCycles(Cycle),
18
19 #[error("CyclesOverflow: lhs {0} rhs {1}")]
21 CyclesOverflow(Cycle, Cycle),
22
23 #[error("MultipleMatches")]
25 MultipleMatches,
26
27 #[error(
29 "ValidationFailure: see error code {1} on page https://nervosnetwork.github.io/ckb-script-error-codes/{0}.html#{1}"
30 )]
31 ValidationFailure(String, i8),
32
33 #[error("Known bugs encountered in output {1}: {0}")]
35 EncounteredKnownBugs(String, usize),
36
37 #[error("InvalidScriptHashType: {0}")]
39 InvalidScriptHashType(String),
40
41 #[error("Invalid VM Version: {0}")]
43 InvalidVmVersion(u8),
44
45 #[error("VM Internal Error: {0:?}")]
47 VMInternalError(VMInternalError),
48
49 #[error("VM Interrupts")]
51 Interrupts,
52
53 #[error("Other Error: {0}")]
55 Other(String),
56}
57
58#[derive(Clone, Debug, Eq, PartialEq)]
60pub enum TransactionScriptErrorSource {
61 Inputs(usize, ScriptGroupType),
62 Outputs(usize, ScriptGroupType),
63 Unknown,
64}
65
66impl TransactionScriptErrorSource {
67 fn from_script_group(script_group: &ScriptGroup) -> Self {
68 if let Some(n) = script_group.input_indices.first() {
69 TransactionScriptErrorSource::Inputs(*n, script_group.group_type)
70 } else if let Some(n) = script_group.output_indices.first() {
71 TransactionScriptErrorSource::Outputs(*n, script_group.group_type)
72 } else {
73 TransactionScriptErrorSource::Unknown
74 }
75 }
76}
77
78impl fmt::Display for TransactionScriptErrorSource {
79 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
80 match self {
81 TransactionScriptErrorSource::Inputs(n, field) => write!(f, "Inputs[{n}].{field}"),
82 TransactionScriptErrorSource::Outputs(n, field) => {
83 write!(f, "Outputs[{n}].{field}")
84 }
85 TransactionScriptErrorSource::Unknown => write!(f, "Unknown"),
86 }
87 }
88}
89
90#[derive(Debug, PartialEq, Eq, Clone)]
92pub struct TransactionScriptError {
93 source: TransactionScriptErrorSource,
94 cause: ScriptError,
95}
96
97impl TransactionScriptError {
98 pub fn originating_script(&self) -> &TransactionScriptErrorSource {
100 &self.source
101 }
102
103 pub fn script_error(&self) -> &ScriptError {
105 &self.cause
106 }
107}
108
109impl StdError for TransactionScriptError {}
122
123impl fmt::Display for TransactionScriptError {
124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
125 write!(
126 f,
127 "TransactionScriptError {{ source: {}, cause: {} }}",
128 self.source, self.cause
129 )
130 }
131}
132
133impl ScriptError {
134 pub fn validation_failure(script: &Script, exit_code: i8) -> ScriptError {
136 let url_path = match ScriptHashType::try_from(script.hash_type()).expect("checked data") {
137 ScriptHashType::Data | ScriptHashType::Data1 | ScriptHashType::Data2 => {
138 format!("by-data-hash/{:x}", script.code_hash())
139 }
140 ScriptHashType::Type => {
141 format!("by-type-hash/{:x}", script.code_hash())
142 }
143 hash_type => {
144 return ScriptError::InvalidScriptHashType(format!(
145 "The ScriptHashType/{:?} has not been activated, and is not permitted for use.",
146 hash_type
147 ));
148 }
149 };
150
151 ScriptError::ValidationFailure(url_path, exit_code)
152 }
153
154 pub fn source(self, script_group: &ScriptGroup) -> TransactionScriptError {
156 TransactionScriptError {
157 source: TransactionScriptErrorSource::from_script_group(script_group),
158 cause: self,
159 }
160 }
161
162 pub fn input_lock_script(self, index: usize) -> TransactionScriptError {
164 TransactionScriptError {
165 source: TransactionScriptErrorSource::Inputs(index, ScriptGroupType::Lock),
166 cause: self,
167 }
168 }
169
170 pub fn input_type_script(self, index: usize) -> TransactionScriptError {
172 TransactionScriptError {
173 source: TransactionScriptErrorSource::Inputs(index, ScriptGroupType::Type),
174 cause: self,
175 }
176 }
177
178 pub fn output_type_script(self, index: usize) -> TransactionScriptError {
180 TransactionScriptError {
181 source: TransactionScriptErrorSource::Outputs(index, ScriptGroupType::Type),
182 cause: self,
183 }
184 }
185
186 pub fn unknown_source(self) -> TransactionScriptError {
188 TransactionScriptError {
189 source: TransactionScriptErrorSource::Unknown,
190 cause: self,
191 }
192 }
193}
194
195impl From<TransactionScriptError> for Error {
196 fn from(error: TransactionScriptError) -> Self {
197 match error.cause {
198 ScriptError::Interrupts => ErrorKind::Internal
199 .because(InternalErrorKind::Interrupts.other(ScriptError::Interrupts.to_string())),
200 _ => ErrorKind::Script.because(error),
201 }
202 }
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208 use ckb_types::core::error::ARGV_TOO_LONG_TEXT;
209
210 #[test]
211 fn test_downcast_error_to_vm_error() {
212 let vm_error = VMInternalError::ElfParseError("Foo bar baz".to_string());
213 let script_error = ScriptError::VMInternalError(vm_error.clone());
214 let error: Error = script_error.output_type_script(177).into();
215
216 let recovered_transaction_error: TransactionScriptError = error
217 .root_cause()
218 .downcast_ref()
219 .cloned()
220 .expect("downcasting transaction error");
221 assert_eq!(
222 recovered_transaction_error.originating_script(),
223 &TransactionScriptErrorSource::Outputs(177, ScriptGroupType::Type),
224 );
225
226 if let ScriptError::VMInternalError(recovered_vm_error) =
227 recovered_transaction_error.script_error()
228 {
229 assert_eq!(recovered_vm_error, &vm_error);
230 } else {
231 panic!(
232 "Invalid script type: {}",
233 recovered_transaction_error.script_error()
234 );
235 }
236 }
237
238 #[test]
239 fn test_vm_internal_error_preserves_text() {
240 let vm_error = VMInternalError::Unexpected(ARGV_TOO_LONG_TEXT.to_string());
241 let script_error = ScriptError::VMInternalError(vm_error);
242 let error: Error = script_error.output_type_script(177).into();
243
244 assert!(format!("{}", error).contains(ARGV_TOO_LONG_TEXT));
245 }
246}