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