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    #[error(
381        "Invalid argument at command {command_idx}, argument {argument_idx}: index {index} is out of bounds"
382    )]
383    InvalidArgumentIndex {
384        command_idx: usize,
385        argument_idx: usize,
386        index: u16,
387    },
388}
389
390/// Custom error type for Iota.
391///
392/// WARNING: This enum is sent between nodes, and the code of a variant is its
393/// declaration index. Add new variants only at the very end of the enum, then
394/// re-run the unit tests and commit the updated variant-order snapshot from
395/// `tests/staged/` together with the change.
396///
397/// The same rules apply to enums embedded in variant fields, such as
398/// [`UserInputError`].
399#[cfg_attr(test, derive(iota_macros::EnumVariantOrder))]
400#[derive(
401    Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Error, Hash, AsRefStr, IntoStaticStr,
402)]
403pub enum IotaError {
404    #[error("Error checking transaction input objects: {error}")]
405    UserInput { error: UserInputError },
406
407    #[error("There are already {queue_len} transactions pending, above threshold of {threshold}")]
408    TooManyTransactionsPendingExecution { queue_len: usize, threshold: usize },
409
410    #[error("There are too many transactions pending in consensus")]
411    TooManyTransactionsPendingConsensus,
412
413    #[error(
414        "Input {object_id} already has {queue_len} transactions pending, above threshold of {threshold}"
415    )]
416    TooManyTransactionsPendingOnObject {
417        object_id: ObjectId,
418        queue_len: usize,
419        threshold: usize,
420    },
421
422    #[error(
423        "Input {object_id} has a transaction {txn_age_sec} seconds old pending, above threshold of {threshold} seconds"
424    )]
425    TooOldTransactionPendingOnObject {
426        object_id: ObjectId,
427        txn_age_sec: u64,
428        threshold: u64,
429    },
430
431    #[error("Soft bundle must only contain transactions of UserTransaction kind")]
432    InvalidTxKindInSoftBundle,
433
434    // Signature verification
435    #[error("Signature is not valid: {}", error)]
436    InvalidSignature { error: String },
437    #[error("Required Signature from {expected} is absent {actual:?}")]
438    SignerSignatureAbsent {
439        expected: String,
440        actual: Vec<String>,
441    },
442    #[error("Expect {expected} signer signatures but got {actual}")]
443    SignerSignatureNumberMismatch { expected: usize, actual: usize },
444    #[error("Value was not signed by the correct sender: {}", error)]
445    IncorrectSigner { error: String },
446    #[error(
447        "Value was not signed by a known authority. signer: {:?}, index: {:?}, committee: {committee}",
448        signer,
449        index
450    )]
451    UnknownSigner {
452        signer: Option<String>,
453        index: Option<u32>,
454        committee: Box<Committee>,
455    },
456    #[error(
457        "Validator {signer:?} responded multiple signatures for the same message, conflicting: {conflicting_sig}"
458    )]
459    StakeAggregatorRepeatedSigner {
460        signer: AuthorityName,
461        conflicting_sig: bool,
462    },
463    // TODO: Used for distinguishing between different occurrences of invalid signatures, to allow
464    // retries in some cases.
465    #[error("Signature is not valid, but a retry may result in a valid one: {error}")]
466    PotentiallyTemporarilyInvalidSignature { error: String },
467
468    // Certificate verification and execution
469    #[error(
470        "Signature or certificate from wrong epoch, expected {expected_epoch}, got {actual_epoch}"
471    )]
472    WrongEpoch {
473        expected_epoch: EpochId,
474        actual_epoch: EpochId,
475    },
476    #[error("Signatures in a certificate must form a quorum")]
477    CertificateRequiresQuorum,
478    #[error("Transaction certificate processing failed: {err}")]
479    // DEPRECATED: "local execution" was removed from fullnodes
480    ErrorWhileProcessingCertificate { err: String },
481    #[error(
482        "Failed to get a quorum of signed effects when processing transaction: {effects_map:?}"
483    )]
484    QuorumFailedToGetEffectsQuorumWhenProcessingTransaction {
485        effects_map: BTreeMap<TransactionEffectsDigest, (Vec<AuthorityName>, StakeUnit)>,
486    },
487    #[error(
488        "Failed to verify Tx certificate with executed effects, error: {error}, validator: {validator_name:?}"
489    )]
490    FailedToVerifyTxCertWithExecutedEffects {
491        validator_name: AuthorityName,
492        error: String,
493    },
494    #[error("Transaction is already finalized but with different user signatures")]
495    TxAlreadyFinalizedWithDifferentUserSigs,
496
497    // Account access
498    #[error("Invalid authenticator")]
499    InvalidAuthenticator,
500    #[error("Invalid address")]
501    InvalidAddress,
502    #[error("Invalid transaction digest")]
503    InvalidTransactionDigest,
504    #[error("Invalid move authentication digest")]
505    InvalidMoveAuthenticatorDigest,
506
507    #[error("Invalid digest length. Expected {expected}, got {actual}")]
508    InvalidDigestLength { expected: usize, actual: usize },
509    #[error("Invalid DKG message size")]
510    InvalidDkgMessageSize,
511
512    #[error("Unexpected message")]
513    UnexpectedMessage,
514
515    #[error("Failed to execute the Move authenticator, reason: {error}")]
516    MoveAuthenticatorExecutionFailure { error: String },
517
518    // Move module publishing related errors
519    #[error("Failed to verify the Move module, reason: {error}")]
520    ModuleVerificationFailure { error: String },
521    #[error("Failed to deserialize the Move module, reason: {error}")]
522    ModuleDeserializationFailure { error: String },
523    #[error("Failed to publish the Move module(s), reason: {error}")]
524    ModulePublishFailure { error: String },
525    #[error("Failed to build Move modules: {error}")]
526    ModuleBuildFailure { error: String },
527
528    // Move call related errors
529    #[error("Function resolution failure: {error}")]
530    FunctionNotFound { error: String },
531    #[error("Module not found in package: {module_name:?}")]
532    ModuleNotFound { module_name: String },
533    #[error("Type error while binding function arguments: {error}")]
534    Type { error: String },
535    #[error("Circular object ownership detected")]
536    CircularObjectOwnership,
537
538    // Internal state errors
539    #[error("Attempt to re-initialize a transaction lock for objects {refs:?}")]
540    ObjectLockAlreadyInitialized { refs: Vec<ObjectReference> },
541    #[error("Object {obj_ref:?} already locked by a different transaction: {pending_transaction}")]
542    ObjectLockConflict {
543        obj_ref: ObjectReference,
544        pending_transaction: TransactionDigest,
545    },
546    #[error(
547        "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:?}"
548    )]
549    ObjectLockedAtFutureEpoch {
550        obj_refs: Vec<ObjectReference>,
551        locked_epoch: EpochId,
552        new_epoch: EpochId,
553        locked_by_tx: TransactionDigest,
554    },
555    #[error("Transaction {digest:?} was recently submitted; duplicate resubmission suppressed")]
556    RecentlyResubmitted { digest: TransactionDigest },
557    #[error("{TRANSACTION_NOT_FOUND_MSG_PREFIX} [{digest}]")]
558    TransactionNotFound { digest: TransactionDigest },
559    #[error("{TRANSACTIONS_NOT_FOUND_MSG_PREFIX} [{digests:?}]")]
560    TransactionsNotFound { digests: Vec<TransactionDigest> },
561    #[error("Could not find the referenced transaction events [{digest}]")]
562    TransactionEventsNotFound { digest: TransactionDigest },
563    #[error(
564        "Attempt to move to `Executed` state an transaction that has already been executed: {digest}"
565    )]
566    TransactionAlreadyExecuted { digest: TransactionDigest },
567    #[error("Object ID did not have the expected type")]
568    BadObjectType { error: String },
569    #[error("Fail to retrieve Object layout for {st}")]
570    FailObjectLayout { st: String },
571
572    #[error("Execution invariant violated")]
573    ExecutionInvariantViolation,
574    #[error("Validator {authority:?} is faulty in a Byzantine manner: {reason}")]
575    ByzantineAuthoritySuspicion {
576        authority: AuthorityName,
577        reason: String,
578    },
579    #[error(
580        "Attempted to access {object} through parent {given_parent}, \
581        but it's actual parent is {actual_owner}"
582    )]
583    InvalidChildObjectAccess {
584        object: ObjectId,
585        given_parent: ObjectId,
586        actual_owner: Owner,
587    },
588
589    #[error("Authority Error: {error}")]
590    GenericAuthority { error: String },
591
592    #[error("Failed to dispatch subscription: {error}")]
593    FailedToDispatchSubscription { error: String },
594
595    #[error("Failed to serialize Owner: {error}")]
596    OwnerFailedToSerialize { error: String },
597
598    #[error("Failed to deserialize fields into JSON: {error}")]
599    ExtraFieldFailedToDeserialize { error: String },
600
601    #[error("Failed to execute transaction locally by Orchestrator: {error}")]
602    TransactionOrchestratorLocalExecution { error: String },
603
604    // Errors returned by authority and client read API's
605    #[error("Failure serializing transaction in the requested format: {error}")]
606    TransactionSerialization { error: String },
607    #[error("Failure serializing object in the requested format: {error}")]
608    ObjectSerialization { error: String },
609    #[error("Failure deserializing object in the requested format: {error}")]
610    ObjectDeserialization { error: String },
611    #[error("Failure deserializing runtime module metadata in the requested format: {error}")]
612    RuntimeModuleMetadataDeserialization { error: String },
613    #[error("Event store component is not active on this node")]
614    NoEventStore,
615
616    // Client side error
617    #[error("Too many authority errors were detected for {action}: {errors:?}")]
618    TooManyIncorrectAuthorities {
619        errors: Vec<(AuthorityName, IotaError)>,
620        action: String,
621    },
622    #[error("Invalid transaction range query to the fullnode: {error}")]
623    FullNodeInvalidTxRangeQuery { error: String },
624
625    // Errors related to the authority-consensus interface.
626    #[error("Failed to submit transaction to consensus: {0}")]
627    FailedToSubmitToConsensus(String),
628    #[error("Failed to connect with consensus node: {0}")]
629    ConsensusConnectionBroken(String),
630    #[error("Failed to execute handle_consensus_transaction on Iota: {0}")]
631    HandleConsensusTransactionFailure(String),
632
633    // Cryptography errors.
634    #[error("Signature key generation error: {0}")]
635    SignatureKeyGen(String),
636    #[error("Key Conversion Error: {0}")]
637    KeyConversion(String),
638    #[error("Invalid Private Key provided")]
639    InvalidPrivateKey,
640
641    // Unsupported Operations on Fullnode
642    #[error("Fullnode does not support handle_certificate")]
643    FullNodeCantHandleCertificate,
644    #[error("Fullnode does not support ValidatorV2 endpoints")]
645    FullNodeCantHandleValidatorV2,
646    #[error("Fullnode does not support handle_authority_capabilities")]
647    FullNodeCantHandleAuthorityCapabilities,
648
649    // Epoch related errors.
650    #[error("Validator temporarily stopped processing transactions due to epoch change")]
651    ValidatorHaltedAtEpochEnd,
652    #[error("Operations for epoch {0} have ended")]
653    EpochEnded(EpochId),
654    #[error("Error when advancing epoch: {error}")]
655    AdvanceEpoch { error: String },
656
657    #[error("Transaction Expired")]
658    TransactionExpired,
659
660    // These are errors that occur when an RPC fails and is simply the utf8 message sent in a
661    // Tonic::Status
662    #[error("{1} - {0}")]
663    Rpc(String, String),
664
665    #[error("Method not allowed")]
666    InvalidRpcMethod,
667
668    // TODO: We should fold this into UserInputError::Unsupported.
669    #[error("Use of disabled feature: {error}")]
670    UnsupportedFeature { error: String },
671
672    #[error("Unable to communicate with the Quorum Driver channel: {error}")]
673    QuorumDriverCommunication { error: String },
674
675    #[error("Operation timed out")]
676    Timeout,
677
678    #[error("Error executing {0}")]
679    Execution(String),
680
681    #[error("Invalid committee composition")]
682    InvalidCommittee(String),
683
684    #[error("Missing committee information for epoch {0}")]
685    MissingCommitteeAtEpoch(EpochId),
686
687    #[error("Index store not available on this Fullnode")]
688    IndexStoreNotAvailable,
689
690    #[error("Failed to read dynamic field from table in the object store: {0}")]
691    DynamicFieldRead(String),
692
693    #[error("Failed to read or deserialize system state related data structures on-chain: {0}")]
694    IotaSystemStateRead(String),
695
696    #[error("Unexpected version error: {0}")]
697    UnexpectedVersion(String),
698
699    #[error("Message version is not supported at the current protocol version: {error}")]
700    WrongMessageVersion { error: String },
701
702    #[error("unknown error: {0}")]
703    Unknown(String),
704
705    #[error("Failed to perform file operation: {0}")]
706    FileIO(String),
707
708    #[error("Failed to get JWK")]
709    JWKRetrieval,
710
711    #[error("Storage error: {0}")]
712    Storage(String),
713
714    #[error(
715        "Validator cannot handle the request at the moment. Please retry after at least {retry_after_secs} seconds"
716    )]
717    ValidatorOverloadedRetryAfter { retry_after_secs: u64 },
718
719    #[error("Too many requests")]
720    TooManyRequests,
721
722    #[error("The request did not contain a certificate")]
723    NoCertificateProvided,
724
725    #[error("Invalid admin request: {0}")]
726    InvalidAdminRequest(String),
727
728    #[error("Could not find the referenced transaction effects [{digest}]")]
729    TransactionEffectsNotFound { digest: TransactionDigest },
730
731    #[error("Dynamic field with key={key} and ID={id} does not exist on parent {parent_id}")]
732    DynamicFieldNotExists {
733        parent_id: ObjectId,
734        id: ObjectId,
735        key: String,
736    },
737}
738
739#[repr(u64)]
740#[expect(non_camel_case_types)]
741#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
742/// Sub-status codes for the `UNKNOWN_VERIFICATION_ERROR` VM Status Code which
743/// provides more context TODO: add more Vm Status errors. We use
744/// `UNKNOWN_VERIFICATION_ERROR` as a catchall for now.
745pub enum VMMVerifierErrorSubStatusCode {
746    MULTIPLE_RETURN_VALUES_NOT_ALLOWED = 0,
747    INVALID_OBJECT_CREATION = 1,
748}
749
750#[repr(u64)]
751#[expect(non_camel_case_types)]
752#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
753/// Sub-status codes for the `MEMORY_LIMIT_EXCEEDED` VM Status Code which
754/// provides more context
755pub enum VMMemoryLimitExceededSubStatusCode {
756    EVENT_COUNT_LIMIT_EXCEEDED = 0,
757    EVENT_SIZE_LIMIT_EXCEEDED = 1,
758    NEW_ID_COUNT_LIMIT_EXCEEDED = 2,
759    DELETED_ID_COUNT_LIMIT_EXCEEDED = 3,
760    TRANSFER_ID_COUNT_LIMIT_EXCEEDED = 4,
761    OBJECT_RUNTIME_CACHE_LIMIT_EXCEEDED = 5,
762    OBJECT_RUNTIME_STORE_LIMIT_EXCEEDED = 6,
763    TOTAL_EVENT_SIZE_LIMIT_EXCEEDED = 7,
764}
765
766pub type IotaResult<T = ()> = Result<T, IotaError>;
767pub type UserInputResult<T = ()> = Result<T, UserInputError>;
768
769impl From<iota_protocol_config::Error> for IotaError {
770    fn from(error: iota_protocol_config::Error) -> Self {
771        IotaError::WrongMessageVersion { error: error.0 }
772    }
773}
774
775impl From<ExecutionError> for IotaError {
776    fn from(error: ExecutionError) -> Self {
777        IotaError::Execution(error.to_string())
778    }
779}
780
781impl From<iota_sdk_types::hash::MissingSignatureError> for IotaError {
782    fn from(error: iota_sdk_types::hash::MissingSignatureError) -> Self {
783        IotaError::InvalidSignature {
784            error: error.to_string(),
785        }
786    }
787}
788
789#[cfg(not(target_arch = "wasm32"))]
790impl From<Status> for IotaError {
791    fn from(status: Status) -> Self {
792        if status.message() == "Too many requests" {
793            return Self::TooManyRequests;
794        }
795        let result = bcs::from_bytes::<IotaError>(status.details());
796        if let Ok(iota_error) = result {
797            iota_error
798        } else {
799            Self::Rpc(
800                status.message().to_owned(),
801                status.code().description().to_owned(),
802            )
803        }
804    }
805}
806
807impl From<TypedStoreError> for IotaError {
808    fn from(e: TypedStoreError) -> Self {
809        Self::Storage(e.to_string())
810    }
811}
812
813impl From<crate::storage::error::Error> for IotaError {
814    fn from(e: crate::storage::error::Error) -> Self {
815        Self::Storage(e.to_string())
816    }
817}
818
819#[cfg(not(target_arch = "wasm32"))]
820impl From<IotaError> for Status {
821    fn from(error: IotaError) -> Self {
822        let bytes = bcs::to_bytes(&error).unwrap();
823        Status::with_details(tonic::Code::Internal, error.to_string(), bytes.into())
824    }
825}
826
827impl From<ExecutionErrorKind> for IotaError {
828    fn from(kind: ExecutionErrorKind) -> Self {
829        ExecutionError::from_kind(kind).into()
830    }
831}
832
833impl From<&str> for IotaError {
834    fn from(error: &str) -> Self {
835        IotaError::GenericAuthority {
836            error: error.to_string(),
837        }
838    }
839}
840
841impl From<String> for IotaError {
842    fn from(error: String) -> Self {
843        IotaError::GenericAuthority { error }
844    }
845}
846
847impl TryFrom<IotaError> for UserInputError {
848    type Error = anyhow::Error;
849
850    fn try_from(err: IotaError) -> Result<Self, Self::Error> {
851        match err {
852            IotaError::UserInput { error } => Ok(error),
853            other => anyhow::bail!("error `{other}` is not UserInput"),
854        }
855    }
856}
857
858impl From<UserInputError> for IotaError {
859    fn from(error: UserInputError) -> Self {
860        IotaError::UserInput { error }
861    }
862}
863
864impl IotaError {
865    pub fn individual_error_indicates_epoch_change(&self) -> bool {
866        matches!(
867            self,
868            IotaError::ValidatorHaltedAtEpochEnd | IotaError::MissingCommitteeAtEpoch(_)
869        )
870    }
871
872    /// Returns if the error is retryable and if the error's retryability is
873    /// explicitly categorized.
874    /// There should be only a handful of retryable errors. For now we list
875    /// common non-retryable error below to help us find more retryable
876    /// errors in logs.
877    pub fn is_retryable(&self) -> (bool, bool) {
878        let retryable = match self {
879            IotaError::Rpc { .. } => true,
880
881            // Reconfig error
882            IotaError::ValidatorHaltedAtEpochEnd => true,
883            IotaError::MissingCommitteeAtEpoch(..) => true,
884            IotaError::WrongEpoch { .. } => true,
885            IotaError::EpochEnded { .. } => true,
886
887            IotaError::UserInput { error } => {
888                match error {
889                    // Only ObjectNotFound and DependentPackageNotFound is potentially retryable
890                    UserInputError::ObjectNotFound { .. } => true,
891                    UserInputError::DependentPackageNotFound { .. } => true,
892                    _ => false,
893                }
894            }
895
896            IotaError::PotentiallyTemporarilyInvalidSignature { .. } => true,
897
898            // Overload errors
899            IotaError::TooManyTransactionsPendingExecution { .. } => true,
900            IotaError::TooManyTransactionsPendingOnObject { .. } => true,
901            IotaError::TooOldTransactionPendingOnObject { .. } => true,
902            IotaError::TooManyTransactionsPendingConsensus => true,
903            IotaError::ValidatorOverloadedRetryAfter { .. } => true,
904
905            // Transient consensus failure — other validators likely unaffected
906            IotaError::FailedToSubmitToConsensus(..) => true,
907
908            // Same digest already in flight — client should wait for the
909            // original to land or retry once the soft locks are released.
910            IotaError::RecentlyResubmitted { .. } => true,
911
912            // Non retryable error
913            IotaError::Execution(..) => false,
914            IotaError::ByzantineAuthoritySuspicion { .. } => false,
915            IotaError::QuorumFailedToGetEffectsQuorumWhenProcessingTransaction { .. } => false,
916            IotaError::TxAlreadyFinalizedWithDifferentUserSigs => false,
917            IotaError::FailedToVerifyTxCertWithExecutedEffects { .. } => false,
918            IotaError::ObjectLockConflict { .. } => false,
919
920            // NB: This is not an internal overload, but instead an imposed rate
921            // limit / blocking of a client. It must be non-retryable otherwise
922            // we will make the threat worse through automatic retries.
923            IotaError::TooManyRequests => false,
924
925            // Signature errors — non-retryable, invalid input
926            IotaError::InvalidSignature { .. } => false,
927            IotaError::SignerSignatureAbsent { .. } => false,
928            IotaError::SignerSignatureNumberMismatch { .. } => false,
929            IotaError::IncorrectSigner { .. } => false,
930            IotaError::UnknownSigner { .. } => false,
931            IotaError::InvalidAuthenticator => false,
932
933            // Transaction lifecycle — non-retryable
934            IotaError::TransactionExpired => false,
935
936            // Fullnode-internal aggregation errors — non-retryable
937            IotaError::StakeAggregatorRepeatedSigner { .. } => false,
938            IotaError::CertificateRequiresQuorum => false,
939
940            // For all un-categorized errors, return here with categorized = false.
941            _ => return (false, false),
942        };
943
944        (retryable, true)
945    }
946
947    pub fn is_object_or_package_not_found(&self) -> bool {
948        match self {
949            IotaError::UserInput { error } => {
950                matches!(
951                    error,
952                    UserInputError::ObjectNotFound { .. }
953                        | UserInputError::DependentPackageNotFound { .. }
954                )
955            }
956            _ => false,
957        }
958    }
959
960    pub fn is_overload(&self) -> bool {
961        matches!(
962            self,
963            IotaError::TooManyTransactionsPendingExecution { .. }
964                | IotaError::TooManyTransactionsPendingOnObject { .. }
965                | IotaError::TooOldTransactionPendingOnObject { .. }
966                | IotaError::TooManyTransactionsPendingConsensus
967        )
968    }
969
970    pub fn is_retryable_overload(&self) -> bool {
971        matches!(self, IotaError::ValidatorOverloadedRetryAfter { .. })
972    }
973
974    /// Returns `true` for errors caused by storage or epoch-lifecycle
975    /// failures (RocksDB, epoch store closed) rather than semantic transaction
976    /// problems. Used by post-consensus validation to distinguish fatal errors
977    /// (halt the commit) from per-transaction drops.
978    pub fn is_storage_or_epoch_error(&self) -> bool {
979        matches!(
980            self,
981            IotaError::Storage(..)
982                | IotaError::EpochEnded(..)
983                | IotaError::ValidatorHaltedAtEpochEnd
984        )
985    }
986
987    pub fn retry_after_secs(&self) -> u64 {
988        match self {
989            IotaError::ValidatorOverloadedRetryAfter { retry_after_secs } => *retry_after_secs,
990            _ => 0,
991        }
992    }
993}
994
995/// Categorizes IotaError into ErrorCategory.
996pub fn categorize(error: &IotaError) -> ErrorCategory {
997    match error {
998        IotaError::UserInput { error } => match error {
999            UserInputError::ObjectNotFound { .. } => ErrorCategory::Aborted,
1000            UserInputError::DependentPackageNotFound { .. } => ErrorCategory::Aborted,
1001            _ => ErrorCategory::InvalidTransaction,
1002        },
1003        IotaError::InvalidSignature { .. }
1004        | IotaError::SignerSignatureAbsent { .. }
1005        | IotaError::SignerSignatureNumberMismatch { .. }
1006        | IotaError::IncorrectSigner { .. }
1007        | IotaError::UnknownSigner { .. }
1008        | IotaError::TransactionExpired => ErrorCategory::InvalidTransaction,
1009
1010        IotaError::ObjectLockConflict { .. } => ErrorCategory::LockConflict,
1011
1012        IotaError::TooManyTransactionsPendingExecution { .. }
1013        | IotaError::TooManyTransactionsPendingOnObject { .. }
1014        | IotaError::TooOldTransactionPendingOnObject { .. }
1015        | IotaError::TooManyTransactionsPendingConsensus
1016        | IotaError::ValidatorOverloadedRetryAfter { .. } => ErrorCategory::ValidatorOverloaded,
1017
1018        _ => ErrorCategory::Aborted,
1019    }
1020}
1021
1022/// Types of IotaError categories for retry decisions.
1023#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, IntoStaticStr)]
1024pub enum ErrorCategory {
1025    /// A generic error that is retriable with new transaction resubmissions.
1026    Aborted,
1027    /// Any validator or full node can check if a transaction is valid.
1028    InvalidTransaction,
1029    /// Lock conflict on the transaction input.
1030    LockConflict,
1031    /// Unexpected client error, for example generating invalid request or
1032    /// entering into invalid state. And unexpected error from the remote
1033    /// peer.
1034    Internal,
1035    /// Validator is overloaded.
1036    ValidatorOverloaded,
1037    /// Target validator is down or there are network issues.
1038    Unavailable,
1039}
1040
1041impl ErrorCategory {
1042    /// Whether the failure is retriable with new transaction submission.
1043    pub fn is_submission_retriable(&self) -> bool {
1044        matches!(
1045            self,
1046            ErrorCategory::Aborted
1047                | ErrorCategory::ValidatorOverloaded
1048                | ErrorCategory::Unavailable
1049        )
1050    }
1051}
1052
1053impl IotaError {
1054    /// Categorizes this error into an ErrorCategory.
1055    pub fn categorize(&self) -> ErrorCategory {
1056        categorize(self)
1057    }
1058}
1059
1060impl Ord for IotaError {
1061    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1062        Ord::cmp(self.as_ref(), other.as_ref())
1063    }
1064}
1065
1066impl PartialOrd for IotaError {
1067    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1068        Some(self.cmp(other))
1069    }
1070}
1071
1072type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
1073
1074pub type ExecutionErrorKind = ExecutionFailureStatus;
1075
1076#[derive(Debug)]
1077pub struct ExecutionError {
1078    inner: Box<ExecutionErrorInner>,
1079}
1080
1081#[derive(Debug)]
1082struct ExecutionErrorInner {
1083    kind: ExecutionErrorKind,
1084    source: Option<BoxError>,
1085    command: Option<u64>,
1086}
1087
1088impl ExecutionError {
1089    pub fn new(kind: ExecutionErrorKind, source: Option<BoxError>) -> Self {
1090        Self {
1091            inner: Box::new(ExecutionErrorInner {
1092                kind,
1093                source,
1094                command: None,
1095            }),
1096        }
1097    }
1098
1099    pub fn new_with_source<E: Into<BoxError>>(kind: ExecutionErrorKind, source: E) -> Self {
1100        Self::new(kind, Some(source.into()))
1101    }
1102
1103    pub fn invariant_violation<E: Into<BoxError>>(source: E) -> Self {
1104        Self::new_with_source(ExecutionFailureStatus::InvariantViolation, source)
1105    }
1106
1107    pub fn with_command_index(mut self, command: u64) -> Self {
1108        self.inner.command = Some(command);
1109        self
1110    }
1111
1112    /// Rewrap this error, produced while executing a Move authenticator, as a
1113    /// [`ExecutionFailureStatus::MoveAuthentication`]. The command index
1114    /// is dropped: it referred to a command of the authenticator's own
1115    /// programmable transaction and is meaningless in the transaction's
1116    /// effects, where it would otherwise collide with the first command of the
1117    /// programmable transaction.
1118    pub fn into_move_authentication_error(self) -> Self {
1119        let ExecutionErrorInner { kind, source, .. } = *self.inner;
1120        Self::new(
1121            ExecutionFailureStatus::MoveAuthentication {
1122                error: Box::new(kind),
1123            },
1124            source,
1125        )
1126    }
1127
1128    pub fn from_kind(kind: ExecutionErrorKind) -> Self {
1129        Self::new(kind, None)
1130    }
1131
1132    pub fn kind(&self) -> &ExecutionErrorKind {
1133        &self.inner.kind
1134    }
1135
1136    pub fn command(&self) -> Option<u64> {
1137        self.inner.command
1138    }
1139
1140    pub fn source(&self) -> &Option<BoxError> {
1141        &self.inner.source
1142    }
1143
1144    pub fn to_execution_status(&self) -> (ExecutionFailureStatus, Option<u64>) {
1145        (self.kind().clone(), self.command())
1146    }
1147}
1148
1149impl std::fmt::Display for ExecutionError {
1150    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1151        write!(f, "{}: {}", self.inner.kind.as_ref(), self.inner.kind)?;
1152        if let Some(source) = self.inner.source.as_ref() {
1153            write!(f, "; caused by: {source}")?;
1154        }
1155        if let Some(command) = self.inner.command {
1156            write!(f, "; at command index: {command}")?;
1157        }
1158        Ok(())
1159    }
1160}
1161
1162impl std::error::Error for ExecutionError {
1163    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1164        self.inner.source.as_ref().map(|e| &**e as _)
1165    }
1166}
1167
1168impl From<ExecutionErrorKind> for ExecutionError {
1169    fn from(kind: ExecutionErrorKind) -> Self {
1170        Self::from_kind(kind)
1171    }
1172}
1173
1174pub fn command_argument_error(e: CommandArgumentError, arg_idx: usize) -> ExecutionError {
1175    ExecutionError::from_kind(ExecutionErrorKind::command_argument_error(
1176        e,
1177        arg_idx as u16,
1178    ))
1179}