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 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
58type AllowanceIds = BTreeMap<(SuiAddress, TypeTag), Vec<ObjectID>>;
60
61#[derive(Default)]
62struct PostExecutionCheckInputs {
63 input_reservations: BTreeMap<(SuiAddress, TypeTag), u64>,
66 allowance_ids: AllowanceIds,
69 advance_epoch_gas_summary: Option<(u64, u64)>,
72 is_genesis: bool,
74 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 store: &'backing dyn BackingStore,
101 tx_digest: TransactionDigest,
102 input_objects: BTreeMap<ObjectID, Object>,
103 post_execution_check_inputs: PostExecutionCheckInputs,
106
107 non_exclusive_input_original_versions: BTreeMap<ObjectID, Object>,
110
111 stream_ended_consensus_objects: BTreeMap<ObjectID, SequenceNumber >,
112 lamport_timestamp: SequenceNumber,
114 mutable_input_refs: BTreeMap<ObjectID, (VersionDigest, Owner)>,
117 execution_results: ExecutionResultsV2,
118 loaded_runtime_objects: BTreeMap<ObjectID, DynamicallyLoadedObjectMetadata>,
120 protocol_config: &'backing ProtocolConfig,
121
122 runtime_packages_loaded_from_db: RwLock<BTreeMap<ObjectID, PackageObject>>,
125
126 receiving_objects: Vec<ObjectRef>,
129
130 cur_epoch: EpochId,
133
134 loaded_per_epoch_config_objects: RwLock<BTreeSet<ObjectID>>,
137
138 invariants: InvariantChecker,
140
141 system_object_versions: SystemObjectVersions,
143
144 loaded_system_objects: RefCell<BTreeMap<ObjectID, (SequenceNumber, ObjectDigest)>>,
148
149 unsettled_object_funds: &'backing dyn UnsettledObjectFundsRead,
150}
151
152impl<'backing> TemporaryStore<'backing> {
153 #[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 &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 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 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 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 .load_implicitly_read_system_object(object_id, version)?,
297 };
298 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 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 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 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 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 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 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 pub(crate) fn ensure_active_inputs_mutated(&mut self) {
486 let mut to_be_updated = vec![];
487 for id in self.mutable_input_refs.keys() {
489 if !self.execution_results.modified_objects.contains(id) {
490 to_be_updated.push(self.input_objects[id].clone());
494 }
495 }
496 for object in to_be_updated {
497 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 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 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 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 #[cfg(debug_assertions)]
600 fn check_invariants(&self) {
601 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 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 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 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 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 pub fn create_object(&mut self, object: Object) {
686 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 pub fn delete_input_object(&mut self, id: &ObjectID) {
701 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 pub(crate) fn into_bump_only(self) -> Self {
717 let Self {
718 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 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_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 bump_only.ensure_active_inputs_mutated();
764 bump_only
765 }
766
767 pub fn read_object(&self, id: &ObjectID) -> Option<&Object> {
768 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 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 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 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 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 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 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 pub fn conserve_unmetered_storage_rebate(&mut self, unmetered_storage_rebate: u64) {
965 if unmetered_storage_rebate == 0 {
966 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 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 pub fn add_accumulator_event(&mut self, event: AccumulatorEvent) {
988 self.execution_results.accumulator_events.push(event);
989 }
990
991 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 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 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 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 pub(crate) fn collect_storage_and_rebate(
1083 &mut self,
1084 rates: &StorageRates,
1085 ) -> Result<StorageCharge, ExecutionError> {
1086 let mut charge = StorageCharge::default();
1087 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 let new_object_size = object.object_size_for_gas_metering();
1106 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 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 let storage_rebate = self
1141 .get_object_modified_at(object_id)
1142 .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}
1174impl 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 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 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 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
1275fn 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 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 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
1339fn 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
1360fn 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 (Data::Package(a), Data::Package(b)) => a == b,
1368 _ => false,
1369 };
1370
1371 let owner_equal = match (&object.owner, &original.owner) {
1372 (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 (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 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 let mut to_remove = Vec::new();
1427 for (id, original) in &self.non_exclusive_input_original_versions {
1428 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 let event_start = self.execution_results.accumulator_events.len();
1454 self.execution_results.merge_results(
1455 results, true, 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 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 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 if let Some(v) = obj
1518 && !self
1519 .runtime_packages_loaded_from_db
1520 .read()
1521 .contains_key(package_id)
1522 {
1523 self.runtime_packages_loaded_from_db
1528 .write()
1529 .insert(*package_id, v.clone());
1530 }
1531 })
1532 }
1533 }
1534}