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