iota_types/transaction_executor.rs
1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{collections::BTreeMap, time::Duration};
6
7use iota_sdk_types::{
8 GasPayment, ObjectId, Transaction, TransactionDigest, TransactionEffects, TransactionEvents,
9};
10
11use crate::{
12 error::{ExecutionError, IotaError},
13 execution::ExecutionResult,
14 messages_checkpoint::CheckpointSequenceNumber,
15 object::Object,
16 quorum_driver_types::{
17 ExecuteTransactionRequestV1, ExecuteTransactionResponseV1, QuorumDriverError,
18 },
19};
20
21/// Trait to define the interface for how the REST service interacts with a
22/// QuorumDriver or a simulated transaction executor.
23#[async_trait::async_trait]
24pub trait TransactionExecutor: Send + Sync {
25 async fn execute_transaction(
26 &self,
27 request: ExecuteTransactionRequestV1,
28 skip_certification: bool,
29 client_addr: Option<std::net::SocketAddr>,
30 ) -> Result<ExecuteTransactionResponseV1, QuorumDriverError>;
31
32 fn simulate_transaction(
33 &self,
34 transaction: Transaction,
35 checks: VmChecks,
36 ) -> Result<SimulateTransactionResult, IotaError>;
37
38 /// Wait until the given transactions are in a checkpoint and the RPC
39 /// indexes include that checkpoint.
40 ///
41 /// Returns a mapping from transaction digest to
42 /// `(checkpoint_sequence_number, checkpoint_timestamp_ms)`.
43 /// On timeout, returns partial results for any transactions that were
44 /// already checkpointed.
45 async fn wait_for_checkpoint_inclusion(
46 &self,
47 digests: &[TransactionDigest],
48 timeout: Duration,
49 ) -> Result<BTreeMap<TransactionDigest, (CheckpointSequenceNumber, u64)>, IotaError>;
50
51 /// Keeps the objects that `read_transaction_from_cache` returns for
52 /// transactions executed from now on readable until the returned value is
53 /// dropped. Take it before executing transactions whose objects are read
54 /// from the cache afterwards. Executors that do not prune retain nothing.
55 fn retain_cached_objects(&self) -> Box<dyn Send + Sync> {
56 Box::new(())
57 }
58
59 /// Read authoritative effects, events, and input/output objects for a
60 /// locally-executed transaction from the cache. Used by callers that
61 /// have already waited for checkpoint inclusion and want to discard any
62 /// uncertified single-validator copies.
63 ///
64 /// Returns `Ok(None)` if the tx is not in the cache, or if the executor
65 /// does not maintain a local cache (e.g. simulacrum).
66 fn read_transaction_from_cache(
67 &self,
68 digest: &TransactionDigest,
69 include_events: bool,
70 include_input_objects: bool,
71 include_output_objects: bool,
72 ) -> Result<Option<CachedTransactionData>, IotaError> {
73 // Default: no cache — safe fallback for executors like simulacrum.
74 let _ = (
75 digest,
76 include_events,
77 include_input_objects,
78 include_output_objects,
79 );
80 Ok(None)
81 }
82}
83
84/// Authoritative per-transaction data read from a local cache.
85pub struct CachedTransactionData {
86 pub effects: TransactionEffects,
87 pub events: Option<TransactionEvents>,
88 pub input_objects: Option<Vec<Object>>,
89 pub output_objects: Option<Vec<Object>>,
90}
91
92pub struct SimulateTransactionResult {
93 pub effects: TransactionEffects,
94 pub events: Option<TransactionEvents>,
95 /// Every object the transaction ran with as input — including immutable
96 /// and read-only shared inputs, the packages it calls, and the gas coins
97 /// (the mock one included) — plus the runtime-loaded objects (e.g. dynamic
98 /// fields) it modified, at their pre-state versions, keyed by id.
99 pub input_objects: BTreeMap<ObjectId, Object>,
100 pub output_objects: BTreeMap<ObjectId, Object>,
101 /// The return values and mutable-reference outputs of every command, under
102 /// either [`VmChecks`] — both run through the executor's dev-inspect entry
103 /// point, which collects them regardless of which checks are in force.
104 pub execution_result: Result<Vec<ExecutionResult>, ExecutionError>,
105 pub mock_gas_id: Option<ObjectId>,
106 pub suggested_gas_price: Option<u64>,
107 /// The gas the simulation ran with, once whatever the transaction left
108 /// unset was filled in. Callers reporting the transaction back should
109 /// use this rather than re-deriving it, which would read a possibly
110 /// different epoch.
111 pub gas_data: GasPayment,
112}
113
114/// Which Move VM checks a simulation runs with.
115///
116/// This is the only thing that separates the two ways a transaction can be
117/// simulated, so it is what callers pick between: a dry run wants
118/// [`VmChecks::Enabled`], a dev inspect wants [`VmChecks::Disabled`].
119#[derive(Default, Debug, Copy, Clone)]
120pub enum VmChecks {
121 /// Run the transaction as it would run on chain: the input checks a
122 /// validator applies ([`InputCheckRules::STRICT`]), and metering against
123 /// the transaction's own budget.
124 #[default]
125 Enabled,
126 /// Relax the rules around entry functions and argument values, so that any
127 /// Move function can be called and any value built from its bytes, and
128 /// drop the input checks named in [`InputCheckRules::RELAXED_UNSAFE`].
129 Disabled,
130}
131
132impl VmChecks {
133 pub fn disabled(self) -> bool {
134 matches!(self, Self::Disabled)
135 }
136
137 pub fn enabled(self) -> bool {
138 matches!(self, Self::Enabled)
139 }
140}
141
142/// Which input checks a simulation drops relative to a transaction bound for
143/// execution.
144///
145/// A rule is enabled when the corresponding field is set to `false`.
146#[derive(Debug, Copy, Clone)]
147pub struct InputCheckRules {
148 /// Skip the bounds on the gas budget, so a caller whose gas is not settled
149 /// runs out of gas rather than being rejected.
150 pub unbounded_gas_budget: bool,
151 /// Skip the match between an address-owned input's owner and the sender, so
152 /// a caller can ask what a transaction would do over objects it does not
153 /// own. Gas coins go through the same check, so the gas owner is not
154 /// matched either.
155 pub any_object_owner: bool,
156 /// Skip the match between an input object's declared digest and the loaded
157 /// object. Execution reads the object by id and version, but the effects
158 /// report the declared digest as the object's input digest, so a wrong one
159 /// is echoed back there.
160 pub any_object_digest: bool,
161 /// Accept a shared object named as an owned input. Execution takes an
162 /// input's mutability from the object itself, so such an input is mutable.
163 /// The `shared_object_disabled` deny rule reads the declared kind, so it
164 /// does not see such an input as shared. The Clock, Random,
165 /// AuthenticatorState and TransactionDenyRules objects are not accepted
166 /// this way.
167 pub shared_object_as_owned_input: bool,
168 /// Skip the match between a shared input's declared initial shared version
169 /// and the object's own. Only consensus reads the declared one.
170 pub any_initial_shared_version: bool,
171 /// Skip the match between a receiving reference's declared version and the
172 /// object's current version, so a simulation can run over a reference the
173 /// caller has not refreshed. Receiving at that version then fails unless
174 /// the store still serves it, as a node does for older versions.
175 pub any_receiving_object_version: bool,
176 /// Skip the match between a receiving reference's declared digest and the
177 /// object it names. Receiving does not read the digest; the effects leave
178 /// the received object out of their dependencies when it does not match.
179 pub any_receiving_object_digest: bool,
180}
181
182impl InputCheckRules {
183 /// No relaxations: exactly what a validator applies.
184 pub const STRICT: Self = Self {
185 unbounded_gas_budget: false,
186 any_object_owner: false,
187 any_object_digest: false,
188 shared_object_as_owned_input: false,
189 any_initial_shared_version: false,
190 any_receiving_object_version: false,
191 any_receiving_object_digest: false,
192 };
193
194 /// What a simulation with [`VmChecks::Disabled`] drops.
195 pub const RELAXED_UNSAFE: Self = Self {
196 unbounded_gas_budget: true,
197 any_object_owner: true,
198 any_object_digest: true,
199 shared_object_as_owned_input: true,
200 any_initial_shared_version: true,
201 any_receiving_object_version: true,
202 any_receiving_object_digest: true,
203 };
204}
205
206impl From<VmChecks> for InputCheckRules {
207 fn from(checks: VmChecks) -> Self {
208 match checks {
209 VmChecks::Enabled => Self::STRICT,
210 VmChecks::Disabled => Self::RELAXED_UNSAFE,
211 }
212 }
213}