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_v1() {
704                    return Err(UserInputError::Unsupported(
705                        "coin deny list not enabled".to_string(),
706                    ));
707                }
708            }
709            Self::BridgeStateCreate(_) => {
710                if !config.enable_bridge() {
711                    return Err(UserInputError::Unsupported(
712                        "bridge not enabled".to_string(),
713                    ));
714                }
715            }
716            Self::BridgeCommitteeInit(_) => {
717                if !config.enable_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.receiving_objects_supported() {
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). This method aggregates all withdraw operations for the same
2886    /// account by merging their reservations. Each account object ID is derived from the type
2887    /// 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)>>;
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)>>;
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)>> {
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)>> {
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)>> {
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)> = BTreeMap::new();
3561        for withdraw in withdraws {
3562            let reserved_amount = match &withdraw.reservation {
3563                Reservation::MaxAmountU64(amount) => {
3564                    if *amount == 0 {
3565                        return Err(UserInputError::InvalidWithdrawReservation {
3566                            error: "Balance withdraw reservation amount must be non-zero"
3567                                .to_string(),
3568                        });
3569                    }
3570                    *amount
3571                }
3572            };
3573
3574            let account_address = withdraw.owner_for_withdrawal(self);
3575            let type_tag = withdraw.type_arg.to_type_tag();
3576            let account_id =
3577                AccumulatorValue::get_field_id(account_address, &type_tag).map_err(|e| {
3578                    UserInputError::InvalidWithdrawReservation {
3579                        error: e.to_string(),
3580                    }
3581                })?;
3582
3583            let (current_amount, _) = withdraw_map
3584                .entry(account_id)
3585                .or_insert_with(|| (0, type_tag));
3586            *current_amount = current_amount.checked_add(reserved_amount).ok_or(
3587                UserInputError::InvalidWithdrawReservation {
3588                    error: "Balance withdraw reservation overflow".to_string(),
3589                },
3590            )?;
3591        }
3592
3593        Ok(withdraw_map)
3594    }
3595
3596    fn get_funds_withdrawal_for_gas_payment(&self) -> Option<FundsWithdrawalArg> {
3597        if self.is_gas_paid_from_address_balance() && self.gas_data().budget > 0 {
3598            Some(if self.sender() != self.gas_owner() {
3599                FundsWithdrawalArg::balance_from_sponsor(self.gas_data().budget, GAS::type_tag())
3600            } else {
3601                FundsWithdrawalArg::balance_from_sender(self.gas_data().budget, GAS::type_tag())
3602            })
3603        } else {
3604            None
3605        }
3606    }
3607
3608    fn get_funds_withdrawals(&self) -> impl Iterator<Item = FundsWithdrawalArg> + '_ {
3609        self.kind.get_funds_withdrawals().cloned()
3610    }
3611
3612    fn coin_reservation_obj_refs(&self) -> impl Iterator<Item = ObjectRef> {
3613        self.kind
3614            .get_coin_reservation_obj_refs()
3615            .chain(self.gas().iter().filter_map(|gas_ref| {
3616                if ParsedDigest::is_coin_reservation_digest(&gas_ref.2) {
3617                    Some(*gas_ref)
3618                } else {
3619                    None
3620                }
3621            }))
3622    }
3623
3624    fn parsed_coin_reservations(
3625        &self,
3626        chain_identifier: ChainIdentifier,
3627    ) -> impl Iterator<Item = ParsedObjectRefWithdrawal> {
3628        self.coin_reservation_obj_refs().map(move |obj_ref| {
3629            ParsedObjectRefWithdrawal::parse(&obj_ref, chain_identifier).unwrap()
3630        })
3631    }
3632}
3633
3634pub struct TxValidityCheckContext<'a> {
3635    pub config: &'a ProtocolConfig,
3636    pub epoch: EpochId,
3637    pub chain_identifier: ChainIdentifier,
3638    pub reference_gas_price: u64,
3639}
3640
3641impl<'a> TxValidityCheckContext<'a> {
3642    pub fn from_cfg_for_testing(config: &'a ProtocolConfig) -> Self {
3643        Self {
3644            config,
3645            epoch: 0,
3646            chain_identifier: ChainIdentifier::default(),
3647            reference_gas_price: 1000,
3648        }
3649    }
3650}
3651
3652#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
3653pub struct SenderSignedData(SizeOneVec<SenderSignedTransaction>);
3654
3655#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3656pub struct SenderSignedTransaction {
3657    pub intent_message: IntentMessage<TransactionData>,
3658    /// A list of signatures signed by all transaction participants.
3659    /// 1. non participant signature must not be present.
3660    /// 2. signature order does not matter.
3661    pub tx_signatures: Vec<GenericSignature>,
3662}
3663
3664impl Serialize for SenderSignedTransaction {
3665    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3666    where
3667        S: serde::Serializer,
3668    {
3669        #[derive(Serialize)]
3670        #[serde(rename = "SenderSignedTransaction")]
3671        struct SignedTxn<'a> {
3672            intent_message: &'a IntentMessage<TransactionData>,
3673            tx_signatures: &'a Vec<GenericSignature>,
3674        }
3675
3676        if self.intent_message().intent != Intent::sui_transaction() {
3677            return Err(serde::ser::Error::custom("invalid Intent for Transaction"));
3678        }
3679
3680        let txn = SignedTxn {
3681            intent_message: self.intent_message(),
3682            tx_signatures: &self.tx_signatures,
3683        };
3684        txn.serialize(serializer)
3685    }
3686}
3687
3688impl<'de> Deserialize<'de> for SenderSignedTransaction {
3689    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3690    where
3691        D: serde::Deserializer<'de>,
3692    {
3693        #[derive(Deserialize)]
3694        #[serde(rename = "SenderSignedTransaction")]
3695        struct SignedTxn {
3696            intent_message: IntentMessage<TransactionData>,
3697            tx_signatures: Vec<GenericSignature>,
3698        }
3699
3700        let SignedTxn {
3701            intent_message,
3702            tx_signatures,
3703        } = Deserialize::deserialize(deserializer)?;
3704
3705        if intent_message.intent != Intent::sui_transaction() {
3706            return Err(serde::de::Error::custom("invalid Intent for Transaction"));
3707        }
3708
3709        Ok(Self {
3710            intent_message,
3711            tx_signatures,
3712        })
3713    }
3714}
3715
3716impl SenderSignedTransaction {
3717    /// Returns a mapping from signer address to the signature and its index in `tx_signatures`.
3718    pub(crate) fn get_signer_sig_mapping(
3719        &self,
3720        verify_legacy_zklogin_address: bool,
3721    ) -> SuiResult<BTreeMap<SuiAddress, (u8, &GenericSignature)>> {
3722        let mut mapping = BTreeMap::new();
3723        for (idx, sig) in self.tx_signatures.iter().enumerate() {
3724            if verify_legacy_zklogin_address && let GenericSignature::ZkLoginAuthenticator(z) = sig
3725            {
3726                // Try deriving the address from the legacy padded way.
3727                mapping.insert(SuiAddress::try_from_padded(&z.inputs)?, (idx as u8, sig));
3728            }
3729            let address = sig.try_into()?;
3730            mapping.insert(address, (idx as u8, sig));
3731        }
3732        Ok(mapping)
3733    }
3734
3735    pub fn intent_message(&self) -> &IntentMessage<TransactionData> {
3736        &self.intent_message
3737    }
3738}
3739
3740impl SenderSignedData {
3741    pub fn new(tx_data: TransactionData, tx_signatures: Vec<GenericSignature>) -> Self {
3742        Self(SizeOneVec::new(SenderSignedTransaction {
3743            intent_message: IntentMessage::new(Intent::sui_transaction(), tx_data),
3744            tx_signatures,
3745        }))
3746    }
3747
3748    pub fn new_from_sender_signature(tx_data: TransactionData, tx_signature: Signature) -> Self {
3749        Self(SizeOneVec::new(SenderSignedTransaction {
3750            intent_message: IntentMessage::new(Intent::sui_transaction(), tx_data),
3751            tx_signatures: vec![tx_signature.into()],
3752        }))
3753    }
3754
3755    pub fn inner(&self) -> &SenderSignedTransaction {
3756        self.0.element()
3757    }
3758
3759    pub fn into_inner(self) -> SenderSignedTransaction {
3760        self.0.into_inner()
3761    }
3762
3763    pub fn inner_mut(&mut self) -> &mut SenderSignedTransaction {
3764        self.0.element_mut()
3765    }
3766
3767    // This function does not check validity of the signature
3768    // or perform any de-dup checks.
3769    pub fn add_signature(&mut self, new_signature: Signature) {
3770        self.inner_mut().tx_signatures.push(new_signature.into());
3771    }
3772
3773    pub(crate) fn get_signer_sig_mapping(
3774        &self,
3775        verify_legacy_zklogin_address: bool,
3776    ) -> SuiResult<BTreeMap<SuiAddress, (u8, &GenericSignature)>> {
3777        self.inner()
3778            .get_signer_sig_mapping(verify_legacy_zklogin_address)
3779    }
3780
3781    pub fn transaction_data(&self) -> &TransactionData {
3782        &self.intent_message().value
3783    }
3784
3785    pub fn intent_message(&self) -> &IntentMessage<TransactionData> {
3786        self.inner().intent_message()
3787    }
3788
3789    pub fn tx_signatures(&self) -> &[GenericSignature] {
3790        &self.inner().tx_signatures
3791    }
3792
3793    pub fn has_zklogin_sig(&self) -> bool {
3794        self.tx_signatures().iter().any(|sig| sig.is_zklogin())
3795    }
3796
3797    pub fn has_upgraded_multisig(&self) -> bool {
3798        self.tx_signatures()
3799            .iter()
3800            .any(|sig| sig.is_upgraded_multisig())
3801    }
3802
3803    #[cfg(test)]
3804    pub fn intent_message_mut_for_testing(&mut self) -> &mut IntentMessage<TransactionData> {
3805        &mut self.inner_mut().intent_message
3806    }
3807
3808    // used cross-crate, so cannot be #[cfg(test)]
3809    pub fn tx_signatures_mut_for_testing(&mut self) -> &mut Vec<GenericSignature> {
3810        &mut self.inner_mut().tx_signatures
3811    }
3812
3813    /// Includes alias_versions to ensure cache invalidation when aliases change.
3814    pub fn full_message_digest_with_alias_versions(
3815        &self,
3816        alias_versions: &Vec<(SuiAddress, Option<SequenceNumber>)>,
3817    ) -> SenderSignedDataDigest {
3818        let mut digest = DefaultHash::default();
3819        bcs::serialize_into(&mut digest, self).expect("serialization should not fail");
3820        bcs::serialize_into(&mut digest, alias_versions).expect("serialization should not fail");
3821        let hash = digest.finalize();
3822        SenderSignedDataDigest::new(hash.into())
3823    }
3824
3825    pub fn serialized_size(&self) -> SuiResult<usize> {
3826        bcs::serialized_size(self).map_err(|e| {
3827            SuiErrorKind::TransactionSerializationError {
3828                error: e.to_string(),
3829            }
3830            .into()
3831        })
3832    }
3833
3834    fn check_user_signature_protocol_compatibility(&self, config: &ProtocolConfig) -> SuiResult {
3835        for sig in &self.inner().tx_signatures {
3836            match sig {
3837                GenericSignature::MultiSig(_) => {
3838                    if !config.supports_upgraded_multisig() {
3839                        return Err(SuiErrorKind::UserInputError {
3840                            error: UserInputError::Unsupported(
3841                                "upgraded multisig format not enabled on this network".to_string(),
3842                            ),
3843                        }
3844                        .into());
3845                    }
3846                }
3847                GenericSignature::ZkLoginAuthenticator(_) => {
3848                    if !config.zklogin_auth() {
3849                        return Err(SuiErrorKind::UserInputError {
3850                            error: UserInputError::Unsupported(
3851                                "zklogin is not enabled on this network".to_string(),
3852                            ),
3853                        }
3854                        .into());
3855                    }
3856                }
3857                GenericSignature::PasskeyAuthenticator(_) => {
3858                    if !config.passkey_auth() {
3859                        return Err(SuiErrorKind::UserInputError {
3860                            error: UserInputError::Unsupported(
3861                                "passkey is not enabled on this network".to_string(),
3862                            ),
3863                        }
3864                        .into());
3865                    }
3866                }
3867                GenericSignature::Signature(_) | GenericSignature::MultiSigLegacy(_) => (),
3868            }
3869        }
3870
3871        Ok(())
3872    }
3873
3874    /// Validate untrusted user transaction, including its size, input count, command count, etc.
3875    /// Returns the certificate serialised bytes size.
3876    pub fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> Result<usize, SuiError> {
3877        // Check that the features used by the user signatures are enabled on the network.
3878        self.check_user_signature_protocol_compatibility(context.config)?;
3879
3880        // TODO: The following checks can be moved to TransactionData, if we pass context into it.
3881
3882        // CRITICAL!!
3883        // Users cannot send system transactions.
3884        let tx_data = &self.transaction_data();
3885        fp_ensure!(
3886            !tx_data.is_system_tx(),
3887            SuiErrorKind::UserInputError {
3888                error: UserInputError::Unsupported(
3889                    "SenderSignedData must not contain system transaction".to_string()
3890                )
3891            }
3892            .into()
3893        );
3894
3895        // Enforce overall transaction size limit.
3896        let tx_size = self.serialized_size()?;
3897        let max_tx_size_bytes = context.config.max_tx_size_bytes();
3898        fp_ensure!(
3899            tx_size as u64 <= max_tx_size_bytes,
3900            SuiErrorKind::UserInputError {
3901                error: UserInputError::SizeLimitExceeded {
3902                    limit: format!(
3903                        "serialized transaction size exceeded maximum of {max_tx_size_bytes}"
3904                    ),
3905                    value: tx_size.to_string(),
3906                }
3907            }
3908            .into()
3909        );
3910
3911        if context.config.enable_gasless() && tx_data.is_gasless_transaction() {
3912            let gasless_max = context.config.get_gasless_max_tx_size_bytes();
3913            fp_ensure!(
3914                tx_size as u64 <= gasless_max,
3915                SuiErrorKind::UserInputError {
3916                    error: UserInputError::SizeLimitExceeded {
3917                        limit: format!(
3918                            "serialized gasless transaction size exceeded maximum of {gasless_max}"
3919                        ),
3920                        value: tx_size.to_string(),
3921                    }
3922                }
3923                .into()
3924            );
3925        }
3926
3927        tx_data.validity_check(context)?;
3928
3929        Ok(tx_size)
3930    }
3931}
3932
3933impl Message for SenderSignedData {
3934    type DigestType = TransactionDigest;
3935    const SCOPE: IntentScope = IntentScope::SenderSignedTransaction;
3936
3937    /// Computes the tx digest that encodes the Rust type prefix from Signable trait.
3938    fn digest(&self) -> Self::DigestType {
3939        self.intent_message().value.digest()
3940    }
3941}
3942
3943impl<S> Envelope<SenderSignedData, S> {
3944    pub fn sender_address(&self) -> SuiAddress {
3945        self.data().intent_message().value.sender()
3946    }
3947
3948    pub fn gas_owner(&self) -> SuiAddress {
3949        self.data().intent_message().value.gas_owner()
3950    }
3951
3952    pub fn gas(&self) -> &[ObjectRef] {
3953        self.data().intent_message().value.gas()
3954    }
3955
3956    pub fn is_consensus_tx(&self) -> bool {
3957        self.transaction_data().has_funds_withdrawals()
3958            || self.shared_input_objects().next().is_some()
3959    }
3960
3961    pub fn shared_input_objects(&self) -> impl Iterator<Item = SharedInputObject> + '_ {
3962        self.data()
3963            .inner()
3964            .intent_message
3965            .value
3966            .shared_input_objects()
3967            .into_iter()
3968    }
3969
3970    // Returns the primary key for this transaction.
3971    pub fn key(&self) -> TransactionKey {
3972        match &self.data().intent_message().value.kind() {
3973            TransactionKind::RandomnessStateUpdate(rsu) => {
3974                TransactionKey::RandomnessRound(rsu.epoch, rsu.randomness_round)
3975            }
3976            _ => TransactionKey::Digest(*self.digest()),
3977        }
3978    }
3979
3980    // Returns non-Digest keys that could be used to refer to this transaction.
3981    //
3982    // At the moment this returns a single Option for efficiency, but if more key types are added,
3983    // the return type could change to Vec<TransactionKey>.
3984    pub fn non_digest_key(&self) -> Option<TransactionKey> {
3985        match &self.data().intent_message().value.kind() {
3986            TransactionKind::RandomnessStateUpdate(rsu) => Some(TransactionKey::RandomnessRound(
3987                rsu.epoch,
3988                rsu.randomness_round,
3989            )),
3990            _ => None,
3991        }
3992    }
3993
3994    pub fn is_system_tx(&self) -> bool {
3995        self.data().intent_message().value.is_system_tx()
3996    }
3997
3998    pub fn is_sponsored_tx(&self) -> bool {
3999        self.data().intent_message().value.is_sponsored_tx()
4000    }
4001}
4002
4003impl Transaction {
4004    pub fn from_data_and_signer(
4005        data: TransactionData,
4006        signers: Vec<&dyn Signer<Signature>>,
4007    ) -> Self {
4008        let signatures = {
4009            let intent_msg = IntentMessage::new(Intent::sui_transaction(), &data);
4010            signers
4011                .into_iter()
4012                .map(|s| Signature::new_secure(&intent_msg, s))
4013                .collect()
4014        };
4015        Self::from_data(data, signatures)
4016    }
4017
4018    // TODO: Rename this function and above to make it clearer.
4019    pub fn from_data(data: TransactionData, signatures: Vec<Signature>) -> Self {
4020        Self::from_generic_sig_data(data, signatures.into_iter().map(|s| s.into()).collect())
4021    }
4022
4023    pub fn signature_from_signer(
4024        data: TransactionData,
4025        intent: Intent,
4026        signer: &dyn Signer<Signature>,
4027    ) -> Signature {
4028        let intent_msg = IntentMessage::new(intent, data);
4029        Signature::new_secure(&intent_msg, signer)
4030    }
4031
4032    pub fn from_generic_sig_data(data: TransactionData, signatures: Vec<GenericSignature>) -> Self {
4033        Self::new(SenderSignedData::new(data, signatures))
4034    }
4035
4036    /// Returns the Base64 encoded tx_bytes
4037    /// and a list of Base64 encoded [enum GenericSignature].
4038    pub fn to_tx_bytes_and_signatures(&self) -> (Base64, Vec<Base64>) {
4039        (
4040            Base64::from_bytes(&bcs::to_bytes(&self.data().intent_message().value).unwrap()),
4041            self.data()
4042                .inner()
4043                .tx_signatures
4044                .iter()
4045                .map(|s| Base64::from_bytes(s.as_ref()))
4046                .collect(),
4047        )
4048    }
4049}
4050
4051impl VerifiedTransaction {
4052    pub fn new_change_epoch(
4053        next_epoch: EpochId,
4054        protocol_version: ProtocolVersion,
4055        storage_charge: u64,
4056        computation_charge: u64,
4057        storage_rebate: u64,
4058        non_refundable_storage_fee: u64,
4059        epoch_start_timestamp_ms: u64,
4060        system_packages: Vec<(SequenceNumber, Vec<Vec<u8>>, Vec<ObjectID>)>,
4061    ) -> Self {
4062        ChangeEpoch {
4063            epoch: next_epoch,
4064            protocol_version,
4065            storage_charge,
4066            computation_charge,
4067            storage_rebate,
4068            non_refundable_storage_fee,
4069            epoch_start_timestamp_ms,
4070            system_packages,
4071        }
4072        .pipe(TransactionKind::ChangeEpoch)
4073        .pipe(Self::new_system_transaction)
4074    }
4075
4076    pub fn new_genesis_transaction(objects: Vec<GenesisObject>) -> Self {
4077        GenesisTransaction { objects }
4078            .pipe(TransactionKind::Genesis)
4079            .pipe(Self::new_system_transaction)
4080    }
4081
4082    pub fn new_consensus_commit_prologue(
4083        epoch: u64,
4084        round: u64,
4085        commit_timestamp_ms: CheckpointTimestamp,
4086    ) -> Self {
4087        ConsensusCommitPrologue {
4088            epoch,
4089            round,
4090            commit_timestamp_ms,
4091        }
4092        .pipe(TransactionKind::ConsensusCommitPrologue)
4093        .pipe(Self::new_system_transaction)
4094    }
4095
4096    pub fn new_consensus_commit_prologue_v2(
4097        epoch: u64,
4098        round: u64,
4099        commit_timestamp_ms: CheckpointTimestamp,
4100        consensus_commit_digest: ConsensusCommitDigest,
4101    ) -> Self {
4102        ConsensusCommitPrologueV2 {
4103            epoch,
4104            round,
4105            commit_timestamp_ms,
4106            consensus_commit_digest,
4107        }
4108        .pipe(TransactionKind::ConsensusCommitPrologueV2)
4109        .pipe(Self::new_system_transaction)
4110    }
4111
4112    pub fn new_consensus_commit_prologue_v3(
4113        epoch: u64,
4114        round: u64,
4115        commit_timestamp_ms: CheckpointTimestamp,
4116        consensus_commit_digest: ConsensusCommitDigest,
4117        consensus_determined_version_assignments: ConsensusDeterminedVersionAssignments,
4118    ) -> Self {
4119        ConsensusCommitPrologueV3 {
4120            epoch,
4121            round,
4122            // sub_dag_index is reserved for when we have multi commits per round.
4123            sub_dag_index: None,
4124            commit_timestamp_ms,
4125            consensus_commit_digest,
4126            consensus_determined_version_assignments,
4127        }
4128        .pipe(TransactionKind::ConsensusCommitPrologueV3)
4129        .pipe(Self::new_system_transaction)
4130    }
4131
4132    pub fn new_consensus_commit_prologue_v4(
4133        epoch: u64,
4134        round: u64,
4135        commit_timestamp_ms: CheckpointTimestamp,
4136        consensus_commit_digest: ConsensusCommitDigest,
4137        consensus_determined_version_assignments: ConsensusDeterminedVersionAssignments,
4138        additional_state_digest: AdditionalConsensusStateDigest,
4139    ) -> Self {
4140        ConsensusCommitPrologueV4 {
4141            epoch,
4142            round,
4143            // sub_dag_index is reserved for when we have multi commits per round.
4144            sub_dag_index: None,
4145            commit_timestamp_ms,
4146            consensus_commit_digest,
4147            consensus_determined_version_assignments,
4148            additional_state_digest,
4149        }
4150        .pipe(TransactionKind::ConsensusCommitPrologueV4)
4151        .pipe(Self::new_system_transaction)
4152    }
4153
4154    pub fn new_authenticator_state_update(
4155        epoch: u64,
4156        round: u64,
4157        new_active_jwks: Vec<ActiveJwk>,
4158        authenticator_obj_initial_shared_version: SequenceNumber,
4159    ) -> Self {
4160        AuthenticatorStateUpdate {
4161            epoch,
4162            round,
4163            new_active_jwks,
4164            authenticator_obj_initial_shared_version,
4165        }
4166        .pipe(TransactionKind::AuthenticatorStateUpdate)
4167        .pipe(Self::new_system_transaction)
4168    }
4169
4170    pub fn new_randomness_state_update(
4171        epoch: u64,
4172        randomness_round: RandomnessRound,
4173        random_bytes: Vec<u8>,
4174        randomness_obj_initial_shared_version: SequenceNumber,
4175    ) -> Self {
4176        RandomnessStateUpdate {
4177            epoch,
4178            randomness_round,
4179            random_bytes,
4180            randomness_obj_initial_shared_version,
4181        }
4182        .pipe(TransactionKind::RandomnessStateUpdate)
4183        .pipe(Self::new_system_transaction)
4184    }
4185
4186    pub fn new_end_of_epoch_transaction(txns: Vec<EndOfEpochTransactionKind>) -> Self {
4187        TransactionKind::EndOfEpochTransaction(txns).pipe(Self::new_system_transaction)
4188    }
4189
4190    pub fn new_system_transaction(system_transaction: TransactionKind) -> Self {
4191        system_transaction
4192            .pipe(TransactionData::new_system_transaction)
4193            .pipe(|data| {
4194                SenderSignedData::new_from_sender_signature(
4195                    data,
4196                    Ed25519SuiSignature::from_bytes(&[0; Ed25519SuiSignature::LENGTH])
4197                        .unwrap()
4198                        .into(),
4199                )
4200            })
4201            .pipe(Transaction::new)
4202            .pipe(Self::new_from_verified)
4203    }
4204}
4205
4206impl VerifiedSignedTransaction {
4207    /// Use signing key to create a signed object.
4208    pub fn new(
4209        epoch: EpochId,
4210        transaction: VerifiedTransaction,
4211        authority: AuthorityName,
4212        secret: &dyn Signer<AuthoritySignature>,
4213    ) -> Self {
4214        Self::new_from_verified(SignedTransaction::new(
4215            epoch,
4216            transaction.into_inner().into_data(),
4217            secret,
4218            authority,
4219        ))
4220    }
4221}
4222
4223/// A transaction that is signed by a sender but not yet by an authority.
4224pub type Transaction = Envelope<SenderSignedData, EmptySignInfo>;
4225pub type VerifiedTransaction = VerifiedEnvelope<SenderSignedData, EmptySignInfo>;
4226pub type TrustedTransaction = TrustedEnvelope<SenderSignedData, EmptySignInfo>;
4227
4228/// A transaction that is signed by a sender and also by an authority.
4229pub type SignedTransaction = Envelope<SenderSignedData, AuthoritySignInfo>;
4230pub type VerifiedSignedTransaction = VerifiedEnvelope<SenderSignedData, AuthoritySignInfo>;
4231
4232impl Transaction {
4233    pub fn verify_signature_for_testing(
4234        &self,
4235        current_epoch: EpochId,
4236        verify_params: &VerifyParams,
4237    ) -> SuiResult {
4238        verify_sender_signed_data_message_signatures(
4239            self.data(),
4240            current_epoch,
4241            verify_params,
4242            Arc::new(VerifiedDigestCache::new_empty()),
4243            vec![],
4244        )?;
4245        Ok(())
4246    }
4247
4248    pub fn try_into_verified_for_testing(
4249        self,
4250        current_epoch: EpochId,
4251        verify_params: &VerifyParams,
4252    ) -> SuiResult<VerifiedTransaction> {
4253        self.verify_signature_for_testing(current_epoch, verify_params)?;
4254        Ok(VerifiedTransaction::new_from_verified(self))
4255    }
4256}
4257
4258impl SignedTransaction {
4259    pub fn verify_signatures_authenticated_for_testing(
4260        &self,
4261        committee: &Committee,
4262        verify_params: &VerifyParams,
4263    ) -> SuiResult {
4264        verify_sender_signed_data_message_signatures(
4265            self.data(),
4266            committee.epoch(),
4267            verify_params,
4268            Arc::new(VerifiedDigestCache::new_empty()),
4269            vec![],
4270        )?;
4271
4272        self.auth_sig().verify_secure(
4273            self.data(),
4274            Intent::sui_app(IntentScope::SenderSignedTransaction),
4275            committee,
4276        )
4277    }
4278
4279    pub fn try_into_verified_for_testing(
4280        self,
4281        committee: &Committee,
4282        verify_params: &VerifyParams,
4283    ) -> SuiResult<VerifiedSignedTransaction> {
4284        self.verify_signatures_authenticated_for_testing(committee, verify_params)?;
4285        Ok(VerifiedSignedTransaction::new_from_verified(self))
4286    }
4287}
4288
4289pub type CertifiedTransaction = Envelope<SenderSignedData, AuthorityStrongQuorumSignInfo>;
4290
4291impl CertifiedTransaction {
4292    pub fn gas_price(&self) -> u64 {
4293        self.data().transaction_data().gas_price()
4294    }
4295}
4296
4297pub type VerifiedCertificate = VerifiedEnvelope<SenderSignedData, AuthorityStrongQuorumSignInfo>;
4298pub type TrustedCertificate = TrustedEnvelope<SenderSignedData, AuthorityStrongQuorumSignInfo>;
4299
4300#[derive(Clone, Debug, Serialize, Deserialize)]
4301pub struct WithAliases<T>(
4302    T,
4303    #[serde(with = "nonempty_as_vec")] NonEmpty<(u8, Option<SequenceNumber>)>,
4304);
4305
4306impl<T> WithAliases<T> {
4307    pub fn new(tx: T, aliases: NonEmpty<(u8, Option<SequenceNumber>)>) -> Self {
4308        Self(tx, aliases)
4309    }
4310
4311    pub fn tx(&self) -> &T {
4312        &self.0
4313    }
4314
4315    pub fn aliases(&self) -> &NonEmpty<(u8, Option<SequenceNumber>)> {
4316        &self.1
4317    }
4318
4319    pub fn into_tx(self) -> T {
4320        self.0
4321    }
4322
4323    pub fn into_aliases(self) -> NonEmpty<(u8, Option<SequenceNumber>)> {
4324        self.1
4325    }
4326
4327    pub fn into_inner(self) -> (T, NonEmpty<(u8, Option<SequenceNumber>)>) {
4328        (self.0, self.1)
4329    }
4330}
4331
4332impl<T: Message, S> WithAliases<VerifiedEnvelope<T, S>> {
4333    /// Analogous to VerifiedEnvelope::serializable.
4334    pub fn serializable(self) -> WithAliases<TrustedEnvelope<T, S>> {
4335        WithAliases(self.0.serializable(), self.1)
4336    }
4337}
4338
4339impl<S> WithAliases<Envelope<SenderSignedData, S>> {
4340    /// Creates a WithAliases where each required signer is mapped to its corresponding
4341    /// signature index (assuming 1:1 correspondence) with no alias object version.
4342    pub fn no_aliases(tx: Envelope<SenderSignedData, S>) -> Self {
4343        let required_signers = tx.intent_message().value.required_signers();
4344        assert_eq!(required_signers.len(), tx.tx_signatures().len());
4345        let no_aliases = required_signers
4346            .iter()
4347            .enumerate()
4348            .map(|(idx, _)| (idx as u8, None))
4349            .collect::<Vec<_>>();
4350        Self::new(
4351            tx,
4352            NonEmpty::from_vec(no_aliases).expect("must have at least one required_signer"),
4353        )
4354    }
4355}
4356
4357impl<S> WithAliases<VerifiedEnvelope<SenderSignedData, S>> {
4358    /// Creates a WithAliases where each required signer is mapped to its corresponding
4359    /// signature index (assuming 1:1 correspondence) with no alias object version.
4360    pub fn no_aliases(tx: VerifiedEnvelope<SenderSignedData, S>) -> Self {
4361        let required_signers = tx.intent_message().value.required_signers();
4362        assert_eq!(required_signers.len(), tx.tx_signatures().len());
4363        let no_aliases = required_signers
4364            .iter()
4365            .enumerate()
4366            .map(|(idx, _)| (idx as u8, None))
4367            .collect::<Vec<_>>();
4368        Self::new(
4369            tx,
4370            NonEmpty::from_vec(no_aliases).expect("must have at least one required_signer"),
4371        )
4372    }
4373}
4374
4375pub type TransactionWithAliases = WithAliases<Transaction>;
4376pub type VerifiedTransactionWithAliases = WithAliases<VerifiedTransaction>;
4377pub type TrustedTransactionWithAliases = WithAliases<TrustedTransaction>;
4378
4379/// Deprecated version of WithAliases that uses SuiAddress instead of u8.
4380/// This is needed to read data from deferred_transactions_with_aliases_v2 table
4381/// which was written with the old format before the type was changed.
4382// TODO: Delete this after all production networks are on the latest table.
4383#[derive(Clone, Debug, Serialize, Deserialize)]
4384pub struct DeprecatedWithAliases<T>(
4385    T,
4386    #[serde(with = "nonempty_as_vec")] NonEmpty<(SuiAddress, Option<SequenceNumber>)>,
4387);
4388
4389impl<T> DeprecatedWithAliases<T> {
4390    pub fn into_inner(self) -> (T, NonEmpty<(SuiAddress, Option<SequenceNumber>)>) {
4391        (self.0, self.1)
4392    }
4393}
4394
4395impl<T: Message, S> From<WithAliases<VerifiedEnvelope<T, S>>> for WithAliases<Envelope<T, S>> {
4396    fn from(value: WithAliases<VerifiedEnvelope<T, S>>) -> Self {
4397        Self(value.0.into(), value.1)
4398    }
4399}
4400
4401impl<T: Message, S> From<WithAliases<TrustedEnvelope<T, S>>>
4402    for WithAliases<VerifiedEnvelope<T, S>>
4403{
4404    fn from(value: WithAliases<TrustedEnvelope<T, S>>) -> Self {
4405        Self(value.0.into(), value.1)
4406    }
4407}
4408
4409mod nonempty_as_vec {
4410    use super::*;
4411    use serde::{Deserialize, Deserializer, Serialize, Serializer};
4412
4413    pub fn serialize<S, T>(value: &NonEmpty<T>, serializer: S) -> Result<S::Ok, S::Error>
4414    where
4415        S: Serializer,
4416        T: Serialize,
4417    {
4418        let vec: Vec<&T> = value.iter().collect();
4419        vec.serialize(serializer)
4420    }
4421
4422    pub fn deserialize<'de, D, T>(deserializer: D) -> Result<NonEmpty<T>, D::Error>
4423    where
4424        D: Deserializer<'de>,
4425        T: Deserialize<'de> + Clone,
4426    {
4427        use serde::de::{SeqAccess, Visitor};
4428        use std::fmt;
4429        use std::marker::PhantomData;
4430
4431        struct NonEmptyVisitor<T>(PhantomData<T>);
4432
4433        impl<'de, T> Visitor<'de> for NonEmptyVisitor<T>
4434        where
4435            T: Deserialize<'de> + Clone,
4436        {
4437            type Value = NonEmpty<T>;
4438
4439            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4440                formatter.write_str("a non-empty sequence")
4441            }
4442
4443            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
4444            where
4445                A: SeqAccess<'de>,
4446            {
4447                let head = seq
4448                    .next_element()?
4449                    .ok_or_else(|| serde::de::Error::custom("empty vector"))?;
4450
4451                let mut tail = Vec::new();
4452                while let Some(elem) = seq.next_element()? {
4453                    tail.push(elem);
4454                }
4455
4456                Ok(NonEmpty { head, tail })
4457            }
4458        }
4459
4460        deserializer.deserialize_seq(NonEmptyVisitor(PhantomData))
4461    }
4462}
4463
4464// =============================================================================
4465// TransactionWithClaims - Generalized claim system for consensus messages
4466// =============================================================================
4467
4468/// Claims that can be attached to a transaction for consensus validation.
4469/// Each claim type represents a piece of information that:
4470/// 1. The submitting validator includes in the consensus message
4471/// 2. Voting validators verify before accepting
4472/// 3. The consensus handler can use deterministically
4473#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
4474pub enum TransactionClaim {
4475    /// DEPRECATED. Do not use.
4476    #[deprecated(note = "Use AddressAliasesV2")]
4477    AddressAliases(
4478        #[serde(with = "nonempty_as_vec")] NonEmpty<(SuiAddress, Option<SequenceNumber>)>,
4479    ),
4480
4481    /// Object IDs that are claimed to be immutable.
4482    /// Used to filter out immutable objects from lock acquisition in consensus handler.
4483    ImmutableInputObjects(Vec<ObjectID>),
4484
4485    /// Address aliases used for signature verification.
4486    /// Length must equal the number of `required_signers`. Each element maps the corresponding
4487    /// signer to the signature index and alias object version (if any) used to verify it.
4488    AddressAliasesV2(#[serde(with = "nonempty_as_vec")] NonEmpty<(u8, Option<SequenceNumber>)>),
4489}
4490
4491/// A transaction with attached claims that have been verified by voting validators.
4492#[derive(Clone, Debug, Serialize, Deserialize)]
4493pub struct TransactionWithClaims<T> {
4494    tx: T,
4495    claims: Vec<TransactionClaim>,
4496}
4497
4498impl<T> TransactionWithClaims<T> {
4499    pub fn new(tx: T, claims: Vec<TransactionClaim>) -> Self {
4500        Self { tx, claims }
4501    }
4502
4503    /// Create from a transaction with only address aliases.
4504    pub fn from_aliases(tx: T, aliases: NonEmpty<(u8, Option<SequenceNumber>)>) -> Self {
4505        Self {
4506            tx,
4507            claims: vec![TransactionClaim::AddressAliasesV2(aliases)],
4508        }
4509    }
4510
4511    /// Creates from a transaction without any aliases attached.
4512    pub fn no_aliases(tx: T) -> Self {
4513        Self { tx, claims: vec![] }
4514    }
4515
4516    pub fn tx(&self) -> &T {
4517        &self.tx
4518    }
4519
4520    pub fn into_tx(self) -> T {
4521        self.tx
4522    }
4523
4524    /// Get the address aliases V2 claim. Differentiate between empty and not present for validation.
4525    pub fn aliases(&self) -> Option<NonEmpty<(u8, Option<SequenceNumber>)>> {
4526        self.claims
4527            .iter()
4528            .find_map(|c| match c {
4529                TransactionClaim::AddressAliasesV2(aliases) => Some(aliases),
4530                _ => None,
4531            })
4532            .cloned()
4533    }
4534
4535    // TODO: Remove once `fix_checkpoint_signature_mapping` flag is enabled in testnet.
4536    #[allow(deprecated)]
4537    pub fn aliases_v1(&self) -> Option<NonEmpty<(SuiAddress, Option<SequenceNumber>)>> {
4538        self.claims
4539            .iter()
4540            .find_map(|c| match c {
4541                TransactionClaim::AddressAliases(aliases) => Some(aliases),
4542                _ => None,
4543            })
4544            .cloned()
4545    }
4546
4547    /// Get the immutable input objects claim. Returns empty vector if not present.
4548    pub fn get_immutable_objects(&self) -> Vec<ObjectID> {
4549        self.claims
4550            .iter()
4551            .find_map(|c| match c {
4552                TransactionClaim::ImmutableInputObjects(objs) => Some(objs.clone()),
4553                _ => None,
4554            })
4555            .unwrap_or_default()
4556    }
4557}
4558
4559pub type PlainTransactionWithClaims = TransactionWithClaims<Transaction>;
4560
4561/// Convert from `WithAliases<VerifiedEnvelope>` to `TransactionWithClaims<Envelope>`.
4562/// Used when feature flag is off to convert existing WithAliases to the new type.
4563impl<T: Message, S> From<WithAliases<VerifiedEnvelope<T, S>>>
4564    for TransactionWithClaims<Envelope<T, S>>
4565{
4566    fn from(value: WithAliases<VerifiedEnvelope<T, S>>) -> Self {
4567        let (tx, aliases) = value.into_inner();
4568        Self::from_aliases(tx.into(), aliases)
4569    }
4570}
4571
4572#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord, Hash)]
4573pub enum InputObjectKind {
4574    // A Move package, must be immutable.
4575    MovePackage(ObjectID),
4576    // A Move object, either immutable, or owned mutable.
4577    ImmOrOwnedMoveObject(ObjectRef),
4578    // A Move object that's shared and mutable.
4579    SharedMoveObject {
4580        id: ObjectID,
4581        initial_shared_version: SequenceNumber,
4582        mutability: SharedObjectMutability,
4583    },
4584}
4585
4586#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord, Hash)]
4587pub enum SharedObjectMutability {
4588    // The "classic" mutable/immutable modes.
4589    Immutable,
4590    Mutable,
4591    // Non-exclusive write is used to allow multiple transactions to
4592    // simultaneously add disjoint dynamic fields to an object.
4593    // (Currently only used by settlement transactions).
4594    NonExclusiveWrite,
4595}
4596
4597impl SharedObjectMutability {
4598    pub fn is_exclusive(&self) -> bool {
4599        match self {
4600            SharedObjectMutability::Mutable => true,
4601            SharedObjectMutability::Immutable => false,
4602            SharedObjectMutability::NonExclusiveWrite => false,
4603        }
4604    }
4605}
4606
4607impl InputObjectKind {
4608    pub fn object_id(&self) -> ObjectID {
4609        self.full_object_id().id()
4610    }
4611
4612    pub fn full_object_id(&self) -> FullObjectID {
4613        match self {
4614            Self::MovePackage(id) => FullObjectID::Fastpath(*id),
4615            Self::ImmOrOwnedMoveObject((id, _, _)) => FullObjectID::Fastpath(*id),
4616            Self::SharedMoveObject {
4617                id,
4618                initial_shared_version,
4619                ..
4620            } => FullObjectID::Consensus((*id, *initial_shared_version)),
4621        }
4622    }
4623
4624    pub fn version(&self) -> Option<SequenceNumber> {
4625        match self {
4626            Self::MovePackage(..) => None,
4627            Self::ImmOrOwnedMoveObject((_, version, _)) => Some(*version),
4628            Self::SharedMoveObject { .. } => None,
4629        }
4630    }
4631
4632    pub fn object_not_found_error(&self) -> UserInputError {
4633        match *self {
4634            Self::MovePackage(package_id) => {
4635                UserInputError::DependentPackageNotFound { package_id }
4636            }
4637            Self::ImmOrOwnedMoveObject((object_id, version, _)) => UserInputError::ObjectNotFound {
4638                object_id,
4639                version: Some(version),
4640            },
4641            Self::SharedMoveObject { id, .. } => UserInputError::ObjectNotFound {
4642                object_id: id,
4643                version: None,
4644            },
4645        }
4646    }
4647
4648    pub fn is_shared_object(&self) -> bool {
4649        matches!(self, Self::SharedMoveObject { .. })
4650    }
4651}
4652
4653/// The result of reading an object for execution. Because shared objects may be deleted, one
4654/// possible result of reading a shared object is that ObjectReadResultKind::Deleted is returned.
4655#[derive(Clone, Debug)]
4656pub struct ObjectReadResult {
4657    pub input_object_kind: InputObjectKind,
4658    pub object: ObjectReadResultKind,
4659}
4660
4661#[derive(Clone)]
4662pub enum ObjectReadResultKind {
4663    Object(Object),
4664    // The version of the object that the transaction intended to read, and the digest of the tx
4665    // that removed it from consensus.
4666    ObjectConsensusStreamEnded(SequenceNumber, TransactionDigest),
4667    // A shared object in a cancelled transaction. The sequence number embeds cancellation reason.
4668    CancelledTransactionSharedObject(SequenceNumber),
4669}
4670
4671impl ObjectReadResultKind {
4672    pub fn is_cancelled(&self) -> bool {
4673        matches!(
4674            self,
4675            ObjectReadResultKind::CancelledTransactionSharedObject(_)
4676        )
4677    }
4678
4679    pub fn version(&self) -> SequenceNumber {
4680        match self {
4681            ObjectReadResultKind::Object(object) => object.version(),
4682            ObjectReadResultKind::ObjectConsensusStreamEnded(seq, _) => *seq,
4683            ObjectReadResultKind::CancelledTransactionSharedObject(seq) => *seq,
4684        }
4685    }
4686}
4687
4688impl std::fmt::Debug for ObjectReadResultKind {
4689    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4690        match self {
4691            ObjectReadResultKind::Object(obj) => {
4692                write!(f, "Object({:?})", obj.compute_object_reference())
4693            }
4694            ObjectReadResultKind::ObjectConsensusStreamEnded(seq, digest) => {
4695                write!(f, "ObjectConsensusStreamEnded({}, {:?})", seq, digest)
4696            }
4697            ObjectReadResultKind::CancelledTransactionSharedObject(seq) => {
4698                write!(f, "CancelledTransactionSharedObject({})", seq)
4699            }
4700        }
4701    }
4702}
4703
4704impl From<Object> for ObjectReadResultKind {
4705    fn from(object: Object) -> Self {
4706        Self::Object(object)
4707    }
4708}
4709
4710impl ObjectReadResult {
4711    pub fn new(input_object_kind: InputObjectKind, object: ObjectReadResultKind) -> Self {
4712        if let (
4713            InputObjectKind::ImmOrOwnedMoveObject(_),
4714            ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
4715        ) = (&input_object_kind, &object)
4716        {
4717            panic!("only consensus objects can be ObjectConsensusStreamEnded");
4718        }
4719
4720        if let (
4721            InputObjectKind::ImmOrOwnedMoveObject(_),
4722            ObjectReadResultKind::CancelledTransactionSharedObject(_),
4723        ) = (&input_object_kind, &object)
4724        {
4725            panic!("only consensus objects can be CancelledTransactionSharedObject");
4726        }
4727
4728        Self {
4729            input_object_kind,
4730            object,
4731        }
4732    }
4733
4734    pub fn id(&self) -> ObjectID {
4735        self.input_object_kind.object_id()
4736    }
4737
4738    pub fn as_object(&self) -> Option<&Object> {
4739        match &self.object {
4740            ObjectReadResultKind::Object(object) => Some(object),
4741            ObjectReadResultKind::ObjectConsensusStreamEnded(_, _) => None,
4742            ObjectReadResultKind::CancelledTransactionSharedObject(_) => None,
4743        }
4744    }
4745
4746    pub fn new_from_gas_object(gas: &Object) -> Self {
4747        let objref = gas.compute_object_reference();
4748        Self {
4749            input_object_kind: InputObjectKind::ImmOrOwnedMoveObject(objref),
4750            object: ObjectReadResultKind::Object(gas.clone()),
4751        }
4752    }
4753
4754    pub fn is_mutable(&self) -> bool {
4755        match (&self.input_object_kind, &self.object) {
4756            (InputObjectKind::MovePackage(_), _) => false,
4757            (InputObjectKind::ImmOrOwnedMoveObject(_), ObjectReadResultKind::Object(object)) => {
4758                !object.is_immutable()
4759            }
4760            (
4761                InputObjectKind::ImmOrOwnedMoveObject(_),
4762                ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
4763            ) => unreachable!(),
4764            (
4765                InputObjectKind::ImmOrOwnedMoveObject(_),
4766                ObjectReadResultKind::CancelledTransactionSharedObject(_),
4767            ) => unreachable!(),
4768            (InputObjectKind::SharedMoveObject { mutability, .. }, _) => match mutability {
4769                SharedObjectMutability::Mutable => true,
4770                SharedObjectMutability::Immutable => false,
4771                SharedObjectMutability::NonExclusiveWrite => false,
4772            },
4773        }
4774    }
4775
4776    pub fn is_shared_object(&self) -> bool {
4777        self.input_object_kind.is_shared_object()
4778    }
4779
4780    pub fn is_consensus_stream_ended(&self) -> bool {
4781        self.consensus_stream_end_info().is_some()
4782    }
4783
4784    pub fn consensus_stream_end_info(&self) -> Option<(SequenceNumber, TransactionDigest)> {
4785        match &self.object {
4786            ObjectReadResultKind::ObjectConsensusStreamEnded(v, tx) => Some((*v, *tx)),
4787            _ => None,
4788        }
4789    }
4790
4791    /// Return the object ref iff the object is an address-owned object (i.e. not shared, not immutable).
4792    pub fn get_address_owned_objref(&self) -> Option<ObjectRef> {
4793        match (&self.input_object_kind, &self.object) {
4794            (InputObjectKind::MovePackage(_), _) => None,
4795            (
4796                InputObjectKind::ImmOrOwnedMoveObject(objref),
4797                ObjectReadResultKind::Object(object),
4798            ) => {
4799                if object.is_immutable() {
4800                    None
4801                } else {
4802                    Some(*objref)
4803                }
4804            }
4805            (
4806                InputObjectKind::ImmOrOwnedMoveObject(_),
4807                ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
4808            ) => unreachable!(),
4809            (
4810                InputObjectKind::ImmOrOwnedMoveObject(_),
4811                ObjectReadResultKind::CancelledTransactionSharedObject(_),
4812            ) => unreachable!(),
4813            (InputObjectKind::SharedMoveObject { .. }, _) => None,
4814        }
4815    }
4816
4817    pub fn is_address_owned(&self) -> bool {
4818        self.get_address_owned_objref().is_some()
4819    }
4820
4821    pub fn is_replay_protected_input(&self) -> bool {
4822        if let InputObjectKind::ImmOrOwnedMoveObject(obj_ref) = &self.input_object_kind
4823            && ParsedDigest::is_coin_reservation_digest(&obj_ref.2)
4824        {
4825            true
4826        } else {
4827            self.is_address_owned()
4828        }
4829    }
4830
4831    pub fn to_shared_input(&self) -> Option<SharedInput> {
4832        match self.input_object_kind {
4833            InputObjectKind::MovePackage(_) => None,
4834            InputObjectKind::ImmOrOwnedMoveObject(_) => None,
4835            InputObjectKind::SharedMoveObject { id, mutability, .. } => Some(match &self.object {
4836                ObjectReadResultKind::Object(obj) => {
4837                    SharedInput::Existing(obj.compute_object_reference())
4838                }
4839                ObjectReadResultKind::ObjectConsensusStreamEnded(seq, digest) => {
4840                    SharedInput::ConsensusStreamEnded((id, *seq, mutability, *digest))
4841                }
4842                ObjectReadResultKind::CancelledTransactionSharedObject(seq) => {
4843                    SharedInput::Cancelled((id, *seq))
4844                }
4845            }),
4846        }
4847    }
4848
4849    pub fn get_previous_transaction(&self) -> Option<TransactionDigest> {
4850        match &self.object {
4851            ObjectReadResultKind::Object(obj) => Some(obj.previous_transaction),
4852            ObjectReadResultKind::ObjectConsensusStreamEnded(_, digest) => Some(*digest),
4853            ObjectReadResultKind::CancelledTransactionSharedObject(_) => None,
4854        }
4855    }
4856}
4857
4858#[derive(Clone)]
4859pub struct InputObjects {
4860    objects: Vec<ObjectReadResult>,
4861}
4862
4863impl std::fmt::Debug for InputObjects {
4864    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4865        f.debug_list().entries(self.objects.iter()).finish()
4866    }
4867}
4868
4869// An InputObjects new-type that has been verified by sui-transaction-checks, and can be
4870// safely passed to execution.
4871#[derive(Clone)]
4872pub struct CheckedInputObjects(InputObjects);
4873
4874// DO NOT CALL outside of sui-transaction-checks, genesis, or replay.
4875//
4876// CheckedInputObjects should really be defined in sui-transaction-checks so that we can
4877// make public construction impossible. But we can't do that because it would result in circular
4878// dependencies.
4879impl CheckedInputObjects {
4880    // Only called by sui-transaction-checks.
4881    pub fn new_with_checked_transaction_inputs(inputs: InputObjects) -> Self {
4882        Self(inputs)
4883    }
4884
4885    // Only called when building the genesis transaction
4886    pub fn new_for_genesis(input_objects: Vec<ObjectReadResult>) -> Self {
4887        Self(InputObjects::new(input_objects))
4888    }
4889
4890    // Only called from the replay tool.
4891    pub fn new_for_replay(input_objects: InputObjects) -> Self {
4892        Self(input_objects)
4893    }
4894
4895    pub fn inner(&self) -> &InputObjects {
4896        &self.0
4897    }
4898
4899    pub fn into_inner(self) -> InputObjects {
4900        self.0
4901    }
4902}
4903
4904impl From<Vec<ObjectReadResult>> for InputObjects {
4905    fn from(objects: Vec<ObjectReadResult>) -> Self {
4906        Self::new(objects)
4907    }
4908}
4909
4910impl InputObjects {
4911    pub fn new(objects: Vec<ObjectReadResult>) -> Self {
4912        Self { objects }
4913    }
4914
4915    pub fn len(&self) -> usize {
4916        self.objects.len()
4917    }
4918
4919    pub fn is_empty(&self) -> bool {
4920        self.objects.is_empty()
4921    }
4922
4923    pub fn contains_consensus_stream_ended_objects(&self) -> bool {
4924        self.objects
4925            .iter()
4926            .any(|obj| obj.is_consensus_stream_ended())
4927    }
4928
4929    // Returns IDs of objects responsible for a transaction being cancelled, and the corresponding
4930    // reason for cancellation.
4931    pub fn get_cancelled_objects(&self) -> Option<(Vec<ObjectID>, SequenceNumber)> {
4932        let mut contains_cancelled = false;
4933        let mut cancel_reason = None;
4934        let mut cancelled_objects = Vec::new();
4935        for obj in &self.objects {
4936            if let ObjectReadResultKind::CancelledTransactionSharedObject(version) = obj.object {
4937                contains_cancelled = true;
4938                if version == SequenceNumber::CONGESTED
4939                    || version == SequenceNumber::RANDOMNESS_UNAVAILABLE
4940                {
4941                    // Verify we don't have multiple cancellation reasons.
4942                    assert!(cancel_reason.is_none() || cancel_reason == Some(version));
4943                    cancel_reason = Some(version);
4944                    cancelled_objects.push(obj.id());
4945                }
4946            }
4947        }
4948
4949        if !cancelled_objects.is_empty() {
4950            Some((
4951                cancelled_objects,
4952                cancel_reason
4953                    .expect("there should be a cancel reason if there are cancelled objects"),
4954            ))
4955        } else {
4956            assert!(!contains_cancelled);
4957            None
4958        }
4959    }
4960
4961    pub fn filter_owned_objects(&self) -> Vec<ObjectRef> {
4962        let owned_objects: Vec<_> = self
4963            .objects
4964            .iter()
4965            .filter_map(|obj| obj.get_address_owned_objref())
4966            .collect();
4967
4968        trace!(
4969            num_mutable_objects = owned_objects.len(),
4970            "Checked locks and found mutable objects"
4971        );
4972
4973        owned_objects
4974    }
4975
4976    pub fn filter_shared_objects(&self) -> Vec<SharedInput> {
4977        self.objects
4978            .iter()
4979            .filter(|obj| obj.is_shared_object())
4980            .map(|obj| {
4981                obj.to_shared_input()
4982                    .expect("already filtered for shared objects")
4983            })
4984            .collect()
4985    }
4986
4987    pub fn transaction_dependencies(&self) -> BTreeSet<TransactionDigest> {
4988        self.objects
4989            .iter()
4990            .filter_map(|obj| obj.get_previous_transaction())
4991            .collect()
4992    }
4993
4994    /// All inputs that will be directly mutated by the transaction. This does
4995    /// not include SharedObjectMutability::NonExclusiveWrite inputs.
4996    pub fn exclusive_mutable_inputs(&self) -> BTreeMap<ObjectID, (VersionDigest, Owner)> {
4997        self.mutables_with_input_kinds()
4998            .filter_map(|(id, (version, owner, kind))| match kind {
4999                InputObjectKind::SharedMoveObject { mutability, .. } => match mutability {
5000                    SharedObjectMutability::Mutable => Some((id, (version, owner))),
5001                    SharedObjectMutability::Immutable => None,
5002                    SharedObjectMutability::NonExclusiveWrite => None,
5003                },
5004                _ => Some((id, (version, owner))),
5005            })
5006            .collect()
5007    }
5008
5009    pub fn non_exclusive_input_objects(&self) -> BTreeMap<ObjectID, Object> {
5010        self.objects
5011            .iter()
5012            .filter_map(|read_result| {
5013                match (read_result.as_object(), read_result.input_object_kind) {
5014                    (
5015                        Some(object),
5016                        InputObjectKind::SharedMoveObject {
5017                            mutability: SharedObjectMutability::NonExclusiveWrite,
5018                            ..
5019                        },
5020                    ) => Some((read_result.id(), object.clone())),
5021                    _ => None,
5022                }
5023            })
5024            .collect()
5025    }
5026
5027    /// All inputs that can be taken as &mut T, which includes both
5028    /// SharedObjectMutability::Mutable and SharedObjectMutability::NonExclusiveWrite inputs.
5029    pub fn all_mutable_inputs(&self) -> BTreeMap<ObjectID, (VersionDigest, Owner)> {
5030        self.mutables_with_input_kinds()
5031            .filter_map(|(id, (version, owner, kind))| match kind {
5032                InputObjectKind::SharedMoveObject { mutability, .. } => match mutability {
5033                    SharedObjectMutability::Mutable => Some((id, (version, owner))),
5034                    SharedObjectMutability::Immutable => None,
5035                    SharedObjectMutability::NonExclusiveWrite => Some((id, (version, owner))),
5036                },
5037                _ => Some((id, (version, owner))),
5038            })
5039            .collect()
5040    }
5041
5042    fn mutables_with_input_kinds(
5043        &self,
5044    ) -> impl Iterator<Item = (ObjectID, (VersionDigest, Owner, InputObjectKind))> + '_ {
5045        self.objects.iter().filter_map(
5046            |ObjectReadResult {
5047                 input_object_kind,
5048                 object,
5049             }| match (input_object_kind, object) {
5050                (InputObjectKind::MovePackage(_), _) => None,
5051                (
5052                    InputObjectKind::ImmOrOwnedMoveObject(object_ref),
5053                    ObjectReadResultKind::Object(object),
5054                ) => {
5055                    if object.is_immutable() {
5056                        None
5057                    } else {
5058                        Some((
5059                            object_ref.0,
5060                            (
5061                                (object_ref.1, object_ref.2),
5062                                object.owner.clone(),
5063                                *input_object_kind,
5064                            ),
5065                        ))
5066                    }
5067                }
5068                (
5069                    InputObjectKind::ImmOrOwnedMoveObject(_),
5070                    ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
5071                ) => {
5072                    unreachable!()
5073                }
5074                (
5075                    InputObjectKind::SharedMoveObject { .. },
5076                    ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
5077                ) => None,
5078                (
5079                    InputObjectKind::SharedMoveObject { mutability, .. },
5080                    ObjectReadResultKind::Object(object),
5081                ) => match *mutability {
5082                    SharedObjectMutability::Mutable => {
5083                        let oref = object.compute_object_reference();
5084                        Some((
5085                            oref.0,
5086                            ((oref.1, oref.2), object.owner.clone(), *input_object_kind),
5087                        ))
5088                    }
5089                    SharedObjectMutability::Immutable => None,
5090                    SharedObjectMutability::NonExclusiveWrite => {
5091                        let oref = object.compute_object_reference();
5092                        Some((
5093                            oref.0,
5094                            ((oref.1, oref.2), object.owner.clone(), *input_object_kind),
5095                        ))
5096                    }
5097                },
5098                (
5099                    InputObjectKind::ImmOrOwnedMoveObject(_),
5100                    ObjectReadResultKind::CancelledTransactionSharedObject(_),
5101                ) => {
5102                    unreachable!()
5103                }
5104                (
5105                    InputObjectKind::SharedMoveObject { .. },
5106                    ObjectReadResultKind::CancelledTransactionSharedObject(_),
5107                ) => None,
5108            },
5109        )
5110    }
5111
5112    /// The version to set on objects created by the computation that `self` is input to.
5113    /// Guaranteed to be strictly greater than the versions of all input objects and objects
5114    /// received in the transaction.
5115    pub fn lamport_timestamp(&self, receiving_objects: &[ObjectRef]) -> SequenceNumber {
5116        let input_versions = self
5117            .objects
5118            .iter()
5119            .filter_map(|object| match &object.object {
5120                ObjectReadResultKind::Object(object) => {
5121                    object.data.try_as_move().map(MoveObject::version)
5122                }
5123                ObjectReadResultKind::ObjectConsensusStreamEnded(v, _) => Some(*v),
5124                ObjectReadResultKind::CancelledTransactionSharedObject(_) => None,
5125            })
5126            .chain(receiving_objects.iter().map(|object_ref| object_ref.1));
5127
5128        SequenceNumber::lamport_increment(input_versions)
5129    }
5130
5131    pub fn object_kinds(&self) -> impl Iterator<Item = &InputObjectKind> {
5132        self.objects.iter().map(
5133            |ObjectReadResult {
5134                 input_object_kind, ..
5135             }| input_object_kind,
5136        )
5137    }
5138
5139    pub fn consensus_stream_ended_objects(&self) -> BTreeMap<ObjectID, SequenceNumber> {
5140        self.objects
5141            .iter()
5142            .filter_map(|obj| {
5143                if let InputObjectKind::SharedMoveObject {
5144                    id,
5145                    initial_shared_version,
5146                    ..
5147                } = obj.input_object_kind
5148                {
5149                    obj.is_consensus_stream_ended()
5150                        .then_some((id, initial_shared_version))
5151                } else {
5152                    None
5153                }
5154            })
5155            .collect()
5156    }
5157
5158    pub fn into_object_map(self) -> BTreeMap<ObjectID, Object> {
5159        self.objects
5160            .into_iter()
5161            .filter_map(|o| o.as_object().map(|object| (o.id(), object.clone())))
5162            .collect()
5163    }
5164
5165    pub fn push(&mut self, object: ObjectReadResult) {
5166        self.objects.push(object);
5167    }
5168
5169    pub fn iter(&self) -> impl Iterator<Item = &ObjectReadResult> {
5170        self.objects.iter()
5171    }
5172
5173    pub fn iter_objects(&self) -> impl Iterator<Item = &Object> {
5174        self.objects.iter().filter_map(|o| o.as_object())
5175    }
5176
5177    pub fn non_exclusive_mutable_inputs(
5178        &self,
5179    ) -> impl Iterator<Item = (ObjectID, SequenceNumber)> + '_ {
5180        self.objects.iter().filter_map(
5181            |ObjectReadResult {
5182                 input_object_kind,
5183                 object,
5184             }| match input_object_kind {
5185                // TODO: this is not exercised yet since settlement transactions cannot be
5186                // cancelled, but if/when we expose non-exclusive writes to users,
5187                // a cancelled transaction should not be considered to have done any writes.
5188                InputObjectKind::SharedMoveObject {
5189                    id,
5190                    mutability: SharedObjectMutability::NonExclusiveWrite,
5191                    ..
5192                } if !object.is_cancelled() => Some((*id, object.version())),
5193                _ => None,
5194            },
5195        )
5196    }
5197}
5198
5199// Result of attempting to read a receiving object (currently only at signing time).
5200// Because an object may have been previously received and deleted, the result may be
5201// ReceivingObjectReadResultKind::PreviouslyReceivedObject.
5202#[derive(Clone, Debug)]
5203pub enum ReceivingObjectReadResultKind {
5204    Object(Object),
5205    // The object was received by some other transaction, and we were not able to read it
5206    PreviouslyReceivedObject,
5207}
5208
5209impl ReceivingObjectReadResultKind {
5210    pub fn as_object(&self) -> Option<&Object> {
5211        match &self {
5212            Self::Object(object) => Some(object),
5213            Self::PreviouslyReceivedObject => None,
5214        }
5215    }
5216}
5217
5218pub struct ReceivingObjectReadResult {
5219    pub object_ref: ObjectRef,
5220    pub object: ReceivingObjectReadResultKind,
5221}
5222
5223impl ReceivingObjectReadResult {
5224    pub fn new(object_ref: ObjectRef, object: ReceivingObjectReadResultKind) -> Self {
5225        Self { object_ref, object }
5226    }
5227
5228    pub fn is_previously_received(&self) -> bool {
5229        matches!(
5230            self.object,
5231            ReceivingObjectReadResultKind::PreviouslyReceivedObject
5232        )
5233    }
5234}
5235
5236impl From<Object> for ReceivingObjectReadResultKind {
5237    fn from(object: Object) -> Self {
5238        Self::Object(object)
5239    }
5240}
5241
5242pub struct ReceivingObjects {
5243    pub objects: Vec<ReceivingObjectReadResult>,
5244}
5245
5246impl ReceivingObjects {
5247    pub fn iter(&self) -> impl Iterator<Item = &ReceivingObjectReadResult> {
5248        self.objects.iter()
5249    }
5250
5251    pub fn iter_objects(&self) -> impl Iterator<Item = &Object> {
5252        self.objects.iter().filter_map(|o| o.object.as_object())
5253    }
5254}
5255
5256impl From<Vec<ReceivingObjectReadResult>> for ReceivingObjects {
5257    fn from(objects: Vec<ReceivingObjectReadResult>) -> Self {
5258        Self { objects }
5259    }
5260}
5261
5262impl Display for CertifiedTransaction {
5263    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
5264        let mut writer = String::new();
5265        writeln!(writer, "Transaction Hash: {:?}", self.digest())?;
5266        writeln!(
5267            writer,
5268            "Signed Authorities Bitmap : {:?}",
5269            self.auth_sig().signers_map
5270        )?;
5271        write!(writer, "{}", &self.data().intent_message().value.kind())?;
5272        write!(f, "{}", writer)
5273    }
5274}
5275
5276/// TransactionKey uniquely identifies a transaction across all epochs.
5277/// Note that a single transaction may have multiple keys, for example a RandomnessStateUpdate
5278/// could be identified by both `Digest` and `RandomnessRound`.
5279#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
5280pub enum TransactionKey {
5281    Digest(TransactionDigest),
5282    RandomnessRound(EpochId, RandomnessRound),
5283    AccumulatorSettlement(EpochId, u64 /* checkpoint height */),
5284    ConsensusCommitPrologue(EpochId, u64 /* round */, u32 /* sub_dag_index */),
5285}
5286
5287impl TransactionKey {
5288    pub fn unwrap_digest(&self) -> &TransactionDigest {
5289        match self {
5290            TransactionKey::Digest(d) => d,
5291            _ => panic!("called unwrap_digest on a non-Digest TransactionKey: {self:?}"),
5292        }
5293    }
5294
5295    pub fn as_digest(&self) -> Option<&TransactionDigest> {
5296        match self {
5297            TransactionKey::Digest(d) => Some(d),
5298            _ => None,
5299        }
5300    }
5301}