Skip to main content

simulacrum/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5//! A `Simulacrum` of IOTA.
6//!
7//! The word simulacrum is latin for "likeness, semblance", it is also a spell
8//! in D&D which creates a copy of a creature which then follows the player's
9//! commands and wishes. As such this crate provides the [`Simulacrum`] type
10//! which is a implementation or instantiation of a iota blockchain, one which
11//! doesn't do anything unless acted upon.
12//!
13//! [`Simulacrum`]: crate::Simulacrum
14
15mod epoch_state;
16pub mod store;
17pub mod transaction_executor;
18
19use std::{
20    num::NonZeroUsize,
21    path::PathBuf,
22    sync::{Arc, RwLock},
23};
24
25use anyhow::{Result, anyhow};
26use fastcrypto::traits::Signer;
27use iota_config::{
28    genesis, transaction_deny_config::TransactionDenyConfig,
29    verifier_signing_config::VerifierSigningConfig,
30};
31use iota_node_storage::{GrpcIndexes, GrpcStateReader};
32use iota_protocol_config::ProtocolVersion;
33use iota_sdk_types::{
34    Address, CheckpointContents, CheckpointContentsDigest, CheckpointDigest, ConsensusCommitDigest,
35    EndOfEpochData, EndOfEpochTransactionKind, GasPayment, ObjectId, StructTag, SystemPackage,
36    Transaction, TransactionDigest, TransactionEffects, TransactionEvents, TransactionKind,
37};
38use iota_storage::blob::{Blob, BlobEncoding};
39use iota_swarm_config::{
40    genesis_config::AccountConfig, network_config::NetworkConfig,
41    network_config_builder::ConfigBuilder,
42};
43use iota_types::{
44    base_types::{AuthorityName, EpochId, VersionNumber},
45    committee::Committee,
46    crypto::AuthoritySignature,
47    digests::ChainIdentifier,
48    error::ExecutionError,
49    gas_coin::{GasCoin, NANOS_PER_IOTA},
50    inner_temporary_store::InnerTemporaryStore,
51    iota_system_state::{
52        IotaSystemState, IotaSystemStateTrait, epoch_start_iota_system_state::EpochStartSystemState,
53    },
54    messages_checkpoint::{CheckpointContentsExt, CheckpointSequenceNumber, VerifiedCheckpoint},
55    mock_checkpoint_builder::{MockCheckpointBuilder, ValidatorKeypairProvider},
56    object::Object,
57    programmable_transaction_builder::ProgrammableTransactionBuilder,
58    signature::VerifyParams,
59    storage::{EpochInfoV2, ObjectStore, ReadStore},
60    supported_protocol_versions::SupportedProtocolVersions,
61    transaction::{TransactionAPI, TransactionEnvelope, VerifiedTransaction},
62};
63use rand::{rand_core::UnwrapErr, rngs::SysRng};
64
65pub use self::store::{SimulatorStore, in_mem_store::InMemoryStore};
66use self::{epoch_state::EpochState, store::in_mem_store::KeyStore};
67
68/// A `Simulacrum` of IOTA.
69///
70/// This type represents a simulated instantiation of an IOTA blockchain that
71/// needs to be driven manually, that is time doesn't advance and checkpoints
72/// are not formed unless explicitly requested.
73///
74/// See [module level][mod] documentation for more details.
75///
76/// [mod]: index.html
77pub struct Simulacrum<R = UnwrapErr<SysRng>, Store: SimulatorStore = InMemoryStore> {
78    // Mutable state protected by RwLock for thread-safe interior mutability
79    inner: RwLock<SimulacrumInner<R, Store>>,
80    // Immutable config - can be accessed directly
81    deny_config: TransactionDenyConfig,
82    verifier_signing_config: VerifierSigningConfig,
83}
84
85struct SimulacrumInner<R, Store: SimulatorStore> {
86    rng: R,
87    keystore: KeyStore,
88    #[expect(unused)]
89    genesis: genesis::Genesis,
90    chain_identifier: ChainIdentifier,
91    store: Store,
92    checkpoint_builder: MockCheckpointBuilder,
93
94    // Epoch specific data
95    epoch_state: EpochState,
96    data_ingestion_path: Option<PathBuf>,
97}
98
99impl Simulacrum {
100    /// Create a new, random Simulacrum instance using an `OsRng` as the source
101    /// of randomness.
102    #[expect(clippy::new_without_default)]
103    pub fn new() -> Self {
104        Self::new_with_rng(UnwrapErr(SysRng))
105    }
106}
107
108impl<R> Simulacrum<R>
109where
110    R: rand::CryptoRng,
111{
112    /// Create a new Simulacrum instance using the provided `rng`.
113    ///
114    /// This allows you to create a fully deterministic initial chainstate when
115    /// a seeded rng is used.
116    ///
117    /// ```
118    /// use rand::{SeedableRng, rngs::StdRng};
119    /// use simulacrum::Simulacrum;
120    ///
121    /// # fn main() {
122    /// let mut rng = StdRng::seed_from_u64(1);
123    /// let simulacrum = Simulacrum::new_with_rng(rng);
124    /// # }
125    /// ```
126    pub fn new_with_rng(mut rng: R) -> Self {
127        let config = ConfigBuilder::new_with_temp_dir()
128            .rng(&mut rng)
129            .with_chain_start_timestamp_ms(1)
130            .deterministic_committee_size(NonZeroUsize::new(1).unwrap())
131            .build();
132        Self::new_with_network_config_in_mem(&config, rng)
133    }
134
135    pub fn new_with_protocol_version_and_accounts(
136        mut rng: R,
137        chain_start_timestamp_ms: u64,
138        protocol_version: ProtocolVersion,
139        account_configs: Vec<AccountConfig>,
140    ) -> Self {
141        let config = ConfigBuilder::new_with_temp_dir()
142            .rng(&mut rng)
143            .with_chain_start_timestamp_ms(chain_start_timestamp_ms)
144            .deterministic_committee_size(NonZeroUsize::new(1).unwrap())
145            .with_protocol_version(protocol_version)
146            // The protocol version never changes, so validators only need the stake it
147            // requires.
148            .with_supported_protocol_versions(SupportedProtocolVersions::new_for_testing(
149                protocol_version.as_u64(),
150                protocol_version.as_u64(),
151            ))
152            .with_accounts(account_configs)
153            .build();
154        Self::new_with_network_config_in_mem(&config, rng)
155    }
156
157    fn new_with_network_config_in_mem(config: &NetworkConfig, rng: R) -> Self {
158        let store = InMemoryStore::new(&config.genesis);
159        Self::new_with_network_config_store(config, rng, store)
160    }
161}
162
163impl<R, S: store::SimulatorStore> Simulacrum<R, S> {
164    pub fn new_with_network_config_store(config: &NetworkConfig, rng: R, store: S) -> Self {
165        let keystore = KeyStore::from_network_config(config);
166        let genesis_checkpoint = config.genesis.checkpoint();
167        let chain_identifier = ChainIdentifier::from(*genesis_checkpoint.digest());
168        let checkpoint_builder = MockCheckpointBuilder::new(genesis_checkpoint);
169
170        let genesis = &config.genesis;
171        let epoch_state = EpochState::new(genesis.iota_system_object());
172
173        Self {
174            deny_config: TransactionDenyConfig::default(),
175            verifier_signing_config: VerifierSigningConfig::default(),
176            inner: RwLock::new(SimulacrumInner {
177                rng,
178                keystore,
179                genesis: genesis.clone(),
180                chain_identifier,
181                store,
182                checkpoint_builder,
183                epoch_state,
184                data_ingestion_path: None,
185            }),
186        }
187    }
188
189    /// Attempts to execute the provided transaction.
190    ///
191    /// The provided transaction undergoes the same types of checks that a
192    /// Validator does prior to signing and executing in the production
193    /// system. Some of these checks are as follows:
194    /// - User signature is valid
195    /// - Sender owns all OwnedObject inputs
196    /// - etc
197    ///
198    /// If the above checks are successful then the transaction is immediately
199    /// executed, enqueued to be included in the next checkpoint (the next
200    /// time `create_checkpoint` is called) and the corresponding
201    /// TransactionEffects are returned.
202    pub fn execute_transaction(
203        &self,
204        transaction: TransactionEnvelope,
205    ) -> anyhow::Result<(TransactionEffects, Option<ExecutionError>)> {
206        let mut inner = self.inner.write().unwrap();
207        let transaction = transaction.try_into_verified_for_testing(
208            &VerifyParams::from_protocol_config(inner.epoch_state.protocol_config()),
209        )?;
210
211        let (inner_temporary_store, _, effects, execution_error_opt) =
212            inner.epoch_state.execute_transaction(
213                &inner.store,
214                inner.chain_identifier,
215                &self.deny_config,
216                &self.verifier_signing_config,
217                &transaction,
218            )?;
219
220        let InnerTemporaryStore {
221            written, events, ..
222        } = inner_temporary_store;
223
224        inner.store.insert_executed_transaction(
225            transaction.clone(),
226            effects.clone(),
227            events,
228            written,
229        );
230
231        // Insert into checkpoint builder
232        inner
233            .checkpoint_builder
234            .push_transaction(transaction, effects.clone());
235        Ok((effects, execution_error_opt.err()))
236    }
237
238    /// Simulate a transaction without committing changes.
239    /// This is useful for testing transaction behavior without modifying state.
240    pub fn simulate_transaction(
241        &self,
242        transaction: Transaction,
243        checks: iota_types::transaction_executor::VmChecks,
244    ) -> iota_types::error::IotaResult<iota_types::transaction_executor::SimulateTransactionResult>
245    {
246        let inner = self.inner.read().unwrap();
247        inner.epoch_state.simulate_transaction(
248            &inner.store,
249            inner.chain_identifier,
250            &self.deny_config,
251            &self.verifier_signing_config,
252            transaction,
253            checks,
254        )
255    }
256
257    /// Creates the next Checkpoint using the Transactions enqueued since the
258    /// last checkpoint was created.
259    pub fn create_checkpoint(&self) -> VerifiedCheckpoint {
260        let (checkpoint, contents) = {
261            let mut inner = self.inner.write().unwrap();
262            let committee = CommitteeWithKeys::new(&inner.keystore, inner.epoch_state.committee());
263            let timestamp_ms = inner.store.get_clock().timestamp_ms;
264            let (checkpoint, contents, _) =
265                inner.checkpoint_builder.build(&committee, timestamp_ms);
266            inner.store.insert_checkpoint(checkpoint.clone());
267            inner.store.insert_checkpoint_contents(contents.clone());
268            (checkpoint, contents)
269        };
270        // Release lock before expensive data ingestion operation
271        self.process_data_ingestion(checkpoint.clone(), contents)
272            .unwrap();
273        checkpoint
274    }
275
276    /// Advances the clock by `duration`.
277    ///
278    /// This creates and executes a ConsensusCommitPrologue transaction which
279    /// advances the chain Clock by the provided duration.
280    pub fn advance_clock(&self, duration: std::time::Duration) -> TransactionEffects {
281        let mut inner = self.inner.write().unwrap();
282        let epoch = inner.epoch_state.epoch();
283        let round = inner.epoch_state.next_consensus_round();
284        let timestamp_ms = inner.store.get_clock().timestamp_ms + duration.as_millis() as u64;
285        drop(inner);
286
287        let consensus_commit_prologue_transaction =
288            VerifiedTransaction::new_consensus_commit_prologue_v1(
289                epoch,
290                round,
291                timestamp_ms,
292                ConsensusCommitDigest::default(),
293                Vec::new(),
294            );
295
296        self.execute_transaction(consensus_commit_prologue_transaction.into())
297            .expect("advancing the clock cannot fail")
298            .0
299    }
300
301    /// Advances the epoch.
302    ///
303    /// This creates and executes an EndOfEpoch transaction which advances the
304    /// chain into the next epoch. Since it is required to be the final
305    /// transaction in an epoch, the final checkpoint in the epoch is also
306    /// created.
307    ///
308    /// NOTE: This function does not currently support updating the protocol
309    /// version or the system packages.
310    ///
311    /// With `create_deny_rules_object`, the end-of-epoch transaction also
312    /// creates the `TransactionDenyRules` object (requires the
313    /// `enable_pcool_flow` feature flag).
314    ///
315    /// Returns the effects of the end-of-epoch transaction.
316    ///
317    /// # Panics
318    ///
319    /// Panics if the end-of-epoch transaction cannot be executed or fails.
320    pub fn advance_epoch(&self, create_deny_rules_object: bool) -> TransactionEffects {
321        let inner = self.inner.read().unwrap();
322        let current_epoch = inner.epoch_state.epoch();
323        let next_epoch = current_epoch + 1;
324        let next_epoch_protocol_version = inner.epoch_state.protocol_version();
325        let gas_cost_summary = inner
326            .checkpoint_builder
327            .epoch_rolling_gas_cost_summary()
328            .clone();
329        let epoch_start_timestamp_ms = inner.store.get_clock().timestamp_ms;
330        let pass_validator_scores = inner
331            .epoch_state
332            .protocol_config()
333            .pass_validator_scores_to_advance_epoch();
334        let adjust_rewards_by_score = inner
335            .epoch_state
336            .protocol_config()
337            .adjust_rewards_by_score();
338        let committee_size = inner.epoch_state.committee().num_members();
339        drop(inner);
340
341        // One full score per validator, so rewards stay unadjusted. This
342        // mirrors the node's default when locally calculated scores are not
343        // passed. Must match MAX_SCORE in validator_set.move.
344        const MAX_SCORE: u64 = u16::MAX as u64 + 1;
345        let scores = vec![MAX_SCORE; committee_size];
346
347        let next_epoch_system_package_bytes: Vec<SystemPackage> = vec![];
348        let mut kinds = Vec::new();
349        if create_deny_rules_object {
350            kinds.push(EndOfEpochTransactionKind::TransactionDenyRulesCreate);
351        }
352        // Mirror the node's kind selection: the framework's `advance_epoch`
353        // expects the V4 argument shape when the flag is enabled.
354        kinds.push(if pass_validator_scores {
355            EndOfEpochTransactionKind::new_change_epoch_v4(
356                next_epoch,
357                next_epoch_protocol_version.as_u64(),
358                gas_cost_summary.storage_cost,
359                gas_cost_summary.computation_cost,
360                gas_cost_summary.computation_cost_burned,
361                gas_cost_summary.storage_rebate,
362                gas_cost_summary.non_refundable_storage_fee,
363                epoch_start_timestamp_ms,
364                next_epoch_system_package_bytes,
365                vec![],
366                scores,
367                adjust_rewards_by_score,
368            )
369        } else {
370            EndOfEpochTransactionKind::new_change_epoch_v3(
371                next_epoch,
372                next_epoch_protocol_version.as_u64(),
373                gas_cost_summary.storage_cost,
374                gas_cost_summary.computation_cost,
375                gas_cost_summary.computation_cost_burned,
376                gas_cost_summary.storage_rebate,
377                gas_cost_summary.non_refundable_storage_fee,
378                epoch_start_timestamp_ms,
379                next_epoch_system_package_bytes,
380                vec![],
381            )
382        });
383
384        let tx = VerifiedTransaction::new_end_of_epoch_transaction(kinds);
385        let (effects, execution_error) = self
386            .execute_transaction(tx.into())
387            .expect("advancing the epoch cannot fail");
388        assert!(
389            execution_error.is_none(),
390            "the end-of-epoch transaction failed: {execution_error:?}, {effects:?}"
391        );
392
393        let (checkpoint, contents, new_epoch_state) = {
394            let mut inner = self.inner.write().unwrap();
395            let system_state = inner.store.get_system_state();
396            // On same-version epoch changes, carry the current protocol config
397            // over instead of re-resolving it from the version, so feature
398            // flags customized for testing survive the epoch change.
399            let prev_protocol_config = inner.epoch_state.protocol_config();
400            let new_epoch_state =
401                if system_state.protocol_version() == prev_protocol_config.version.as_u64() {
402                    EpochState::new_with_config(prev_protocol_config.clone(), system_state)
403                } else {
404                    EpochState::new(system_state)
405                };
406            let end_of_epoch_data = EndOfEpochData {
407                next_epoch_committee: new_epoch_state.committee().committee_members(),
408                next_epoch_protocol_version: next_epoch_protocol_version.as_u64(),
409                epoch_commitments: vec![],
410                // Do not simulate supply changes for now.
411                epoch_supply_change: 0,
412            };
413            let (checkpoint, contents, _) = {
414                let committee =
415                    CommitteeWithKeys::new(&inner.keystore, inner.epoch_state.committee());
416                let timestamp_ms = inner.store.get_clock().timestamp_ms;
417                inner.checkpoint_builder.build_end_of_epoch(
418                    &committee,
419                    timestamp_ms,
420                    next_epoch,
421                    end_of_epoch_data,
422                )
423            };
424
425            inner.store.insert_checkpoint(checkpoint.clone());
426            inner.store.insert_checkpoint_contents(contents.clone());
427            inner
428                .store
429                .update_last_checkpoint_of_epoch(current_epoch, checkpoint.sequence_number());
430            (checkpoint, contents, new_epoch_state)
431        };
432
433        // Process data ingestion without holding the lock
434        self.process_data_ingestion(checkpoint, contents).unwrap();
435
436        // Finally, update the epoch state
437        let mut inner = self.inner.write().unwrap();
438        inner.epoch_state = new_epoch_state;
439
440        effects
441    }
442
443    /// Execute a function with read access to the store.
444    ///
445    /// This provides thread-safe access to the underlying store by locking it
446    /// for the duration of the closure execution.
447    pub fn with_store<F, T>(&self, f: F) -> T
448    where
449        F: FnOnce(&S) -> T,
450    {
451        let inner = self.inner.read().unwrap();
452        f(&inner.store)
453    }
454
455    /// Execute a function with read access to the keystore.
456    ///
457    /// This provides thread-safe access to the keystore by locking it
458    /// for the duration of the closure execution.
459    pub fn with_keystore<F, T>(&self, f: F) -> T
460    where
461        F: FnOnce(&KeyStore) -> T,
462    {
463        let inner = self.inner.read().unwrap();
464        f(&inner.keystore)
465    }
466
467    pub fn epoch_start_state(&self) -> EpochStartSystemState {
468        let inner = self.inner.read().unwrap();
469        inner.epoch_state.epoch_start_state()
470    }
471
472    /// Execute a function with mutable access to the internally held RNG.
473    ///
474    /// Provides mutable access to the RNG used to create this Simulacrum for
475    /// use as a source of randomness. Using a seeded RNG to build a
476    /// Simulacrum and then utilizing the stored RNG as a source of
477    /// randomness can lead to a fully deterministic chain evolution.
478    pub fn with_rng<F, T>(&self, f: F) -> T
479    where
480        F: FnOnce(&mut R) -> T,
481    {
482        let mut inner = self.inner.write().unwrap();
483        f(&mut inner.rng)
484    }
485
486    /// Return the reference gas price for the current epoch
487    pub fn reference_gas_price(&self) -> u64 {
488        self.inner.read().unwrap().epoch_state.reference_gas_price()
489    }
490
491    /// Request that `amount` Nanos be sent to `address` from a faucet account.
492    ///
493    /// ```
494    /// use iota_sdk_types::Address;
495    /// use iota_types::gas_coin::NANOS_PER_IOTA;
496    /// use simulacrum::Simulacrum;
497    ///
498    /// # fn main() {
499    /// let mut simulacrum = Simulacrum::new();
500    /// let address = simulacrum.with_rng(|rng| Address::random_with(rng));
501    /// simulacrum.request_gas(address, NANOS_PER_IOTA).unwrap();
502    ///
503    /// // `account` now has a Coin<IOTA> object with single IOTA in it.
504    /// // ...
505    /// # }
506    /// ```
507    pub fn request_gas(&self, address: Address, amount: u64) -> Result<TransactionEffects> {
508        // For right now we'll just use the first account as the `faucet` account. We
509        // may want to explicitly cordon off the faucet account from the rest of
510        // the accounts though.
511        let (sender, key) = self.with_keystore(|keystore| -> Result<(Address, _)> {
512            let (s, k) = keystore
513                .accounts()
514                .next()
515                .ok_or_else(|| anyhow!("no accounts available in keystore"))?;
516            Ok((*s, k.clone()))
517        })?;
518
519        let object = self
520            .with_store(|store| {
521                store.owned_objects(sender).find(|object| {
522                    object.is_gas_coin()
523                        && object.get_coin_value_unchecked() > amount + NANOS_PER_IOTA
524                })
525            })
526            .ok_or_else(|| {
527                anyhow!("unable to find a coin with enough to satisfy request for {amount} Nanos")
528            })?;
529
530        let gas_data = GasPayment {
531            objects: vec![object.object_ref()],
532            owner: sender,
533            price: self.reference_gas_price(),
534            budget: NANOS_PER_IOTA,
535        };
536
537        let pt = {
538            let mut builder =
539                iota_types::programmable_transaction_builder::ProgrammableTransactionBuilder::new();
540            builder.transfer_iota(address, Some(amount));
541            builder.finish()
542        };
543
544        let kind = TransactionKind::Programmable(pt);
545        let tx = iota_sdk_types::Transaction::new_with_gas_data(kind, sender, gas_data);
546        let tx = TransactionEnvelope::from_data_and_signer(tx, vec![&key]);
547
548        self.execute_transaction(tx).map(|x| x.0)
549    }
550
551    pub fn set_data_ingestion_path(&self, data_ingestion_path: PathBuf) {
552        let checkpoint = {
553            let mut inner = self.inner.write().unwrap();
554            inner.data_ingestion_path = Some(data_ingestion_path);
555            let checkpoint = inner.store.get_checkpoint_by_sequence_number(0).unwrap();
556            let contents = inner
557                .store
558                .get_checkpoint_contents_by_digest(&checkpoint.contents_digest);
559            (checkpoint, contents)
560        };
561        // Release lock before expensive data ingestion operation
562        if let (checkpoint, Some(contents)) = checkpoint {
563            self.process_data_ingestion(checkpoint, contents).unwrap();
564        }
565    }
566
567    /// Overrides the next checkpoint number indirectly by setting the previous
568    /// checkpoint's number to checkpoint_number - 1. This ensures the next
569    /// generated checkpoint has the exact sequence number provided. This
570    /// can be useful to generate checkpoints with specific sequence
571    /// numbers. Monotonicity of checkpoint numbers is enforced strictly.
572    pub fn override_next_checkpoint_number(&self, number: CheckpointSequenceNumber) {
573        let mut inner = self.inner.write().unwrap();
574        let committee = CommitteeWithKeys::new(&inner.keystore, inner.epoch_state.committee());
575        inner
576            .checkpoint_builder
577            .override_next_checkpoint_number(number, &committee);
578    }
579
580    /// Process data ingestion without holding the inner lock.
581    /// This version should be used when you don't already hold the lock.
582    fn process_data_ingestion(
583        &self,
584        checkpoint: VerifiedCheckpoint,
585        checkpoint_contents: CheckpointContents,
586    ) -> anyhow::Result<()> {
587        let path = self.inner.read().unwrap().data_ingestion_path.clone();
588        if let Some(data_path) = path {
589            let file_name = format!("{}.chk", checkpoint.sequence_number);
590            let checkpoint_data = self.try_get_checkpoint_data(checkpoint, checkpoint_contents)?;
591            std::fs::create_dir_all(&data_path)?;
592            let blob = Blob::encode(&checkpoint_data, BlobEncoding::Bcs)?;
593            std::fs::write(data_path.join(file_name), blob.to_bytes())?;
594        }
595        Ok(())
596    }
597}
598
599pub struct CommitteeWithKeys {
600    keystore: KeyStore,
601    committee: Committee,
602}
603
604impl CommitteeWithKeys {
605    fn new(keystore: &KeyStore, committee: &Committee) -> Self {
606        Self {
607            keystore: keystore.clone(),
608            committee: committee.clone(),
609        }
610    }
611
612    pub fn keystore(&self) -> &KeyStore {
613        &self.keystore
614    }
615}
616
617impl ValidatorKeypairProvider for CommitteeWithKeys {
618    fn get_validator_key(&self, name: &AuthorityName) -> &dyn Signer<AuthoritySignature> {
619        self.keystore.validator(name).unwrap()
620    }
621
622    fn get_committee(&self) -> &Committee {
623        &self.committee
624    }
625}
626
627impl<T, V: store::SimulatorStore> ObjectStore for Simulacrum<T, V> {
628    fn try_get_object(
629        &self,
630        object_id: &ObjectId,
631    ) -> Result<Option<Object>, iota_types::storage::error::Error> {
632        self.with_store(|store| store.try_get_object(object_id))
633    }
634
635    fn try_get_object_by_key(
636        &self,
637        object_id: &ObjectId,
638        version: VersionNumber,
639    ) -> Result<Option<Object>, iota_types::storage::error::Error> {
640        self.with_store(|store| store.try_get_object_by_key(object_id, version))
641    }
642}
643
644impl<T, V: store::SimulatorStore> ReadStore for Simulacrum<T, V> {
645    fn try_get_committee(
646        &self,
647        epoch: iota_types::committee::EpochId,
648    ) -> iota_types::storage::error::Result<Option<std::sync::Arc<Committee>>> {
649        self.with_store(|store| store.try_get_committee(epoch))
650    }
651
652    fn try_get_latest_checkpoint(&self) -> iota_types::storage::error::Result<VerifiedCheckpoint> {
653        Ok(self.with_store(|store| store.get_highest_checkpoint().unwrap()))
654    }
655
656    fn try_get_latest_epoch_id(&self) -> iota_types::storage::error::Result<EpochId> {
657        Ok(self.inner.read().unwrap().epoch_state.epoch())
658    }
659
660    fn try_get_highest_verified_checkpoint(
661        &self,
662    ) -> iota_types::storage::error::Result<VerifiedCheckpoint> {
663        Ok(self.with_store(|store| store.get_highest_checkpoint().unwrap()))
664    }
665
666    fn try_get_highest_synced_checkpoint(
667        &self,
668    ) -> iota_types::storage::error::Result<VerifiedCheckpoint> {
669        Ok(self.with_store(|store| store.get_highest_checkpoint().unwrap()))
670    }
671
672    fn try_get_lowest_available_checkpoint(
673        &self,
674    ) -> iota_types::storage::error::Result<iota_types::messages_checkpoint::CheckpointSequenceNumber>
675    {
676        // TODO wire this up to the underlying sim store, for now this will work since
677        // we never prune the sim store
678        Ok(0)
679    }
680
681    fn try_get_checkpoint_by_digest(
682        &self,
683        digest: &CheckpointDigest,
684    ) -> iota_types::storage::error::Result<Option<VerifiedCheckpoint>> {
685        Ok(self.with_store(|store| store.get_checkpoint_by_digest(digest)))
686    }
687
688    fn try_get_checkpoint_by_sequence_number(
689        &self,
690        sequence_number: iota_types::messages_checkpoint::CheckpointSequenceNumber,
691    ) -> iota_types::storage::error::Result<Option<VerifiedCheckpoint>> {
692        Ok(self.with_store(|store| store.get_checkpoint_by_sequence_number(sequence_number)))
693    }
694
695    fn try_get_checkpoint_contents_by_digest(
696        &self,
697        digest: &CheckpointContentsDigest,
698    ) -> iota_types::storage::error::Result<Option<CheckpointContents>> {
699        Ok(self.with_store(|store| store.get_checkpoint_contents_by_digest(digest)))
700    }
701
702    fn try_get_checkpoint_contents_by_sequence_number(
703        &self,
704        sequence_number: iota_types::messages_checkpoint::CheckpointSequenceNumber,
705    ) -> iota_types::storage::error::Result<Option<CheckpointContents>> {
706        Ok(self.with_store(|store| {
707            store
708                .get_checkpoint_by_sequence_number(sequence_number)
709                .and_then(|checkpoint| {
710                    store.get_checkpoint_contents_by_digest(&checkpoint.contents_digest)
711                })
712        }))
713    }
714
715    fn try_get_transaction(
716        &self,
717        tx_digest: &TransactionDigest,
718    ) -> iota_types::storage::error::Result<Option<Arc<VerifiedTransaction>>> {
719        Ok(self.with_store(|store| store.get_transaction(tx_digest)))
720    }
721
722    fn try_get_transaction_effects(
723        &self,
724        tx_digest: &TransactionDigest,
725    ) -> iota_types::storage::error::Result<Option<TransactionEffects>> {
726        Ok(self.with_store(|store| store.get_transaction_effects(tx_digest)))
727    }
728
729    fn try_get_events(
730        &self,
731        digest: &TransactionDigest,
732    ) -> iota_types::storage::error::Result<Option<TransactionEvents>> {
733        Ok(self.with_store(|store| store.get_events(digest)))
734    }
735
736    fn try_get_full_checkpoint_contents_by_sequence_number(
737        &self,
738        sequence_number: iota_types::messages_checkpoint::CheckpointSequenceNumber,
739    ) -> iota_types::storage::error::Result<
740        Option<iota_types::messages_checkpoint::FullCheckpointContents>,
741    > {
742        self.with_store(|store| {
743            store
744                .try_get_checkpoint_by_sequence_number(sequence_number)?
745                .and_then(|chk| store.get_checkpoint_contents_by_digest(&chk.contents_digest))
746                .map_or(Ok(None), |contents| {
747                    iota_types::messages_checkpoint::FullCheckpointContents::try_from_checkpoint_contents(
748                        store,
749                        contents,
750                    )
751                })
752        })
753    }
754
755    fn try_get_full_checkpoint_contents(
756        &self,
757        digest: &CheckpointContentsDigest,
758    ) -> iota_types::storage::error::Result<
759        Option<iota_types::messages_checkpoint::FullCheckpointContents>,
760    > {
761        self.with_store(|store| {
762            store.get_checkpoint_contents_by_digest(digest)
763            .map_or(Ok(None), |contents| {
764                iota_types::messages_checkpoint::FullCheckpointContents::try_from_checkpoint_contents(
765                    store,
766                    contents,
767                )
768            })
769        })
770    }
771}
772
773impl<T: Send + Sync, V: store::SimulatorStore + Send + Sync> GrpcStateReader for Simulacrum<T, V> {
774    fn get_lowest_available_checkpoint_objects(
775        &self,
776    ) -> iota_types::storage::error::Result<CheckpointSequenceNumber> {
777        Ok(0)
778    }
779
780    fn get_chain_identifier(
781        &self,
782    ) -> iota_types::storage::error::Result<iota_types::digests::ChainIdentifier> {
783        Ok(self
784            .with_store(|store| store.get_checkpoint_by_sequence_number(0))
785            .expect("lowest available checkpoint should exist")
786            .digest()
787            .to_owned()
788            .into())
789    }
790
791    fn get_epoch_last_checkpoint(
792        &self,
793        epoch_id: iota_types::committee::EpochId,
794    ) -> iota_types::storage::error::Result<Option<VerifiedCheckpoint>> {
795        Ok(self.with_store(|store| {
796            store
797                .get_last_checkpoint_of_epoch(epoch_id)
798                .and_then(|seq| store.get_checkpoint_by_sequence_number(seq))
799        }))
800    }
801
802    fn get_epoch_info(
803        &self,
804        epoch: iota_types::committee::EpochId,
805    ) -> iota_types::storage::error::Result<Option<EpochInfoV2>> {
806        Ok(self.with_store(|store| {
807            let start_checkpoint_seq = if epoch != 0 {
808                store
809                    .get_last_checkpoint_of_epoch(epoch - 1)
810                    .map(|seq| Some(seq + 1))
811                    .unwrap_or(None)?
812            } else {
813                0
814            };
815
816            let start_checkpoint = store.get_checkpoint_by_sequence_number(start_checkpoint_seq)?;
817
818            let system_state = self.get_system_state_for_epoch(epoch)?;
819
820            Some(EpochInfoV2 {
821                epoch,
822                start_checkpoint: start_checkpoint_seq,
823                start_timestamp_ms: start_checkpoint.data().timestamp_ms,
824                system_state,
825                // Simulacrum doesn't build the close-of-epoch proof, so the
826                // derived `end_*` fields report `None`.
827                epoch_close_proof: None,
828            })
829        }))
830    }
831
832    fn grpc_indexes(&self) -> Option<&dyn iota_node_storage::GrpcIndexes> {
833        Some(self)
834    }
835
836    fn get_transaction_checkpoint(
837        &self,
838        digest: &TransactionDigest,
839    ) -> iota_types::storage::error::Result<Option<CheckpointSequenceNumber>> {
840        Ok(self.with_store(|store| {
841            let highest_seq = store
842                .get_highest_checkpoint()
843                .map(|cp| cp.sequence_number())?;
844
845            for seq in (0..=highest_seq).rev() {
846                if let Some(checkpoint) = store.get_checkpoint_by_sequence_number(seq) {
847                    if let Some(contents) =
848                        store.get_checkpoint_contents_by_digest(&checkpoint.contents_digest)
849                    {
850                        if contents
851                            .iter()
852                            .any(|exec_digests| exec_digests.transaction == *digest)
853                        {
854                            return Some(checkpoint.sequence_number());
855                        }
856                    }
857                }
858            }
859            None
860        }))
861    }
862
863    fn get_struct_layout(
864        &self,
865        _: &StructTag,
866    ) -> iota_types::storage::error::Result<Option<move_core_types::annotated_value::MoveTypeLayout>>
867    {
868        Ok(None)
869    }
870}
871
872impl<T: Send + Sync, V: store::SimulatorStore + Send + Sync> Simulacrum<T, V> {
873    fn get_system_state_for_epoch(&self, epoch: u64) -> Option<IotaSystemState> {
874        self.with_store(|store| {
875            if let Some(historical_state) = store.get_system_state_by_epoch(epoch) {
876                return Some(historical_state.clone());
877            }
878            let current_system_state = store.get_system_state();
879            if epoch == current_system_state.epoch() {
880                return Some(current_system_state);
881            }
882            None
883        })
884    }
885}
886
887impl<T: Send + Sync, V: store::SimulatorStore + Send + Sync> GrpcIndexes for Simulacrum<T, V> {
888    fn account_owned_objects_info_iter(
889        &self,
890        _owner: Address,
891        _cursor: Option<&iota_types::storage::OwnedObjectCursor>,
892        _object_type: Option<StructTag>,
893    ) -> iota_types::storage::error::Result<
894        Box<dyn Iterator<Item = iota_types::storage::OwnedObjectIteratorItem> + '_>,
895    > {
896        Ok(Box::new(std::iter::empty()))
897    }
898
899    fn dynamic_field_iter(
900        &self,
901        _parent: iota_sdk_types::ObjectId,
902        _cursor: Option<iota_sdk_types::ObjectId>,
903    ) -> iota_types::storage::error::Result<
904        Box<
905            dyn Iterator<
906                    Item = Result<
907                        iota_types::storage::DynamicFieldKey,
908                        typed_store_error::TypedStoreError,
909                    >,
910                > + '_,
911        >,
912    > {
913        Ok(Box::new(std::iter::empty()))
914    }
915
916    fn get_coin_info(
917        &self,
918        _coin_type: &StructTag,
919    ) -> iota_types::storage::error::Result<Option<iota_types::storage::CoinInfo>> {
920        Ok(None)
921    }
922
923    fn package_versions_iter(
924        &self,
925        _original_package_id: iota_sdk_types::ObjectId,
926        _cursor: Option<u64>,
927    ) -> iota_types::storage::error::Result<
928        Box<dyn Iterator<Item = iota_types::storage::PackageVersionIteratorItem> + '_>,
929    > {
930        Ok(Box::new(std::iter::empty()))
931    }
932}
933
934impl Simulacrum {
935    /// Generate a random transfer transaction.
936    /// TODO: This is here today to make it easier to write tests. But we should
937    /// utilize all the existing code for generating transactions in
938    /// iota-test-transaction-builder by defining a trait
939    /// that both WalletContext and Simulacrum implement. Then we can remove
940    /// this function.
941    pub fn transfer_txn(&self, recipient: Address) -> (TransactionEnvelope, u64) {
942        let (sender, key) = self.with_keystore(|keystore| {
943            let (s, k) = keystore.accounts().next().unwrap();
944            (*s, k.clone())
945        });
946
947        let (object, gas_coin_value) = self.with_store(|store| {
948            let object = store
949                .owned_objects(sender)
950                .find(|object| object.is_gas_coin())
951                .unwrap();
952            let gas_coin = GasCoin::try_from(object).unwrap();
953            (object.clone(), gas_coin.value())
954        });
955        let transfer_amount = gas_coin_value / 2;
956
957        let pt = {
958            let mut builder = ProgrammableTransactionBuilder::new();
959            builder.transfer_iota(recipient, Some(transfer_amount));
960            builder.finish()
961        };
962
963        let kind = TransactionKind::Programmable(pt);
964        let gas_data = GasPayment {
965            objects: vec![object.object_ref()],
966            owner: sender,
967            price: self.reference_gas_price(),
968            budget: 1_000_000_000,
969        };
970        let tx = Transaction::new_with_gas_data(kind, sender, gas_data);
971        let tx = TransactionEnvelope::from_data_and_signer(tx, vec![&key]);
972        (tx, transfer_amount)
973    }
974}
975
976#[cfg(test)]
977mod tests {
978    use std::time::Duration;
979
980    use iota_types::{
981        effects::TransactionEffectsAPI,
982        error::IotaError,
983        gas_coin::GasCoin,
984        transaction::TransactionAPI,
985        transaction_executor::VmChecks,
986        utils::{assert_size_limit_err, ptb_above_max_tx_size},
987    };
988    use rand::{SeedableRng, rngs::StdRng};
989
990    use super::*;
991
992    #[test]
993    fn deterministic_genesis() {
994        let rng = StdRng::from_seed([9; 32]);
995        let chain1 = Simulacrum::new_with_rng(rng);
996        let genesis_checkpoint_digest1 = chain1
997            .with_store(|store| *store.get_checkpoint_by_sequence_number(0).unwrap().digest());
998
999        let rng = StdRng::from_seed([9; 32]);
1000        let chain2 = Simulacrum::new_with_rng(rng);
1001        let genesis_checkpoint_digest2 = chain2
1002            .with_store(|store| *store.get_checkpoint_by_sequence_number(0).unwrap().digest());
1003
1004        assert_eq!(genesis_checkpoint_digest1, genesis_checkpoint_digest2);
1005
1006        // Ensure the committees are different when using different seeds
1007        let rng = StdRng::from_seed([0; 32]);
1008        let chain3 = Simulacrum::new_with_rng(rng);
1009
1010        let committee1 = chain1.with_store(|store| store.get_committee_by_epoch(0).cloned());
1011        let committee3 = chain3.with_store(|store| store.get_committee_by_epoch(0).cloned());
1012        assert_ne!(committee1, committee3);
1013    }
1014
1015    #[test]
1016    fn simple() {
1017        let steps = 10;
1018        let sim = Simulacrum::new();
1019
1020        let start_time_ms = sim.with_store(|store| {
1021            let clock = store.get_clock();
1022            println!("clock: {clock:#?}");
1023            clock.timestamp_ms
1024        });
1025
1026        for _ in 0..steps {
1027            sim.advance_clock(Duration::from_millis(1));
1028            sim.create_checkpoint();
1029            sim.with_store(|store| {
1030                let clock = store.get_clock();
1031                println!("clock: {clock:#?}");
1032            });
1033        }
1034        let end_time_ms = sim.with_store(|store| store.get_clock().timestamp_ms);
1035        assert_eq!(end_time_ms - start_time_ms, steps);
1036        sim.with_store(|store| {
1037            dbg!(store.get_highest_checkpoint());
1038        });
1039    }
1040
1041    #[test]
1042    fn advance_epoch_creates_deny_rules_object() {
1043        let sim = Simulacrum::new();
1044
1045        assert!(sim.with_store(|store| {
1046            store
1047                .get_object(&iota_types::IOTA_TRANSACTION_DENY_RULES_OBJECT_ID)
1048                .is_none()
1049        }));
1050
1051        sim.advance_epoch(true);
1052
1053        let object = sim
1054            .with_store(|store| {
1055                store
1056                    .get_object(&iota_types::IOTA_TRANSACTION_DENY_RULES_OBJECT_ID)
1057                    .cloned()
1058            })
1059            .expect("the TransactionDenyRules object must exist after the create");
1060        assert!(object.owner().is_shared());
1061    }
1062
1063    /// The full deny rule state read back by walking the object's
1064    /// `LinkedTable`s matches the deltas applied through real execution.
1065    #[test]
1066    fn walked_object_state_matches_applied_deltas() {
1067        use std::collections::BTreeSet;
1068
1069        use iota_sdk_types::TransactionDenyRulesUpdate;
1070        use iota_types::transaction_deny_rules::{
1071            get_transaction_deny_rules, get_transaction_deny_rules_obj_initial_shared_version,
1072        };
1073
1074        let sim = Simulacrum::new();
1075        sim.advance_epoch(true);
1076
1077        let initial_shared_version = sim
1078            .with_store(|store| get_transaction_deny_rules_obj_initial_shared_version(store))
1079            .unwrap()
1080            .expect("object must exist after the create");
1081
1082        let denied_address = Address::new([0xAA; 32]);
1083        let removed_address = Address::new([0xBB; 32]);
1084        let denied_package = ObjectId::new([0x2B; 32]);
1085        let update = |round, added_addresses: BTreeSet<Address>, removed_addresses| {
1086            VerifiedTransaction::new_transaction_deny_rules_update(TransactionDenyRulesUpdate {
1087                epoch: 1,
1088                round,
1089                added_addresses,
1090                removed_addresses,
1091                added_objects: BTreeSet::new(),
1092                removed_objects: BTreeSet::new(),
1093                added_packages: [denied_package].into(),
1094                removed_packages: BTreeSet::new(),
1095                package_publish_disabled: false,
1096                package_upgrade_disabled: false,
1097                shared_object_disabled: true,
1098                user_transaction_disabled: false,
1099                receiving_objects_disabled: false,
1100                move_authenticator_disabled: false,
1101                deny_rules_obj_initial_shared_version: initial_shared_version,
1102            })
1103        };
1104
1105        // Two entries in, then one removed again: the walk crosses re-linked
1106        // nodes, not just appended ones.
1107        let (_, error) = sim
1108            .execute_transaction(
1109                update(0, [denied_address, removed_address].into(), BTreeSet::new()).into(),
1110            )
1111            .unwrap();
1112        assert!(error.is_none());
1113        let (_, error) = sim
1114            .execute_transaction(update(1, BTreeSet::new(), [removed_address].into()).into())
1115            .unwrap();
1116        assert!(error.is_none());
1117
1118        let walked = sim
1119            .with_store(|store| get_transaction_deny_rules(store))
1120            .unwrap()
1121            .expect("object must exist");
1122        assert_eq!(walked.denied_addresses, [denied_address].into());
1123        assert!(walked.denied_objects.is_empty());
1124        assert_eq!(walked.denied_packages, [denied_package].into());
1125        assert!(walked.shared_object_disabled);
1126        assert!(!walked.user_transaction_disabled);
1127    }
1128
1129    /// A chunk at the `deny_rule_update_max_entries_per_tx` ceiling executes:
1130    /// all additions and all removals, which stress different limits (new
1131    /// object ids and event size vs the store entries touched by re-linking).
1132    #[test]
1133    fn deny_rule_update_executes_at_the_chunk_ceiling() {
1134        use std::collections::BTreeSet;
1135
1136        use iota_sdk_types::TransactionDenyRulesUpdate;
1137        use iota_types::transaction_deny_rules::{
1138            get_transaction_deny_rules, get_transaction_deny_rules_obj_initial_shared_version,
1139        };
1140
1141        const CEILING: u64 = 2048;
1142
1143        let _guard =
1144            iota_protocol_config::ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
1145                config.set_deny_rule_update_max_entries_per_tx_for_testing(CEILING);
1146                config
1147            });
1148        let sim = Simulacrum::new();
1149        sim.advance_epoch(true);
1150
1151        let initial_shared_version = sim
1152            .with_store(|store| get_transaction_deny_rules_obj_initial_shared_version(store))
1153            .unwrap()
1154            .expect("object must exist after the create");
1155
1156        let addresses: BTreeSet<Address> = (0..CEILING)
1157            .map(|i| {
1158                let mut bytes = [0u8; 32];
1159                bytes[..8].copy_from_slice(&i.to_be_bytes());
1160                Address::new(bytes)
1161            })
1162            .collect();
1163        let update = |round, added_addresses, removed_addresses| {
1164            VerifiedTransaction::new_transaction_deny_rules_update(TransactionDenyRulesUpdate {
1165                epoch: 1,
1166                round,
1167                added_addresses,
1168                removed_addresses,
1169                added_objects: BTreeSet::new(),
1170                removed_objects: BTreeSet::new(),
1171                added_packages: BTreeSet::new(),
1172                removed_packages: BTreeSet::new(),
1173                package_publish_disabled: false,
1174                package_upgrade_disabled: false,
1175                shared_object_disabled: false,
1176                user_transaction_disabled: false,
1177                receiving_objects_disabled: false,
1178                move_authenticator_disabled: false,
1179                deny_rules_obj_initial_shared_version: initial_shared_version,
1180            })
1181        };
1182
1183        let (_, error) = sim
1184            .execute_transaction(update(0, addresses.clone(), BTreeSet::new()).into())
1185            .unwrap();
1186        assert!(error.is_none());
1187        let walked = sim
1188            .with_store(|store| get_transaction_deny_rules(store))
1189            .unwrap()
1190            .expect("object must exist");
1191        assert_eq!(walked.denied_addresses.len(), CEILING as usize);
1192
1193        let (_, error) = sim
1194            .execute_transaction(update(1, BTreeSet::new(), addresses).into())
1195            .unwrap();
1196        assert!(error.is_none());
1197        let walked = sim
1198            .with_store(|store| get_transaction_deny_rules(store))
1199            .unwrap()
1200            .expect("object must exist");
1201        assert!(walked.denied_addresses.is_empty());
1202    }
1203
1204    #[test]
1205    fn simple_epoch() {
1206        let steps = 10;
1207        let sim = Simulacrum::new();
1208
1209        let start_epoch = sim.with_store(|store| store.get_highest_checkpoint().unwrap().epoch);
1210        for i in 0..steps {
1211            sim.advance_epoch(false);
1212            sim.advance_clock(Duration::from_millis(1));
1213            sim.create_checkpoint();
1214            println!("{i}");
1215        }
1216        let end_epoch = sim.with_store(|store| store.get_highest_checkpoint().unwrap().epoch);
1217        assert_eq!(end_epoch - start_epoch, steps);
1218        sim.with_store(|store| {
1219            dbg!(store.get_highest_checkpoint());
1220        });
1221    }
1222
1223    #[test]
1224    fn transfer() {
1225        let sim = Simulacrum::new();
1226        let recipient = Address::random();
1227        let (tx, transfer_amount) = sim.transfer_txn(recipient);
1228
1229        let gas_id = tx.data().transaction().gas_data().objects[0].object_id;
1230        let effects = sim.execute_transaction(tx).unwrap().0;
1231        let gas_summary = effects.gas_cost_summary();
1232        let gas_paid = gas_summary.net_gas_usage();
1233
1234        sim.with_store(|store| {
1235            assert_eq!(
1236                (transfer_amount as i64 - gas_paid) as u64,
1237                store::SimulatorStore::get_object(store, &gas_id)
1238                    .and_then(|object| GasCoin::try_from(&object).ok())
1239                    .unwrap()
1240                    .value()
1241            );
1242
1243            assert_eq!(
1244                transfer_amount,
1245                store
1246                    .owned_objects(recipient)
1247                    .next()
1248                    .and_then(|object| GasCoin::try_from(object).ok())
1249                    .unwrap()
1250                    .value()
1251            );
1252        });
1253
1254        let checkpoint = sim.create_checkpoint();
1255
1256        assert_eq!(&checkpoint.epoch_rolling_gas_cost_summary, gas_summary);
1257        assert_eq!(checkpoint.network_total_transactions, 2); // genesis + 1 txn
1258    }
1259
1260    /// A dependent of a failed transaction executes without running any
1261    /// command. A dependent of a transaction that has not executed is
1262    /// simulated as if that transaction succeeded, and rejected at execution.
1263    #[test]
1264    fn transaction_dependency() {
1265        use iota_protocol_config::ProtocolConfig;
1266        use iota_sdk_types::{ExecutionStatus, TransactionExpiration};
1267        use iota_types::error::UserInputError;
1268
1269        let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
1270            config.set_enable_transaction_dependencies_for_testing(true);
1271            config
1272        });
1273        let sim = Simulacrum::new();
1274        let (sender, key) = sim.with_keystore(|keystore| {
1275            let (sender, key) = keystore.accounts().next().unwrap();
1276            (*sender, key.clone())
1277        });
1278        let transfer = |amount: u64, dependency: Option<TransactionDigest>| {
1279            let gas = sim.with_store(|store| {
1280                store
1281                    .owned_objects(sender)
1282                    .find(|object| object.is_gas_coin())
1283                    .unwrap()
1284                    .object_ref()
1285            });
1286            let mut builder = ProgrammableTransactionBuilder::new();
1287            builder.transfer_iota(Address::random(), Some(amount));
1288            if let Some(dependency) = dependency {
1289                builder.transaction_dependency(dependency);
1290            }
1291            let gas_data = GasPayment {
1292                objects: vec![gas],
1293                owner: sender,
1294                price: sim.reference_gas_price(),
1295                budget: 1_000_000_000,
1296            };
1297            let mut transaction = Transaction::new_with_gas_data(
1298                TransactionKind::Programmable(builder.finish()),
1299                sender,
1300                gas_data,
1301            );
1302            if let (Some(_), Transaction::V1(transaction)) = (dependency, &mut transaction) {
1303                transaction.expiration = TransactionExpiration::Epoch(0);
1304            }
1305            TransactionEnvelope::from_data_and_signer(transaction, vec![&key])
1306        };
1307
1308        let failing = transfer(u64::MAX, None);
1309        let failing_digest = *failing.digest();
1310        let (effects, _) = sim.execute_transaction(failing).unwrap();
1311        assert!(!effects.status().is_success(), "{effects:?}");
1312
1313        let (effects, _) = sim
1314            .execute_transaction(transfer(1, Some(failing_digest)))
1315            .unwrap();
1316        assert_eq!(
1317            effects.status(),
1318            &ExecutionStatus::Failure {
1319                error: iota_sdk_types::ExecutionError::TransactionDependencyFailed {
1320                    dependency: failing_digest
1321                },
1322                command: None,
1323            }
1324        );
1325        assert!(effects.dependencies().contains(&failing_digest));
1326
1327        let unknown = TransactionDigest::random();
1328        let simulated = sim
1329            .simulate_transaction(
1330                transfer(1, Some(unknown)).data().transaction().clone(),
1331                VmChecks::Enabled,
1332            )
1333            .unwrap();
1334        assert!(
1335            simulated.effects.status().is_success(),
1336            "{:?}",
1337            simulated.effects
1338        );
1339        let error = sim
1340            .execute_transaction(transfer(1, Some(unknown)))
1341            .unwrap_err();
1342        assert!(
1343            matches!(
1344                error.downcast_ref::<IotaError>(),
1345                Some(IotaError::UserInput {
1346                    error: UserInputError::TransactionDependencyNotFound { digest }
1347                }) if *digest == unknown
1348            ),
1349            "{error:?}"
1350        );
1351    }
1352
1353    /// A system transaction kind is rejected under both check modes.
1354    ///
1355    /// Simulating one would run it outside the sequencing that gives it
1356    /// meaning, and the shared input checks treat a system transaction as
1357    /// exempt from the gas and object rules rather than rejecting it, so the
1358    /// entry point is where this belongs — as it is on the node and in the SDK.
1359    #[test]
1360    fn simulate_rejects_system_transactions() {
1361        use iota_types::{error::IotaError, transaction_executor::VmChecks};
1362
1363        let sim = Simulacrum::new();
1364        let (tx, _) = sim.transfer_txn(Address::random());
1365        let mut transaction = tx.data().transaction().clone();
1366        *transaction.kind_mut() = TransactionKind::EndOfEpoch(vec![]);
1367
1368        for checks in [VmChecks::Enabled, VmChecks::Disabled] {
1369            let Err(error) = sim.simulate_transaction(transaction.clone(), checks) else {
1370                panic!("{checks:?} must not simulate a system transaction");
1371            };
1372            assert!(
1373                matches!(error, IotaError::UnsupportedFeature { .. }),
1374                "unexpected error for {checks:?}: {error:?}"
1375            );
1376        }
1377    }
1378
1379    /// An owned input object whose owner is not the sender is rejected under
1380    /// [`VmChecks::Enabled`] and accepted under [`VmChecks::Disabled`].
1381    #[test]
1382    fn simulate_distinguishes_owned_input_owner_by_check_mode() {
1383        use iota_sdk_types::ExecutionStatus;
1384        use iota_types::{
1385            error::{IotaError, UserInputError},
1386            transaction::CallArg,
1387            transaction_executor::VmChecks,
1388        };
1389
1390        let sim = Simulacrum::new();
1391        let (sender, other) = sim.with_keystore(|keystore| {
1392            let mut accounts = keystore.accounts();
1393            let (sender, _) = accounts.next().unwrap();
1394            let (other, _) = accounts.next().unwrap();
1395            (*sender, *other)
1396        });
1397
1398        let (foreign_object, gas_object) = sim.with_store(|store| {
1399            let foreign = store
1400                .owned_objects(other)
1401                .find(|object| object.is_gas_coin())
1402                .unwrap()
1403                .clone();
1404            let gas = store
1405                .owned_objects(sender)
1406                .find(|object| object.is_gas_coin())
1407                .unwrap()
1408                .clone();
1409            (foreign, gas)
1410        });
1411
1412        let pt = {
1413            let mut builder = ProgrammableTransactionBuilder::new();
1414            builder
1415                .input(CallArg::ImmutableOrOwned(foreign_object.object_ref()))
1416                .unwrap();
1417            builder.transfer_iota(Address::random(), Some(1000));
1418            builder.finish()
1419        };
1420        let kind = TransactionKind::Programmable(pt);
1421        let gas_data = GasPayment {
1422            objects: vec![gas_object.object_ref()],
1423            owner: sender,
1424            price: sim.reference_gas_price(),
1425            budget: 1_000_000_000,
1426        };
1427        let transaction = Transaction::new_with_gas_data(kind, sender, gas_data);
1428
1429        let Err(error) = sim.simulate_transaction(transaction.clone(), VmChecks::Enabled) else {
1430            panic!("a dry run must reject an owned input owned by a different address");
1431        };
1432        assert!(
1433            matches!(
1434                error,
1435                IotaError::UserInput {
1436                    error: UserInputError::IncorrectUserSignature { .. }
1437                }
1438            ),
1439            "unexpected error: {error:?}"
1440        );
1441
1442        let result = sim
1443            .simulate_transaction(transaction, VmChecks::Disabled)
1444            .expect("a dev inspect must accept an owned input owned by a different address");
1445        assert_eq!(result.effects.status(), &ExecutionStatus::Success);
1446    }
1447
1448    #[test]
1449    fn simulate_rejects_a_transaction_above_the_size_limit() {
1450        let sim = Simulacrum::new();
1451        let pt = {
1452            let inner = sim.inner.read().unwrap();
1453            ptb_above_max_tx_size(inner.epoch_state.protocol_config())
1454        };
1455        let transaction =
1456            Transaction::new_programmable(Address::random(), vec![], pt, 10_000_000, 1000);
1457
1458        let Err(err) = sim.simulate_transaction(transaction, VmChecks::Enabled) else {
1459            panic!("a transaction above the size limit must be rejected");
1460        };
1461        let IotaError::UserInput { error } = &err else {
1462            panic!("got {err:?}");
1463        };
1464        assert_size_limit_err(error, "serialized transaction size exceeded maximum");
1465    }
1466}