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