iota_types/
error.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// Modifications Copyright (c) 2024 IOTA Stiftung
4// SPDX-License-Identifier: Apache-2.0
5
6use std::{collections::BTreeMap, fmt::Debug};
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10use strum::{AsRefStr, IntoStaticStr};
11use thiserror::Error;
12use tonic::Status;
13use typed_store_error::TypedStoreError;
14
15use crate::{
16    base_types::*,
17    committee::{Committee, EpochId, StakeUnit},
18    digests::CheckpointContentsDigest,
19    execution_status::CommandArgumentError,
20    messages_checkpoint::CheckpointSequenceNumber,
21    object::Owner,
22};
23
24pub const TRANSACTION_NOT_FOUND_MSG_PREFIX: &str = "Could not find the referenced transaction";
25pub const TRANSACTIONS_NOT_FOUND_MSG_PREFIX: &str = "Could not find the referenced transactions";
26
27#[macro_export]
28macro_rules! fp_bail {
29    ($e:expr) => {
30        return Err($e)
31    };
32}
33
34#[macro_export(local_inner_macros)]
35macro_rules! fp_ensure {
36    ($cond:expr, $e:expr) => {
37        if !($cond) {
38            fp_bail!($e);
39        }
40    };
41}
42pub(crate) use fp_ensure;
43
44use crate::{
45    digests::TransactionEventsDigest,
46    execution_status::{CommandIndex, ExecutionFailureStatus},
47};
48
49#[macro_export]
50macro_rules! exit_main {
51    ($result:expr) => {
52        match $result {
53            Ok(_) => (),
54            Err(err) => {
55                let err = format!("{:?}", err);
56                println!("{}", err.bold().red());
57                std::process::exit(1);
58            }
59        }
60    };
61}
62
63#[macro_export]
64macro_rules! make_invariant_violation {
65    ($($args:expr),* $(,)?) => {{
66        if cfg!(debug_assertions) {
67            panic!($($args),*)
68        }
69        ExecutionError::invariant_violation(format!($($args),*))
70    }}
71}
72
73#[macro_export]
74macro_rules! invariant_violation {
75    ($($args:expr),* $(,)?) => {
76        return Err(make_invariant_violation!($($args),*).into())
77    };
78}
79
80#[macro_export]
81macro_rules! assert_invariant {
82    ($cond:expr, $($args:expr),* $(,)?) => {{
83        if !$cond {
84            invariant_violation!($($args),*)
85        }
86    }};
87}
88
89#[derive(
90    Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, Hash, AsRefStr, IntoStaticStr,
91)]
92pub enum UserInputError {
93    #[error("Mutable object {object_id} cannot appear more than one in one transaction")]
94    MutableObjectUsedMoreThanOnce { object_id: ObjectID },
95    #[error("Wrong number of parameters for the transaction")]
96    ObjectInputArityViolation,
97    #[error(
98        "Could not find the referenced object {:?} at version {:?}",
99        object_id,
100        version
101    )]
102    ObjectNotFound {
103        object_id: ObjectID,
104        version: Option<SequenceNumber>,
105    },
106    #[error(
107        "Object ID {} Version {} Digest {} is not available for consumption, current version: {current_version}",
108        .provided_obj_ref.0, .provided_obj_ref.1, .provided_obj_ref.2
109    )]
110    ObjectVersionUnavailableForConsumption {
111        provided_obj_ref: ObjectRef,
112        current_version: SequenceNumber,
113    },
114    #[error("Package verification failed: {err:?}")]
115    PackageVerificationTimedout { err: String },
116    #[error("Dependent package not found on-chain: {package_id:?}")]
117    DependentPackageNotFound { package_id: ObjectID },
118    #[error("Mutable parameter provided, immutable parameter expected")]
119    ImmutableParameterExpected { object_id: ObjectID },
120    #[error("Size limit exceeded: {limit} is {value}")]
121    SizeLimitExceeded { limit: String, value: String },
122    #[error(
123        "Object {child_id:?} is owned by object {parent_id:?}. \
124        Objects owned by other objects cannot be used as input arguments"
125    )]
126    InvalidChildObjectArgument {
127        child_id: ObjectID,
128        parent_id: ObjectID,
129    },
130    #[error(
131        "Invalid Object digest for object {object_id:?}. Expected digest : {expected_digest:?}"
132    )]
133    InvalidObjectDigest {
134        object_id: ObjectID,
135        expected_digest: ObjectDigest,
136    },
137    #[error("Sequence numbers above the maximal value are not usable for transfers")]
138    InvalidSequenceNumber,
139    #[error("A move object is expected, instead a move package is passed: {object_id}")]
140    MovePackageAsObject { object_id: ObjectID },
141    #[error("A move package is expected, instead a move object is passed: {object_id}")]
142    MoveObjectAsPackage { object_id: ObjectID },
143    #[error("Transaction was not signed by the correct sender: {}", error)]
144    IncorrectUserSignature { error: String },
145
146    #[error("Object used as shared is not shared")]
147    NotSharedObject,
148    #[error("The transaction inputs contain duplicated ObjectRef's")]
149    DuplicateObjectRefInput,
150
151    // Gas related errors
152    #[error("Transaction gas payment missing")]
153    MissingGasPayment,
154    #[error("Gas object is not an owned object with owner: {:?}", owner)]
155    GasObjectNotOwnedObject { owner: Owner },
156    #[error("Gas budget: {:?} is higher than max: {:?}", gas_budget, max_budget)]
157    GasBudgetTooHigh { gas_budget: u64, max_budget: u64 },
158    #[error("Gas budget: {:?} is lower than min: {:?}", gas_budget, min_budget)]
159    GasBudgetTooLow { gas_budget: u64, min_budget: u64 },
160    #[error(
161        "Balance of gas object {:?} is lower than the needed amount: {:?}",
162        gas_balance,
163        needed_gas_amount
164    )]
165    GasBalanceTooLow {
166        gas_balance: u128,
167        needed_gas_amount: u128,
168    },
169    #[error("Transaction kind does not support Sponsored Transaction")]
170    UnsupportedSponsoredTransactionKind,
171    #[error(
172        "Gas price {:?} under reference gas price (RGP) {:?}",
173        gas_price,
174        reference_gas_price
175    )]
176    GasPriceUnderRGP {
177        gas_price: u64,
178        reference_gas_price: u64,
179    },
180    #[error("Gas price cannot exceed {:?} nanos", max_gas_price)]
181    GasPriceTooHigh { max_gas_price: u64 },
182    #[error("Object {object_id} is not a gas object")]
183    InvalidGasObject { object_id: ObjectID },
184    #[error("Gas object does not have enough balance to cover minimal gas spend")]
185    InsufficientBalanceToCoverMinimalGas,
186
187    #[error(
188        "Could not find the referenced object {:?} as the asked version {:?} is higher than the latest {:?}",
189        object_id,
190        asked_version,
191        latest_version
192    )]
193    ObjectSequenceNumberTooHigh {
194        object_id: ObjectID,
195        asked_version: SequenceNumber,
196        latest_version: SequenceNumber,
197    },
198    #[error("Object deleted at reference {:?}", object_ref)]
199    ObjectDeleted { object_ref: ObjectRef },
200    #[error("Invalid Batch Transaction: {}", error)]
201    InvalidBatchTransaction { error: String },
202    #[error("This Move function is currently disabled and not available for call")]
203    BlockedMoveFunction,
204    #[error("Empty input coins for Pay related transaction")]
205    EmptyInputCoins,
206
207    #[error(
208        "IOTA payment transactions use first input coin for gas payment, but found a different gas object"
209    )]
210    UnexpectedGasPaymentObject,
211
212    #[error("Wrong initial version given for shared object")]
213    SharedObjectStartingVersionMismatch,
214
215    #[error(
216        "Attempt to transfer object {object_id} that does not have public transfer. Object transfer must be done instead using a distinct Move function call"
217    )]
218    TransferObjectWithoutPublicTransfer { object_id: ObjectID },
219
220    #[error(
221        "TransferObjects, MergeCoin, and Publish cannot have empty arguments. \
222        If MakeMoveVec has empty arguments, it must have a type specified"
223    )]
224    EmptyCommandInput,
225
226    #[error("Transaction is denied: {}", error)]
227    TransactionDenied { error: String },
228
229    #[error("Feature is not supported: {0}")]
230    Unsupported(String),
231
232    #[error("Query transactions with move function input error: {0}")]
233    MoveFunctionInput(String),
234
235    #[error("Verified checkpoint not found for sequence number: {0}")]
236    VerifiedCheckpointNotFound(CheckpointSequenceNumber),
237
238    #[error("Verified checkpoint not found for digest: {0}")]
239    VerifiedCheckpointDigestNotFound(String),
240
241    #[error("Latest checkpoint sequence number not found")]
242    LatestCheckpointSequenceNumberNotFound,
243
244    #[error("Checkpoint contents not found for digest: {0}")]
245    CheckpointContentsNotFound(CheckpointContentsDigest),
246
247    #[error("Genesis transaction not found")]
248    GenesisTransactionNotFound,
249
250    #[error("Transaction {0} not found")]
251    TransactionCursorNotFound(u64),
252
253    #[error(
254        "Object {:?} is a system object and cannot be accessed by user transactions",
255        object_id
256    )]
257    InaccessibleSystemObject { object_id: ObjectID },
258    #[error(
259        "{max_publish_commands} max publish/upgrade commands allowed, {publish_count} provided"
260    )]
261    MaxPublishCountExceeded {
262        max_publish_commands: u64,
263        publish_count: u64,
264    },
265
266    #[error("Immutable parameter provided, mutable parameter expected")]
267    MutableParameterExpected { object_id: ObjectID },
268
269    #[error("Address {address:?} is denied for coin {coin_type}")]
270    AddressDeniedForCoin {
271        address: IotaAddress,
272        coin_type: String,
273    },
274
275    #[error("Commands following a command with Random can only be TransferObjects or MergeCoins")]
276    PostRandomCommandRestrictions,
277
278    // Soft Bundle related errors
279    #[error(
280        "Number of transactions exceeds the maximum allowed ({:?}) in a Soft Bundle",
281        limit
282    )]
283    TooManyTransactionsInSoftBundle { limit: u64 },
284    #[error(
285        "Total transactions size ({:?})bytes exceeds the maximum allowed ({:?})bytes in a Soft Bundle",
286        size,
287        limit
288    )]
289    SoftBundleTooLarge { size: u64, limit: u64 },
290    #[error("Transaction {:?} in Soft Bundle contains no shared objects", digest)]
291    NoSharedObject { digest: TransactionDigest },
292    #[error("Transaction {:?} in Soft Bundle has already been executed", digest)]
293    AlreadyExecuted { digest: TransactionDigest },
294    #[error("At least one certificate in Soft Bundle has already been processed")]
295    CertificateAlreadyProcessed,
296    #[error(
297        "Gas price for transaction {:?} in Soft Bundle mismatch: want {:?}, have {:?}",
298        digest,
299        expected,
300        actual
301    )]
302    GasPriceMismatch {
303        digest: TransactionDigest,
304        expected: u64,
305        actual: u64,
306    },
307
308    #[error("Coin type is globally paused for use: {coin_type}")]
309    CoinTypeGlobalPause { coin_type: String },
310}
311
312#[derive(
313    Eq,
314    PartialEq,
315    Clone,
316    Debug,
317    Serialize,
318    Deserialize,
319    Hash,
320    AsRefStr,
321    IntoStaticStr,
322    JsonSchema,
323    Error,
324)]
325#[serde(tag = "code", rename = "ObjectResponseError", rename_all = "camelCase")]
326pub enum IotaObjectResponseError {
327    #[error("Object {:?} does not exist", object_id)]
328    NotExists { object_id: ObjectID },
329    #[error("Cannot find dynamic field for parent object {:?}", parent_object_id)]
330    DynamicFieldNotFound { parent_object_id: ObjectID },
331    #[error(
332        "Object has been deleted object_id: {:?} at version: {:?} in digest {:?}",
333        object_id,
334        version,
335        digest
336    )]
337    Deleted {
338        object_id: ObjectID,
339        /// Object version.
340        version: SequenceNumber,
341        /// Base64 string representing the object digest
342        digest: ObjectDigest,
343    },
344    #[error("Unknown Error")]
345    Unknown,
346    #[error("Display Error: {:?}", error)]
347    Display { error: String },
348    // TODO: also integrate IotaPastObjectResponse (VersionNotFound,  VersionTooHigh)
349}
350
351/// Custom error type for Iota.
352#[derive(
353    Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, Hash, AsRefStr, IntoStaticStr,
354)]
355pub enum IotaError {
356    #[error("Error checking transaction input objects: {:?}", error)]
357    UserInput { error: UserInputError },
358
359    #[error("Error checking transaction object: {:?}", error)]
360    IotaObjectResponse { error: IotaObjectResponseError },
361
362    #[error("Expecting a single owner, shared ownership found")]
363    UnexpectedOwnerType,
364
365    #[error("There are already {queue_len} transactions pending, above threshold of {threshold}")]
366    TooManyTransactionsPendingExecution { queue_len: usize, threshold: usize },
367
368    #[error("There are too many transactions pending in consensus")]
369    TooManyTransactionsPendingConsensus,
370
371    #[error(
372        "Input {object_id} already has {queue_len} transactions pending, above threshold of {threshold}"
373    )]
374    TooManyTransactionsPendingOnObject {
375        object_id: ObjectID,
376        queue_len: usize,
377        threshold: usize,
378    },
379
380    #[error(
381        "Input {object_id} has a transaction {txn_age_sec} seconds old pending, above threshold of {threshold} seconds"
382    )]
383    TooOldTransactionPendingOnObject {
384        object_id: ObjectID,
385        txn_age_sec: u64,
386        threshold: u64,
387    },
388
389    #[error("Soft bundle must only contain transactions of UserTransaction kind")]
390    InvalidTxKindInSoftBundle,
391
392    // Signature verification
393    #[error("Signature is not valid: {}", error)]
394    InvalidSignature { error: String },
395    #[error("Required Signature from {expected} is absent {:?}", actual)]
396    SignerSignatureAbsent {
397        expected: String,
398        actual: Vec<String>,
399    },
400    #[error("Expect {expected} signer signatures but got {actual}")]
401    SignerSignatureNumberMismatch { expected: usize, actual: usize },
402    #[error("Value was not signed by the correct sender: {}", error)]
403    IncorrectSigner { error: String },
404    #[error(
405        "Value was not signed by a known authority. signer: {:?}, index: {:?}, committee: {committee}",
406        signer,
407        index
408    )]
409    UnknownSigner {
410        signer: Option<String>,
411        index: Option<u32>,
412        committee: Box<Committee>,
413    },
414    #[error(
415        "Validator {:?} responded multiple signatures for the same message, conflicting: {:?}",
416        signer,
417        conflicting_sig
418    )]
419    StakeAggregatorRepeatedSigner {
420        signer: AuthorityName,
421        conflicting_sig: bool,
422    },
423    // TODO: Used for distinguishing between different occurrences of invalid signatures, to allow
424    // retries in some cases.
425    #[error(
426        "Signature is not valid, but a retry may result in a valid one: {}",
427        error
428    )]
429    PotentiallyTemporarilyInvalidSignature { error: String },
430
431    // Certificate verification and execution
432    #[error(
433        "Signature or certificate from wrong epoch, expected {expected_epoch}, got {actual_epoch}"
434    )]
435    WrongEpoch {
436        expected_epoch: EpochId,
437        actual_epoch: EpochId,
438    },
439    #[error("Signatures in a certificate must form a quorum")]
440    CertificateRequiresQuorum,
441    #[error("Transaction certificate processing failed: {err}")]
442    ErrorWhileProcessingCertificate { err: String },
443    #[error(
444        "Failed to get a quorum of signed effects when processing transaction: {effects_map:?}"
445    )]
446    QuorumFailedToGetEffectsQuorumWhenProcessingTransaction {
447        effects_map: BTreeMap<TransactionEffectsDigest, (Vec<AuthorityName>, StakeUnit)>,
448    },
449    #[error(
450        "Failed to verify Tx certificate with executed effects, error: {error:?}, validator: {validator_name:?}"
451    )]
452    FailedToVerifyTxCertWithExecutedEffects {
453        validator_name: AuthorityName,
454        error: String,
455    },
456    #[error("Transaction is already finalized but with different user signatures")]
457    TxAlreadyFinalizedWithDifferentUserSigs,
458
459    // Account access
460    #[error("Invalid authenticator")]
461    InvalidAuthenticator,
462    #[error("Invalid address")]
463    InvalidAddress,
464    #[error("Invalid transaction digest.")]
465    InvalidTransactionDigest,
466
467    #[error("Invalid digest length. Expected {expected}, got {actual}")]
468    InvalidDigestLength { expected: usize, actual: usize },
469    #[error("Invalid DKG message size")]
470    InvalidDkgMessageSize,
471
472    #[error("Unexpected message.")]
473    UnexpectedMessage,
474
475    // Move module publishing related errors
476    #[error("Failed to verify the Move module, reason: {error:?}.")]
477    ModuleVerificationFailure { error: String },
478    #[error("Failed to deserialize the Move module, reason: {error:?}.")]
479    ModuleDeserializationFailure { error: String },
480    #[error("Failed to publish the Move module(s), reason: {error}")]
481    ModulePublishFailure { error: String },
482    #[error("Failed to build Move modules: {error}.")]
483    ModuleBuildFailure { error: String },
484
485    // Move call related errors
486    #[error("Function resolution failure: {error:?}.")]
487    FunctionNotFound { error: String },
488    #[error("Module not found in package: {module_name:?}.")]
489    ModuleNotFound { module_name: String },
490    #[error("Type error while binding function arguments: {error:?}.")]
491    Type { error: String },
492    #[error("Circular object ownership detected")]
493    CircularObjectOwnership,
494
495    // Internal state errors
496    #[error("Attempt to re-initialize a transaction lock for objects {:?}.", refs)]
497    ObjectLockAlreadyInitialized { refs: Vec<ObjectRef> },
498    #[error(
499        "Object {obj_ref:?} already locked by a different transaction: {pending_transaction:?}"
500    )]
501    ObjectLockConflict {
502        obj_ref: ObjectRef,
503        pending_transaction: TransactionDigest,
504    },
505    #[error(
506        "Objects {obj_refs:?} are already locked by a transaction from a future epoch {locked_epoch:?}), attempt to override with a transaction from epoch {new_epoch:?}"
507    )]
508    ObjectLockedAtFutureEpoch {
509        obj_refs: Vec<ObjectRef>,
510        locked_epoch: EpochId,
511        new_epoch: EpochId,
512        locked_by_tx: TransactionDigest,
513    },
514    #[error("{TRANSACTION_NOT_FOUND_MSG_PREFIX} [{:?}].", digest)]
515    TransactionNotFound { digest: TransactionDigest },
516    #[error("{TRANSACTIONS_NOT_FOUND_MSG_PREFIX} [{:?}].", digests)]
517    TransactionsNotFound { digests: Vec<TransactionDigest> },
518    #[error("Could not find the referenced transaction events [{digest:?}].")]
519    TransactionEventsNotFound { digest: TransactionEventsDigest },
520    #[error(
521        "Attempt to move to `Executed` state an transaction that has already been executed: {:?}.",
522        digest
523    )]
524    TransactionAlreadyExecuted { digest: TransactionDigest },
525    #[error("Object ID did not have the expected type")]
526    BadObjectType { error: String },
527    #[error("Fail to retrieve Object layout for {st}")]
528    FailObjectLayout { st: String },
529
530    #[error("Execution invariant violated")]
531    ExecutionInvariantViolation,
532    #[error("Validator {authority:?} is faulty in a Byzantine manner: {reason:?}")]
533    ByzantineAuthoritySuspicion {
534        authority: AuthorityName,
535        reason: String,
536    },
537    #[error(
538        "Attempted to access {object} through parent {given_parent}, \
539        but it's actual parent is {actual_owner}"
540    )]
541    InvalidChildObjectAccess {
542        object: ObjectID,
543        given_parent: ObjectID,
544        actual_owner: Owner,
545    },
546
547    #[error("Authority Error: {error:?}")]
548    GenericAuthority { error: String },
549
550    #[error("Failed to dispatch subscription: {error:?}")]
551    FailedToDispatchSubscription { error: String },
552
553    #[error("Failed to serialize Owner: {error:?}")]
554    OwnerFailedToSerialize { error: String },
555
556    #[error("Failed to deserialize fields into JSON: {error:?}")]
557    ExtraFieldFailedToDeserialize { error: String },
558
559    #[error("Failed to execute transaction locally by Orchestrator: {error:?}")]
560    TransactionOrchestratorLocalExecution { error: String },
561
562    // Errors returned by authority and client read API's
563    #[error("Failure serializing transaction in the requested format: {:?}", error)]
564    TransactionSerialization { error: String },
565    #[error("Failure serializing object in the requested format: {:?}", error)]
566    ObjectSerialization { error: String },
567    #[error("Failure deserializing object in the requested format: {:?}", error)]
568    ObjectDeserialization { error: String },
569    #[error("Event store component is not active on this node")]
570    NoEventStore,
571
572    // Client side error
573    #[error("Too many authority errors were detected for {}: {:?}", action, errors)]
574    TooManyIncorrectAuthorities {
575        errors: Vec<(AuthorityName, IotaError)>,
576        action: String,
577    },
578    #[error("Invalid transaction range query to the fullnode: {:?}", error)]
579    FullNodeInvalidTxRangeQuery { error: String },
580
581    // Errors related to the authority-consensus interface.
582    #[error("Failed to submit transaction to consensus: {0}")]
583    FailedToSubmitToConsensus(String),
584    #[error("Failed to connect with consensus node: {0}")]
585    ConsensusConnectionBroken(String),
586    #[error("Failed to execute handle_consensus_transaction on Iota: {0}")]
587    HandleConsensusTransactionFailure(String),
588
589    // Cryptography errors.
590    #[error("Signature key generation error: {0}")]
591    SignatureKeyGen(String),
592    #[error("Key Conversion Error: {0}")]
593    KeyConversion(String),
594    #[error("Invalid Private Key provided")]
595    InvalidPrivateKey,
596
597    // Unsupported Operations on Fullnode
598    #[error("Fullnode does not support handle_certificate")]
599    FullNodeCantHandleCertificate,
600
601    // Epoch related errors.
602    #[error("Validator temporarily stopped processing transactions due to epoch change")]
603    ValidatorHaltedAtEpochEnd,
604    #[error("Operations for epoch {0} have ended")]
605    EpochEnded(EpochId),
606    #[error("Error when advancing epoch: {:?}", error)]
607    AdvanceEpoch { error: String },
608
609    #[error("Transaction Expired")]
610    TransactionExpired,
611
612    // These are errors that occur when an RPC fails and is simply the utf8 message sent in a
613    // Tonic::Status
614    #[error("{1} - {0}")]
615    Rpc(String, String),
616
617    #[error("Method not allowed")]
618    InvalidRpcMethod,
619
620    // TODO: We should fold this into UserInputError::Unsupported.
621    #[error("Use of disabled feature: {:?}", error)]
622    UnsupportedFeature { error: String },
623
624    #[error("Unable to communicate with the Quorum Driver channel: {:?}", error)]
625    QuorumDriverCommunication { error: String },
626
627    #[error("Operation timed out")]
628    Timeout,
629
630    #[error("Error executing {0}")]
631    Execution(String),
632
633    #[error("Invalid committee composition")]
634    InvalidCommittee(String),
635
636    #[error("Missing committee information for epoch {0}")]
637    MissingCommitteeAtEpoch(EpochId),
638
639    #[error("Index store not available on this Fullnode.")]
640    IndexStoreNotAvailable,
641
642    #[error("Failed to read dynamic field from table in the object store: {0}")]
643    DynamicFieldRead(String),
644
645    #[error("Failed to read or deserialize system state related data structures on-chain: {0}")]
646    IotaSystemStateRead(String),
647
648    #[error("Unexpected version error: {0}")]
649    UnexpectedVersion(String),
650
651    #[error("Message version is not supported at the current protocol version: {error}")]
652    WrongMessageVersion { error: String },
653
654    #[error("unknown error: {0}")]
655    Unknown(String),
656
657    #[error("Failed to perform file operation: {0}")]
658    FileIO(String),
659
660    #[error("Failed to get JWK")]
661    JWKRetrieval,
662
663    #[error("Storage error: {0}")]
664    Storage(String),
665
666    #[error(
667        "Validator cannot handle the request at the moment. Please retry after at least {retry_after_secs} seconds."
668    )]
669    ValidatorOverloadedRetryAfter { retry_after_secs: u64 },
670
671    #[error("Too many requests")]
672    TooManyRequests,
673
674    #[error("The request did not contain a certificate")]
675    NoCertificateProvided,
676}
677
678#[repr(u64)]
679#[expect(non_camel_case_types)]
680#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
681/// Sub-status codes for the `UNKNOWN_VERIFICATION_ERROR` VM Status Code which
682/// provides more context TODO: add more Vm Status errors. We use
683/// `UNKNOWN_VERIFICATION_ERROR` as a catchall for now.
684pub enum VMMVerifierErrorSubStatusCode {
685    MULTIPLE_RETURN_VALUES_NOT_ALLOWED = 0,
686    INVALID_OBJECT_CREATION = 1,
687}
688
689#[repr(u64)]
690#[expect(non_camel_case_types)]
691#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
692/// Sub-status codes for the `MEMORY_LIMIT_EXCEEDED` VM Status Code which
693/// provides more context
694pub enum VMMemoryLimitExceededSubStatusCode {
695    EVENT_COUNT_LIMIT_EXCEEDED = 0,
696    EVENT_SIZE_LIMIT_EXCEEDED = 1,
697    NEW_ID_COUNT_LIMIT_EXCEEDED = 2,
698    DELETED_ID_COUNT_LIMIT_EXCEEDED = 3,
699    TRANSFER_ID_COUNT_LIMIT_EXCEEDED = 4,
700    OBJECT_RUNTIME_CACHE_LIMIT_EXCEEDED = 5,
701    OBJECT_RUNTIME_STORE_LIMIT_EXCEEDED = 6,
702    TOTAL_EVENT_SIZE_LIMIT_EXCEEDED = 7,
703}
704
705pub type IotaResult<T = ()> = Result<T, IotaError>;
706pub type UserInputResult<T = ()> = Result<T, UserInputError>;
707
708impl From<iota_protocol_config::Error> for IotaError {
709    fn from(error: iota_protocol_config::Error) -> Self {
710        IotaError::WrongMessageVersion { error: error.0 }
711    }
712}
713
714impl From<ExecutionError> for IotaError {
715    fn from(error: ExecutionError) -> Self {
716        IotaError::Execution(error.to_string())
717    }
718}
719
720impl From<Status> for IotaError {
721    fn from(status: Status) -> Self {
722        if status.message() == "Too many requests" {
723            return Self::TooManyRequests;
724        }
725        let result = bcs::from_bytes::<IotaError>(status.details());
726        if let Ok(iota_error) = result {
727            iota_error
728        } else {
729            Self::Rpc(
730                status.message().to_owned(),
731                status.code().description().to_owned(),
732            )
733        }
734    }
735}
736
737impl From<TypedStoreError> for IotaError {
738    fn from(e: TypedStoreError) -> Self {
739        Self::Storage(e.to_string())
740    }
741}
742
743impl From<crate::storage::error::Error> for IotaError {
744    fn from(e: crate::storage::error::Error) -> Self {
745        Self::Storage(e.to_string())
746    }
747}
748
749impl From<IotaError> for Status {
750    fn from(error: IotaError) -> Self {
751        let bytes = bcs::to_bytes(&error).unwrap();
752        Status::with_details(tonic::Code::Internal, error.to_string(), bytes.into())
753    }
754}
755
756impl From<ExecutionErrorKind> for IotaError {
757    fn from(kind: ExecutionErrorKind) -> Self {
758        ExecutionError::from_kind(kind).into()
759    }
760}
761
762impl From<&str> for IotaError {
763    fn from(error: &str) -> Self {
764        IotaError::GenericAuthority {
765            error: error.to_string(),
766        }
767    }
768}
769
770impl From<String> for IotaError {
771    fn from(error: String) -> Self {
772        IotaError::GenericAuthority { error }
773    }
774}
775
776impl TryFrom<IotaError> for UserInputError {
777    type Error = anyhow::Error;
778
779    fn try_from(err: IotaError) -> Result<Self, Self::Error> {
780        match err {
781            IotaError::UserInput { error } => Ok(error),
782            other => anyhow::bail!("error {:?} is not UserInput", other),
783        }
784    }
785}
786
787impl From<UserInputError> for IotaError {
788    fn from(error: UserInputError) -> Self {
789        IotaError::UserInput { error }
790    }
791}
792
793impl From<IotaObjectResponseError> for IotaError {
794    fn from(error: IotaObjectResponseError) -> Self {
795        IotaError::IotaObjectResponse { error }
796    }
797}
798
799impl IotaError {
800    pub fn individual_error_indicates_epoch_change(&self) -> bool {
801        matches!(
802            self,
803            IotaError::ValidatorHaltedAtEpochEnd | IotaError::MissingCommitteeAtEpoch(_)
804        )
805    }
806
807    /// Returns if the error is retryable and if the error's retryability is
808    /// explicitly categorized.
809    /// There should be only a handful of retryable errors. For now we list
810    /// common non-retryable error below to help us find more retryable
811    /// errors in logs.
812    pub fn is_retryable(&self) -> (bool, bool) {
813        let retryable = match self {
814            IotaError::Rpc { .. } => true,
815
816            // Reconfig error
817            IotaError::ValidatorHaltedAtEpochEnd => true,
818            IotaError::MissingCommitteeAtEpoch(..) => true,
819            IotaError::WrongEpoch { .. } => true,
820            IotaError::EpochEnded { .. } => true,
821
822            IotaError::UserInput { error } => {
823                match error {
824                    // Only ObjectNotFound and DependentPackageNotFound is potentially retryable
825                    UserInputError::ObjectNotFound { .. } => true,
826                    UserInputError::DependentPackageNotFound { .. } => true,
827                    _ => false,
828                }
829            }
830
831            IotaError::PotentiallyTemporarilyInvalidSignature { .. } => true,
832
833            // Overload errors
834            IotaError::TooManyTransactionsPendingExecution { .. } => true,
835            IotaError::TooManyTransactionsPendingOnObject { .. } => true,
836            IotaError::TooOldTransactionPendingOnObject { .. } => true,
837            IotaError::TooManyTransactionsPendingConsensus => true,
838            IotaError::ValidatorOverloadedRetryAfter { .. } => true,
839
840            // Non retryable error
841            IotaError::Execution(..) => false,
842            IotaError::ByzantineAuthoritySuspicion { .. } => false,
843            IotaError::QuorumFailedToGetEffectsQuorumWhenProcessingTransaction { .. } => false,
844            IotaError::TxAlreadyFinalizedWithDifferentUserSigs => false,
845            IotaError::FailedToVerifyTxCertWithExecutedEffects { .. } => false,
846            IotaError::ObjectLockConflict { .. } => false,
847
848            // NB: This is not an internal overload, but instead an imposed rate
849            // limit / blocking of a client. It must be non-retryable otherwise
850            // we will make the threat worse through automatic retries.
851            IotaError::TooManyRequests => false,
852
853            // For all un-categorized errors, return here with categorized = false.
854            _ => return (false, false),
855        };
856
857        (retryable, true)
858    }
859
860    pub fn is_object_or_package_not_found(&self) -> bool {
861        match self {
862            IotaError::UserInput { error } => {
863                matches!(
864                    error,
865                    UserInputError::ObjectNotFound { .. }
866                        | UserInputError::DependentPackageNotFound { .. }
867                )
868            }
869            _ => false,
870        }
871    }
872
873    pub fn is_overload(&self) -> bool {
874        matches!(
875            self,
876            IotaError::TooManyTransactionsPendingExecution { .. }
877                | IotaError::TooManyTransactionsPendingOnObject { .. }
878                | IotaError::TooOldTransactionPendingOnObject { .. }
879                | IotaError::TooManyTransactionsPendingConsensus
880        )
881    }
882
883    pub fn is_retryable_overload(&self) -> bool {
884        matches!(self, IotaError::ValidatorOverloadedRetryAfter { .. })
885    }
886
887    pub fn retry_after_secs(&self) -> u64 {
888        match self {
889            IotaError::ValidatorOverloadedRetryAfter { retry_after_secs } => *retry_after_secs,
890            _ => 0,
891        }
892    }
893}
894
895impl Ord for IotaError {
896    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
897        Ord::cmp(self.as_ref(), other.as_ref())
898    }
899}
900
901impl PartialOrd for IotaError {
902    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
903        Some(self.cmp(other))
904    }
905}
906
907type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
908
909pub type ExecutionErrorKind = ExecutionFailureStatus;
910
911#[derive(Debug)]
912pub struct ExecutionError {
913    inner: Box<ExecutionErrorInner>,
914}
915
916#[derive(Debug)]
917struct ExecutionErrorInner {
918    kind: ExecutionErrorKind,
919    source: Option<BoxError>,
920    command: Option<CommandIndex>,
921}
922
923impl ExecutionError {
924    pub fn new(kind: ExecutionErrorKind, source: Option<BoxError>) -> Self {
925        Self {
926            inner: Box::new(ExecutionErrorInner {
927                kind,
928                source,
929                command: None,
930            }),
931        }
932    }
933
934    pub fn new_with_source<E: Into<BoxError>>(kind: ExecutionErrorKind, source: E) -> Self {
935        Self::new(kind, Some(source.into()))
936    }
937
938    pub fn invariant_violation<E: Into<BoxError>>(source: E) -> Self {
939        Self::new_with_source(ExecutionFailureStatus::InvariantViolation, source)
940    }
941
942    pub fn with_command_index(mut self, command: CommandIndex) -> Self {
943        self.inner.command = Some(command);
944        self
945    }
946
947    pub fn from_kind(kind: ExecutionErrorKind) -> Self {
948        Self::new(kind, None)
949    }
950
951    pub fn kind(&self) -> &ExecutionErrorKind {
952        &self.inner.kind
953    }
954
955    pub fn command(&self) -> Option<CommandIndex> {
956        self.inner.command
957    }
958
959    pub fn source(&self) -> &Option<BoxError> {
960        &self.inner.source
961    }
962
963    pub fn to_execution_status(&self) -> (ExecutionFailureStatus, Option<CommandIndex>) {
964        (self.kind().clone(), self.command())
965    }
966}
967
968impl std::fmt::Display for ExecutionError {
969    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
970        write!(f, "ExecutionError: {:?}", self)
971    }
972}
973
974impl std::error::Error for ExecutionError {
975    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
976        self.inner.source.as_ref().map(|e| &**e as _)
977    }
978}
979
980impl From<ExecutionErrorKind> for ExecutionError {
981    fn from(kind: ExecutionErrorKind) -> Self {
982        Self::from_kind(kind)
983    }
984}
985
986pub fn command_argument_error(e: CommandArgumentError, arg_idx: usize) -> ExecutionError {
987    ExecutionError::from_kind(ExecutionErrorKind::command_argument_error(
988        e,
989        arg_idx as u16,
990    ))
991}