1use 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
59type AllowanceIds = BTreeMap<(SuiAddress, TypeTag), Vec<ObjectID>>;
61
62type SeizeAuthIds = BTreeMap<(SuiAddress, TypeTag), ObjectID>;
65
66struct InputReservations {
69 reservations: BTreeMap<(SuiAddress, TypeTag), u64>,
70 allowance_ids: AllowanceIds,
71 seize_auth_ids: SeizeAuthIds,
72}
73
74#[derive(Default)]
75struct PostExecutionCheckInputs {
76 input_reservations: BTreeMap<(SuiAddress, TypeTag), u64>,
79 allowance_ids: AllowanceIds,
82 seize_auth_ids: SeizeAuthIds,
85 advance_epoch_gas_summary: Option<(u64, u64)>,
88 is_genesis: bool,
90 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 store: &'backing dyn BackingStore,
121 tx_digest: TransactionDigest,
122 input_objects: BTreeMap<ObjectID, Object>,
123 post_execution_check_inputs: PostExecutionCheckInputs,
126
127 non_exclusive_input_original_versions: BTreeMap<ObjectID, Object>,
130
131 stream_ended_consensus_objects: BTreeMap<ObjectID, SequenceNumber >,
132 lamport_timestamp: SequenceNumber,
134 mutable_input_refs: BTreeMap<ObjectID, (VersionDigest, Owner)>,
137 execution_results: ExecutionResultsV2,
138 loaded_runtime_objects: BTreeMap<ObjectID, DynamicallyLoadedObjectMetadata>,
140 protocol_config: &'backing ProtocolConfig,
141
142 runtime_packages_loaded_from_db: RwLock<BTreeMap<ObjectID, PackageObject>>,
145
146 receiving_objects: Vec<ObjectRef>,
149
150 cur_epoch: EpochId,
153
154 loaded_per_epoch_config_objects: RwLock<BTreeSet<ObjectID>>,
157
158 invariants: InvariantChecker,
160
161 system_object_versions: SystemObjectVersions,
163
164 loaded_system_objects: RefCell<BTreeMap<ObjectID, (SequenceNumber, ObjectDigest)>>,
168
169 unsettled_object_funds: &'backing dyn UnsettledObjectFundsRead,
170}
171
172impl<'backing> TemporaryStore<'backing> {
173 #[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 &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 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 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 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 .load_implicitly_read_system_object(object_id, version)?,
317 };
318 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 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 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 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 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 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 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 pub(crate) fn ensure_active_inputs_mutated(&mut self) {
506 let mut to_be_updated = vec![];
507 for id in self.mutable_input_refs.keys() {
509 if !self.execution_results.modified_objects.contains(id) {
510 to_be_updated.push(self.input_objects[id].clone());
514 }
515 }
516 for object in to_be_updated {
517 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 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 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 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 #[cfg(debug_assertions)]
620 fn check_invariants(&self) {
621 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 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 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 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 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 pub fn create_object(&mut self, object: Object) {
706 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 pub fn delete_input_object(&mut self, id: &ObjectID) {
721 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 pub(crate) fn into_bump_only(self) -> Self {
737 let Self {
738 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 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_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 bump_only.ensure_active_inputs_mutated();
784 bump_only
785 }
786
787 pub fn read_object(&self, id: &ObjectID) -> Option<&Object> {
788 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 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 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 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 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 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 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 pub fn conserve_unmetered_storage_rebate(&mut self, unmetered_storage_rebate: u64) {
985 if unmetered_storage_rebate == 0 {
986 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 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 pub fn add_accumulator_event(&mut self, event: AccumulatorEvent) {
1008 self.execution_results.accumulator_events.push(event);
1009 }
1010
1011 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 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 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 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 pub(crate) fn collect_storage_and_rebate(
1103 &mut self,
1104 rates: &StorageRates,
1105 ) -> Result<StorageCharge, ExecutionError> {
1106 let mut charge = StorageCharge::default();
1107 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 let new_object_size = object.object_size_for_gas_metering();
1126 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 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 let storage_rebate = self
1161 .get_object_modified_at(object_id)
1162 .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}
1194impl 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 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 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 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
1302fn 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 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 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
1381fn 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
1402fn 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 (Data::Package(a), Data::Package(b)) => a == b,
1410 _ => false,
1411 };
1412
1413 let owner_equal = match (&object.owner, &original.owner) {
1414 (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 (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 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 let mut to_remove = Vec::new();
1469 for (id, original) in &self.non_exclusive_input_original_versions {
1470 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 let event_start = self.execution_results.accumulator_events.len();
1496 self.execution_results.merge_results(
1497 results, true, 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 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 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 if let Some(v) = obj
1560 && !self
1561 .runtime_packages_loaded_from_db
1562 .read()
1563 .contains_key(package_id)
1564 {
1565 self.runtime_packages_loaded_from_db
1570 .write()
1571 .insert(*package_id, v.clone());
1572 }
1573 })
1574 }
1575 }
1576}