ckb_script/
error.rs

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/// Script execution error.
9#[derive(Error, Debug, PartialEq, Eq, Clone)]
10pub enum ScriptError {
11    /// The field code_hash in script can't be resolved
12    #[error("ScriptNotFound: code_hash: {0}")]
13    ScriptNotFound(Byte32),
14
15    /// The script consumes too much cycles
16    #[error("ExceededMaximumCycles: expect cycles <= {0}")]
17    ExceededMaximumCycles(Cycle),
18
19    /// Internal error cycles overflow
20    #[error("CyclesOverflow: lhs {0} rhs {1}")]
21    CyclesOverflow(Cycle, Cycle),
22
23    /// `script.type_hash` hits multiple cells with different data
24    #[error("MultipleMatches")]
25    MultipleMatches,
26
27    /// Non-zero exit code returns by script
28    #[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    /// Known bugs are detected in transaction script outputs
32    #[error("Known bugs encountered in output {1}: {0}")]
33    EncounteredKnownBugs(String, usize),
34
35    /// InvalidScriptHashType
36    #[error("InvalidScriptHashType: {0}")]
37    InvalidScriptHashType(String),
38
39    /// InvalidVmVersion
40    #[error("Invalid VM Version: {0}")]
41    InvalidVmVersion(u8),
42
43    /// Errors thrown by ckb-vm
44    #[error("VM Internal Error: {0:?}")]
45    VMInternalError(VMInternalError),
46
47    /// Interrupts, such as a Ctrl-C signal
48    #[error("VM Interrupts")]
49    Interrupts,
50
51    /// Other errors raised in script execution process
52    #[error("Other Error: {0}")]
53    Other(String),
54}
55
56/// Locate the script using the first input index if possible, otherwise the first output index.
57#[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/// Script execution error with the error source information.
89#[derive(Debug, PartialEq, Eq, Clone)]
90pub struct TransactionScriptError {
91    source: TransactionScriptErrorSource,
92    cause: ScriptError,
93}
94
95impl TransactionScriptError {
96    /// Originating script for the generated error
97    pub fn originating_script(&self) -> &TransactionScriptErrorSource {
98        &self.source
99    }
100
101    /// Actual error generated when verifying script
102    pub fn script_error(&self) -> &ScriptError {
103        &self.cause
104    }
105}
106
107/// It is a deliberate choice here to implement StdError directly, instead of
108/// implementing thiserror::Error on TransactionScriptError. This way, calling
109/// root_cause() on ckb_error::Error would return TransactionScriptError structure,
110/// providing us enough information to inspect on all kinds of errors generated when
111/// verifying a script.
112///
113/// This also means calling source() or cause() from std::error::Error on
114/// TransactionScriptError would return None values. One is expected to cast
115/// a value of `std::error::Error` type(possibly returned from root_cause) into
116/// concrete TransactionScriptError type, then use the defined methods to fetch
117/// originating script, as well as the actual script error. See the unit test defined
118/// at the end of this file for an example.
119impl 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    /// Creates a script error originated the script and its exit code.
133    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    ///  Creates a script error originated from the script group.
147    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    /// Creates a script error originated from the lock script of the input cell at the specific index.
155    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    /// Creates a script error originated from the type script of the input cell at the specific index.
163    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    /// Creates a script error originated from the type script of the output cell at the specific index.
171    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    /// Creates a script error with unknown source, usually a internal error
179    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}