iota_types/execution.rs
1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6 collections::{BTreeMap, BTreeSet, HashSet},
7 time::Duration,
8};
9
10use iota_sdk_types::{
11 Argument, Event, ObjectData, ObjectDigest, ObjectId, ObjectReference, Owner, TransactionDigest,
12 TransactionEffects, TypeTag, Version,
13};
14use once_cell::sync::Lazy;
15use serde::{Deserialize, Serialize};
16
17use crate::{
18 error::{ExecutionError, ExecutionErrorKind},
19 gas::IotaGasStatus,
20 inner_temporary_store::InnerTemporaryStore,
21 object::{MoveStructExt, Object},
22 storage::BackingPackageStore,
23};
24
25/// A type containing all of the information needed to work with a deleted
26/// shared object in execution and when committing the execution effects of the
27/// transaction. This holds:
28/// 0. The object ID of the deleted shared object.
29/// 1. The version of the shared object.
30/// 2. Whether the object appeared as mutable (or owned) in the transaction, or as a read-only
31/// shared object.
32/// 3. The transaction digest of the previous transaction that used this shared object mutably or
33/// took it by value.
34pub type DeletedSharedObjectInfo = (ObjectId, Version, bool, TransactionDigest);
35
36/// A sequence of information about deleted shared objects in the transaction's
37/// inputs.
38pub type DeletedSharedObjects = Vec<DeletedSharedObjectInfo>;
39
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum SharedInput {
42 Existing(ObjectReference),
43 Deleted(DeletedSharedObjectInfo),
44 Cancelled((ObjectId, Version)),
45}
46
47#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
48pub struct DynamicallyLoadedObjectMetadata {
49 pub version: Version,
50 pub digest: ObjectDigest,
51 pub owner: Owner,
52 pub storage_rebate: u64,
53 pub previous_transaction: TransactionDigest,
54}
55
56/// View of the store necessary to produce the layouts of types.
57pub trait TypeLayoutStore: BackingPackageStore {}
58impl<T> TypeLayoutStore for T where T: BackingPackageStore {}
59
60#[derive(Debug)]
61pub enum ExecutionResults {
62 V1(ExecutionResultsV1),
63}
64
65/// Used by iota-execution v1 and above, to capture the execution results from
66/// Move. The results represent the primitive information that can then be used
67/// to construct both transaction effect V1.
68#[derive(Debug, Default)]
69pub struct ExecutionResultsV1 {
70 /// All objects written regardless of whether they were mutated, created, or
71 /// unwrapped.
72 pub written_objects: BTreeMap<ObjectId, Object>,
73 /// All objects that existed prior to this transaction, and are modified in
74 /// this transaction. This includes any type of modification, including
75 /// mutated, wrapped and deleted objects.
76 pub modified_objects: BTreeSet<ObjectId>,
77 /// All object IDs created in this transaction.
78 pub created_object_ids: BTreeSet<ObjectId>,
79 /// All object IDs deleted in this transaction.
80 /// No object ID should be in both created_object_ids and
81 /// deleted_object_ids.
82 pub deleted_object_ids: BTreeSet<ObjectId>,
83 /// All Move events emitted in this transaction.
84 pub user_events: Vec<Event>,
85}
86
87pub type ExecutionResult = (
88 // mutable_reference_outputs
89 Vec<(Argument, Vec<u8>, TypeTag)>,
90 // return_values
91 Vec<(Vec<u8>, TypeTag)>,
92);
93
94/// What authenticating and then executing a transaction returns: the temporary
95/// store, the gas status, the effects, the timings and the execution result,
96/// plus the Move authentication error when that phase failed. The body's own
97/// checks may replace that error in the effects.
98pub type AuthenticateThenExecuteOutput<R> = (
99 InnerTemporaryStore,
100 IotaGasStatus,
101 TransactionEffects,
102 Vec<ExecutionTiming>,
103 Result<R, ExecutionError>,
104 Option<ExecutionErrorKind>,
105);
106
107/// Returns the error wrapped in an [`ExecutionErrorKind::MoveAuthentication`]
108/// status, the way the engine reports a failed authentication when the
109/// protocol feature flag `report_move_authentication_error` is on, so the
110/// authenticator's own failure can be matched. Any other kind is returned as
111/// it is.
112pub fn unwrap_move_authentication_error(kind: &ExecutionErrorKind) -> &ExecutionErrorKind {
113 match kind {
114 ExecutionErrorKind::MoveAuthentication { error } => error.as_ref(),
115 kind => kind,
116 }
117}
118
119/// Whether `kind` says the execution was canceled rather than failed: canceled
120/// at the consensus commit because of shared object congestion, execution
121/// worker congestion or unavailable randomness, or denied by
122/// [`is_certificate_denied()`]. A Move authentication never reports a denial:
123/// its input checks skip the deny list, which applies after authentication. A
124/// kind wrapped in an [`ExecutionErrorKind::MoveAuthentication`] status must
125/// be unwrapped first with [`unwrap_move_authentication_error()`].
126pub fn is_cancellation(kind: &ExecutionErrorKind) -> bool {
127 matches!(
128 kind,
129 ExecutionErrorKind::CertificateDenied
130 | ExecutionErrorKind::ExecutionCanceledDueToSharedObjectCongestion { .. }
131 | ExecutionErrorKind::ExecutionCanceledDueToSharedObjectCongestionV2 { .. }
132 | ExecutionErrorKind::ExecutionCanceledDueToExecutionWorkerCongestion { .. }
133 | ExecutionErrorKind::ExecutionCanceledDueToRandomnessUnavailable
134 )
135}
136
137/// Whether `kind` is an invariant violation of the execution layer or of the
138/// Move VM: an internal error, not a failure the transaction caused. A kind
139/// wrapped in an [`ExecutionErrorKind::MoveAuthentication`] status must be
140/// unwrapped first with [`unwrap_move_authentication_error()`].
141pub fn is_any_invariant_violation(kind: &ExecutionErrorKind) -> bool {
142 matches!(
143 kind,
144 ExecutionErrorKind::InvariantViolation | ExecutionErrorKind::VmInvariantViolation
145 )
146}
147
148impl ExecutionResultsV1 {
149 pub fn drop_writes(&mut self) {
150 self.written_objects.clear();
151 self.modified_objects.clear();
152 self.created_object_ids.clear();
153 self.deleted_object_ids.clear();
154 self.user_events.clear();
155 }
156
157 pub fn merge_results(&mut self, new_results: Self) {
158 self.written_objects.extend(new_results.written_objects);
159 self.modified_objects.extend(new_results.modified_objects);
160 self.created_object_ids
161 .extend(new_results.created_object_ids);
162 self.deleted_object_ids
163 .extend(new_results.deleted_object_ids);
164 self.user_events.extend(new_results.user_events);
165 }
166
167 pub fn update_version_and_previous_tx(
168 &mut self,
169 lamport_version: Version,
170 prev_tx: TransactionDigest,
171 input_objects: &BTreeMap<ObjectId, Object>,
172 ) {
173 for (id, obj) in self.written_objects.iter_mut() {
174 // TODO: We can now get rid of the following logic by passing in lamport version
175 // into the execution layer, and create new objects using the lamport version
176 // directly.
177
178 // Update the version for the written object.
179 match &mut obj.data {
180 ObjectData::Struct(obj) => {
181 // Move objects all get the transaction's lamport timestamp
182 obj.increment_version_to(lamport_version);
183 }
184
185 ObjectData::Package(pkg) => {
186 // Modified packages get their version incremented (this is a special case that
187 // only applies to system packages). All other packages can only be created,
188 // and they are left alone.
189 if self.modified_objects.contains(id) {
190 debug_assert!(id.is_system_package());
191 pkg.increment_version()
192 .expect("package version should never overflow");
193 }
194 }
195
196 _ => unimplemented!(
197 "a new ObjectData enum variant was added and needs to be handled"
198 ),
199 }
200
201 // Record the version that the shared object was created at in its owner field.
202 // Note, this only works because shared objects must be created as
203 // shared (not created as owned in one transaction and later
204 // converted to shared in another).
205 if let Owner::Shared(initial_shared_version) = &mut obj.owner {
206 if self.created_object_ids.contains(id) {
207 assert_eq!(
208 *initial_shared_version,
209 Version::default(),
210 "Initial version should be blank before this point for {id}",
211 );
212 *initial_shared_version = lamport_version;
213 }
214
215 // Update initial_shared_version for reshared objects
216 if let Some(previous_initial_shared_version) = input_objects
217 .get(id)
218 .and_then(|obj| obj.owner.as_opt_shared())
219 {
220 debug_assert!(!self.created_object_ids.contains(id));
221 debug_assert!(!self.deleted_object_ids.contains(id));
222 debug_assert!(
223 *initial_shared_version == Version::default()
224 || *initial_shared_version == *previous_initial_shared_version
225 );
226
227 *initial_shared_version = *previous_initial_shared_version;
228 }
229 }
230
231 obj.previous_transaction = prev_tx;
232 }
233 }
234}
235
236pub enum ExecutionTiming {
237 Success(Duration),
238 Abort(Duration),
239}
240pub type ResultWithTimings<R, E> = Result<(R, Vec<ExecutionTiming>), (E, Vec<ExecutionTiming>)>;
241
242/// If a transaction digest shows up in this list, when executing such
243/// transaction, we will always return `ExecutionError::CertificateDenied`
244/// without executing it (but still do gas smashing). Because this list is not
245/// gated by protocol version, there are a few important criteria for adding a
246/// digest to this list:
247/// 1. The certificate must be causing all validators to either panic or hang forever
248/// deterministically.
249/// 2. If we ever ship a fix to make it no longer panic or hang when executing such transaction, we
250/// must make sure the transaction is already in this list. Otherwise nodes running the newer
251/// version without these transactions in the list will generate forked result.
252///
253/// Below is a scenario of when we need to use this list:
254/// 1. We detect that a specific transaction is causing all validators to either panic or hang
255/// forever deterministically.
256/// 2. We push a CertificateDenyConfig to deny such transaction to all validators asap.
257/// 3. To make sure that all fullnodes are able to sync to the latest version, we need to add the
258/// transaction digest to this list as well asap, and ship this binary to all fullnodes, so that
259/// they can sync past this transaction.
260/// 4. We then can start fixing the issue, and ship the fix to all nodes.
261/// 5. Unfortunately, we can't remove the transaction digest from this list, because if we do so,
262/// any future node that sync from genesis will fork on this transaction. We may be able to
263/// remove it once we have stable snapshots and the binary has a minimum supported protocol
264/// version past the epoch.
265pub fn get_denied_certificates() -> &'static HashSet<TransactionDigest> {
266 static DENIED_CERTIFICATES: Lazy<HashSet<TransactionDigest>> = Lazy::new(|| HashSet::from([]));
267 Lazy::force(&DENIED_CERTIFICATES)
268}
269
270pub fn is_certificate_denied(
271 transaction_digest: &TransactionDigest,
272 certificate_deny_set: &HashSet<TransactionDigest>,
273) -> bool {
274 certificate_deny_set.contains(transaction_digest)
275 || get_denied_certificates().contains(transaction_digest)
276}