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