Skip to main content

iota_adapter_latest/
execution_engine.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5pub use checked::*;
6
7#[iota_macros::with_checked_arithmetic]
8mod checked {
9
10    use std::{
11        cell::RefCell,
12        collections::{BTreeMap, BTreeSet, HashSet},
13        rc::Rc,
14        sync::Arc,
15    };
16
17    use iota_move_natives::all_natives;
18    use iota_protocol_config::{LimitThresholdCrossed, ProtocolConfig, check_limit_by_meter};
19    use iota_sdk_types::{
20        Address, Argument, ChangeEpoch, ChangeEpochV2, ChangeEpochV3, ChangeEpochV4, Command,
21        EndOfEpochTransactionKind, ExecutionStatus, GasCostSummary, GasPayment, GenesisTransaction,
22        Identifier, MoveAuthenticator, ObjectId, ProgrammableTransaction, RandomnessStateUpdate,
23        SharedObjectReference, StructTag, SystemPackage, TransactionDenyRulesUpdate,
24        TransactionDigest, TransactionEffects, TransactionKind, TypeTag, Version,
25    };
26    #[cfg(msim)]
27    use iota_types::iota_system_state::advance_epoch_result_injection::maybe_modify_result;
28    use iota_types::{
29        account_abstraction::authenticator_function::{
30            AuthenticatorFunctionRef, AuthenticatorFunctionRefForExecution,
31            AuthenticatorFunctionRefV1, MoveAuthenticatorForExecution,
32            MoveAuthenticatorsForExecution,
33        },
34        auth_context::{AuthContext, AuthContextData},
35        balance::{BALANCE_CREATE_REWARDS_FUNCTION_NAME, BALANCE_DESTROY_REBATES_FUNCTION_NAME},
36        base_types::TxContext,
37        clock::CONSENSUS_COMMIT_PROLOGUE_FUNCTION_NAME,
38        committee::EpochId,
39        error::{ExecutionError, ExecutionErrorKind},
40        execution::{
41            AuthenticateThenExecuteOutput, ExecutionResults, ExecutionResultsV1, ExecutionTiming,
42            ResultWithTimings, SharedInput, is_any_invariant_violation, is_cancellation,
43            is_certificate_denied, unwrap_move_authentication_error,
44        },
45        execution_config_utils::to_binary_config,
46        gas::{IotaGasStatus, IotaGasStatusAPI},
47        inner_temporary_store::InnerTemporaryStore,
48        iota_system_state::{ADVANCE_EPOCH_FUNCTION_NAME, AdvanceEpochParams},
49        messages_checkpoint::CheckpointTimestamp,
50        metrics::LimitsMetrics,
51        move_authenticator::MoveAuthenticatorExt,
52        object::{OBJECT_START_VERSION, Object, ObjectInner},
53        programmable_transaction_builder::ProgrammableTransactionBuilder,
54        randomness_state::RANDOMNESS_STATE_UPDATE_FUNCTION_NAME,
55        storage::{BackingStore, Storage},
56        transaction::{
57            CallArg, CancelledObjects, CheckedInputObjects, InputObjects, TransactionKindExt,
58        },
59        transaction_deny_rules::{
60            TRANSACTION_DENY_RULES_CREATE_FUNCTION_NAME, TRANSACTION_DENY_RULES_MODULE,
61            TRANSACTION_DENY_RULES_UPDATE_FUNCTION_NAME,
62        },
63    };
64    use move_binary_format::CompiledModule;
65    use move_trace_format::format::MoveTraceBuilder;
66    use move_vm_runtime::move_vm::MoveVM;
67    use tracing::{info, instrument, trace, warn};
68
69    use crate::{
70        adapter::new_move_vm,
71        execution_mode::{self, ExecutionMode},
72        gas_charger::GasCharger,
73        programmable_transactions,
74        temporary_store::TemporaryStore,
75        type_layout_resolver::TypeLayoutResolver,
76    };
77
78    /// The main entry point to the adapter's transaction execution. It
79    /// prepares a transaction for execution, then executes it through an
80    /// inner execution method and finally produces an instance of
81    /// transaction effects. It also returns the inner temporary store, which
82    /// contains the objects resulting from the transaction execution, the gas
83    /// status instance, which tracks the gas usage, and the execution result.
84    /// The function handles transaction execution based on the provided
85    /// `TransactionKind`. It checks for any expensive operations, manages
86    /// shared object references, and ensures transaction dependencies are
87    /// met. The returned objects are not committed to the store until the
88    /// resulting effects are applied by the caller.
89    #[instrument(name = "tx_execute_to_effects", level = "debug", skip_all)]
90    pub fn execute_transaction_to_effects<Mode: ExecutionMode>(
91        store: &dyn BackingStore,
92        input_objects: CheckedInputObjects,
93        gas_data: GasPayment,
94        gas_status: IotaGasStatus,
95        transaction_kind: TransactionKind,
96        transaction_signer: Address,
97        transaction_digest: TransactionDigest,
98        move_vm: &Arc<MoveVM>,
99        epoch_id: &EpochId,
100        epoch_timestamp_ms: u64,
101        protocol_config: &ProtocolConfig,
102        metrics: Arc<LimitsMetrics>,
103        enable_expensive_checks: bool,
104        certificate_deny_set: &HashSet<TransactionDigest>,
105        trace_builder_opt: &mut Option<MoveTraceBuilder>,
106    ) -> (
107        InnerTemporaryStore,
108        IotaGasStatus,
109        TransactionEffects,
110        Vec<ExecutionTiming>,
111        Result<Mode::ExecutionResults, ExecutionError>,
112    ) {
113        let input_objects = input_objects.into_inner();
114        let mutable_inputs = if enable_expensive_checks {
115            input_objects.mutable_inputs().keys().copied().collect()
116        } else {
117            HashSet::new()
118        };
119        let shared_object_refs = input_objects.filter_shared_objects();
120        let receiving_objects = transaction_kind.receiving_objects();
121        let transaction_dependencies = input_objects.transaction_dependencies();
122        let contains_deleted_input = input_objects.contains_deleted_objects();
123        let cancelled_objects = input_objects.get_cancelled_objects();
124        let failed_dependency = input_objects.failed_transaction_dependency();
125
126        let temporary_store = TemporaryStore::new(
127            store,
128            input_objects,
129            receiving_objects,
130            transaction_digest,
131            protocol_config,
132            *epoch_id,
133        );
134
135        let sponsor = resolve_sponsor(&gas_data, &transaction_signer);
136        let gas_price = gas_status.gas_price();
137        let rgp = gas_status.reference_gas_price();
138        let gas_charger = GasCharger::new(
139            transaction_digest,
140            gas_data.objects,
141            gas_status,
142            protocol_config,
143        );
144
145        let tx_ctx = TxContext::new_from_components(
146            &transaction_signer,
147            &transaction_digest,
148            epoch_id,
149            epoch_timestamp_ms,
150            rgp,
151            gas_price,
152            gas_data.budget,
153            sponsor,
154            protocol_config,
155        );
156        let tx_ctx = Rc::new(RefCell::new(tx_ctx));
157
158        execute_transaction_to_effects_inner::<Mode>(
159            temporary_store,
160            gas_charger,
161            tx_ctx,
162            &mutable_inputs,
163            shared_object_refs,
164            transaction_dependencies,
165            contains_deleted_input,
166            cancelled_objects,
167            failed_dependency,
168            transaction_kind,
169            transaction_signer,
170            transaction_digest,
171            move_vm,
172            epoch_id,
173            protocol_config,
174            metrics,
175            enable_expensive_checks,
176            certificate_deny_set,
177            trace_builder_opt,
178            None,
179        )
180    }
181
182    /// The main execution function that processes a transaction and produces
183    /// effects. It handles gas charging and execution logic.
184    #[instrument(name = "tx_execute_to_effects_inner", level = "debug", skip_all)]
185    fn execute_transaction_to_effects_inner<Mode: ExecutionMode>(
186        mut temporary_store: TemporaryStore,
187        mut gas_charger: GasCharger,
188        tx_ctx: Rc<RefCell<TxContext>>,
189        mutable_inputs: &HashSet<ObjectId>,
190        shared_object_refs: Vec<SharedInput>,
191        mut transaction_dependencies: BTreeSet<TransactionDigest>,
192        contains_deleted_input: bool,
193        cancelled_objects: Option<(CancelledObjects, Version)>,
194        failed_dependency: Option<TransactionDigest>,
195        transaction_kind: TransactionKind,
196        transaction_signer: Address,
197        transaction_digest: TransactionDigest,
198        move_vm: &Arc<MoveVM>,
199        epoch_id: &EpochId,
200        protocol_config: &ProtocolConfig,
201        metrics: Arc<LimitsMetrics>,
202        enable_expensive_checks: bool,
203        certificate_deny_set: &HashSet<TransactionDigest>,
204        trace_builder_opt: &mut Option<MoveTraceBuilder>,
205        pre_execution_result_opt: Option<
206            Result<
207                <execution_mode::Authentication as ExecutionMode>::ExecutionResults,
208                ExecutionError,
209            >,
210        >,
211    ) -> (
212        InnerTemporaryStore,
213        IotaGasStatus,
214        TransactionEffects,
215        Vec<ExecutionTiming>,
216        Result<Mode::ExecutionResults, ExecutionError>,
217    ) {
218        let is_epoch_change = transaction_kind.is_end_of_epoch();
219        let deny_cert = is_certificate_denied(&transaction_digest, certificate_deny_set);
220
221        let (gas_cost_summary, execution_result, timings) = execute_transaction::<Mode>(
222            &mut temporary_store,
223            transaction_kind,
224            &mut gas_charger,
225            tx_ctx,
226            move_vm,
227            protocol_config,
228            metrics,
229            enable_expensive_checks,
230            deny_cert,
231            contains_deleted_input,
232            cancelled_objects,
233            failed_dependency,
234            trace_builder_opt,
235            pre_execution_result_opt,
236        );
237
238        let status = if let Err(error) = &execution_result {
239            elaborate_error_logs(error, transaction_digest)
240        } else {
241            ExecutionStatus::Success
242        };
243
244        #[skip_checked_arithmetic]
245        trace!(
246            tx_digest = ?transaction_digest,
247            computation_gas_cost = gas_cost_summary.computation_cost,
248            computation_gas_cost_burned = gas_cost_summary.computation_cost_burned,
249            storage_gas_cost = gas_cost_summary.storage_cost,
250            storage_gas_rebate = gas_cost_summary.storage_rebate,
251            "Finished execution of transaction with status {:?}",
252            status
253        );
254
255        // Genesis writes a special digest to indicate that an object was created during
256        // genesis and not written by any normal transaction - remove that from the
257        // dependencies
258        transaction_dependencies.remove(&TransactionDigest::GENESIS_MARKER);
259
260        if enable_expensive_checks && !Mode::allow_arbitrary_function_calls() {
261            temporary_store
262                .check_ownership_invariants(
263                    &transaction_signer,
264                    &mut gas_charger,
265                    mutable_inputs,
266                    is_epoch_change,
267                )
268                .unwrap()
269        } // else, in dev inspect mode and anything goes--don't check
270
271        let (inner, effects) = temporary_store.into_effects(
272            shared_object_refs,
273            &transaction_digest,
274            transaction_dependencies,
275            gas_cost_summary,
276            status,
277            &mut gas_charger,
278            *epoch_id,
279        );
280
281        (
282            inner,
283            gas_charger.into_gas_status(),
284            effects,
285            timings,
286            execution_result,
287        )
288    }
289
290    /// This function produces transaction effects for a transaction that
291    /// requires the Move authentication.
292    /// It creates a temporary store, gas charger, and transaction context for
293    /// the authentication execution and then reuses these for the normal
294    /// transaction execution.
295    /// When consensus cancelled the transaction, no authenticator runs and
296    /// the effects carry the cancellation; with the P-COOL flow on, a gas
297    /// owner that is a Move account is then not charged. Otherwise, running
298    /// the Move authentication can have two outcomes:
299    ///   - If it fails, then it charges gas for the failed execution of the authentication and
300    ///     produces transaction effects with the appropriate error status. With the P-COOL flow on,
301    ///     a gas owner that is a Move account and did not authorize the transaction is not charged;
302    ///     see `execute_without_gas_charge_to_effects`. When `gas_owner_pays` is given, it decides
303    ///     whether such a gas owner pays anyway, unless the failure is a cancellation or an
304    ///     invariant violation. A gas owner that did authorize it is charged, and every owned input
305    ///     moves to its next version.
306    ///   - Else, if the authentication is successful, it continues with the normal transaction
307    ///     execution.
308    /// Unlike a transaction cancelled at sequencing, one whose transaction
309    /// dependency did not succeed is authenticated, and its effects carry
310    /// `TransactionDependencyFailed` from the checks on its inputs, as for a
311    /// deleted input.
312    /// It combines the input objects from both the authentication and
313    /// transaction.
314    ///
315    /// The authenticators and the body are metered on `gas_status`. With
316    /// validator attestation (`enable_validator_attestation`), the
317    /// authenticators share at most `max_auth_gas` of it, as before consensus.
318    /// When they run out of it, the status is `InsufficientGas`, as when the
319    /// budget runs out, and the source of the error returned names
320    /// `max_auth_gas`.
321    #[instrument(
322        name = "tx_authenticate_then_execute_to_effects",
323        level = "debug",
324        skip_all
325    )]
326    pub fn authenticate_then_execute_transaction_to_effects<Mode: ExecutionMode>(
327        store: &dyn BackingStore,
328        // Configuration
329        protocol_config: &ProtocolConfig,
330        metrics: Arc<LimitsMetrics>,
331        enable_expensive_checks: bool,
332        certificate_deny_set: &HashSet<TransactionDigest>,
333        // Epoch
334        epoch_id: &EpochId,
335        epoch_timestamp_ms: u64,
336        // Gas related
337        gas_data: GasPayment,
338        gas_status: IotaGasStatus,
339        // Authentication
340        authenticators: MoveAuthenticatorsForExecution,
341        authenticator_and_transaction_input_objects: CheckedInputObjects,
342        gas_owner_pays: Option<&dyn Fn(&ExecutionErrorKind) -> bool>,
343        // Transaction
344        transaction_kind: TransactionKind,
345        transaction_signer: Address,
346        transaction_digest: TransactionDigest,
347        auth_context_data: AuthContextData,
348        // Tracing
349        trace_builder_opt: &mut Option<MoveTraceBuilder>,
350        // VM
351        move_vm: &Arc<MoveVM>,
352    ) -> AuthenticateThenExecuteOutput<Mode::ExecutionResults> {
353        // Preparation
354        // It involves setting up the TemporaryStore, GasCharger, and TxContext, that
355        // will be common for both the authentication and transaction execution.
356
357        // Input objects come from both authentication and transaction inputs
358        let input_objects = authenticator_and_transaction_input_objects.into_inner();
359        // Mutable inputs come only from the transaction inputs
360        let mutable_inputs = if enable_expensive_checks {
361            input_objects.mutable_inputs().keys().copied().collect()
362        } else {
363            HashSet::new()
364        };
365        // Shared object refs come from both authentication and transaction inputs
366        let shared_object_refs = input_objects.filter_shared_objects();
367        // Receiving objects can only come from the transaction inputs
368        let transaction_receiving_objects = transaction_kind.receiving_objects();
369        // Transaction dependencies come from both authentication and transaction inputs
370        let transaction_dependencies = input_objects.transaction_dependencies();
371        // Deleted and cancelled objects come from both authentication and transaction
372        // inputs
373        let contains_deleted_input = input_objects.contains_deleted_objects();
374        let mut cancelled_objects = input_objects.get_cancelled_objects();
375        let failed_dependency = input_objects.failed_transaction_dependency();
376
377        // Prepare the temporary store.
378        let mut temporary_store = TemporaryStore::new(
379            store,
380            input_objects,
381            transaction_receiving_objects,
382            transaction_digest,
383            protocol_config,
384            *epoch_id,
385        );
386
387        // Prepare the gas charger.
388        let sponsor = resolve_sponsor(&gas_data, &transaction_signer);
389        let gas_owner = gas_data.owner;
390        let gas_price = gas_status.gas_price();
391        let rgp = gas_status.reference_gas_price();
392        let mut gas_charger = GasCharger::new(
393            transaction_digest,
394            gas_data.objects,
395            gas_status,
396            protocol_config,
397        );
398
399        // Prepare the transaction context.
400        let tx_ctx = TxContext::new_from_components(
401            &transaction_signer,
402            &transaction_digest,
403            epoch_id,
404            epoch_timestamp_ms,
405            rgp,
406            gas_price,
407            gas_data.budget,
408            sponsor,
409            protocol_config,
410        );
411        let tx_ctx = Rc::new(RefCell::new(tx_ctx));
412
413        let enable_pcool = protocol_config.enable_pcool_flow();
414        let run_authenticator =
415            |temporary_store: &mut TemporaryStore<'_>,
416             gas_charger: &mut GasCharger,
417             trace_builder_opt: &mut Option<MoveTraceBuilder>,
418             authenticator: MoveAuthenticator,
419             authenticator_function_ref: AuthenticatorFunctionRef,
420             authenticator_input_objects: CheckedInputObjects| {
421                match authenticator_function_ref {
422                    AuthenticatorFunctionRef::V1(authenticator_function_ref_v1) => {
423                        authenticate_transaction_inner(
424                            temporary_store,
425                            protocol_config,
426                            metrics.clone(),
427                            gas_charger,
428                            authenticator,
429                            authenticator_function_ref_v1,
430                            &authenticator_input_objects.into_inner(),
431                            transaction_kind.clone(),
432                            transaction_digest,
433                            auth_context_data.clone(),
434                            tx_ctx.clone(),
435                            trace_builder_opt,
436                            move_vm,
437                        )
438                    }
439                }
440            };
441
442        // A cancelled transaction fails with its cancellation: its
443        // authenticators are not run, and a failure to resolve them is not
444        // reported. The cancellation is reported as is, not as an
445        // authentication failure, and only once: the transaction execution
446        // gets no cancelled objects to check. A failed transaction dependency
447        // is left to the input checks after authentication: only an
448        // authenticator that ran shows whether a Move account authorized
449        // paying for the transaction.
450        let cancellation_check = run_inputs_checks(
451            protocol_config,
452            false,
453            false,
454            cancelled_objects.take(),
455            None,
456        );
457
458        // Next to the result, whether the gas owner authorized the transaction.
459        // An owner that signed it did, as its signature is checked before
460        // consensus. A Move account did only if its authenticator ran and
461        // succeeded.
462        //
463        // Under the P-COOL flow the gas owner's authenticator runs first, and
464        // also after another account failed to resolve, so whether
465        // the gas owner authorized does not depend on the order of the
466        // signatures. When it fails, its failure is the one reported.
467        //
468        // Otherwise a resolution failure skips the authenticators entirely, so
469        // the objects holding their function references are neither recorded as
470        // loaded nor charged for.
471        let (authentication_execution_result, gas_owner_authorized) = match cancellation_check {
472            // No authenticator ran, so a gas owner that is a Move account did
473            // not authorize the transaction.
474            Err(error) => {
475                let gas_owner_authorized = match &authenticators {
476                    MoveAuthenticatorsForExecution::ResolutionFailed { accounts, .. } => {
477                        !accounts.contains(&gas_owner)
478                    }
479                    MoveAuthenticatorsForExecution::Resolved(authenticators) => !authenticators
480                        .iter()
481                        .any(|authenticator| authenticator.authenticator.address() == gas_owner),
482                };
483                (Err(error), gas_owner_authorized)
484            }
485            Ok(()) => {
486                // The authenticators share at most `max_auth_gas`, as before
487                // consensus; the rest of the budget is there again to charge
488                // for a failure or to run the body.
489                let (authentication_result, gas_owner_authorized) =
490                    with_max_auth_gas(protocol_config, &mut gas_charger, |gas_charger| {
491                        run_move_authenticators(
492                            &mut temporary_store,
493                            gas_charger,
494                            trace_builder_opt,
495                            authenticators,
496                            gas_owner,
497                            enable_pcool,
498                            run_authenticator,
499                        )
500                    });
501
502                // A resolution failure goes through the same reporting as an
503                // authenticator that fails, so a client sees `MoveAuthentication` for
504                // both.
505                (
506                    report_authentication_error(authentication_result, protocol_config),
507                    gas_owner_authorized,
508                )
509            }
510        };
511
512        // The body's own checks may replace this error in the effects, so its
513        // kind is reported alongside.
514        let authentication_error = authentication_execution_result
515            .as_ref()
516            .err()
517            .map(|error| error.kind().clone());
518
519        // Under the P-COOL flow, the gas owner's authenticator runs for the
520        // first time here, so a transaction it did not authorize can reach
521        // execution. Nobody pays for it, unless `gas_owner_pays` answers `true`.
522        let authentication_execution_result = match authentication_execution_result {
523            Err(error)
524                if !gas_owner_authorized
525                    && protocol_config.enable_pcool_flow()
526                    && !charge_gas_owner(protocol_config, &error, gas_owner_pays) =>
527            {
528                let (inner_temp_store, gas_status, effects, timings, execution_result) =
529                    execute_without_gas_charge_to_effects::<Mode>(
530                        temporary_store,
531                        gas_charger,
532                        shared_object_refs,
533                        transaction_dependencies,
534                        contains_deleted_input,
535                        cancelled_objects,
536                        failed_dependency,
537                        transaction_digest,
538                        epoch_id,
539                        protocol_config,
540                        certificate_deny_set,
541                        error,
542                    );
543
544                return (
545                    inner_temp_store,
546                    gas_status,
547                    effects,
548                    timings,
549                    execution_result,
550                    authentication_error,
551                );
552            }
553            // Also a gas owner that `gas_owner_pays` charges: it pays like any
554            // failed transaction its gas owner authorized.
555            result => result,
556        };
557        // Transaction execution.
558        // At this stage we arrive with gas charged for the execution of the
559        // authenticate function and a result which is either empty or an error.
560        // We can now start the creation of the transaction effects, either for an
561        // authentication failure or for a normal execution of the transaction.
562
563        // Run the transaction execution and return the effects.
564        let (inner_temp_store, gas_status, effects, timings, execution_result) =
565            execute_transaction_to_effects_inner::<Mode>(
566                temporary_store,
567                gas_charger,
568                tx_ctx,
569                &mutable_inputs,
570                shared_object_refs,
571                transaction_dependencies,
572                contains_deleted_input,
573                cancelled_objects,
574                failed_dependency,
575                transaction_kind,
576                transaction_signer,
577                transaction_digest,
578                move_vm,
579                epoch_id,
580                protocol_config,
581                metrics,
582                enable_expensive_checks,
583                certificate_deny_set,
584                trace_builder_opt,
585                Some(authentication_execution_result),
586            );
587        (
588            inner_temp_store,
589            gas_status,
590            effects,
591            timings,
592            execution_result,
593            authentication_error,
594        )
595    }
596
597    /// Runs the Move authenticators of a transaction bound for execution, each
598    /// through `run_authenticator`, and returns the result next to whether the
599    /// gas owner authorized the transaction. Before an authenticator runs, the
600    /// object holding its function reference is recorded as loaded in
601    /// `temporary_store`.
602    fn run_move_authenticators<'s>(
603        temporary_store: &mut TemporaryStore<'s>,
604        gas_charger: &mut GasCharger,
605        trace_builder_opt: &mut Option<MoveTraceBuilder>,
606        authenticators: MoveAuthenticatorsForExecution,
607        gas_owner: Address,
608        enable_pcool: bool,
609        run_authenticator: impl Fn(
610            &mut TemporaryStore<'s>,
611            &mut GasCharger,
612            &mut Option<MoveTraceBuilder>,
613            MoveAuthenticator,
614            AuthenticatorFunctionRef,
615            CheckedInputObjects,
616        ) -> Result<(), ExecutionError>,
617    ) -> (Result<(), ExecutionError>, bool) {
618        match authenticators {
619            MoveAuthenticatorsForExecution::ResolutionFailed {
620                error,
621                accounts,
622                gas_owner: gas_owner_authenticator,
623            } => {
624                if !accounts.contains(&gas_owner) {
625                    (Err(error), true)
626                } else {
627                    match gas_owner_authenticator
628                        .filter(|_| enable_pcool)
629                        .map(|gas_owner_authenticator| *gas_owner_authenticator)
630                    {
631                        Some(MoveAuthenticatorForExecution {
632                            authenticator,
633                            function_ref,
634                            input_objects: authenticator_input_objects,
635                        }) => {
636                            let AuthenticatorFunctionRefForExecution {
637                                authenticator_function_ref,
638                                loaded_object_id,
639                                loaded_object_metadata,
640                            } = function_ref;
641                            temporary_store.save_loaded_runtime_objects(BTreeMap::from([(
642                                loaded_object_id,
643                                loaded_object_metadata,
644                            )]));
645                            match run_authenticator(
646                                temporary_store,
647                                gas_charger,
648                                trace_builder_opt,
649                                authenticator,
650                                authenticator_function_ref,
651                                authenticator_input_objects,
652                            ) {
653                                Ok(()) => (Err(error), true),
654                                Err(gas_owner_error) => (Err(gas_owner_error), false),
655                            }
656                        }
657                        None => (Err(error), false),
658                    }
659                }
660            }
661            MoveAuthenticatorsForExecution::Resolved(authenticators) => {
662                // Prepare the authenticators for execution.
663                // Store the loaded object metadata in the `TemporaryStore` before the
664                // authenticators are executed.
665                // The temporary store must contain all the required information at this
666                // point.
667                let mut authenticators = authenticators
668                    .into_iter()
669                    .map(
670                        |MoveAuthenticatorForExecution {
671                             authenticator,
672                             function_ref,
673                             input_objects: authenticator_input_objects,
674                         }| {
675                            let AuthenticatorFunctionRefForExecution {
676                                authenticator_function_ref,
677                                loaded_object_id,
678                                loaded_object_metadata,
679                            } = function_ref;
680
681                            // Save the loaded object metadata, i.e., the field object
682                            // containing the AuthenticatorFunctionRef, in the temporary
683                            // store.
684                            temporary_store.save_loaded_runtime_objects(BTreeMap::from([(
685                                loaded_object_id,
686                                loaded_object_metadata,
687                            )]));
688
689                            (
690                                authenticator,
691                                authenticator_function_ref,
692                                authenticator_input_objects,
693                            )
694                        },
695                    )
696                    .collect::<Vec<_>>();
697
698                if enable_pcool {
699                    move_gas_owner_authenticator_first(&mut authenticators, gas_owner);
700                }
701
702                let mut gas_owner_authorized = !authenticators
703                    .iter()
704                    .any(|(authenticator, ..)| authenticator.address() == gas_owner);
705
706                // Authentication execution.
707                // It does not alter the state, if not for command execution gas charging,
708                // and produces no effects other than possible errors.
709
710                // Run each authenticator in sequence; the first failure aborts the chain.
711                let result = authenticators.into_iter().try_for_each(
712                    |(authenticator, authenticator_function_ref, authenticator_input_objects)| {
713                        let account = authenticator.address();
714                        let result = run_authenticator(
715                            temporary_store,
716                            gas_charger,
717                            trace_builder_opt,
718                            authenticator,
719                            authenticator_function_ref,
720                            authenticator_input_objects,
721                        );
722                        if result.is_ok() && account == gas_owner {
723                            gas_owner_authorized = true;
724                        }
725                        result
726                    },
727                );
728                (result, gas_owner_authorized)
729            }
730        }
731    }
732
733    /// Moves the gas owner's authenticator, when it has one, in front of the
734    /// others, which keep their order.
735    fn move_gas_owner_authenticator_first(
736        authenticators: &mut Vec<(
737            MoveAuthenticator,
738            AuthenticatorFunctionRef,
739            CheckedInputObjects,
740        )>,
741        gas_owner: Address,
742    ) {
743        if let Some(position) = authenticators
744            .iter()
745            .position(|(authenticator, ..)| authenticator.address() == gas_owner)
746        {
747            let gas_owner_authenticator = authenticators.remove(position);
748            authenticators.insert(0, gas_owner_authenticator);
749        }
750    }
751
752    /// Runs the Move authenticators through `run`. With validator attestation
753    /// (`enable_validator_attestation`) they share at most `max_auth_gas` of
754    /// the gas left; the rest is there again once `run`
755    /// returns. When they run out of `max_auth_gas`, the source of the error
756    /// names it.
757    fn with_max_auth_gas<T>(
758        protocol_config: &ProtocolConfig,
759        gas_charger: &mut GasCharger,
760        run: impl FnOnce(&mut GasCharger) -> (Result<(), ExecutionError>, T),
761    ) -> (Result<(), ExecutionError>, T) {
762        let max_auth_gas = protocol_config
763            .enable_validator_attestation()
764            .then(|| protocol_config.max_auth_gas());
765        let ((result, output), gas_limited) = gas_charger.with_gas_limit(max_auth_gas, run);
766        let result = result.map_err(|error| match max_auth_gas {
767            Some(max_auth_gas) if gas_limited => {
768                name_max_auth_gas_when_out_of_gas(error, max_auth_gas)
769            }
770            _ => error,
771        });
772        (result, output)
773    }
774
775    /// Says in the source of `error` that the Move authenticators ran out of
776    /// `max_auth_gas`, when `error` is them running out of gas while limited to
777    /// it. The status is that of running out of the gas budget, but a larger
778    /// budget does not give the authenticators more gas.
779    fn name_max_auth_gas_when_out_of_gas(
780        error: ExecutionError,
781        max_auth_gas: u64,
782    ) -> ExecutionError {
783        if !matches!(error.kind(), ExecutionErrorKind::InsufficientGas) {
784            return error;
785        }
786        let message = format!(
787            "the Move authenticators ran out of max_auth_gas ({max_auth_gas}), which a larger gas budget does not raise"
788        );
789        let message = match error.source() {
790            Some(source) => format!("{message}: {source}"),
791            None => message,
792        };
793        let out_of_max_auth_gas =
794            ExecutionError::new_with_source(ExecutionErrorKind::InsufficientGas, message);
795        match error.command() {
796            Some(command) => out_of_max_auth_gas.with_command_index(command),
797            None => out_of_max_auth_gas,
798        }
799    }
800
801    /// Whether a gas owner that is a Move account and did not authorize the
802    /// transaction pays for its failed authentication, as `gas_owner_pays`
803    /// decides under the protocol feature flag `enable_validator_attestation`.
804    /// `gas_owner_pays` is not asked about a cancellation, decided at the
805    /// consensus commit before any authenticator ran, nor about an invariant
806    /// violation, an internal error: such a gas owner is not charged.
807    fn charge_gas_owner(
808        protocol_config: &ProtocolConfig,
809        error: &ExecutionError,
810        gas_owner_pays: Option<&dyn Fn(&ExecutionErrorKind) -> bool>,
811    ) -> bool {
812        let kind = unwrap_move_authentication_error(error.kind());
813
814        protocol_config.enable_validator_attestation()
815            && !is_cancellation(kind)
816            && !is_any_invariant_violation(kind)
817            && gas_owner_pays.is_some_and(|pays| pays(kind))
818    }
819
820    /// Produces the effects of a transaction whose gas owner is a Move account
821    /// that did not authorize it: its authenticator failed, or did not run
822    /// because resolution or an earlier authenticator failed. Nobody authorized
823    /// paying for gas, so nobody is charged:
824    ///   - owned inputs, gas coins included, move to their next versions with their contents,
825    ///     owners and storage rebates unchanged;
826    ///   - mutable shared inputs move to the version consensus assigned, with their contents and
827    ///     storage rebates unchanged, so later transactions find them at the versions consensus
828    ///     gave those transactions.
829    ///
830    /// The effects name the first gas coin, at its next version, as the gas
831    /// object, with a zero gas cost; no other gas coin is merged into it.
832    ///
833    /// The checks every transaction runs on its inputs come first, as when gas
834    /// is charged, so a deleted or cancelled input, or a transaction
835    /// dependency that did not succeed, is reported the same way whoever pays.
836    fn execute_without_gas_charge_to_effects<Mode: ExecutionMode>(
837        mut temporary_store: TemporaryStore,
838        mut gas_charger: GasCharger,
839        shared_object_refs: Vec<SharedInput>,
840        mut transaction_dependencies: BTreeSet<TransactionDigest>,
841        contains_deleted_input: bool,
842        cancelled_objects: Option<(CancelledObjects, Version)>,
843        failed_dependency: Option<TransactionDigest>,
844        transaction_digest: TransactionDigest,
845        epoch_id: &EpochId,
846        protocol_config: &ProtocolConfig,
847        certificate_deny_set: &HashSet<TransactionDigest>,
848        authentication_error: ExecutionError,
849    ) -> (
850        InnerTemporaryStore,
851        IotaGasStatus,
852        TransactionEffects,
853        Vec<ExecutionTiming>,
854        Result<Mode::ExecutionResults, ExecutionError>,
855    ) {
856        let deny_cert = is_certificate_denied(&transaction_digest, certificate_deny_set);
857        let error = run_inputs_checks(
858            protocol_config,
859            deny_cert,
860            contains_deleted_input,
861            cancelled_objects,
862            failed_dependency,
863        )
864        .err()
865        .unwrap_or(authentication_error);
866        let status = elaborate_error_logs(&error, transaction_digest);
867
868        temporary_store.drop_writes();
869        temporary_store.ensure_active_inputs_mutated();
870
871        // Genesis writes a special digest to indicate that an object was created during
872        // genesis and not written by any normal transaction - remove that from the
873        // dependencies
874        transaction_dependencies.remove(&TransactionDigest::GENESIS_MARKER);
875
876        gas_charger.set_gas_coin_without_smashing();
877        let (inner, effects) = temporary_store.into_effects(
878            shared_object_refs,
879            &transaction_digest,
880            transaction_dependencies,
881            GasCostSummary::default(),
882            status,
883            &mut gas_charger,
884            *epoch_id,
885        );
886
887        (
888            inner,
889            gas_charger.into_gas_status(),
890            effects,
891            vec![],
892            Err(error),
893        )
894    }
895
896    /// This function checks the authentication of a transaction without
897    /// returning effects. It executes an authenticate function using the
898    /// information of an authenticator. If the execution fails, it returns
899    /// an execution error; otherwise it returns an empty value. The gas
900    /// status the authentication was metered on is returned alongside.
901    ///
902    /// With validator attestation (`enable_validator_attestation`) the
903    /// authenticators are metered as at execution, whatever `gas_status`
904    /// holds: they share at most `max_auth_gas`, and the gas owner's runs
905    /// first.
906    #[instrument(name = "tx_validate", level = "debug", skip_all)]
907    pub fn authenticate_transaction(
908        store: &dyn BackingStore,
909        // Configuration
910        protocol_config: &ProtocolConfig,
911        metrics: Arc<LimitsMetrics>,
912        // Epoch
913        epoch_id: &EpochId,
914        epoch_timestamp_ms: u64,
915        // Gas related
916        gas_data: GasPayment,
917        gas_status: IotaGasStatus,
918        // Authentication
919        authenticators: Vec<(
920            MoveAuthenticator,
921            AuthenticatorFunctionRef,
922            CheckedInputObjects,
923        )>,
924        aggregated_authenticator_input_objects: CheckedInputObjects,
925        // Transaction
926        transaction_kind: TransactionKind,
927        transaction_signer: Address,
928        transaction_digest: TransactionDigest,
929        auth_context_data: AuthContextData,
930        // Tracing
931        trace_builder_opt: &mut Option<MoveTraceBuilder>,
932        // VM
933        move_vm: &Arc<MoveVM>,
934    ) -> (
935        IotaGasStatus,
936        Result<<execution_mode::Authentication as ExecutionMode>::ExecutionResults, ExecutionError>,
937    ) {
938        // Prepare the gas charger for authentication execution.
939        let sponsor = resolve_sponsor(&gas_data, &transaction_signer);
940        let gas_price = gas_status.gas_price();
941        let rgp = gas_status.reference_gas_price();
942        let mut gas_charger =
943            GasCharger::new(transaction_digest, vec![], gas_status, protocol_config);
944
945        // Prepare the transaction context, equal for both authentication and
946        // transaction execution.
947        let tx_ctx = TxContext::new_from_components(
948            &transaction_signer,
949            &transaction_digest,
950            epoch_id,
951            epoch_timestamp_ms,
952            rgp,
953            gas_price,
954            gas_data.budget,
955            sponsor,
956            protocol_config,
957        );
958        let tx_ctx = Rc::new(RefCell::new(tx_ctx));
959
960        let mut temporary_store = TemporaryStore::new(
961            store,
962            aggregated_authenticator_input_objects.into_inner(),
963            vec![],
964            transaction_digest,
965            protocol_config,
966            *epoch_id,
967        );
968
969        // The authenticators share one gas limit, so what each of them finds
970        // left depends on the order they run in.
971        let mut authenticators = authenticators;
972        if protocol_config.enable_validator_attestation() {
973            move_gas_owner_authenticator_first(&mut authenticators, gas_data.owner);
974        }
975
976        // Run each authenticator in sequence; return on first failure.
977        let (authentication_execution_result, ()) =
978            with_max_auth_gas(protocol_config, &mut gas_charger, |gas_charger| {
979                let result = authenticators.into_iter().try_for_each(
980                    |(authenticator, authenticator_function_ref, authenticator_input_objects)| {
981                        match authenticator_function_ref {
982                            AuthenticatorFunctionRef::V1(authenticator_function_ref_v1) => {
983                                authenticate_transaction_inner(
984                                    &mut temporary_store,
985                                    protocol_config,
986                                    metrics.clone(),
987                                    gas_charger,
988                                    authenticator,
989                                    authenticator_function_ref_v1,
990                                    &authenticator_input_objects.into_inner(),
991                                    transaction_kind.clone(),
992                                    transaction_digest,
993                                    auth_context_data.clone(),
994                                    tx_ctx.clone(),
995                                    trace_builder_opt,
996                                    move_vm,
997                                )
998                            }
999                        }
1000                    },
1001                );
1002                (result, ())
1003            });
1004
1005        let result = report_authentication_error(authentication_execution_result, protocol_config);
1006        (gas_charger.into_gas_status(), result)
1007    }
1008
1009    // This function implements the authentication execution. It checks that the
1010    // authentication method used by the authenticator is valid. It prepares a
1011    /// `MoveAuthenticator` PTB with a single move call for execution, then
1012    /// executes it through an inner execution method. The
1013    /// `MoveAuthenticator` provides the inputs to use for the
1014    /// authentication function found in `AuthenticatorFunctionRef`,
1015    /// that is retrieved from an account.
1016    /// If the execution fails, it returns an execution error; otherwise it
1017    /// returns an empty value.
1018    #[instrument(name = "tx_validate", level = "debug", skip_all)]
1019    pub fn authenticate_transaction_inner(
1020        temporary_store: &mut TemporaryStore<'_>,
1021        // Configuration
1022        protocol_config: &ProtocolConfig,
1023        metrics: Arc<LimitsMetrics>,
1024        // Gas related
1025        gas_charger: &mut GasCharger,
1026        // Authenticator
1027        authenticator: MoveAuthenticator,
1028        authenticator_function_ref: AuthenticatorFunctionRefV1,
1029        authenticator_input_objects: &InputObjects,
1030        // Transaction
1031        transaction_kind: TransactionKind,
1032        transaction_digest: TransactionDigest,
1033        auth_context_data: AuthContextData,
1034        tx_ctx: Rc<RefCell<TxContext>>,
1035        // Tracing
1036        trace_builder_opt: &mut Option<MoveTraceBuilder>,
1037        // VM
1038        move_vm: &Arc<MoveVM>,
1039    ) -> Result<<execution_mode::Authentication as ExecutionMode>::ExecutionResults, ExecutionError>
1040    {
1041        // Check the preconditions.
1042        debug_assert!(
1043            transaction_kind.is_programmable(),
1044            "Only programmable transactions are allowed"
1045        );
1046        debug_assert!(
1047            authenticator_input_objects
1048                .mutable_inputs()
1049                .keys()
1050                .copied()
1051                .collect::<HashSet<_>>()
1052                .is_empty(),
1053            "No mutable inputs are allowed"
1054        );
1055        debug_assert!(
1056            authenticator.receiving_objects().is_empty(),
1057            "No receiving inputs are allowed"
1058        );
1059
1060        let contains_deleted_input = authenticator_input_objects.contains_deleted_objects();
1061        let cancelled_objects = authenticator_input_objects.get_cancelled_objects();
1062
1063        // Prepare the authentication context.
1064        let auth_ctx = {
1065            let TransactionKind::Programmable(ptb) = &transaction_kind else {
1066                unreachable!("Only programmable transactions are allowed");
1067            };
1068            AuthContext::new_from_components(
1069                authenticator.digest().into(),
1070                auth_context_data.sender_auth_digest,
1071                auth_context_data.sponsor_auth_digest,
1072                auth_context_data
1073                    .sender_authenticator_function_ref
1074                    .and_then(Into::into),
1075                auth_context_data
1076                    .sponsor_authenticator_function_ref
1077                    .and_then(Into::into),
1078                ptb,
1079                auth_context_data.transaction_data_bytes,
1080            )
1081        };
1082        let auth_ctx = Rc::new(RefCell::new(auth_ctx));
1083
1084        // Store the authentication context in the temporary store.
1085        // It will be added to the authentication's parameter list later, just before
1086        // execution.
1087        temporary_store.store_auth_context(auth_ctx);
1088
1089        // Execute the authentication.
1090        let authentication_execution_result = execute_authenticator_move_call(
1091            temporary_store,
1092            authenticator,
1093            authenticator_function_ref,
1094            gas_charger,
1095            tx_ctx,
1096            move_vm,
1097            protocol_config,
1098            metrics,
1099            false,
1100            contains_deleted_input,
1101            cancelled_objects,
1102            trace_builder_opt,
1103        );
1104
1105        // Check the authentication result.
1106        let authentication_execution_status = if let Err(error) = &authentication_execution_result {
1107            elaborate_error_logs(error, transaction_digest)
1108        } else {
1109            ExecutionStatus::Success
1110        };
1111
1112        #[skip_checked_arithmetic]
1113        trace!(
1114            tx_digest = ?transaction_digest,
1115            computation_gas_cost = gas_charger.summary().gas_used(),
1116            "Finished authenticator execution of transaction with status {:?}",
1117            authentication_execution_status
1118        );
1119
1120        authentication_execution_result
1121    }
1122
1123    /// Executes an authentication move call by processing the specified
1124    /// `ProgrammableTransaction`, running the main execution logic.
1125    /// Similarly to `execute_transaction`, this function handles certain error
1126    /// conditions such as denied certificate, deleted input objects failed
1127    /// consistency checks.
1128    ///
1129    /// Gas costs are managed through the `GasCharger` argument and charged only
1130    /// for authentication move function execution.
1131    ///
1132    /// Returns only the execution results.
1133    #[instrument(name = "auth_execute", level = "debug", skip_all)]
1134    fn execute_authenticator_move_call(
1135        temporary_store: &mut TemporaryStore<'_>,
1136        authenticator: MoveAuthenticator,
1137        authenticator_function_ref: AuthenticatorFunctionRefV1,
1138        gas_charger: &mut GasCharger,
1139        tx_ctx: Rc<RefCell<TxContext>>,
1140        move_vm: &Arc<MoveVM>,
1141        protocol_config: &ProtocolConfig,
1142        metrics: Arc<LimitsMetrics>,
1143        deny_cert: bool,
1144        contains_deleted_input: bool,
1145        cancelled_objects: Option<(CancelledObjects, Version)>,
1146        trace_builder_opt: &mut Option<MoveTraceBuilder>,
1147    ) -> Result<<execution_mode::Authentication as ExecutionMode>::ExecutionResults, ExecutionError>
1148    {
1149        // It must NOT charge gas for reading the Move authenticator input objects from
1150        // the storage. It will be done later during the transaction execution.
1151        // Then execute the authentication.
1152        // A failed transaction dependency is checked with the transaction's
1153        // inputs after authentication, so none is checked here.
1154        run_inputs_checks(
1155            protocol_config,
1156            deny_cert,
1157            contains_deleted_input,
1158            cancelled_objects,
1159            None,
1160        )
1161        .and_then(|()| {
1162            let authenticator_move_call =
1163                setup_authenticator_move_call(authenticator, authenticator_function_ref)?;
1164            programmable_transactions::execution::execute::<execution_mode::Authentication>(
1165                protocol_config,
1166                metrics.clone(),
1167                move_vm,
1168                temporary_store,
1169                tx_ctx,
1170                gas_charger,
1171                authenticator_move_call,
1172                trace_builder_opt,
1173            )
1174            .map_err(|(e, _)| e)
1175            .and_then(|(ok_result, _timings)| {
1176                temporary_store.check_move_authenticator_results_consistency()?;
1177                Ok(ok_result)
1178            })
1179        })
1180    }
1181
1182    /// Function dedicated to the execution of a GenesisTransaction.
1183    /// The function creates an `InnerTemporaryStore`, processes the input
1184    /// objects, and executes the transaction in unmetered mode using the
1185    /// `Genesis` execution mode. It returns an inner temporary store that
1186    /// contains the objects found into the input `GenesisTransaction` by
1187    /// adding the data for `previous_transaction` and `storage_rebate` fields.
1188    pub fn execute_genesis_state_update(
1189        store: &dyn BackingStore,
1190        protocol_config: &ProtocolConfig,
1191        metrics: Arc<LimitsMetrics>,
1192        move_vm: &Arc<MoveVM>,
1193        tx_context: Rc<RefCell<TxContext>>,
1194        input_objects: CheckedInputObjects,
1195        pt: ProgrammableTransaction,
1196    ) -> Result<InnerTemporaryStore, ExecutionError> {
1197        let input_objects = input_objects.into_inner();
1198        let tx_digest = tx_context.borrow().digest();
1199
1200        let mut temporary_store =
1201            TemporaryStore::new(store, input_objects, vec![], tx_digest, protocol_config, 0);
1202        let mut gas_charger = GasCharger::new_unmetered(tx_digest);
1203        programmable_transactions::execution::execute::<execution_mode::Genesis>(
1204            protocol_config,
1205            metrics,
1206            move_vm,
1207            &mut temporary_store,
1208            tx_context,
1209            &mut gas_charger,
1210            pt,
1211            &mut None,
1212        )
1213        .map_err(|(e, _)| e)?;
1214        temporary_store.update_object_version_and_prev_tx();
1215        Ok(temporary_store.into_inner())
1216    }
1217
1218    /// Executes a transaction by processing the specified `TransactionKind`,
1219    /// applying the necessary gas charges and running the main execution logic.
1220    /// The function handles certain error conditions such as denied
1221    /// certificate, deleted input objects, exceeded execution meter limits,
1222    /// failed conservation checks. It also accounts for unmetered storage
1223    /// rebates and adjusts for special cases like epoch change
1224    /// transactions. Gas costs are managed through the `GasCharger`
1225    /// argument; gas is also charged in case of errors.
1226    #[instrument(name = "tx_execute", level = "debug", skip_all)]
1227    fn execute_transaction<Mode: ExecutionMode>(
1228        temporary_store: &mut TemporaryStore<'_>,
1229        transaction_kind: TransactionKind,
1230        gas_charger: &mut GasCharger,
1231        tx_ctx: Rc<RefCell<TxContext>>,
1232        move_vm: &Arc<MoveVM>,
1233        protocol_config: &ProtocolConfig,
1234        metrics: Arc<LimitsMetrics>,
1235        enable_expensive_checks: bool,
1236        deny_cert: bool,
1237        contains_deleted_input: bool,
1238        cancelled_objects: Option<(CancelledObjects, Version)>,
1239        failed_dependency: Option<TransactionDigest>,
1240        trace_builder_opt: &mut Option<MoveTraceBuilder>,
1241        pre_execution_result_opt: Option<
1242            Result<
1243                <execution_mode::Authentication as ExecutionMode>::ExecutionResults,
1244                ExecutionError,
1245            >,
1246        >,
1247    ) -> (
1248        GasCostSummary,
1249        Result<Mode::ExecutionResults, ExecutionError>,
1250        Vec<ExecutionTiming>,
1251    ) {
1252        gas_charger.smash_gas(temporary_store);
1253
1254        // At this point, either no charges have been applied yet or we have
1255        // already a pre execution result to handle.
1256        debug_assert!(
1257            pre_execution_result_opt.is_some() || gas_charger.no_charges(),
1258            "No gas charges must be applied yet"
1259        );
1260
1261        let is_genesis_or_epoch_change_tx = matches!(transaction_kind, TransactionKind::Genesis(_))
1262            || transaction_kind.is_end_of_epoch();
1263
1264        let advance_epoch_gas_summary = transaction_kind.get_advance_epoch_tx_gas_summary();
1265
1266        let tx_digest = tx_ctx.borrow().digest();
1267
1268        // We must charge object read here during transaction execution, because if this
1269        // fails we must still ensure an effect is committed and all objects
1270        // versions incremented
1271        let result = gas_charger.charge_input_objects(temporary_store);
1272        let result: ResultWithTimings<Mode::ExecutionResults, ExecutionError> =
1273            result.map_err(|e| (e, vec![])).and_then(
1274                |()| -> ResultWithTimings<Mode::ExecutionResults, ExecutionError> {
1275                    run_inputs_checks(
1276                        protocol_config,
1277                        deny_cert,
1278                        contains_deleted_input,
1279                        cancelled_objects,
1280                        failed_dependency,
1281                    )
1282                    .map_err(|e| (e, vec![]))?;
1283
1284                    // If the pre-execution succeeded, proceed with the main execution loop
1285                    // else propagate the pre-execution error
1286                    let mut execution_result = pre_execution_result_opt
1287                        .unwrap_or(Ok(()))
1288                        .map_err(|e| (e, vec![]))
1289                        .and_then(|_| {
1290                            execution_loop::<Mode>(
1291                                temporary_store,
1292                                transaction_kind,
1293                                tx_ctx,
1294                                move_vm,
1295                                gas_charger,
1296                                protocol_config,
1297                                metrics.clone(),
1298                                trace_builder_opt,
1299                            )
1300                        });
1301
1302                    let meter_check = check_meter_limit(
1303                        temporary_store,
1304                        gas_charger,
1305                        protocol_config,
1306                        metrics.clone(),
1307                    );
1308                    if let Err(e) = meter_check {
1309                        execution_result = Err((e, vec![]));
1310                    }
1311
1312                    if execution_result.is_ok() {
1313                        let gas_check = check_written_objects_limit(
1314                            temporary_store,
1315                            gas_charger,
1316                            protocol_config,
1317                            metrics,
1318                        );
1319                        if let Err(e) = gas_check {
1320                            execution_result = Err((e, vec![]));
1321                        }
1322                    }
1323
1324                    execution_result
1325                },
1326            );
1327
1328        let (mut result, timings) = match result {
1329            Ok((r, t)) => (Ok(r), t),
1330            Err((e, t)) => (Err(e), t),
1331        };
1332
1333        let cost_summary = gas_charger.charge_gas(temporary_store, &mut result);
1334        // For advance epoch transaction, we need to provide epoch rewards and rebates
1335        // as extra information provided to check_iota_conserved, because we
1336        // mint rewards, and burn the rebates. We also need to pass in the
1337        // unmetered_storage_rebate because storage rebate is not reflected in
1338        // the storage_rebate of gas summary. This is a bit confusing.
1339        // We could probably clean up the code a bit.
1340        // Put all the storage rebate accumulated in the system transaction
1341        // to the 0x5 object so that it's not lost.
1342        temporary_store.conserve_unmetered_storage_rebate(gas_charger.unmetered_storage_rebate());
1343
1344        if let Err(e) = run_conservation_checks::<Mode>(
1345            temporary_store,
1346            gas_charger,
1347            tx_digest,
1348            move_vm,
1349            enable_expensive_checks,
1350            &cost_summary,
1351            is_genesis_or_epoch_change_tx,
1352            advance_epoch_gas_summary,
1353        ) {
1354            // FIXME: we cannot fail the transaction if this is an epoch change transaction.
1355            result = Err(e);
1356        }
1357
1358        (cost_summary, result, timings)
1359    }
1360
1361    /// When enabled by the protocol config, report a failure of the Move
1362    /// authentication as a distinct
1363    /// [`ExecutionErrorKind::MoveAuthentication`], dropping the
1364    /// authenticator's internal command index so it is not attributed to a
1365    /// command of the programmable transaction.
1366    fn report_authentication_error<T>(
1367        authentication_execution_result: Result<T, ExecutionError>,
1368        protocol_config: &ProtocolConfig,
1369    ) -> Result<T, ExecutionError> {
1370        if protocol_config.report_move_authentication_error() {
1371            authentication_execution_result.map_err(ExecutionError::into_move_authentication_error)
1372        } else {
1373            authentication_execution_result
1374        }
1375    }
1376
1377    /// Elaborate errors in logs if they are unexpected or their status is
1378    /// terse.
1379    fn elaborate_error_logs(
1380        execution_error: &ExecutionError,
1381        transaction_digest: TransactionDigest,
1382    ) -> ExecutionStatus {
1383        use ExecutionErrorKind as K;
1384        match execution_error.kind() {
1385            K::InvariantViolation | K::VmInvariantViolation => {
1386                #[skip_checked_arithmetic]
1387                tracing::error!(
1388                    kind = ?execution_error.kind(),
1389                    tx_digest = ?transaction_digest,
1390                    "INVARIANT VIOLATION! Source: {:?}",
1391                    execution_error.source(),
1392                );
1393            }
1394
1395            K::IotaMoveVerificationError | K::VmVerificationOrDeserializationError => {
1396                #[skip_checked_arithmetic]
1397                tracing::debug!(
1398                    kind = ?execution_error.kind(),
1399                    tx_digest = ?transaction_digest,
1400                    "Verification Error. Source: {:?}",
1401                    execution_error.source(),
1402                );
1403            }
1404
1405            K::PublishUpgradeMissingDependency | K::PublishUpgradeDependencyDowngrade => {
1406                #[skip_checked_arithmetic]
1407                tracing::debug!(
1408                    kind = ?execution_error.kind(),
1409                    tx_digest = ?transaction_digest,
1410                    "Publish/Upgrade Error. Source: {:?}",
1411                    execution_error.source(),
1412                )
1413            }
1414
1415            _ => (),
1416        };
1417
1418        let (status, command) = execution_error.to_execution_status();
1419        ExecutionStatus::new_failure(status, command)
1420    }
1421
1422    /// Performs IOTA conservation checks during transaction execution, ensuring
1423    /// that the transaction does not create or destroy IOTA. If
1424    /// conservation is violated, the function attempts to recover
1425    /// by resetting the gas charger, recharging gas, and rechecking
1426    /// conservation. If recovery fails, it panics to avoid IOTA creation or
1427    /// destruction. These checks include both simple and expensive
1428    /// checks based on the configuration and are skipped for genesis or epoch
1429    /// change transactions.
1430    #[instrument(name = "run_conservation_checks", level = "debug", skip_all)]
1431    fn run_conservation_checks<Mode: ExecutionMode>(
1432        temporary_store: &mut TemporaryStore<'_>,
1433        gas_charger: &mut GasCharger,
1434        tx_digest: TransactionDigest,
1435        move_vm: &Arc<MoveVM>,
1436        enable_expensive_checks: bool,
1437        cost_summary: &GasCostSummary,
1438        is_genesis_or_epoch_change_tx: bool,
1439        advance_epoch_gas_summary: Option<(u64, u64)>,
1440    ) -> Result<(), ExecutionError> {
1441        let mut result: std::result::Result<(), iota_types::error::ExecutionError> = Ok(());
1442        if !is_genesis_or_epoch_change_tx && !Mode::skip_conservation_checks() {
1443            // ensure that this transaction did not create or destroy IOTA, try to recover
1444            // if the check fails
1445            let conservation_result = {
1446                temporary_store
1447                    .check_iota_conserved(cost_summary)
1448                    .and_then(|()| {
1449                        if enable_expensive_checks {
1450                            // ensure that this transaction did not create or destroy IOTA, try to
1451                            // recover if the check fails
1452                            let mut layout_resolver =
1453                                TypeLayoutResolver::new(move_vm, Box::new(&*temporary_store));
1454                            temporary_store.check_iota_conserved_expensive(
1455                                cost_summary,
1456                                advance_epoch_gas_summary,
1457                                &mut layout_resolver,
1458                            )
1459                        } else {
1460                            Ok(())
1461                        }
1462                    })
1463            };
1464            if let Err(conservation_err) = conservation_result {
1465                // conservation violated. try to avoid panic by dumping all writes, charging for
1466                // gas, re-checking conservation, and surfacing an aborted
1467                // transaction with an invariant violation if all of that works
1468                result = Err(conservation_err);
1469                gas_charger.reset(temporary_store);
1470                gas_charger.charge_gas(temporary_store, &mut result);
1471                // check conservation once more
1472                if let Err(recovery_err) = temporary_store
1473                    .check_iota_conserved(cost_summary)
1474                    .and_then(|()| {
1475                        if enable_expensive_checks {
1476                            // ensure that this transaction did not create or destroy IOTA, try
1477                            // to recover if the check fails
1478                            let mut layout_resolver =
1479                                TypeLayoutResolver::new(move_vm, Box::new(&*temporary_store));
1480                            temporary_store.check_iota_conserved_expensive(
1481                                cost_summary,
1482                                advance_epoch_gas_summary,
1483                                &mut layout_resolver,
1484                            )
1485                        } else {
1486                            Ok(())
1487                        }
1488                    })
1489                {
1490                    // if we still fail, it's a problem with gas
1491                    // charging that happens even in the "aborted" case--no other option but panic.
1492                    // we will create or destroy IOTA otherwise
1493                    panic!(
1494                        "IOTA conservation fail in tx block {}: {}\nGas status is {}\nTx was ",
1495                        tx_digest,
1496                        recovery_err,
1497                        gas_charger.summary()
1498                    )
1499                }
1500            }
1501        } // else, we're in the genesis transaction which mints the IOTA supply, and hence
1502        // does not satisfy IOTA conservation, or we're in the non-production
1503        // dev inspect mode which allows us to violate conservation
1504        result
1505    }
1506
1507    /// Runs checks on the input objects of a transaction to ensure that they
1508    /// meet the necessary conditions for execution.
1509    ///
1510    /// It checks for denied certificates, deleted input objects, and cancelled
1511    /// objects due to congestion or randomness unavailability. If any of
1512    /// these conditions are met, it returns an appropriate
1513    /// `ExecutionError`.
1514    ///
1515    /// If all checks pass, it returns `Ok(())`, indicating that the transaction
1516    /// can proceed with execution.
1517    #[instrument(name = "run_inputs_checks", level = "debug", skip_all)]
1518    fn run_inputs_checks(
1519        protocol_config: &ProtocolConfig,
1520        deny_cert: bool,
1521        contains_deleted_input: bool,
1522        cancelled_objects: Option<(CancelledObjects, Version)>,
1523        failed_dependency: Option<TransactionDigest>,
1524    ) -> Result<(), ExecutionError> {
1525        if deny_cert {
1526            Err(ExecutionError::new(
1527                ExecutionErrorKind::CertificateDenied,
1528                None,
1529            ))
1530        } else if contains_deleted_input {
1531            Err(ExecutionError::new(
1532                ExecutionErrorKind::InputObjectDeleted,
1533                None,
1534            ))
1535        } else if let Some((cancelled_objects, reason)) = cancelled_objects {
1536            match reason {
1537                version if version.is_congested() => Err(ExecutionError::new(
1538                    match cancelled_objects {
1539                        // A transaction cancelled through its gas object has no shared
1540                        // inputs, so the execution workers are the congested resource
1541                        // and no individual object is responsible.
1542                        CancelledObjects::GasObject => {
1543                            ExecutionErrorKind::ExecutionCanceledDueToExecutionWorkerCongestion {
1544                                suggested_gas_price: version
1545                                    .get_congested_version_suggested_gas_price()
1546                                    .expect(
1547                                        "execution-worker congestion control requires the gas \
1548                                        price feedback mechanism",
1549                                    ),
1550                            }
1551                        }
1552                        CancelledObjects::SharedObjects(congested_objects) => {
1553                            if protocol_config.congestion_control_gas_price_feedback_mechanism() {
1554                                ExecutionErrorKind::ExecutionCanceledDueToSharedObjectCongestionV2 {
1555                                    congested_objects,
1556                                    suggested_gas_price: version
1557                                        .get_congested_version_suggested_gas_price()
1558                                        .unwrap(),
1559                                }
1560                            } else {
1561                                // WARN: do not remove this `else` branch even after
1562                                // `congestion_control_gas_price_feedback_mechanism` is enabled
1563                                // on the mainnet. It must be kept to be able to replay old
1564                                // transaction data.
1565                                ExecutionErrorKind::ExecutionCanceledDueToSharedObjectCongestion {
1566                                    congested_objects,
1567                                }
1568                            }
1569                        }
1570                    },
1571                    None,
1572                )),
1573                Version::RANDOMNESS_UNAVAILABLE => Err(ExecutionError::new(
1574                    ExecutionErrorKind::ExecutionCanceledDueToRandomnessUnavailable,
1575                    None,
1576                )),
1577                _ => panic!("invalid cancellation reason Version: {reason}"),
1578            }
1579        } else if let Some(dependency) = failed_dependency {
1580            Err(ExecutionError::new(
1581                ExecutionErrorKind::TransactionDependencyFailed { dependency },
1582                None,
1583            ))
1584        } else {
1585            Ok(())
1586        }
1587    }
1588
1589    /// Checks if the estimated size of transaction effects exceeds predefined
1590    /// limits based on the protocol configuration. For metered
1591    /// transactions, it enforces hard limits, while for system transactions, it
1592    /// allows soft limits with warnings.
1593    #[instrument(name = "check_meter_limit", level = "debug", skip_all)]
1594    fn check_meter_limit(
1595        temporary_store: &mut TemporaryStore<'_>,
1596        gas_charger: &mut GasCharger,
1597        protocol_config: &ProtocolConfig,
1598        metrics: Arc<LimitsMetrics>,
1599    ) -> Result<(), ExecutionError> {
1600        let effects_estimated_size = temporary_store.estimate_effects_size_upperbound();
1601
1602        // Check if a limit threshold was crossed.
1603        // For metered transactions, there is not soft limit.
1604        // For system transactions, we allow a soft limit with alerting, and a hard
1605        // limit where we terminate
1606        match check_limit_by_meter!(
1607            !gas_charger.is_unmetered(),
1608            effects_estimated_size,
1609            protocol_config.max_serialized_tx_effects_size_bytes(),
1610            protocol_config.max_serialized_tx_effects_size_bytes_system_tx(),
1611            metrics.excessive_estimated_effects_size
1612        ) {
1613            LimitThresholdCrossed::None => Ok(()),
1614            LimitThresholdCrossed::Soft(_, limit) => {
1615                warn!(
1616                    effects_estimated_size = effects_estimated_size,
1617                    soft_limit = limit,
1618                    "Estimated transaction effects size crossed soft limit",
1619                );
1620                Ok(())
1621            }
1622            LimitThresholdCrossed::Hard(_, lim) => Err(ExecutionError::new_with_source(
1623                ExecutionErrorKind::EffectsTooLarge {
1624                    current_size: effects_estimated_size as u64,
1625                    max_size: lim as u64,
1626                },
1627                "Transaction effects are too large",
1628            )),
1629        }
1630    }
1631
1632    /// Checks if the total size of written objects in the transaction exceeds
1633    /// the limits defined in the protocol configuration. For metered
1634    /// transactions, it enforces a hard limit, while for system transactions,
1635    /// it allows a soft limit with warnings.
1636    #[instrument(name = "check_written_objects_limit", level = "debug", skip_all)]
1637    fn check_written_objects_limit(
1638        temporary_store: &mut TemporaryStore<'_>,
1639        gas_charger: &mut GasCharger,
1640        protocol_config: &ProtocolConfig,
1641        metrics: Arc<LimitsMetrics>,
1642    ) -> Result<(), ExecutionError> {
1643        if let (Some(normal_lim), Some(system_lim)) = (
1644            protocol_config.max_size_written_objects_as_option(),
1645            protocol_config.max_size_written_objects_system_tx_as_option(),
1646        ) {
1647            let written_objects_size = temporary_store.written_objects_size();
1648
1649            match check_limit_by_meter!(
1650                !gas_charger.is_unmetered(),
1651                written_objects_size,
1652                normal_lim,
1653                system_lim,
1654                metrics.excessive_written_objects_size
1655            ) {
1656                LimitThresholdCrossed::None => (),
1657                LimitThresholdCrossed::Soft(_, limit) => {
1658                    warn!(
1659                        written_objects_size = written_objects_size,
1660                        soft_limit = limit,
1661                        "Written objects size crossed soft limit",
1662                    )
1663                }
1664                LimitThresholdCrossed::Hard(_, lim) => {
1665                    return Err(ExecutionError::new_with_source(
1666                        ExecutionErrorKind::WrittenObjectsTooLarge {
1667                            object_size: written_objects_size as u64,
1668                            max_object_size: lim as u64,
1669                        },
1670                        "Written objects size crossed hard limit",
1671                    ));
1672                }
1673            };
1674        }
1675
1676        Ok(())
1677    }
1678
1679    /// Executes the given transaction based on its `TransactionKind` by
1680    /// processing it through corresponding handlers such as epoch changes,
1681    /// genesis transactions, consensus commit prologues, and programmable
1682    /// transactions. For each type of transaction, the corresponding logic is
1683    /// invoked, such as advancing the epoch, setting up consensus commits, or
1684    /// executing a programmable transaction.
1685    #[instrument(level = "debug", skip_all)]
1686    fn execution_loop<Mode: ExecutionMode>(
1687        temporary_store: &mut TemporaryStore<'_>,
1688        transaction_kind: TransactionKind,
1689        tx_ctx: Rc<RefCell<TxContext>>,
1690        move_vm: &Arc<MoveVM>,
1691        gas_charger: &mut GasCharger,
1692        protocol_config: &ProtocolConfig,
1693        metrics: Arc<LimitsMetrics>,
1694        trace_builder_opt: &mut Option<MoveTraceBuilder>,
1695    ) -> ResultWithTimings<Mode::ExecutionResults, ExecutionError> {
1696        let result = match transaction_kind {
1697            TransactionKind::Genesis(GenesisTransaction { objects, events }) => {
1698                if tx_ctx.borrow().epoch() != 0 {
1699                    panic!("BUG: Genesis Transactions can only be executed in epoch 0");
1700                }
1701
1702                for genesis_object in objects {
1703                    let object = ObjectInner {
1704                        data: genesis_object.data,
1705                        owner: genesis_object.owner,
1706                        previous_transaction: tx_ctx.borrow().digest(),
1707                        storage_rebate: 0,
1708                    };
1709                    temporary_store.create_object(object.into());
1710                }
1711
1712                temporary_store.record_execution_results(ExecutionResults::V1(
1713                    ExecutionResultsV1 {
1714                        user_events: events,
1715                        ..Default::default()
1716                    },
1717                ));
1718
1719                Ok((Mode::empty_results(), vec![]))
1720            }
1721            TransactionKind::ConsensusCommitPrologueV1(prologue) => {
1722                setup_consensus_commit(
1723                    prologue.commit_timestamp_ms,
1724                    temporary_store,
1725                    tx_ctx,
1726                    move_vm,
1727                    gas_charger,
1728                    protocol_config,
1729                    metrics,
1730                    trace_builder_opt,
1731                )
1732                .expect("ConsensusCommitPrologueV1 cannot fail");
1733                Ok((Mode::empty_results(), vec![]))
1734            }
1735            TransactionKind::Programmable(pt) => {
1736                programmable_transactions::execution::execute::<Mode>(
1737                    protocol_config,
1738                    metrics,
1739                    move_vm,
1740                    temporary_store,
1741                    tx_ctx,
1742                    gas_charger,
1743                    pt,
1744                    trace_builder_opt,
1745                )
1746            }
1747            TransactionKind::EndOfEpoch(txns) => {
1748                // Non-change-epoch kinds accumulate commands into the builder;
1749                // the change-epoch kind is always last and executes the built
1750                // transaction as part of advancing the epoch.
1751                let mut builder = ProgrammableTransactionBuilder::new();
1752                let len = txns.len();
1753
1754                for (i, tx) in txns.into_iter().enumerate() {
1755                    match tx {
1756                        EndOfEpochTransactionKind::ChangeEpoch(change_epoch) => {
1757                            assert_eq!(i, len - 1);
1758                            advance_epoch_v1(
1759                                builder,
1760                                change_epoch,
1761                                temporary_store,
1762                                tx_ctx,
1763                                move_vm,
1764                                gas_charger,
1765                                protocol_config,
1766                                metrics,
1767                                trace_builder_opt,
1768                            )
1769                            .map_err(|e| (e, vec![]))?;
1770                            return Ok((Mode::empty_results(), vec![]));
1771                        }
1772                        EndOfEpochTransactionKind::ChangeEpochV2(change_epoch_v2) => {
1773                            assert_eq!(i, len - 1);
1774                            advance_epoch_v2(
1775                                builder,
1776                                change_epoch_v2,
1777                                temporary_store,
1778                                tx_ctx,
1779                                move_vm,
1780                                gas_charger,
1781                                protocol_config,
1782                                metrics,
1783                                trace_builder_opt,
1784                            )
1785                            .map_err(|e| (e, vec![]))?;
1786                            return Ok((Mode::empty_results(), vec![]));
1787                        }
1788                        EndOfEpochTransactionKind::ChangeEpochV3(change_epoch_v3) => {
1789                            assert_eq!(i, len - 1);
1790                            advance_epoch_v3(
1791                                builder,
1792                                change_epoch_v3,
1793                                temporary_store,
1794                                tx_ctx,
1795                                move_vm,
1796                                gas_charger,
1797                                protocol_config,
1798                                metrics,
1799                                trace_builder_opt,
1800                            )
1801                            .map_err(|e| (e, vec![]))?;
1802                            return Ok((Mode::empty_results(), vec![]));
1803                        }
1804                        EndOfEpochTransactionKind::ChangeEpochV4(change_epoch_v4) => {
1805                            assert_eq!(i, len - 1);
1806                            advance_epoch_v4(
1807                                builder,
1808                                change_epoch_v4,
1809                                temporary_store,
1810                                tx_ctx,
1811                                move_vm,
1812                                gas_charger,
1813                                protocol_config,
1814                                metrics,
1815                                trace_builder_opt,
1816                            )
1817                            .map_err(|e| (e, vec![]))?;
1818                            return Ok((Mode::empty_results(), vec![]));
1819                        }
1820                        EndOfEpochTransactionKind::TransactionDenyRulesCreate => {
1821                            assert!(
1822                                protocol_config.enable_pcool_flow(),
1823                                "unexpected TransactionDenyRulesCreate: on-chain deny rule governance is not enabled"
1824                            );
1825                            builder = setup_transaction_deny_rules_create(builder)
1826                                .map_err(|e| (e, vec![]))?;
1827                        }
1828                        _ => unimplemented!(
1829                            "a new EndOfEpochTransactionKind enum variant was added and needs to be handled"
1830                        ),
1831                    }
1832                }
1833                unreachable!(
1834                    "EndOfEpochTransactionKind::ChangeEpoch should be the last transaction in the list"
1835                )
1836            }
1837            #[allow(deprecated)]
1838            TransactionKind::AuthenticatorStateUpdateV1Deprecated => {
1839                // Deprecated: Authenticator state (JWK) is deprecated and
1840                // was never enabled. These transaction kinds are retained
1841                // only for BCS enum variant compatibility.
1842                return Err((
1843                    ExecutionError::new(
1844                        ExecutionErrorKind::VmInvariantViolation,
1845                        Some("AuthenticatorState transactions are deprecated and were never created on IOTA".into()),
1846                    ),
1847                    vec![],
1848                ));
1849            }
1850            TransactionKind::RandomnessStateUpdate(randomness_state_update) => {
1851                setup_randomness_state_update(
1852                    randomness_state_update,
1853                    temporary_store,
1854                    tx_ctx,
1855                    move_vm,
1856                    gas_charger,
1857                    protocol_config,
1858                    metrics,
1859                    trace_builder_opt,
1860                )
1861                .map_err(|e| (e, vec![]))?;
1862                Ok((Mode::empty_results(), vec![]))
1863            }
1864            TransactionKind::TransactionDenyRulesUpdate(update) => {
1865                assert!(
1866                    protocol_config.enable_pcool_flow(),
1867                    "unexpected TransactionDenyRulesUpdate: on-chain deny rule governance is not enabled"
1868                );
1869                setup_transaction_deny_rules_update(
1870                    update,
1871                    temporary_store,
1872                    tx_ctx,
1873                    move_vm,
1874                    gas_charger,
1875                    protocol_config,
1876                    metrics,
1877                    trace_builder_opt,
1878                )
1879                .map_err(|e| (e, vec![]))?;
1880                Ok((Mode::empty_results(), vec![]))
1881            }
1882            _ => unimplemented!(
1883                "a new TransactionKind enum variant was added and needs to be handled"
1884            ),
1885        }?;
1886        temporary_store
1887            .check_execution_results_consistency()
1888            .map_err(|e| (e, vec![]))?;
1889        Ok(result)
1890    }
1891
1892    /// Mints epoch rewards by creating both storage and computation charges
1893    /// using a `ProgrammableTransactionBuilder`. The function takes in the
1894    /// `AdvanceEpochParams`, serializes the storage and computation
1895    /// charges, and invokes the reward creation function within the IOTA
1896    /// Prepares invocations for creating both storage and computation charges
1897    /// with a `ProgrammableTransactionBuilder` using the `AdvanceEpochParams`.
1898    /// The corresponding functions from the IOTA framework can be invoked later
1899    /// during execution of the programmable transaction.
1900    fn mint_epoch_rewards_in_pt(
1901        builder: &mut ProgrammableTransactionBuilder,
1902        params: &AdvanceEpochParams,
1903    ) -> (Argument, Argument) {
1904        // Create storage charges.
1905        let storage_charge_arg = builder
1906            .input(CallArg::pure(&params.storage_charge))
1907            .unwrap();
1908        let storage_charges = builder.programmable_move_call(
1909            ObjectId::FRAMEWORK,
1910            Identifier::BALANCE_MODULE,
1911            BALANCE_CREATE_REWARDS_FUNCTION_NAME,
1912            vec![TypeTag::from(StructTag::new_gas())],
1913            vec![storage_charge_arg],
1914        );
1915
1916        // Create computation charges.
1917        let computation_charge_arg = builder
1918            .input(CallArg::pure(&params.computation_charge))
1919            .unwrap();
1920        let computation_charges = builder.programmable_move_call(
1921            ObjectId::FRAMEWORK,
1922            Identifier::BALANCE_MODULE,
1923            BALANCE_CREATE_REWARDS_FUNCTION_NAME,
1924            vec![TypeTag::from(StructTag::new_gas())],
1925            vec![computation_charge_arg],
1926        );
1927        (storage_charges, computation_charges)
1928    }
1929
1930    /// Constructs a `ProgrammableTransaction` to advance the epoch. It creates
1931    /// storage charges and computation charges by invoking
1932    /// `mint_epoch_rewards_in_pt`, advances the epoch by setting up the
1933    /// necessary arguments, such as epoch number, protocol version, storage
1934    /// rebate, and slashing rate, and executing the `advance_epoch` function
1935    /// within the IOTA system. Then, it destroys the storage rebates to
1936    /// complete the transaction.
1937    pub fn construct_advance_epoch_pt_impl(
1938        mut builder: ProgrammableTransactionBuilder,
1939        params: &AdvanceEpochParams,
1940        call_arg_vec: Vec<CallArg>,
1941    ) -> Result<ProgrammableTransaction, ExecutionError> {
1942        // Create storage and computation charges and add them as arguments.
1943        let (storage_charges, computation_charges) = mint_epoch_rewards_in_pt(&mut builder, params);
1944        let mut arguments = vec![
1945            builder
1946                .pure(params.validator_subsidy)
1947                .expect("bcs encoding a u64 should not fail"),
1948            storage_charges,
1949            computation_charges,
1950        ];
1951
1952        let call_arg_arguments = call_arg_vec
1953            .into_iter()
1954            .map(|a| builder.input(a))
1955            .collect::<Result<_, _>>();
1956
1957        assert_invariant!(
1958            call_arg_arguments.is_ok(),
1959            "Unable to generate args for advance_epoch transaction!"
1960        );
1961
1962        arguments.append(&mut call_arg_arguments.unwrap());
1963
1964        info!("Call arguments to advance_epoch transaction: {:?}", params);
1965
1966        let storage_rebates = builder.programmable_move_call(
1967            ObjectId::SYSTEM,
1968            Identifier::IOTA_SYSTEM_MODULE,
1969            ADVANCE_EPOCH_FUNCTION_NAME,
1970            vec![],
1971            arguments,
1972        );
1973
1974        // Step 3: Destroy the storage rebates.
1975        builder.programmable_move_call(
1976            ObjectId::FRAMEWORK,
1977            Identifier::BALANCE_MODULE,
1978            BALANCE_DESTROY_REBATES_FUNCTION_NAME,
1979            vec![TypeTag::from(StructTag::new_gas())],
1980            vec![storage_rebates],
1981        );
1982        Ok(builder.finish())
1983    }
1984
1985    pub fn construct_advance_epoch_pt_v1(
1986        builder: ProgrammableTransactionBuilder,
1987        params: &AdvanceEpochParams,
1988    ) -> Result<ProgrammableTransaction, ExecutionError> {
1989        // the first three arguments to the advance_epoch function, namely
1990        // validator_subsidy, storage_charges and computation_charges, are
1991        // common to both v1 and v2 and are added in `construct_advance_epoch_pt_impl`.
1992        // The remaining arguments are added here.
1993        let call_arg_vec = vec![
1994            CallArg::IOTA_SYSTEM_MUTABLE, // wrapper: &mut IotaSystemState
1995            CallArg::pure(&params.epoch), // new_epoch: u64
1996            CallArg::pure(&params.next_protocol_version.as_u64()), // next_protocol_version: u64
1997            CallArg::pure(&params.storage_rebate), // storage_rebate: u64
1998            CallArg::pure(&params.non_refundable_storage_fee), // non_refundable_storage_fee: u64
1999            CallArg::pure(&params.reward_slashing_rate), // reward_slashing_rate: u64
2000            CallArg::pure(&params.epoch_start_timestamp_ms), // epoch_start_timestamp_ms: u64
2001        ];
2002        construct_advance_epoch_pt_impl(builder, params, call_arg_vec)
2003    }
2004
2005    pub fn construct_advance_epoch_pt_v2(
2006        builder: ProgrammableTransactionBuilder,
2007        params: &AdvanceEpochParams,
2008    ) -> Result<ProgrammableTransaction, ExecutionError> {
2009        // the first three arguments to the advance_epoch function, namely
2010        // validator_subsidy, storage_charges and computation_charges, are
2011        // common to both v1 and v2 and are added in `construct_advance_epoch_pt_impl`.
2012        // The remaining arguments are added here.
2013        let call_arg_vec = vec![
2014            CallArg::pure(&params.computation_charge_burned), // computation_charge_burned: u64
2015            CallArg::IOTA_SYSTEM_MUTABLE,                     // wrapper: &mut IotaSystemState
2016            CallArg::pure(&params.epoch),                     // new_epoch: u64
2017            CallArg::pure(&params.next_protocol_version.as_u64()), // next_protocol_version: u64
2018            CallArg::pure(&params.storage_rebate),            // storage_rebate: u64
2019            CallArg::pure(&params.non_refundable_storage_fee), // non_refundable_storage_fee: u64
2020            CallArg::pure(&params.reward_slashing_rate),      // reward_slashing_rate: u64
2021            CallArg::pure(&params.epoch_start_timestamp_ms),  // epoch_start_timestamp_ms: u64
2022            CallArg::pure(&params.max_committee_members_count), // max_committee_members_count: u64
2023        ];
2024        construct_advance_epoch_pt_impl(builder, params, call_arg_vec)
2025    }
2026
2027    pub fn construct_advance_epoch_pt_v3(
2028        builder: ProgrammableTransactionBuilder,
2029        params: &AdvanceEpochParams,
2030    ) -> Result<ProgrammableTransaction, ExecutionError> {
2031        // the first three arguments to the advance_epoch function, namely
2032        // validator_subsidy, storage_charges and computation_charges, are
2033        // common to both v1, v2 and v3 and are added in
2034        // `construct_advance_epoch_pt_impl`. The remaining arguments are added
2035        // here.
2036        let call_arg_vec = vec![
2037            CallArg::pure(&params.computation_charge_burned), // computation_charge_burned: u64
2038            CallArg::IOTA_SYSTEM_MUTABLE,                     // wrapper: &mut IotaSystemState
2039            CallArg::pure(&params.epoch),                     // new_epoch: u64
2040            CallArg::pure(&params.next_protocol_version.as_u64()), // next_protocol_version: u64
2041            CallArg::pure(&params.storage_rebate),            // storage_rebate: u64
2042            CallArg::pure(&params.non_refundable_storage_fee), // non_refundable_storage_fee: u64
2043            CallArg::pure(&params.reward_slashing_rate),      // reward_slashing_rate: u64
2044            CallArg::pure(&params.epoch_start_timestamp_ms),  // epoch_start_timestamp_ms: u64
2045            CallArg::pure(&params.max_committee_members_count), // max_committee_members_count: u64
2046            CallArg::pure(&params.eligible_active_validators), /* eligible_active_validators:
2047                                                               * Vec<u64> */
2048        ];
2049        construct_advance_epoch_pt_impl(builder, params, call_arg_vec)
2050    }
2051
2052    pub fn construct_advance_epoch_pt_v4(
2053        builder: ProgrammableTransactionBuilder,
2054        params: &AdvanceEpochParams,
2055    ) -> Result<ProgrammableTransaction, ExecutionError> {
2056        // the first three arguments to the advance_epoch function, namely
2057        // validator_subsidy, storage_charges and computation_charges, are
2058        // common to both v1, v2, v3 and v4 and are added in
2059        // `construct_advance_epoch_pt_impl`. The remaining arguments are added
2060        // here.
2061        let call_arg_vec = vec![
2062            CallArg::pure(&params.computation_charge_burned), // computation_charge_burned: u64
2063            CallArg::IOTA_SYSTEM_MUTABLE,                     // wrapper: &mut IotaSystemState
2064            CallArg::pure(&params.epoch),                     // new_epoch: u64
2065            CallArg::pure(&params.next_protocol_version.as_u64()), // next_protocol_version: u64
2066            CallArg::pure(&params.storage_rebate),            // storage_rebate: u64
2067            CallArg::pure(&params.non_refundable_storage_fee), // non_refundable_storage_fee: u64
2068            CallArg::pure(&params.reward_slashing_rate),      // reward_slashing_rate: u64
2069            CallArg::pure(&params.epoch_start_timestamp_ms),  // epoch_start_timestamp_ms: u64
2070            CallArg::pure(&params.max_committee_members_count), // max_committee_members_count: u64
2071            CallArg::pure(&params.eligible_active_validators), /* eligible_active_validators:
2072                                                               * Vec<u64> */
2073            CallArg::pure(&params.scores), // scores: Vec<u64>
2074            CallArg::pure(&params.adjust_rewards_by_score), // adjust_rewards_by_score: bool
2075        ];
2076        construct_advance_epoch_pt_impl(builder, params, call_arg_vec)
2077    }
2078
2079    /// Advances the epoch by executing a `ProgrammableTransaction`. If the
2080    /// transaction fails, it switches to safe mode and retries the epoch
2081    /// advancement in a more controlled environment. The function also
2082    /// handles the publication and upgrade of system packages for the new
2083    /// epoch. If any system package is added or upgraded, it ensures the
2084    /// proper execution and storage of the changes.
2085    fn advance_epoch_impl(
2086        advance_epoch_pt: ProgrammableTransaction,
2087        params: AdvanceEpochParams,
2088        system_packages: Vec<SystemPackage>,
2089        temporary_store: &mut TemporaryStore<'_>,
2090        tx_ctx: Rc<RefCell<TxContext>>,
2091        move_vm: &Arc<MoveVM>,
2092        gas_charger: &mut GasCharger,
2093        protocol_config: &ProtocolConfig,
2094        metrics: Arc<LimitsMetrics>,
2095        trace_builder_opt: &mut Option<MoveTraceBuilder>,
2096    ) -> Result<(), ExecutionError> {
2097        let result = programmable_transactions::execution::execute::<execution_mode::System>(
2098            protocol_config,
2099            metrics.clone(),
2100            move_vm,
2101            temporary_store,
2102            tx_ctx.clone(),
2103            gas_charger,
2104            advance_epoch_pt,
2105            trace_builder_opt,
2106        );
2107
2108        #[cfg(msim)]
2109        let result = maybe_modify_result(result, params.epoch);
2110
2111        if let Err(err) = &result {
2112            tracing::error!(
2113                "Failed to execute advance epoch transaction. Switching to safe mode. Error: {:?}. Input objects: {:?}. Tx params: {:?}",
2114                err.0,
2115                temporary_store.objects(),
2116                params,
2117            );
2118            temporary_store.drop_writes();
2119            // Must reset the storage rebate since we are re-executing.
2120            gas_charger.reset_storage_cost_and_rebate();
2121
2122            temporary_store.advance_epoch_safe_mode(&params, protocol_config);
2123        }
2124
2125        let new_vm = new_move_vm(
2126            all_natives(/* silent */ true, protocol_config),
2127            protocol_config,
2128            // enable_profiler
2129            None,
2130        )
2131        .expect("Failed to create new MoveVM");
2132        process_system_packages(
2133            system_packages,
2134            temporary_store,
2135            tx_ctx,
2136            &new_vm,
2137            gas_charger,
2138            protocol_config,
2139            metrics,
2140            trace_builder_opt,
2141        );
2142
2143        Ok(())
2144    }
2145
2146    /// Advances the epoch for the given `ChangeEpoch` transaction kind by
2147    /// constructing a programmable transaction, executing it and processing the
2148    /// system packages.
2149    fn advance_epoch_v1(
2150        builder: ProgrammableTransactionBuilder,
2151        change_epoch: ChangeEpoch,
2152        temporary_store: &mut TemporaryStore<'_>,
2153        tx_ctx: Rc<RefCell<TxContext>>,
2154        move_vm: &Arc<MoveVM>,
2155        gas_charger: &mut GasCharger,
2156        protocol_config: &ProtocolConfig,
2157        metrics: Arc<LimitsMetrics>,
2158        trace_builder_opt: &mut Option<MoveTraceBuilder>,
2159    ) -> Result<(), ExecutionError> {
2160        let params = AdvanceEpochParams {
2161            epoch: change_epoch.epoch,
2162            next_protocol_version: change_epoch.protocol_version.into(),
2163            validator_subsidy: protocol_config.validator_target_reward(),
2164            storage_charge: change_epoch.storage_charge,
2165            computation_charge: change_epoch.computation_charge,
2166            // all computation charge is burned in v1
2167            computation_charge_burned: change_epoch.computation_charge,
2168            storage_rebate: change_epoch.storage_rebate,
2169            non_refundable_storage_fee: change_epoch.non_refundable_storage_fee,
2170            reward_slashing_rate: protocol_config.reward_slashing_rate(),
2171            epoch_start_timestamp_ms: change_epoch.epoch_start_timestamp_ms,
2172            // AdvanceEpochV1 does not use those fields, but keeping them to avoid creating a
2173            // separate AdvanceEpochParams struct.
2174            max_committee_members_count: 0,
2175            eligible_active_validators: vec![],
2176            scores: vec![],
2177            adjust_rewards_by_score: false,
2178        };
2179        let advance_epoch_pt = construct_advance_epoch_pt_v1(builder, &params)?;
2180        advance_epoch_impl(
2181            advance_epoch_pt,
2182            params,
2183            change_epoch.system_packages,
2184            temporary_store,
2185            tx_ctx,
2186            move_vm,
2187            gas_charger,
2188            protocol_config,
2189            metrics,
2190            trace_builder_opt,
2191        )
2192    }
2193
2194    /// Advances the epoch for the given `ChangeEpochV2` transaction kind by
2195    /// constructing a programmable transaction, executing it and processing the
2196    /// system packages.
2197    fn advance_epoch_v2(
2198        builder: ProgrammableTransactionBuilder,
2199        change_epoch_v2: ChangeEpochV2,
2200        temporary_store: &mut TemporaryStore<'_>,
2201        tx_ctx: Rc<RefCell<TxContext>>,
2202        move_vm: &Arc<MoveVM>,
2203        gas_charger: &mut GasCharger,
2204        protocol_config: &ProtocolConfig,
2205        metrics: Arc<LimitsMetrics>,
2206        trace_builder_opt: &mut Option<MoveTraceBuilder>,
2207    ) -> Result<(), ExecutionError> {
2208        let params = AdvanceEpochParams {
2209            epoch: change_epoch_v2.epoch,
2210            next_protocol_version: change_epoch_v2.protocol_version.into(),
2211            validator_subsidy: protocol_config.validator_target_reward(),
2212            storage_charge: change_epoch_v2.storage_charge,
2213            computation_charge: change_epoch_v2.computation_charge,
2214            computation_charge_burned: change_epoch_v2.computation_charge_burned,
2215            storage_rebate: change_epoch_v2.storage_rebate,
2216            non_refundable_storage_fee: change_epoch_v2.non_refundable_storage_fee,
2217            reward_slashing_rate: protocol_config.reward_slashing_rate(),
2218            epoch_start_timestamp_ms: change_epoch_v2.epoch_start_timestamp_ms,
2219            max_committee_members_count: protocol_config.max_committee_members_count(),
2220            // AdvanceEpochV2 does not use these fields, but keeping them to avoid creating a
2221            // separate AdvanceEpochParams struct.
2222            eligible_active_validators: vec![],
2223            scores: vec![],
2224            adjust_rewards_by_score: false,
2225        };
2226        let advance_epoch_pt = construct_advance_epoch_pt_v2(builder, &params)?;
2227        advance_epoch_impl(
2228            advance_epoch_pt,
2229            params,
2230            change_epoch_v2.system_packages,
2231            temporary_store,
2232            tx_ctx,
2233            move_vm,
2234            gas_charger,
2235            protocol_config,
2236            metrics,
2237            trace_builder_opt,
2238        )
2239    }
2240
2241    /// Advances the epoch for the given `ChangeEpochV3` transaction kind by
2242    /// constructing a programmable transaction, executing it and processing the
2243    /// system packages.
2244    fn advance_epoch_v3(
2245        builder: ProgrammableTransactionBuilder,
2246        change_epoch_v3: ChangeEpochV3,
2247        temporary_store: &mut TemporaryStore<'_>,
2248        tx_ctx: Rc<RefCell<TxContext>>,
2249        move_vm: &Arc<MoveVM>,
2250        gas_charger: &mut GasCharger,
2251        protocol_config: &ProtocolConfig,
2252        metrics: Arc<LimitsMetrics>,
2253        trace_builder_opt: &mut Option<MoveTraceBuilder>,
2254    ) -> Result<(), ExecutionError> {
2255        let params = AdvanceEpochParams {
2256            epoch: change_epoch_v3.epoch,
2257            next_protocol_version: change_epoch_v3.protocol_version.into(),
2258            validator_subsidy: protocol_config.validator_target_reward(),
2259            storage_charge: change_epoch_v3.storage_charge,
2260            computation_charge: change_epoch_v3.computation_charge,
2261            computation_charge_burned: change_epoch_v3.computation_charge_burned,
2262            storage_rebate: change_epoch_v3.storage_rebate,
2263            non_refundable_storage_fee: change_epoch_v3.non_refundable_storage_fee,
2264            reward_slashing_rate: protocol_config.reward_slashing_rate(),
2265            epoch_start_timestamp_ms: change_epoch_v3.epoch_start_timestamp_ms,
2266            max_committee_members_count: protocol_config.max_committee_members_count(),
2267            eligible_active_validators: change_epoch_v3.eligible_active_validators,
2268            // AdvanceEpochV3 does not use these fields, but keeping them to avoid creating a
2269            // separate AdvanceEpochParams struct.
2270            scores: vec![],
2271            adjust_rewards_by_score: false,
2272        };
2273        let advance_epoch_pt = construct_advance_epoch_pt_v3(builder, &params)?;
2274        advance_epoch_impl(
2275            advance_epoch_pt,
2276            params,
2277            change_epoch_v3.system_packages,
2278            temporary_store,
2279            tx_ctx,
2280            move_vm,
2281            gas_charger,
2282            protocol_config,
2283            metrics,
2284            trace_builder_opt,
2285        )
2286    }
2287
2288    /// Advances the epoch for the given `ChangeEpochV4` transaction kind by
2289    /// constructing a programmable transaction, executing it and processing the
2290    /// system packages.
2291    fn advance_epoch_v4(
2292        builder: ProgrammableTransactionBuilder,
2293        change_epoch_v4: ChangeEpochV4,
2294        temporary_store: &mut TemporaryStore<'_>,
2295        tx_ctx: Rc<RefCell<TxContext>>,
2296        move_vm: &Arc<MoveVM>,
2297        gas_charger: &mut GasCharger,
2298        protocol_config: &ProtocolConfig,
2299        metrics: Arc<LimitsMetrics>,
2300        trace_builder_opt: &mut Option<MoveTraceBuilder>,
2301    ) -> Result<(), ExecutionError> {
2302        let params = AdvanceEpochParams {
2303            epoch: change_epoch_v4.epoch,
2304            next_protocol_version: change_epoch_v4.protocol_version.into(),
2305            validator_subsidy: protocol_config.validator_target_reward(),
2306            storage_charge: change_epoch_v4.storage_charge,
2307            computation_charge: change_epoch_v4.computation_charge,
2308            computation_charge_burned: change_epoch_v4.computation_charge_burned,
2309            storage_rebate: change_epoch_v4.storage_rebate,
2310            non_refundable_storage_fee: change_epoch_v4.non_refundable_storage_fee,
2311            reward_slashing_rate: protocol_config.reward_slashing_rate(),
2312            epoch_start_timestamp_ms: change_epoch_v4.epoch_start_timestamp_ms,
2313            max_committee_members_count: protocol_config.max_committee_members_count(),
2314            eligible_active_validators: change_epoch_v4.eligible_active_validators,
2315            scores: change_epoch_v4.scores,
2316            adjust_rewards_by_score: change_epoch_v4.adjust_rewards_by_score,
2317        };
2318        let advance_epoch_pt = construct_advance_epoch_pt_v4(builder, &params)?;
2319        advance_epoch_impl(
2320            advance_epoch_pt,
2321            params,
2322            change_epoch_v4.system_packages,
2323            temporary_store,
2324            tx_ctx,
2325            move_vm,
2326            gas_charger,
2327            protocol_config,
2328            metrics,
2329            trace_builder_opt,
2330        )
2331    }
2332
2333    fn process_system_packages(
2334        system_packages: Vec<SystemPackage>,
2335        temporary_store: &mut TemporaryStore<'_>,
2336        tx_ctx: Rc<RefCell<TxContext>>,
2337        move_vm: &MoveVM,
2338        gas_charger: &mut GasCharger,
2339        protocol_config: &ProtocolConfig,
2340        metrics: Arc<LimitsMetrics>,
2341        trace_builder_opt: &mut Option<MoveTraceBuilder>,
2342    ) {
2343        let binary_config = to_binary_config(protocol_config, None);
2344        for SystemPackage {
2345            version,
2346            modules,
2347            dependencies,
2348        } in system_packages.into_iter()
2349        {
2350            let deserialized_modules: Vec<_> = modules
2351                .iter()
2352                .map(|m| CompiledModule::deserialize_with_config(m, &binary_config).unwrap())
2353                .collect();
2354
2355            if version == OBJECT_START_VERSION {
2356                let package_id = deserialized_modules.first().unwrap().address();
2357                info!("adding new system package {package_id}");
2358
2359                let publish_pt = {
2360                    let mut b = ProgrammableTransactionBuilder::new();
2361                    b.command(Command::new_publish(modules, dependencies));
2362                    b.finish()
2363                };
2364
2365                programmable_transactions::execution::execute::<execution_mode::System>(
2366                    protocol_config,
2367                    metrics.clone(),
2368                    move_vm,
2369                    temporary_store,
2370                    tx_ctx.clone(),
2371                    gas_charger,
2372                    publish_pt,
2373                    trace_builder_opt,
2374                )
2375                .map_err(|(e, _)| e)
2376                .expect("System Package Publish must succeed");
2377            } else {
2378                let mut new_package = Object::new_system_package(
2379                    &deserialized_modules,
2380                    version,
2381                    dependencies,
2382                    tx_ctx.borrow().digest(),
2383                );
2384
2385                info!("upgraded system package {:?}", new_package.object_ref());
2386
2387                // Decrement the version before writing the package so that the store can record
2388                // the version growing by one in the effects.
2389                new_package
2390                    .data
2391                    .as_opt_mut_package()
2392                    .unwrap()
2393                    .decrement_version()
2394                    .expect("package version should never underflow");
2395
2396                // upgrade of a previously existing framework module
2397                temporary_store.upgrade_system_package(new_package);
2398            }
2399        }
2400    }
2401
2402    /// Perform metadata updates in preparation for the transactions in the
2403    /// upcoming checkpoint:
2404    ///
2405    /// - Set the timestamp for the `Clock` shared object from the timestamp in the header from
2406    ///   consensus.
2407    fn setup_consensus_commit(
2408        consensus_commit_timestamp_ms: CheckpointTimestamp,
2409        temporary_store: &mut TemporaryStore<'_>,
2410        tx_ctx: Rc<RefCell<TxContext>>,
2411        move_vm: &Arc<MoveVM>,
2412        gas_charger: &mut GasCharger,
2413        protocol_config: &ProtocolConfig,
2414        metrics: Arc<LimitsMetrics>,
2415        trace_builder_opt: &mut Option<MoveTraceBuilder>,
2416    ) -> Result<(), ExecutionError> {
2417        let pt = {
2418            let mut builder = ProgrammableTransactionBuilder::new();
2419            let res = builder.move_call(
2420                ObjectId::FRAMEWORK,
2421                Identifier::CLOCK_MODULE,
2422                CONSENSUS_COMMIT_PROLOGUE_FUNCTION_NAME,
2423                vec![],
2424                vec![
2425                    CallArg::CLOCK_MUTABLE,
2426                    CallArg::pure(&consensus_commit_timestamp_ms),
2427                ],
2428            );
2429            assert_invariant!(
2430                res.is_ok(),
2431                "Unable to generate consensus_commit_prologue transaction!"
2432            );
2433            builder.finish()
2434        };
2435        programmable_transactions::execution::execute::<execution_mode::System>(
2436            protocol_config,
2437            metrics,
2438            move_vm,
2439            temporary_store,
2440            tx_ctx,
2441            gas_charger,
2442            pt,
2443            trace_builder_opt,
2444        )
2445        .map_err(|(e, _)| e)?;
2446        Ok(())
2447    }
2448
2449    /// The function constructs a transaction that invokes
2450    /// the `randomness_state_update` function from the IOTA framework,
2451    /// passing the randomness state object, the `randomness_round`,
2452    /// and the `random_bytes` as arguments. It then executes the transaction
2453    /// using the system execution mode.
2454    fn setup_randomness_state_update(
2455        update: RandomnessStateUpdate,
2456        temporary_store: &mut TemporaryStore<'_>,
2457        tx_ctx: Rc<RefCell<TxContext>>,
2458        move_vm: &Arc<MoveVM>,
2459        gas_charger: &mut GasCharger,
2460        protocol_config: &ProtocolConfig,
2461        metrics: Arc<LimitsMetrics>,
2462        trace_builder_opt: &mut Option<MoveTraceBuilder>,
2463    ) -> Result<(), ExecutionError> {
2464        let pt = {
2465            let mut builder = ProgrammableTransactionBuilder::new();
2466            let res = builder.move_call(
2467                ObjectId::FRAMEWORK,
2468                Identifier::RANDOM_MODULE,
2469                RANDOMNESS_STATE_UPDATE_FUNCTION_NAME,
2470                vec![],
2471                vec![
2472                    CallArg::Shared(SharedObjectReference::new(
2473                        ObjectId::RANDOMNESS_STATE,
2474                        update.randomness_obj_initial_shared_version,
2475                        true,
2476                    )),
2477                    CallArg::pure(&update.randomness_round),
2478                    CallArg::pure(&update.random_bytes),
2479                ],
2480            );
2481            assert_invariant!(
2482                res.is_ok(),
2483                "Unable to generate randomness_state_update transaction!"
2484            );
2485            builder.finish()
2486        };
2487        programmable_transactions::execution::execute::<execution_mode::System>(
2488            protocol_config,
2489            metrics,
2490            move_vm,
2491            temporary_store,
2492            tx_ctx,
2493            gas_charger,
2494            pt,
2495            trace_builder_opt,
2496        )
2497        .map_err(|(e, _)| e)?;
2498        Ok(())
2499    }
2500
2501    /// Appends the `transaction_deny_rules::create` call to the end-of-epoch
2502    /// transaction being built. If the built transaction later fails and epoch
2503    /// advancement falls back to safe mode, the creation is dropped with it
2504    /// and must be re-injected at a later epoch end while the object is
2505    /// absent.
2506    fn setup_transaction_deny_rules_create(
2507        mut builder: ProgrammableTransactionBuilder,
2508    ) -> Result<ProgrammableTransactionBuilder, ExecutionError> {
2509        let res = builder.move_call(
2510            ObjectId::FRAMEWORK,
2511            TRANSACTION_DENY_RULES_MODULE,
2512            TRANSACTION_DENY_RULES_CREATE_FUNCTION_NAME,
2513            vec![],
2514            vec![],
2515        );
2516        assert_invariant!(
2517            res.is_ok(),
2518            "Unable to generate transaction_deny_rules create transaction!"
2519        );
2520        Ok(builder)
2521    }
2522
2523    /// Executes a `TransactionDenyRulesUpdate` system transaction: a single
2524    /// call to `transaction_deny_rules::update` applying the payload's
2525    /// add/remove delta and switch states.
2526    fn setup_transaction_deny_rules_update(
2527        update: TransactionDenyRulesUpdate,
2528        temporary_store: &mut TemporaryStore<'_>,
2529        tx_ctx: Rc<RefCell<TxContext>>,
2530        move_vm: &Arc<MoveVM>,
2531        gas_charger: &mut GasCharger,
2532        protocol_config: &ProtocolConfig,
2533        metrics: Arc<LimitsMetrics>,
2534        trace_builder_opt: &mut Option<MoveTraceBuilder>,
2535    ) -> Result<(), ExecutionError> {
2536        let pt = {
2537            let mut builder = ProgrammableTransactionBuilder::new();
2538            // Argument order must match `transaction_deny_rules::update`. The
2539            // set-typed delta lists BCS-encode identically to the `vector`
2540            // parameters the Move function takes.
2541            let res = builder.move_call(
2542                ObjectId::FRAMEWORK,
2543                TRANSACTION_DENY_RULES_MODULE,
2544                TRANSACTION_DENY_RULES_UPDATE_FUNCTION_NAME,
2545                vec![],
2546                vec![
2547                    CallArg::Shared(SharedObjectReference::new(
2548                        ObjectId::TRANSACTION_DENY_RULES,
2549                        update.deny_rules_obj_initial_shared_version,
2550                        true,
2551                    )),
2552                    CallArg::pure(&update.added_addresses),
2553                    CallArg::pure(&update.removed_addresses),
2554                    CallArg::pure(&update.added_objects),
2555                    CallArg::pure(&update.removed_objects),
2556                    CallArg::pure(&update.added_packages),
2557                    CallArg::pure(&update.removed_packages),
2558                    CallArg::pure(&update.package_publish_disabled),
2559                    CallArg::pure(&update.package_upgrade_disabled),
2560                    CallArg::pure(&update.shared_object_disabled),
2561                    CallArg::pure(&update.user_transaction_disabled),
2562                    CallArg::pure(&update.receiving_objects_disabled),
2563                    CallArg::pure(&update.move_authenticator_disabled),
2564                ],
2565            );
2566            assert_invariant!(
2567                res.is_ok(),
2568                "Unable to generate transaction_deny_rules update transaction!"
2569            );
2570            builder.finish()
2571        };
2572        programmable_transactions::execution::execute::<execution_mode::System>(
2573            protocol_config,
2574            metrics,
2575            move_vm,
2576            temporary_store,
2577            tx_ctx,
2578            gas_charger,
2579            pt,
2580            trace_builder_opt,
2581        )
2582        .map(|(results, _timings)| results)
2583        .map_err(|(error, _timings)| error)
2584    }
2585
2586    /// Construct a PTB with a single move call. This calls the authenticator
2587    /// function found in `AuthenticatorFunctionRef`. The inputs for the
2588    /// function are found in `MoveAuthenticator`.
2589    /// `MoveAuthenticator::object_to_authenticate` is added as the first
2590    /// argument to the created PTB, followed by all arguments in
2591    /// `MoveAuthenticator::call_args`.
2592    fn setup_authenticator_move_call(
2593        authenticator: MoveAuthenticator,
2594        authenticator_function_ref: AuthenticatorFunctionRefV1,
2595    ) -> Result<ProgrammableTransaction, ExecutionError> {
2596        let mut builder = ProgrammableTransactionBuilder::new();
2597
2598        let mut args = vec![authenticator.object_to_authenticate().to_owned()];
2599        args.extend(authenticator.call_args().to_owned());
2600
2601        let res = builder.move_call(
2602            authenticator_function_ref.package,
2603            Identifier::new(authenticator_function_ref.module.clone()).expect(
2604                "`AuthenticatorFunctionRefV1::module` is expected to be a valid `Identifier`",
2605            ),
2606            Identifier::new(authenticator_function_ref.function).expect(
2607                "`AuthenticatorFunctionRefV1::function` is expected to be a valid `Identifier`",
2608            ),
2609            authenticator.type_args().to_vec(),
2610            args,
2611        );
2612
2613        assert_invariant!(
2614            res.is_ok(),
2615            "Unable to generate an account authenticator call transaction!"
2616        );
2617
2618        Ok(builder.finish())
2619    }
2620
2621    fn resolve_sponsor(gas_data: &GasPayment, transaction_signer: &Address) -> Option<Address> {
2622        let gas_owner = gas_data.owner;
2623        if &gas_owner == transaction_signer {
2624            None
2625        } else {
2626            Some(gas_owner)
2627        }
2628    }
2629}