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