Skip to main content

sui_types/storage/
mod.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4pub mod error;
5mod object_filter;
6mod object_store_trait;
7mod read_store;
8mod shared_in_memory_store;
9mod write_store;
10
11use crate::IMPLICITLY_READ_SYSTEM_OBJECTS;
12use crate::base_types::{
13    ConsensusObjectSequenceKey, ConsensusObjectVersion, FullObjectID, FullObjectRef, SuiAddress,
14    SystemObjectVersions, TransactionDigest, VersionNumber,
15};
16use crate::committee::EpochId;
17use crate::effects::{TransactionEffects, TransactionEffectsAPI};
18use crate::error::{ExecutionError, SuiError, SuiErrorKind};
19use crate::execution::{DynamicallyLoadedObjectMetadata, ExecutionResults};
20use crate::full_checkpoint_content::ObjectSet;
21use crate::message_envelope::Message;
22use crate::move_package::MovePackage;
23use crate::storage::error::Error as StorageError;
24use crate::transaction::TransactionData;
25use crate::transaction::{InputObjects, SenderSignedData, TransactionDataAPI};
26use crate::{
27    base_types::{ObjectID, ObjectRef, SequenceNumber},
28    error::SuiResult,
29    object::Object,
30};
31use itertools::Itertools;
32use move_binary_format::CompiledModule;
33use move_core_types::language_storage::{ModuleId, TypeTag};
34use move_core_types::resolver::SerializedPackage;
35pub use object_filter::DnfFilter;
36pub use object_filter::DynamicFieldFilter;
37pub use object_filter::DynamicFieldPredicate;
38pub use object_filter::FilterLiteral;
39pub use object_filter::NameTypePattern;
40pub use object_filter::OwnedObjectFilter;
41pub use object_filter::StructTypePattern;
42pub use object_store_trait::ObjectStore;
43pub use read_store::BalanceInfo;
44pub use read_store::BalanceIterator;
45pub use read_store::CoinInfo;
46pub use read_store::DynamicFieldIndexInfo;
47pub use read_store::DynamicFieldIteratorItem;
48pub use read_store::DynamicFieldKey;
49pub use read_store::EpochInfo;
50pub use read_store::IndexedPackageVersion;
51pub use read_store::LedgerBitmapBucket;
52pub use read_store::LedgerBitmapBucketIter;
53pub use read_store::LedgerBitmapBucketIterator;
54pub use read_store::LedgerTxSeqDigest;
55pub use read_store::LedgerTxSeqDigestIterator;
56pub use read_store::ObjectVersionsIterator;
57pub use read_store::OwnedObjectInfo;
58pub use read_store::PackagePublishKey;
59pub use read_store::PackageVersionsIterator;
60pub use read_store::PackagesByCheckpointIterator;
61pub use read_store::ReadStore;
62pub use read_store::RpcIndexes;
63pub use read_store::RpcStateReader;
64pub use read_store::TransactionInfo;
65use serde::{Deserialize, Serialize};
66use serde_with::serde_as;
67pub use shared_in_memory_store::SharedInMemoryStore;
68pub use shared_in_memory_store::SingleCheckpointSharedInMemoryStore;
69use std::collections::{BTreeMap, BTreeSet};
70use std::fmt::{Display, Formatter};
71use std::sync::Arc;
72pub use write_store::WriteStore;
73
74/// A potential input to a transaction.
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
76pub enum InputKey {
77    VersionedObject {
78        id: FullObjectID,
79        version: SequenceNumber,
80    },
81    Package {
82        id: ObjectID,
83    },
84}
85
86impl InputKey {
87    pub fn id(&self) -> FullObjectID {
88        match self {
89            InputKey::VersionedObject { id, .. } => *id,
90            InputKey::Package { id } => FullObjectID::Fastpath(*id),
91        }
92    }
93
94    pub fn version(&self) -> Option<SequenceNumber> {
95        match self {
96            InputKey::VersionedObject { version, .. } => Some(*version),
97            InputKey::Package { .. } => None,
98        }
99    }
100
101    pub fn is_cancelled(&self) -> bool {
102        match self {
103            InputKey::VersionedObject { version, .. } => version.is_cancelled(),
104            InputKey::Package { .. } => false,
105        }
106    }
107}
108
109impl From<&Object> for InputKey {
110    fn from(obj: &Object) -> Self {
111        if obj.is_package() {
112            InputKey::Package { id: obj.id() }
113        } else {
114            InputKey::VersionedObject {
115                id: obj.full_id(),
116                version: obj.version(),
117            }
118        }
119    }
120}
121
122#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
123pub enum WriteKind {
124    /// The object was in storage already but has been modified
125    Mutate,
126    /// The object was created in this transaction
127    Create,
128    /// The object was previously wrapped in another object, but has been restored to storage
129    Unwrap,
130}
131
132#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
133pub enum DeleteKind {
134    /// An object is provided in the call input, and gets deleted.
135    Normal,
136    /// An object is not provided in the call input, but gets unwrapped
137    /// from another object, and then gets deleted.
138    UnwrapThenDelete,
139    /// An object is provided in the call input, and gets wrapped into another object.
140    Wrap,
141}
142
143#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
144pub enum MarkerValue {
145    /// An object was received at the given version in the transaction and is no longer able
146    /// to be received at that version in subequent transactions.
147    Received,
148    /// A fastpath object was deleted, wrapped, or transferred to consensus at the given
149    /// version, and is no longer able to be accessed or used in subsequent transactions via
150    /// fastpath unless/until it is returned to fastpath.
151    FastpathStreamEnded,
152    /// A consensus object was deleted or removed from consensus by the transaction and is no longer
153    /// able to be accessed or used in subsequent transactions with the same initial shared version.
154    ConsensusStreamEnded(TransactionDigest),
155}
156
157/// DeleteKind together with the old sequence number prior to the deletion, if available.
158/// For normal deletion and wrap, we always will consult the object store to obtain the old sequence number.
159/// For UnwrapThenDelete however, in the old protocol where simplified_unwrap_then_delete is false,
160/// we will consult the object store to obtain the old sequence number, which latter will be put in
161/// modified_at_versions; in the new protocol where simplified_unwrap_then_delete is true,
162/// we will not consult the object store, and hence won't have the old sequence number.
163#[derive(Debug)]
164pub enum DeleteKindWithOldVersion {
165    Normal(SequenceNumber),
166    // This variant will be deprecated when we turn on simplified_unwrap_then_delete.
167    UnwrapThenDeleteDEPRECATED(SequenceNumber),
168    UnwrapThenDelete,
169    Wrap(SequenceNumber),
170}
171
172impl DeleteKindWithOldVersion {
173    pub fn old_version(&self) -> Option<SequenceNumber> {
174        match self {
175            DeleteKindWithOldVersion::Normal(version)
176            | DeleteKindWithOldVersion::UnwrapThenDeleteDEPRECATED(version)
177            | DeleteKindWithOldVersion::Wrap(version) => Some(*version),
178            DeleteKindWithOldVersion::UnwrapThenDelete => None,
179        }
180    }
181
182    pub fn to_delete_kind(&self) -> DeleteKind {
183        match self {
184            DeleteKindWithOldVersion::Normal(_) => DeleteKind::Normal,
185            DeleteKindWithOldVersion::UnwrapThenDeleteDEPRECATED(_)
186            | DeleteKindWithOldVersion::UnwrapThenDelete => DeleteKind::UnwrapThenDelete,
187            DeleteKindWithOldVersion::Wrap(_) => DeleteKind::Wrap,
188        }
189    }
190}
191
192#[derive(Debug)]
193pub enum ObjectChange {
194    Write(Object, WriteKind),
195    // DeleteKind together with the old sequence number prior to the deletion, if available.
196    Delete(DeleteKindWithOldVersion),
197}
198
199pub trait StorageView: Storage + ParentSync + RuntimeObjectResolver {}
200impl<T: Storage + ParentSync + RuntimeObjectResolver> StorageView for T {}
201
202#[derive(Debug, Clone, PartialEq, Eq)]
203#[must_use]
204pub enum ObjectFundsSufficiency {
205    Sufficient,
206    Insufficient,
207    Overflow,
208    LoadError(String),
209}
210
211/// An abstraction of the (possibly distributed) store for objects. This
212/// API only allows for the retrieval of objects, not any state changes
213pub trait RuntimeObjectResolver: BackingPackageStore {
214    /// `child` must have an `ObjectOwner` ownership equal to `owner`.
215    fn read_child_object(
216        &self,
217        parent: &ObjectID,
218        child: &ObjectID,
219        child_version_upper_bound: SequenceNumber,
220    ) -> SuiResult<Option<Object>>;
221
222    /// `receiving_object_id` must have an `AddressOwner` ownership equal to `owner`.
223    /// `get_object_received_at_version` must be the exact version at which the object will be received,
224    /// and it cannot have been previously received at that version. NB: An object not existing at
225    /// that version, and not having valid access to the object will be treated exactly the same
226    /// and `Ok(None)` must be returned.
227    fn get_object_received_at_version(
228        &self,
229        owner: &ObjectID,
230        receiving_object_id: &ObjectID,
231        receive_object_at_version: SequenceNumber,
232        epoch_id: EpochId,
233    ) -> SuiResult<Option<Object>>;
234
235    /// Get's the package at the given version. Returns `Some(package)` only if the `package_id` is
236    /// a `MovePackage` with the given `package_version`. Returns `None` in all other cases.
237    ///
238    /// Since the has the _possibility_ of doing unsequenced reads of object IDs it is important
239    /// here that:
240    /// * If the package object does not exist; or
241    /// * If the package object exists but is not a Move package; or
242    /// * If the package object exists and is a Move package, but the version is not the supplied version.
243    ///
244    /// All return the same error.
245    ///
246    /// To be extra careful, we simply return `None` in all cases unless the object is a package
247    /// with the exact version supplied, and let the caller decide how to handle it.
248    fn get_package_at_version(
249        &self,
250        package_id: &ObjectID,
251        package_version: SequenceNumber,
252    ) -> Option<MovePackage> {
253        let move_pkg = self
254            .get_package_object(package_id)
255            .ok()
256            .flatten()?
257            .into_move_package();
258        if move_pkg.version() == package_version {
259            Some(move_pkg)
260        } else {
261            None
262        }
263    }
264}
265
266/// Answers queries against the implicitly read system objects, each read as of the version
267/// consensus assigned to this transaction. Never sees writes made earlier in the same transaction.
268pub trait ImplicitSystemObjectResolver {
269    fn object_available_balance(&self, owner: SuiAddress, type_: &TypeTag) -> SuiResult<u128>;
270
271    fn clock(&self) -> SuiResult<Object>;
272}
273
274pub struct DenyListResult {
275    /// Ok if all regulated coin owners are allowed.
276    /// Err if any regulated coin owner is denied (returning the error for first one denied).
277    pub result: Result<(), ExecutionError>,
278    /// The number of non-gas-coin owners in the transaction results
279    pub num_non_gas_coin_owners: u64,
280}
281
282/// An abstraction of the (possibly distributed) store for objects, and (soon) events and transactions
283pub trait Storage {
284    fn reset(&mut self);
285
286    fn read_object(&self, id: &ObjectID) -> Option<&Object>;
287
288    fn record_execution_results(&mut self, results: ExecutionResults)
289    -> Result<(), ExecutionError>;
290
291    fn save_loaded_runtime_objects(
292        &mut self,
293        loaded_runtime_objects: BTreeMap<ObjectID, DynamicallyLoadedObjectMetadata>,
294    );
295
296    fn save_wrapped_object_containers(
297        &mut self,
298        wrapped_object_containers: BTreeMap<ObjectID, ObjectID>,
299    );
300
301    /// Given the set of all coin types and owners that are receiving the coins during execution,
302    /// Check coin denylist v2, and return the number of non-gas-coin owners.
303    fn check_coin_deny_list(
304        &self,
305        receiving_funds_type_and_owners: BTreeMap<TypeTag, BTreeSet<SuiAddress>>,
306    ) -> DenyListResult;
307
308    fn record_generated_object_ids(&mut self, generated_ids: BTreeSet<ObjectID>);
309}
310
311pub type PackageFetchResults<Package> = Result<Vec<Package>, Vec<ObjectID>>;
312
313#[derive(Clone, Debug)]
314pub struct PackageObject {
315    package_object: Object,
316}
317
318impl PackageObject {
319    pub fn new(package_object: Object) -> Self {
320        assert!(package_object.is_package());
321        Self { package_object }
322    }
323
324    pub fn object(&self) -> &Object {
325        &self.package_object
326    }
327
328    pub fn move_package(&self) -> &MovePackage {
329        self.package_object.data.try_as_package().unwrap()
330    }
331
332    pub fn into_move_package(self) -> MovePackage {
333        self.package_object
334            .into_inner()
335            .data
336            .try_into_package()
337            .unwrap()
338    }
339}
340
341impl From<PackageObject> for Object {
342    fn from(package_object_arc: PackageObject) -> Self {
343        package_object_arc.package_object
344    }
345}
346
347pub trait BackingPackageStore {
348    fn get_package_object(&self, package_id: &ObjectID) -> SuiResult<Option<PackageObject>>;
349}
350
351impl<S: ?Sized + BackingPackageStore> BackingPackageStore for Box<S> {
352    fn get_package_object(&self, package_id: &ObjectID) -> SuiResult<Option<PackageObject>> {
353        BackingPackageStore::get_package_object(self.as_ref(), package_id)
354    }
355}
356
357impl<S: ?Sized + BackingPackageStore> BackingPackageStore for Arc<S> {
358    fn get_package_object(&self, package_id: &ObjectID) -> SuiResult<Option<PackageObject>> {
359        BackingPackageStore::get_package_object(self.as_ref(), package_id)
360    }
361}
362
363impl<S: ?Sized + BackingPackageStore> BackingPackageStore for &S {
364    fn get_package_object(&self, package_id: &ObjectID) -> SuiResult<Option<PackageObject>> {
365        BackingPackageStore::get_package_object(*self, package_id)
366    }
367}
368
369impl<S: ?Sized + BackingPackageStore> BackingPackageStore for &mut S {
370    fn get_package_object(&self, package_id: &ObjectID) -> SuiResult<Option<PackageObject>> {
371        BackingPackageStore::get_package_object(*self, package_id)
372    }
373}
374
375/// A BackingPackageStore that overlays objects on top of a backing store.
376/// This allows resolving packages from a set of objects (e.g., output objects from a transaction)
377/// before falling back to the backing store.
378pub struct OverlayBackingPackageStore<'a, S> {
379    overlay: &'a ObjectSet,
380    backing: S,
381}
382
383impl<'a, S> OverlayBackingPackageStore<'a, S> {
384    pub fn new(overlay: &'a ObjectSet, backing: S) -> Self {
385        Self { overlay, backing }
386    }
387}
388
389impl<S: BackingPackageStore> BackingPackageStore for OverlayBackingPackageStore<'_, S> {
390    fn get_package_object(&self, package_id: &ObjectID) -> SuiResult<Option<PackageObject>> {
391        // First check the overlay for the object
392        for obj in self.overlay.iter() {
393            if &obj.id() == package_id {
394                // Found in overlay - check if it's a package
395                fp_ensure!(
396                    obj.is_package(),
397                    SuiErrorKind::BadObjectType {
398                        error: format!("Package expected, Move object found: {package_id}"),
399                    }
400                    .into()
401                );
402                return Ok(Some(PackageObject::new(obj.clone())));
403            }
404        }
405        // Not in overlay, fall back to the backing store
406        self.backing.get_package_object(package_id)
407    }
408}
409
410pub fn load_package_object_from_object_store(
411    store: &impl ObjectStore,
412    package_id: &ObjectID,
413) -> SuiResult<Option<PackageObject>> {
414    let package = store.get_object(package_id);
415    if let Some(obj) = &package {
416        fp_ensure!(
417            obj.is_package(),
418            SuiErrorKind::BadObjectType {
419                error: format!("Package expected, Move object found: {package_id}"),
420            }
421            .into()
422        );
423    }
424    Ok(package.map(PackageObject::new))
425}
426
427/// Returns Ok(<package object for each package id in `package_ids`>) if all package IDs in
428/// `package_id` were found. If any package in `package_ids` was not found it returns a list
429/// of any package ids that are unable to be found>).
430pub fn get_package_objects<'a>(
431    store: &impl BackingPackageStore,
432    package_ids: impl IntoIterator<Item = &'a ObjectID>,
433) -> SuiResult<PackageFetchResults<PackageObject>> {
434    let packages: Vec<Result<_, _>> = package_ids
435        .into_iter()
436        .map(|id| match store.get_package_object(id) {
437            Ok(None) => Ok(Err(*id)),
438            Ok(Some(o)) => Ok(Ok(o)),
439            Err(x) => Err(x),
440        })
441        .collect::<SuiResult<_>>()?;
442
443    let (fetched, failed_to_fetch): (Vec<_>, Vec<_>) = packages.into_iter().partition_result();
444    if !failed_to_fetch.is_empty() {
445        Ok(Err(failed_to_fetch))
446    } else {
447        Ok(Ok(fetched))
448    }
449}
450
451pub fn get_module(
452    store: impl BackingPackageStore,
453    module_id: &ModuleId,
454) -> Result<Option<Vec<u8>>, SuiError> {
455    Ok(store
456        .get_package_object(&ObjectID::from(*module_id.address()))?
457        .and_then(|package| {
458            package
459                .move_package()
460                .serialized_module_map()
461                .get(module_id.name().as_str())
462                .cloned()
463        }))
464}
465
466pub fn get_package(
467    store: impl BackingPackageStore,
468    id: &ObjectID,
469) -> SuiResult<Option<SerializedPackage>> {
470    store
471        .get_package_object(id)?
472        .map(|package| package.move_package().into_serialized_move_package())
473        .transpose()
474}
475
476pub fn get_module_by_id<S: BackingPackageStore>(
477    store: &S,
478    id: &ModuleId,
479) -> anyhow::Result<Option<CompiledModule>, SuiError> {
480    Ok(get_module(store, id)?
481        .map(|bytes| CompiledModule::deserialize_with_defaults(&bytes).unwrap()))
482}
483
484/// A `BackingPackageStore` that resolves packages from a backing store, but also includes any
485/// packages that were published in the current transaction execution. This can be used to resolve
486/// Move modules right after transaction execution, but newly published packages have not yet been
487/// committed to the backing store on a fullnode.
488pub struct PostExecutionPackageResolver {
489    backing_store: Arc<dyn BackingPackageStore>,
490    new_packages: BTreeMap<ObjectID, PackageObject>,
491}
492
493impl PostExecutionPackageResolver {
494    pub fn new(
495        backing_store: Arc<dyn BackingPackageStore>,
496        output_objects: &Option<Vec<Object>>,
497    ) -> Self {
498        let new_packages = output_objects
499            .iter()
500            .flatten()
501            .filter_map(|o| {
502                if o.is_package() {
503                    Some((o.id(), PackageObject::new(o.clone())))
504                } else {
505                    None
506                }
507            })
508            .collect();
509        Self {
510            backing_store,
511            new_packages,
512        }
513    }
514}
515
516impl BackingPackageStore for PostExecutionPackageResolver {
517    fn get_package_object(&self, package_id: &ObjectID) -> SuiResult<Option<PackageObject>> {
518        if let Some(package) = self.new_packages.get(package_id) {
519            Ok(Some(package.clone()))
520        } else {
521            self.backing_store.get_package_object(package_id)
522        }
523    }
524}
525
526pub trait ParentSync {
527    /// This function is only called by older protocol versions.
528    /// It creates an explicit dependency to tombstones, which is not desired.
529    fn get_latest_parent_entry_ref_deprecated(&self, object_id: ObjectID) -> Option<ObjectRef>;
530}
531
532impl<S: ParentSync> ParentSync for std::sync::Arc<S> {
533    fn get_latest_parent_entry_ref_deprecated(&self, object_id: ObjectID) -> Option<ObjectRef> {
534        ParentSync::get_latest_parent_entry_ref_deprecated(self.as_ref(), object_id)
535    }
536}
537
538impl<S: ParentSync> ParentSync for &S {
539    fn get_latest_parent_entry_ref_deprecated(&self, object_id: ObjectID) -> Option<ObjectRef> {
540        ParentSync::get_latest_parent_entry_ref_deprecated(*self, object_id)
541    }
542}
543
544impl<S: ParentSync> ParentSync for &mut S {
545    fn get_latest_parent_entry_ref_deprecated(&self, object_id: ObjectID) -> Option<ObjectRef> {
546        ParentSync::get_latest_parent_entry_ref_deprecated(*self, object_id)
547    }
548}
549
550impl<S: RuntimeObjectResolver> RuntimeObjectResolver for std::sync::Arc<S> {
551    fn read_child_object(
552        &self,
553        parent: &ObjectID,
554        child: &ObjectID,
555        child_version_upper_bound: SequenceNumber,
556    ) -> SuiResult<Option<Object>> {
557        RuntimeObjectResolver::read_child_object(
558            self.as_ref(),
559            parent,
560            child,
561            child_version_upper_bound,
562        )
563    }
564    fn get_object_received_at_version(
565        &self,
566        owner: &ObjectID,
567        receiving_object_id: &ObjectID,
568        receive_object_at_version: SequenceNumber,
569        epoch_id: EpochId,
570    ) -> SuiResult<Option<Object>> {
571        RuntimeObjectResolver::get_object_received_at_version(
572            self.as_ref(),
573            owner,
574            receiving_object_id,
575            receive_object_at_version,
576            epoch_id,
577        )
578    }
579}
580
581impl<S: RuntimeObjectResolver> RuntimeObjectResolver for &S {
582    fn read_child_object(
583        &self,
584        parent: &ObjectID,
585        child: &ObjectID,
586        child_version_upper_bound: SequenceNumber,
587    ) -> SuiResult<Option<Object>> {
588        RuntimeObjectResolver::read_child_object(*self, parent, child, child_version_upper_bound)
589    }
590    fn get_object_received_at_version(
591        &self,
592        owner: &ObjectID,
593        receiving_object_id: &ObjectID,
594        receive_object_at_version: SequenceNumber,
595        epoch_id: EpochId,
596    ) -> SuiResult<Option<Object>> {
597        RuntimeObjectResolver::get_object_received_at_version(
598            *self,
599            owner,
600            receiving_object_id,
601            receive_object_at_version,
602            epoch_id,
603        )
604    }
605}
606
607impl<S: RuntimeObjectResolver> RuntimeObjectResolver for &mut S {
608    fn read_child_object(
609        &self,
610        parent: &ObjectID,
611        child: &ObjectID,
612        child_version_upper_bound: SequenceNumber,
613    ) -> SuiResult<Option<Object>> {
614        RuntimeObjectResolver::read_child_object(*self, parent, child, child_version_upper_bound)
615    }
616    fn get_object_received_at_version(
617        &self,
618        owner: &ObjectID,
619        receiving_object_id: &ObjectID,
620        receive_object_at_version: SequenceNumber,
621        epoch_id: EpochId,
622    ) -> SuiResult<Option<Object>> {
623        RuntimeObjectResolver::get_object_received_at_version(
624            *self,
625            owner,
626            receiving_object_id,
627            receive_object_at_version,
628            epoch_id,
629        )
630    }
631}
632
633#[serde_as]
634#[derive(Eq, PartialEq, Clone, Copy, PartialOrd, Ord, Hash, Serialize, Deserialize, Debug)]
635pub struct ObjectKey(pub ObjectID, pub VersionNumber);
636
637impl ObjectKey {
638    pub const ZERO: ObjectKey = ObjectKey(ObjectID::ZERO, VersionNumber::MIN);
639
640    pub fn max_for_id(id: &ObjectID) -> Self {
641        Self(*id, VersionNumber::MAX)
642    }
643
644    pub fn min_for_id(id: &ObjectID) -> Self {
645        Self(*id, VersionNumber::MIN)
646    }
647}
648
649impl From<ObjectRef> for ObjectKey {
650    fn from(object_ref: ObjectRef) -> Self {
651        ObjectKey::from(&object_ref)
652    }
653}
654
655impl From<&ObjectRef> for ObjectKey {
656    fn from(object_ref: &ObjectRef) -> Self {
657        Self(object_ref.0, object_ref.1)
658    }
659}
660
661#[serde_as]
662#[derive(Eq, PartialEq, Clone, Copy, PartialOrd, Ord, Hash, Serialize, Deserialize, Debug)]
663pub struct ConsensusObjectKey(pub ConsensusObjectSequenceKey, pub VersionNumber);
664
665/// FullObjectKey represents a unique object a specific version. For fastpath objects, this
666/// is the same as ObjectKey. For consensus objects, this includes the start version, which
667/// may change if an object is transferred out of and back into consensus.
668#[serde_as]
669#[derive(Eq, PartialEq, Clone, Copy, PartialOrd, Ord, Hash, Serialize, Deserialize, Debug)]
670pub enum FullObjectKey {
671    Fastpath(ObjectKey),
672    Consensus(ConsensusObjectKey),
673}
674
675impl FullObjectKey {
676    pub fn max_for_id(id: &FullObjectID) -> Self {
677        match id {
678            FullObjectID::Fastpath(object_id) => Self::Fastpath(ObjectKey::max_for_id(object_id)),
679            FullObjectID::Consensus(consensus_object_sequence_key) => Self::Consensus(
680                ConsensusObjectKey(*consensus_object_sequence_key, VersionNumber::MAX),
681            ),
682        }
683    }
684
685    pub fn min_for_id(id: &FullObjectID) -> Self {
686        match id {
687            FullObjectID::Fastpath(object_id) => Self::Fastpath(ObjectKey::min_for_id(object_id)),
688            FullObjectID::Consensus(consensus_object_sequence_key) => Self::Consensus(
689                ConsensusObjectKey(*consensus_object_sequence_key, VersionNumber::MIN),
690            ),
691        }
692    }
693
694    pub fn new(object_id: FullObjectID, version: VersionNumber) -> Self {
695        match object_id {
696            FullObjectID::Fastpath(object_id) => Self::Fastpath(ObjectKey(object_id, version)),
697            FullObjectID::Consensus(consensus_object_sequence_key) => {
698                Self::Consensus(ConsensusObjectKey(consensus_object_sequence_key, version))
699            }
700        }
701    }
702
703    pub fn id(&self) -> FullObjectID {
704        match self {
705            FullObjectKey::Fastpath(object_key) => FullObjectID::Fastpath(object_key.0),
706            FullObjectKey::Consensus(consensus_object_key) => {
707                FullObjectID::Consensus(consensus_object_key.0)
708            }
709        }
710    }
711
712    pub fn version(&self) -> VersionNumber {
713        match self {
714            FullObjectKey::Fastpath(object_key) => object_key.1,
715            FullObjectKey::Consensus(consensus_object_key) => consensus_object_key.1,
716        }
717    }
718}
719
720impl From<FullObjectRef> for FullObjectKey {
721    fn from(object_ref: FullObjectRef) -> Self {
722        FullObjectKey::from(&object_ref)
723    }
724}
725
726impl From<&FullObjectRef> for FullObjectKey {
727    fn from(object_ref: &FullObjectRef) -> Self {
728        FullObjectKey::new(object_ref.0, object_ref.1)
729    }
730}
731
732#[derive(Clone, Debug, PartialEq, Eq)]
733pub enum ObjectOrTombstone {
734    Object(Object),
735    Tombstone(ObjectRef),
736}
737
738impl ObjectOrTombstone {
739    pub fn as_objref(&self) -> ObjectRef {
740        match self {
741            ObjectOrTombstone::Object(obj) => obj.compute_object_reference(),
742            ObjectOrTombstone::Tombstone(obref) => *obref,
743        }
744    }
745}
746
747impl From<Object> for ObjectOrTombstone {
748    fn from(object: Object) -> Self {
749        ObjectOrTombstone::Object(object)
750    }
751}
752
753/// Fetch the `ObjectKey`s (IDs and versions) for non-shared input objects.  Includes owned,
754/// and immutable objects as well as the gas objects, but not move packages or shared objects.
755pub fn transaction_non_shared_input_object_keys(
756    tx: &SenderSignedData,
757) -> SuiResult<Vec<ObjectKey>> {
758    use crate::transaction::InputObjectKind as I;
759    Ok(tx
760        .intent_message()
761        .value
762        .input_objects()?
763        .into_iter()
764        .filter_map(|object| match object {
765            I::MovePackage(_) | I::SharedMoveObject { .. } => None,
766            I::ImmOrOwnedMoveObject(obj) => Some(obj.into()),
767        })
768        .collect())
769}
770
771pub fn transaction_receiving_object_keys(tx: &SenderSignedData) -> Vec<ObjectKey> {
772    tx.intent_message()
773        .value
774        .receiving_objects()
775        .into_iter()
776        .map(|oref| oref.into())
777        .collect()
778}
779
780impl Display for DeleteKind {
781    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
782        match self {
783            DeleteKind::Wrap => write!(f, "Wrap"),
784            DeleteKind::Normal => write!(f, "Normal"),
785            DeleteKind::UnwrapThenDelete => write!(f, "UnwrapThenDelete"),
786        }
787    }
788}
789
790pub trait BackingStore: RuntimeObjectResolver + ObjectStore + ParentSync {}
791
792impl<T> BackingStore for T
793where
794    T: RuntimeObjectResolver,
795    T: ObjectStore,
796    T: ParentSync,
797{
798}
799
800pub fn get_transaction_input_objects(
801    object_store: &dyn ObjectStore,
802    effects: &TransactionEffects,
803) -> Result<Vec<Object>, StorageError> {
804    let input_object_keys = effects
805        .modified_at_versions()
806        .into_iter()
807        .map(|(object_id, version)| ObjectKey(object_id, version))
808        .collect::<Vec<_>>();
809
810    let input_objects = object_store
811        .multi_get_objects_by_key(&input_object_keys)
812        .into_iter()
813        .enumerate()
814        .map(|(idx, maybe_object)| {
815            maybe_object.ok_or_else(|| {
816                StorageError::custom(format!(
817                    "missing input object key {:?} from tx {} effects {}",
818                    input_object_keys[idx],
819                    effects.transaction_digest(),
820                    effects.digest()
821                ))
822            })
823        })
824        .collect::<Result<Vec<_>, _>>()?;
825    Ok(input_objects)
826}
827
828pub fn get_transaction_output_objects(
829    object_store: &dyn ObjectStore,
830    effects: &TransactionEffects,
831) -> Result<Vec<Object>, StorageError> {
832    let output_object_keys = effects
833        .all_changed_objects()
834        .into_iter()
835        .map(|(object_ref, _owner, _kind)| ObjectKey::from(object_ref))
836        .collect::<Vec<_>>();
837
838    let output_objects = object_store
839        .multi_get_objects_by_key(&output_object_keys)
840        .into_iter()
841        .enumerate()
842        .map(|(idx, maybe_object)| {
843            maybe_object.ok_or_else(|| {
844                StorageError::custom(format!(
845                    "missing output object key {:?} from tx {} effects {}",
846                    output_object_keys[idx],
847                    effects.transaction_digest(),
848                    effects.digest()
849                ))
850            })
851        })
852        .collect::<Result<Vec<_>, _>>()?;
853    Ok(output_objects)
854}
855
856impl SystemObjectVersions {
857    /// Obtains pinned system object versions from effects, queries the store for the initial shared versions.
858    pub fn from_effects(effects: &TransactionEffects, store: &dyn ObjectStore) -> Self {
859        Self::from_map(
860            effects
861                .accessed_consensus_objects()
862                .into_iter()
863                .filter_map(|ico| {
864                    let (id, version) = ico.id_and_version();
865                    if !id.is_implicitly_read_system_object() || version.is_cancelled() {
866                        return None;
867                    }
868                    let initial_shared_version = store
869                        .get_object(&id)
870                        .and_then(|object| object.owner().start_version())
871                        // unwrap safe because if effects contain an implicitly read system object,
872                        // it must exist in the store and is a shared object.
873                        .unwrap();
874                    Some((
875                        id,
876                        ConsensusObjectVersion {
877                            initial_shared_version,
878                            version,
879                        },
880                    ))
881                })
882                .collect(),
883        )
884    }
885
886    /// Before execution, get the versions of the implicitly read system objects from the declared
887    /// inputs, or else the latest from the store, and use these versions as the exact version to
888    /// read during execution.
889    /// This is used only in environments where there is no consensus to assign versions, e.g. simulacrum and dry-run.
890    pub fn from_inputs_or_latest_in_store(
891        input_objects: &InputObjects,
892        store: &dyn ObjectStore,
893    ) -> Self {
894        Self::from_map(
895            IMPLICITLY_READ_SYSTEM_OBJECTS
896                .iter()
897                .filter_map(|id| {
898                    let object = input_objects
899                        .iter_objects()
900                        .find(|object| object.id() == *id)
901                        .cloned()
902                        .or_else(|| store.get_object(id))?;
903                    let initial_shared_version = object
904                        .owner()
905                        .start_version()
906                        .expect("implicitly read system objects must be consensus objects");
907                    Some((
908                        *id,
909                        ConsensusObjectVersion {
910                            initial_shared_version,
911                            version: object.version(),
912                        },
913                    ))
914                })
915                .collect(),
916        )
917    }
918}
919
920// Returns a set of the ObjectKey's of objects read or written by this transaction
921pub fn get_transaction_object_set(
922    transaction: &TransactionData,
923    effects: &TransactionEffects,
924    unchanged_loaded_runtime_objects: &[ObjectKey],
925) -> BTreeSet<ObjectKey> {
926    // enumerate the full set of input objects in order to properly capture immutable objects that
927    // may not appear in the effects.
928    //
929    // This excludes packages
930    let input_objects = transaction
931        .input_objects()
932        .expect("txn was executed and must have valid input objects")
933        .into_iter()
934        .filter_map(|input| {
935            input
936                .version()
937                .map(|version| ObjectKey(input.object_id(), version))
938        });
939
940    // The full set of output/written objects as well as any of their initial versions
941    let modified_set = effects
942        .object_changes()
943        .into_iter()
944        .flat_map(|change| {
945            [
946                change
947                    .input_version
948                    .map(|version| ObjectKey(change.id, version)),
949                change
950                    .output_version
951                    .map(|version| ObjectKey(change.id, version)),
952            ]
953        })
954        .flatten();
955
956    // The set of unchanged consensus objects
957    let unchanged_consensus =
958        effects
959            .unchanged_consensus_objects()
960            .into_iter()
961            .flat_map(|unchanged| {
962                if let crate::effects::UnchangedConsensusKind::ReadOnlyRoot((version, _)) =
963                    unchanged.1
964                {
965                    Some(ObjectKey(unchanged.0, version))
966                } else {
967                    None
968                }
969            });
970
971    input_objects
972        .chain(modified_set)
973        .chain(unchanged_consensus)
974        .chain(unchanged_loaded_runtime_objects.iter().copied())
975        .collect()
976}
977
978// A BackingStore to pass to execution in order to track all objects loaded during execution.
979//
980// Today this is used to very accurately track the objects that were loaded but unchanged during
981// execution.
982pub struct TrackingBackingStore<'a> {
983    inner: &'a dyn crate::storage::BackingStore,
984    read_objects: std::cell::RefCell<ObjectSet>,
985}
986
987impl<'a> TrackingBackingStore<'a> {
988    pub fn new(inner: &'a dyn crate::storage::BackingStore) -> Self {
989        Self {
990            inner,
991            read_objects: Default::default(),
992        }
993    }
994
995    pub fn into_read_objects(self) -> ObjectSet {
996        self.read_objects.into_inner()
997    }
998
999    fn track_object(&self, object: &Object) {
1000        self.read_objects.borrow_mut().insert(object.clone());
1001    }
1002}
1003
1004impl BackingPackageStore for TrackingBackingStore<'_> {
1005    fn get_package_object(
1006        &self,
1007        package_id: &ObjectID,
1008    ) -> crate::error::SuiResult<Option<PackageObject>> {
1009        self.inner.get_package_object(package_id).inspect(|o| {
1010            o.as_ref()
1011                .inspect(|package| self.track_object(package.object()));
1012        })
1013    }
1014}
1015
1016impl RuntimeObjectResolver for TrackingBackingStore<'_> {
1017    fn read_child_object(
1018        &self,
1019        parent: &ObjectID,
1020        child: &ObjectID,
1021        child_version_upper_bound: SequenceNumber,
1022    ) -> crate::error::SuiResult<Option<Object>> {
1023        self.inner
1024            .read_child_object(parent, child, child_version_upper_bound)
1025            .inspect(|o| {
1026                o.as_ref().inspect(|object| self.track_object(object));
1027            })
1028    }
1029
1030    fn get_object_received_at_version(
1031        &self,
1032        owner: &ObjectID,
1033        receiving_object_id: &ObjectID,
1034        receive_object_at_version: SequenceNumber,
1035        epoch_id: crate::committee::EpochId,
1036    ) -> crate::error::SuiResult<Option<Object>> {
1037        self.inner
1038            .get_object_received_at_version(
1039                owner,
1040                receiving_object_id,
1041                receive_object_at_version,
1042                epoch_id,
1043            )
1044            .inspect(|o| {
1045                o.as_ref().inspect(|object| self.track_object(object));
1046            })
1047    }
1048}
1049
1050impl crate::storage::ObjectStore for TrackingBackingStore<'_> {
1051    fn get_object(&self, object_id: &ObjectID) -> Option<Object> {
1052        self.inner
1053            .get_object(object_id)
1054            .inspect(|o| self.track_object(o))
1055    }
1056
1057    fn load_implicitly_read_system_object(
1058        &self,
1059        object_id: &ObjectID,
1060        version: crate::base_types::ConsensusObjectVersion,
1061    ) -> Option<Object> {
1062        self.inner
1063            .load_implicitly_read_system_object(object_id, version)
1064            .inspect(|o| self.track_object(o))
1065    }
1066
1067    fn get_object_by_key(
1068        &self,
1069        object_id: &ObjectID,
1070        version: crate::base_types::VersionNumber,
1071    ) -> Option<Object> {
1072        self.inner
1073            .get_object_by_key(object_id, version)
1074            .inspect(|o| self.track_object(o))
1075    }
1076}
1077
1078impl ParentSync for TrackingBackingStore<'_> {
1079    fn get_latest_parent_entry_ref_deprecated(
1080        &self,
1081        object_id: ObjectID,
1082    ) -> Option<crate::base_types::ObjectRef> {
1083        self.inner.get_latest_parent_entry_ref_deprecated(object_id)
1084    }
1085}