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