iota_types/
execution_status.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::fmt::{self, Display, Formatter};
6
7use iota_macros::EnumVariantOrder;
8use move_binary_format::file_format::{CodeOffset, TypeParameterIndex};
9use move_core_types::language_storage::ModuleId;
10use serde::{Deserialize, Serialize};
11use thiserror::Error;
12
13use crate::{ObjectID, base_types::IotaAddress};
14
15#[cfg(test)]
16#[path = "unit_tests/execution_status_tests.rs"]
17mod execution_status_tests;
18
19#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
20pub enum ExecutionStatus {
21    Success,
22    /// Gas used in the failed case, and the error.
23    Failure {
24        /// The error
25        error: ExecutionFailureStatus,
26        /// Which command the error occurred
27        command: Option<CommandIndex>,
28    },
29}
30
31#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
32pub struct CongestedObjects(pub Vec<ObjectID>);
33
34impl fmt::Display for CongestedObjects {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
36        for obj in &self.0 {
37            write!(f, "{}, ", obj)?;
38        }
39        Ok(())
40    }
41}
42
43#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, EnumVariantOrder)]
44pub enum ExecutionFailureStatus {
45    // General transaction errors
46    #[error("Insufficient Gas.")]
47    InsufficientGas,
48    #[error("Invalid Gas Object. Possibly not address-owned or possibly not an IOTA coin.")]
49    InvalidGasObject,
50    #[error("INVARIANT VIOLATION.")]
51    InvariantViolation,
52    #[error("Attempted to used feature that is not supported yet")]
53    FeatureNotYetSupported,
54    #[error(
55        "Move object with size {object_size} is larger \
56        than the maximum object size {max_object_size}"
57    )]
58    MoveObjectTooBig {
59        object_size: u64,
60        max_object_size: u64,
61    },
62    #[error(
63        "Move package with size {object_size} is larger than the \
64        maximum object size {max_object_size}"
65    )]
66    MovePackageTooBig {
67        object_size: u64,
68        max_object_size: u64,
69    },
70    #[error("Circular Object Ownership, including object {object}.")]
71    CircularObjectOwnership { object: ObjectID },
72
73    // Coin errors
74    #[error("Insufficient coin balance for operation.")]
75    InsufficientCoinBalance,
76    #[error("The coin balance overflows u64")]
77    CoinBalanceOverflow,
78
79    // Publish/Upgrade errors
80    #[error(
81        "Publish Error, Non-zero Address. \
82        The modules in the package must have their self-addresses set to zero."
83    )]
84    PublishErrorNonZeroAddress,
85
86    #[error(
87        "IOTA Move Bytecode Verification Error. \
88        Please run the IOTA Move Verifier for more information."
89    )]
90    IotaMoveVerificationError,
91
92    // Errors from the Move VM
93    //
94    // Indicates an error from a non-abort instruction
95    #[error(
96        "Move Primitive Runtime Error. Location: {0}. \
97        Arithmetic error, stack overflow, max value depth, etc."
98    )]
99    MovePrimitiveRuntimeError(MoveLocationOpt),
100    #[error("Move Runtime Abort. Location: {0}, Abort Code: {1}")]
101    MoveAbort(MoveLocation, u64),
102    #[error(
103        "Move Bytecode Verification Error. \
104        Please run the Bytecode Verifier for more information."
105    )]
106    VMVerificationOrDeserializationError,
107    #[error("MOVE VM INVARIANT VIOLATION.")]
108    VMInvariantViolation,
109
110    // Programmable Transaction Errors
111    #[error("Function Not Found.")]
112    FunctionNotFound,
113    #[error(
114        "Arity mismatch for Move function. \
115        The number of arguments does not match the number of parameters"
116    )]
117    ArityMismatch,
118    #[error(
119        "Type arity mismatch for Move function. \
120        Mismatch between the number of actual versus expected type arguments."
121    )]
122    TypeArityMismatch,
123    #[error("Non Entry Function Invoked. Move Call must start with an entry function")]
124    NonEntryFunctionInvoked,
125    #[error("Invalid command argument at {arg_idx}. {kind}")]
126    CommandArgumentError {
127        arg_idx: u16,
128        kind: CommandArgumentError,
129    },
130    #[error("Error for type argument at index {argument_idx}: {kind}")]
131    TypeArgumentError {
132        argument_idx: TypeParameterIndex,
133        kind: TypeArgumentError,
134    },
135    #[error(
136        "Unused result without the drop ability. \
137        Command result {result_idx}, return value {secondary_idx}"
138    )]
139    UnusedValueWithoutDrop { result_idx: u16, secondary_idx: u16 },
140    #[error(
141        "Invalid public Move function signature. \
142        Unsupported return type for return value {idx}"
143    )]
144    InvalidPublicFunctionReturnType { idx: u16 },
145    #[error("Invalid Transfer Object, object does not have public transfer.")]
146    InvalidTransferObject,
147
148    // Post-execution errors
149    //
150    // Indicates the effects from the transaction are too large
151    #[error(
152        "Effects of size {current_size} bytes too large. \
153    Limit is {max_size} bytes"
154    )]
155    EffectsTooLarge { current_size: u64, max_size: u64 },
156
157    #[error(
158        "Publish/Upgrade Error, Missing dependency. \
159         A dependency of a published or upgraded package has not been assigned an on-chain \
160         address."
161    )]
162    PublishUpgradeMissingDependency,
163
164    #[error(
165        "Publish/Upgrade Error, Dependency downgrade. \
166         Indirect (transitive) dependency of published or upgraded package has been assigned an \
167         on-chain version that is less than the version required by one of the package's \
168         transitive dependencies."
169    )]
170    PublishUpgradeDependencyDowngrade,
171
172    #[error("Invalid package upgrade. {upgrade_error}")]
173    PackageUpgradeError { upgrade_error: PackageUpgradeError },
174
175    // Indicates the transaction tried to write objects too large to storage
176    #[error(
177        "Written objects of {current_size} bytes too large. \
178    Limit is {max_size} bytes"
179    )]
180    WrittenObjectsTooLarge { current_size: u64, max_size: u64 },
181
182    #[error("Certificate is on the deny list")]
183    CertificateDenied,
184
185    #[error(
186        "IOTA Move Bytecode Verification Timeout. \
187        Please run the IOTA Move Verifier for more information."
188    )]
189    IotaMoveVerificationTimeout,
190
191    #[error("The shared object operation is not allowed.")]
192    SharedObjectOperationNotAllowed,
193
194    #[error("Certificate cannot be executed due to a dependency on a deleted shared object")]
195    InputObjectDeleted,
196
197    #[error("Certificate is cancelled due to congestion on shared objects: {congested_objects}")]
198    ExecutionCancelledDueToSharedObjectCongestion { congested_objects: CongestedObjects },
199
200    #[error("Address {address:?} is denied for coin {coin_type}")]
201    AddressDeniedForCoin {
202        address: IotaAddress,
203        coin_type: String,
204    },
205
206    #[error("Coin type is globally paused for use: {coin_type}")]
207    CoinTypeGlobalPause { coin_type: String },
208
209    #[error("Certificate is cancelled because randomness could not be generated this epoch")]
210    ExecutionCancelledDueToRandomnessUnavailable,
211    // NOTE: if you want to add a new enum,
212    // please add it at the end for Rust SDK backward compatibility.
213}
214
215#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Hash)]
216pub struct MoveLocation {
217    pub module: ModuleId,
218    pub function: u16,
219    pub instruction: CodeOffset,
220    pub function_name: Option<String>,
221}
222
223#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Hash)]
224pub struct MoveLocationOpt(pub Option<MoveLocation>);
225
226#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Hash, Error)]
227pub enum CommandArgumentError {
228    #[error("The type of the value does not match the expected type")]
229    TypeMismatch,
230    #[error("The argument cannot be deserialized into a value of the specified type")]
231    InvalidBCSBytes,
232    #[error("The argument cannot be instantiated from raw bytes")]
233    InvalidUsageOfPureArg,
234    #[error(
235        "Invalid argument to private entry function. \
236        These functions cannot take arguments from other Move functions"
237    )]
238    InvalidArgumentToPrivateEntryFunction,
239    #[error("Out of bounds access to input or result vector {idx}")]
240    IndexOutOfBounds { idx: u16 },
241    #[error(
242        "Out of bounds secondary access to result vector \
243        {result_idx} at secondary index {secondary_idx}"
244    )]
245    SecondaryIndexOutOfBounds { result_idx: u16, secondary_idx: u16 },
246    #[error(
247        "Invalid usage of result {result_idx}, \
248        expected a single result but found either no return values or multiple."
249    )]
250    InvalidResultArity { result_idx: u16 },
251    #[error(
252        "Invalid taking of the Gas coin. \
253        It can only be used by-value with TransferObjects"
254    )]
255    InvalidGasCoinUsage,
256    #[error(
257        "Invalid usage of value. \
258        Mutably borrowed values require unique usage. \
259        Immutably borrowed values cannot be taken or borrowed mutably. \
260        Taken values cannot be used again."
261    )]
262    InvalidValueUsage,
263    #[error("Immutable objects cannot be passed by-value.")]
264    InvalidObjectByValue,
265    #[error("Immutable objects cannot be passed by mutable reference, &mut.")]
266    InvalidObjectByMutRef,
267    #[error(
268        "Shared object operations such a wrapping, freezing, or converting to owned are not \
269        allowed."
270    )]
271    SharedObjectOperationNotAllowed,
272}
273
274#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Hash, Error)]
275pub enum PackageUpgradeError {
276    #[error("Unable to fetch package at {package_id}")]
277    UnableToFetchPackage { package_id: ObjectID },
278    #[error("Object {object_id} is not a package")]
279    NotAPackage { object_id: ObjectID },
280    #[error("New package is incompatible with previous version")]
281    IncompatibleUpgrade,
282    #[error("Digest in upgrade ticket and computed digest disagree")]
283    DigestDoesNotMatch { digest: Vec<u8> },
284    #[error("Upgrade policy {policy} is not a valid upgrade policy")]
285    UnknownUpgradePolicy { policy: u8 },
286    #[error("Package ID {package_id} does not match package ID in upgrade ticket {ticket_id}")]
287    PackageIDDoesNotMatch {
288        package_id: ObjectID,
289        ticket_id: ObjectID,
290    },
291}
292
293#[derive(Eq, PartialEq, Clone, Copy, Debug, Serialize, Deserialize, Hash, Error)]
294pub enum TypeArgumentError {
295    #[error("A type was not found in the module specified.")]
296    TypeNotFound,
297    #[error("A type provided did not match the specified constraints.")]
298    ConstraintNotSatisfied,
299}
300
301impl ExecutionFailureStatus {
302    pub fn command_argument_error(kind: CommandArgumentError, arg_idx: u16) -> Self {
303        Self::CommandArgumentError { arg_idx, kind }
304    }
305}
306
307impl Display for MoveLocationOpt {
308    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
309        match &self.0 {
310            None => write!(f, "UNKNOWN"),
311            Some(l) => write!(f, "{l}"),
312        }
313    }
314}
315
316impl Display for MoveLocation {
317    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
318        let Self {
319            module,
320            function,
321            instruction,
322            function_name,
323        } = self;
324        if let Some(fname) = function_name {
325            write!(
326                f,
327                "{module}::{fname} (function index {function}) at offset {instruction}"
328            )
329        } else {
330            write!(
331                f,
332                "{module} in function definition {function} at offset {instruction}"
333            )
334        }
335    }
336}
337
338impl ExecutionStatus {
339    pub fn new_failure(
340        error: ExecutionFailureStatus,
341        command: Option<CommandIndex>,
342    ) -> ExecutionStatus {
343        ExecutionStatus::Failure { error, command }
344    }
345
346    pub fn is_ok(&self) -> bool {
347        matches!(self, ExecutionStatus::Success)
348    }
349
350    pub fn is_err(&self) -> bool {
351        matches!(self, ExecutionStatus::Failure { .. })
352    }
353
354    pub fn unwrap(&self) {
355        match self {
356            ExecutionStatus::Success => {}
357            ExecutionStatus::Failure { .. } => {
358                panic!("Unable to unwrap() on {:?}", self);
359            }
360        }
361    }
362
363    pub fn unwrap_err(self) -> (ExecutionFailureStatus, Option<CommandIndex>) {
364        match self {
365            ExecutionStatus::Success => {
366                panic!("Unable to unwrap() on {:?}", self);
367            }
368            ExecutionStatus::Failure { error, command } => (error, command),
369        }
370    }
371}
372
373pub type CommandIndex = usize;