Skip to main content

sui_types/
transaction.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// SPDX-License-Identifier: Apache-2.0
4
5use super::{SUI_BRIDGE_OBJECT_ID, base_types::*, error::*};
6use crate::accumulator_root::{AccumulatorObjId, AccumulatorValue, check_accumulator_type_bounds};
7use crate::allowance::{ResolvedAllowance, parse_allowance_object};
8use crate::authenticator_state::ActiveJwk;
9use crate::balance::{
10    BALANCE_MODULE_NAME, BALANCE_REDEEM_FUNDS_FUNCTION_NAME, BALANCE_SEND_FUNDS_FUNCTION_NAME,
11    BALANCE_SPLIT_FUNCTION_NAME, BALANCE_ZERO_FUNCTION_NAME, Balance,
12};
13use crate::coin::{
14    COIN_MODULE_NAME, INTO_BALANCE_FUNC_NAME, PUT_FUNC_NAME, REDEEM_FUNDS_FUNC_NAME,
15    SEND_FUNDS_FUNC_NAME,
16};
17use crate::coin_reservation::{
18    CoinReservationResolverTrait, ParsedDigest, ParsedObjectRefWithdrawal,
19};
20use crate::committee::{Committee, EpochId, ProtocolVersion};
21use crate::crypto::{
22    AuthoritySignInfo, AuthoritySignInfoTrait, AuthoritySignature, AuthorityStrongQuorumSignInfo,
23    DefaultHash, Ed25519SuiSignature, EmptySignInfo, RandomnessRound, Signature, Signer,
24    SuiSignatureInner, ToFromBytes, default_hash,
25};
26use crate::digests::{AdditionalConsensusStateDigest, SenderSignedDataDigest};
27use crate::digests::{ChainIdentifier, ConsensusCommitDigest};
28use crate::execution::{ExecutionTimeObservationKey, SharedInput};
29use crate::funds_accumulator::{FUNDS_ACCUMULATOR_MODULE_NAME, WITHDRAWAL_SPLIT_FUNC_NAME};
30use crate::gas::minimum_gas_budget;
31use crate::gas_coin::GAS;
32use crate::gas_model::gas_predicates::check_for_gas_price_too_high;
33use crate::message_envelope::{Envelope, Message, TrustedEnvelope, VerifiedEnvelope};
34use crate::messages_checkpoint::CheckpointTimestamp;
35use crate::messages_consensus::{
36    ConsensusCommitPrologue, ConsensusCommitPrologueV2, ConsensusCommitPrologueV3,
37    ConsensusCommitPrologueV4, ConsensusDeterminedVersionAssignments,
38};
39use crate::object::{MoveObject, Object, Owner};
40use crate::programmable_transaction_builder::ProgrammableTransactionBuilder;
41use crate::signature::{GenericSignature, VerifyParams};
42use crate::signature_verification::{
43    VerifiedDigestCache, verify_sender_signed_data_message_signatures,
44};
45use crate::type_input::TypeInput;
46use crate::{
47    SUI_ACCUMULATOR_ROOT_OBJECT_ID, SUI_AUTHENTICATOR_STATE_OBJECT_ID, SUI_CLOCK_OBJECT_ID,
48    SUI_CLOCK_OBJECT_SHARED_VERSION, SUI_FRAMEWORK_ADDRESS, SUI_FRAMEWORK_PACKAGE_ID,
49    SUI_RANDOMNESS_STATE_OBJECT_ID, SUI_SYSTEM_STATE_OBJECT_ID,
50    SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
51};
52use enum_dispatch::enum_dispatch;
53use fastcrypto::{encoding::Base64, hash::HashFunction};
54use itertools::{Either, Itertools};
55use move_core_types::account_address::AccountAddress;
56use move_core_types::identifier::IdentStr;
57use move_core_types::{ident_str, identifier};
58use move_core_types::{identifier::Identifier, language_storage::TypeTag};
59use mysten_common::{ZipDebugEqIteratorExt, assert_reachable, debug_fatal};
60use nonempty::{NonEmpty, nonempty};
61use serde::{Deserialize, Serialize};
62use shared_crypto::intent::{Intent, IntentMessage, IntentScope};
63use std::collections::btree_map::Entry;
64use std::fmt::Write;
65use std::fmt::{Debug, Display, Formatter};
66use std::sync::Arc;
67use std::sync::RwLock;
68use std::time::Duration;
69use std::{
70    collections::{BTreeMap, BTreeSet, HashSet},
71    hash::Hash,
72    iter,
73};
74use strum::IntoStaticStr;
75use sui_protocol_config::{PerObjectCongestionControlMode, ProtocolConfig};
76use tap::Pipe;
77use tracing::trace;
78
79#[cfg(test)]
80#[path = "unit_tests/transaction_serialization_tests.rs"]
81mod transaction_serialization_tests;
82
83pub const TEST_ONLY_GAS_UNIT_FOR_TRANSFER: u64 = 10_000;
84pub const TEST_ONLY_GAS_UNIT_FOR_OBJECT_BASICS: u64 = 50_000;
85// Multiplied by the reference gas price, this must cover the MIST-denominated publish charge on
86// top of the execution and storage costs of the fixture packages. At a reference gas price of 100
87// the budget is 2 SUI, and at 1000 it is 20 SUI, under the maximum budget.
88pub const TEST_ONLY_GAS_UNIT_FOR_PUBLISH: u64 = 20_000_000;
89pub const TEST_ONLY_GAS_UNIT_FOR_STAKING: u64 = 50_000;
90pub const TEST_ONLY_GAS_UNIT_FOR_GENERIC: u64 = 50_000;
91pub const TEST_ONLY_GAS_UNIT_FOR_SPLIT_COIN: u64 = 10_000;
92// For some transactions we may either perform heavy operations or touch
93// objects that are storage expensive. That may happen (and often is the case)
94// because the object touched are set up in genesis and carry no storage cost
95// (and thus rebate) on first usage.
96pub const TEST_ONLY_GAS_UNIT_FOR_HEAVY_COMPUTATION_STORAGE: u64 = 5_000_000;
97
98pub const GAS_PRICE_FOR_SYSTEM_TX: u64 = 1;
99
100pub const DEFAULT_VALIDATOR_GAS_PRICE: u64 = 1000;
101
102const BLOCKED_MOVE_FUNCTIONS: [(ObjectID, &str, &str); 0] = [];
103
104#[cfg(test)]
105#[path = "unit_tests/messages_tests.rs"]
106mod messages_tests;
107
108#[cfg(test)]
109#[path = "unit_tests/balance_withdraw_tests.rs"]
110mod balance_withdraw_tests;
111
112#[cfg(test)]
113#[path = "unit_tests/address_balance_gas_tests.rs"]
114mod address_balance_gas_tests;
115
116#[cfg(test)]
117#[path = "unit_tests/transaction_claims_tests.rs"]
118mod transaction_claims_tests;
119
120#[cfg(test)]
121#[path = "unit_tests/allowed_proposers_tests.rs"]
122mod allowed_proposers_tests;
123
124#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
125pub enum CallArg {
126    // contains no structs or objects
127    Pure(Vec<u8>),
128    // an object
129    Object(ObjectArg),
130    // Reservation to withdraw balance from a funds a accumulator. This will be converted into a
131    // `sui::funds_accumulator::Withdrawal` struct and passed into Move.
132    // It is allowed to have multiple withdraw arguments even for the same funds type.
133    FundsWithdrawal(FundsWithdrawalArg),
134}
135
136impl CallArg {
137    pub const SUI_SYSTEM_MUT: Self = Self::Object(ObjectArg::SUI_SYSTEM_MUT);
138    pub const CLOCK_IMM: Self = Self::Object(ObjectArg::SharedObject {
139        id: SUI_CLOCK_OBJECT_ID,
140        initial_shared_version: SUI_CLOCK_OBJECT_SHARED_VERSION,
141        mutability: SharedObjectMutability::Immutable,
142    });
143    pub const CLOCK_MUT: Self = Self::Object(ObjectArg::SharedObject {
144        id: SUI_CLOCK_OBJECT_ID,
145        initial_shared_version: SUI_CLOCK_OBJECT_SHARED_VERSION,
146        mutability: SharedObjectMutability::Mutable,
147    });
148}
149
150#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, Deserialize)]
151pub enum ObjectArg {
152    // A Move object from fastpath.
153    ImmOrOwnedObject(ObjectRef),
154    // A Move object from consensus (historically consensus objects were always shared).
155    // SharedObject::mutable controls whether caller asks for a mutable reference to shared object.
156    SharedObject {
157        id: ObjectID,
158        initial_shared_version: SequenceNumber,
159        // Note: this used to be a bool, but because true/false encode to 0x00/0x01, we are able to
160        // be backward compatible.
161        mutability: SharedObjectMutability,
162    },
163    // A Move object that can be received in this transaction.
164    Receiving(ObjectRef),
165}
166
167#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
168pub enum Reservation {
169    // Reserve a specific amount of the balance.
170    MaxAmountU64(u64),
171}
172
173#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
174pub enum WithdrawalTypeArg {
175    Balance(TypeTag),
176}
177
178impl WithdrawalTypeArg {
179    /// Convert the withdrawal type argument to a full type tag,
180    /// e.g. `Balance<T>` -> `0x2::balance::Balance<T>`
181    pub fn to_type_tag(&self) -> TypeTag {
182        let WithdrawalTypeArg::Balance(type_param) = self;
183        Balance::type_tag(type_param.clone())
184    }
185
186    /// If this is a Balance accumulator, return the type parameter of `Balance<T>`,
187    /// e.g. `Balance<T>` -> `Some(T)`
188    /// Otherwise, return `None`. This is not possible today, but in the future we will support other types of accumulators.
189    pub fn get_balance_type_param(&self) -> Option<TypeTag> {
190        let WithdrawalTypeArg::Balance(type_param) = self;
191        Some(type_param.clone())
192    }
193}
194
195// TODO(address-balances): Rename all the related structs and enums.
196#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
197pub struct FundsWithdrawalArg {
198    /// The reservation of the funds accumulator to withdraw.
199    pub reservation: Reservation,
200    /// The type argument of the funds accumulator to withdraw, e.g. `Balance<_>`.
201    pub type_arg: WithdrawalTypeArg,
202    /// The source of the funds to withdraw.
203    pub withdraw_from: WithdrawFrom,
204}
205
206#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
207pub enum WithdrawFrom {
208    /// Withdraw from the sender of the transaction.
209    Sender,
210    /// Withdraw from the sponsor of the transaction (gas owner).
211    Sponsor,
212    /// Withdraw from `funder`'s balance under an `Allowance` granted to the sender.
213    SenderAllowance {
214        funder: SuiAddress,
215        allowance: ObjectID,
216    },
217    /// Seize from frozen `seized_from`'s balance under a `SeizeAuth` owned by the sender.
218    FrozenAddress {
219        seized_from: SuiAddress,
220        seize_auth: ObjectID,
221    },
222    // TODO(address-balances): Add more options here, such as multi-party withdraws.
223}
224
225impl FundsWithdrawalArg {
226    /// Withdraws from `Balance<balance_type>` in the sender's address.
227    pub fn balance_from_sender(amount: u64, balance_type: TypeTag) -> Self {
228        Self {
229            reservation: Reservation::MaxAmountU64(amount),
230            type_arg: WithdrawalTypeArg::Balance(balance_type),
231            withdraw_from: WithdrawFrom::Sender,
232        }
233    }
234
235    /// Withdraws from `Balance<balance_type>` in the sponsor's address (gas owner).
236    pub fn balance_from_sponsor(amount: u64, balance_type: TypeTag) -> Self {
237        Self {
238            reservation: Reservation::MaxAmountU64(amount),
239            type_arg: WithdrawalTypeArg::Balance(balance_type),
240            withdraw_from: WithdrawFrom::Sponsor,
241        }
242    }
243
244    /// Withdraws from `Balance<balance_type>` in `funder`'s address, gated by the
245    /// allowance object.
246    pub fn balance_from_allowance(
247        amount: u64,
248        balance_type: TypeTag,
249        funder: SuiAddress,
250        allowance: ObjectID,
251    ) -> Self {
252        Self {
253            reservation: Reservation::MaxAmountU64(amount),
254            type_arg: WithdrawalTypeArg::Balance(balance_type),
255            withdraw_from: WithdrawFrom::SenderAllowance { funder, allowance },
256        }
257    }
258
259    /// The account debited by this withdrawal
260    pub fn owner_for_withdrawal(&self, tx: &impl TransactionDataAPI) -> SuiAddress {
261        match &self.withdraw_from {
262            WithdrawFrom::Sender => tx.sender(),
263            WithdrawFrom::Sponsor => tx.gas_owner(),
264            WithdrawFrom::SenderAllowance { funder, .. } => *funder,
265            WithdrawFrom::FrozenAddress { seized_from, .. } => *seized_from,
266        }
267    }
268}
269
270fn type_input_validity_check(
271    tag: &TypeInput,
272    config: &ProtocolConfig,
273    starting_count: &mut usize,
274) -> UserInputResult<()> {
275    let mut stack = vec![(tag, 1)];
276    while let Some((tag, depth)) = stack.pop() {
277        *starting_count += 1;
278        fp_ensure!(
279            *starting_count < config.max_type_arguments() as usize,
280            UserInputError::SizeLimitExceeded {
281                limit: "maximum type arguments in a call transaction".to_string(),
282                value: config.max_type_arguments().to_string()
283            }
284        );
285        fp_ensure!(
286            depth < config.max_type_argument_depth(),
287            UserInputError::SizeLimitExceeded {
288                limit: "maximum type argument depth in a call transaction".to_string(),
289                value: config.max_type_argument_depth().to_string()
290            }
291        );
292        match tag {
293            TypeInput::Bool
294            | TypeInput::U8
295            | TypeInput::U64
296            | TypeInput::U128
297            | TypeInput::Address
298            | TypeInput::Signer
299            | TypeInput::U16
300            | TypeInput::U32
301            | TypeInput::U256 => (),
302            TypeInput::Vector(t) => {
303                stack.push((t, depth + 1));
304            }
305            TypeInput::Struct(s) => {
306                let next_depth = depth + 1;
307                if config.validate_identifier_inputs() {
308                    fp_ensure!(
309                        identifier::is_valid(&s.module),
310                        UserInputError::InvalidIdentifier {
311                            error: s.module.clone()
312                        }
313                    );
314                    fp_ensure!(
315                        identifier::is_valid(&s.name),
316                        UserInputError::InvalidIdentifier {
317                            error: s.name.clone()
318                        }
319                    );
320                }
321                stack.extend(s.type_params.iter().map(|t| (t, next_depth)));
322            }
323        }
324    }
325    Ok(())
326}
327
328#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
329pub struct ChangeEpoch {
330    /// The next (to become) epoch ID.
331    pub epoch: EpochId,
332    /// The protocol version in effect in the new epoch.
333    pub protocol_version: ProtocolVersion,
334    /// The total amount of gas charged for storage during the epoch.
335    pub storage_charge: u64,
336    /// The total amount of gas charged for computation during the epoch.
337    pub computation_charge: u64,
338    /// The amount of storage rebate refunded to the txn senders.
339    pub storage_rebate: u64,
340    /// The non-refundable storage fee.
341    pub non_refundable_storage_fee: u64,
342    /// Unix timestamp when epoch started
343    pub epoch_start_timestamp_ms: u64,
344    /// System packages (specifically framework and move stdlib) that are written before the new
345    /// epoch starts. This tracks framework upgrades on chain. When executing the ChangeEpoch txn,
346    /// the validator must write out the modules below.  Modules are provided with the version they
347    /// will be upgraded to, their modules in serialized form (which include their package ID), and
348    /// a list of their transitive dependencies.
349    pub system_packages: Vec<(SequenceNumber, Vec<Vec<u8>>, Vec<ObjectID>)>,
350}
351
352#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
353pub struct GenesisTransaction {
354    pub objects: Vec<GenesisObject>,
355}
356
357#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
358pub enum GenesisObject {
359    RawObject {
360        data: crate::object::Data,
361        owner: crate::object::Owner,
362    },
363}
364
365impl GenesisObject {
366    pub fn id(&self) -> ObjectID {
367        match self {
368            GenesisObject::RawObject { data, .. } => data.id(),
369        }
370    }
371}
372
373#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
374pub struct AuthenticatorStateExpire {
375    /// expire JWKs that have a lower epoch than this
376    pub min_epoch: u64,
377    /// The initial version of the authenticator object that it was shared at.
378    pub authenticator_obj_initial_shared_version: SequenceNumber,
379}
380
381impl AuthenticatorStateExpire {
382    pub fn authenticator_obj_initial_shared_version(&self) -> SequenceNumber {
383        self.authenticator_obj_initial_shared_version
384    }
385}
386
387#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
388pub enum StoredExecutionTimeObservations {
389    V1(Vec<(ExecutionTimeObservationKey, Vec<(AuthorityName, Duration)>)>),
390}
391
392#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
393pub struct WriteAccumulatorStorageCost {
394    /// Contains the end-of-epoch-computed storage cost for accumulator objects.
395    pub storage_cost: u64,
396}
397
398impl StoredExecutionTimeObservations {
399    pub fn unwrap_v1(self) -> Vec<(ExecutionTimeObservationKey, Vec<(AuthorityName, Duration)>)> {
400        match self {
401            Self::V1(observations) => observations,
402        }
403    }
404
405    pub fn filter_and_sort_v1<P>(&self, predicate: P, limit: usize) -> Self
406    where
407        P: FnMut(&&(ExecutionTimeObservationKey, Vec<(AuthorityName, Duration)>)) -> bool,
408    {
409        match self {
410            Self::V1(observations) => Self::V1(
411                observations
412                    .iter()
413                    .filter(predicate)
414                    .sorted_by_key(|(key, _)| key)
415                    .take(limit)
416                    .cloned()
417                    .collect(),
418            ),
419        }
420    }
421
422    /// Split observations into chunks of the specified size.
423    /// Returns a vector of chunks, each containing up to `chunk_size` observations.
424    pub fn chunk_observations(&self, chunk_size: usize) -> Vec<Self> {
425        match self {
426            Self::V1(observations) => {
427                if chunk_size == 0 {
428                    return vec![];
429                }
430                observations
431                    .chunks(chunk_size)
432                    .map(|chunk| Self::V1(chunk.to_vec()))
433                    .collect()
434            }
435        }
436    }
437
438    /// Merge multiple chunks into a single observation set.
439    /// Chunks must be provided in order and already sorted.
440    pub fn merge_sorted_chunks(chunks: Vec<Self>) -> Self {
441        let mut all_observations = Vec::new();
442
443        for chunk in chunks {
444            match chunk {
445                Self::V1(observations) => {
446                    all_observations.extend(observations);
447                }
448            }
449        }
450
451        Self::V1(all_observations)
452    }
453}
454
455#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
456pub struct AuthenticatorStateUpdate {
457    /// Epoch of the authenticator state update transaction
458    pub epoch: u64,
459    /// Consensus round of the authenticator state update
460    pub round: u64,
461    /// newly active jwks
462    pub new_active_jwks: Vec<ActiveJwk>,
463    /// The initial version of the authenticator object that it was shared at.
464    pub authenticator_obj_initial_shared_version: SequenceNumber,
465    // to version this struct, do not add new fields. Instead, add a AuthenticatorStateUpdateV2 to
466    // TransactionKind.
467}
468
469impl AuthenticatorStateUpdate {
470    pub fn authenticator_obj_initial_shared_version(&self) -> SequenceNumber {
471        self.authenticator_obj_initial_shared_version
472    }
473}
474
475#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
476pub struct RandomnessStateUpdate {
477    /// Epoch of the randomness state update transaction
478    pub epoch: u64,
479    /// Randomness round of the update
480    pub randomness_round: RandomnessRound,
481    /// Updated random bytes
482    pub random_bytes: Vec<u8>,
483    /// The initial version of the randomness object that it was shared at.
484    pub randomness_obj_initial_shared_version: SequenceNumber,
485    // to version this struct, do not add new fields. Instead, add a RandomnessStateUpdateV2 to
486    // TransactionKind.
487}
488
489impl RandomnessStateUpdate {
490    pub fn randomness_obj_initial_shared_version(&self) -> SequenceNumber {
491        self.randomness_obj_initial_shared_version
492    }
493}
494
495#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, IntoStaticStr)]
496pub enum TransactionKind {
497    /// A transaction that allows the interleaving of native commands and Move calls
498    ProgrammableTransaction(ProgrammableTransaction),
499    /// A system transaction that will update epoch information on-chain.
500    /// It will only ever be executed once in an epoch.
501    /// The argument is the next epoch number, which is critical
502    /// because it ensures that this transaction has a unique digest.
503    /// This will eventually be translated to a Move call during execution.
504    /// It also doesn't require/use a gas object.
505    /// A validator will not sign a transaction of this kind from outside. It only
506    /// signs internally during epoch changes.
507    ///
508    /// The ChangeEpoch enumerant is now deprecated (but the ChangeEpoch struct is still used by
509    /// EndOfEpochTransaction below).
510    ChangeEpoch(ChangeEpoch),
511    Genesis(GenesisTransaction),
512    ConsensusCommitPrologue(ConsensusCommitPrologue),
513    AuthenticatorStateUpdate(AuthenticatorStateUpdate),
514
515    /// EndOfEpochTransaction replaces ChangeEpoch with a list of transactions that are allowed to
516    /// run at the end of the epoch.
517    EndOfEpochTransaction(Vec<EndOfEpochTransactionKind>),
518
519    RandomnessStateUpdate(RandomnessStateUpdate),
520    // V2 ConsensusCommitPrologue also includes the digest of the current consensus output.
521    ConsensusCommitPrologueV2(ConsensusCommitPrologueV2),
522
523    ConsensusCommitPrologueV3(ConsensusCommitPrologueV3),
524    ConsensusCommitPrologueV4(ConsensusCommitPrologueV4),
525
526    /// A system transaction that is expressed as a PTB
527    ProgrammableSystemTransaction(ProgrammableTransaction),
528    // .. more transaction types go here
529}
530
531/// EndOfEpochTransactionKind
532#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize, IntoStaticStr)]
533pub enum EndOfEpochTransactionKind {
534    ChangeEpoch(ChangeEpoch),
535    AuthenticatorStateCreate,
536    AuthenticatorStateExpire(AuthenticatorStateExpire),
537    RandomnessStateCreate,
538    DenyListStateCreate,
539    BridgeStateCreate(ChainIdentifier),
540    BridgeCommitteeInit(SequenceNumber),
541    StoreExecutionTimeObservations(StoredExecutionTimeObservations),
542    AccumulatorRootCreate,
543    CoinRegistryCreate,
544    DisplayRegistryCreate,
545    AddressAliasStateCreate,
546    WriteAccumulatorStorageCost(WriteAccumulatorStorageCost),
547    ForwardingAddressRegistryCreate,
548    FreezeListCreate,
549}
550
551impl EndOfEpochTransactionKind {
552    pub fn new_change_epoch(
553        next_epoch: EpochId,
554        protocol_version: ProtocolVersion,
555        storage_charge: u64,
556        computation_charge: u64,
557        storage_rebate: u64,
558        non_refundable_storage_fee: u64,
559        epoch_start_timestamp_ms: u64,
560        system_packages: Vec<(SequenceNumber, Vec<Vec<u8>>, Vec<ObjectID>)>,
561    ) -> Self {
562        Self::ChangeEpoch(ChangeEpoch {
563            epoch: next_epoch,
564            protocol_version,
565            storage_charge,
566            computation_charge,
567            storage_rebate,
568            non_refundable_storage_fee,
569            epoch_start_timestamp_ms,
570            system_packages,
571        })
572    }
573
574    pub fn new_authenticator_state_expire(
575        min_epoch: u64,
576        authenticator_obj_initial_shared_version: SequenceNumber,
577    ) -> Self {
578        Self::AuthenticatorStateExpire(AuthenticatorStateExpire {
579            min_epoch,
580            authenticator_obj_initial_shared_version,
581        })
582    }
583
584    pub fn new_authenticator_state_create() -> Self {
585        Self::AuthenticatorStateCreate
586    }
587
588    pub fn new_randomness_state_create() -> Self {
589        Self::RandomnessStateCreate
590    }
591
592    pub fn new_accumulator_root_create() -> Self {
593        Self::AccumulatorRootCreate
594    }
595
596    pub fn new_coin_registry_create() -> Self {
597        Self::CoinRegistryCreate
598    }
599
600    pub fn new_display_registry_create() -> Self {
601        Self::DisplayRegistryCreate
602    }
603
604    pub fn new_deny_list_state_create() -> Self {
605        Self::DenyListStateCreate
606    }
607
608    pub fn new_address_alias_state_create() -> Self {
609        Self::AddressAliasStateCreate
610    }
611
612    pub fn new_forwarding_address_registry_create() -> Self {
613        Self::ForwardingAddressRegistryCreate
614    }
615
616    pub fn new_freeze_list_create() -> Self {
617        Self::FreezeListCreate
618    }
619
620    pub fn new_bridge_create(chain_identifier: ChainIdentifier) -> Self {
621        Self::BridgeStateCreate(chain_identifier)
622    }
623
624    pub fn init_bridge_committee(bridge_shared_version: SequenceNumber) -> Self {
625        Self::BridgeCommitteeInit(bridge_shared_version)
626    }
627
628    pub fn new_store_execution_time_observations(
629        estimates: StoredExecutionTimeObservations,
630    ) -> Self {
631        Self::StoreExecutionTimeObservations(estimates)
632    }
633
634    pub fn new_write_accumulator_storage_cost(storage_cost: u64) -> Self {
635        Self::WriteAccumulatorStorageCost(WriteAccumulatorStorageCost { storage_cost })
636    }
637
638    fn input_objects(&self) -> Vec<InputObjectKind> {
639        match self {
640            Self::ChangeEpoch(_) => {
641                vec![InputObjectKind::SharedMoveObject {
642                    id: SUI_SYSTEM_STATE_OBJECT_ID,
643                    initial_shared_version: SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
644                    mutability: SharedObjectMutability::Mutable,
645                }]
646            }
647            Self::AuthenticatorStateCreate => vec![],
648            Self::AuthenticatorStateExpire(expire) => {
649                vec![InputObjectKind::SharedMoveObject {
650                    id: SUI_AUTHENTICATOR_STATE_OBJECT_ID,
651                    initial_shared_version: expire.authenticator_obj_initial_shared_version(),
652                    mutability: SharedObjectMutability::Mutable,
653                }]
654            }
655            Self::RandomnessStateCreate => vec![],
656            Self::DenyListStateCreate => vec![],
657            Self::BridgeStateCreate(_) => vec![],
658            Self::BridgeCommitteeInit(bridge_version) => vec![
659                InputObjectKind::SharedMoveObject {
660                    id: SUI_BRIDGE_OBJECT_ID,
661                    initial_shared_version: *bridge_version,
662                    mutability: SharedObjectMutability::Mutable,
663                },
664                InputObjectKind::SharedMoveObject {
665                    id: SUI_SYSTEM_STATE_OBJECT_ID,
666                    initial_shared_version: SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
667                    mutability: SharedObjectMutability::Mutable,
668                },
669            ],
670            Self::StoreExecutionTimeObservations(_) => {
671                vec![InputObjectKind::SharedMoveObject {
672                    id: SUI_SYSTEM_STATE_OBJECT_ID,
673                    initial_shared_version: SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
674                    mutability: SharedObjectMutability::Mutable,
675                }]
676            }
677            Self::AccumulatorRootCreate => vec![],
678            Self::CoinRegistryCreate => vec![],
679            Self::DisplayRegistryCreate => vec![],
680            Self::AddressAliasStateCreate => vec![],
681            Self::WriteAccumulatorStorageCost(_) => {
682                vec![InputObjectKind::SharedMoveObject {
683                    id: SUI_SYSTEM_STATE_OBJECT_ID,
684                    initial_shared_version: SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
685                    mutability: SharedObjectMutability::Mutable,
686                }]
687            }
688            Self::ForwardingAddressRegistryCreate => vec![],
689            Self::FreezeListCreate => vec![],
690        }
691    }
692
693    fn shared_input_objects(&self) -> impl Iterator<Item = SharedInputObject> + '_ {
694        match self {
695            Self::ChangeEpoch(_) => {
696                Either::Left(vec![SharedInputObject::SUI_SYSTEM_OBJ].into_iter())
697            }
698            Self::AuthenticatorStateExpire(expire) => Either::Left(
699                vec![SharedInputObject {
700                    id: SUI_AUTHENTICATOR_STATE_OBJECT_ID,
701                    initial_shared_version: expire.authenticator_obj_initial_shared_version(),
702                    mutability: SharedObjectMutability::Mutable,
703                }]
704                .into_iter(),
705            ),
706            Self::AuthenticatorStateCreate => Either::Right(iter::empty()),
707            Self::RandomnessStateCreate => Either::Right(iter::empty()),
708            Self::DenyListStateCreate => Either::Right(iter::empty()),
709            Self::BridgeStateCreate(_) => Either::Right(iter::empty()),
710            Self::BridgeCommitteeInit(bridge_version) => Either::Left(
711                vec![
712                    SharedInputObject {
713                        id: SUI_BRIDGE_OBJECT_ID,
714                        initial_shared_version: *bridge_version,
715                        mutability: SharedObjectMutability::Mutable,
716                    },
717                    SharedInputObject::SUI_SYSTEM_OBJ,
718                ]
719                .into_iter(),
720            ),
721            Self::StoreExecutionTimeObservations(_) => {
722                Either::Left(vec![SharedInputObject::SUI_SYSTEM_OBJ].into_iter())
723            }
724            Self::AccumulatorRootCreate => Either::Right(iter::empty()),
725            Self::CoinRegistryCreate => Either::Right(iter::empty()),
726            Self::DisplayRegistryCreate => Either::Right(iter::empty()),
727            Self::AddressAliasStateCreate => Either::Right(iter::empty()),
728            Self::WriteAccumulatorStorageCost(_) => {
729                Either::Left(vec![SharedInputObject::SUI_SYSTEM_OBJ].into_iter())
730            }
731            Self::ForwardingAddressRegistryCreate => Either::Right(iter::empty()),
732            Self::FreezeListCreate => Either::Right(iter::empty()),
733        }
734    }
735
736    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
737        match self {
738            Self::ChangeEpoch(_) => (),
739            Self::AuthenticatorStateCreate | Self::AuthenticatorStateExpire(_) => {
740                if !config.enable_jwk_consensus_updates() {
741                    return Err(UserInputError::Unsupported(
742                        "authenticator state updates not enabled".to_string(),
743                    ));
744                }
745            }
746            Self::RandomnessStateCreate => {
747                if !config.random_beacon() {
748                    return Err(UserInputError::Unsupported(
749                        "random beacon not enabled".to_string(),
750                    ));
751                }
752            }
753            Self::DenyListStateCreate => {
754                if !config.enable_coin_deny_list() {
755                    return Err(UserInputError::Unsupported(
756                        "coin deny list not enabled".to_string(),
757                    ));
758                }
759            }
760            Self::BridgeStateCreate(_) => {
761                if !config.bridge() {
762                    return Err(UserInputError::Unsupported(
763                        "bridge not enabled".to_string(),
764                    ));
765                }
766            }
767            Self::BridgeCommitteeInit(_) => {
768                if !config.bridge() {
769                    return Err(UserInputError::Unsupported(
770                        "bridge not enabled".to_string(),
771                    ));
772                }
773                if !config.should_try_to_finalize_bridge_committee() {
774                    return Err(UserInputError::Unsupported(
775                        "should not try to finalize committee yet".to_string(),
776                    ));
777                }
778            }
779            Self::StoreExecutionTimeObservations(_) => {
780                if !matches!(
781                    config.per_object_congestion_control_mode(),
782                    PerObjectCongestionControlMode::ExecutionTimeEstimate(_)
783                ) {
784                    return Err(UserInputError::Unsupported(
785                        "execution time estimation not enabled".to_string(),
786                    ));
787                }
788            }
789            Self::AccumulatorRootCreate => {
790                if !config.create_root_accumulator_object() {
791                    return Err(UserInputError::Unsupported(
792                        "accumulators not enabled".to_string(),
793                    ));
794                }
795            }
796            Self::CoinRegistryCreate => {
797                if !config.enable_coin_registry() {
798                    return Err(UserInputError::Unsupported(
799                        "coin registry not enabled".to_string(),
800                    ));
801                }
802            }
803            Self::DisplayRegistryCreate => {
804                if !config.enable_display_registry() {
805                    return Err(UserInputError::Unsupported(
806                        "display registry not enabled".to_string(),
807                    ));
808                }
809            }
810            Self::AddressAliasStateCreate => {
811                if !config.address_aliases() {
812                    return Err(UserInputError::Unsupported(
813                        "address aliases not enabled".to_string(),
814                    ));
815                }
816            }
817            Self::WriteAccumulatorStorageCost(_) => {
818                if !config.enable_accumulators() {
819                    return Err(UserInputError::Unsupported(
820                        "accumulators not enabled".to_string(),
821                    ));
822                }
823            }
824            Self::ForwardingAddressRegistryCreate => {
825                if !config.create_forwarding_address_registry() {
826                    return Err(UserInputError::Unsupported(
827                        "forwarding address registry not enabled".to_string(),
828                    ));
829                }
830            }
831            Self::FreezeListCreate => {
832                if !config.create_freeze_list() {
833                    return Err(UserInputError::Unsupported(
834                        "freeze list not enabled".to_string(),
835                    ));
836                }
837            }
838        }
839        Ok(())
840    }
841}
842
843impl CallArg {
844    fn input_objects(&self) -> Vec<InputObjectKind> {
845        match self {
846            CallArg::Pure(_) => vec![],
847            CallArg::Object(ObjectArg::ImmOrOwnedObject(object_ref)) => {
848                if ParsedDigest::is_coin_reservation_digest(&object_ref.2) {
849                    vec![]
850                } else {
851                    vec![InputObjectKind::ImmOrOwnedMoveObject(*object_ref)]
852                }
853            }
854            CallArg::Object(ObjectArg::SharedObject {
855                id,
856                initial_shared_version,
857                mutability,
858            }) => vec![InputObjectKind::SharedMoveObject {
859                id: *id,
860                initial_shared_version: *initial_shared_version,
861                mutability: *mutability,
862            }],
863            // Receiving objects are not part of the input objects.
864            CallArg::Object(ObjectArg::Receiving(_)) => vec![],
865            // While we do read accumulator state when processing withdraws,
866            // this really happened at scheduling time instead of execution time.
867            // Hence we do not need to depend on the accumulator object in withdraws.
868            CallArg::FundsWithdrawal(_) => vec![],
869        }
870    }
871
872    fn receiving_objects(&self) -> Vec<ObjectRef> {
873        match self {
874            CallArg::Pure(_) => vec![],
875            CallArg::Object(o) => match o {
876                ObjectArg::ImmOrOwnedObject(_) => vec![],
877                ObjectArg::SharedObject { .. } => vec![],
878                ObjectArg::Receiving(obj_ref) => vec![*obj_ref],
879            },
880            CallArg::FundsWithdrawal(_) => vec![],
881        }
882    }
883
884    pub fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
885        match self {
886            CallArg::Pure(p) => {
887                fp_ensure!(
888                    p.len() < config.max_pure_argument_size() as usize,
889                    UserInputError::SizeLimitExceeded {
890                        limit: "maximum pure argument size".to_string(),
891                        value: config.max_pure_argument_size().to_string()
892                    }
893                );
894            }
895            CallArg::Object(o) => match o {
896                ObjectArg::ImmOrOwnedObject(obj_ref)
897                    if ParsedDigest::is_coin_reservation_digest(&obj_ref.2) =>
898                {
899                    if !config.enable_coin_reservation_obj_refs() {
900                        return Err(UserInputError::Unsupported(
901                            "coin reservation backward compatibility layer is not enabled"
902                                .to_string(),
903                        ));
904                    }
905                }
906                ObjectArg::ImmOrOwnedObject(_) => (),
907                ObjectArg::SharedObject { mutability, .. } => match mutability {
908                    SharedObjectMutability::Mutable | SharedObjectMutability::Immutable => (),
909                    SharedObjectMutability::NonExclusiveWrite => {
910                        if !config.enable_non_exclusive_writes() {
911                            return Err(UserInputError::Unsupported(
912                                "User transactions cannot use SharedObjectMutability::NonExclusiveWrite".to_string(),
913                            ));
914                        }
915                    }
916                },
917
918                ObjectArg::Receiving(_) => {
919                    if !config.receive_objects() {
920                        return Err(UserInputError::Unsupported(format!(
921                            "receiving objects is not supported at {:?}",
922                            config.version
923                        )));
924                    }
925                }
926            },
927            CallArg::FundsWithdrawal(w) => {
928                fp_ensure!(
929                    check_accumulator_type_bounds(config, &w.type_arg.to_type_tag()),
930                    UserInputError::SizeLimitExceeded {
931                        limit: "maximum type nodes in a funds accumulator type".to_string(),
932                        value: config.max_accumulator_type_nodes().to_string()
933                    }
934                );
935            }
936        }
937        Ok(())
938    }
939}
940
941impl From<bool> for CallArg {
942    fn from(b: bool) -> Self {
943        // unwrap safe because every u8 value is BCS-serializable
944        CallArg::Pure(bcs::to_bytes(&b).unwrap())
945    }
946}
947
948impl From<u8> for CallArg {
949    fn from(n: u8) -> Self {
950        // unwrap safe because every u8 value is BCS-serializable
951        CallArg::Pure(bcs::to_bytes(&n).unwrap())
952    }
953}
954
955impl From<u16> for CallArg {
956    fn from(n: u16) -> Self {
957        // unwrap safe because every u16 value is BCS-serializable
958        CallArg::Pure(bcs::to_bytes(&n).unwrap())
959    }
960}
961
962impl From<u32> for CallArg {
963    fn from(n: u32) -> Self {
964        // unwrap safe because every u32 value is BCS-serializable
965        CallArg::Pure(bcs::to_bytes(&n).unwrap())
966    }
967}
968
969impl From<u64> for CallArg {
970    fn from(n: u64) -> Self {
971        // unwrap safe because every u64 value is BCS-serializable
972        CallArg::Pure(bcs::to_bytes(&n).unwrap())
973    }
974}
975
976impl From<u128> for CallArg {
977    fn from(n: u128) -> Self {
978        // unwrap safe because every u128 value is BCS-serializable
979        CallArg::Pure(bcs::to_bytes(&n).unwrap())
980    }
981}
982
983impl From<&Vec<u8>> for CallArg {
984    fn from(v: &Vec<u8>) -> Self {
985        // unwrap safe because every vec<u8> value is BCS-serializable
986        CallArg::Pure(bcs::to_bytes(v).unwrap())
987    }
988}
989
990impl From<ObjectRef> for CallArg {
991    fn from(obj: ObjectRef) -> Self {
992        CallArg::Object(ObjectArg::ImmOrOwnedObject(obj))
993    }
994}
995
996impl ObjectArg {
997    pub const SUI_SYSTEM_MUT: Self = Self::SharedObject {
998        id: SUI_SYSTEM_STATE_OBJECT_ID,
999        initial_shared_version: SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
1000        mutability: SharedObjectMutability::Mutable,
1001    };
1002
1003    pub fn id(&self) -> ObjectID {
1004        match self {
1005            ObjectArg::Receiving((id, _, _))
1006            | ObjectArg::ImmOrOwnedObject((id, _, _))
1007            | ObjectArg::SharedObject { id, .. } => *id,
1008        }
1009    }
1010}
1011
1012// Add package IDs, `ObjectID`, for types defined in modules.
1013fn add_type_input_packages(packages: &mut BTreeSet<ObjectID>, type_argument: &TypeInput) {
1014    let mut stack = vec![type_argument];
1015    while let Some(cur) = stack.pop() {
1016        match cur {
1017            TypeInput::Bool
1018            | TypeInput::U8
1019            | TypeInput::U64
1020            | TypeInput::U128
1021            | TypeInput::Address
1022            | TypeInput::Signer
1023            | TypeInput::U16
1024            | TypeInput::U32
1025            | TypeInput::U256 => (),
1026            TypeInput::Vector(inner) => stack.push(inner),
1027            TypeInput::Struct(struct_tag) => {
1028                packages.insert(struct_tag.address.into());
1029                stack.extend(struct_tag.type_params.iter())
1030            }
1031        }
1032    }
1033}
1034
1035/// A series of commands where the results of one command can be used in future
1036/// commands
1037#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1038pub struct ProgrammableTransaction {
1039    /// Input objects or primitive values
1040    pub inputs: Vec<CallArg>,
1041    /// The commands to be executed sequentially. A failure in any command will
1042    /// result in the failure of the entire transaction.
1043    pub commands: Vec<Command>,
1044}
1045
1046#[cfg(feature = "testing")]
1047static GASLESS_TOKENS_FOR_TESTING: RwLock<Vec<(String, u64)>> = RwLock::new(Vec::new());
1048
1049#[cfg(feature = "testing")]
1050pub fn add_gasless_token_for_testing(type_string: String, min_transfer: u64) {
1051    GASLESS_TOKENS_FOR_TESTING
1052        .write()
1053        .unwrap()
1054        .push((type_string, min_transfer));
1055}
1056
1057#[cfg(feature = "testing")]
1058pub fn clear_gasless_tokens_for_testing() {
1059    GASLESS_TOKENS_FOR_TESTING.write().unwrap().clear();
1060}
1061
1062impl ProgrammableTransaction {
1063    pub fn validate_argument_indices(&self) -> UserInputResult {
1064        for (command_idx, command) in self.commands.iter().enumerate() {
1065            for (argument_idx, argument) in command.arguments().enumerate() {
1066                let index = match argument {
1067                    Argument::Input(index) if *index as usize >= self.inputs.len() => *index,
1068                    Argument::Result(index) | Argument::NestedResult(index, _)
1069                        if *index as usize >= command_idx =>
1070                    {
1071                        *index
1072                    }
1073                    Argument::GasCoin
1074                    | Argument::Input(_)
1075                    | Argument::Result(_)
1076                    | Argument::NestedResult(_, _) => continue,
1077                };
1078                return Err(UserInputError::InvalidArgumentIndex {
1079                    command_idx,
1080                    argument_idx,
1081                    index,
1082                });
1083            }
1084        }
1085        Ok(())
1086    }
1087
1088    pub fn has_shared_inputs(&self) -> bool {
1089        self.inputs
1090            .iter()
1091            .any(|input| matches!(input, CallArg::Object(ObjectArg::SharedObject { .. })))
1092    }
1093
1094    pub fn validate_gasless_transaction(&self, config: &ProtocolConfig) -> UserInputResult {
1095        fp_ensure!(
1096            !self.commands.is_empty(),
1097            UserInputError::Unsupported(
1098                "Gasless transactions must have at least one command".to_string()
1099            )
1100        );
1101
1102        for input in &self.inputs {
1103            match input {
1104                CallArg::Pure(_) | CallArg::FundsWithdrawal(_) => {}
1105                CallArg::Object(
1106                    ObjectArg::ImmOrOwnedObject(_) | ObjectArg::SharedObject { .. },
1107                ) => {}
1108                CallArg::Object(ObjectArg::Receiving(_)) => {
1109                    return Err(UserInputError::Unsupported(
1110                        "Gasless transactions do not support Receiving object inputs".to_string(),
1111                    ));
1112                }
1113            }
1114        }
1115
1116        let allowed_token_types = get_gasless_allowed_token_types(config);
1117
1118        for command in &self.commands {
1119            command.validate_gasless_transaction(&allowed_token_types)?;
1120        }
1121
1122        self.validate_gasless_inputs(config)?;
1123
1124        Ok(())
1125    }
1126
1127    fn validate_gasless_inputs(&self, config: &ProtocolConfig) -> UserInputResult {
1128        let mut used_inputs = vec![false; self.inputs.len()];
1129        for idx in self.commands.iter().flat_map(|cmd| cmd.input_arguments()) {
1130            if let Some(slot) = used_inputs.get_mut(idx as usize) {
1131                *slot = true;
1132            }
1133        }
1134
1135        let max_unused_pure = config.get_gasless_max_unused_inputs();
1136        let max_pure_bytes = config.get_gasless_max_pure_input_bytes();
1137        let mut unused_pure_count = 0u64;
1138
1139        for (i, input) in self.inputs.iter().enumerate() {
1140            let is_used = used_inputs[i];
1141            match input {
1142                CallArg::Pure(bytes) => {
1143                    fp_ensure!(
1144                        bytes.len() as u64 <= max_pure_bytes,
1145                        UserInputError::Unsupported(format!(
1146                            "Input {} has size {} bytes, but gasless transactions \
1147                             allow at most {} bytes per Pure input",
1148                            i,
1149                            bytes.len(),
1150                            max_pure_bytes
1151                        ))
1152                    );
1153                    if !is_used {
1154                        unused_pure_count += 1;
1155                    }
1156                }
1157                CallArg::Object(_) if !is_used => {
1158                    return Err(UserInputError::Unsupported(format!(
1159                        "Gasless transactions do not allow unused Object inputs (input {})",
1160                        i
1161                    )));
1162                }
1163                CallArg::FundsWithdrawal(_) if !is_used => {
1164                    return Err(UserInputError::Unsupported(format!(
1165                        "Gasless transactions do not allow unused FundsWithdrawal inputs (input {})",
1166                        i
1167                    )));
1168                }
1169                CallArg::Object(_) | CallArg::FundsWithdrawal(_) => {}
1170            }
1171        }
1172
1173        fp_ensure!(
1174            unused_pure_count <= max_unused_pure,
1175            UserInputError::Unsupported(format!(
1176                "Gasless transactions allow at most {} unused Pure inputs, but found {}",
1177                max_unused_pure, unused_pure_count
1178            ))
1179        );
1180
1181        Ok(())
1182    }
1183}
1184
1185/// Caches gasless allowed token types for the most recently seen protocol version.
1186pub fn get_gasless_allowed_token_types(config: &ProtocolConfig) -> Arc<BTreeMap<TypeTag, u64>> {
1187    #[allow(clippy::type_complexity)]
1188    static CACHE: RwLock<Option<(u64, Arc<BTreeMap<TypeTag, u64>>)>> = RwLock::new(None);
1189
1190    let version = config.version.as_u64();
1191
1192    // Fast path: read lock only.
1193    if let Some((v, map)) = CACHE.read().unwrap().as_ref()
1194        && *v == version
1195    {
1196        return apply_test_token_overrides(Arc::clone(map));
1197    }
1198
1199    // Parse from ProtocolConfig if it changed.
1200    let mut cache = CACHE.write().unwrap();
1201    if let Some((v, map)) = cache.as_ref()
1202        && *v == version
1203    {
1204        return apply_test_token_overrides(Arc::clone(map));
1205    }
1206    let map: BTreeMap<TypeTag, u64> = config
1207        .gasless_allowed_token_types()
1208        .iter()
1209        .map(|(s, min_amount)| {
1210            let tag: TypeTag = s
1211                .parse()
1212                .unwrap_or_else(|e| panic!("invalid gasless token type {s:?}: {e}"));
1213            (tag, *min_amount)
1214        })
1215        .collect();
1216    let arc = Arc::new(map);
1217    *cache = Some((version, Arc::clone(&arc)));
1218    apply_test_token_overrides(arc)
1219}
1220
1221fn apply_test_token_overrides(base: Arc<BTreeMap<TypeTag, u64>>) -> Arc<BTreeMap<TypeTag, u64>> {
1222    #[cfg(feature = "testing")]
1223    {
1224        let overrides = GASLESS_TOKENS_FOR_TESTING.read().unwrap();
1225        if !overrides.is_empty() {
1226            let mut types = (*base).clone();
1227            for (s, min_transfer) in overrides.iter() {
1228                match s.parse() {
1229                    Ok(tag) => {
1230                        types.insert(tag, *min_transfer);
1231                    }
1232                    Err(e) => {
1233                        debug_fatal!("invalid gasless token override {s:?}: {e}");
1234                    }
1235                }
1236            }
1237            return Arc::new(types);
1238        }
1239    }
1240    base
1241}
1242
1243/// A single command in a programmable transaction.
1244#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1245pub enum Command {
1246    /// A call to either an entry or a public Move function
1247    MoveCall(Box<ProgrammableMoveCall>),
1248    /// `(Vec<forall T:key+store. T>, address)`
1249    /// It sends n-objects to the specified address. These objects must have store
1250    /// (public transfer) and either the previous owner must be an address or the object must
1251    /// be newly created.
1252    TransferObjects(Vec<Argument>, Argument),
1253    /// `(&mut Coin<T>, Vec<u64>)` -> `Vec<Coin<T>>`
1254    /// It splits off some amounts into a new coins with those amounts
1255    SplitCoins(Argument, Vec<Argument>),
1256    /// `(&mut Coin<T>, Vec<Coin<T>>)`
1257    /// It merges n-coins into the first coin
1258    MergeCoins(Argument, Vec<Argument>),
1259    /// Publishes a Move package. It takes the package bytes and a list of the package's transitive
1260    /// dependencies to link against on-chain.
1261    Publish(Vec<Vec<u8>>, Vec<ObjectID>),
1262    /// `forall T: Vec<T> -> vector<T>`
1263    /// Given n-values of the same type, it constructs a vector. For non objects or an empty vector,
1264    /// the type tag must be specified.
1265    MakeMoveVec(Option<TypeInput>, Vec<Argument>),
1266    /// Upgrades a Move package
1267    /// Takes (in order):
1268    /// 1. A vector of serialized modules for the package.
1269    /// 2. A vector of object ids for the transitive dependencies of the new package.
1270    /// 3. The object ID of the package being upgraded.
1271    /// 4. An argument holding the `UpgradeTicket` that must have been produced from an earlier command in the same
1272    ///    programmable transaction.
1273    Upgrade(Vec<Vec<u8>>, Vec<ObjectID>, ObjectID, Argument),
1274}
1275
1276/// An argument to a programmable transaction command
1277#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, Deserialize)]
1278pub enum Argument {
1279    /// The gas coin. The gas coin can only be used by-ref, except for with
1280    /// `TransferObjects`, which can use it by-value.
1281    GasCoin,
1282    /// One of the input objects or primitive values (from
1283    /// `ProgrammableTransaction` inputs)
1284    Input(u16),
1285    /// The result of another command (from `ProgrammableTransaction` commands)
1286    Result(u16),
1287    /// Like a `Result` but it accesses a nested result. Currently, the only usage
1288    /// of this is to access a value from a Move call with multiple return values.
1289    NestedResult(u16, u16),
1290}
1291
1292/// The command for calling a Move function, either an entry function or a public
1293/// function (which cannot return references).
1294#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1295pub struct ProgrammableMoveCall {
1296    /// The package containing the module and function.
1297    pub package: ObjectID,
1298    /// The specific module in the package containing the function.
1299    pub module: String,
1300    /// The function to be called.
1301    pub function: String,
1302    /// The type arguments to the function.
1303    pub type_arguments: Vec<TypeInput>,
1304    /// The arguments to the function.
1305    pub arguments: Vec<Argument>,
1306}
1307
1308impl ProgrammableMoveCall {
1309    fn input_objects(&self) -> Vec<InputObjectKind> {
1310        let ProgrammableMoveCall {
1311            package,
1312            type_arguments,
1313            ..
1314        } = self;
1315        let mut packages = BTreeSet::from([*package]);
1316        for type_argument in type_arguments {
1317            add_type_input_packages(&mut packages, type_argument)
1318        }
1319        packages
1320            .into_iter()
1321            .map(InputObjectKind::MovePackage)
1322            .collect()
1323    }
1324
1325    pub fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
1326        let is_blocked = BLOCKED_MOVE_FUNCTIONS.contains(&(
1327            self.package,
1328            self.module.as_str(),
1329            self.function.as_str(),
1330        ));
1331        fp_ensure!(!is_blocked, UserInputError::BlockedMoveFunction);
1332        let mut type_arguments_count = 0;
1333        for tag in &self.type_arguments {
1334            type_input_validity_check(tag, config, &mut type_arguments_count)?;
1335        }
1336        fp_ensure!(
1337            self.arguments.len() < config.max_arguments() as usize,
1338            UserInputError::SizeLimitExceeded {
1339                limit: "maximum arguments in a move call".to_string(),
1340                value: config.max_arguments().to_string()
1341            }
1342        );
1343        if config.validate_identifier_inputs() {
1344            fp_ensure!(
1345                identifier::is_valid(&self.module),
1346                UserInputError::InvalidIdentifier {
1347                    error: self.module.clone()
1348                }
1349            );
1350            fp_ensure!(
1351                identifier::is_valid(&self.function),
1352                UserInputError::InvalidIdentifier {
1353                    error: self.module.clone()
1354                }
1355            );
1356        }
1357        Ok(())
1358    }
1359
1360    fn validate_gasless_transaction(
1361        &self,
1362        allowed_token_types: &BTreeMap<TypeTag, u64>,
1363    ) -> UserInputResult {
1364        type FunctionIdent = (AccountAddress, &'static IdentStr, &'static IdentStr);
1365
1366        enum TypeArgConstraint {
1367            /// Type arg is the fund type directly (e.g. `send_funds<USDC>`).
1368            FundType,
1369            /// Type arg is `Balance<T>`; extract `T` as the fund type.
1370            BalanceType,
1371        }
1372        use TypeArgConstraint::*;
1373
1374        const SUI_BALANCE_SEND_FUNDS: FunctionIdent = (
1375            SUI_FRAMEWORK_ADDRESS,
1376            BALANCE_MODULE_NAME,
1377            BALANCE_SEND_FUNDS_FUNCTION_NAME,
1378        );
1379        const SUI_BALANCE_REDEEM_FUNDS: FunctionIdent = (
1380            SUI_FRAMEWORK_ADDRESS,
1381            BALANCE_MODULE_NAME,
1382            BALANCE_REDEEM_FUNDS_FUNCTION_NAME,
1383        );
1384        const SUI_BALANCE_SPLIT: FunctionIdent = (
1385            SUI_FRAMEWORK_ADDRESS,
1386            BALANCE_MODULE_NAME,
1387            BALANCE_SPLIT_FUNCTION_NAME,
1388        );
1389        const SUI_BALANCE_ZERO: FunctionIdent = (
1390            SUI_FRAMEWORK_ADDRESS,
1391            BALANCE_MODULE_NAME,
1392            BALANCE_ZERO_FUNCTION_NAME,
1393        );
1394        const SUI_FUNDS_ACCUMULATOR_WITHDRAWAL_SPLIT: FunctionIdent = (
1395            SUI_FRAMEWORK_ADDRESS,
1396            FUNDS_ACCUMULATOR_MODULE_NAME,
1397            WITHDRAWAL_SPLIT_FUNC_NAME,
1398        );
1399        const SUI_COIN_INTO_BALANCE: FunctionIdent = (
1400            SUI_FRAMEWORK_ADDRESS,
1401            COIN_MODULE_NAME,
1402            INTO_BALANCE_FUNC_NAME,
1403        );
1404        const SUI_COIN_REDEEM_FUNDS: FunctionIdent = (
1405            SUI_FRAMEWORK_ADDRESS,
1406            COIN_MODULE_NAME,
1407            REDEEM_FUNDS_FUNC_NAME,
1408        );
1409        const SUI_COIN_SEND_FUNDS: FunctionIdent = (
1410            SUI_FRAMEWORK_ADDRESS,
1411            COIN_MODULE_NAME,
1412            SEND_FUNDS_FUNC_NAME,
1413        );
1414        const SUI_COIN_PUT: FunctionIdent =
1415            (SUI_FRAMEWORK_ADDRESS, COIN_MODULE_NAME, PUT_FUNC_NAME);
1416
1417        const GASLESS_FUNCTIONS: &[(FunctionIdent, &[Option<TypeArgConstraint>])] = &[
1418            (SUI_BALANCE_SEND_FUNDS, &[Some(FundType)]),
1419            (SUI_BALANCE_REDEEM_FUNDS, &[Some(FundType)]),
1420            (SUI_BALANCE_SPLIT, &[Some(FundType)]),
1421            (SUI_BALANCE_ZERO, &[Some(FundType)]),
1422            (SUI_FUNDS_ACCUMULATOR_WITHDRAWAL_SPLIT, &[Some(BalanceType)]),
1423            (SUI_COIN_INTO_BALANCE, &[Some(FundType)]),
1424            (SUI_COIN_REDEEM_FUNDS, &[Some(FundType)]),
1425            (SUI_COIN_SEND_FUNDS, &[Some(FundType)]),
1426            (SUI_COIN_PUT, &[Some(FundType)]),
1427        ];
1428
1429        let Some((_, type_arg_constraints)) =
1430            GASLESS_FUNCTIONS
1431                .iter()
1432                .find(|((addr, module, function), _)| {
1433                    *addr == AccountAddress::from(self.package)
1434                        && module.as_str() == self.module
1435                        && function.as_str() == self.function
1436                })
1437        else {
1438            return Err(UserInputError::Unsupported(format!(
1439                "Function {}::{}::{} is not supported in gasless transactions",
1440                self.package, self.module, self.function
1441            )));
1442        };
1443
1444        fp_ensure!(
1445            type_arg_constraints.len() == self.type_arguments.len(),
1446            UserInputError::Unsupported(format!(
1447                "Function {}::{}::{} requires {} type arguments, but {} were provided",
1448                self.package,
1449                self.module,
1450                self.function,
1451                type_arg_constraints.len(),
1452                self.type_arguments.len()
1453            ))
1454        );
1455
1456        for (type_arg_constraint, type_input) in type_arg_constraints
1457            .iter()
1458            .zip_debug_eq(&self.type_arguments)
1459        {
1460            let Some(type_arg_constraint) = type_arg_constraint else {
1461                continue;
1462            };
1463            let type_arg = type_input.to_type_tag().map_err(|e| {
1464                UserInputError::Unsupported(format!(
1465                    "Failed to parse type argument {type_input} as a type tag: {e}"
1466                ))
1467            })?;
1468            let fund_type = match type_arg_constraint {
1469                TypeArgConstraint::FundType => type_arg,
1470                TypeArgConstraint::BalanceType => Balance::maybe_get_balance_type_param(&type_arg)
1471                    .ok_or_else(|| {
1472                        UserInputError::Unsupported(format!(
1473                            "Expected a type Balance<_> but got {type_input}",
1474                        ))
1475                    })?,
1476            };
1477            fp_ensure!(
1478                allowed_token_types.contains_key(&fund_type),
1479                UserInputError::Unsupported(format!(
1480                    "Fund type {fund_type} is not currently allowed in gasless transactions"
1481                ))
1482            );
1483        }
1484        Ok(())
1485    }
1486}
1487
1488impl Command {
1489    pub fn move_call(
1490        package: ObjectID,
1491        module: Identifier,
1492        function: Identifier,
1493        type_arguments: Vec<TypeTag>,
1494        arguments: Vec<Argument>,
1495    ) -> Self {
1496        let module = module.to_string();
1497        let function = function.to_string();
1498        let type_arguments = type_arguments.into_iter().map(TypeInput::from).collect();
1499        Command::MoveCall(Box::new(ProgrammableMoveCall {
1500            package,
1501            module,
1502            function,
1503            type_arguments,
1504            arguments,
1505        }))
1506    }
1507
1508    pub fn make_move_vec(ty: Option<TypeTag>, args: Vec<Argument>) -> Self {
1509        Command::MakeMoveVec(ty.map(TypeInput::from), args)
1510    }
1511
1512    fn input_objects(&self) -> Vec<InputObjectKind> {
1513        match self {
1514            Command::Upgrade(_, deps, package_id, _) => deps
1515                .iter()
1516                .map(|id| InputObjectKind::MovePackage(*id))
1517                .chain(Some(InputObjectKind::MovePackage(*package_id)))
1518                .collect(),
1519            Command::Publish(_, deps) => deps
1520                .iter()
1521                .map(|id| InputObjectKind::MovePackage(*id))
1522                .collect(),
1523            Command::MoveCall(c) => c.input_objects(),
1524            Command::MakeMoveVec(Some(t), _) => {
1525                let mut packages = BTreeSet::new();
1526                add_type_input_packages(&mut packages, t);
1527                packages
1528                    .into_iter()
1529                    .map(InputObjectKind::MovePackage)
1530                    .collect()
1531            }
1532            Command::MakeMoveVec(None, _)
1533            | Command::TransferObjects(_, _)
1534            | Command::SplitCoins(_, _)
1535            | Command::MergeCoins(_, _) => vec![],
1536        }
1537    }
1538
1539    fn non_system_packages_to_be_published(&self) -> Option<&Vec<Vec<u8>>> {
1540        match self {
1541            Command::Upgrade(v, _, _, _) => Some(v),
1542            Command::Publish(v, _) => Some(v),
1543            Command::MoveCall(_)
1544            | Command::TransferObjects(_, _)
1545            | Command::SplitCoins(_, _)
1546            | Command::MergeCoins(_, _)
1547            | Command::MakeMoveVec(_, _) => None,
1548        }
1549    }
1550
1551    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
1552        match self {
1553            Command::MoveCall(call) => call.validity_check(config)?,
1554            Command::TransferObjects(args, _)
1555            | Command::MergeCoins(_, args)
1556            | Command::SplitCoins(_, args) => {
1557                fp_ensure!(!args.is_empty(), UserInputError::EmptyCommandInput);
1558                fp_ensure!(
1559                    args.len() < config.max_arguments() as usize,
1560                    UserInputError::SizeLimitExceeded {
1561                        limit: "maximum arguments in a programmable transaction command"
1562                            .to_string(),
1563                        value: config.max_arguments().to_string()
1564                    }
1565                );
1566            }
1567            Command::MakeMoveVec(ty_opt, args) => {
1568                // ty_opt.is_none() ==> !args.is_empty()
1569                fp_ensure!(
1570                    ty_opt.is_some() || !args.is_empty(),
1571                    UserInputError::EmptyCommandInput
1572                );
1573                if let Some(ty) = ty_opt {
1574                    let mut type_arguments_count = 0;
1575                    type_input_validity_check(ty, config, &mut type_arguments_count)?;
1576                }
1577                fp_ensure!(
1578                    args.len() < config.max_arguments() as usize,
1579                    UserInputError::SizeLimitExceeded {
1580                        limit: "maximum arguments in a programmable transaction command"
1581                            .to_string(),
1582                        value: config.max_arguments().to_string()
1583                    }
1584                );
1585            }
1586            Command::Publish(modules, deps) | Command::Upgrade(modules, deps, _, _) => {
1587                fp_ensure!(!modules.is_empty(), UserInputError::EmptyCommandInput);
1588                fp_ensure!(
1589                    modules.len() < config.max_modules_in_publish() as usize,
1590                    UserInputError::SizeLimitExceeded {
1591                        limit: "maximum modules in a programmable transaction upgrade command"
1592                            .to_string(),
1593                        value: config.max_modules_in_publish().to_string()
1594                    }
1595                );
1596                if let Some(max_package_dependencies) = config.max_package_dependencies_as_option()
1597                {
1598                    fp_ensure!(
1599                        deps.len() < max_package_dependencies as usize,
1600                        UserInputError::SizeLimitExceeded {
1601                            limit: "maximum package dependencies".to_string(),
1602                            value: max_package_dependencies.to_string()
1603                        }
1604                    );
1605                };
1606            }
1607        };
1608        Ok(())
1609    }
1610
1611    fn validate_gasless_transaction(
1612        &self,
1613        allowed_token_types: &BTreeMap<TypeTag, u64>,
1614    ) -> UserInputResult {
1615        match self {
1616            Command::MoveCall(call) => call.validate_gasless_transaction(allowed_token_types),
1617            Command::MergeCoins(_, _) | Command::SplitCoins(_, _) => Ok(()),
1618            _ => Err(UserInputError::Unsupported(
1619                "Gasless transactions only support MoveCall, MergeCoins, and SplitCoins commands"
1620                    .to_string(),
1621            )),
1622        }
1623    }
1624
1625    fn is_input_arg_used(&self, input_arg: u16) -> bool {
1626        self.is_argument_used(Argument::Input(input_arg))
1627    }
1628
1629    pub fn is_gas_coin_used(&self) -> bool {
1630        self.is_argument_used(Argument::GasCoin)
1631    }
1632
1633    pub fn is_argument_used(&self, argument: Argument) -> bool {
1634        self.arguments().any(|a| a == &argument)
1635    }
1636
1637    fn input_arguments(&self) -> impl Iterator<Item = u16> + '_ {
1638        self.arguments().filter_map(|arg| match arg {
1639            Argument::Input(i) => Some(*i),
1640            _ => None,
1641        })
1642    }
1643
1644    /// Iterates over arguments in command-argument order.
1645    pub(crate) fn arguments(&self) -> Box<dyn Iterator<Item = &Argument> + '_> {
1646        match self {
1647            Command::MoveCall(c) => Box::new(c.arguments.iter()),
1648            Command::TransferObjects(args, recipient) => {
1649                Box::new(args.iter().chain(std::iter::once(recipient)))
1650            }
1651            Command::SplitCoins(coin, amounts) | Command::MergeCoins(coin, amounts) => {
1652                Box::new(std::iter::once(coin).chain(amounts))
1653            }
1654            Command::MakeMoveVec(_, args) => Box::new(args.iter()),
1655            Command::Upgrade(_, _, _, arg) => Box::new(std::iter::once(arg)),
1656            Command::Publish(_, _) => Box::new(std::iter::empty()),
1657        }
1658    }
1659}
1660
1661pub fn write_sep<T: Display>(
1662    f: &mut Formatter<'_>,
1663    items: impl IntoIterator<Item = T>,
1664    sep: &str,
1665) -> std::fmt::Result {
1666    let mut xs = items.into_iter();
1667    let Some(x) = xs.next() else {
1668        return Ok(());
1669    };
1670    write!(f, "{x}")?;
1671    for x in xs {
1672        write!(f, "{sep}{x}")?;
1673    }
1674    Ok(())
1675}
1676
1677impl ProgrammableTransaction {
1678    pub fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
1679        let ProgrammableTransaction { inputs, commands } = self;
1680        let input_arg_objects = inputs
1681            .iter()
1682            .flat_map(|arg| arg.input_objects())
1683            .collect::<Vec<_>>();
1684        // all objects, not just mutable, must be unique
1685        let mut used = HashSet::new();
1686        if !input_arg_objects.iter().all(|o| used.insert(o.object_id())) {
1687            return Err(UserInputError::DuplicateObjectRefInput);
1688        }
1689        // do not duplicate packages referred to in commands
1690        let command_input_objects: BTreeSet<InputObjectKind> = commands
1691            .iter()
1692            .flat_map(|command| command.input_objects())
1693            .collect();
1694        Ok(input_arg_objects
1695            .into_iter()
1696            .chain(command_input_objects)
1697            .collect())
1698    }
1699
1700    fn receiving_objects(&self) -> Vec<ObjectRef> {
1701        let ProgrammableTransaction { inputs, .. } = self;
1702        inputs
1703            .iter()
1704            .flat_map(|arg| arg.receiving_objects())
1705            .collect()
1706    }
1707
1708    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
1709        let ProgrammableTransaction { inputs, commands } = self;
1710        fp_ensure!(
1711            commands.len() < config.max_programmable_tx_commands() as usize,
1712            UserInputError::SizeLimitExceeded {
1713                limit: "maximum commands in a programmable transaction".to_string(),
1714                value: config.max_programmable_tx_commands().to_string()
1715            }
1716        );
1717        let total_inputs = self.input_objects()?.len() + self.receiving_objects().len();
1718        fp_ensure!(
1719            total_inputs <= config.max_input_objects() as usize,
1720            UserInputError::SizeLimitExceeded {
1721                limit: "maximum input + receiving objects in a transaction".to_string(),
1722                value: config.max_input_objects().to_string()
1723            }
1724        );
1725        fp_ensure!(
1726            inputs.len() <= u16::MAX as usize,
1727            UserInputError::SizeLimitExceeded {
1728                limit: "maximum inputs in a programmable transaction".to_string(),
1729                value: u16::MAX.to_string()
1730            }
1731        );
1732        for input in inputs {
1733            input.validity_check(config)?
1734        }
1735        if let Some(max_publish_commands) = config.max_publish_or_upgrade_per_ptb_as_option() {
1736            let publish_count = commands
1737                .iter()
1738                .filter(|c| matches!(c, Command::Publish(_, _) | Command::Upgrade(_, _, _, _)))
1739                .count() as u64;
1740            fp_ensure!(
1741                publish_count <= max_publish_commands,
1742                UserInputError::MaxPublishCountExceeded {
1743                    max_publish_commands,
1744                    publish_count,
1745                }
1746            );
1747        }
1748        for command in commands {
1749            command.validity_check(config)?;
1750        }
1751        if config.validate_ptb_argument_indices() {
1752            self.validate_argument_indices()?;
1753        }
1754
1755        // If randomness is used, it must be enabled by protocol config.
1756        // A command that uses Random can only be followed by TransferObjects or MergeCoins.
1757        if let Some(random_index) = inputs.iter().position(|obj| {
1758            matches!(
1759                obj,
1760                CallArg::Object(ObjectArg::SharedObject { id, .. }) if *id == SUI_RANDOMNESS_STATE_OBJECT_ID
1761            )
1762        }) {
1763            fp_ensure!(
1764                config.random_beacon(),
1765                UserInputError::Unsupported(
1766                    "randomness is not enabled on this network".to_string(),
1767                )
1768            );
1769            let mut used_random_object = false;
1770            let random_index = random_index.try_into().unwrap();
1771            for command in commands {
1772                if !used_random_object {
1773                    used_random_object = command.is_input_arg_used(random_index);
1774                } else {
1775                    fp_ensure!(
1776                        matches!(
1777                            command,
1778                            Command::TransferObjects(_, _) | Command::MergeCoins(_, _)
1779                        ),
1780                        UserInputError::PostRandomCommandRestrictions
1781                    );
1782                }
1783            }
1784        }
1785
1786        Ok(())
1787    }
1788
1789    /// Return all coin reservation object references used by the transaction inputs.
1790    pub fn coin_reservation_obj_refs(&self) -> impl Iterator<Item = ObjectRef> + '_ {
1791        self.inputs.iter().filter_map(|arg| match arg {
1792            CallArg::Object(ObjectArg::ImmOrOwnedObject(obj_ref))
1793                if ParsedDigest::is_coin_reservation_digest(&obj_ref.2) =>
1794            {
1795                Some(*obj_ref)
1796            }
1797            _ => None,
1798        })
1799    }
1800
1801    pub fn shared_input_objects(&self) -> impl Iterator<Item = SharedInputObject> + '_ {
1802        self.inputs.iter().filter_map(|arg| match arg {
1803            CallArg::Pure(_)
1804            | CallArg::Object(ObjectArg::Receiving(_))
1805            | CallArg::Object(ObjectArg::ImmOrOwnedObject(_))
1806            | CallArg::FundsWithdrawal(_) => None,
1807            CallArg::Object(ObjectArg::SharedObject {
1808                id,
1809                initial_shared_version,
1810                mutability,
1811            }) => Some(SharedInputObject {
1812                id: *id,
1813                initial_shared_version: *initial_shared_version,
1814                mutability: *mutability,
1815            }),
1816        })
1817    }
1818
1819    fn move_calls(&self) -> Vec<(usize, &ObjectID, &str, &str)> {
1820        self.commands
1821            .iter()
1822            .enumerate()
1823            .filter_map(|(idx, command)| match command {
1824                Command::MoveCall(m) => {
1825                    Some((idx, &m.package, m.module.as_str(), m.function.as_str()))
1826                }
1827                _ => None,
1828            })
1829            .collect()
1830    }
1831
1832    pub fn non_system_packages_to_be_published(&self) -> impl Iterator<Item = &Vec<Vec<u8>>> + '_ {
1833        self.commands
1834            .iter()
1835            .filter_map(|q| q.non_system_packages_to_be_published())
1836    }
1837}
1838
1839impl Display for Argument {
1840    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1841        match self {
1842            Argument::GasCoin => write!(f, "GasCoin"),
1843            Argument::Input(i) => write!(f, "Input({i})"),
1844            Argument::Result(i) => write!(f, "Result({i})"),
1845            Argument::NestedResult(i, j) => write!(f, "NestedResult({i},{j})"),
1846        }
1847    }
1848}
1849
1850impl Display for ProgrammableMoveCall {
1851    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1852        let ProgrammableMoveCall {
1853            package,
1854            module,
1855            function,
1856            type_arguments,
1857            arguments,
1858        } = self;
1859        write!(f, "{package}::{module}::{function}")?;
1860        if !type_arguments.is_empty() {
1861            write!(f, "<")?;
1862            write_sep(f, type_arguments, ",")?;
1863            write!(f, ">")?;
1864        }
1865        write!(f, "(")?;
1866        write_sep(f, arguments, ",")?;
1867        write!(f, ")")
1868    }
1869}
1870
1871impl Display for Command {
1872    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1873        match self {
1874            Command::MoveCall(p) => {
1875                write!(f, "MoveCall({p})")
1876            }
1877            Command::MakeMoveVec(ty_opt, elems) => {
1878                write!(f, "MakeMoveVec(")?;
1879                if let Some(ty) = ty_opt {
1880                    write!(f, "Some{ty}")?;
1881                } else {
1882                    write!(f, "None")?;
1883                }
1884                write!(f, ",[")?;
1885                write_sep(f, elems, ",")?;
1886                write!(f, "])")
1887            }
1888            Command::TransferObjects(objs, addr) => {
1889                write!(f, "TransferObjects([")?;
1890                write_sep(f, objs, ",")?;
1891                write!(f, "],{addr})")
1892            }
1893            Command::SplitCoins(coin, amounts) => {
1894                write!(f, "SplitCoins({coin}")?;
1895                write_sep(f, amounts, ",")?;
1896                write!(f, ")")
1897            }
1898            Command::MergeCoins(target, coins) => {
1899                write!(f, "MergeCoins({target},")?;
1900                write_sep(f, coins, ",")?;
1901                write!(f, ")")
1902            }
1903            Command::Publish(_bytes, deps) => {
1904                write!(f, "Publish(_,")?;
1905                write_sep(f, deps, ",")?;
1906                write!(f, ")")
1907            }
1908            Command::Upgrade(_bytes, deps, current_package_id, ticket) => {
1909                write!(f, "Upgrade(_,")?;
1910                write_sep(f, deps, ",")?;
1911                write!(f, ", {current_package_id}")?;
1912                write!(f, ", {ticket}")?;
1913                write!(f, ")")
1914            }
1915        }
1916    }
1917}
1918
1919impl Display for ProgrammableTransaction {
1920    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1921        let ProgrammableTransaction { inputs, commands } = self;
1922        writeln!(f, "Inputs: {inputs:?}")?;
1923        writeln!(f, "Commands: [")?;
1924        for c in commands {
1925            writeln!(f, "  {c},")?;
1926        }
1927        writeln!(f, "]")
1928    }
1929}
1930
1931#[derive(Debug, PartialEq, Eq)]
1932pub struct SharedInputObject {
1933    pub id: ObjectID,
1934    pub initial_shared_version: SequenceNumber,
1935    pub mutability: SharedObjectMutability,
1936}
1937
1938impl SharedInputObject {
1939    pub const SUI_SYSTEM_OBJ: Self = Self {
1940        id: SUI_SYSTEM_STATE_OBJECT_ID,
1941        initial_shared_version: SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
1942        mutability: SharedObjectMutability::Mutable,
1943    };
1944
1945    pub fn id(&self) -> ObjectID {
1946        self.id
1947    }
1948
1949    pub fn id_and_version(&self) -> (ObjectID, SequenceNumber) {
1950        (self.id, self.initial_shared_version)
1951    }
1952
1953    pub fn into_id_and_version(self) -> (ObjectID, SequenceNumber) {
1954        (self.id, self.initial_shared_version)
1955    }
1956
1957    pub fn is_accessed_exclusively(&self) -> bool {
1958        self.mutability.is_exclusive()
1959    }
1960
1961    /// Whether this input object may be mutated by the transaction, either exclusively or non-exclusively.
1962    pub fn may_mutate(&self) -> bool {
1963        match self.mutability {
1964            SharedObjectMutability::Immutable => false,
1965            SharedObjectMutability::Mutable | SharedObjectMutability::NonExclusiveWrite => true,
1966        }
1967    }
1968}
1969
1970impl TransactionKind {
1971    /// present to make migrations to programmable transactions eaier.
1972    /// Will be removed
1973    pub fn programmable(pt: ProgrammableTransaction) -> Self {
1974        TransactionKind::ProgrammableTransaction(pt)
1975    }
1976
1977    pub fn is_system_tx(&self) -> bool {
1978        // Keep this as an exhaustive match so that we can't forget to update it.
1979        match self {
1980            TransactionKind::ChangeEpoch(_)
1981            | TransactionKind::Genesis(_)
1982            | TransactionKind::ConsensusCommitPrologue(_)
1983            | TransactionKind::ConsensusCommitPrologueV2(_)
1984            | TransactionKind::ConsensusCommitPrologueV3(_)
1985            | TransactionKind::ConsensusCommitPrologueV4(_)
1986            | TransactionKind::AuthenticatorStateUpdate(_)
1987            | TransactionKind::RandomnessStateUpdate(_)
1988            | TransactionKind::EndOfEpochTransaction(_)
1989            | TransactionKind::ProgrammableSystemTransaction(_) => true,
1990            TransactionKind::ProgrammableTransaction(_) => false,
1991        }
1992    }
1993
1994    pub fn is_end_of_epoch_tx(&self) -> bool {
1995        matches!(
1996            self,
1997            TransactionKind::EndOfEpochTransaction(_) | TransactionKind::ChangeEpoch(_)
1998        )
1999    }
2000
2001    pub fn is_accumulator_barrier_settle_tx(&self) -> bool {
2002        matches!(self, TransactionKind::ProgrammableSystemTransaction(_))
2003            && self.shared_input_objects().any(|obj| {
2004                obj.id == SUI_ACCUMULATOR_ROOT_OBJECT_ID
2005                    && obj.mutability == SharedObjectMutability::Mutable
2006            })
2007    }
2008
2009    /// Whether this is any accumulator settlement transaction (a settlement chunk or
2010    /// the barrier); every one declares the accumulator root object as a shared input.
2011    pub fn is_accumulator_settle_tx(&self) -> bool {
2012        if let TransactionKind::ProgrammableSystemTransaction(pt) = self {
2013            pt.shared_input_objects()
2014                .any(|obj| obj.id == SUI_ACCUMULATOR_ROOT_OBJECT_ID)
2015        } else {
2016            false
2017        }
2018    }
2019
2020    /// If this is an accumulator barrier settlement transaction, returns its
2021    /// `AccumulatorSettlement` transaction key by extracting epoch and
2022    /// checkpoint_height from the prologue call arguments.
2023    pub fn accumulator_barrier_settlement_key(&self) -> Option<TransactionKey> {
2024        let TransactionKind::ProgrammableSystemTransaction(pt) = self else {
2025            return None;
2026        };
2027        let has_mutable_acc_root = pt.inputs.iter().any(|input| {
2028            matches!(
2029                input,
2030                CallArg::Object(ObjectArg::SharedObject {
2031                    id,
2032                    mutability: SharedObjectMutability::Mutable,
2033                    ..
2034                }) if *id == SUI_ACCUMULATOR_ROOT_OBJECT_ID
2035            )
2036        });
2037        if !has_mutable_acc_root {
2038            return None;
2039        }
2040        // The prologue embeds epoch as Input(1) and checkpoint_height as Input(2),
2041        // both as BCS-encoded u64 pure values.
2042        let epoch = pt.inputs.get(1).and_then(|arg| match arg {
2043            CallArg::Pure(bytes) => bcs::from_bytes::<u64>(bytes).ok(),
2044            _ => None,
2045        })?;
2046        let checkpoint_height = pt.inputs.get(2).and_then(|arg| match arg {
2047            CallArg::Pure(bytes) => bcs::from_bytes::<u64>(bytes).ok(),
2048            _ => None,
2049        })?;
2050        Some(TransactionKey::AccumulatorSettlement(
2051            epoch,
2052            checkpoint_height,
2053        ))
2054    }
2055
2056    /// If this is advance epoch transaction, returns (total gas charged, total gas rebated).
2057    /// TODO: We should use GasCostSummary directly in ChangeEpoch struct, and return that
2058    /// directly.
2059    pub fn get_advance_epoch_tx_gas_summary(&self) -> Option<(u64, u64)> {
2060        let e = match self {
2061            Self::ChangeEpoch(e) => e,
2062            Self::EndOfEpochTransaction(txns) => {
2063                if let EndOfEpochTransactionKind::ChangeEpoch(e) =
2064                    txns.last().expect("at least one end-of-epoch txn required")
2065                {
2066                    e
2067                } else {
2068                    panic!("final end-of-epoch txn must be ChangeEpoch")
2069                }
2070            }
2071            _ => return None,
2072        };
2073
2074        Some((e.computation_charge + e.storage_charge, e.storage_rebate))
2075    }
2076
2077    /// Returns an iterator of all shared input objects used by this transaction.
2078    /// It covers both Call and ChangeEpoch transaction kind, because both makes Move calls.
2079    pub fn shared_input_objects(&self) -> impl Iterator<Item = SharedInputObject> + '_ {
2080        match &self {
2081            Self::ChangeEpoch(_) => {
2082                Either::Left(Either::Left(iter::once(SharedInputObject::SUI_SYSTEM_OBJ)))
2083            }
2084
2085            Self::ConsensusCommitPrologue(_)
2086            | Self::ConsensusCommitPrologueV2(_)
2087            | Self::ConsensusCommitPrologueV3(_)
2088            | Self::ConsensusCommitPrologueV4(_) => {
2089                Either::Left(Either::Left(iter::once(SharedInputObject {
2090                    id: SUI_CLOCK_OBJECT_ID,
2091                    initial_shared_version: SUI_CLOCK_OBJECT_SHARED_VERSION,
2092                    mutability: SharedObjectMutability::Mutable,
2093                })))
2094            }
2095            Self::AuthenticatorStateUpdate(update) => {
2096                Either::Left(Either::Left(iter::once(SharedInputObject {
2097                    id: SUI_AUTHENTICATOR_STATE_OBJECT_ID,
2098                    initial_shared_version: update.authenticator_obj_initial_shared_version,
2099                    mutability: SharedObjectMutability::Mutable,
2100                })))
2101            }
2102            Self::RandomnessStateUpdate(update) => {
2103                Either::Left(Either::Left(iter::once(SharedInputObject {
2104                    id: SUI_RANDOMNESS_STATE_OBJECT_ID,
2105                    initial_shared_version: update.randomness_obj_initial_shared_version,
2106                    mutability: SharedObjectMutability::Mutable,
2107                })))
2108            }
2109            Self::EndOfEpochTransaction(txns) => Either::Left(Either::Right(
2110                txns.iter().flat_map(|txn| txn.shared_input_objects()),
2111            )),
2112            Self::ProgrammableTransaction(pt) | Self::ProgrammableSystemTransaction(pt) => {
2113                Either::Right(Either::Left(pt.shared_input_objects()))
2114            }
2115            Self::Genesis(_) => Either::Right(Either::Right(iter::empty())),
2116        }
2117    }
2118
2119    fn move_calls(&self) -> Vec<(usize, &ObjectID, &str, &str)> {
2120        match &self {
2121            Self::ProgrammableTransaction(pt) => pt.move_calls(),
2122            _ => vec![],
2123        }
2124    }
2125
2126    pub fn receiving_objects(&self) -> Vec<ObjectRef> {
2127        match &self {
2128            TransactionKind::ChangeEpoch(_)
2129            | TransactionKind::Genesis(_)
2130            | TransactionKind::ConsensusCommitPrologue(_)
2131            | TransactionKind::ConsensusCommitPrologueV2(_)
2132            | TransactionKind::ConsensusCommitPrologueV3(_)
2133            | TransactionKind::ConsensusCommitPrologueV4(_)
2134            | TransactionKind::AuthenticatorStateUpdate(_)
2135            | TransactionKind::RandomnessStateUpdate(_)
2136            | TransactionKind::EndOfEpochTransaction(_)
2137            | TransactionKind::ProgrammableSystemTransaction(_) => vec![],
2138            TransactionKind::ProgrammableTransaction(pt) => pt.receiving_objects(),
2139        }
2140    }
2141
2142    /// Return the metadata of each of the input objects for the transaction.
2143    /// For a Move object, we attach the object reference;
2144    /// for a Move package, we provide the object id only since they never change on chain.
2145    /// TODO: use an iterator over references here instead of a Vec to avoid allocations.
2146    pub fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
2147        let input_objects = match &self {
2148            Self::ChangeEpoch(_) => {
2149                vec![InputObjectKind::SharedMoveObject {
2150                    id: SUI_SYSTEM_STATE_OBJECT_ID,
2151                    initial_shared_version: SUI_SYSTEM_STATE_OBJECT_SHARED_VERSION,
2152                    mutability: SharedObjectMutability::Mutable,
2153                }]
2154            }
2155            Self::Genesis(_) => {
2156                vec![]
2157            }
2158            Self::ConsensusCommitPrologue(_)
2159            | Self::ConsensusCommitPrologueV2(_)
2160            | Self::ConsensusCommitPrologueV3(_)
2161            | Self::ConsensusCommitPrologueV4(_) => {
2162                vec![InputObjectKind::SharedMoveObject {
2163                    id: SUI_CLOCK_OBJECT_ID,
2164                    initial_shared_version: SUI_CLOCK_OBJECT_SHARED_VERSION,
2165                    mutability: SharedObjectMutability::Mutable,
2166                }]
2167            }
2168            Self::AuthenticatorStateUpdate(update) => {
2169                vec![InputObjectKind::SharedMoveObject {
2170                    id: SUI_AUTHENTICATOR_STATE_OBJECT_ID,
2171                    initial_shared_version: update.authenticator_obj_initial_shared_version(),
2172                    mutability: SharedObjectMutability::Mutable,
2173                }]
2174            }
2175            Self::RandomnessStateUpdate(update) => {
2176                vec![InputObjectKind::SharedMoveObject {
2177                    id: SUI_RANDOMNESS_STATE_OBJECT_ID,
2178                    initial_shared_version: update.randomness_obj_initial_shared_version(),
2179                    mutability: SharedObjectMutability::Mutable,
2180                }]
2181            }
2182            Self::EndOfEpochTransaction(txns) => {
2183                // Dedup since transactions may have a overlap in input objects.
2184                // Note: it's critical to ensure the order of inputs are deterministic.
2185                let before_dedup: Vec<_> =
2186                    txns.iter().flat_map(|txn| txn.input_objects()).collect();
2187                let mut has_seen = HashSet::new();
2188                let mut after_dedup = vec![];
2189                for obj in before_dedup {
2190                    if has_seen.insert(obj) {
2191                        after_dedup.push(obj);
2192                    }
2193                }
2194                after_dedup
2195            }
2196            Self::ProgrammableTransaction(p) | Self::ProgrammableSystemTransaction(p) => {
2197                return p.input_objects();
2198            }
2199        };
2200        // Ensure that there are no duplicate inputs. This cannot be removed because:
2201        // In [`AuthorityState::check_locks`], we check that there are no duplicate mutable
2202        // input objects, which would have made this check here unnecessary. However we
2203        // do plan to allow shared objects show up more than once in multiple single
2204        // transactions down the line. Once we have that, we need check here to make sure
2205        // the same shared object doesn't show up more than once in the same single
2206        // transaction.
2207        let mut used = HashSet::new();
2208        if !input_objects.iter().all(|o| used.insert(o.object_id())) {
2209            return Err(UserInputError::DuplicateObjectRefInput);
2210        }
2211        Ok(input_objects)
2212    }
2213
2214    pub fn get_funds_withdrawals<'a>(
2215        &'a self,
2216    ) -> impl Iterator<Item = &'a FundsWithdrawalArg> + 'a {
2217        let TransactionKind::ProgrammableTransaction(pt) = &self else {
2218            return Either::Left(iter::empty());
2219        };
2220        Either::Right(pt.inputs.iter().filter_map(|input| {
2221            if let CallArg::FundsWithdrawal(withdraw) = input {
2222                Some(withdraw)
2223            } else {
2224                None
2225            }
2226        }))
2227    }
2228
2229    pub fn get_coin_reservation_obj_refs(&self) -> impl Iterator<Item = ObjectRef> + '_ {
2230        let TransactionKind::ProgrammableTransaction(pt) = &self else {
2231            return Either::Left(iter::empty());
2232        };
2233        Either::Right(pt.coin_reservation_obj_refs())
2234    }
2235
2236    pub fn has_coin_reservations(&self) -> bool {
2237        self.get_coin_reservation_obj_refs().next().is_some()
2238    }
2239
2240    pub fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
2241        match self {
2242            TransactionKind::ProgrammableTransaction(p) => p.validity_check(config)?,
2243            // All transactiond kinds below are assumed to be system,
2244            // and no validity or limit checks are performed.
2245            TransactionKind::ChangeEpoch(_)
2246            | TransactionKind::Genesis(_)
2247            | TransactionKind::ConsensusCommitPrologue(_) => (),
2248            TransactionKind::ConsensusCommitPrologueV2(_) => {
2249                if !config.include_consensus_digest_in_prologue() {
2250                    return Err(UserInputError::Unsupported(
2251                        "ConsensusCommitPrologueV2 is not supported".to_string(),
2252                    ));
2253                }
2254            }
2255            TransactionKind::ConsensusCommitPrologueV3(_) => {
2256                if !config.record_consensus_determined_version_assignments_in_prologue() {
2257                    return Err(UserInputError::Unsupported(
2258                        "ConsensusCommitPrologueV3 is not supported".to_string(),
2259                    ));
2260                }
2261            }
2262            TransactionKind::ConsensusCommitPrologueV4(_) => {
2263                if !config.record_additional_state_digest_in_prologue() {
2264                    return Err(UserInputError::Unsupported(
2265                        "ConsensusCommitPrologueV4 is not supported".to_string(),
2266                    ));
2267                }
2268            }
2269            TransactionKind::EndOfEpochTransaction(txns) => {
2270                if !config.end_of_epoch_transaction_supported() {
2271                    return Err(UserInputError::Unsupported(
2272                        "EndOfEpochTransaction is not supported".to_string(),
2273                    ));
2274                }
2275
2276                for tx in txns {
2277                    tx.validity_check(config)?;
2278                }
2279            }
2280
2281            TransactionKind::AuthenticatorStateUpdate(_) => {
2282                if !config.enable_jwk_consensus_updates() {
2283                    return Err(UserInputError::Unsupported(
2284                        "authenticator state updates not enabled".to_string(),
2285                    ));
2286                }
2287            }
2288            TransactionKind::RandomnessStateUpdate(_) => {
2289                if !config.random_beacon() {
2290                    return Err(UserInputError::Unsupported(
2291                        "randomness state updates not enabled".to_string(),
2292                    ));
2293                }
2294            }
2295            TransactionKind::ProgrammableSystemTransaction(_) => {
2296                if !config.enable_accumulators() {
2297                    return Err(UserInputError::Unsupported(
2298                        "accumulators not enabled".to_string(),
2299                    ));
2300                }
2301            }
2302        };
2303        Ok(())
2304    }
2305
2306    /// number of commands, or 0 if it is a system transaction
2307    pub fn num_commands(&self) -> usize {
2308        match self {
2309            TransactionKind::ProgrammableTransaction(pt) => pt.commands.len(),
2310            _ => 0,
2311        }
2312    }
2313
2314    pub fn iter_commands(&self) -> impl Iterator<Item = &Command> {
2315        match self {
2316            TransactionKind::ProgrammableTransaction(pt) => pt.commands.iter(),
2317            _ => [].iter(),
2318        }
2319    }
2320
2321    /// number of transactions, or 1 if it is a system transaction
2322    pub fn tx_count(&self) -> usize {
2323        match self {
2324            TransactionKind::ProgrammableTransaction(pt) => pt.commands.len(),
2325            _ => 1,
2326        }
2327    }
2328
2329    pub fn name(&self) -> &'static str {
2330        match self {
2331            Self::ChangeEpoch(_) => "ChangeEpoch",
2332            Self::Genesis(_) => "Genesis",
2333            Self::ConsensusCommitPrologue(_) => "ConsensusCommitPrologue",
2334            Self::ConsensusCommitPrologueV2(_) => "ConsensusCommitPrologueV2",
2335            Self::ConsensusCommitPrologueV3(_) => "ConsensusCommitPrologueV3",
2336            Self::ConsensusCommitPrologueV4(_) => "ConsensusCommitPrologueV4",
2337            Self::ProgrammableTransaction(_) => "ProgrammableTransaction",
2338            Self::ProgrammableSystemTransaction(_) => "ProgrammableSystemTransaction",
2339            Self::AuthenticatorStateUpdate(_) => "AuthenticatorStateUpdate",
2340            Self::RandomnessStateUpdate(_) => "RandomnessStateUpdate",
2341            Self::EndOfEpochTransaction(_) => "EndOfEpochTransaction",
2342        }
2343    }
2344}
2345
2346impl Display for TransactionKind {
2347    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2348        let mut writer = String::new();
2349        match &self {
2350            Self::ChangeEpoch(e) => {
2351                writeln!(writer, "Transaction Kind : Epoch Change")?;
2352                writeln!(writer, "New epoch ID : {}", e.epoch)?;
2353                writeln!(writer, "Storage gas reward : {}", e.storage_charge)?;
2354                writeln!(writer, "Computation gas reward : {}", e.computation_charge)?;
2355                writeln!(writer, "Storage rebate : {}", e.storage_rebate)?;
2356                writeln!(writer, "Timestamp : {}", e.epoch_start_timestamp_ms)?;
2357            }
2358            Self::Genesis(_) => {
2359                writeln!(writer, "Transaction Kind : Genesis")?;
2360            }
2361            Self::ConsensusCommitPrologue(p) => {
2362                writeln!(writer, "Transaction Kind : Consensus Commit Prologue")?;
2363                writeln!(writer, "Timestamp : {}", p.commit_timestamp_ms)?;
2364            }
2365            Self::ConsensusCommitPrologueV2(p) => {
2366                writeln!(writer, "Transaction Kind : Consensus Commit Prologue V2")?;
2367                writeln!(writer, "Timestamp : {}", p.commit_timestamp_ms)?;
2368                writeln!(writer, "Consensus Digest: {}", p.consensus_commit_digest)?;
2369            }
2370            Self::ConsensusCommitPrologueV3(p) => {
2371                writeln!(writer, "Transaction Kind : Consensus Commit Prologue V3")?;
2372                writeln!(writer, "Timestamp : {}", p.commit_timestamp_ms)?;
2373                writeln!(writer, "Consensus Digest: {}", p.consensus_commit_digest)?;
2374                writeln!(
2375                    writer,
2376                    "Consensus determined version assignment: {:?}",
2377                    p.consensus_determined_version_assignments
2378                )?;
2379            }
2380            Self::ConsensusCommitPrologueV4(p) => {
2381                writeln!(writer, "Transaction Kind : Consensus Commit Prologue V4")?;
2382                writeln!(writer, "Timestamp : {}", p.commit_timestamp_ms)?;
2383                writeln!(writer, "Consensus Digest: {}", p.consensus_commit_digest)?;
2384                writeln!(
2385                    writer,
2386                    "Consensus determined version assignment: {:?}",
2387                    p.consensus_determined_version_assignments
2388                )?;
2389                writeln!(
2390                    writer,
2391                    "Additional State Digest: {}",
2392                    p.additional_state_digest
2393                )?;
2394            }
2395            Self::ProgrammableTransaction(p) => {
2396                writeln!(writer, "Transaction Kind : Programmable")?;
2397                write!(writer, "{p}")?;
2398            }
2399            Self::ProgrammableSystemTransaction(p) => {
2400                writeln!(writer, "Transaction Kind : Programmable System")?;
2401                write!(writer, "{p}")?;
2402            }
2403            Self::AuthenticatorStateUpdate(_) => {
2404                writeln!(writer, "Transaction Kind : Authenticator State Update")?;
2405            }
2406            Self::RandomnessStateUpdate(_) => {
2407                writeln!(writer, "Transaction Kind : Randomness State Update")?;
2408            }
2409            Self::EndOfEpochTransaction(_) => {
2410                writeln!(writer, "Transaction Kind : End of Epoch Transaction")?;
2411            }
2412        }
2413        write!(f, "{}", writer)
2414    }
2415}
2416
2417#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
2418pub struct GasData {
2419    pub payment: Vec<ObjectRef>,
2420    pub owner: SuiAddress,
2421    pub price: u64,
2422    pub budget: u64,
2423}
2424
2425impl GasData {
2426    pub fn is_unmetered(&self) -> bool {
2427        self.payment.len() == 1
2428            && self.payment[0].0 == ObjectID::ZERO
2429            && self.payment[0].1 == SequenceNumber::default()
2430            && self.payment[0].2 == ObjectDigest::MIN
2431    }
2432}
2433
2434pub fn is_gas_paid_from_address_balance(
2435    gas_data: &GasData,
2436    transaction_kind: &TransactionKind,
2437) -> bool {
2438    gas_data.payment.is_empty()
2439        && matches!(
2440            transaction_kind,
2441            TransactionKind::ProgrammableTransaction(_)
2442        )
2443}
2444
2445pub fn is_gasless_transaction(gas_data: &GasData, transaction_kind: &TransactionKind) -> bool {
2446    is_gas_paid_from_address_balance(gas_data, transaction_kind) && gas_data.price == 0
2447}
2448
2449/// The largest `min_timestamp` or `max_timestamp` (Unix seconds), 9999-12-31T23:59:59Z.
2450pub const MAX_EXPIRATION_TIMESTAMP_SECS: u64 = 253_402_300_799;
2451
2452#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
2453pub enum TransactionExpiration {
2454    /// The transaction has no expiration
2455    None,
2456    /// Validators wont sign a transaction unless the expiration Epoch
2457    /// is greater than or equal to the current epoch
2458    Epoch(EpochId),
2459    /// ValidDuring enables gas payments from address balances.
2460    ///
2461    /// When transactions use address balances for gas payment instead of explicit gas coins,
2462    /// we lose the natural transaction uniqueness and replay prevention that comes from
2463    /// mutation of gas coin objects.
2464    ///
2465    /// By bounding expiration and providing a nonce, validators must only retain
2466    /// executed digests for the maximum possible expiry range to differentiate
2467    /// retries from unique transactions with otherwise identical inputs.
2468    ValidDuring {
2469        /// Transaction invalid before this epoch. Must equal current epoch.
2470        min_epoch: Option<EpochId>,
2471        /// Transaction expires after this epoch. Must equal current epoch
2472        max_epoch: Option<EpochId>,
2473        /// Earliest time (Unix seconds, inclusive) at which the transaction is valid. A quorum
2474        /// must vote to accept the transaction at or after this time by their local clocks, so
2475        /// the commit timestamp can be slightly earlier. A rejected transaction can be submitted
2476        /// again.
2477        min_timestamp: Option<u64>,
2478        /// Latest consensus commit time (Unix seconds, inclusive) at which the transaction is
2479        /// valid. A transaction scheduled by a later commit fails with `TransactionExpired`.
2480        max_timestamp: Option<u64>,
2481        /// Network identifier to prevent cross-chain replay
2482        chain: ChainIdentifier,
2483        /// User-provided uniqueness identifier to differentiate otherwise identical transactions
2484        nonce: u32,
2485    },
2486    /// Everything in `ValidDuring`, plus a restriction on which validators may propose the
2487    /// transaction in consensus.
2488    Validity {
2489        /// Transaction invalid before this epoch. Must equal current epoch.
2490        min_epoch: Option<EpochId>,
2491        /// Transaction expires after this epoch. Must equal current epoch
2492        max_epoch: Option<EpochId>,
2493        /// Earliest time (Unix seconds, inclusive) at which the transaction is valid. A quorum
2494        /// must vote to accept the transaction at or after this time by their local clocks, so
2495        /// the commit timestamp can be slightly earlier. A rejected transaction can be submitted
2496        /// again.
2497        min_timestamp: Option<u64>,
2498        /// Latest consensus commit time (Unix seconds, inclusive) at which the transaction is
2499        /// valid. A transaction scheduled by a later commit fails with `TransactionExpired`.
2500        max_timestamp: Option<u64>,
2501        /// Network identifier to prevent cross-chain replay
2502        chain: ChainIdentifier,
2503        /// User-provided uniqueness identifier to differentiate otherwise identical transactions
2504        nonce: u32,
2505        /// The validators allowed to propose this transaction in consensus, if it restricts them.
2506        allowed_proposers: Option<AllowedProposers>,
2507    },
2508}
2509
2510/// The validators allowed to propose a transaction in consensus. Proposal by any other validator
2511/// is byzantine behavior and invalidates the whole block.
2512#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
2513pub struct AllowedProposers {
2514    /// The epoch whose committee `proposers` indexes into. Committee indices are only meaningful
2515    /// against one committee, so a set recorded for any other epoch is ignored entirely — see
2516    /// `TransactionExpiration::allowed_proposers`.
2517    pub epoch: EpochId,
2518    /// Committee indices of the allowed proposers. Must be strictly increasing, and each index
2519    /// must be within the committee.
2520    ///
2521    /// SIP-45 bounds the length by the gas price: see `MAX_UNPAID_ALLOWED_PROPOSERS`.
2522    #[serde(with = "nonempty_as_vec")]
2523    pub proposers: NonEmpty<u32>,
2524}
2525
2526/// The number of allowed proposers a transaction may name without paying for amplification.
2527/// Beyond this, SIP-45 caps the proposer set at `gas_price / reference_gas_price`.
2528///
2529/// Naming several proposers is also what keeps a transaction submittable when some of them are
2530/// offline, so this is a floor as much as it is an allowance.
2531pub const MAX_UNPAID_ALLOWED_PROPOSERS: u64 = 3;
2532
2533/// SIP-45: the number of consensus submissions a gas price pays for. Every transaction may
2534/// be proposed by `MAX_UNPAID_ALLOWED_PROPOSERS` validators; a gas price of `n` times the
2535/// reference price buys `n`. The single definition behind sizing an explicit proposer set,
2536/// the immediate slots of staggered submission, and the deferral of unpaid duplicates.
2537pub fn paid_proposer_count(gas_price: u64, reference_gas_price: u64) -> u64 {
2538    MAX_UNPAID_ALLOWED_PROPOSERS.max(gas_price / reference_gas_price.max(1))
2539}
2540
2541impl TransactionExpiration {
2542    /// Validators remember all executed transaction digests from the current and previous
2543    /// epoch. Therefore, a one or two epoch validity window provides replay protection.
2544    /// Either the transaction is statically invalid (current epoch not within range) or the
2545    /// validator will remember if the transaction was already executed.
2546    pub fn is_replay_protected(&self) -> bool {
2547        matches!(
2548            self,
2549            TransactionExpiration::ValidDuring {
2550                min_epoch: Some(min_epoch),
2551                max_epoch: Some(max_epoch),
2552                ..
2553            }
2554            | TransactionExpiration::Validity {
2555                min_epoch: Some(min_epoch),
2556                max_epoch: Some(max_epoch),
2557                ..
2558            } if *max_epoch == *min_epoch || *max_epoch == min_epoch.saturating_add(1)
2559        )
2560    }
2561
2562    /// Whether `timestamp_ms` is before `min_timestamp`, which is in seconds. The transaction can
2563    /// become valid later.
2564    pub fn is_not_yet_valid_at(&self, timestamp_ms: u64) -> bool {
2565        match self {
2566            TransactionExpiration::None | TransactionExpiration::Epoch(_) => false,
2567            TransactionExpiration::ValidDuring { min_timestamp, .. }
2568            | TransactionExpiration::Validity { min_timestamp, .. } => {
2569                min_timestamp.is_some_and(|min| timestamp_ms / 1000 < min)
2570            }
2571        }
2572    }
2573
2574    /// Whether `timestamp_ms` is after `max_timestamp`, which is in seconds. The bound covers
2575    /// the whole second it names. The transaction can never become valid.
2576    pub fn is_expired_at(&self, timestamp_ms: u64) -> bool {
2577        // Defined through `first_expired_timestamp_ms`, so that checkpoint execution, which
2578        // uses that timestamp, reproduces the expiry by construction.
2579        self.first_expired_timestamp_ms()
2580            .is_some_and(|first_expired_ms| timestamp_ms >= first_expired_ms)
2581    }
2582
2583    /// The `min_timestamp` (Unix seconds), if there is one.
2584    pub fn min_timestamp(&self) -> Option<u64> {
2585        match self {
2586            TransactionExpiration::None | TransactionExpiration::Epoch(_) => None,
2587            TransactionExpiration::ValidDuring { min_timestamp, .. }
2588            | TransactionExpiration::Validity { min_timestamp, .. } => *min_timestamp,
2589        }
2590    }
2591
2592    /// The earliest timestamp (Unix ms) at which `is_not_yet_valid_at` is false, if there is a
2593    /// `min_timestamp`.
2594    pub fn first_valid_timestamp_ms(&self) -> Option<u64> {
2595        self.min_timestamp().and_then(|min| min.checked_mul(1000))
2596    }
2597
2598    /// The earliest timestamp (Unix ms) at which `is_expired_at` is true, if there is one.
2599    pub fn first_expired_timestamp_ms(&self) -> Option<u64> {
2600        match self {
2601            TransactionExpiration::None | TransactionExpiration::Epoch(_) => None,
2602            TransactionExpiration::ValidDuring { max_timestamp, .. }
2603            | TransactionExpiration::Validity { max_timestamp, .. } => max_timestamp
2604                .and_then(|max| max.checked_add(1))
2605                .and_then(|secs| secs.checked_mul(1000)),
2606        }
2607    }
2608
2609    /// The validators allowed to propose this transaction in consensus during `epoch`.
2610    ///
2611    /// A set recorded for any other epoch indexes into a committee that is not the one deciding
2612    /// this transaction, so it is ignored entirely and the transaction is treated as naming no
2613    /// proposers. The incentive to record the current epoch is on the signer, who is the party
2614    /// the restriction protects; transactions without a usable set may in future be subject to
2615    /// submission delays to limit amplification.
2616    pub fn allowed_proposers(&self, epoch: EpochId) -> Option<&AllowedProposers> {
2617        match self {
2618            TransactionExpiration::Validity {
2619                allowed_proposers: Some(allowed),
2620                ..
2621            } if allowed.epoch == epoch => Some(allowed),
2622            _ => None,
2623        }
2624    }
2625
2626    /// Whether the transaction restricts its proposers during `epoch`. Only such a transaction has
2627    /// its consensus amplification bounded by `validity_check`.
2628    pub fn restricts_proposers(&self, epoch: EpochId) -> bool {
2629        self.allowed_proposers(epoch).is_some()
2630    }
2631
2632    /// Whether `proposer` (an index into `epoch`'s committee) may propose this transaction in
2633    /// consensus.
2634    pub fn is_allowed_proposer(&self, proposer: u32, epoch: EpochId) -> bool {
2635        self.allowed_proposers(epoch).is_none_or(|allowed| {
2636            // The set is strictly increasing, so stop as soon as it passes `proposer`. An
2637            // unsorted set is rejected by validity_check; reading it as a miss here is
2638            // deterministic across validators, which is all block verification requires.
2639            allowed
2640                .proposers
2641                .iter()
2642                .find(|p| **p >= proposer)
2643                .is_some_and(|p| *p == proposer)
2644        })
2645    }
2646}
2647
2648#[enum_dispatch(TransactionDataAPI)]
2649#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
2650pub enum TransactionData {
2651    V1(TransactionDataV1),
2652    // When new variants are introduced, it is important that we check version support
2653    // in the validity_check function based on the protocol config.
2654}
2655
2656#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
2657pub struct TransactionDataV1 {
2658    pub kind: TransactionKind,
2659    pub sender: SuiAddress,
2660    pub gas_data: GasData,
2661    pub expiration: TransactionExpiration,
2662}
2663
2664impl TransactionData {
2665    pub fn as_v1(&self) -> &TransactionDataV1 {
2666        match self {
2667            TransactionData::V1(v1) => v1,
2668        }
2669    }
2670
2671    /// Whether the transaction is protected against replay, given its loaded `input_objects`:
2672    /// it has a `ValidDuring` expiration of at most two epochs, a gas payment object, or an
2673    /// address-owned input or coin reservation among `input_objects`. `input_objects` is only
2674    /// consumed when the expiration and gas payment do not already protect the transaction.
2675    pub fn has_replay_protection(
2676        &self,
2677        input_objects: impl IntoIterator<Item = impl std::borrow::Borrow<ObjectReadResult>>,
2678    ) -> bool {
2679        self.expiration().is_replay_protected()
2680            || !self.gas_data().payment.is_empty()
2681            || input_objects
2682                .into_iter()
2683                .any(|object| object.borrow().is_replay_protected_input())
2684    }
2685    fn new_system_transaction(kind: TransactionKind) -> Self {
2686        // assert transaction kind if a system transaction
2687        assert!(kind.is_system_tx());
2688        let sender = SuiAddress::default();
2689        TransactionData::V1(TransactionDataV1 {
2690            kind,
2691            sender,
2692            gas_data: GasData {
2693                price: GAS_PRICE_FOR_SYSTEM_TX,
2694                owner: sender,
2695                payment: vec![(ObjectID::ZERO, SequenceNumber::default(), ObjectDigest::MIN)],
2696                budget: 0,
2697            },
2698            expiration: TransactionExpiration::None,
2699        })
2700    }
2701
2702    pub fn new(
2703        kind: TransactionKind,
2704        sender: SuiAddress,
2705        gas_payment: ObjectRef,
2706        gas_budget: u64,
2707        gas_price: u64,
2708    ) -> Self {
2709        TransactionData::V1(TransactionDataV1 {
2710            kind,
2711            sender,
2712            gas_data: GasData {
2713                price: gas_price,
2714                owner: sender,
2715                payment: vec![gas_payment],
2716                budget: gas_budget,
2717            },
2718            expiration: TransactionExpiration::None,
2719        })
2720    }
2721
2722    pub fn new_with_gas_coins(
2723        kind: TransactionKind,
2724        sender: SuiAddress,
2725        gas_payment: Vec<ObjectRef>,
2726        gas_budget: u64,
2727        gas_price: u64,
2728    ) -> Self {
2729        Self::new_with_gas_coins_allow_sponsor(
2730            kind,
2731            sender,
2732            gas_payment,
2733            gas_budget,
2734            gas_price,
2735            sender,
2736        )
2737    }
2738
2739    pub fn new_with_gas_coins_allow_sponsor(
2740        kind: TransactionKind,
2741        sender: SuiAddress,
2742        gas_payment: Vec<ObjectRef>,
2743        gas_budget: u64,
2744        gas_price: u64,
2745        gas_sponsor: SuiAddress,
2746    ) -> Self {
2747        TransactionData::V1(TransactionDataV1 {
2748            kind,
2749            sender,
2750            gas_data: GasData {
2751                price: gas_price,
2752                owner: gas_sponsor,
2753                payment: gas_payment,
2754                budget: gas_budget,
2755            },
2756            expiration: TransactionExpiration::None,
2757        })
2758    }
2759
2760    pub fn new_with_gas_data(kind: TransactionKind, sender: SuiAddress, gas_data: GasData) -> Self {
2761        TransactionData::V1(TransactionDataV1 {
2762            kind,
2763            sender,
2764            gas_data,
2765            expiration: TransactionExpiration::None,
2766        })
2767    }
2768
2769    pub fn new_with_gas_data_and_expiration(
2770        kind: TransactionKind,
2771        sender: SuiAddress,
2772        gas_data: GasData,
2773        expiration: TransactionExpiration,
2774    ) -> Self {
2775        TransactionData::V1(TransactionDataV1 {
2776            kind,
2777            sender,
2778            gas_data,
2779            expiration,
2780        })
2781    }
2782
2783    pub fn new_move_call(
2784        sender: SuiAddress,
2785        package: ObjectID,
2786        module: Identifier,
2787        function: Identifier,
2788        type_arguments: Vec<TypeTag>,
2789        gas_payment: ObjectRef,
2790        arguments: Vec<CallArg>,
2791        gas_budget: u64,
2792        gas_price: u64,
2793    ) -> anyhow::Result<Self> {
2794        Self::new_move_call_with_gas_coins(
2795            sender,
2796            package,
2797            module,
2798            function,
2799            type_arguments,
2800            vec![gas_payment],
2801            arguments,
2802            gas_budget,
2803            gas_price,
2804        )
2805    }
2806
2807    pub fn new_move_call_with_gas_coins(
2808        sender: SuiAddress,
2809        package: ObjectID,
2810        module: Identifier,
2811        function: Identifier,
2812        type_arguments: Vec<TypeTag>,
2813        gas_payment: Vec<ObjectRef>,
2814        arguments: Vec<CallArg>,
2815        gas_budget: u64,
2816        gas_price: u64,
2817    ) -> anyhow::Result<Self> {
2818        let pt = {
2819            let mut builder = ProgrammableTransactionBuilder::new();
2820            builder.move_call(package, module, function, type_arguments, arguments)?;
2821            builder.finish()
2822        };
2823        Ok(Self::new_programmable(
2824            sender,
2825            gas_payment,
2826            pt,
2827            gas_budget,
2828            gas_price,
2829        ))
2830    }
2831
2832    pub fn new_transfer(
2833        recipient: SuiAddress,
2834        full_object_ref: FullObjectRef,
2835        sender: SuiAddress,
2836        gas_payment: ObjectRef,
2837        gas_budget: u64,
2838        gas_price: u64,
2839    ) -> Self {
2840        let pt = {
2841            let mut builder = ProgrammableTransactionBuilder::new();
2842            builder.transfer_object(recipient, full_object_ref).unwrap();
2843            builder.finish()
2844        };
2845        Self::new_programmable(sender, vec![gas_payment], pt, gas_budget, gas_price)
2846    }
2847
2848    pub fn new_transfer_sui(
2849        recipient: SuiAddress,
2850        sender: SuiAddress,
2851        amount: Option<u64>,
2852        gas_payment: ObjectRef,
2853        gas_budget: u64,
2854        gas_price: u64,
2855    ) -> Self {
2856        Self::new_transfer_sui_allow_sponsor(
2857            recipient,
2858            sender,
2859            amount,
2860            gas_payment,
2861            gas_budget,
2862            gas_price,
2863            sender,
2864        )
2865    }
2866
2867    pub fn new_transfer_sui_allow_sponsor(
2868        recipient: SuiAddress,
2869        sender: SuiAddress,
2870        amount: Option<u64>,
2871        gas_payment: ObjectRef,
2872        gas_budget: u64,
2873        gas_price: u64,
2874        gas_sponsor: SuiAddress,
2875    ) -> Self {
2876        let pt = {
2877            let mut builder = ProgrammableTransactionBuilder::new();
2878            builder.transfer_sui(recipient, amount);
2879            builder.finish()
2880        };
2881        Self::new_programmable_allow_sponsor(
2882            sender,
2883            vec![gas_payment],
2884            pt,
2885            gas_budget,
2886            gas_price,
2887            gas_sponsor,
2888        )
2889    }
2890
2891    pub fn new_pay(
2892        sender: SuiAddress,
2893        coins: Vec<ObjectRef>,
2894        recipients: Vec<SuiAddress>,
2895        amounts: Vec<u64>,
2896        gas_payment: ObjectRef,
2897        gas_budget: u64,
2898        gas_price: u64,
2899    ) -> anyhow::Result<Self> {
2900        let pt = {
2901            let mut builder = ProgrammableTransactionBuilder::new();
2902            builder.pay(coins, recipients, amounts)?;
2903            builder.finish()
2904        };
2905        Ok(Self::new_programmable(
2906            sender,
2907            vec![gas_payment],
2908            pt,
2909            gas_budget,
2910            gas_price,
2911        ))
2912    }
2913
2914    pub fn new_pay_sui(
2915        sender: SuiAddress,
2916        mut coins: Vec<ObjectRef>,
2917        recipients: Vec<SuiAddress>,
2918        amounts: Vec<u64>,
2919        gas_payment: ObjectRef,
2920        gas_budget: u64,
2921        gas_price: u64,
2922    ) -> anyhow::Result<Self> {
2923        coins.insert(0, gas_payment);
2924        let pt = {
2925            let mut builder = ProgrammableTransactionBuilder::new();
2926            builder.pay_sui(recipients, amounts)?;
2927            builder.finish()
2928        };
2929        Ok(Self::new_programmable(
2930            sender, coins, pt, gas_budget, gas_price,
2931        ))
2932    }
2933
2934    pub fn new_pay_all_sui(
2935        sender: SuiAddress,
2936        mut coins: Vec<ObjectRef>,
2937        recipient: SuiAddress,
2938        gas_payment: ObjectRef,
2939        gas_budget: u64,
2940        gas_price: u64,
2941    ) -> Self {
2942        coins.insert(0, gas_payment);
2943        let pt = {
2944            let mut builder = ProgrammableTransactionBuilder::new();
2945            builder.pay_all_sui(recipient);
2946            builder.finish()
2947        };
2948        Self::new_programmable(sender, coins, pt, gas_budget, gas_price)
2949    }
2950
2951    pub fn new_split_coin(
2952        sender: SuiAddress,
2953        coin: ObjectRef,
2954        amounts: Vec<u64>,
2955        gas_payment: ObjectRef,
2956        gas_budget: u64,
2957        gas_price: u64,
2958    ) -> Self {
2959        let pt = {
2960            let mut builder = ProgrammableTransactionBuilder::new();
2961            builder.split_coin(sender, coin, amounts);
2962            builder.finish()
2963        };
2964        Self::new_programmable(sender, vec![gas_payment], pt, gas_budget, gas_price)
2965    }
2966
2967    pub fn new_module(
2968        sender: SuiAddress,
2969        gas_payment: ObjectRef,
2970        modules: Vec<Vec<u8>>,
2971        dep_ids: Vec<ObjectID>,
2972        gas_budget: u64,
2973        gas_price: u64,
2974    ) -> Self {
2975        let pt = {
2976            let mut builder = ProgrammableTransactionBuilder::new();
2977            let upgrade_cap = builder.publish_upgradeable(modules, dep_ids);
2978            builder.transfer_arg(sender, upgrade_cap);
2979            builder.finish()
2980        };
2981        Self::new_programmable(sender, vec![gas_payment], pt, gas_budget, gas_price)
2982    }
2983
2984    pub fn new_upgrade(
2985        sender: SuiAddress,
2986        gas_payment: ObjectRef,
2987        package_id: ObjectID,
2988        modules: Vec<Vec<u8>>,
2989        dep_ids: Vec<ObjectID>,
2990        (upgrade_capability, capability_owner): (ObjectRef, Owner),
2991        upgrade_policy: u8,
2992        digest: Vec<u8>,
2993        gas_budget: u64,
2994        gas_price: u64,
2995    ) -> anyhow::Result<Self> {
2996        let pt = {
2997            let mut builder = ProgrammableTransactionBuilder::new();
2998            let capability_arg = match capability_owner {
2999                Owner::AddressOwner(_) => ObjectArg::ImmOrOwnedObject(upgrade_capability),
3000                Owner::Shared {
3001                    initial_shared_version,
3002                }
3003                | Owner::ConsensusAddressOwner {
3004                    start_version: initial_shared_version,
3005                    ..
3006                }
3007                | Owner::Party {
3008                    start_version: initial_shared_version,
3009                    ..
3010                } => ObjectArg::SharedObject {
3011                    id: upgrade_capability.0,
3012                    initial_shared_version,
3013                    mutability: SharedObjectMutability::Mutable,
3014                },
3015                Owner::Immutable => {
3016                    return Err(anyhow::anyhow!(
3017                        "Upgrade capability is stored immutably and cannot be used for upgrades"
3018                    ));
3019                }
3020                // If the capability is owned by an object, then the module defining the owning
3021                // object gets to decide how the upgrade capability should be used.
3022                Owner::ObjectOwner(_) => {
3023                    return Err(anyhow::anyhow!("Upgrade capability controlled by object"));
3024                }
3025            };
3026            builder.obj(capability_arg).unwrap();
3027            let upgrade_arg = builder.pure(upgrade_policy).unwrap();
3028            let digest_arg = builder.pure(digest).unwrap();
3029            let upgrade_ticket = builder.programmable_move_call(
3030                SUI_FRAMEWORK_PACKAGE_ID,
3031                ident_str!("package").to_owned(),
3032                ident_str!("authorize_upgrade").to_owned(),
3033                vec![],
3034                vec![Argument::Input(0), upgrade_arg, digest_arg],
3035            );
3036            let upgrade_receipt = builder.upgrade(package_id, upgrade_ticket, dep_ids, modules);
3037
3038            builder.programmable_move_call(
3039                SUI_FRAMEWORK_PACKAGE_ID,
3040                ident_str!("package").to_owned(),
3041                ident_str!("commit_upgrade").to_owned(),
3042                vec![],
3043                vec![Argument::Input(0), upgrade_receipt],
3044            );
3045
3046            builder.finish()
3047        };
3048        Ok(Self::new_programmable(
3049            sender,
3050            vec![gas_payment],
3051            pt,
3052            gas_budget,
3053            gas_price,
3054        ))
3055    }
3056
3057    pub fn new_programmable(
3058        sender: SuiAddress,
3059        gas_payment: Vec<ObjectRef>,
3060        pt: ProgrammableTransaction,
3061        gas_budget: u64,
3062        gas_price: u64,
3063    ) -> Self {
3064        Self::new_programmable_allow_sponsor(sender, gas_payment, pt, gas_budget, gas_price, sender)
3065    }
3066
3067    pub fn new_programmable_allow_sponsor(
3068        sender: SuiAddress,
3069        gas_payment: Vec<ObjectRef>,
3070        pt: ProgrammableTransaction,
3071        gas_budget: u64,
3072        gas_price: u64,
3073        sponsor: SuiAddress,
3074    ) -> Self {
3075        let kind = TransactionKind::ProgrammableTransaction(pt);
3076        Self::new_with_gas_coins_allow_sponsor(
3077            kind,
3078            sender,
3079            gas_payment,
3080            gas_budget,
3081            gas_price,
3082            sponsor,
3083        )
3084    }
3085
3086    pub fn new_programmable_with_address_balance_gas(
3087        sender: SuiAddress,
3088        pt: ProgrammableTransaction,
3089        gas_budget: u64,
3090        gas_price: u64,
3091        chain_identifier: ChainIdentifier,
3092        current_epoch: EpochId,
3093        nonce: u32,
3094    ) -> Self {
3095        TransactionData::V1(TransactionDataV1 {
3096            kind: TransactionKind::ProgrammableTransaction(pt),
3097            sender,
3098            gas_data: GasData {
3099                payment: vec![],
3100                owner: sender,
3101                price: gas_price,
3102                budget: gas_budget,
3103            },
3104            expiration: TransactionExpiration::ValidDuring {
3105                min_epoch: Some(current_epoch),
3106                max_epoch: Some(current_epoch + 1),
3107                min_timestamp: None,
3108                max_timestamp: None,
3109                chain: chain_identifier,
3110                nonce,
3111            },
3112        })
3113    }
3114
3115    pub fn message_version(&self) -> u64 {
3116        match self {
3117            TransactionData::V1(_) => 1,
3118        }
3119    }
3120
3121    pub fn execution_parts(&self) -> (TransactionKind, SuiAddress, GasData) {
3122        (self.kind().clone(), self.sender(), self.gas_data().clone())
3123    }
3124
3125    pub fn uses_randomness(&self) -> bool {
3126        self.kind()
3127            .shared_input_objects()
3128            .any(|obj| obj.id() == SUI_RANDOMNESS_STATE_OBJECT_ID)
3129    }
3130
3131    pub fn digest(&self) -> TransactionDigest {
3132        TransactionDigest::new(default_hash(self))
3133    }
3134}
3135
3136#[enum_dispatch]
3137pub trait TransactionDataAPI {
3138    fn sender(&self) -> SuiAddress;
3139
3140    // Note: this implies that SingleTransactionKind itself must be versioned, so that it can be
3141    // shared across versions. This will be easy to do since it is already an enum.
3142    fn kind(&self) -> &TransactionKind;
3143
3144    // Used by programmable_transaction_builder
3145    fn kind_mut(&mut self) -> &mut TransactionKind;
3146
3147    // kind is moved out of often enough that this is worth it to special case.
3148    fn into_kind(self) -> TransactionKind;
3149
3150    /// Transaction signer and Gas owner
3151    fn required_signers(&self) -> NonEmpty<SuiAddress>;
3152
3153    fn gas_data(&self) -> &GasData;
3154
3155    fn gas_owner(&self) -> SuiAddress;
3156
3157    fn gas(&self) -> &[ObjectRef];
3158
3159    fn gas_price(&self) -> u64;
3160
3161    fn gas_budget(&self) -> u64;
3162
3163    fn expiration(&self) -> &TransactionExpiration;
3164
3165    fn expiration_mut(&mut self) -> &mut TransactionExpiration;
3166
3167    fn move_calls(&self) -> Vec<(usize, &ObjectID, &str, &str)>;
3168
3169    fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>>;
3170
3171    fn shared_input_objects(&self) -> Vec<SharedInputObject>;
3172
3173    fn receiving_objects(&self) -> Vec<ObjectRef>;
3174
3175    // Dependency (input, package & receiving) objects that already have a version,
3176    // and do not require version assignment from consensus.
3177    // Returns move objects, package objects and receiving objects.
3178    fn fastpath_dependency_objects(
3179        &self,
3180    ) -> UserInputResult<(Vec<ObjectRef>, Vec<ObjectID>, Vec<ObjectRef>)>;
3181
3182    /// Processes funds withdraws and returns a map from funds account object ID to (total
3183    /// reserved amount, type tag, owner address). This method aggregates all withdraw operations
3184    /// for the same account by merging their reservations. Each account object ID is derived from
3185    /// the owner address and the type parameter of each withdraw operation.
3186    ///
3187    /// This method is used at signing time, and can reject a transaction if it contains
3188    /// invalid reservations.
3189    fn process_funds_withdrawals_for_signing(
3190        &self,
3191        chain_identifier: ChainIdentifier,
3192        coin_resolver: &dyn CoinReservationResolverTrait,
3193    ) -> UserInputResult<BTreeMap<AccumulatorObjId, (u64, TypeTag, SuiAddress)>>;
3194
3195    /// Like `process_funds_withdrawals_for_signing`, but excludes the implicit gas payment
3196    /// withdrawal. This is used during gas selection estimation to avoid double-counting the
3197    /// gas budget when determining available address balance.
3198    fn process_funds_withdrawals_for_estimation(
3199        &self,
3200        chain_identifier: ChainIdentifier,
3201        coin_resolver: &dyn CoinReservationResolverTrait,
3202    ) -> UserInputResult<BTreeMap<AccumulatorObjId, (u64, TypeTag, SuiAddress)>>;
3203
3204    /// Like `process_funds_withdrawals_for_signing`, but must only be called on a certified
3205    /// transaction, i.e. one that is known to be valid.
3206    fn process_funds_withdrawals_for_execution(
3207        &self,
3208        chain_identifier: ChainIdentifier,
3209    ) -> BTreeMap<AccumulatorObjId, u64>;
3210
3211    /// Validates the declared funder, the spender, and the funds type of each
3212    /// `WithdrawFrom::SenderAllowance` against its loaded input object. Execution trusts the
3213    /// declared funder, which is immutable on the allowance. Policy checks live in Move.
3214    fn check_allowance_inputs(&self, input_objects: &InputObjects) -> UserInputResult<()>;
3215
3216    // A cheap way to quickly check if the transaction has funds withdraws.
3217    fn has_funds_withdrawals(&self) -> bool;
3218
3219    fn coin_reservation_obj_refs(
3220        &self,
3221        chain_identifier: ChainIdentifier,
3222    ) -> Vec<ParsedObjectRefWithdrawal>;
3223
3224    fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> SuiResult;
3225
3226    /// Check if the transaction is compliant with sponsorship.
3227    fn check_sponsorship(&self) -> UserInputResult;
3228
3229    fn is_system_tx(&self) -> bool;
3230    fn is_genesis_tx(&self) -> bool;
3231
3232    /// returns true if the transaction is one that is specially sequenced to run at the very end
3233    /// of the epoch
3234    fn is_end_of_epoch_tx(&self) -> bool;
3235
3236    fn is_consensus_commit_prologue(&self) -> bool;
3237
3238    /// Check if the transaction is sponsored (namely gas owner != sender)
3239    fn is_sponsored_tx(&self) -> bool;
3240
3241    fn is_gas_paid_from_address_balance(&self) -> bool;
3242
3243    fn is_gasless_transaction(&self) -> bool;
3244
3245    fn sender_mut_for_testing(&mut self) -> &mut SuiAddress;
3246
3247    fn gas_data_mut(&mut self) -> &mut GasData;
3248
3249    // This should be used in testing only.
3250    fn expiration_mut_for_testing(&mut self) -> &mut TransactionExpiration;
3251}
3252
3253impl TransactionDataAPI for TransactionDataV1 {
3254    fn sender(&self) -> SuiAddress {
3255        self.sender
3256    }
3257
3258    fn kind(&self) -> &TransactionKind {
3259        &self.kind
3260    }
3261
3262    fn kind_mut(&mut self) -> &mut TransactionKind {
3263        &mut self.kind
3264    }
3265
3266    fn into_kind(self) -> TransactionKind {
3267        self.kind
3268    }
3269
3270    /// Transaction signer and Gas owner
3271    fn required_signers(&self) -> NonEmpty<SuiAddress> {
3272        let mut signers = nonempty![self.sender];
3273        if self.gas_owner() != self.sender {
3274            signers.push(self.gas_owner());
3275        }
3276        signers
3277    }
3278
3279    fn gas_data(&self) -> &GasData {
3280        &self.gas_data
3281    }
3282
3283    fn gas_owner(&self) -> SuiAddress {
3284        self.gas_data.owner
3285    }
3286
3287    fn gas(&self) -> &[ObjectRef] {
3288        &self.gas_data.payment
3289    }
3290
3291    fn gas_price(&self) -> u64 {
3292        self.gas_data.price
3293    }
3294
3295    fn gas_budget(&self) -> u64 {
3296        self.gas_data.budget
3297    }
3298
3299    fn expiration(&self) -> &TransactionExpiration {
3300        &self.expiration
3301    }
3302
3303    fn expiration_mut(&mut self) -> &mut TransactionExpiration {
3304        &mut self.expiration
3305    }
3306
3307    fn move_calls(&self) -> Vec<(usize, &ObjectID, &str, &str)> {
3308        self.kind.move_calls()
3309    }
3310
3311    fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
3312        let mut inputs = self.kind.input_objects()?;
3313
3314        if !self.kind.is_system_tx() {
3315            inputs.extend(
3316                self.gas()
3317                    .iter()
3318                    .filter(|obj_ref| !ParsedDigest::is_coin_reservation_digest(&obj_ref.2))
3319                    .map(|obj_ref| InputObjectKind::ImmOrOwnedMoveObject(*obj_ref)),
3320            );
3321        }
3322        Ok(inputs)
3323    }
3324
3325    fn shared_input_objects(&self) -> Vec<SharedInputObject> {
3326        self.kind.shared_input_objects().collect()
3327    }
3328
3329    fn receiving_objects(&self) -> Vec<ObjectRef> {
3330        self.kind.receiving_objects()
3331    }
3332
3333    fn fastpath_dependency_objects(
3334        &self,
3335    ) -> UserInputResult<(Vec<ObjectRef>, Vec<ObjectID>, Vec<ObjectRef>)> {
3336        let mut move_objects = vec![];
3337        let mut packages = vec![];
3338        let mut receiving_objects = vec![];
3339        self.input_objects()?.iter().for_each(|o| match o {
3340            InputObjectKind::ImmOrOwnedMoveObject(object_ref) => {
3341                move_objects.push(*object_ref);
3342            }
3343            InputObjectKind::MovePackage(package_id) => {
3344                packages.push(*package_id);
3345            }
3346            InputObjectKind::SharedMoveObject { .. } => {}
3347        });
3348        self.receiving_objects().iter().for_each(|object_ref| {
3349            receiving_objects.push(*object_ref);
3350        });
3351        Ok((move_objects, packages, receiving_objects))
3352    }
3353
3354    fn process_funds_withdrawals_for_signing(
3355        &self,
3356        chain_identifier: ChainIdentifier,
3357        coin_resolver: &dyn CoinReservationResolverTrait,
3358    ) -> UserInputResult<BTreeMap<AccumulatorObjId, (u64, TypeTag, SuiAddress)>> {
3359        self.accumulate_funds_withdrawals(chain_identifier, coin_resolver, true)
3360    }
3361
3362    fn process_funds_withdrawals_for_estimation(
3363        &self,
3364        chain_identifier: ChainIdentifier,
3365        coin_resolver: &dyn CoinReservationResolverTrait,
3366    ) -> UserInputResult<BTreeMap<AccumulatorObjId, (u64, TypeTag, SuiAddress)>> {
3367        self.accumulate_funds_withdrawals(chain_identifier, coin_resolver, false)
3368    }
3369
3370    fn process_funds_withdrawals_for_execution(
3371        &self,
3372        chain_identifier: ChainIdentifier,
3373    ) -> BTreeMap<AccumulatorObjId, u64> {
3374        let mut withdraws: Vec<_> = self.get_funds_withdrawals().collect();
3375        withdraws.extend(self.get_funds_withdrawal_for_gas_payment());
3376
3377        // Accumulate all withdraws per account.
3378        let mut withdraw_map: BTreeMap<AccumulatorObjId, u64> = BTreeMap::new();
3379        for withdraw in withdraws {
3380            let reserved_amount = match &withdraw.reservation {
3381                Reservation::MaxAmountU64(amount) => {
3382                    assert!(*amount > 0, "verified in validity check");
3383                    *amount
3384                }
3385            };
3386
3387            let withdrawal_owner = withdraw.owner_for_withdrawal(self);
3388
3389            // unwrap checked at signing time
3390            let account_id =
3391                AccumulatorValue::get_field_id(withdrawal_owner, &withdraw.type_arg.to_type_tag())
3392                    .unwrap();
3393
3394            let value = withdraw_map.entry(account_id).or_default();
3395            // overflow checked at signing time
3396            *value = value.checked_add(reserved_amount).unwrap();
3397        }
3398
3399        // It is not necessarily possible to construct a FundsWithdrawalArg for coin reservations, because
3400        // the accumulator object may not exist any more. This is okay, as the scheduler will simply
3401        // cancel the transaction if there are no funds available.
3402        for obj in self.coin_reservation_obj_refs() {
3403            assert_reachable!("processing coin reservation withdrawal");
3404            // unwrap safe because of signing time checks
3405            let parsed = ParsedObjectRefWithdrawal::parse(&obj, chain_identifier).unwrap();
3406            let value = withdraw_map
3407                // new_unchecked is safe because we verify that this is a valid accumulator object id
3408                // at signing time
3409                // The underlying object may have been deleted by now - this is okay. We don't need type information
3410                // here, we only need the accumulator object id.
3411                .entry(AccumulatorObjId::new_unchecked(parsed.unmasked_object_id))
3412                .or_default();
3413            // overflow checked at signing time
3414            *value = value.checked_add(parsed.reservation_amount()).unwrap();
3415        }
3416
3417        withdraw_map
3418    }
3419
3420    fn check_allowance_inputs(&self, input_objects: &InputObjects) -> UserInputResult<()> {
3421        let allowance_withdrawals: Vec<_> = self
3422            .get_funds_withdrawals()
3423            .filter_map(|w| match w.withdraw_from {
3424                WithdrawFrom::SenderAllowance { funder, allowance } => {
3425                    Some((funder, allowance, w.type_arg.to_type_tag()))
3426                }
3427                _ => None,
3428            })
3429            .collect();
3430        if allowance_withdrawals.is_empty() {
3431            return Ok(());
3432        }
3433        // An allowance must be among the tx's inputs, or it fails to resolve here.
3434        let objects_by_id: BTreeMap<ObjectID, &Object> = input_objects
3435            .iter()
3436            .filter_map(|input| Some((input.id(), input.as_object()?)))
3437            .collect();
3438        // Two withdrawals may source the same allowance with different declared funders
3439        // (and should be rejected).
3440        let mut resolved_allowances: BTreeMap<ObjectID, ResolvedAllowance> = BTreeMap::new();
3441        for (specified_funder, allowance, requested_funds_type) in allowance_withdrawals {
3442            let resolved: &ResolvedAllowance = match resolved_allowances.entry(allowance) {
3443                Entry::Occupied(entry) => entry.into_mut(),
3444                Entry::Vacant(entry) => {
3445                    let object = objects_by_id.get(&allowance).ok_or_else(|| {
3446                        UserInputError::InvalidWithdrawReservation {
3447                            error: format!(
3448                                "Specified allowance {allowance} not found among the tx inputs"
3449                            ),
3450                        }
3451                    })?;
3452                    entry.insert(parse_allowance_object(object)?)
3453                }
3454            };
3455            if resolved.funder != specified_funder {
3456                return Err(UserInputError::InvalidWithdrawReservation {
3457                    error: format!(
3458                        "Specified funder {specified_funder} does not match the funder of \
3459                        allowance {allowance}"
3460                    ),
3461                });
3462            }
3463            if resolved.spender != Some(self.sender()) {
3464                return Err(UserInputError::InvalidWithdrawReservation {
3465                    error: format!(
3466                        "Transaction sender is not the spender of allowance {allowance}"
3467                    ),
3468                });
3469            }
3470            if resolved.funds_type != requested_funds_type {
3471                return Err(UserInputError::InvalidWithdrawReservation {
3472                    error: format!(
3473                        "Allowance {allowance} is for {}, not {requested_funds_type}",
3474                        resolved.funds_type
3475                    ),
3476                });
3477            }
3478        }
3479        Ok(())
3480    }
3481
3482    fn has_funds_withdrawals(&self) -> bool {
3483        if self.is_gas_paid_from_address_balance() && self.gas_data().budget > 0 {
3484            return true;
3485        }
3486        if let TransactionKind::ProgrammableTransaction(pt) = &self.kind {
3487            for input in &pt.inputs {
3488                if matches!(input, CallArg::FundsWithdrawal(_)) {
3489                    return true;
3490                }
3491            }
3492        }
3493        if self.coin_reservation_obj_refs().next().is_some() {
3494            return true;
3495        }
3496        false
3497    }
3498
3499    fn coin_reservation_obj_refs(
3500        &self,
3501        chain_identifier: ChainIdentifier,
3502    ) -> Vec<ParsedObjectRefWithdrawal> {
3503        self.coin_reservation_obj_refs()
3504            .filter_map(|obj_ref| ParsedObjectRefWithdrawal::parse(&obj_ref, chain_identifier))
3505            .collect()
3506    }
3507
3508    fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> SuiResult {
3509        let config = context.config;
3510
3511        // Checks to see if the transaction has expired
3512        match self.expiration() {
3513            TransactionExpiration::None => (), // always valid
3514            TransactionExpiration::Epoch(max_epoch) => {
3515                if context.epoch > *max_epoch {
3516                    return Err(SuiErrorKind::TransactionExpired.into());
3517                }
3518            }
3519            TransactionExpiration::ValidDuring {
3520                min_epoch,
3521                max_epoch,
3522                min_timestamp,
3523                max_timestamp,
3524                chain,
3525                ..
3526            }
3527            | TransactionExpiration::Validity {
3528                min_epoch,
3529                max_epoch,
3530                min_timestamp,
3531                max_timestamp,
3532                chain,
3533                ..
3534            } => {
3535                // The variant itself is gated regardless of whether its proposer set is usable,
3536                // so that a transaction accepted after the upgrade cannot be accepted before it.
3537                if matches!(self.expiration(), TransactionExpiration::Validity { .. }) {
3538                    fp_ensure!(
3539                        config.allowed_proposers(),
3540                        UserInputError::Unsupported(
3541                            "Restricting the proposers of a transaction is not supported"
3542                                .to_string(),
3543                        )
3544                        .into()
3545                    );
3546                }
3547
3548                // A proposer set recorded for another epoch is ignored, so there is nothing to
3549                // check: the transaction is treated as if it named no proposers at all.
3550                if let Some(allowed_proposers) = self.expiration().allowed_proposers(context.epoch)
3551                {
3552                    let proposers = &allowed_proposers.proposers;
3553
3554                    // SIP-45: submitting the same transaction to several proposers amplifies its
3555                    // consensus cost, which must be paid for with a raised gas price. Sizing the
3556                    // proposer set is the sender's declaration of how much it intends to amplify.
3557                    // No gas price buys more proposers than there are validators.
3558                    //
3559                    // Checked first, so that everything below walks a bounded list.
3560                    let max_proposers =
3561                        paid_proposer_count(self.gas_data.price, context.reference_gas_price)
3562                            .min(context.committee_size as u64);
3563                    fp_ensure!(
3564                        proposers.len() as u64 <= max_proposers,
3565                        UserInputError::InvalidExpiration {
3566                            error: format!(
3567                                "allowed_proposers has {} entries, but at most {max_proposers} \
3568                                 are permitted with gas price {}, reference gas price {}, and a \
3569                                 committee of {}",
3570                                proposers.len(),
3571                                self.gas_data.price,
3572                                context.reference_gas_price,
3573                                context.committee_size,
3574                            ),
3575                        }
3576                        .into()
3577                    );
3578
3579                    // Canonical encoding: a proposer set cannot be padded with duplicates, and
3580                    // lookups can rely on the ordering.
3581                    fp_ensure!(
3582                        proposers.iter().is_sorted_by(|a, b| a < b),
3583                        UserInputError::InvalidExpiration {
3584                            error: "allowed_proposers must be strictly increasing".to_string(),
3585                        }
3586                        .into()
3587                    );
3588
3589                    // An out-of-range index names no one, so it can only make the transaction
3590                    // unproposable.
3591                    if let Some(out_of_range) =
3592                        proposers.iter().find(|i| **i >= context.committee_size)
3593                    {
3594                        return Err(UserInputError::InvalidExpiration {
3595                            error: format!(
3596                                "allowed_proposers contains index {out_of_range}, but the \
3597                                 committee has {} members",
3598                                context.committee_size,
3599                            ),
3600                        }
3601                        .into());
3602                    }
3603                }
3604
3605                if min_timestamp.is_some() || max_timestamp.is_some() {
3606                    fp_ensure!(
3607                        config.enable_timestamp_transaction_expiration(),
3608                        UserInputError::Unsupported(
3609                            "Timestamp-based transaction expiration is not yet supported"
3610                                .to_string(),
3611                        )
3612                        .into()
3613                    );
3614                    // gRPC carries the bounds as protobuf `Timestamp` seconds, which end at
3615                    // 9999-12-31T23:59:59Z. The bound also rejects millisecond values.
3616                    for timestamp in [min_timestamp, max_timestamp].into_iter().flatten() {
3617                        fp_ensure!(
3618                            *timestamp <= MAX_EXPIRATION_TIMESTAMP_SECS,
3619                            UserInputError::InvalidExpiration {
3620                                error: format!(
3621                                    "timestamp {timestamp} is greater than {MAX_EXPIRATION_TIMESTAMP_SECS}"
3622                                ),
3623                            }
3624                            .into()
3625                        );
3626                    }
3627                    if let (Some(min), Some(max)) = (min_timestamp, max_timestamp) {
3628                        fp_ensure!(
3629                            min <= max,
3630                            UserInputError::InvalidExpiration {
3631                                error: format!(
3632                                    "min_timestamp {min} is greater than max_timestamp {max}"
3633                                ),
3634                            }
3635                            .into()
3636                        );
3637                    }
3638                }
3639
3640                // Legacy behavior: If a validity window is present, it must have either one- or
3641                // two-epoch validity, even if the transaction has other replay-protection.
3642                // New behavior: any epoch range can be specified. Replay protection is enforced
3643                // by sui_transaction_checks::check_replay_protection.
3644                match (min_epoch, max_epoch) {
3645                    _ if config.relax_valid_during_for_owned_inputs() => (),
3646                    (Some(min), Some(max)) => {
3647                        if config.enable_multi_epoch_transaction_expiration() {
3648                            if !(*max == *min || *max == min.saturating_add(1)) {
3649                                return Err(UserInputError::Unsupported(
3650                                    "max_epoch must be at most min_epoch + 1".to_string(),
3651                                )
3652                                .into());
3653                            }
3654                        } else if min != max {
3655                            return Err(UserInputError::Unsupported(
3656                                "min_epoch must equal max_epoch".to_string(),
3657                            )
3658                            .into());
3659                        }
3660                    }
3661                    _ => {
3662                        return Err(UserInputError::Unsupported(
3663                            "Both min_epoch and max_epoch must be specified".to_string(),
3664                        )
3665                        .into());
3666                    }
3667                }
3668
3669                if *chain != context.chain_identifier {
3670                    return Err(UserInputError::InvalidChainId {
3671                        provided: format!("{:?}", chain),
3672                        expected: format!("{:?}", context.chain_identifier),
3673                    }
3674                    .into());
3675                }
3676
3677                if let Some(min) = min_epoch
3678                    && context.epoch < *min
3679                {
3680                    return Err(SuiErrorKind::TransactionExpired.into());
3681                }
3682                if let Some(max) = max_epoch
3683                    && context.epoch > *max
3684                {
3685                    return Err(SuiErrorKind::TransactionExpired.into());
3686                }
3687            }
3688        }
3689
3690        if self.has_funds_withdrawals() {
3691            // TODO: this check is incorrect, we should only require this if there are zero owned
3692            // inputs
3693            fp_ensure!(
3694                !self.gas().is_empty() || config.enable_address_balance_gas_payments(),
3695                UserInputError::MissingGasPayment.into()
3696            );
3697
3698            fp_ensure!(
3699                config.enable_accumulators(),
3700                UserInputError::Unsupported("Address balance withdraw is not enabled".to_string())
3701                    .into()
3702            );
3703
3704            // TODO(address-balances): Use a protocol config parameter for max_withdraws.
3705            let max_withdraws = 10;
3706            let mut num_reservations = 0;
3707
3708            for withdraw in self.kind.get_funds_withdrawals() {
3709                num_reservations += 1;
3710                match withdraw.withdraw_from {
3711                    WithdrawFrom::Sender => (),
3712                    WithdrawFrom::Sponsor => {
3713                        return Err(UserInputError::InvalidWithdrawReservation {
3714                            error: "Explicit sponsor withdrawals are not yet supported".to_string(),
3715                        }
3716                        .into());
3717                    }
3718                    WithdrawFrom::FrozenAddress { .. } => {
3719                        return Err(UserInputError::InvalidWithdrawReservation {
3720                            error: "Frozen address withdrawals are not yet supported".to_string(),
3721                        }
3722                        .into());
3723                    }
3724                    // The allowance itself is checked after input loading, in
3725                    // `check_allowance_inputs`.
3726                    WithdrawFrom::SenderAllowance { .. } => {
3727                        fp_ensure!(
3728                            config.enable_allowances(),
3729                            UserInputError::Unsupported(
3730                                "Allowance withdrawals are not enabled".to_string()
3731                            )
3732                            .into()
3733                        );
3734                    }
3735                }
3736
3737                match withdraw.reservation {
3738                    Reservation::MaxAmountU64(amount) => {
3739                        fp_ensure!(
3740                            amount > 0,
3741                            UserInputError::InvalidWithdrawReservation {
3742                                error: "Balance withdraw reservation amount must be non-zero"
3743                                    .to_string(),
3744                            }
3745                            .into()
3746                        );
3747                    }
3748                };
3749            }
3750
3751            for parsed in self.parsed_coin_reservations(context.chain_identifier) {
3752                num_reservations += 1;
3753                // coin reservations are valid for the current and next epoch, just as transactions that
3754                // specify a TransactionDuring are.
3755                // TODO: this check can be skipped if the transaction contains any address owned inputs.
3756                if parsed.epoch_id() != context.epoch && parsed.epoch_id() + 1 != context.epoch {
3757                    return Err(SuiErrorKind::TransactionExpired.into());
3758                }
3759                if parsed.reservation_amount() == 0 {
3760                    return Err(UserInputError::InvalidWithdrawReservation {
3761                        error: "Balance withdraw reservation amount must be non-zero".to_string(),
3762                    }
3763                    .into());
3764                }
3765            }
3766
3767            // Count implicit gas budget as a withdrawal when gas is paid from address balance
3768            if config.enable_address_balance_gas_payments()
3769                && self.is_gas_paid_from_address_balance()
3770            {
3771                num_reservations += 1;
3772            }
3773
3774            fp_ensure!(
3775                num_reservations <= max_withdraws,
3776                UserInputError::InvalidWithdrawReservation {
3777                    error: format!(
3778                        "Maximum number of balance withdraw reservations is {max_withdraws}"
3779                    ),
3780                }
3781                .into()
3782            );
3783        }
3784
3785        if config.enable_accumulators()
3786            && config.enable_address_balance_gas_payments()
3787            && self.is_gas_paid_from_address_balance()
3788        {
3789            if config.address_balance_gas_reject_gas_coin_arg()
3790                && let TransactionKind::ProgrammableTransaction(pt) = &self.kind
3791            {
3792                fp_ensure!(
3793                    !pt.commands.iter().any(|cmd| cmd.is_gas_coin_used()),
3794                    UserInputError::Unsupported(
3795                        "Argument::GasCoin is not supported with address balance gas payments"
3796                            .to_string(),
3797                    )
3798                    .into()
3799                );
3800            }
3801
3802            let is_gasless = config.enable_gasless() && self.is_gasless_transaction();
3803            if config.address_balance_gas_check_rgp_at_signing() && !is_gasless {
3804                fp_ensure!(
3805                    self.gas_data.price >= context.reference_gas_price,
3806                    UserInputError::GasPriceUnderRGP {
3807                        gas_price: self.gas_data.price,
3808                        reference_gas_price: context.reference_gas_price,
3809                    }
3810                    .into()
3811                );
3812            }
3813
3814            // Legacy behavior: when paying gas from address balance, we require ValidDuring expiration
3815            // even if the transaction has other replay-protected inputs.
3816            // New behavior: the check is done in `check_replay_protection` in sui-transaction-checks,
3817            // which only requires two-epoch ValidDuring if there are no replay-protected inputs.
3818            if !config.relax_valid_during_for_owned_inputs() {
3819                if matches!(self.expiration(), TransactionExpiration::None) {
3820                    // To avoid changing error behavior unnecessarily, we flag this as a missing gas payment error
3821                    // instead of a missing expiration error.
3822                    return Err(UserInputError::MissingGasPayment.into());
3823                }
3824
3825                if !self.expiration().is_replay_protected() {
3826                    return Err(UserInputError::InvalidExpiration {
3827                        error: "Address balance gas payments require ValidDuring expiration"
3828                            .to_string(),
3829                    }
3830                    .into());
3831                }
3832            }
3833        } else {
3834            fp_ensure!(
3835                !self.gas().is_empty(),
3836                UserInputError::MissingGasPayment.into()
3837            );
3838        }
3839
3840        let gas_len = self.gas().len();
3841        let max_gas_objects = config.max_gas_payment_objects() as usize;
3842
3843        let within_limit = if config.correct_gas_payment_limit_check() {
3844            gas_len <= max_gas_objects
3845        } else {
3846            gas_len < max_gas_objects
3847        };
3848
3849        fp_ensure!(
3850            within_limit,
3851            UserInputError::SizeLimitExceeded {
3852                limit: "maximum number of gas payment objects".to_string(),
3853                value: config.max_gas_payment_objects().to_string()
3854            }
3855            .into()
3856        );
3857
3858        if !config.enable_coin_reservation_obj_refs() {
3859            for (_, _, gas_digest) in self.gas() {
3860                fp_ensure!(
3861                    !ParsedDigest::is_coin_reservation_digest(gas_digest),
3862                    UserInputError::GasObjectNotOwnedObject {
3863                        owner: Owner::AddressOwner(self.sender)
3864                    }
3865                    .into()
3866                );
3867            }
3868        } else {
3869            // When coin reservations are enabled, validate that gas coin reservations are for SUI,
3870            // and that they are owned by the sender. (Sponsorship via coin reservations is not supported.)
3871            let sui_accumulator_id =
3872                *AccumulatorValue::get_field_id(self.sender, &Balance::type_tag(GAS::type_tag()))?
3873                    .inner();
3874
3875            for gas_ref in self.gas() {
3876                if let Some(parsed) =
3877                    ParsedObjectRefWithdrawal::parse(gas_ref, context.chain_identifier)
3878                {
3879                    // Coin reservations draw from the sender's address balance, so they cannot
3880                    // be used in sponsored transactions where gas is paid by someone else.
3881                    fp_ensure!(
3882                        self.gas_owner() == self.sender,
3883                        UserInputError::GasObjectNotOwnedObject {
3884                            owner: Owner::AddressOwner(self.sender)
3885                        }
3886                        .into()
3887                    );
3888                    fp_ensure!(
3889                        parsed.unmasked_object_id == sui_accumulator_id,
3890                        UserInputError::GasObjectNotOwnedObject {
3891                            owner: Owner::AddressOwner(self.sender)
3892                        }
3893                        .into()
3894                    );
3895                }
3896            }
3897        }
3898
3899        if !self.is_system_tx() {
3900            fp_ensure!(
3901                !check_for_gas_price_too_high(config.gas_model_version())
3902                    || self.gas_data.price < config.max_gas_price(),
3903                UserInputError::GasPriceTooHigh {
3904                    max_gas_price: config.max_gas_price(),
3905                }
3906                .into()
3907            );
3908            fp_ensure!(
3909                self.gas_data.budget <= config.max_tx_gas(),
3910                UserInputError::GasBudgetTooHigh {
3911                    gas_budget: self.gas_data().budget,
3912                    max_budget: config.max_tx_gas(),
3913                }
3914                .into()
3915            );
3916            let is_gasless = config.enable_gasless() && self.is_gasless_transaction();
3917            if is_gasless {
3918                fp_ensure!(
3919                    self.gas_data.budget == 0,
3920                    UserInputError::Unsupported(
3921                        "gas_budget must be 0 for gasless transactions".to_string()
3922                    )
3923                    .into()
3924                );
3925            } else {
3926                let min_budget = minimum_gas_budget(config, self.gas_data.price);
3927                fp_ensure!(
3928                    self.gas_data.budget >= min_budget,
3929                    UserInputError::GasBudgetTooLow {
3930                        gas_budget: self.gas_data.budget,
3931                        min_budget,
3932                    }
3933                    .into()
3934                );
3935            }
3936        }
3937
3938        self.kind().validity_check(config)?;
3939
3940        if config.enable_gasless() && self.is_gasless_transaction() {
3941            let TransactionKind::ProgrammableTransaction(pt) = &self.kind else {
3942                debug_fatal!("gasless transaction is not a ProgrammableTransaction");
3943                return Err(UserInputError::Unsupported(
3944                    "Gasless transactions must be programmable transactions".to_string(),
3945                )
3946                .into());
3947            };
3948            pt.validate_gasless_transaction(config)?;
3949        }
3950
3951        self.check_sponsorship()?;
3952        Ok(())
3953    }
3954
3955    /// Check if the transaction is sponsored (namely gas owner != sender)
3956    fn is_sponsored_tx(&self) -> bool {
3957        self.gas_owner() != self.sender
3958    }
3959
3960    // Note: it is possible to pay gas from a coin reservation, which ultimately draws from
3961    // the address balance. This function still returns false in that case. In other words,
3962    // it indicates use of the first-class API for address balance gas payments, not the legacy API.
3963    fn is_gas_paid_from_address_balance(&self) -> bool {
3964        is_gas_paid_from_address_balance(&self.gas_data, &self.kind)
3965    }
3966
3967    fn is_gasless_transaction(&self) -> bool {
3968        is_gasless_transaction(&self.gas_data, &self.kind)
3969    }
3970
3971    /// Check if the transaction is compliant with sponsorship.
3972    fn check_sponsorship(&self) -> UserInputResult {
3973        // Not a sponsored transaction, nothing to check
3974        if self.gas_owner() == self.sender() {
3975            return Ok(());
3976        }
3977        if matches!(&self.kind, TransactionKind::ProgrammableTransaction(_)) {
3978            return Ok(());
3979        }
3980        Err(UserInputError::UnsupportedSponsoredTransactionKind)
3981    }
3982
3983    fn is_end_of_epoch_tx(&self) -> bool {
3984        matches!(
3985            self.kind,
3986            TransactionKind::ChangeEpoch(_) | TransactionKind::EndOfEpochTransaction(_)
3987        )
3988    }
3989
3990    fn is_consensus_commit_prologue(&self) -> bool {
3991        match &self.kind {
3992            TransactionKind::ConsensusCommitPrologue(_)
3993            | TransactionKind::ConsensusCommitPrologueV2(_)
3994            | TransactionKind::ConsensusCommitPrologueV3(_)
3995            | TransactionKind::ConsensusCommitPrologueV4(_) => true,
3996
3997            TransactionKind::ProgrammableTransaction(_)
3998            | TransactionKind::ProgrammableSystemTransaction(_)
3999            | TransactionKind::ChangeEpoch(_)
4000            | TransactionKind::Genesis(_)
4001            | TransactionKind::AuthenticatorStateUpdate(_)
4002            | TransactionKind::EndOfEpochTransaction(_)
4003            | TransactionKind::RandomnessStateUpdate(_) => false,
4004        }
4005    }
4006
4007    fn is_system_tx(&self) -> bool {
4008        self.kind.is_system_tx()
4009    }
4010
4011    fn is_genesis_tx(&self) -> bool {
4012        matches!(self.kind, TransactionKind::Genesis(_))
4013    }
4014
4015    fn sender_mut_for_testing(&mut self) -> &mut SuiAddress {
4016        &mut self.sender
4017    }
4018
4019    fn gas_data_mut(&mut self) -> &mut GasData {
4020        &mut self.gas_data
4021    }
4022
4023    fn expiration_mut_for_testing(&mut self) -> &mut TransactionExpiration {
4024        &mut self.expiration
4025    }
4026}
4027
4028impl TransactionDataV1 {
4029    fn accumulate_funds_withdrawals(
4030        &self,
4031        chain_identifier: ChainIdentifier,
4032        coin_resolver: &dyn CoinReservationResolverTrait,
4033        include_gas_payment: bool,
4034    ) -> UserInputResult<BTreeMap<AccumulatorObjId, (u64, TypeTag, SuiAddress)>> {
4035        let mut withdraws: Vec<_> = self.get_funds_withdrawals().collect();
4036
4037        for withdraw in self.parsed_coin_reservations(chain_identifier) {
4038            let withdrawal_arg =
4039                coin_resolver.resolve_funds_withdrawal(self.sender(), withdraw, None)?;
4040            withdraws.push(withdrawal_arg);
4041        }
4042
4043        if include_gas_payment {
4044            withdraws.extend(self.get_funds_withdrawal_for_gas_payment());
4045        }
4046
4047        let mut withdraw_map: BTreeMap<AccumulatorObjId, (u64, TypeTag, SuiAddress)> =
4048            BTreeMap::new();
4049        for withdraw in withdraws {
4050            let reserved_amount = match &withdraw.reservation {
4051                Reservation::MaxAmountU64(amount) => {
4052                    if *amount == 0 {
4053                        return Err(UserInputError::InvalidWithdrawReservation {
4054                            error: "Balance withdraw reservation amount must be non-zero"
4055                                .to_string(),
4056                        });
4057                    }
4058                    *amount
4059                }
4060            };
4061
4062            let account_address = withdraw.owner_for_withdrawal(self);
4063            let type_tag = withdraw.type_arg.to_type_tag();
4064            let account_id =
4065                AccumulatorValue::get_field_id(account_address, &type_tag).map_err(|e| {
4066                    UserInputError::InvalidWithdrawReservation {
4067                        error: e.to_string(),
4068                    }
4069                })?;
4070
4071            let (current_amount, _, _) = withdraw_map
4072                .entry(account_id)
4073                .or_insert_with(|| (0, type_tag, account_address));
4074            *current_amount = current_amount.checked_add(reserved_amount).ok_or(
4075                UserInputError::InvalidWithdrawReservation {
4076                    error: "Balance withdraw reservation overflow".to_string(),
4077                },
4078            )?;
4079        }
4080
4081        Ok(withdraw_map)
4082    }
4083
4084    fn get_funds_withdrawal_for_gas_payment(&self) -> Option<FundsWithdrawalArg> {
4085        if self.is_gas_paid_from_address_balance() && self.gas_data().budget > 0 {
4086            Some(if self.sender() != self.gas_owner() {
4087                FundsWithdrawalArg::balance_from_sponsor(self.gas_data().budget, GAS::type_tag())
4088            } else {
4089                FundsWithdrawalArg::balance_from_sender(self.gas_data().budget, GAS::type_tag())
4090            })
4091        } else {
4092            None
4093        }
4094    }
4095
4096    fn get_funds_withdrawals(&self) -> impl Iterator<Item = FundsWithdrawalArg> + '_ {
4097        self.kind.get_funds_withdrawals().cloned()
4098    }
4099
4100    fn coin_reservation_obj_refs(&self) -> impl Iterator<Item = ObjectRef> {
4101        self.kind
4102            .get_coin_reservation_obj_refs()
4103            .chain(self.gas().iter().filter_map(|gas_ref| {
4104                if ParsedDigest::is_coin_reservation_digest(&gas_ref.2) {
4105                    Some(*gas_ref)
4106                } else {
4107                    None
4108                }
4109            }))
4110    }
4111
4112    fn parsed_coin_reservations(
4113        &self,
4114        chain_identifier: ChainIdentifier,
4115    ) -> impl Iterator<Item = ParsedObjectRefWithdrawal> {
4116        self.coin_reservation_obj_refs().map(move |obj_ref| {
4117            ParsedObjectRefWithdrawal::parse(&obj_ref, chain_identifier).unwrap()
4118        })
4119    }
4120}
4121
4122pub struct TxValidityCheckContext<'a> {
4123    pub config: &'a ProtocolConfig,
4124    pub epoch: EpochId,
4125    pub chain_identifier: ChainIdentifier,
4126    pub reference_gas_price: u64,
4127    /// Number of validators in the current epoch's committee, used to bound committee indices.
4128    pub committee_size: u32,
4129}
4130
4131impl<'a> TxValidityCheckContext<'a> {
4132    pub fn from_cfg_for_testing(config: &'a ProtocolConfig) -> Self {
4133        Self {
4134            config,
4135            epoch: 0,
4136            chain_identifier: ChainIdentifier::default(),
4137            reference_gas_price: 1000,
4138            committee_size: 4,
4139        }
4140    }
4141}
4142
4143#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
4144pub struct SenderSignedData(SizeOneVec<SenderSignedTransaction>);
4145
4146#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4147pub struct SenderSignedTransaction {
4148    pub intent_message: IntentMessage<TransactionData>,
4149    /// A list of signatures signed by all transaction participants.
4150    /// 1. non participant signature must not be present.
4151    /// 2. signature order does not matter.
4152    pub tx_signatures: Vec<GenericSignature>,
4153}
4154
4155impl Serialize for SenderSignedTransaction {
4156    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
4157    where
4158        S: serde::Serializer,
4159    {
4160        #[derive(Serialize)]
4161        #[serde(rename = "SenderSignedTransaction")]
4162        struct SignedTxn<'a> {
4163            intent_message: &'a IntentMessage<TransactionData>,
4164            tx_signatures: &'a Vec<GenericSignature>,
4165        }
4166
4167        if self.intent_message().intent != Intent::sui_transaction() {
4168            return Err(serde::ser::Error::custom("invalid Intent for Transaction"));
4169        }
4170
4171        let txn = SignedTxn {
4172            intent_message: self.intent_message(),
4173            tx_signatures: &self.tx_signatures,
4174        };
4175        txn.serialize(serializer)
4176    }
4177}
4178
4179impl<'de> Deserialize<'de> for SenderSignedTransaction {
4180    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
4181    where
4182        D: serde::Deserializer<'de>,
4183    {
4184        #[derive(Deserialize)]
4185        #[serde(rename = "SenderSignedTransaction")]
4186        struct SignedTxn {
4187            intent_message: IntentMessage<TransactionData>,
4188            tx_signatures: Vec<GenericSignature>,
4189        }
4190
4191        let SignedTxn {
4192            intent_message,
4193            tx_signatures,
4194        } = Deserialize::deserialize(deserializer)?;
4195
4196        if intent_message.intent != Intent::sui_transaction() {
4197            return Err(serde::de::Error::custom("invalid Intent for Transaction"));
4198        }
4199
4200        Ok(Self {
4201            intent_message,
4202            tx_signatures,
4203        })
4204    }
4205}
4206
4207impl SenderSignedTransaction {
4208    /// Returns a mapping from signer address to the signature and its index in `tx_signatures`.
4209    pub(crate) fn get_signer_sig_mapping(
4210        &self,
4211        verify_legacy_zklogin_address: bool,
4212    ) -> SuiResult<BTreeMap<SuiAddress, (u8, &GenericSignature)>> {
4213        let mut mapping = BTreeMap::new();
4214        for (idx, sig) in self.tx_signatures.iter().enumerate() {
4215            if verify_legacy_zklogin_address && let GenericSignature::ZkLoginAuthenticator(z) = sig
4216            {
4217                // Try deriving the address from the legacy padded way.
4218                mapping.insert(SuiAddress::try_from_padded(&z.inputs)?, (idx as u8, sig));
4219            }
4220            let address = sig.try_into()?;
4221            mapping.insert(address, (idx as u8, sig));
4222        }
4223        Ok(mapping)
4224    }
4225
4226    pub fn intent_message(&self) -> &IntentMessage<TransactionData> {
4227        &self.intent_message
4228    }
4229}
4230
4231/// Any ML-DSA-65 part of a multisig is a BCS variant older binaries cannot
4232/// decode, so it stays out of blocks until the flag is on, even when only
4233/// classical members signed.
4234fn mldsa65_multisig_unsupported() -> SuiError {
4235    SuiErrorKind::UserInputError {
4236        error: UserInputError::Unsupported(
4237            "ML-DSA-65 multisig members are not enabled on this network".to_string(),
4238        ),
4239    }
4240    .into()
4241}
4242
4243impl SenderSignedData {
4244    pub fn new(tx_data: TransactionData, tx_signatures: Vec<GenericSignature>) -> Self {
4245        Self(SizeOneVec::new(SenderSignedTransaction {
4246            intent_message: IntentMessage::new(Intent::sui_transaction(), tx_data),
4247            tx_signatures,
4248        }))
4249    }
4250
4251    pub fn new_from_sender_signature(tx_data: TransactionData, tx_signature: Signature) -> Self {
4252        Self(SizeOneVec::new(SenderSignedTransaction {
4253            intent_message: IntentMessage::new(Intent::sui_transaction(), tx_data),
4254            tx_signatures: vec![tx_signature.into()],
4255        }))
4256    }
4257
4258    pub fn inner(&self) -> &SenderSignedTransaction {
4259        self.0.element()
4260    }
4261
4262    pub fn into_inner(self) -> SenderSignedTransaction {
4263        self.0.into_inner()
4264    }
4265
4266    pub fn inner_mut(&mut self) -> &mut SenderSignedTransaction {
4267        self.0.element_mut()
4268    }
4269
4270    // This function does not check validity of the signature
4271    // or perform any de-dup checks.
4272    pub fn add_signature(&mut self, new_signature: Signature) {
4273        self.inner_mut().tx_signatures.push(new_signature.into());
4274    }
4275
4276    pub(crate) fn get_signer_sig_mapping(
4277        &self,
4278        verify_legacy_zklogin_address: bool,
4279    ) -> SuiResult<BTreeMap<SuiAddress, (u8, &GenericSignature)>> {
4280        self.inner()
4281            .get_signer_sig_mapping(verify_legacy_zklogin_address)
4282    }
4283
4284    pub fn transaction_data(&self) -> &TransactionData {
4285        &self.intent_message().value
4286    }
4287
4288    pub fn intent_message(&self) -> &IntentMessage<TransactionData> {
4289        self.inner().intent_message()
4290    }
4291
4292    pub fn tx_signatures(&self) -> &[GenericSignature] {
4293        &self.inner().tx_signatures
4294    }
4295
4296    pub fn has_zklogin_sig(&self) -> bool {
4297        self.tx_signatures().iter().any(|sig| sig.is_zklogin())
4298    }
4299
4300    pub fn has_upgraded_multisig(&self) -> bool {
4301        self.tx_signatures()
4302            .iter()
4303            .any(|sig| sig.is_upgraded_multisig())
4304    }
4305
4306    #[cfg(test)]
4307    pub fn intent_message_mut_for_testing(&mut self) -> &mut IntentMessage<TransactionData> {
4308        &mut self.inner_mut().intent_message
4309    }
4310
4311    // used cross-crate, so cannot be #[cfg(test)]
4312    pub fn tx_signatures_mut_for_testing(&mut self) -> &mut Vec<GenericSignature> {
4313        &mut self.inner_mut().tx_signatures
4314    }
4315
4316    /// Includes alias_versions to ensure cache invalidation when aliases change.
4317    pub fn full_message_digest_with_alias_versions(
4318        &self,
4319        alias_versions: &Vec<(SuiAddress, Option<SequenceNumber>)>,
4320    ) -> SenderSignedDataDigest {
4321        let mut digest = DefaultHash::default();
4322        bcs::serialize_into(&mut digest, self).expect("serialization should not fail");
4323        bcs::serialize_into(&mut digest, alias_versions).expect("serialization should not fail");
4324        let hash = digest.finalize();
4325        SenderSignedDataDigest::new(hash.into())
4326    }
4327
4328    pub fn serialized_size(&self) -> SuiResult<usize> {
4329        bcs::serialized_size(self).map_err(|e| {
4330            SuiErrorKind::TransactionSerializationError {
4331                error: e.to_string(),
4332            }
4333            .into()
4334        })
4335    }
4336
4337    fn check_user_signature_protocol_compatibility(&self, config: &ProtocolConfig) -> SuiResult {
4338        for sig in &self.inner().tx_signatures {
4339            match sig {
4340                GenericSignature::MultiSig(multisig) => {
4341                    if !config.upgraded_multisig_supported() {
4342                        return Err(SuiErrorKind::UserInputError {
4343                            error: UserInputError::Unsupported(
4344                                "upgraded multisig format not enabled on this network".to_string(),
4345                            ),
4346                        }
4347                        .into());
4348                    }
4349                    if multisig.uses_mldsa65() && !config.mldsa65_auth() {
4350                        return Err(mldsa65_multisig_unsupported());
4351                    }
4352                }
4353                GenericSignature::ZkLoginAuthenticator(_) => {
4354                    if !config.zklogin_auth() {
4355                        return Err(SuiErrorKind::UserInputError {
4356                            error: UserInputError::Unsupported(
4357                                "zklogin is not enabled on this network".to_string(),
4358                            ),
4359                        }
4360                        .into());
4361                    }
4362                }
4363                GenericSignature::PasskeyAuthenticator(_) => {
4364                    if !config.passkey_auth() {
4365                        return Err(SuiErrorKind::UserInputError {
4366                            error: UserInputError::Unsupported(
4367                                "passkey is not enabled on this network".to_string(),
4368                            ),
4369                        }
4370                        .into());
4371                    }
4372                }
4373                GenericSignature::Signature(_) => {
4374                    // Only ML-DSA-65 is gated; the classical schemes predate feature flags.
4375                    if sig.is_mldsa65() && !config.mldsa65_auth() {
4376                        return Err(SuiErrorKind::UserInputError {
4377                            error: UserInputError::Unsupported(
4378                                "ML-DSA-65 signatures are not enabled on this network".to_string(),
4379                            ),
4380                        }
4381                        .into());
4382                    }
4383                }
4384                GenericSignature::MultiSigLegacy(multisig) => {
4385                    if multisig.uses_mldsa65() && !config.mldsa65_auth() {
4386                        return Err(mldsa65_multisig_unsupported());
4387                    }
4388                }
4389            }
4390        }
4391
4392        Ok(())
4393    }
4394
4395    /// Validate untrusted user transaction, including its size, input count, command count, etc.
4396    /// Returns the certificate serialised bytes size.
4397    pub fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> Result<usize, SuiError> {
4398        // Check that the features used by the user signatures are enabled on the network.
4399        self.check_user_signature_protocol_compatibility(context.config)?;
4400
4401        // TODO: The following checks can be moved to TransactionData, if we pass context into it.
4402
4403        // CRITICAL!!
4404        // Users cannot send system transactions.
4405        let tx_data = &self.transaction_data();
4406        fp_ensure!(
4407            !tx_data.is_system_tx(),
4408            SuiErrorKind::UserInputError {
4409                error: UserInputError::Unsupported(
4410                    "SenderSignedData must not contain system transaction".to_string()
4411                )
4412            }
4413            .into()
4414        );
4415
4416        // Enforce overall transaction size limit.
4417        let tx_size = self.serialized_size()?;
4418        let max_tx_size_bytes = context.config.max_tx_size_bytes();
4419        fp_ensure!(
4420            tx_size as u64 <= max_tx_size_bytes,
4421            SuiErrorKind::UserInputError {
4422                error: UserInputError::SizeLimitExceeded {
4423                    limit: format!(
4424                        "serialized transaction size exceeded maximum of {max_tx_size_bytes}"
4425                    ),
4426                    value: tx_size.to_string(),
4427                }
4428            }
4429            .into()
4430        );
4431
4432        if context.config.enable_gasless() && tx_data.is_gasless_transaction() {
4433            let gasless_max = context.config.get_gasless_max_tx_size_bytes();
4434            fp_ensure!(
4435                tx_size as u64 <= gasless_max,
4436                SuiErrorKind::UserInputError {
4437                    error: UserInputError::SizeLimitExceeded {
4438                        limit: format!(
4439                            "serialized gasless transaction size exceeded maximum of {gasless_max}"
4440                        ),
4441                        value: tx_size.to_string(),
4442                    }
4443                }
4444                .into()
4445            );
4446        }
4447
4448        tx_data.validity_check(context)?;
4449
4450        Ok(tx_size)
4451    }
4452}
4453
4454impl Message for SenderSignedData {
4455    type DigestType = TransactionDigest;
4456    const SCOPE: IntentScope = IntentScope::SenderSignedTransaction;
4457
4458    /// Computes the tx digest that encodes the Rust type prefix from Signable trait.
4459    fn digest(&self) -> Self::DigestType {
4460        self.intent_message().value.digest()
4461    }
4462}
4463
4464impl<S> Envelope<SenderSignedData, S> {
4465    pub fn sender_address(&self) -> SuiAddress {
4466        self.data().intent_message().value.sender()
4467    }
4468
4469    pub fn gas_owner(&self) -> SuiAddress {
4470        self.data().intent_message().value.gas_owner()
4471    }
4472
4473    pub fn gas(&self) -> &[ObjectRef] {
4474        self.data().intent_message().value.gas()
4475    }
4476
4477    pub fn is_consensus_tx(&self) -> bool {
4478        self.transaction_data().has_funds_withdrawals()
4479            || self.shared_input_objects().next().is_some()
4480    }
4481
4482    pub fn shared_input_objects(&self) -> impl Iterator<Item = SharedInputObject> + '_ {
4483        self.data()
4484            .inner()
4485            .intent_message
4486            .value
4487            .shared_input_objects()
4488            .into_iter()
4489    }
4490
4491    // Returns the primary key for this transaction.
4492    pub fn key(&self) -> TransactionKey {
4493        match &self.data().intent_message().value.kind() {
4494            TransactionKind::RandomnessStateUpdate(rsu) => {
4495                TransactionKey::RandomnessRound(rsu.epoch, rsu.randomness_round)
4496            }
4497            _ => TransactionKey::Digest(*self.digest()),
4498        }
4499    }
4500
4501    // Returns non-Digest keys that could be used to refer to this transaction.
4502    //
4503    // At the moment this returns a single Option for efficiency, but if more key types are added,
4504    // the return type could change to Vec<TransactionKey>.
4505    pub fn non_digest_key(&self) -> Option<TransactionKey> {
4506        match &self.data().intent_message().value.kind() {
4507            TransactionKind::RandomnessStateUpdate(rsu) => Some(TransactionKey::RandomnessRound(
4508                rsu.epoch,
4509                rsu.randomness_round,
4510            )),
4511            _ => None,
4512        }
4513    }
4514
4515    pub fn is_system_tx(&self) -> bool {
4516        self.data().intent_message().value.is_system_tx()
4517    }
4518
4519    pub fn is_sponsored_tx(&self) -> bool {
4520        self.data().intent_message().value.is_sponsored_tx()
4521    }
4522}
4523
4524impl Transaction {
4525    pub fn from_data_and_signer(
4526        data: TransactionData,
4527        signers: Vec<&dyn Signer<Signature>>,
4528    ) -> Self {
4529        let signatures = {
4530            let intent_msg = IntentMessage::new(Intent::sui_transaction(), &data);
4531            signers
4532                .into_iter()
4533                .map(|s| Signature::new_secure(&intent_msg, s))
4534                .collect()
4535        };
4536        Self::from_data(data, signatures)
4537    }
4538
4539    // TODO: Rename this function and above to make it clearer.
4540    pub fn from_data(data: TransactionData, signatures: Vec<Signature>) -> Self {
4541        Self::from_generic_sig_data(data, signatures.into_iter().map(|s| s.into()).collect())
4542    }
4543
4544    pub fn signature_from_signer(
4545        data: TransactionData,
4546        intent: Intent,
4547        signer: &dyn Signer<Signature>,
4548    ) -> Signature {
4549        let intent_msg = IntentMessage::new(intent, data);
4550        Signature::new_secure(&intent_msg, signer)
4551    }
4552
4553    pub fn from_generic_sig_data(data: TransactionData, signatures: Vec<GenericSignature>) -> Self {
4554        Self::new(SenderSignedData::new(data, signatures))
4555    }
4556
4557    /// Returns the Base64 encoded tx_bytes
4558    /// and a list of Base64 encoded [enum GenericSignature].
4559    pub fn to_tx_bytes_and_signatures(&self) -> (Base64, Vec<Base64>) {
4560        (
4561            Base64::from_bytes(&bcs::to_bytes(&self.data().intent_message().value).unwrap()),
4562            self.data()
4563                .inner()
4564                .tx_signatures
4565                .iter()
4566                .map(|s| Base64::from_bytes(s.as_ref()))
4567                .collect(),
4568        )
4569    }
4570}
4571
4572impl VerifiedTransaction {
4573    pub fn new_change_epoch(
4574        next_epoch: EpochId,
4575        protocol_version: ProtocolVersion,
4576        storage_charge: u64,
4577        computation_charge: u64,
4578        storage_rebate: u64,
4579        non_refundable_storage_fee: u64,
4580        epoch_start_timestamp_ms: u64,
4581        system_packages: Vec<(SequenceNumber, Vec<Vec<u8>>, Vec<ObjectID>)>,
4582    ) -> Self {
4583        ChangeEpoch {
4584            epoch: next_epoch,
4585            protocol_version,
4586            storage_charge,
4587            computation_charge,
4588            storage_rebate,
4589            non_refundable_storage_fee,
4590            epoch_start_timestamp_ms,
4591            system_packages,
4592        }
4593        .pipe(TransactionKind::ChangeEpoch)
4594        .pipe(Self::new_system_transaction)
4595    }
4596
4597    pub fn new_genesis_transaction(objects: Vec<GenesisObject>) -> Self {
4598        GenesisTransaction { objects }
4599            .pipe(TransactionKind::Genesis)
4600            .pipe(Self::new_system_transaction)
4601    }
4602
4603    pub fn new_consensus_commit_prologue(
4604        epoch: u64,
4605        round: u64,
4606        commit_timestamp_ms: CheckpointTimestamp,
4607    ) -> Self {
4608        ConsensusCommitPrologue {
4609            epoch,
4610            round,
4611            commit_timestamp_ms,
4612        }
4613        .pipe(TransactionKind::ConsensusCommitPrologue)
4614        .pipe(Self::new_system_transaction)
4615    }
4616
4617    pub fn new_consensus_commit_prologue_v2(
4618        epoch: u64,
4619        round: u64,
4620        commit_timestamp_ms: CheckpointTimestamp,
4621        consensus_commit_digest: ConsensusCommitDigest,
4622    ) -> Self {
4623        ConsensusCommitPrologueV2 {
4624            epoch,
4625            round,
4626            commit_timestamp_ms,
4627            consensus_commit_digest,
4628        }
4629        .pipe(TransactionKind::ConsensusCommitPrologueV2)
4630        .pipe(Self::new_system_transaction)
4631    }
4632
4633    pub fn new_consensus_commit_prologue_v3(
4634        epoch: u64,
4635        round: u64,
4636        commit_timestamp_ms: CheckpointTimestamp,
4637        consensus_commit_digest: ConsensusCommitDigest,
4638        consensus_determined_version_assignments: ConsensusDeterminedVersionAssignments,
4639    ) -> Self {
4640        ConsensusCommitPrologueV3 {
4641            epoch,
4642            round,
4643            // sub_dag_index is reserved for when we have multi commits per round.
4644            sub_dag_index: None,
4645            commit_timestamp_ms,
4646            consensus_commit_digest,
4647            consensus_determined_version_assignments,
4648        }
4649        .pipe(TransactionKind::ConsensusCommitPrologueV3)
4650        .pipe(Self::new_system_transaction)
4651    }
4652
4653    pub fn new_consensus_commit_prologue_v4(
4654        epoch: u64,
4655        round: u64,
4656        commit_timestamp_ms: CheckpointTimestamp,
4657        consensus_commit_digest: ConsensusCommitDigest,
4658        consensus_determined_version_assignments: ConsensusDeterminedVersionAssignments,
4659        additional_state_digest: AdditionalConsensusStateDigest,
4660    ) -> Self {
4661        ConsensusCommitPrologueV4 {
4662            epoch,
4663            round,
4664            // sub_dag_index is reserved for when we have multi commits per round.
4665            sub_dag_index: None,
4666            commit_timestamp_ms,
4667            consensus_commit_digest,
4668            consensus_determined_version_assignments,
4669            additional_state_digest,
4670        }
4671        .pipe(TransactionKind::ConsensusCommitPrologueV4)
4672        .pipe(Self::new_system_transaction)
4673    }
4674
4675    pub fn new_authenticator_state_update(
4676        epoch: u64,
4677        round: u64,
4678        new_active_jwks: Vec<ActiveJwk>,
4679        authenticator_obj_initial_shared_version: SequenceNumber,
4680    ) -> Self {
4681        AuthenticatorStateUpdate {
4682            epoch,
4683            round,
4684            new_active_jwks,
4685            authenticator_obj_initial_shared_version,
4686        }
4687        .pipe(TransactionKind::AuthenticatorStateUpdate)
4688        .pipe(Self::new_system_transaction)
4689    }
4690
4691    pub fn new_randomness_state_update(
4692        epoch: u64,
4693        randomness_round: RandomnessRound,
4694        random_bytes: Vec<u8>,
4695        randomness_obj_initial_shared_version: SequenceNumber,
4696    ) -> Self {
4697        RandomnessStateUpdate {
4698            epoch,
4699            randomness_round,
4700            random_bytes,
4701            randomness_obj_initial_shared_version,
4702        }
4703        .pipe(TransactionKind::RandomnessStateUpdate)
4704        .pipe(Self::new_system_transaction)
4705    }
4706
4707    pub fn new_end_of_epoch_transaction(txns: Vec<EndOfEpochTransactionKind>) -> Self {
4708        TransactionKind::EndOfEpochTransaction(txns).pipe(Self::new_system_transaction)
4709    }
4710
4711    pub fn new_system_transaction(system_transaction: TransactionKind) -> Self {
4712        system_transaction
4713            .pipe(TransactionData::new_system_transaction)
4714            .pipe(|data| {
4715                SenderSignedData::new_from_sender_signature(
4716                    data,
4717                    Ed25519SuiSignature::from_bytes(&[0; Ed25519SuiSignature::LENGTH])
4718                        .unwrap()
4719                        .into(),
4720                )
4721            })
4722            .pipe(Transaction::new)
4723            .pipe(Self::new_from_verified)
4724    }
4725}
4726
4727impl VerifiedSignedTransaction {
4728    /// Use signing key to create a signed object.
4729    pub fn new(
4730        epoch: EpochId,
4731        transaction: VerifiedTransaction,
4732        authority: AuthorityName,
4733        secret: &dyn Signer<AuthoritySignature>,
4734    ) -> Self {
4735        Self::new_from_verified(SignedTransaction::new(
4736            epoch,
4737            transaction.into_inner().into_data(),
4738            secret,
4739            authority,
4740        ))
4741    }
4742}
4743
4744/// A transaction that is signed by a sender but not yet by an authority.
4745pub type Transaction = Envelope<SenderSignedData, EmptySignInfo>;
4746pub type VerifiedTransaction = VerifiedEnvelope<SenderSignedData, EmptySignInfo>;
4747pub type TrustedTransaction = TrustedEnvelope<SenderSignedData, EmptySignInfo>;
4748
4749/// A transaction that is signed by a sender and also by an authority.
4750pub type SignedTransaction = Envelope<SenderSignedData, AuthoritySignInfo>;
4751pub type VerifiedSignedTransaction = VerifiedEnvelope<SenderSignedData, AuthoritySignInfo>;
4752
4753impl Transaction {
4754    pub fn verify_signature_for_testing(
4755        &self,
4756        current_epoch: EpochId,
4757        verify_params: &VerifyParams,
4758    ) -> SuiResult {
4759        verify_sender_signed_data_message_signatures(
4760            self.data(),
4761            current_epoch,
4762            verify_params,
4763            Arc::new(VerifiedDigestCache::new_empty()),
4764            vec![],
4765        )?;
4766        Ok(())
4767    }
4768
4769    pub fn try_into_verified_for_testing(
4770        self,
4771        current_epoch: EpochId,
4772        verify_params: &VerifyParams,
4773    ) -> SuiResult<VerifiedTransaction> {
4774        self.verify_signature_for_testing(current_epoch, verify_params)?;
4775        Ok(VerifiedTransaction::new_from_verified(self))
4776    }
4777}
4778
4779impl SignedTransaction {
4780    pub fn verify_signatures_authenticated_for_testing(
4781        &self,
4782        committee: &Committee,
4783        verify_params: &VerifyParams,
4784    ) -> SuiResult {
4785        verify_sender_signed_data_message_signatures(
4786            self.data(),
4787            committee.epoch(),
4788            verify_params,
4789            Arc::new(VerifiedDigestCache::new_empty()),
4790            vec![],
4791        )?;
4792
4793        self.auth_sig().verify_secure(
4794            self.data(),
4795            Intent::sui_app(IntentScope::SenderSignedTransaction),
4796            committee,
4797        )
4798    }
4799
4800    pub fn try_into_verified_for_testing(
4801        self,
4802        committee: &Committee,
4803        verify_params: &VerifyParams,
4804    ) -> SuiResult<VerifiedSignedTransaction> {
4805        self.verify_signatures_authenticated_for_testing(committee, verify_params)?;
4806        Ok(VerifiedSignedTransaction::new_from_verified(self))
4807    }
4808}
4809
4810pub type CertifiedTransaction = Envelope<SenderSignedData, AuthorityStrongQuorumSignInfo>;
4811
4812impl CertifiedTransaction {
4813    pub fn gas_price(&self) -> u64 {
4814        self.data().transaction_data().gas_price()
4815    }
4816}
4817
4818pub type VerifiedCertificate = VerifiedEnvelope<SenderSignedData, AuthorityStrongQuorumSignInfo>;
4819pub type TrustedCertificate = TrustedEnvelope<SenderSignedData, AuthorityStrongQuorumSignInfo>;
4820
4821#[derive(Clone, Debug, Serialize, Deserialize)]
4822pub struct WithAliases<T>(
4823    T,
4824    #[serde(with = "nonempty_as_vec")] NonEmpty<(u8, Option<SequenceNumber>)>,
4825);
4826
4827impl<T> WithAliases<T> {
4828    pub fn new(tx: T, aliases: NonEmpty<(u8, Option<SequenceNumber>)>) -> Self {
4829        Self(tx, aliases)
4830    }
4831
4832    pub fn tx(&self) -> &T {
4833        &self.0
4834    }
4835
4836    pub fn aliases(&self) -> &NonEmpty<(u8, Option<SequenceNumber>)> {
4837        &self.1
4838    }
4839
4840    pub fn into_tx(self) -> T {
4841        self.0
4842    }
4843
4844    pub fn into_aliases(self) -> NonEmpty<(u8, Option<SequenceNumber>)> {
4845        self.1
4846    }
4847
4848    pub fn into_inner(self) -> (T, NonEmpty<(u8, Option<SequenceNumber>)>) {
4849        (self.0, self.1)
4850    }
4851}
4852
4853impl<T: Message, S> WithAliases<VerifiedEnvelope<T, S>> {
4854    /// Analogous to VerifiedEnvelope::serializable.
4855    pub fn serializable(self) -> WithAliases<TrustedEnvelope<T, S>> {
4856        WithAliases(self.0.serializable(), self.1)
4857    }
4858}
4859
4860impl<S> WithAliases<Envelope<SenderSignedData, S>> {
4861    /// Creates a WithAliases where each required signer is mapped to its corresponding
4862    /// signature index (assuming 1:1 correspondence) with no alias object version.
4863    pub fn no_aliases(tx: Envelope<SenderSignedData, S>) -> Self {
4864        let required_signers = tx.intent_message().value.required_signers();
4865        assert_eq!(required_signers.len(), tx.tx_signatures().len());
4866        let no_aliases = required_signers
4867            .iter()
4868            .enumerate()
4869            .map(|(idx, _)| (idx as u8, None))
4870            .collect::<Vec<_>>();
4871        Self::new(
4872            tx,
4873            NonEmpty::from_vec(no_aliases).expect("must have at least one required_signer"),
4874        )
4875    }
4876}
4877
4878impl<S> WithAliases<VerifiedEnvelope<SenderSignedData, S>> {
4879    /// Creates a WithAliases where each required signer is mapped to its corresponding
4880    /// signature index (assuming 1:1 correspondence) with no alias object version.
4881    pub fn no_aliases(tx: VerifiedEnvelope<SenderSignedData, S>) -> Self {
4882        let required_signers = tx.intent_message().value.required_signers();
4883        assert_eq!(required_signers.len(), tx.tx_signatures().len());
4884        let no_aliases = required_signers
4885            .iter()
4886            .enumerate()
4887            .map(|(idx, _)| (idx as u8, None))
4888            .collect::<Vec<_>>();
4889        Self::new(
4890            tx,
4891            NonEmpty::from_vec(no_aliases).expect("must have at least one required_signer"),
4892        )
4893    }
4894}
4895
4896pub type TransactionWithAliases = WithAliases<Transaction>;
4897pub type VerifiedTransactionWithAliases = WithAliases<VerifiedTransaction>;
4898pub type TrustedTransactionWithAliases = WithAliases<TrustedTransaction>;
4899
4900/// Deprecated version of WithAliases that uses SuiAddress instead of u8.
4901/// This is needed to read data from deferred_transactions_with_aliases_v2 table
4902/// which was written with the old format before the type was changed.
4903// TODO: Delete this after all production networks are on the latest table.
4904#[derive(Clone, Debug, Serialize, Deserialize)]
4905pub struct DeprecatedWithAliases<T>(
4906    T,
4907    #[serde(with = "nonempty_as_vec")] NonEmpty<(SuiAddress, Option<SequenceNumber>)>,
4908);
4909
4910impl<T> DeprecatedWithAliases<T> {
4911    pub fn into_inner(self) -> (T, NonEmpty<(SuiAddress, Option<SequenceNumber>)>) {
4912        (self.0, self.1)
4913    }
4914}
4915
4916impl<T: Message, S> From<WithAliases<VerifiedEnvelope<T, S>>> for WithAliases<Envelope<T, S>> {
4917    fn from(value: WithAliases<VerifiedEnvelope<T, S>>) -> Self {
4918        Self(value.0.into(), value.1)
4919    }
4920}
4921
4922impl<T: Message, S> From<WithAliases<TrustedEnvelope<T, S>>>
4923    for WithAliases<VerifiedEnvelope<T, S>>
4924{
4925    fn from(value: WithAliases<TrustedEnvelope<T, S>>) -> Self {
4926        Self(value.0.into(), value.1)
4927    }
4928}
4929
4930mod nonempty_as_vec {
4931    use super::*;
4932    use serde::{Deserialize, Deserializer, Serialize, Serializer};
4933
4934    pub fn serialize<S, T>(value: &NonEmpty<T>, serializer: S) -> Result<S::Ok, S::Error>
4935    where
4936        S: Serializer,
4937        T: Serialize,
4938    {
4939        let vec: Vec<&T> = value.iter().collect();
4940        vec.serialize(serializer)
4941    }
4942
4943    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<NonEmpty<T>, D::Error>
4944    where
4945        D: Deserializer<'de>,
4946        T: Deserialize<'de> + Clone,
4947    {
4948        use serde::de::{SeqAccess, Visitor};
4949        use std::fmt;
4950        use std::marker::PhantomData;
4951
4952        struct NonEmptyVisitor<T>(PhantomData<T>);
4953
4954        impl<'de, T> Visitor<'de> for NonEmptyVisitor<T>
4955        where
4956            T: Deserialize<'de> + Clone,
4957        {
4958            type Value = NonEmpty<T>;
4959
4960            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4961                formatter.write_str("a non-empty sequence")
4962            }
4963
4964            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
4965            where
4966                A: SeqAccess<'de>,
4967            {
4968                let head = seq
4969                    .next_element()?
4970                    .ok_or_else(|| serde::de::Error::custom("empty vector"))?;
4971
4972                let mut tail = Vec::new();
4973                while let Some(elem) = seq.next_element()? {
4974                    tail.push(elem);
4975                }
4976
4977                Ok(NonEmpty { head, tail })
4978            }
4979        }
4980
4981        deserializer.deserialize_seq(NonEmptyVisitor(PhantomData))
4982    }
4983}
4984
4985// =============================================================================
4986// TransactionWithClaims - Generalized claim system for consensus messages
4987// =============================================================================
4988
4989/// Claims that can be attached to a transaction for consensus validation.
4990/// Each claim type represents a piece of information that:
4991/// 1. The submitting validator includes in the consensus message
4992/// 2. Voting validators verify before accepting
4993/// 3. The consensus handler can use deterministically
4994#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
4995pub enum TransactionClaim {
4996    /// DEPRECATED. Do not use.
4997    #[deprecated(note = "Use AddressAliasesV2")]
4998    AddressAliases(
4999        #[serde(with = "nonempty_as_vec")] NonEmpty<(SuiAddress, Option<SequenceNumber>)>,
5000    ),
5001
5002    /// Object IDs that are claimed to be immutable.
5003    /// Used to filter out immutable objects from lock acquisition in consensus handler.
5004    ImmutableInputObjects(Vec<ObjectID>),
5005
5006    /// Address aliases used for signature verification.
5007    /// Length must equal the number of `required_signers`. Each element maps the corresponding
5008    /// signer to the signature index and alias object version (if any) used to verify it.
5009    AddressAliasesV2(#[serde(with = "nonempty_as_vec")] NonEmpty<(u8, Option<SequenceNumber>)>),
5010}
5011
5012/// A transaction with attached claims that have been verified by voting validators.
5013#[derive(Clone, Debug, Serialize, Deserialize)]
5014pub struct TransactionWithClaims<T> {
5015    tx: T,
5016    claims: Vec<TransactionClaim>,
5017}
5018
5019impl<T> TransactionWithClaims<T> {
5020    pub fn new(tx: T, claims: Vec<TransactionClaim>) -> Self {
5021        Self { tx, claims }
5022    }
5023
5024    /// Create from a transaction with only address aliases.
5025    pub fn from_aliases(tx: T, aliases: NonEmpty<(u8, Option<SequenceNumber>)>) -> Self {
5026        Self {
5027            tx,
5028            claims: vec![TransactionClaim::AddressAliasesV2(aliases)],
5029        }
5030    }
5031
5032    /// Creates from a transaction without any aliases attached.
5033    pub fn no_aliases(tx: T) -> Self {
5034        Self { tx, claims: vec![] }
5035    }
5036
5037    pub fn tx(&self) -> &T {
5038        &self.tx
5039    }
5040
5041    pub fn into_tx(self) -> T {
5042        self.tx
5043    }
5044
5045    /// Get the address aliases V2 claim. Differentiate between empty and not present for validation.
5046    pub fn aliases(&self) -> Option<NonEmpty<(u8, Option<SequenceNumber>)>> {
5047        self.claims
5048            .iter()
5049            .find_map(|c| match c {
5050                TransactionClaim::AddressAliasesV2(aliases) => Some(aliases),
5051                _ => None,
5052            })
5053            .cloned()
5054    }
5055
5056    // TODO: Remove once `fix_checkpoint_signature_mapping` flag is enabled in testnet.
5057    #[allow(deprecated)]
5058    pub fn aliases_v1(&self) -> Option<NonEmpty<(SuiAddress, Option<SequenceNumber>)>> {
5059        self.claims
5060            .iter()
5061            .find_map(|c| match c {
5062                TransactionClaim::AddressAliases(aliases) => Some(aliases),
5063                _ => None,
5064            })
5065            .cloned()
5066    }
5067
5068    /// Get the immutable input objects claim. Returns empty vector if not present.
5069    pub fn get_immutable_objects(&self) -> Vec<ObjectID> {
5070        self.claims
5071            .iter()
5072            .find_map(|c| match c {
5073                TransactionClaim::ImmutableInputObjects(objs) => Some(objs.clone()),
5074                _ => None,
5075            })
5076            .unwrap_or_default()
5077    }
5078}
5079
5080pub type PlainTransactionWithClaims = TransactionWithClaims<Transaction>;
5081
5082/// Convert from `WithAliases<VerifiedEnvelope>` to `TransactionWithClaims<Envelope>`.
5083/// Used when feature flag is off to convert existing WithAliases to the new type.
5084impl<T: Message, S> From<WithAliases<VerifiedEnvelope<T, S>>>
5085    for TransactionWithClaims<Envelope<T, S>>
5086{
5087    fn from(value: WithAliases<VerifiedEnvelope<T, S>>) -> Self {
5088        let (tx, aliases) = value.into_inner();
5089        Self::from_aliases(tx.into(), aliases)
5090    }
5091}
5092
5093#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord, Hash)]
5094pub enum InputObjectKind {
5095    // A Move package, must be immutable.
5096    MovePackage(ObjectID),
5097    // A Move object, either immutable, or owned mutable.
5098    ImmOrOwnedMoveObject(ObjectRef),
5099    // A Move object that's shared and mutable.
5100    SharedMoveObject {
5101        id: ObjectID,
5102        initial_shared_version: SequenceNumber,
5103        mutability: SharedObjectMutability,
5104    },
5105}
5106
5107#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord, Hash)]
5108pub enum SharedObjectMutability {
5109    // The "classic" mutable/immutable modes.
5110    Immutable,
5111    Mutable,
5112    // Non-exclusive write is used to allow multiple transactions to
5113    // simultaneously add disjoint dynamic fields to an object.
5114    // (Currently only used by settlement transactions).
5115    NonExclusiveWrite,
5116}
5117
5118impl SharedObjectMutability {
5119    pub fn is_exclusive(&self) -> bool {
5120        match self {
5121            SharedObjectMutability::Mutable => true,
5122            SharedObjectMutability::Immutable => false,
5123            SharedObjectMutability::NonExclusiveWrite => false,
5124        }
5125    }
5126}
5127
5128impl InputObjectKind {
5129    pub fn object_id(&self) -> ObjectID {
5130        self.full_object_id().id()
5131    }
5132
5133    pub fn full_object_id(&self) -> FullObjectID {
5134        match self {
5135            Self::MovePackage(id) => FullObjectID::Fastpath(*id),
5136            Self::ImmOrOwnedMoveObject((id, _, _)) => FullObjectID::Fastpath(*id),
5137            Self::SharedMoveObject {
5138                id,
5139                initial_shared_version,
5140                ..
5141            } => FullObjectID::Consensus((*id, *initial_shared_version)),
5142        }
5143    }
5144
5145    pub fn version(&self) -> Option<SequenceNumber> {
5146        match self {
5147            Self::MovePackage(..) => None,
5148            Self::ImmOrOwnedMoveObject((_, version, _)) => Some(*version),
5149            Self::SharedMoveObject { .. } => None,
5150        }
5151    }
5152
5153    pub fn object_not_found_error(&self) -> UserInputError {
5154        match *self {
5155            Self::MovePackage(package_id) => {
5156                UserInputError::DependentPackageNotFound { package_id }
5157            }
5158            Self::ImmOrOwnedMoveObject((object_id, version, _)) => UserInputError::ObjectNotFound {
5159                object_id,
5160                version: Some(version),
5161            },
5162            Self::SharedMoveObject { id, .. } => UserInputError::ObjectNotFound {
5163                object_id: id,
5164                version: None,
5165            },
5166        }
5167    }
5168
5169    pub fn is_shared_object(&self) -> bool {
5170        matches!(self, Self::SharedMoveObject { .. })
5171    }
5172}
5173
5174/// The result of reading an object for execution. Because shared objects may be deleted, one
5175/// possible result of reading a shared object is that ObjectReadResultKind::Deleted is returned.
5176#[derive(Clone, Debug)]
5177pub struct ObjectReadResult {
5178    pub input_object_kind: InputObjectKind,
5179    pub object: ObjectReadResultKind,
5180}
5181
5182#[derive(Clone)]
5183pub enum ObjectReadResultKind {
5184    Object(Object),
5185    // The version of the object that the transaction intended to read, and the digest of the tx
5186    // that removed it from consensus.
5187    ObjectConsensusStreamEnded(SequenceNumber, TransactionDigest),
5188    // A shared object in a cancelled transaction. The sequence number embeds cancellation reason.
5189    CancelledTransactionSharedObject(SequenceNumber),
5190}
5191
5192impl ObjectReadResultKind {
5193    pub fn is_cancelled(&self) -> bool {
5194        matches!(
5195            self,
5196            ObjectReadResultKind::CancelledTransactionSharedObject(_)
5197        )
5198    }
5199
5200    pub fn version(&self) -> SequenceNumber {
5201        match self {
5202            ObjectReadResultKind::Object(object) => object.version(),
5203            ObjectReadResultKind::ObjectConsensusStreamEnded(seq, _) => *seq,
5204            ObjectReadResultKind::CancelledTransactionSharedObject(seq) => *seq,
5205        }
5206    }
5207}
5208
5209impl std::fmt::Debug for ObjectReadResultKind {
5210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5211        match self {
5212            ObjectReadResultKind::Object(obj) => {
5213                write!(f, "Object({:?})", obj.compute_object_reference())
5214            }
5215            ObjectReadResultKind::ObjectConsensusStreamEnded(seq, digest) => {
5216                write!(f, "ObjectConsensusStreamEnded({}, {:?})", seq, digest)
5217            }
5218            ObjectReadResultKind::CancelledTransactionSharedObject(seq) => {
5219                write!(f, "CancelledTransactionSharedObject({})", seq)
5220            }
5221        }
5222    }
5223}
5224
5225impl From<Object> for ObjectReadResultKind {
5226    fn from(object: Object) -> Self {
5227        Self::Object(object)
5228    }
5229}
5230
5231impl ObjectReadResult {
5232    pub fn new(input_object_kind: InputObjectKind, object: ObjectReadResultKind) -> Self {
5233        if let (
5234            InputObjectKind::ImmOrOwnedMoveObject(_),
5235            ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
5236        ) = (&input_object_kind, &object)
5237        {
5238            panic!("only consensus objects can be ObjectConsensusStreamEnded");
5239        }
5240
5241        if let (
5242            InputObjectKind::ImmOrOwnedMoveObject(_),
5243            ObjectReadResultKind::CancelledTransactionSharedObject(_),
5244        ) = (&input_object_kind, &object)
5245        {
5246            panic!("only consensus objects can be CancelledTransactionSharedObject");
5247        }
5248
5249        Self {
5250            input_object_kind,
5251            object,
5252        }
5253    }
5254
5255    pub fn id(&self) -> ObjectID {
5256        self.input_object_kind.object_id()
5257    }
5258
5259    pub fn as_object(&self) -> Option<&Object> {
5260        match &self.object {
5261            ObjectReadResultKind::Object(object) => Some(object),
5262            ObjectReadResultKind::ObjectConsensusStreamEnded(_, _) => None,
5263            ObjectReadResultKind::CancelledTransactionSharedObject(_) => None,
5264        }
5265    }
5266
5267    pub fn new_from_gas_object(gas: &Object) -> Self {
5268        let objref = gas.compute_object_reference();
5269        Self {
5270            input_object_kind: InputObjectKind::ImmOrOwnedMoveObject(objref),
5271            object: ObjectReadResultKind::Object(gas.clone()),
5272        }
5273    }
5274
5275    pub fn is_mutable(&self) -> bool {
5276        match (&self.input_object_kind, &self.object) {
5277            (InputObjectKind::MovePackage(_), _) => false,
5278            (InputObjectKind::ImmOrOwnedMoveObject(_), ObjectReadResultKind::Object(object)) => {
5279                !object.is_immutable()
5280            }
5281            (
5282                InputObjectKind::ImmOrOwnedMoveObject(_),
5283                ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
5284            ) => unreachable!(),
5285            (
5286                InputObjectKind::ImmOrOwnedMoveObject(_),
5287                ObjectReadResultKind::CancelledTransactionSharedObject(_),
5288            ) => unreachable!(),
5289            (InputObjectKind::SharedMoveObject { mutability, .. }, _) => match mutability {
5290                SharedObjectMutability::Mutable => true,
5291                SharedObjectMutability::Immutable => false,
5292                SharedObjectMutability::NonExclusiveWrite => false,
5293            },
5294        }
5295    }
5296
5297    pub fn is_shared_object(&self) -> bool {
5298        self.input_object_kind.is_shared_object()
5299    }
5300
5301    pub fn is_consensus_stream_ended(&self) -> bool {
5302        self.consensus_stream_end_info().is_some()
5303    }
5304
5305    pub fn consensus_stream_end_info(&self) -> Option<(SequenceNumber, TransactionDigest)> {
5306        match &self.object {
5307            ObjectReadResultKind::ObjectConsensusStreamEnded(v, tx) => Some((*v, *tx)),
5308            _ => None,
5309        }
5310    }
5311
5312    /// Return the object ref iff the object is an address-owned object (i.e. not shared, not immutable).
5313    pub fn get_address_owned_objref(&self) -> Option<ObjectRef> {
5314        match (&self.input_object_kind, &self.object) {
5315            (InputObjectKind::MovePackage(_), _) => None,
5316            (
5317                InputObjectKind::ImmOrOwnedMoveObject(objref),
5318                ObjectReadResultKind::Object(object),
5319            ) => {
5320                if object.is_immutable() {
5321                    None
5322                } else {
5323                    Some(*objref)
5324                }
5325            }
5326            (
5327                InputObjectKind::ImmOrOwnedMoveObject(_),
5328                ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
5329            ) => unreachable!(),
5330            (
5331                InputObjectKind::ImmOrOwnedMoveObject(_),
5332                ObjectReadResultKind::CancelledTransactionSharedObject(_),
5333            ) => unreachable!(),
5334            (InputObjectKind::SharedMoveObject { .. }, _) => None,
5335        }
5336    }
5337
5338    pub fn is_address_owned(&self) -> bool {
5339        self.get_address_owned_objref().is_some()
5340    }
5341
5342    pub fn is_replay_protected_input(&self) -> bool {
5343        if let InputObjectKind::ImmOrOwnedMoveObject(obj_ref) = &self.input_object_kind
5344            && ParsedDigest::is_coin_reservation_digest(&obj_ref.2)
5345        {
5346            true
5347        } else {
5348            self.is_address_owned()
5349        }
5350    }
5351
5352    pub fn to_shared_input(&self) -> Option<SharedInput> {
5353        match self.input_object_kind {
5354            InputObjectKind::MovePackage(_) => None,
5355            InputObjectKind::ImmOrOwnedMoveObject(_) => None,
5356            InputObjectKind::SharedMoveObject { id, mutability, .. } => Some(match &self.object {
5357                ObjectReadResultKind::Object(obj) => {
5358                    SharedInput::Existing(obj.compute_object_reference())
5359                }
5360                ObjectReadResultKind::ObjectConsensusStreamEnded(seq, digest) => {
5361                    SharedInput::ConsensusStreamEnded((id, *seq, mutability, *digest))
5362                }
5363                ObjectReadResultKind::CancelledTransactionSharedObject(seq) => {
5364                    SharedInput::Cancelled((id, *seq))
5365                }
5366            }),
5367        }
5368    }
5369
5370    pub fn get_previous_transaction(&self) -> Option<TransactionDigest> {
5371        match &self.object {
5372            ObjectReadResultKind::Object(obj) => Some(obj.previous_transaction),
5373            ObjectReadResultKind::ObjectConsensusStreamEnded(_, digest) => Some(*digest),
5374            ObjectReadResultKind::CancelledTransactionSharedObject(_) => None,
5375        }
5376    }
5377}
5378
5379#[derive(Clone)]
5380pub struct InputObjects {
5381    objects: Vec<ObjectReadResult>,
5382}
5383
5384impl std::fmt::Debug for InputObjects {
5385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5386        f.debug_list().entries(self.objects.iter()).finish()
5387    }
5388}
5389
5390// An InputObjects new-type that has been verified by sui-transaction-checks, and can be
5391// safely passed to execution.
5392#[derive(Clone)]
5393pub struct CheckedInputObjects(InputObjects);
5394
5395// DO NOT CALL outside of sui-transaction-checks, genesis, or replay.
5396//
5397// CheckedInputObjects should really be defined in sui-transaction-checks so that we can
5398// make public construction impossible. But we can't do that because it would result in circular
5399// dependencies.
5400impl CheckedInputObjects {
5401    // Only called by sui-transaction-checks.
5402    pub fn new_with_checked_transaction_inputs(inputs: InputObjects) -> Self {
5403        Self(inputs)
5404    }
5405
5406    // Only called when building the genesis transaction
5407    pub fn new_for_genesis(input_objects: Vec<ObjectReadResult>) -> Self {
5408        Self(InputObjects::new(input_objects))
5409    }
5410
5411    // Only called from the replay tool.
5412    pub fn new_for_replay(input_objects: InputObjects) -> Self {
5413        Self(input_objects)
5414    }
5415
5416    pub fn inner(&self) -> &InputObjects {
5417        &self.0
5418    }
5419
5420    pub fn into_inner(self) -> InputObjects {
5421        self.0
5422    }
5423}
5424
5425impl From<Vec<ObjectReadResult>> for InputObjects {
5426    fn from(objects: Vec<ObjectReadResult>) -> Self {
5427        Self::new(objects)
5428    }
5429}
5430
5431impl InputObjects {
5432    pub fn new(objects: Vec<ObjectReadResult>) -> Self {
5433        Self { objects }
5434    }
5435
5436    pub fn len(&self) -> usize {
5437        self.objects.len()
5438    }
5439
5440    pub fn is_empty(&self) -> bool {
5441        self.objects.is_empty()
5442    }
5443
5444    pub fn contains_consensus_stream_ended_objects(&self) -> bool {
5445        self.objects
5446            .iter()
5447            .any(|obj| obj.is_consensus_stream_ended())
5448    }
5449
5450    // Returns IDs of objects responsible for a transaction being cancelled, and the corresponding
5451    // reason for cancellation.
5452    pub fn get_cancelled_objects(&self) -> Option<(Vec<ObjectID>, SequenceNumber)> {
5453        let mut contains_cancelled = false;
5454        let mut cancel_reason = None;
5455        let mut cancelled_objects = Vec::new();
5456        for obj in &self.objects {
5457            if let ObjectReadResultKind::CancelledTransactionSharedObject(version) = obj.object {
5458                contains_cancelled = true;
5459                if version == SequenceNumber::CONGESTED
5460                    || version == SequenceNumber::RANDOMNESS_UNAVAILABLE
5461                {
5462                    // Verify we don't have multiple cancellation reasons.
5463                    assert!(cancel_reason.is_none() || cancel_reason == Some(version));
5464                    cancel_reason = Some(version);
5465                    cancelled_objects.push(obj.id());
5466                }
5467            }
5468        }
5469
5470        if !cancelled_objects.is_empty() {
5471            Some((
5472                cancelled_objects,
5473                cancel_reason
5474                    .expect("there should be a cancel reason if there are cancelled objects"),
5475            ))
5476        } else {
5477            assert!(!contains_cancelled);
5478            None
5479        }
5480    }
5481
5482    pub fn filter_owned_objects(&self) -> Vec<ObjectRef> {
5483        let owned_objects: Vec<_> = self
5484            .objects
5485            .iter()
5486            .filter_map(|obj| obj.get_address_owned_objref())
5487            .collect();
5488
5489        trace!(
5490            num_mutable_objects = owned_objects.len(),
5491            "Checked locks and found mutable objects"
5492        );
5493
5494        owned_objects
5495    }
5496
5497    pub fn filter_shared_objects(&self) -> Vec<SharedInput> {
5498        self.objects
5499            .iter()
5500            .filter(|obj| obj.is_shared_object())
5501            .map(|obj| {
5502                obj.to_shared_input()
5503                    .expect("already filtered for shared objects")
5504            })
5505            .collect()
5506    }
5507
5508    pub fn transaction_dependencies(&self) -> BTreeSet<TransactionDigest> {
5509        self.objects
5510            .iter()
5511            .filter_map(|obj| obj.get_previous_transaction())
5512            .collect()
5513    }
5514
5515    /// All inputs that will be directly mutated by the transaction. This does
5516    /// not include SharedObjectMutability::NonExclusiveWrite inputs.
5517    pub fn exclusive_mutable_inputs(&self) -> BTreeMap<ObjectID, (VersionDigest, Owner)> {
5518        self.mutables_with_input_kinds()
5519            .filter_map(|(id, (version, owner, kind))| match kind {
5520                InputObjectKind::SharedMoveObject { mutability, .. } => match mutability {
5521                    SharedObjectMutability::Mutable => Some((id, (version, owner))),
5522                    SharedObjectMutability::Immutable => None,
5523                    SharedObjectMutability::NonExclusiveWrite => None,
5524                },
5525                _ => Some((id, (version, owner))),
5526            })
5527            .collect()
5528    }
5529
5530    pub fn non_exclusive_input_objects(&self) -> BTreeMap<ObjectID, Object> {
5531        self.objects
5532            .iter()
5533            .filter_map(|read_result| {
5534                match (read_result.as_object(), read_result.input_object_kind) {
5535                    (
5536                        Some(object),
5537                        InputObjectKind::SharedMoveObject {
5538                            mutability: SharedObjectMutability::NonExclusiveWrite,
5539                            ..
5540                        },
5541                    ) => Some((read_result.id(), object.clone())),
5542                    _ => None,
5543                }
5544            })
5545            .collect()
5546    }
5547
5548    /// All inputs that can be taken as &mut T, which includes both
5549    /// SharedObjectMutability::Mutable and SharedObjectMutability::NonExclusiveWrite inputs.
5550    pub fn all_mutable_inputs(&self) -> BTreeMap<ObjectID, (VersionDigest, Owner)> {
5551        self.mutables_with_input_kinds()
5552            .filter_map(|(id, (version, owner, kind))| match kind {
5553                InputObjectKind::SharedMoveObject { mutability, .. } => match mutability {
5554                    SharedObjectMutability::Mutable => Some((id, (version, owner))),
5555                    SharedObjectMutability::Immutable => None,
5556                    SharedObjectMutability::NonExclusiveWrite => Some((id, (version, owner))),
5557                },
5558                _ => Some((id, (version, owner))),
5559            })
5560            .collect()
5561    }
5562
5563    fn mutables_with_input_kinds(
5564        &self,
5565    ) -> impl Iterator<Item = (ObjectID, (VersionDigest, Owner, InputObjectKind))> + '_ {
5566        self.objects.iter().filter_map(
5567            |ObjectReadResult {
5568                 input_object_kind,
5569                 object,
5570             }| match (input_object_kind, object) {
5571                (InputObjectKind::MovePackage(_), _) => None,
5572                (
5573                    InputObjectKind::ImmOrOwnedMoveObject(object_ref),
5574                    ObjectReadResultKind::Object(object),
5575                ) => {
5576                    if object.is_immutable() {
5577                        None
5578                    } else {
5579                        Some((
5580                            object_ref.0,
5581                            (
5582                                (object_ref.1, object_ref.2),
5583                                object.owner.clone(),
5584                                *input_object_kind,
5585                            ),
5586                        ))
5587                    }
5588                }
5589                (
5590                    InputObjectKind::ImmOrOwnedMoveObject(_),
5591                    ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
5592                ) => {
5593                    unreachable!()
5594                }
5595                (
5596                    InputObjectKind::SharedMoveObject { .. },
5597                    ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
5598                ) => None,
5599                (
5600                    InputObjectKind::SharedMoveObject { mutability, .. },
5601                    ObjectReadResultKind::Object(object),
5602                ) => match *mutability {
5603                    SharedObjectMutability::Mutable => {
5604                        let oref = object.compute_object_reference();
5605                        Some((
5606                            oref.0,
5607                            ((oref.1, oref.2), object.owner.clone(), *input_object_kind),
5608                        ))
5609                    }
5610                    SharedObjectMutability::Immutable => None,
5611                    SharedObjectMutability::NonExclusiveWrite => {
5612                        let oref = object.compute_object_reference();
5613                        Some((
5614                            oref.0,
5615                            ((oref.1, oref.2), object.owner.clone(), *input_object_kind),
5616                        ))
5617                    }
5618                },
5619                (
5620                    InputObjectKind::ImmOrOwnedMoveObject(_),
5621                    ObjectReadResultKind::CancelledTransactionSharedObject(_),
5622                ) => {
5623                    unreachable!()
5624                }
5625                (
5626                    InputObjectKind::SharedMoveObject { .. },
5627                    ObjectReadResultKind::CancelledTransactionSharedObject(_),
5628                ) => None,
5629            },
5630        )
5631    }
5632
5633    /// The version to set on objects created by the computation that `self` is input to.
5634    /// Guaranteed to be strictly greater than the versions of all input objects and objects
5635    /// received in the transaction.
5636    pub fn lamport_timestamp(&self, receiving_objects: &[ObjectRef]) -> SequenceNumber {
5637        let input_versions = self
5638            .objects
5639            .iter()
5640            .filter_map(|object| match &object.object {
5641                ObjectReadResultKind::Object(object) => {
5642                    object.data.try_as_move().map(MoveObject::version)
5643                }
5644                ObjectReadResultKind::ObjectConsensusStreamEnded(v, _) => Some(*v),
5645                ObjectReadResultKind::CancelledTransactionSharedObject(_) => None,
5646            })
5647            .chain(receiving_objects.iter().map(|object_ref| object_ref.1));
5648
5649        SequenceNumber::lamport_increment(input_versions)
5650    }
5651
5652    pub fn object_kinds(&self) -> impl Iterator<Item = &InputObjectKind> {
5653        self.objects.iter().map(
5654            |ObjectReadResult {
5655                 input_object_kind, ..
5656             }| input_object_kind,
5657        )
5658    }
5659
5660    pub fn consensus_stream_ended_objects(&self) -> BTreeMap<ObjectID, SequenceNumber> {
5661        self.objects
5662            .iter()
5663            .filter_map(|obj| {
5664                if let InputObjectKind::SharedMoveObject {
5665                    id,
5666                    initial_shared_version,
5667                    ..
5668                } = obj.input_object_kind
5669                {
5670                    obj.is_consensus_stream_ended()
5671                        .then_some((id, initial_shared_version))
5672                } else {
5673                    None
5674                }
5675            })
5676            .collect()
5677    }
5678
5679    pub fn into_object_map(self) -> BTreeMap<ObjectID, Object> {
5680        self.objects
5681            .into_iter()
5682            .filter_map(|o| o.as_object().map(|object| (o.id(), object.clone())))
5683            .collect()
5684    }
5685
5686    pub fn push(&mut self, object: ObjectReadResult) {
5687        self.objects.push(object);
5688    }
5689
5690    pub fn iter(&self) -> impl Iterator<Item = &ObjectReadResult> {
5691        self.objects.iter()
5692    }
5693
5694    pub fn iter_objects(&self) -> impl Iterator<Item = &Object> {
5695        self.objects.iter().filter_map(|o| o.as_object())
5696    }
5697
5698    pub fn non_exclusive_mutable_inputs(
5699        &self,
5700    ) -> impl Iterator<Item = (ObjectID, SequenceNumber)> + '_ {
5701        self.objects.iter().filter_map(
5702            |ObjectReadResult {
5703                 input_object_kind,
5704                 object,
5705             }| match input_object_kind {
5706                // TODO: this is not exercised yet since settlement transactions cannot be
5707                // cancelled, but if/when we expose non-exclusive writes to users,
5708                // a cancelled transaction should not be considered to have done any writes.
5709                InputObjectKind::SharedMoveObject {
5710                    id,
5711                    mutability: SharedObjectMutability::NonExclusiveWrite,
5712                    ..
5713                } if !object.is_cancelled() => Some((*id, object.version())),
5714                _ => None,
5715            },
5716        )
5717    }
5718}
5719
5720// Result of attempting to read a receiving object (currently only at signing time).
5721// Because an object may have been previously received and deleted, the result may be
5722// ReceivingObjectReadResultKind::PreviouslyReceivedObject.
5723#[derive(Clone, Debug)]
5724pub enum ReceivingObjectReadResultKind {
5725    Object(Object),
5726    // The object was received by some other transaction, and we were not able to read it
5727    PreviouslyReceivedObject,
5728}
5729
5730impl ReceivingObjectReadResultKind {
5731    pub fn as_object(&self) -> Option<&Object> {
5732        match &self {
5733            Self::Object(object) => Some(object),
5734            Self::PreviouslyReceivedObject => None,
5735        }
5736    }
5737}
5738
5739pub struct ReceivingObjectReadResult {
5740    pub object_ref: ObjectRef,
5741    pub object: ReceivingObjectReadResultKind,
5742}
5743
5744impl ReceivingObjectReadResult {
5745    pub fn new(object_ref: ObjectRef, object: ReceivingObjectReadResultKind) -> Self {
5746        Self { object_ref, object }
5747    }
5748
5749    pub fn is_previously_received(&self) -> bool {
5750        matches!(
5751            self.object,
5752            ReceivingObjectReadResultKind::PreviouslyReceivedObject
5753        )
5754    }
5755}
5756
5757impl From<Object> for ReceivingObjectReadResultKind {
5758    fn from(object: Object) -> Self {
5759        Self::Object(object)
5760    }
5761}
5762
5763pub struct ReceivingObjects {
5764    pub objects: Vec<ReceivingObjectReadResult>,
5765}
5766
5767impl ReceivingObjects {
5768    pub fn iter(&self) -> impl Iterator<Item = &ReceivingObjectReadResult> {
5769        self.objects.iter()
5770    }
5771
5772    pub fn iter_objects(&self) -> impl Iterator<Item = &Object> {
5773        self.objects.iter().filter_map(|o| o.object.as_object())
5774    }
5775}
5776
5777impl From<Vec<ReceivingObjectReadResult>> for ReceivingObjects {
5778    fn from(objects: Vec<ReceivingObjectReadResult>) -> Self {
5779        Self { objects }
5780    }
5781}
5782
5783impl Display for CertifiedTransaction {
5784    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
5785        let mut writer = String::new();
5786        writeln!(writer, "Transaction Hash: {:?}", self.digest())?;
5787        writeln!(
5788            writer,
5789            "Signed Authorities Bitmap : {:?}",
5790            self.auth_sig().signers_map
5791        )?;
5792        write!(writer, "{}", self.data().intent_message().value.kind())?;
5793        write!(f, "{}", writer)
5794    }
5795}
5796
5797/// TransactionKey uniquely identifies a transaction across all epochs.
5798/// Note that a single transaction may have multiple keys, for example a RandomnessStateUpdate
5799/// could be identified by both `Digest` and `RandomnessRound`.
5800#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
5801pub enum TransactionKey {
5802    Digest(TransactionDigest),
5803    RandomnessRound(EpochId, RandomnessRound),
5804    AccumulatorSettlement(EpochId, u64 /* checkpoint height */),
5805    ConsensusCommitPrologue(EpochId, u64 /* round */, u32 /* sub_dag_index */),
5806}
5807
5808impl TransactionKey {
5809    pub fn unwrap_digest(&self) -> &TransactionDigest {
5810        match self {
5811            TransactionKey::Digest(d) => d,
5812            _ => panic!("called unwrap_digest on a non-Digest TransactionKey: {self:?}"),
5813        }
5814    }
5815
5816    pub fn as_digest(&self) -> Option<&TransactionDigest> {
5817        match self {
5818            TransactionKey::Digest(d) => Some(d),
5819            _ => None,
5820        }
5821    }
5822}