Skip to main content

sui_adapter_latest/
temporary_store.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::execution_mode::ExecutionMode;
5use crate::execution_value::ExecutionState;
6use crate::metering::gas_charger::ChargedGas;
7use crate::metering::gas_state::{StorageCharge, StorageRates};
8use move_vm_runtime::runtime::MoveRuntime;
9use mysten_common::{ZipDebugEqIteratorExt, debug_fatal};
10use mysten_metrics::monitored_scope;
11use parking_lot::RwLock;
12use std::cell::RefCell;
13use std::collections::{BTreeMap, BTreeSet, HashSet};
14use std::sync::Arc;
15use sui_protocol_config::ProtocolConfig;
16use sui_types::accumulator_event::AccumulatorEvent;
17use sui_types::accumulator_root::{
18    AccumulatorObjId, AccumulatorValue as AccumulatorRootValue, EmptyUnsettledObjectFunds,
19    UnsettledObjectFundsRead,
20};
21use sui_types::base_types::{SystemObjectVersions, VersionDigest};
22use sui_types::coin_reservation::ParsedDigest;
23use sui_types::committee::EpochId;
24use sui_types::deny_list_v2::check_coin_deny_list_v2_during_execution;
25use sui_types::effects::{
26    AccumulatorOperation, AccumulatorValue, AccumulatorWriteV1, TransactionEffects,
27    TransactionEffectsV2, TransactionEvents,
28};
29use sui_types::error::SuiErrorKind;
30use sui_types::execution::{
31    DynamicallyLoadedObjectMetadata, ExecutionResults, ExecutionResultsV2, SharedInput,
32};
33use sui_types::execution_status::{ExecutionErrorKind, ExecutionStatus};
34use sui_types::inner_temporary_store::InnerTemporaryStore;
35use sui_types::object::Data;
36use sui_types::storage::{
37    BackingStore, DenyListResult, ImplicitSystemObjectResolver, PackageObject,
38};
39use sui_types::sui_system_state::{AdvanceEpochParams, get_sui_system_state_wrapper};
40use sui_types::transaction::{Command, GasData, TransactionKind, is_gasless_transaction};
41use sui_types::{
42    SUI_ACCUMULATOR_ROOT_OBJECT_ID, SUI_CLOCK_OBJECT_ID, SUI_DENY_LIST_OBJECT_ID,
43    SUI_FREEZE_LIST_OBJECT_ID,
44    base_types::{ObjectID, ObjectRef, SequenceNumber, SuiAddress, TransactionDigest},
45    digests::ObjectDigest,
46    effects::EffectsObjectChange,
47    error::{ExecutionError, SuiResult},
48    gas::GasCostSummary,
49    object::Object,
50    object::Owner,
51    storage::{BackingPackageStore, RuntimeObjectResolver, Storage},
52    transaction::InputObjects,
53};
54use sui_types::{SUI_SYSTEM_STATE_OBJECT_ID, TypeTag, is_system_package};
55
56pub(crate) mod invariants;
57use invariants::InvariantChecker;
58
59/// Declared allowance ids per `(funder, funds type)` key.
60type AllowanceIds = BTreeMap<(SuiAddress, TypeTag), Vec<ObjectID>>;
61
62/// The declared SeizeAuth id per `(frozen address, funds type)` key. Signing allows one
63/// `WithdrawFrom::FrozenAddress` per frozen address.
64type SeizeAuthIds = BTreeMap<(SuiAddress, TypeTag), ObjectID>;
65
66/// The funds a transaction declares, as `compute_input_reservations` computes them. See
67/// `PostExecutionCheckInputs` for each field.
68struct InputReservations {
69    reservations: BTreeMap<(SuiAddress, TypeTag), u64>,
70    allowance_ids: AllowanceIds,
71    seize_auth_ids: SeizeAuthIds,
72}
73
74#[derive(Default)]
75struct PostExecutionCheckInputs {
76    /// Per-`(address, type)` funds-accumulator reservation budget authorized by this transaction.
77    /// Shared by gasless execution validation and the post-execution invariant checks.
78    input_reservations: BTreeMap<(SuiAddress, TypeTag), u64>,
79    /// The allowance ids declared per `WithdrawFrom::SenderAllowance` reservation key. Consumed by
80    /// `check_ownership_invariants` to authorize Splits at non-signer keys.
81    allowance_ids: AllowanceIds,
82    /// The SeizeAuth id declared per `WithdrawFrom::FrozenAddress` reservation key, used like
83    /// `allowance_ids`.
84    seize_auth_ids: SeizeAuthIds,
85    /// For the advance-epoch transaction, `(epoch_fees minted, epoch_rebates burned)`; `None`
86    /// for every other transaction. Needed by the expensive SUI conservation check.
87    advance_epoch_gas_summary: Option<(u64, u64)>,
88    /// The genesis transaction mints the initial SUI supply and so is exempt from conservation.
89    is_genesis: bool,
90    /// What each `Publish`/`Upgrade` command in the PTB says the package it writes should look like.
91    /// `None` when the transaction is not a PTB.
92    declared_packages: Option<Vec<(usize, BTreeSet<ObjectID>)>>,
93}
94
95impl PostExecutionCheckInputs {
96    fn new(transaction: (&TransactionKind, &GasData, SuiAddress)) -> Self {
97        let (transaction_kind, gas_data, transaction_signer) = transaction;
98        let InputReservations {
99            reservations: input_reservations,
100            allowance_ids,
101            seize_auth_ids,
102        } = compute_input_reservations(transaction_kind, gas_data, transaction_signer);
103        Self {
104            input_reservations,
105            allowance_ids,
106            seize_auth_ids,
107            advance_epoch_gas_summary: transaction_kind.get_advance_epoch_tx_gas_summary(),
108            is_genesis: matches!(transaction_kind, TransactionKind::Genesis(_)),
109            declared_packages: declared_packages(transaction_kind),
110        }
111    }
112}
113
114pub struct TemporaryStore<'backing> {
115    // The backing store for retrieving Move packages onchain.
116    // When executing a Move call, the dependent packages are not going to be
117    // in the input objects. They will be fetched from the backing store.
118    // Also used for fetching the backing parent_sync to get the last known version for wrapped
119    // objects
120    store: &'backing dyn BackingStore,
121    tx_digest: TransactionDigest,
122    input_objects: BTreeMap<ObjectID, Object>,
123    /// Immutable transaction-derived inputs needed for various checks after execution finishes.
124    // TODO: We should merge all input-derived immutable data to a single struct.
125    post_execution_check_inputs: PostExecutionCheckInputs,
126
127    /// Store the original versions of the non-exclusive write inputs, in order to detect
128    /// mutations (which are illegal, but not prevented by the type system).
129    non_exclusive_input_original_versions: BTreeMap<ObjectID, Object>,
130
131    stream_ended_consensus_objects: BTreeMap<ObjectID, SequenceNumber /* start_version */>,
132    /// The version to assign to all objects written by the transaction using this store.
133    lamport_timestamp: SequenceNumber,
134    /// Inputs that will be mutated by the transaction. Does not include NonExclusiveWrite inputs,
135    /// which can be taken as `&mut T` but cannot be directly mutated.
136    mutable_input_refs: BTreeMap<ObjectID, (VersionDigest, Owner)>,
137    execution_results: ExecutionResultsV2,
138    /// Objects that were loaded during execution (dynamic fields + received objects).
139    loaded_runtime_objects: BTreeMap<ObjectID, DynamicallyLoadedObjectMetadata>,
140    protocol_config: &'backing ProtocolConfig,
141
142    /// Every package that was loaded from DB store during execution.
143    /// These packages were not previously loaded into the temporary store.
144    runtime_packages_loaded_from_db: RwLock<BTreeMap<ObjectID, PackageObject>>,
145
146    /// The set of objects that we may receive during execution. Not guaranteed to receive all, or
147    /// any of the objects referenced in this set.
148    receiving_objects: Vec<ObjectRef>,
149
150    // TODO: Now that we track epoch here, there are a few places we don't need to pass it around.
151    /// The current epoch.
152    cur_epoch: EpochId,
153
154    /// The set of per-epoch config objects that were loaded during execution, and are not in the
155    /// input objects. This allows us to commit them to the effects.
156    loaded_per_epoch_config_objects: RwLock<BTreeSet<ObjectID>>,
157
158    /// Execution-attempt bookkeeping for post-execution system checks.
159    invariants: InvariantChecker,
160
161    /// Versions of system objects this transaction may implicitly read during execution.
162    system_object_versions: SystemObjectVersions,
163
164    /// System objects implicitly read during execution, keyed by object ID, with the version (and its
165    /// digest) at which they were read.
166    /// Interior-mutable because reads happen behind `&self` (`RuntimeObjectResolver`).
167    loaded_system_objects: RefCell<BTreeMap<ObjectID, (SequenceNumber, ObjectDigest)>>,
168
169    unsettled_object_funds: &'backing dyn UnsettledObjectFundsRead,
170}
171
172impl<'backing> TemporaryStore<'backing> {
173    /// Creates a new store associated with an authority store, and populates it with
174    /// initial objects.
175    #[allow(clippy::too_many_arguments)]
176    pub(crate) fn new(
177        store: &'backing dyn BackingStore,
178        input_objects: InputObjects,
179        receiving_objects: Vec<ObjectRef>,
180        tx_digest: TransactionDigest,
181        protocol_config: &'backing ProtocolConfig,
182        cur_epoch: EpochId,
183        system_object_versions: SystemObjectVersions,
184        transaction: (&TransactionKind, &GasData, SuiAddress),
185        unsettled_object_funds: &'backing dyn UnsettledObjectFundsRead,
186    ) -> Self {
187        let post_execution_check_inputs = PostExecutionCheckInputs::new(transaction);
188        Self::new_with_input_objects(
189            store,
190            input_objects,
191            receiving_objects,
192            tx_digest,
193            protocol_config,
194            cur_epoch,
195            system_object_versions,
196            post_execution_check_inputs,
197            unsettled_object_funds,
198        )
199    }
200
201    pub(crate) fn new_for_genesis_state_update(
202        store: &'backing dyn BackingStore,
203        tx_digest: TransactionDigest,
204        protocol_config: &'backing ProtocolConfig,
205    ) -> Self {
206        Self::new_with_input_objects(
207            store,
208            InputObjects::new(vec![]),
209            vec![],
210            tx_digest,
211            protocol_config,
212            0,
213            SystemObjectVersions::empty(),
214            PostExecutionCheckInputs {
215                is_genesis: true,
216                ..Default::default()
217            },
218            // The genesis transaction cannot withdraw object funds, so there are never
219            // unsettled withdrawals for it to account for.
220            &EmptyUnsettledObjectFunds,
221        )
222    }
223
224    fn new_with_input_objects(
225        store: &'backing dyn BackingStore,
226        input_objects: InputObjects,
227        receiving_objects: Vec<ObjectRef>,
228        tx_digest: TransactionDigest,
229        protocol_config: &'backing ProtocolConfig,
230        cur_epoch: EpochId,
231        system_object_versions: SystemObjectVersions,
232        post_execution_check_inputs: PostExecutionCheckInputs,
233        unsettled_object_funds: &'backing dyn UnsettledObjectFundsRead,
234    ) -> Self {
235        let mutable_input_refs = input_objects.exclusive_mutable_inputs();
236        let non_exclusive_input_original_versions = input_objects.non_exclusive_input_objects();
237
238        let lamport_timestamp = input_objects.lamport_timestamp(&receiving_objects);
239        let stream_ended_consensus_objects = input_objects.consensus_stream_ended_objects();
240        let objects = input_objects.into_object_map();
241        #[cfg(debug_assertions)]
242        {
243            // Ensure that input objects and receiving objects must not overlap.
244            assert!(
245                objects
246                    .keys()
247                    .collect::<HashSet<_>>()
248                    .intersection(
249                        &receiving_objects
250                            .iter()
251                            .map(|oref| &oref.0)
252                            .collect::<HashSet<_>>()
253                    )
254                    .next()
255                    .is_none()
256            );
257        }
258        Self {
259            store,
260            tx_digest,
261            input_objects: objects,
262            non_exclusive_input_original_versions,
263            stream_ended_consensus_objects,
264            lamport_timestamp,
265            mutable_input_refs,
266            execution_results: ExecutionResultsV2::default(),
267            protocol_config,
268            loaded_runtime_objects: BTreeMap::new(),
269            runtime_packages_loaded_from_db: RwLock::new(BTreeMap::new()),
270            receiving_objects,
271            cur_epoch,
272            loaded_per_epoch_config_objects: RwLock::new(BTreeSet::new()),
273            post_execution_check_inputs,
274            invariants: InvariantChecker::default(),
275            system_object_versions,
276            loaded_system_objects: RefCell::new(BTreeMap::new()),
277            unsettled_object_funds,
278        }
279    }
280
281    /// Checks that the system object `object_id` is available at the version this transaction
282    /// requires, and records the read so it can be emitted into effects
283    /// and reproduced on replay.
284    /// This is expected to return Some in normal cases. If it ever returns None, it should be
285    /// treated as an invariant violation.
286    pub fn load_implicitly_read_system_object(&self, object_id: &ObjectID) -> Option<Object> {
287        let version = match self.system_object_versions.get(object_id) {
288            Some(version) => version,
289            None => {
290                debug_fatal!(
291                    "system_object_versions must contain entry for object_id: {:?}",
292                    object_id
293                );
294                return None;
295            }
296        };
297        let object = match self.input_objects.get(object_id) {
298            // A declared input is the object this transaction was sequenced against, so it is
299            // the same object the implicit read must see.
300            Some(object) => {
301                if object.version() != version.version {
302                    debug_fatal!(
303                        "declared input {object_id} at version {:?} disagrees with its implicit \
304                         read version {:?}",
305                        object.version(),
306                        version.version
307                    );
308                    return None;
309                }
310                object.clone()
311            }
312            None => self
313                .store
314                // If this transaction needs to read an implicit system object,
315                // the version must be assigned before execution.
316                .load_implicitly_read_system_object(object_id, version)?,
317        };
318        // Record the read version so it can be emitted into effects as a read-only consensus object and
319        // reproduced on replay.
320        self.loaded_system_objects
321            .borrow_mut()
322            .insert(*object_id, (object.version(), object.digest()));
323        Some(object)
324    }
325
326    pub fn unsettled_object_funds(&self) -> &dyn UnsettledObjectFundsRead {
327        self.unsettled_object_funds
328    }
329
330    // Helpers to access private fields
331    pub fn objects(&self) -> &BTreeMap<ObjectID, Object> {
332        &self.input_objects
333    }
334
335    pub fn update_object_version_and_prev_tx(&mut self) {
336        self.execution_results.update_version_and_previous_tx(
337            self.lamport_timestamp,
338            self.tx_digest,
339            &self.input_objects,
340            self.protocol_config.reshare_at_same_initial_version(),
341        );
342
343        #[cfg(debug_assertions)]
344        {
345            self.check_invariants();
346        }
347    }
348
349    fn calculate_accumulator_running_max_withdraws(&self) -> BTreeMap<AccumulatorObjId, u128> {
350        let mut running_net_withdraws: BTreeMap<AccumulatorObjId, i128> = BTreeMap::new();
351        let mut running_max_withdraws: BTreeMap<AccumulatorObjId, u128> = BTreeMap::new();
352        for event in &self.execution_results.accumulator_events {
353            match &event.write.value {
354                AccumulatorValue::Integer(amount) => match event.write.operation {
355                    AccumulatorOperation::Split => {
356                        let entry = running_net_withdraws
357                            .entry(event.accumulator_obj)
358                            .or_default();
359                        *entry += *amount as i128;
360                        if *entry > 0 {
361                            let max_entry = running_max_withdraws
362                                .entry(event.accumulator_obj)
363                                .or_default();
364                            *max_entry = (*max_entry).max(*entry as u128);
365                        }
366                    }
367                    AccumulatorOperation::Merge => {
368                        let entry = running_net_withdraws
369                            .entry(event.accumulator_obj)
370                            .or_default();
371                        *entry -= *amount as i128;
372                    }
373                },
374                AccumulatorValue::IntegerTuple(_, _) | AccumulatorValue::EventDigest(_) => {}
375            }
376        }
377        running_max_withdraws
378    }
379
380    /// Ensure that, per accumulator object, the gross Merge total and gross Split total are
381    /// representable: bounded by the total SUI supply for `Balance<SUI>` keys, and by `u64::MAX`
382    /// otherwise.
383    ///
384    /// `AccumulatorWriteV1::merge` folds all writes for a key by summing Merge amounts and Split
385    /// amounts separately into `u64`s. The object runtime caps Move-native merges per key at
386    /// `u64::MAX`, but the gas charger emits additional, uncapped SUI deposit/withdraw events during
387    /// gas smashing and gas charging (e.g. a refund Merge to an address balance), so a per-key SUI
388    /// total could be pushed past `u64::MAX`, overflowing that fold (and the SUI-conservation sum).
389    /// Reaching such a total requires SUI from an object-sourced withdrawal whose backing is only
390    /// verified at settlement.
391    ///
392    /// Bounding SUI to `TOTAL_SUPPLY_MIST` rejects any such amount here, *before* gas is charged, so
393    /// the rejected PTB-emitted writes are dropped on gas reset and only the (bounded) gas events
394    /// remain. Crucially, `TOTAL_SUPPLY_MIST` is ~8.4B SUI below `u64::MAX`, so the gas events emitted
395    /// after this check (which move only real SUI) cannot push any per-key total past `u64::MAX` -
396    /// hence they need not be re-checked. Non-SUI balances have no uncapped gas path, so the
397    /// object-runtime per-key `u64::MAX` cap is the binding guard there and we only backstop u64
398    /// representability.
399    ///
400    /// The per-key limits are not sufficient on their own: withdrawn SUI can be spread across several
401    /// object keys (each withdrawal `<= TOTAL_SUPPLY_MIST`) and then recombined *outside* the
402    /// accumulator - e.g. each withdrawal redeemed to a `Coin<SUI>` and merged into the PTB gas coin
403    /// via `MergeCoins`, which is an object mutation, not an accumulator event. The recombined coin
404    /// can then reach `u64::MAX` and overflow `deduct_gas` on a refund. So we also bound the
405    /// *cross-key* total SUI withdrawn (gross Split) to the supply, capping the total SUI a single
406    /// transaction can withdraw regardless of how it is later recombined.
407    pub(crate) fn check_accumulator_amounts_representable(&self) -> Result<(), ExecutionError> {
408        let supply = sui_types::gas_coin::TOTAL_SUPPLY_MIST as u128;
409        let mut merge_totals: BTreeMap<AccumulatorObjId, u128> = BTreeMap::new();
410        let mut split_totals: BTreeMap<AccumulatorObjId, u128> = BTreeMap::new();
411        // Cross-key total of SUI withdrawn (gross Split), bounded to the supply (see above).
412        let mut total_sui_split: u128 = 0;
413        for event in &self.execution_results.accumulator_events {
414            let AccumulatorValue::Integer(amount) = event.write.value else {
415                continue;
416            };
417            let amount = amount as u128;
418            // SUI cannot exceed its total supply through any single balance. Bounding to the supply
419            // (rather than u64::MAX) leaves headroom for the not-yet-emitted gas events.
420            let is_sui = sui_types::gas_coin::GasCoin::is_gas_balance_type(&event.write.address.ty);
421            let limit = if is_sui { supply } else { u64::MAX as u128 };
422            let total = match event.write.operation {
423                AccumulatorOperation::Merge => {
424                    merge_totals.entry(event.accumulator_obj).or_default()
425                }
426                AccumulatorOperation::Split => {
427                    split_totals.entry(event.accumulator_obj).or_default()
428                }
429            };
430            *total += amount;
431            if *total > limit {
432                return Err(ExecutionError::new_with_source(
433                    ExecutionErrorKind::CoinBalanceOverflow,
434                    format!(
435                        "accumulator balance change for {:?} exceeds the representable limit \
436                         (gross total {}, limit {})",
437                        event.accumulator_obj, *total, limit
438                    ),
439                ));
440            }
441            if is_sui && matches!(event.write.operation, AccumulatorOperation::Split) {
442                total_sui_split += amount;
443                if total_sui_split > supply {
444                    return Err(ExecutionError::new_with_source(
445                        ExecutionErrorKind::CoinBalanceOverflow,
446                        format!(
447                            "total SUI withdrawn across all accumulators ({total_sui_split}) \
448                             exceeds the total supply ({supply})"
449                        ),
450                    ));
451                }
452            }
453        }
454        Ok(())
455    }
456
457    /// Ensure that there is one entry for each accumulator object in the accumulator events.
458    fn merge_accumulator_events(&mut self) {
459        self.execution_results.accumulator_events = self
460            .execution_results
461            .accumulator_events
462            .iter()
463            .fold(
464                BTreeMap::<AccumulatorObjId, Vec<AccumulatorWriteV1>>::new(),
465                |mut map, event| {
466                    map.entry(event.accumulator_obj)
467                        .or_default()
468                        .push(event.write.clone());
469                    map
470                },
471            )
472            .into_iter()
473            .map(|(obj_id, writes)| {
474                AccumulatorEvent::new(obj_id, AccumulatorWriteV1::merge(writes))
475            })
476            .collect();
477    }
478
479    /// Break up the structure and return its internal stores (objects, active_inputs, written, deleted)
480    pub fn into_inner(
481        self,
482        accumulator_running_max_withdraws: BTreeMap<AccumulatorObjId, u128>,
483    ) -> InnerTemporaryStore {
484        let results = self.execution_results;
485        InnerTemporaryStore {
486            input_objects: self.input_objects,
487            stream_ended_consensus_objects: self.stream_ended_consensus_objects,
488            mutable_inputs: self.mutable_input_refs,
489            written: results.written_objects,
490            events: TransactionEvents {
491                data: results.user_events,
492            },
493            accumulator_events: results.accumulator_events,
494            loaded_runtime_objects: self.loaded_runtime_objects,
495            runtime_packages_loaded_from_db: self.runtime_packages_loaded_from_db.into_inner(),
496            lamport_version: self.lamport_timestamp,
497            binary_config: self.protocol_config.binary_config(None),
498            accumulator_running_max_withdraws,
499        }
500    }
501
502    /// For every object from active_inputs (i.e. all mutable objects), if they are not
503    /// mutated during the transaction execution, force mutating them by incrementing the
504    /// sequence number. This is required to achieve safety.
505    pub(crate) fn ensure_active_inputs_mutated(&mut self) {
506        let mut to_be_updated = vec![];
507        // Note: we do not mutate input objects if they are non-exclusive write
508        for id in self.mutable_input_refs.keys() {
509            if !self.execution_results.modified_objects.contains(id) {
510                // We cannot update here but have to push to `to_be_updated` and update later
511                // because the for loop is holding a reference to `self`, and calling
512                // `self.mutate_input_object` requires a mutable reference to `self`.
513                to_be_updated.push(self.input_objects[id].clone());
514            }
515        }
516        for object in to_be_updated {
517            // The object must be mutated as it was present in the input objects
518            self.mutate_input_object(object.clone());
519        }
520    }
521
522    fn get_object_changes(&self) -> BTreeMap<ObjectID, EffectsObjectChange> {
523        let results = &self.execution_results;
524        let all_ids = results
525            .created_object_ids
526            .iter()
527            .chain(&results.deleted_object_ids)
528            .chain(&results.modified_objects)
529            .chain(results.written_objects.keys())
530            .collect::<BTreeSet<_>>();
531        all_ids
532            .into_iter()
533            .map(|id| {
534                (
535                    *id,
536                    EffectsObjectChange::new(
537                        self.get_object_modified_at(id)
538                            .map(|metadata| ((metadata.version, metadata.digest), metadata.owner)),
539                        results.written_objects.get(id),
540                        results.created_object_ids.contains(id),
541                        results.deleted_object_ids.contains(id),
542                    ),
543                )
544            })
545            .chain(results.accumulator_events.iter().cloned().map(
546                |AccumulatorEvent {
547                     accumulator_obj,
548                     write,
549                 }| {
550                    (
551                        *accumulator_obj.inner(),
552                        EffectsObjectChange::new_from_accumulator_write(write),
553                    )
554                },
555            ))
556            .collect()
557    }
558
559    pub fn into_effects(
560        mut self,
561        shared_object_refs: Vec<SharedInput>,
562        transaction_digest: &TransactionDigest,
563        gas_cost_summary: GasCostSummary,
564        status: ExecutionStatus,
565        gas_coin: Option<ObjectID>,
566        epoch: EpochId,
567    ) -> (InnerTemporaryStore, TransactionEffects) {
568        // Defense-in-depth: Owner::Party is not yet supported as an effect output. There are
569        // no constructions of `Owner::Party` yet so a hard assert should be safe.
570        for (id, obj) in &self.execution_results.written_objects {
571            assert!(
572                !matches!(obj.owner, Owner::Party { .. }),
573                "Party-owned objects are not yet supported (object {id})"
574            );
575        }
576
577        self.update_object_version_and_prev_tx();
578        // This must happens before merge_accumulator_events.
579        let accumulator_running_max_withdraws = self.calculate_accumulator_running_max_withdraws();
580        self.merge_accumulator_events();
581
582        assert!(self.protocol_config.enable_effects_v2());
583
584        let object_changes = self.get_object_changes();
585
586        let lamport_version = self.lamport_timestamp;
587        // TODO: Cleanup this clone. Potentially add unchanged_shraed_objects directly to InnerTempStore.
588        let loaded_per_epoch_config_objects = self.loaded_per_epoch_config_objects.read().clone();
589        let loaded_system_objects = self.loaded_system_objects.borrow().clone();
590        let unchanged_consensus_objects = TransactionEffectsV2::compute_unchanged_consensus_objects(
591            shared_object_refs,
592            loaded_per_epoch_config_objects,
593            &object_changes,
594            loaded_system_objects,
595        );
596        let inner = self.into_inner(accumulator_running_max_withdraws);
597
598        let effects = TransactionEffects::new_from_execution_v2(
599            status,
600            epoch,
601            gas_cost_summary,
602            unchanged_consensus_objects,
603            *transaction_digest,
604            lamport_version,
605            object_changes,
606            gas_coin,
607            if inner.events.data.is_empty() {
608                None
609            } else {
610                Some(inner.events.digest())
611            },
612            vec![],
613        );
614
615        (inner, effects)
616    }
617
618    /// An internal check of the invariants (will only fire in debug)
619    #[cfg(debug_assertions)]
620    fn check_invariants(&self) {
621        // Check not both deleted and written
622        debug_assert!(
623            {
624                self.execution_results
625                    .written_objects
626                    .keys()
627                    .all(|id| !self.execution_results.deleted_object_ids.contains(id))
628            },
629            "Object both written and deleted."
630        );
631
632        // Check all mutable inputs are modified
633        debug_assert!(
634            {
635                self.mutable_input_refs
636                    .keys()
637                    .all(|id| self.execution_results.modified_objects.contains(id))
638            },
639            "Mutable input not modified."
640        );
641
642        debug_assert!(
643            {
644                self.execution_results
645                    .written_objects
646                    .values()
647                    .all(|obj| obj.previous_transaction == self.tx_digest)
648            },
649            "Object previous transaction not properly set",
650        );
651    }
652
653    /// Mutate a mutable input object. This is used to mutate input objects outside of PT execution.
654    pub fn mutate_input_object(&mut self, object: Object) {
655        let id = object.id();
656        debug_assert!(self.input_objects.contains_key(&id));
657        debug_assert!(!object.is_immutable());
658        self.execution_results.modified_objects.insert(id);
659        self.execution_results.written_objects.insert(id, object);
660    }
661
662    pub fn mutate_new_or_input_object(&mut self, object: Object) {
663        let id = object.id();
664        debug_assert!(!object.is_immutable());
665        if self.input_objects.contains_key(&id) {
666            self.execution_results.modified_objects.insert(id);
667        }
668        self.execution_results.written_objects.insert(id, object);
669    }
670
671    /// Mutate a child object outside of PT. This should be used extremely rarely.
672    /// Currently it's only used by advance_epoch_safe_mode because it's all native
673    /// without PT. This should almost never be used otherwise.
674    pub fn mutate_child_object(&mut self, old_object: Object, new_object: Object) {
675        let id = new_object.id();
676        let old_ref = old_object.compute_object_reference();
677        debug_assert_eq!(old_ref.0, id);
678        self.loaded_runtime_objects.insert(
679            id,
680            DynamicallyLoadedObjectMetadata {
681                version: old_ref.1,
682                digest: old_ref.2,
683                owner: old_object.owner.clone(),
684                storage_rebate: old_object.storage_rebate,
685                previous_transaction: old_object.previous_transaction,
686            },
687        );
688        self.execution_results.modified_objects.insert(id);
689        self.execution_results
690            .written_objects
691            .insert(id, new_object);
692    }
693
694    /// Upgrade system package during epoch change. This requires special treatment
695    /// since the system package to be upgraded is not in the input objects.
696    /// We could probably fix above to make it less special.
697    pub fn upgrade_system_package(&mut self, package: Object) {
698        let id = package.id();
699        assert!(package.is_package() && is_system_package(id));
700        self.execution_results.modified_objects.insert(id);
701        self.execution_results.written_objects.insert(id, package);
702    }
703
704    /// Crate a new objcet. This is used to create objects outside of PT execution.
705    pub fn create_object(&mut self, object: Object) {
706        // Created mutable objects' versions are set to the store's lamport timestamp when it is
707        // committed to effects. Creating an object at a non-zero version risks violating the
708        // lamport timestamp invariant (that a transaction's lamport timestamp is strictly greater
709        // than all versions witnessed by the transaction).
710        debug_assert!(
711            object.is_immutable() || object.version() == SequenceNumber::MIN,
712            "Created mutable objects should not have a version set",
713        );
714        let id = object.id();
715        self.execution_results.created_object_ids.insert(id);
716        self.execution_results.written_objects.insert(id, object);
717    }
718
719    /// Delete a mutable input object. This is used to delete input objects outside of PT execution.
720    pub fn delete_input_object(&mut self, id: &ObjectID) {
721        // there should be no deletion after write
722        debug_assert!(!self.execution_results.written_objects.contains_key(id));
723        debug_assert!(self.input_objects.contains_key(id));
724        self.execution_results.modified_objects.insert(*id);
725        self.execution_results.deleted_object_ids.insert(*id);
726    }
727
728    pub fn drop_writes(&mut self) {
729        self.execution_results.drop_writes();
730        self.invariants = InvariantChecker::default();
731    }
732
733    /// Consume this (post-execution) store and return the store used by a `BumpOnly` exit: keep
734    /// the input-derived state as well as information about the execution needed for replay,
735    /// discard everything related to the execution results, then bump the mutable inputs.
736    pub(crate) fn into_bump_only(self) -> Self {
737        let Self {
738            // Input-derived - reused verbatim.
739            store,
740            tx_digest,
741            input_objects,
742            non_exclusive_input_original_versions,
743            stream_ended_consensus_objects,
744            lamport_timestamp,
745            mutable_input_refs,
746            receiving_objects,
747            cur_epoch,
748            protocol_config,
749            post_execution_check_inputs,
750            system_object_versions,
751            // Represents what happened during execution, which needs to be kept.
752            loaded_runtime_objects,
753            runtime_packages_loaded_from_db,
754            loaded_per_epoch_config_objects,
755            loaded_system_objects,
756            unsettled_object_funds,
757            // Execution outcomes can be discarded.
758            execution_results: _,
759            invariants: _,
760        } = self;
761        let mut bump_only = Self {
762            store,
763            tx_digest,
764            input_objects,
765            non_exclusive_input_original_versions,
766            stream_ended_consensus_objects,
767            lamport_timestamp,
768            mutable_input_refs,
769            receiving_objects,
770            cur_epoch,
771            protocol_config,
772            loaded_runtime_objects,
773            runtime_packages_loaded_from_db,
774            loaded_per_epoch_config_objects,
775            post_execution_check_inputs,
776            system_object_versions,
777            loaded_system_objects,
778            unsettled_object_funds,
779            execution_results: ExecutionResultsV2::default(),
780            invariants: InvariantChecker::default(),
781        };
782        // The only writes a BumpOnly exit records: bump the versions of the mutable inputs it locked.
783        bump_only.ensure_active_inputs_mutated();
784        bump_only
785    }
786
787    pub fn read_object(&self, id: &ObjectID) -> Option<&Object> {
788        // there should be no read after delete
789        debug_assert!(!self.execution_results.deleted_object_ids.contains(id));
790        self.execution_results
791            .written_objects
792            .get(id)
793            .or_else(|| self.input_objects.get(id))
794    }
795
796    pub fn save_loaded_runtime_objects(
797        &mut self,
798        loaded_runtime_objects: BTreeMap<ObjectID, DynamicallyLoadedObjectMetadata>,
799    ) {
800        #[cfg(debug_assertions)]
801        {
802            for (id, v1) in &loaded_runtime_objects {
803                if let Some(v2) = self.loaded_runtime_objects.get(id) {
804                    assert_eq!(v1, v2);
805                }
806            }
807            for (id, v1) in &self.loaded_runtime_objects {
808                if let Some(v2) = loaded_runtime_objects.get(id) {
809                    assert_eq!(v1, v2);
810                }
811            }
812        }
813        // Merge the two maps because we may be calling the execution engine more than once
814        // (e.g. in advance epoch transaction, where we may be publishing a new system package).
815        self.loaded_runtime_objects.extend(loaded_runtime_objects);
816    }
817
818    pub fn save_wrapped_object_containers(
819        &mut self,
820        wrapped_object_containers: BTreeMap<ObjectID, ObjectID>,
821    ) {
822        self.invariants
823            .save_wrapped_object_containers(wrapped_object_containers);
824    }
825
826    pub fn save_generated_object_ids(&mut self, generated_ids: BTreeSet<ObjectID>) {
827        self.invariants.save_generated_object_ids(generated_ids);
828    }
829
830    pub fn estimate_effects_size_upperbound(&self) -> usize {
831        let complete_effects_size_estimate = self.protocol_config.complete_effects_size_estimate();
832
833        let (num_id_only_changes, num_unchanged_consensus_objects) =
834            if complete_effects_size_estimate {
835                (
836                    self.count_id_only_changes(),
837                    self.count_unchanged_consensus_objects_upperbound(),
838                )
839            } else {
840                (0, 0)
841            };
842
843        TransactionEffects::estimate_effects_size_upperbound_v2(
844            self.execution_results.written_objects.len(),
845            self.execution_results.modified_objects.len(),
846            self.input_objects.len(),
847            num_id_only_changes,
848            num_unchanged_consensus_objects,
849            &self.execution_results.accumulator_events,
850            complete_effects_size_estimate,
851        )
852    }
853
854    /// Counts the IDs that `get_object_changes` records without a written or modified object:
855    /// objects created then wrapped, and objects unwrapped then deleted.
856    fn count_id_only_changes(&self) -> usize {
857        let results = &self.execution_results;
858        results
859            .created_object_ids
860            .iter()
861            .chain(&results.deleted_object_ids)
862            .filter(|id| {
863                !results.written_objects.contains_key(id) && !results.modified_objects.contains(id)
864            })
865            .count()
866    }
867
868    /// Upper bound on the entries that `compute_unchanged_consensus_objects` records: read-only
869    /// consensus inputs, inputs whose consensus stream ended, per-epoch config objects and system
870    /// objects loaded during execution. Cancelled inputs are left out because a cancelled
871    /// transaction runs no commands, so its effects stay small.
872    fn count_unchanged_consensus_objects_upperbound(&self) -> usize {
873        let results = &self.execution_results;
874        let read_only_consensus_inputs = self
875            .input_objects
876            .iter()
877            .filter(|(id, obj)| obj.owner.is_consensus() && !results.modified_objects.contains(id))
878            .count();
879        read_only_consensus_inputs
880            .saturating_add(self.stream_ended_consensus_objects.len())
881            .saturating_add(self.loaded_per_epoch_config_objects.read().len())
882            .saturating_add(self.loaded_system_objects.borrow().len())
883    }
884
885    pub fn written_objects_size(&self) -> usize {
886        self.execution_results
887            .written_objects
888            .values()
889            .fold(0, |sum, obj| sum + obj.object_size_for_gas_metering())
890    }
891
892    /// Validates gasless post-execution requirements:
893    /// - No new objects were created or existing objects mutated (written_objects is empty)
894    /// - The set of deleted objects exactly equals the set of input Coin objects
895    /// - Each recipient receives at least the minimum transfer amount per token type
896    /// - Unused withdrawal reservation (reservation - actual split) is 0 or >= min_amount
897    pub(crate) fn check_gasless_execution_requirements(&self) -> Result<(), String> {
898        use sui_types::balance::Balance;
899
900        if !self.execution_results.written_objects.is_empty() {
901            return Err("Gasless transactions cannot create or mutate objects".to_string());
902        }
903
904        let input_coin_ids: BTreeSet<ObjectID> = self
905            .input_objects
906            .iter()
907            .filter(|(_, obj)| obj.coin_type_maybe().is_some())
908            .map(|(id, _)| *id)
909            .collect();
910        if self.execution_results.deleted_object_ids != input_coin_ids {
911            return Err(format!(
912                "Gasless transaction must destroy exactly its input Coins. \
913                 Expected: {input_coin_ids:?}, deleted: {:?}",
914                self.execution_results.deleted_object_ids
915            ));
916        }
917
918        let allowed_types =
919            sui_types::transaction::get_gasless_allowed_token_types(self.protocol_config);
920
921        // Aggregate signed balance changes per (address, token_type).
922        // Positive nets are recipient deposits that must meet the minimum transfer amount.
923        let net_totals = sui_types::balance_change::signed_balance_changes_from_events(
924            &self.execution_results.accumulator_events,
925        )
926        .fold(
927            BTreeMap::<(SuiAddress, TypeTag), i128>::new(),
928            |mut totals, (address, token_type, signed_amount)| {
929                *totals.entry((address, token_type)).or_default() += signed_amount;
930                totals
931            },
932        );
933
934        for ((recipient, token_type), net_amount) in &net_totals {
935            if *net_amount <= 0 {
936                continue;
937            }
938            if let Some(&min_amount) = allowed_types.get(token_type)
939                && *net_amount < i128::from(min_amount)
940            {
941                return Err(format!(
942                    "Gasless transfer of {net_amount} to {recipient} is below \
943                     minimum {min_amount} for token type {token_type}"
944                ));
945            }
946        }
947
948        // Gasless requirements are expressed in coin types `T`, while the shared input reservation
949        // budget is keyed by accumulator types `Balance<T>`.
950        let withdrawal_reservations: BTreeMap<(SuiAddress, TypeTag), u64> = self
951            .post_execution_check_inputs
952            .input_reservations
953            .iter()
954            .filter_map(|((owner, ty), amount)| {
955                Balance::maybe_get_balance_type_param(ty)
956                    .map(|coin_type| ((*owner, coin_type), *amount))
957            })
958            .collect();
959        for ((owner, token_type), &reserved) in &withdrawal_reservations {
960            let net = net_totals
961                .get(&(*owner, token_type.clone()))
962                .copied()
963                .unwrap_or(0);
964            let remaining = (reserved as i128).saturating_add(net);
965            if remaining > 0
966                && let Some(&min_balance_remaining) = allowed_types.get(token_type)
967                && min_balance_remaining > 0
968                && remaining < min_balance_remaining as i128
969            {
970                return Err(format!(
971                    "Gasless withdrawal leaves {remaining} unused for {owner}, \
972                     below minimum {min_balance_remaining} for token type {token_type}"
973                ));
974            }
975        }
976
977        Ok(())
978    }
979
980    /// If there are unmetered storage rebate (due to system transaction), we put them into
981    /// the storage rebate of 0x5 object.
982    /// TODO: This will not work for potential future new system transactions if 0x5 is not in the input.
983    /// We should fix this.
984    pub fn conserve_unmetered_storage_rebate(&mut self, unmetered_storage_rebate: u64) {
985        if unmetered_storage_rebate == 0 {
986            // If unmetered_storage_rebate is 0, we are most likely executing the genesis transaction.
987            // And in that case we cannot mutate the 0x5 object because it's newly created.
988            // And there is no storage rebate that needs distribution anyway.
989            return;
990        }
991        tracing::debug!(
992            "Amount of unmetered storage rebate from system tx: {:?}",
993            unmetered_storage_rebate
994        );
995        let mut system_state_wrapper = self
996            .read_object(&SUI_SYSTEM_STATE_OBJECT_ID)
997            .expect("0x5 object must be mutated in system tx with unmetered storage rebate")
998            .clone();
999        // In unmetered execution, storage_rebate field of mutated object must be 0.
1000        // If not, we would be dropping SUI on the floor by overriding it.
1001        assert_eq!(system_state_wrapper.storage_rebate, 0);
1002        system_state_wrapper.storage_rebate = unmetered_storage_rebate;
1003        self.mutate_input_object(system_state_wrapper);
1004    }
1005
1006    /// Add an accumulator event to the execution results.
1007    pub fn add_accumulator_event(&mut self, event: AccumulatorEvent) {
1008        self.execution_results.accumulator_events.push(event);
1009    }
1010
1011    /// Given an object ID, if it's not modified, returns None.
1012    /// Otherwise returns its metadata, including version, digest, owner and storage rebate.
1013    /// A modified object must be either a mutable input, or a loaded child object.
1014    /// The only exception is when we upgrade system packages, in which case the upgraded
1015    /// system packages are not part of input, but are modified.
1016    fn get_object_modified_at(
1017        &self,
1018        object_id: &ObjectID,
1019    ) -> Option<DynamicallyLoadedObjectMetadata> {
1020        if self.execution_results.modified_objects.contains(object_id) {
1021            Some(
1022                self.mutable_input_refs
1023                    .get(object_id)
1024                    .map(
1025                        |((version, digest), owner)| DynamicallyLoadedObjectMetadata {
1026                            version: *version,
1027                            digest: *digest,
1028                            owner: owner.clone(),
1029                            // It's guaranteed that a mutable input object is an input object.
1030                            storage_rebate: self.input_objects[object_id].storage_rebate,
1031                            previous_transaction: self.input_objects[object_id]
1032                                .previous_transaction,
1033                        },
1034                    )
1035                    .or_else(|| self.loaded_runtime_objects.get(object_id).cloned())
1036                    .unwrap_or_else(|| {
1037                        debug_assert!(is_system_package(*object_id));
1038                        let package_obj =
1039                            self.store.get_package_object(object_id).unwrap().unwrap();
1040                        let obj = package_obj.object();
1041                        DynamicallyLoadedObjectMetadata {
1042                            version: obj.version(),
1043                            digest: obj.digest(),
1044                            owner: obj.owner.clone(),
1045                            storage_rebate: obj.storage_rebate,
1046                            previous_transaction: obj.previous_transaction,
1047                        }
1048                    }),
1049            )
1050        } else {
1051            None
1052        }
1053    }
1054
1055    pub fn protocol_config(&self) -> &'backing ProtocolConfig {
1056        self.protocol_config
1057    }
1058
1059    /// Run the (read-only) SUI-conservation and balance-accumulator invariant checks.
1060    /// See [`invariants::InvariantChecker::check_conservation_invariants`].
1061    pub(crate) fn check_conservation_invariants<Mode: ExecutionMode>(
1062        &self,
1063        move_vm: &Arc<MoveRuntime>,
1064        enable_expensive_checks: bool,
1065        cost_summary: &GasCostSummary,
1066    ) -> Result<(), ExecutionError> {
1067        self.invariants.check_conservation_invariants::<Mode>(
1068            self,
1069            move_vm,
1070            enable_expensive_checks,
1071            cost_summary,
1072        )
1073    }
1074
1075    /// Check that every modified object traces back to an authenticated owner.
1076    /// See [`invariants::InvariantChecker::check_ownership_invariants`].
1077    /// See [`invariants::InvariantChecker::check_published_packages`].
1078    pub(crate) fn check_published_packages(&self) -> Result<(), ExecutionError> {
1079        self.invariants.check_published_packages(self)
1080    }
1081
1082    pub(crate) fn check_ownership_invariants(
1083        &self,
1084        sender: &SuiAddress,
1085        sponsor: &Option<SuiAddress>,
1086        charged_gas: &ChargedGas,
1087        is_epoch_change: bool,
1088    ) -> SuiResult<()> {
1089        self.invariants.check_ownership_invariants(
1090            self,
1091            sender,
1092            sponsor,
1093            charged_gas,
1094            is_epoch_change,
1095        )
1096    }
1097}
1098
1099impl TemporaryStore<'_> {
1100    // The storage cost of each written object and the rebate of each deleted object. Each
1101    // written object gets its new storage rebate.
1102    pub(crate) fn collect_storage_and_rebate(
1103        &mut self,
1104        rates: &StorageRates,
1105    ) -> Result<StorageCharge, ExecutionError> {
1106        let mut charge = StorageCharge::default();
1107        // Use two loops because we cannot mut iterate written while calling get_object_modified_at.
1108        let old_storage_rebates: Vec<_> = self
1109            .execution_results
1110            .written_objects
1111            .keys()
1112            .map(|object_id| {
1113                self.get_object_modified_at(object_id)
1114                    .map(|metadata| metadata.storage_rebate)
1115                    .unwrap_or_default()
1116            })
1117            .collect();
1118        for (object, old_storage_rebate) in self
1119            .execution_results
1120            .written_objects
1121            .values_mut()
1122            .zip_debug_eq(old_storage_rebates)
1123        {
1124            // new object size
1125            let new_object_size = object.object_size_for_gas_metering();
1126            // track changes and compute the new object `storage_rebate`
1127            let new_storage_rebate = charge
1128                .track_mutation(rates, object.id(), new_object_size, old_storage_rebate)
1129                .ok_or_else(|| ExecutionError::from_kind(ExecutionErrorKind::InvariantViolation))?;
1130            object.storage_rebate = new_storage_rebate;
1131        }
1132        self.track_deleted(rates, &mut charge)?;
1133        Ok(charge)
1134    }
1135
1136    // The rebates of the deleted objects only.
1137    pub(crate) fn collect_rebate_only(
1138        &self,
1139        rates: &StorageRates,
1140    ) -> Result<StorageCharge, ExecutionError> {
1141        let mut charge = StorageCharge::default();
1142        self.track_deleted(rates, &mut charge)?;
1143        Ok(charge)
1144    }
1145
1146    fn track_deleted(
1147        &self,
1148        rates: &StorageRates,
1149        charge: &mut StorageCharge,
1150    ) -> Result<(), ExecutionError> {
1151        for object_id in &self.execution_results.modified_objects {
1152            if self
1153                .execution_results
1154                .written_objects
1155                .contains_key(object_id)
1156            {
1157                continue;
1158            }
1159            // get and track the deleted object `storage_rebate`
1160            let storage_rebate = self
1161                .get_object_modified_at(object_id)
1162                // Unwrap is safe because this loop iterates through all modified objects.
1163                .unwrap()
1164                .storage_rebate;
1165            charge
1166                .track_mutation(rates, *object_id, 0, storage_rebate)
1167                .ok_or_else(|| ExecutionError::from_kind(ExecutionErrorKind::InvariantViolation))?;
1168        }
1169        Ok(())
1170    }
1171
1172    pub fn check_execution_results_consistency<Mode: ExecutionMode>(
1173        &self,
1174    ) -> Result<(), Mode::Error> {
1175        assert_invariant!(
1176            self.execution_results
1177                .created_object_ids
1178                .iter()
1179                .all(|id| !self.execution_results.deleted_object_ids.contains(id)
1180                    && !self.execution_results.modified_objects.contains(id)),
1181            "Created object IDs cannot also be deleted or modified"
1182        );
1183        assert_invariant!(
1184            self.execution_results.modified_objects.iter().all(|id| {
1185                self.mutable_input_refs.contains_key(id)
1186                    || self.loaded_runtime_objects.contains_key(id)
1187                    || is_system_package(*id)
1188            }),
1189            "A modified object must be either a mutable input, a loaded child object, or a system package"
1190        );
1191        Ok(())
1192    }
1193}
1194//==============================================================================
1195// Charge gas current - end
1196//==============================================================================
1197
1198impl TemporaryStore<'_> {
1199    pub fn advance_epoch_safe_mode(
1200        &mut self,
1201        params: &AdvanceEpochParams,
1202        protocol_config: &ProtocolConfig,
1203    ) {
1204        let wrapper = get_sui_system_state_wrapper(self.store)
1205            .expect("System state wrapper object must exist");
1206        let (old_object, new_object) =
1207            wrapper.advance_epoch_safe_mode(params, self.store, protocol_config);
1208        self.mutate_child_object(old_object, new_object);
1209    }
1210}
1211
1212impl ExecutionState for TemporaryStore<'_> {
1213    fn lamport_timestamp(&self) -> SequenceNumber {
1214        self.lamport_timestamp
1215    }
1216
1217    fn freeze_list_version(&self) -> Option<SequenceNumber> {
1218        self.system_object_versions
1219            .get(&SUI_FREEZE_LIST_OBJECT_ID)?;
1220        let object = self.load_implicitly_read_system_object(&SUI_FREEZE_LIST_OBJECT_ID)?;
1221        Some(object.version())
1222    }
1223}
1224
1225impl RuntimeObjectResolver for TemporaryStore<'_> {
1226    fn read_child_object(
1227        &self,
1228        parent: &ObjectID,
1229        child: &ObjectID,
1230        child_version_upper_bound: SequenceNumber,
1231    ) -> SuiResult<Option<Object>> {
1232        let obj_opt = self.execution_results.written_objects.get(child);
1233        if obj_opt.is_some() {
1234            Ok(obj_opt.cloned())
1235        } else {
1236            let _scope = monitored_scope("Execution::read_child_object");
1237            self.store
1238                .read_child_object(parent, child, child_version_upper_bound)
1239        }
1240    }
1241
1242    fn get_object_received_at_version(
1243        &self,
1244        owner: &ObjectID,
1245        receiving_object_id: &ObjectID,
1246        receive_object_at_version: SequenceNumber,
1247        epoch_id: EpochId,
1248    ) -> SuiResult<Option<Object>> {
1249        // You should never be able to try and receive an object after deleting it or writing it in the same
1250        // transaction since `Receiving` doesn't have copy.
1251        debug_assert!(
1252            !self
1253                .execution_results
1254                .written_objects
1255                .contains_key(receiving_object_id)
1256        );
1257        debug_assert!(
1258            !self
1259                .execution_results
1260                .deleted_object_ids
1261                .contains(receiving_object_id)
1262        );
1263        self.store.get_object_received_at_version(
1264            owner,
1265            receiving_object_id,
1266            receive_object_at_version,
1267            epoch_id,
1268        )
1269    }
1270}
1271
1272impl ImplicitSystemObjectResolver for TemporaryStore<'_> {
1273    /// Loads the object balance at the required version and subtracts withdrawals from the same
1274    /// checkpoint that have not settled yet.
1275    /// This function is expected never to fail; an error indicates an invariant violation.
1276    fn object_available_balance(&self, owner: SuiAddress, type_: &TypeTag) -> SuiResult<u128> {
1277        let required_version = self
1278            .load_implicitly_read_system_object(&SUI_ACCUMULATOR_ROOT_OBJECT_ID)
1279            .ok_or(SuiErrorKind::ExecutionInvariantViolation)?
1280            .version();
1281
1282        let settled = AccumulatorRootValue::load(self, Some(required_version), owner, type_)?
1283            .and_then(|value| value.as_u128())
1284            .unwrap_or(0);
1285
1286        let unsettled = self.unsettled_object_funds.get_unsettled_object_withdraw(
1287            &AccumulatorRootValue::get_field_id(owner, type_)?,
1288            required_version,
1289        );
1290        settled
1291            .checked_sub(unsettled)
1292            .ok_or_else(|| SuiErrorKind::ExecutionInvariantViolation.into())
1293    }
1294
1295    /// This function is expected never to fail; an error indicates an invariant violation.
1296    fn clock(&self) -> SuiResult<Object> {
1297        self.load_implicitly_read_system_object(&SUI_CLOCK_OBJECT_ID)
1298            .ok_or_else(|| SuiErrorKind::ExecutionInvariantViolation.into())
1299    }
1300}
1301
1302/// Compute the per-`(address, type)` funds-accumulator reservation budget authorized by the
1303/// transaction, and the allowance and SeizeAuth ids declared per key. Today every funds
1304/// accumulator is a `Balance<T>`, but the `(address, TypeTag)` keying lets this generalize as more
1305/// accumulator types are added. Budget sources:
1306/// - PTB `FundsWithdrawalArg`s for any supported accumulator type (sender, sponsor, allowance
1307///   funder, or frozen address as owner).
1308/// - Gas paid entirely from address balance (credits `(gas_owner, Balance<SUI>)`).
1309/// - Gas-data entries with coin-reservation digests (also credit `(gas_owner, Balance<SUI>)`).
1310fn compute_input_reservations(
1311    transaction_kind: &TransactionKind,
1312    gas_data: &GasData,
1313    transaction_signer: SuiAddress,
1314) -> InputReservations {
1315    use sui_types::balance::Balance;
1316    use sui_types::gas_coin::GAS;
1317    use sui_types::transaction::{Reservation, WithdrawFrom, is_gas_paid_from_address_balance};
1318
1319    let is_gasless = is_gasless_transaction(gas_data, transaction_kind);
1320    let mut reservations: BTreeMap<(SuiAddress, TypeTag), u64> = BTreeMap::new();
1321    let mut allowance_ids = AllowanceIds::new();
1322    let mut seize_auth_ids = SeizeAuthIds::new();
1323    let sui_balance_type = Balance::type_tag(GAS::type_tag());
1324
1325    for arg in transaction_kind.get_funds_withdrawals() {
1326        let ty = arg.type_arg.to_type_tag();
1327        let owner = match arg.withdraw_from {
1328            WithdrawFrom::Sender => transaction_signer,
1329            WithdrawFrom::Sponsor => gas_data.owner,
1330            // The funder will differ from the signer/sponsor, but permission
1331            // is verified at signing
1332            WithdrawFrom::SenderAllowance { funder, allowance } => {
1333                allowance_ids
1334                    .entry((funder, ty.clone()))
1335                    .or_default()
1336                    .push(allowance);
1337                funder
1338            }
1339            WithdrawFrom::FrozenAddress {
1340                seized_from,
1341                seize_auth,
1342            } => {
1343                let prev = seize_auth_ids.insert((seized_from, ty.clone()), seize_auth);
1344                debug_assert!(
1345                    prev.is_none(),
1346                    "Signing allows one FrozenAddress withdrawal per frozen address"
1347                );
1348                seized_from
1349            }
1350        };
1351        let Reservation::MaxAmountU64(reservation) = arg.reservation;
1352        let entry = reservations.entry((owner, ty)).or_insert(0);
1353        *entry = entry.saturating_add(reservation);
1354    }
1355
1356    // Gasless transactions charge no gas, so gas sources grant no reservation (their budget is
1357    // validated to be 0 anyway; skipping keeps the map free of a phantom zero entry).
1358    if !is_gasless && is_gas_paid_from_address_balance(gas_data, transaction_kind) {
1359        let entry = reservations
1360            .entry((gas_data.owner, sui_balance_type.clone()))
1361            .or_insert(0);
1362        *entry = entry.saturating_add(gas_data.budget);
1363    }
1364
1365    for entry in &gas_data.payment {
1366        if let Ok(parsed) = ParsedDigest::try_from(entry.2) {
1367            let entry = reservations
1368                .entry((gas_data.owner, sui_balance_type.clone()))
1369                .or_insert(0);
1370            *entry = entry.saturating_add(parsed.reservation_amount());
1371        }
1372    }
1373
1374    InputReservations {
1375        reservations,
1376        allowance_ids,
1377        seize_auth_ids,
1378    }
1379}
1380
1381/// What each `Publish`/`Upgrade` command declares about the package it writes, in command order.
1382/// `None` for transaction kinds that are not PTBs.
1383fn declared_packages(
1384    transaction_kind: &TransactionKind,
1385) -> Option<Vec<(usize, BTreeSet<ObjectID>)>> {
1386    let TransactionKind::ProgrammableTransaction(pt) = transaction_kind else {
1387        return None;
1388    };
1389    Some(
1390        pt.commands
1391            .iter()
1392            .filter_map(|command| match command {
1393                Command::Publish(modules, dep_ids) | Command::Upgrade(modules, dep_ids, _, _) => {
1394                    Some((modules.len(), dep_ids.iter().copied().collect()))
1395                }
1396                _ => None,
1397            })
1398            .collect(),
1399    )
1400}
1401
1402/// Compares the owner and payload of an object.
1403/// This is used to detect illegal writes to non-exclusive write objects.
1404fn was_object_mutated(object: &Object, original: &Object) -> bool {
1405    let data_equal = match (&object.data, &original.data) {
1406        (Data::Move(a), Data::Move(b)) => a.contents_and_type_equal(b),
1407        // We don't have a use for package content-equality, so we remain as strict as
1408        // possible for now.
1409        (Data::Package(a), Data::Package(b)) => a == b,
1410        _ => false,
1411    };
1412
1413    let owner_equal = match (&object.owner, &original.owner) {
1414        // We don't compare initial shared versions, because re-shared objects do not have the
1415        // correct initial shared version at this point in time, and this field is not something
1416        // that can be modified by a single transaction anyway.
1417        (Owner::Shared { .. }, Owner::Shared { .. }) => true,
1418        (
1419            Owner::ConsensusAddressOwner { owner: a, .. },
1420            Owner::ConsensusAddressOwner { owner: b, .. },
1421        ) => a == b,
1422        (Owner::AddressOwner(a), Owner::AddressOwner(b)) => a == b,
1423        (Owner::Immutable, Owner::Immutable) => true,
1424        (Owner::ObjectOwner(a), Owner::ObjectOwner(b)) => a == b,
1425        (
1426            Owner::Party {
1427                permissions: a,
1428                start_version: _,
1429            },
1430            Owner::Party {
1431                permissions: b,
1432                start_version: _,
1433            },
1434        ) => a == b,
1435
1436        // Keep the left hand side of the match exhaustive to catch future
1437        // changes to Owner
1438        (Owner::AddressOwner(_), _)
1439        | (Owner::Immutable, _)
1440        | (Owner::ObjectOwner(_), _)
1441        | (Owner::Shared { .. }, _)
1442        | (Owner::ConsensusAddressOwner { .. }, _)
1443        | (Owner::Party { .. }, _) => false,
1444    };
1445
1446    !data_equal || !owner_equal
1447}
1448
1449impl Storage for TemporaryStore<'_> {
1450    fn reset(&mut self) {
1451        self.drop_writes();
1452    }
1453
1454    fn read_object(&self, id: &ObjectID) -> Option<&Object> {
1455        TemporaryStore::read_object(self, id)
1456    }
1457
1458    /// Take execution results v2, and translate it back to be compatible with effects v1.
1459    fn record_execution_results(
1460        &mut self,
1461        results: ExecutionResults,
1462    ) -> Result<(), ExecutionError> {
1463        let ExecutionResults::V2(mut results) = results else {
1464            panic!("ExecutionResults::V2 expected in sui-execution v1 and above");
1465        };
1466
1467        // for all non-exclusive write inputs, remove them from written objects
1468        let mut to_remove = Vec::new();
1469        for (id, original) in &self.non_exclusive_input_original_versions {
1470            // Object must be present in `written_objects` and identical
1471            if results
1472                .written_objects
1473                .get(id)
1474                .map(|obj| was_object_mutated(obj, original))
1475                .unwrap_or(true)
1476            {
1477                return Err(ExecutionError::new_with_source(
1478                    ExecutionErrorKind::NonExclusiveWriteInputObjectModified { id: *id },
1479                    "Non-exclusive write input object has been modified or deleted",
1480                ));
1481            }
1482            to_remove.push(*id);
1483        }
1484
1485        for id in to_remove {
1486            results.written_objects.remove(&id);
1487            results.modified_objects.remove(&id);
1488        }
1489
1490        // It's important to merge instead of override results because it's
1491        // possible to execute PT more than once during tx execution.
1492        // Track the index range of accumulator events brought in here as PTB-emitted; the
1493        // address-balance change invariant (run inside `run_conservation_checks`) uses this
1494        // set to distinguish trusted PTB-emitted events from runtime-emitted ones.
1495        let event_start = self.execution_results.accumulator_events.len();
1496        self.execution_results.merge_results(
1497            results, /* consistent_merge */ true, /* invariant_checks */ true,
1498        )?;
1499        let event_end = self.execution_results.accumulator_events.len();
1500        self.invariants
1501            .record_ptb_event_range(event_start, event_end);
1502
1503        Ok(())
1504    }
1505
1506    fn save_loaded_runtime_objects(
1507        &mut self,
1508        loaded_runtime_objects: BTreeMap<ObjectID, DynamicallyLoadedObjectMetadata>,
1509    ) {
1510        TemporaryStore::save_loaded_runtime_objects(self, loaded_runtime_objects)
1511    }
1512
1513    fn save_wrapped_object_containers(
1514        &mut self,
1515        wrapped_object_containers: BTreeMap<ObjectID, ObjectID>,
1516    ) {
1517        TemporaryStore::save_wrapped_object_containers(self, wrapped_object_containers)
1518    }
1519
1520    fn check_coin_deny_list(
1521        &self,
1522        receiving_funds_type_and_owners: BTreeMap<TypeTag, BTreeSet<SuiAddress>>,
1523    ) -> DenyListResult {
1524        let result = check_coin_deny_list_v2_during_execution(
1525            receiving_funds_type_and_owners,
1526            self.cur_epoch,
1527            self.store,
1528        );
1529        // The denylist object is only loaded if there are regulated transfers.
1530        // And also if we already have it in the input there is no need to commit it again in the effects.
1531        if result.num_non_gas_coin_owners > 0
1532            && !self.input_objects.contains_key(&SUI_DENY_LIST_OBJECT_ID)
1533        {
1534            self.loaded_per_epoch_config_objects
1535                .write()
1536                .insert(SUI_DENY_LIST_OBJECT_ID);
1537        }
1538        result
1539    }
1540
1541    fn record_generated_object_ids(&mut self, generated_ids: BTreeSet<ObjectID>) {
1542        TemporaryStore::save_generated_object_ids(self, generated_ids)
1543    }
1544}
1545
1546impl BackingPackageStore for TemporaryStore<'_> {
1547    fn get_package_object(&self, package_id: &ObjectID) -> SuiResult<Option<PackageObject>> {
1548        // We first check the objects in the temporary store because in non-production code path,
1549        // it is possible to read packages that are just written in the same transaction.
1550        // This can happen for example when we run the expensive conservation checks, where we may
1551        // look into the types of each written object in the output, and some of them need the
1552        // newly written packages for type checking.
1553        // In production path though, this should never happen.
1554        if let Some(obj) = self.execution_results.written_objects.get(package_id) {
1555            Ok(Some(PackageObject::new(obj.clone())))
1556        } else {
1557            self.store.get_package_object(package_id).inspect(|obj| {
1558                // Track object but leave unchanged
1559                if let Some(v) = obj
1560                    && !self
1561                        .runtime_packages_loaded_from_db
1562                        .read()
1563                        .contains_key(package_id)
1564                {
1565                    // TODO: Can this lock ever block execution?
1566                    // TODO: Another way to avoid the cost of maintaining this map is to not
1567                    // enable it in normal runs, and if a fork is detected, rerun it with a flag
1568                    // turned on and start populating this field.
1569                    self.runtime_packages_loaded_from_db
1570                        .write()
1571                        .insert(*package_id, v.clone());
1572                }
1573            })
1574        }
1575    }
1576}