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