Skip to main content

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