1use 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;
87pub 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 Pure(Vec<u8>),
119 Object(ObjectArg),
121 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 ImmOrOwnedObject(ObjectRef),
145 SharedObject {
148 id: ObjectID,
149 initial_shared_version: SequenceNumber,
150 mutability: SharedObjectMutability,
153 },
154 Receiving(ObjectRef),
156}
157
158#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
159pub enum Reservation {
160 MaxAmountU64(u64),
162}
163
164#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
165pub enum WithdrawalTypeArg {
166 Balance(TypeTag),
167}
168
169impl WithdrawalTypeArg {
170 pub fn to_type_tag(&self) -> TypeTag {
173 let WithdrawalTypeArg::Balance(type_param) = self;
174 Balance::type_tag(type_param.clone())
175 }
176
177 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#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
188pub struct FundsWithdrawalArg {
189 pub reservation: Reservation,
191 pub type_arg: WithdrawalTypeArg,
193 pub withdraw_from: WithdrawFrom,
195}
196
197#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
198pub enum WithdrawFrom {
199 Sender,
201 Sponsor,
203 }
205
206impl FundsWithdrawalArg {
207 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 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 pub epoch: EpochId,
295 pub protocol_version: ProtocolVersion,
297 pub storage_charge: u64,
299 pub computation_charge: u64,
301 pub storage_rebate: u64,
303 pub non_refundable_storage_fee: u64,
305 pub epoch_start_timestamp_ms: u64,
307 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 pub min_epoch: u64,
340 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 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 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 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 pub epoch: u64,
422 pub round: u64,
424 pub new_active_jwks: Vec<ActiveJwk>,
426 pub authenticator_obj_initial_shared_version: SequenceNumber,
428 }
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 pub epoch: u64,
442 pub randomness_round: RandomnessRound,
444 pub random_bytes: Vec<u8>,
446 pub randomness_obj_initial_shared_version: SequenceNumber,
448 }
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 ProgrammableTransaction(ProgrammableTransaction),
462 ChangeEpoch(ChangeEpoch),
474 Genesis(GenesisTransaction),
475 ConsensusCommitPrologue(ConsensusCommitPrologue),
476 AuthenticatorStateUpdate(AuthenticatorStateUpdate),
477
478 EndOfEpochTransaction(Vec<EndOfEpochTransactionKind>),
481
482 RandomnessStateUpdate(RandomnessStateUpdate),
483 ConsensusCommitPrologueV2(ConsensusCommitPrologueV2),
485
486 ConsensusCommitPrologueV3(ConsensusCommitPrologueV3),
487 ConsensusCommitPrologueV4(ConsensusCommitPrologueV4),
488
489 ProgrammableSystemTransaction(ProgrammableTransaction),
491 }
493
494#[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 CallArg::Object(ObjectArg::Receiving(_)) => vec![],
800 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 CallArg::Pure(bcs::to_bytes(&b).unwrap())
872 }
873}
874
875impl From<u8> for CallArg {
876 fn from(n: u8) -> Self {
877 CallArg::Pure(bcs::to_bytes(&n).unwrap())
879 }
880}
881
882impl From<u16> for CallArg {
883 fn from(n: u16) -> Self {
884 CallArg::Pure(bcs::to_bytes(&n).unwrap())
886 }
887}
888
889impl From<u32> for CallArg {
890 fn from(n: u32) -> Self {
891 CallArg::Pure(bcs::to_bytes(&n).unwrap())
893 }
894}
895
896impl From<u64> for CallArg {
897 fn from(n: u64) -> Self {
898 CallArg::Pure(bcs::to_bytes(&n).unwrap())
900 }
901}
902
903impl From<u128> for CallArg {
904 fn from(n: u128) -> Self {
905 CallArg::Pure(bcs::to_bytes(&n).unwrap())
907 }
908}
909
910impl From<&Vec<u8>> for CallArg {
911 fn from(v: &Vec<u8>) -> Self {
912 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
939fn 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#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
965pub struct ProgrammableTransaction {
966 pub inputs: Vec<CallArg>,
968 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
1087pub 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 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 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#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1147pub enum Command {
1148 MoveCall(Box<ProgrammableMoveCall>),
1150 TransferObjects(Vec<Argument>, Argument),
1155 SplitCoins(Argument, Vec<Argument>),
1158 MergeCoins(Argument, Vec<Argument>),
1161 Publish(Vec<Vec<u8>>, Vec<ObjectID>),
1164 MakeMoveVec(Option<TypeInput>, Vec<Argument>),
1168 Upgrade(Vec<Vec<u8>>, Vec<ObjectID>, ObjectID, Argument),
1176}
1177
1178#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy, Serialize, Deserialize)]
1180pub enum Argument {
1181 GasCoin,
1184 Input(u16),
1187 Result(u16),
1189 NestedResult(u16, u16),
1192}
1193
1194#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
1197pub struct ProgrammableMoveCall {
1198 pub package: ObjectID,
1200 pub module: String,
1202 pub function: String,
1204 pub type_arguments: Vec<TypeInput>,
1206 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 FundType,
1271 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 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 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 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 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 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 pub fn programmable(pt: ProgrammableTransaction) -> Self {
1855 TransactionKind::ProgrammableTransaction(pt)
1856 }
1857
1858 pub fn is_system_tx(&self) -> bool {
1859 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 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 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 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 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 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 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 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 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 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 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 None,
2323 Epoch(EpochId),
2326 ValidDuring {
2336 min_epoch: Option<EpochId>,
2338 max_epoch: Option<EpochId>,
2340 min_timestamp: Option<u64>,
2342 max_timestamp: Option<u64>,
2344 chain: ChainIdentifier,
2346 nonce: u32,
2348 },
2349}
2350
2351impl TransactionExpiration {
2352 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 }
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!(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 } => ObjectArg::SharedObject {
2709 id: upgrade_capability.0,
2710 initial_shared_version,
2711 mutability: SharedObjectMutability::Mutable,
2712 },
2713 Owner::Immutable => {
2714 return Err(anyhow::anyhow!(
2715 "Upgrade capability is stored immutably and cannot be used for upgrades"
2716 ));
2717 }
2718 Owner::ObjectOwner(_) => {
2721 return Err(anyhow::anyhow!("Upgrade capability controlled by object"));
2722 }
2723 };
2724 builder.obj(capability_arg).unwrap();
2725 let upgrade_arg = builder.pure(upgrade_policy).unwrap();
2726 let digest_arg = builder.pure(digest).unwrap();
2727 let upgrade_ticket = builder.programmable_move_call(
2728 SUI_FRAMEWORK_PACKAGE_ID,
2729 ident_str!("package").to_owned(),
2730 ident_str!("authorize_upgrade").to_owned(),
2731 vec![],
2732 vec![Argument::Input(0), upgrade_arg, digest_arg],
2733 );
2734 let upgrade_receipt = builder.upgrade(package_id, upgrade_ticket, dep_ids, modules);
2735
2736 builder.programmable_move_call(
2737 SUI_FRAMEWORK_PACKAGE_ID,
2738 ident_str!("package").to_owned(),
2739 ident_str!("commit_upgrade").to_owned(),
2740 vec![],
2741 vec![Argument::Input(0), upgrade_receipt],
2742 );
2743
2744 builder.finish()
2745 };
2746 Ok(Self::new_programmable(
2747 sender,
2748 vec![gas_payment],
2749 pt,
2750 gas_budget,
2751 gas_price,
2752 ))
2753 }
2754
2755 pub fn new_programmable(
2756 sender: SuiAddress,
2757 gas_payment: Vec<ObjectRef>,
2758 pt: ProgrammableTransaction,
2759 gas_budget: u64,
2760 gas_price: u64,
2761 ) -> Self {
2762 Self::new_programmable_allow_sponsor(sender, gas_payment, pt, gas_budget, gas_price, sender)
2763 }
2764
2765 pub fn new_programmable_allow_sponsor(
2766 sender: SuiAddress,
2767 gas_payment: Vec<ObjectRef>,
2768 pt: ProgrammableTransaction,
2769 gas_budget: u64,
2770 gas_price: u64,
2771 sponsor: SuiAddress,
2772 ) -> Self {
2773 let kind = TransactionKind::ProgrammableTransaction(pt);
2774 Self::new_with_gas_coins_allow_sponsor(
2775 kind,
2776 sender,
2777 gas_payment,
2778 gas_budget,
2779 gas_price,
2780 sponsor,
2781 )
2782 }
2783
2784 pub fn new_programmable_with_address_balance_gas(
2785 sender: SuiAddress,
2786 pt: ProgrammableTransaction,
2787 gas_budget: u64,
2788 gas_price: u64,
2789 chain_identifier: ChainIdentifier,
2790 current_epoch: EpochId,
2791 nonce: u32,
2792 ) -> Self {
2793 TransactionData::V1(TransactionDataV1 {
2794 kind: TransactionKind::ProgrammableTransaction(pt),
2795 sender,
2796 gas_data: GasData {
2797 payment: vec![],
2798 owner: sender,
2799 price: gas_price,
2800 budget: gas_budget,
2801 },
2802 expiration: TransactionExpiration::ValidDuring {
2803 min_epoch: Some(current_epoch),
2804 max_epoch: Some(current_epoch + 1),
2805 min_timestamp: None,
2806 max_timestamp: None,
2807 chain: chain_identifier,
2808 nonce,
2809 },
2810 })
2811 }
2812
2813 pub fn message_version(&self) -> u64 {
2814 match self {
2815 TransactionData::V1(_) => 1,
2816 }
2817 }
2818
2819 pub fn execution_parts(&self) -> (TransactionKind, SuiAddress, GasData) {
2820 (self.kind().clone(), self.sender(), self.gas_data().clone())
2821 }
2822
2823 pub fn uses_randomness(&self) -> bool {
2824 self.kind()
2825 .shared_input_objects()
2826 .any(|obj| obj.id() == SUI_RANDOMNESS_STATE_OBJECT_ID)
2827 }
2828
2829 pub fn digest(&self) -> TransactionDigest {
2830 TransactionDigest::new(default_hash(self))
2831 }
2832}
2833
2834#[enum_dispatch]
2835pub trait TransactionDataAPI {
2836 fn sender(&self) -> SuiAddress;
2837
2838 fn kind(&self) -> &TransactionKind;
2841
2842 fn kind_mut(&mut self) -> &mut TransactionKind;
2844
2845 fn into_kind(self) -> TransactionKind;
2847
2848 fn required_signers(&self) -> NonEmpty<SuiAddress>;
2850
2851 fn gas_data(&self) -> &GasData;
2852
2853 fn gas_owner(&self) -> SuiAddress;
2854
2855 fn gas(&self) -> &[ObjectRef];
2856
2857 fn gas_price(&self) -> u64;
2858
2859 fn gas_budget(&self) -> u64;
2860
2861 fn expiration(&self) -> &TransactionExpiration;
2862
2863 fn expiration_mut(&mut self) -> &mut TransactionExpiration;
2864
2865 fn move_calls(&self) -> Vec<(usize, &ObjectID, &str, &str)>;
2866
2867 fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>>;
2868
2869 fn shared_input_objects(&self) -> Vec<SharedInputObject>;
2870
2871 fn receiving_objects(&self) -> Vec<ObjectRef>;
2872
2873 fn fastpath_dependency_objects(
2877 &self,
2878 ) -> UserInputResult<(Vec<ObjectRef>, Vec<ObjectID>, Vec<ObjectRef>)>;
2879
2880 fn process_funds_withdrawals_for_signing(
2888 &self,
2889 chain_identifier: ChainIdentifier,
2890 coin_resolver: &dyn CoinReservationResolverTrait,
2891 ) -> UserInputResult<BTreeMap<AccumulatorObjId, (u64, TypeTag)>>;
2892
2893 fn process_funds_withdrawals_for_estimation(
2897 &self,
2898 chain_identifier: ChainIdentifier,
2899 coin_resolver: &dyn CoinReservationResolverTrait,
2900 ) -> UserInputResult<BTreeMap<AccumulatorObjId, (u64, TypeTag)>>;
2901
2902 fn process_funds_withdrawals_for_execution(
2905 &self,
2906 chain_identifier: ChainIdentifier,
2907 ) -> BTreeMap<AccumulatorObjId, u64>;
2908
2909 fn has_funds_withdrawals(&self) -> bool;
2911
2912 fn coin_reservation_obj_refs(
2913 &self,
2914 chain_identifier: ChainIdentifier,
2915 ) -> Vec<ParsedObjectRefWithdrawal>;
2916
2917 fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> SuiResult;
2918
2919 fn validity_check_no_gas_check(&self, config: &ProtocolConfig) -> UserInputResult;
2920
2921 fn check_sponsorship(&self) -> UserInputResult;
2923
2924 fn is_system_tx(&self) -> bool;
2925 fn is_genesis_tx(&self) -> bool;
2926
2927 fn is_end_of_epoch_tx(&self) -> bool;
2930
2931 fn is_consensus_commit_prologue(&self) -> bool;
2932
2933 fn is_sponsored_tx(&self) -> bool;
2935
2936 fn is_gas_paid_from_address_balance(&self) -> bool;
2937
2938 fn is_gasless_transaction(&self) -> bool;
2939
2940 fn sender_mut_for_testing(&mut self) -> &mut SuiAddress;
2941
2942 fn gas_data_mut(&mut self) -> &mut GasData;
2943
2944 fn expiration_mut_for_testing(&mut self) -> &mut TransactionExpiration;
2946}
2947
2948impl TransactionDataAPI for TransactionDataV1 {
2949 fn sender(&self) -> SuiAddress {
2950 self.sender
2951 }
2952
2953 fn kind(&self) -> &TransactionKind {
2954 &self.kind
2955 }
2956
2957 fn kind_mut(&mut self) -> &mut TransactionKind {
2958 &mut self.kind
2959 }
2960
2961 fn into_kind(self) -> TransactionKind {
2962 self.kind
2963 }
2964
2965 fn required_signers(&self) -> NonEmpty<SuiAddress> {
2967 let mut signers = nonempty![self.sender];
2968 if self.gas_owner() != self.sender {
2969 signers.push(self.gas_owner());
2970 }
2971 signers
2972 }
2973
2974 fn gas_data(&self) -> &GasData {
2975 &self.gas_data
2976 }
2977
2978 fn gas_owner(&self) -> SuiAddress {
2979 self.gas_data.owner
2980 }
2981
2982 fn gas(&self) -> &[ObjectRef] {
2983 &self.gas_data.payment
2984 }
2985
2986 fn gas_price(&self) -> u64 {
2987 self.gas_data.price
2988 }
2989
2990 fn gas_budget(&self) -> u64 {
2991 self.gas_data.budget
2992 }
2993
2994 fn expiration(&self) -> &TransactionExpiration {
2995 &self.expiration
2996 }
2997
2998 fn expiration_mut(&mut self) -> &mut TransactionExpiration {
2999 &mut self.expiration
3000 }
3001
3002 fn move_calls(&self) -> Vec<(usize, &ObjectID, &str, &str)> {
3003 self.kind.move_calls()
3004 }
3005
3006 fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
3007 let mut inputs = self.kind.input_objects()?;
3008
3009 if !self.kind.is_system_tx() {
3010 inputs.extend(
3011 self.gas()
3012 .iter()
3013 .filter(|obj_ref| !ParsedDigest::is_coin_reservation_digest(&obj_ref.2))
3014 .map(|obj_ref| InputObjectKind::ImmOrOwnedMoveObject(*obj_ref)),
3015 );
3016 }
3017 Ok(inputs)
3018 }
3019
3020 fn shared_input_objects(&self) -> Vec<SharedInputObject> {
3021 self.kind.shared_input_objects().collect()
3022 }
3023
3024 fn receiving_objects(&self) -> Vec<ObjectRef> {
3025 self.kind.receiving_objects()
3026 }
3027
3028 fn fastpath_dependency_objects(
3029 &self,
3030 ) -> UserInputResult<(Vec<ObjectRef>, Vec<ObjectID>, Vec<ObjectRef>)> {
3031 let mut move_objects = vec![];
3032 let mut packages = vec![];
3033 let mut receiving_objects = vec![];
3034 self.input_objects()?.iter().for_each(|o| match o {
3035 InputObjectKind::ImmOrOwnedMoveObject(object_ref) => {
3036 move_objects.push(*object_ref);
3037 }
3038 InputObjectKind::MovePackage(package_id) => {
3039 packages.push(*package_id);
3040 }
3041 InputObjectKind::SharedMoveObject { .. } => {}
3042 });
3043 self.receiving_objects().iter().for_each(|object_ref| {
3044 receiving_objects.push(*object_ref);
3045 });
3046 Ok((move_objects, packages, receiving_objects))
3047 }
3048
3049 fn process_funds_withdrawals_for_signing(
3050 &self,
3051 chain_identifier: ChainIdentifier,
3052 coin_resolver: &dyn CoinReservationResolverTrait,
3053 ) -> UserInputResult<BTreeMap<AccumulatorObjId, (u64, TypeTag)>> {
3054 self.accumulate_funds_withdrawals(chain_identifier, coin_resolver, true)
3055 }
3056
3057 fn process_funds_withdrawals_for_estimation(
3058 &self,
3059 chain_identifier: ChainIdentifier,
3060 coin_resolver: &dyn CoinReservationResolverTrait,
3061 ) -> UserInputResult<BTreeMap<AccumulatorObjId, (u64, TypeTag)>> {
3062 self.accumulate_funds_withdrawals(chain_identifier, coin_resolver, false)
3063 }
3064
3065 fn process_funds_withdrawals_for_execution(
3066 &self,
3067 chain_identifier: ChainIdentifier,
3068 ) -> BTreeMap<AccumulatorObjId, u64> {
3069 let mut withdraws: Vec<_> = self.get_funds_withdrawals().collect();
3070 withdraws.extend(self.get_funds_withdrawal_for_gas_payment());
3071
3072 let mut withdraw_map: BTreeMap<AccumulatorObjId, u64> = BTreeMap::new();
3074 for withdraw in withdraws {
3075 let reserved_amount = match &withdraw.reservation {
3076 Reservation::MaxAmountU64(amount) => {
3077 assert!(*amount > 0, "verified in validity check");
3078 *amount
3079 }
3080 };
3081
3082 let withdrawal_owner = withdraw.owner_for_withdrawal(self);
3083
3084 let account_id =
3086 AccumulatorValue::get_field_id(withdrawal_owner, &withdraw.type_arg.to_type_tag())
3087 .unwrap();
3088
3089 let value = withdraw_map.entry(account_id).or_default();
3090 *value = value.checked_add(reserved_amount).unwrap();
3092 }
3093
3094 for obj in self.coin_reservation_obj_refs() {
3098 assert_reachable!("processing coin reservation withdrawal");
3099 let parsed = ParsedObjectRefWithdrawal::parse(&obj, chain_identifier).unwrap();
3101 let value = withdraw_map
3102 .entry(AccumulatorObjId::new_unchecked(parsed.unmasked_object_id))
3107 .or_default();
3108 *value = value.checked_add(parsed.reservation_amount()).unwrap();
3110 }
3111
3112 withdraw_map
3113 }
3114
3115 fn has_funds_withdrawals(&self) -> bool {
3116 if self.is_gas_paid_from_address_balance() && self.gas_data().budget > 0 {
3117 return true;
3118 }
3119 if let TransactionKind::ProgrammableTransaction(pt) = &self.kind {
3120 for input in &pt.inputs {
3121 if matches!(input, CallArg::FundsWithdrawal(_)) {
3122 return true;
3123 }
3124 }
3125 }
3126 if self.coin_reservation_obj_refs().next().is_some() {
3127 return true;
3128 }
3129 false
3130 }
3131
3132 fn coin_reservation_obj_refs(
3133 &self,
3134 chain_identifier: ChainIdentifier,
3135 ) -> Vec<ParsedObjectRefWithdrawal> {
3136 self.coin_reservation_obj_refs()
3137 .filter_map(|obj_ref| ParsedObjectRefWithdrawal::parse(&obj_ref, chain_identifier))
3138 .collect()
3139 }
3140
3141 fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> SuiResult {
3142 let config = context.config;
3143
3144 match self.expiration() {
3146 TransactionExpiration::None => (), TransactionExpiration::Epoch(max_epoch) => {
3148 if context.epoch > *max_epoch {
3149 return Err(SuiErrorKind::TransactionExpired.into());
3150 }
3151 }
3152 TransactionExpiration::ValidDuring {
3153 min_epoch,
3154 max_epoch,
3155 min_timestamp,
3156 max_timestamp,
3157 chain,
3158 nonce: _,
3159 } => {
3160 if min_timestamp.is_some() || max_timestamp.is_some() {
3161 return Err(UserInputError::Unsupported(
3162 "Timestamp-based transaction expiration is not yet supported".to_string(),
3163 )
3164 .into());
3165 }
3166
3167 match (min_epoch, max_epoch) {
3172 _ if config.relax_valid_during_for_owned_inputs() => (),
3173 (Some(min), Some(max)) => {
3174 if config.enable_multi_epoch_transaction_expiration() {
3175 if !(*max == *min || *max == min.saturating_add(1)) {
3176 return Err(UserInputError::Unsupported(
3177 "max_epoch must be at most min_epoch + 1".to_string(),
3178 )
3179 .into());
3180 }
3181 } else if min != max {
3182 return Err(UserInputError::Unsupported(
3183 "min_epoch must equal max_epoch".to_string(),
3184 )
3185 .into());
3186 }
3187 }
3188 _ => {
3189 return Err(UserInputError::Unsupported(
3190 "Both min_epoch and max_epoch must be specified".to_string(),
3191 )
3192 .into());
3193 }
3194 }
3195
3196 if *chain != context.chain_identifier {
3197 return Err(UserInputError::InvalidChainId {
3198 provided: format!("{:?}", chain),
3199 expected: format!("{:?}", context.chain_identifier),
3200 }
3201 .into());
3202 }
3203
3204 if let Some(min) = min_epoch
3205 && context.epoch < *min
3206 {
3207 return Err(SuiErrorKind::TransactionExpired.into());
3208 }
3209 if let Some(max) = max_epoch
3210 && context.epoch > *max
3211 {
3212 return Err(SuiErrorKind::TransactionExpired.into());
3213 }
3214 }
3215 }
3216
3217 if self.has_funds_withdrawals() {
3218 fp_ensure!(
3221 !self.gas().is_empty() || config.enable_address_balance_gas_payments(),
3222 UserInputError::MissingGasPayment.into()
3223 );
3224
3225 fp_ensure!(
3226 config.enable_accumulators(),
3227 UserInputError::Unsupported("Address balance withdraw is not enabled".to_string())
3228 .into()
3229 );
3230
3231 let max_withdraws = 10;
3233 let mut num_reservations = 0;
3234
3235 for withdraw in self.kind.get_funds_withdrawals() {
3236 num_reservations += 1;
3237 match withdraw.withdraw_from {
3238 WithdrawFrom::Sender => (),
3239 WithdrawFrom::Sponsor => {
3240 return Err(UserInputError::InvalidWithdrawReservation {
3241 error: "Explicit sponsor withdrawals are not yet supported".to_string(),
3242 }
3243 .into());
3244 }
3245 }
3246
3247 match withdraw.reservation {
3248 Reservation::MaxAmountU64(amount) => {
3249 fp_ensure!(
3250 amount > 0,
3251 UserInputError::InvalidWithdrawReservation {
3252 error: "Balance withdraw reservation amount must be non-zero"
3253 .to_string(),
3254 }
3255 .into()
3256 );
3257 }
3258 };
3259 }
3260
3261 for parsed in self.parsed_coin_reservations(context.chain_identifier) {
3262 num_reservations += 1;
3263 if parsed.epoch_id() != context.epoch && parsed.epoch_id() + 1 != context.epoch {
3267 return Err(SuiErrorKind::TransactionExpired.into());
3268 }
3269 if parsed.reservation_amount() == 0 {
3270 return Err(UserInputError::InvalidWithdrawReservation {
3271 error: "Balance withdraw reservation amount must be non-zero".to_string(),
3272 }
3273 .into());
3274 }
3275 }
3276
3277 if config.enable_address_balance_gas_payments()
3279 && self.is_gas_paid_from_address_balance()
3280 {
3281 num_reservations += 1;
3282 }
3283
3284 fp_ensure!(
3285 num_reservations <= max_withdraws,
3286 UserInputError::InvalidWithdrawReservation {
3287 error: format!(
3288 "Maximum number of balance withdraw reservations is {max_withdraws}"
3289 ),
3290 }
3291 .into()
3292 );
3293 }
3294
3295 if config.enable_accumulators()
3296 && config.enable_address_balance_gas_payments()
3297 && self.is_gas_paid_from_address_balance()
3298 {
3299 if config.address_balance_gas_reject_gas_coin_arg()
3300 && let TransactionKind::ProgrammableTransaction(pt) = &self.kind
3301 {
3302 fp_ensure!(
3303 !pt.commands.iter().any(|cmd| cmd.is_gas_coin_used()),
3304 UserInputError::Unsupported(
3305 "Argument::GasCoin is not supported with address balance gas payments"
3306 .to_string(),
3307 )
3308 .into()
3309 );
3310 }
3311
3312 let is_gasless = config.enable_gasless() && self.is_gasless_transaction();
3313 if config.address_balance_gas_check_rgp_at_signing() && !is_gasless {
3314 fp_ensure!(
3315 self.gas_data.price >= context.reference_gas_price,
3316 UserInputError::GasPriceUnderRGP {
3317 gas_price: self.gas_data.price,
3318 reference_gas_price: context.reference_gas_price,
3319 }
3320 .into()
3321 );
3322 }
3323
3324 if !config.relax_valid_during_for_owned_inputs() {
3329 if matches!(self.expiration(), TransactionExpiration::None) {
3330 return Err(UserInputError::MissingGasPayment.into());
3333 }
3334
3335 if !self.expiration().is_replay_protected() {
3336 return Err(UserInputError::InvalidExpiration {
3337 error: "Address balance gas payments require ValidDuring expiration"
3338 .to_string(),
3339 }
3340 .into());
3341 }
3342 }
3343 } else {
3344 fp_ensure!(
3345 !self.gas().is_empty(),
3346 UserInputError::MissingGasPayment.into()
3347 );
3348 }
3349
3350 let gas_len = self.gas().len();
3351 let max_gas_objects = config.max_gas_payment_objects() as usize;
3352
3353 let within_limit = if config.correct_gas_payment_limit_check() {
3354 gas_len <= max_gas_objects
3355 } else {
3356 gas_len < max_gas_objects
3357 };
3358
3359 fp_ensure!(
3360 within_limit,
3361 UserInputError::SizeLimitExceeded {
3362 limit: "maximum number of gas payment objects".to_string(),
3363 value: config.max_gas_payment_objects().to_string()
3364 }
3365 .into()
3366 );
3367
3368 if !config.enable_coin_reservation_obj_refs() {
3369 for (_, _, gas_digest) in self.gas() {
3370 fp_ensure!(
3371 !ParsedDigest::is_coin_reservation_digest(gas_digest),
3372 UserInputError::GasObjectNotOwnedObject {
3373 owner: Owner::AddressOwner(self.sender)
3374 }
3375 .into()
3376 );
3377 }
3378 } else {
3379 let sui_accumulator_id =
3382 *AccumulatorValue::get_field_id(self.sender, &Balance::type_tag(GAS::type_tag()))?
3383 .inner();
3384
3385 for gas_ref in self.gas() {
3386 if let Some(parsed) =
3387 ParsedObjectRefWithdrawal::parse(gas_ref, context.chain_identifier)
3388 {
3389 fp_ensure!(
3392 self.gas_owner() == self.sender,
3393 UserInputError::GasObjectNotOwnedObject {
3394 owner: Owner::AddressOwner(self.sender)
3395 }
3396 .into()
3397 );
3398 fp_ensure!(
3399 parsed.unmasked_object_id == sui_accumulator_id,
3400 UserInputError::GasObjectNotOwnedObject {
3401 owner: Owner::AddressOwner(self.sender)
3402 }
3403 .into()
3404 );
3405 }
3406 }
3407 }
3408
3409 if !self.is_system_tx() {
3410 fp_ensure!(
3411 !check_for_gas_price_too_high(config.gas_model_version())
3412 || self.gas_data.price < config.max_gas_price(),
3413 UserInputError::GasPriceTooHigh {
3414 max_gas_price: config.max_gas_price(),
3415 }
3416 .into()
3417 );
3418 let cost_table = SuiCostTable::new(config, self.gas_data.price);
3419
3420 fp_ensure!(
3421 self.gas_data.budget <= cost_table.max_gas_budget,
3422 UserInputError::GasBudgetTooHigh {
3423 gas_budget: self.gas_data().budget,
3424 max_budget: cost_table.max_gas_budget,
3425 }
3426 .into()
3427 );
3428 let is_gasless = config.enable_gasless() && self.is_gasless_transaction();
3429 if is_gasless {
3430 fp_ensure!(
3431 self.gas_data.budget == 0,
3432 UserInputError::Unsupported(
3433 "gas_budget must be 0 for gasless transactions".to_string()
3434 )
3435 .into()
3436 );
3437 } else {
3438 fp_ensure!(
3439 self.gas_data.budget >= cost_table.min_transaction_cost,
3440 UserInputError::GasBudgetTooLow {
3441 gas_budget: self.gas_data.budget,
3442 min_budget: cost_table.min_transaction_cost,
3443 }
3444 .into()
3445 );
3446 }
3447 }
3448
3449 self.validity_check_no_gas_check(config)?;
3450 Ok(())
3451 }
3452
3453 fn validity_check_no_gas_check(&self, config: &ProtocolConfig) -> UserInputResult {
3456 self.kind().validity_check(config)?;
3457
3458 if config.enable_gasless() && self.is_gasless_transaction() {
3459 let TransactionKind::ProgrammableTransaction(pt) = &self.kind else {
3460 debug_fatal!("gasless transaction is not a ProgrammableTransaction");
3461 return Err(UserInputError::Unsupported(
3462 "Gasless transactions must be programmable transactions".to_string(),
3463 ));
3464 };
3465 pt.validate_gasless_transaction(config)?;
3466 }
3467
3468 self.check_sponsorship()
3469 }
3470
3471 fn is_sponsored_tx(&self) -> bool {
3473 self.gas_owner() != self.sender
3474 }
3475
3476 fn is_gas_paid_from_address_balance(&self) -> bool {
3480 is_gas_paid_from_address_balance(&self.gas_data, &self.kind)
3481 }
3482
3483 fn is_gasless_transaction(&self) -> bool {
3484 is_gasless_transaction(&self.gas_data, &self.kind)
3485 }
3486
3487 fn check_sponsorship(&self) -> UserInputResult {
3489 if self.gas_owner() == self.sender() {
3491 return Ok(());
3492 }
3493 if matches!(&self.kind, TransactionKind::ProgrammableTransaction(_)) {
3494 return Ok(());
3495 }
3496 Err(UserInputError::UnsupportedSponsoredTransactionKind)
3497 }
3498
3499 fn is_end_of_epoch_tx(&self) -> bool {
3500 matches!(
3501 self.kind,
3502 TransactionKind::ChangeEpoch(_) | TransactionKind::EndOfEpochTransaction(_)
3503 )
3504 }
3505
3506 fn is_consensus_commit_prologue(&self) -> bool {
3507 match &self.kind {
3508 TransactionKind::ConsensusCommitPrologue(_)
3509 | TransactionKind::ConsensusCommitPrologueV2(_)
3510 | TransactionKind::ConsensusCommitPrologueV3(_)
3511 | TransactionKind::ConsensusCommitPrologueV4(_) => true,
3512
3513 TransactionKind::ProgrammableTransaction(_)
3514 | TransactionKind::ProgrammableSystemTransaction(_)
3515 | TransactionKind::ChangeEpoch(_)
3516 | TransactionKind::Genesis(_)
3517 | TransactionKind::AuthenticatorStateUpdate(_)
3518 | TransactionKind::EndOfEpochTransaction(_)
3519 | TransactionKind::RandomnessStateUpdate(_) => false,
3520 }
3521 }
3522
3523 fn is_system_tx(&self) -> bool {
3524 self.kind.is_system_tx()
3525 }
3526
3527 fn is_genesis_tx(&self) -> bool {
3528 matches!(self.kind, TransactionKind::Genesis(_))
3529 }
3530
3531 fn sender_mut_for_testing(&mut self) -> &mut SuiAddress {
3532 &mut self.sender
3533 }
3534
3535 fn gas_data_mut(&mut self) -> &mut GasData {
3536 &mut self.gas_data
3537 }
3538
3539 fn expiration_mut_for_testing(&mut self) -> &mut TransactionExpiration {
3540 &mut self.expiration
3541 }
3542}
3543
3544impl TransactionDataV1 {
3545 fn accumulate_funds_withdrawals(
3546 &self,
3547 chain_identifier: ChainIdentifier,
3548 coin_resolver: &dyn CoinReservationResolverTrait,
3549 include_gas_payment: bool,
3550 ) -> UserInputResult<BTreeMap<AccumulatorObjId, (u64, TypeTag)>> {
3551 let mut withdraws: Vec<_> = self.get_funds_withdrawals().collect();
3552
3553 for withdraw in self.parsed_coin_reservations(chain_identifier) {
3554 let withdrawal_arg =
3555 coin_resolver.resolve_funds_withdrawal(self.sender(), withdraw, None)?;
3556 withdraws.push(withdrawal_arg);
3557 }
3558
3559 if include_gas_payment {
3560 withdraws.extend(self.get_funds_withdrawal_for_gas_payment());
3561 }
3562
3563 let mut withdraw_map: BTreeMap<AccumulatorObjId, (u64, TypeTag)> = BTreeMap::new();
3564 for withdraw in withdraws {
3565 let reserved_amount = match &withdraw.reservation {
3566 Reservation::MaxAmountU64(amount) => {
3567 if *amount == 0 {
3568 return Err(UserInputError::InvalidWithdrawReservation {
3569 error: "Balance withdraw reservation amount must be non-zero"
3570 .to_string(),
3571 });
3572 }
3573 *amount
3574 }
3575 };
3576
3577 let account_address = withdraw.owner_for_withdrawal(self);
3578 let type_tag = withdraw.type_arg.to_type_tag();
3579 let account_id =
3580 AccumulatorValue::get_field_id(account_address, &type_tag).map_err(|e| {
3581 UserInputError::InvalidWithdrawReservation {
3582 error: e.to_string(),
3583 }
3584 })?;
3585
3586 let (current_amount, _) = withdraw_map
3587 .entry(account_id)
3588 .or_insert_with(|| (0, type_tag));
3589 *current_amount = current_amount.checked_add(reserved_amount).ok_or(
3590 UserInputError::InvalidWithdrawReservation {
3591 error: "Balance withdraw reservation overflow".to_string(),
3592 },
3593 )?;
3594 }
3595
3596 Ok(withdraw_map)
3597 }
3598
3599 fn get_funds_withdrawal_for_gas_payment(&self) -> Option<FundsWithdrawalArg> {
3600 if self.is_gas_paid_from_address_balance() && self.gas_data().budget > 0 {
3601 Some(if self.sender() != self.gas_owner() {
3602 FundsWithdrawalArg::balance_from_sponsor(self.gas_data().budget, GAS::type_tag())
3603 } else {
3604 FundsWithdrawalArg::balance_from_sender(self.gas_data().budget, GAS::type_tag())
3605 })
3606 } else {
3607 None
3608 }
3609 }
3610
3611 fn get_funds_withdrawals(&self) -> impl Iterator<Item = FundsWithdrawalArg> + '_ {
3612 self.kind.get_funds_withdrawals().cloned()
3613 }
3614
3615 fn coin_reservation_obj_refs(&self) -> impl Iterator<Item = ObjectRef> {
3616 self.kind
3617 .get_coin_reservation_obj_refs()
3618 .chain(self.gas().iter().filter_map(|gas_ref| {
3619 if ParsedDigest::is_coin_reservation_digest(&gas_ref.2) {
3620 Some(*gas_ref)
3621 } else {
3622 None
3623 }
3624 }))
3625 }
3626
3627 fn parsed_coin_reservations(
3628 &self,
3629 chain_identifier: ChainIdentifier,
3630 ) -> impl Iterator<Item = ParsedObjectRefWithdrawal> {
3631 self.coin_reservation_obj_refs().map(move |obj_ref| {
3632 ParsedObjectRefWithdrawal::parse(&obj_ref, chain_identifier).unwrap()
3633 })
3634 }
3635}
3636
3637pub struct TxValidityCheckContext<'a> {
3638 pub config: &'a ProtocolConfig,
3639 pub epoch: EpochId,
3640 pub chain_identifier: ChainIdentifier,
3641 pub reference_gas_price: u64,
3642}
3643
3644impl<'a> TxValidityCheckContext<'a> {
3645 pub fn from_cfg_for_testing(config: &'a ProtocolConfig) -> Self {
3646 Self {
3647 config,
3648 epoch: 0,
3649 chain_identifier: ChainIdentifier::default(),
3650 reference_gas_price: 1000,
3651 }
3652 }
3653}
3654
3655#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
3656pub struct SenderSignedData(SizeOneVec<SenderSignedTransaction>);
3657
3658#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3659pub struct SenderSignedTransaction {
3660 pub intent_message: IntentMessage<TransactionData>,
3661 pub tx_signatures: Vec<GenericSignature>,
3665}
3666
3667impl Serialize for SenderSignedTransaction {
3668 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3669 where
3670 S: serde::Serializer,
3671 {
3672 #[derive(Serialize)]
3673 #[serde(rename = "SenderSignedTransaction")]
3674 struct SignedTxn<'a> {
3675 intent_message: &'a IntentMessage<TransactionData>,
3676 tx_signatures: &'a Vec<GenericSignature>,
3677 }
3678
3679 if self.intent_message().intent != Intent::sui_transaction() {
3680 return Err(serde::ser::Error::custom("invalid Intent for Transaction"));
3681 }
3682
3683 let txn = SignedTxn {
3684 intent_message: self.intent_message(),
3685 tx_signatures: &self.tx_signatures,
3686 };
3687 txn.serialize(serializer)
3688 }
3689}
3690
3691impl<'de> Deserialize<'de> for SenderSignedTransaction {
3692 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3693 where
3694 D: serde::Deserializer<'de>,
3695 {
3696 #[derive(Deserialize)]
3697 #[serde(rename = "SenderSignedTransaction")]
3698 struct SignedTxn {
3699 intent_message: IntentMessage<TransactionData>,
3700 tx_signatures: Vec<GenericSignature>,
3701 }
3702
3703 let SignedTxn {
3704 intent_message,
3705 tx_signatures,
3706 } = Deserialize::deserialize(deserializer)?;
3707
3708 if intent_message.intent != Intent::sui_transaction() {
3709 return Err(serde::de::Error::custom("invalid Intent for Transaction"));
3710 }
3711
3712 Ok(Self {
3713 intent_message,
3714 tx_signatures,
3715 })
3716 }
3717}
3718
3719impl SenderSignedTransaction {
3720 pub(crate) fn get_signer_sig_mapping(
3722 &self,
3723 verify_legacy_zklogin_address: bool,
3724 ) -> SuiResult<BTreeMap<SuiAddress, (u8, &GenericSignature)>> {
3725 let mut mapping = BTreeMap::new();
3726 for (idx, sig) in self.tx_signatures.iter().enumerate() {
3727 if verify_legacy_zklogin_address && let GenericSignature::ZkLoginAuthenticator(z) = sig
3728 {
3729 mapping.insert(SuiAddress::try_from_padded(&z.inputs)?, (idx as u8, sig));
3731 }
3732 let address = sig.try_into()?;
3733 mapping.insert(address, (idx as u8, sig));
3734 }
3735 Ok(mapping)
3736 }
3737
3738 pub fn intent_message(&self) -> &IntentMessage<TransactionData> {
3739 &self.intent_message
3740 }
3741}
3742
3743impl SenderSignedData {
3744 pub fn new(tx_data: TransactionData, tx_signatures: Vec<GenericSignature>) -> Self {
3745 Self(SizeOneVec::new(SenderSignedTransaction {
3746 intent_message: IntentMessage::new(Intent::sui_transaction(), tx_data),
3747 tx_signatures,
3748 }))
3749 }
3750
3751 pub fn new_from_sender_signature(tx_data: TransactionData, tx_signature: Signature) -> Self {
3752 Self(SizeOneVec::new(SenderSignedTransaction {
3753 intent_message: IntentMessage::new(Intent::sui_transaction(), tx_data),
3754 tx_signatures: vec![tx_signature.into()],
3755 }))
3756 }
3757
3758 pub fn inner(&self) -> &SenderSignedTransaction {
3759 self.0.element()
3760 }
3761
3762 pub fn into_inner(self) -> SenderSignedTransaction {
3763 self.0.into_inner()
3764 }
3765
3766 pub fn inner_mut(&mut self) -> &mut SenderSignedTransaction {
3767 self.0.element_mut()
3768 }
3769
3770 pub fn add_signature(&mut self, new_signature: Signature) {
3773 self.inner_mut().tx_signatures.push(new_signature.into());
3774 }
3775
3776 pub(crate) fn get_signer_sig_mapping(
3777 &self,
3778 verify_legacy_zklogin_address: bool,
3779 ) -> SuiResult<BTreeMap<SuiAddress, (u8, &GenericSignature)>> {
3780 self.inner()
3781 .get_signer_sig_mapping(verify_legacy_zklogin_address)
3782 }
3783
3784 pub fn transaction_data(&self) -> &TransactionData {
3785 &self.intent_message().value
3786 }
3787
3788 pub fn intent_message(&self) -> &IntentMessage<TransactionData> {
3789 self.inner().intent_message()
3790 }
3791
3792 pub fn tx_signatures(&self) -> &[GenericSignature] {
3793 &self.inner().tx_signatures
3794 }
3795
3796 pub fn has_zklogin_sig(&self) -> bool {
3797 self.tx_signatures().iter().any(|sig| sig.is_zklogin())
3798 }
3799
3800 pub fn has_upgraded_multisig(&self) -> bool {
3801 self.tx_signatures()
3802 .iter()
3803 .any(|sig| sig.is_upgraded_multisig())
3804 }
3805
3806 #[cfg(test)]
3807 pub fn intent_message_mut_for_testing(&mut self) -> &mut IntentMessage<TransactionData> {
3808 &mut self.inner_mut().intent_message
3809 }
3810
3811 pub fn tx_signatures_mut_for_testing(&mut self) -> &mut Vec<GenericSignature> {
3813 &mut self.inner_mut().tx_signatures
3814 }
3815
3816 pub fn full_message_digest_with_alias_versions(
3818 &self,
3819 alias_versions: &Vec<(SuiAddress, Option<SequenceNumber>)>,
3820 ) -> SenderSignedDataDigest {
3821 let mut digest = DefaultHash::default();
3822 bcs::serialize_into(&mut digest, self).expect("serialization should not fail");
3823 bcs::serialize_into(&mut digest, alias_versions).expect("serialization should not fail");
3824 let hash = digest.finalize();
3825 SenderSignedDataDigest::new(hash.into())
3826 }
3827
3828 pub fn serialized_size(&self) -> SuiResult<usize> {
3829 bcs::serialized_size(self).map_err(|e| {
3830 SuiErrorKind::TransactionSerializationError {
3831 error: e.to_string(),
3832 }
3833 .into()
3834 })
3835 }
3836
3837 fn check_user_signature_protocol_compatibility(&self, config: &ProtocolConfig) -> SuiResult {
3838 for sig in &self.inner().tx_signatures {
3839 match sig {
3840 GenericSignature::MultiSig(_) => {
3841 if !config.supports_upgraded_multisig() {
3842 return Err(SuiErrorKind::UserInputError {
3843 error: UserInputError::Unsupported(
3844 "upgraded multisig format not enabled on this network".to_string(),
3845 ),
3846 }
3847 .into());
3848 }
3849 }
3850 GenericSignature::ZkLoginAuthenticator(_) => {
3851 if !config.zklogin_auth() {
3852 return Err(SuiErrorKind::UserInputError {
3853 error: UserInputError::Unsupported(
3854 "zklogin is not enabled on this network".to_string(),
3855 ),
3856 }
3857 .into());
3858 }
3859 }
3860 GenericSignature::PasskeyAuthenticator(_) => {
3861 if !config.passkey_auth() {
3862 return Err(SuiErrorKind::UserInputError {
3863 error: UserInputError::Unsupported(
3864 "passkey is not enabled on this network".to_string(),
3865 ),
3866 }
3867 .into());
3868 }
3869 }
3870 GenericSignature::Signature(_) | GenericSignature::MultiSigLegacy(_) => (),
3871 }
3872 }
3873
3874 Ok(())
3875 }
3876
3877 pub fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> Result<usize, SuiError> {
3880 self.check_user_signature_protocol_compatibility(context.config)?;
3882
3883 let tx_data = &self.transaction_data();
3888 fp_ensure!(
3889 !tx_data.is_system_tx(),
3890 SuiErrorKind::UserInputError {
3891 error: UserInputError::Unsupported(
3892 "SenderSignedData must not contain system transaction".to_string()
3893 )
3894 }
3895 .into()
3896 );
3897
3898 let tx_size = self.serialized_size()?;
3900 let max_tx_size_bytes = context.config.max_tx_size_bytes();
3901 fp_ensure!(
3902 tx_size as u64 <= max_tx_size_bytes,
3903 SuiErrorKind::UserInputError {
3904 error: UserInputError::SizeLimitExceeded {
3905 limit: format!(
3906 "serialized transaction size exceeded maximum of {max_tx_size_bytes}"
3907 ),
3908 value: tx_size.to_string(),
3909 }
3910 }
3911 .into()
3912 );
3913
3914 if context.config.enable_gasless() && tx_data.is_gasless_transaction() {
3915 let gasless_max = context.config.get_gasless_max_tx_size_bytes();
3916 fp_ensure!(
3917 tx_size as u64 <= gasless_max,
3918 SuiErrorKind::UserInputError {
3919 error: UserInputError::SizeLimitExceeded {
3920 limit: format!(
3921 "serialized gasless transaction size exceeded maximum of {gasless_max}"
3922 ),
3923 value: tx_size.to_string(),
3924 }
3925 }
3926 .into()
3927 );
3928 }
3929
3930 tx_data.validity_check(context)?;
3931
3932 Ok(tx_size)
3933 }
3934}
3935
3936impl Message for SenderSignedData {
3937 type DigestType = TransactionDigest;
3938 const SCOPE: IntentScope = IntentScope::SenderSignedTransaction;
3939
3940 fn digest(&self) -> Self::DigestType {
3942 self.intent_message().value.digest()
3943 }
3944}
3945
3946impl<S> Envelope<SenderSignedData, S> {
3947 pub fn sender_address(&self) -> SuiAddress {
3948 self.data().intent_message().value.sender()
3949 }
3950
3951 pub fn gas_owner(&self) -> SuiAddress {
3952 self.data().intent_message().value.gas_owner()
3953 }
3954
3955 pub fn gas(&self) -> &[ObjectRef] {
3956 self.data().intent_message().value.gas()
3957 }
3958
3959 pub fn is_consensus_tx(&self) -> bool {
3960 self.transaction_data().has_funds_withdrawals()
3961 || self.shared_input_objects().next().is_some()
3962 }
3963
3964 pub fn shared_input_objects(&self) -> impl Iterator<Item = SharedInputObject> + '_ {
3965 self.data()
3966 .inner()
3967 .intent_message
3968 .value
3969 .shared_input_objects()
3970 .into_iter()
3971 }
3972
3973 pub fn key(&self) -> TransactionKey {
3975 match &self.data().intent_message().value.kind() {
3976 TransactionKind::RandomnessStateUpdate(rsu) => {
3977 TransactionKey::RandomnessRound(rsu.epoch, rsu.randomness_round)
3978 }
3979 _ => TransactionKey::Digest(*self.digest()),
3980 }
3981 }
3982
3983 pub fn non_digest_key(&self) -> Option<TransactionKey> {
3988 match &self.data().intent_message().value.kind() {
3989 TransactionKind::RandomnessStateUpdate(rsu) => Some(TransactionKey::RandomnessRound(
3990 rsu.epoch,
3991 rsu.randomness_round,
3992 )),
3993 _ => None,
3994 }
3995 }
3996
3997 pub fn is_system_tx(&self) -> bool {
3998 self.data().intent_message().value.is_system_tx()
3999 }
4000
4001 pub fn is_sponsored_tx(&self) -> bool {
4002 self.data().intent_message().value.is_sponsored_tx()
4003 }
4004}
4005
4006impl Transaction {
4007 pub fn from_data_and_signer(
4008 data: TransactionData,
4009 signers: Vec<&dyn Signer<Signature>>,
4010 ) -> Self {
4011 let signatures = {
4012 let intent_msg = IntentMessage::new(Intent::sui_transaction(), &data);
4013 signers
4014 .into_iter()
4015 .map(|s| Signature::new_secure(&intent_msg, s))
4016 .collect()
4017 };
4018 Self::from_data(data, signatures)
4019 }
4020
4021 pub fn from_data(data: TransactionData, signatures: Vec<Signature>) -> Self {
4023 Self::from_generic_sig_data(data, signatures.into_iter().map(|s| s.into()).collect())
4024 }
4025
4026 pub fn signature_from_signer(
4027 data: TransactionData,
4028 intent: Intent,
4029 signer: &dyn Signer<Signature>,
4030 ) -> Signature {
4031 let intent_msg = IntentMessage::new(intent, data);
4032 Signature::new_secure(&intent_msg, signer)
4033 }
4034
4035 pub fn from_generic_sig_data(data: TransactionData, signatures: Vec<GenericSignature>) -> Self {
4036 Self::new(SenderSignedData::new(data, signatures))
4037 }
4038
4039 pub fn to_tx_bytes_and_signatures(&self) -> (Base64, Vec<Base64>) {
4042 (
4043 Base64::from_bytes(&bcs::to_bytes(&self.data().intent_message().value).unwrap()),
4044 self.data()
4045 .inner()
4046 .tx_signatures
4047 .iter()
4048 .map(|s| Base64::from_bytes(s.as_ref()))
4049 .collect(),
4050 )
4051 }
4052}
4053
4054impl VerifiedTransaction {
4055 pub fn new_change_epoch(
4056 next_epoch: EpochId,
4057 protocol_version: ProtocolVersion,
4058 storage_charge: u64,
4059 computation_charge: u64,
4060 storage_rebate: u64,
4061 non_refundable_storage_fee: u64,
4062 epoch_start_timestamp_ms: u64,
4063 system_packages: Vec<(SequenceNumber, Vec<Vec<u8>>, Vec<ObjectID>)>,
4064 ) -> Self {
4065 ChangeEpoch {
4066 epoch: next_epoch,
4067 protocol_version,
4068 storage_charge,
4069 computation_charge,
4070 storage_rebate,
4071 non_refundable_storage_fee,
4072 epoch_start_timestamp_ms,
4073 system_packages,
4074 }
4075 .pipe(TransactionKind::ChangeEpoch)
4076 .pipe(Self::new_system_transaction)
4077 }
4078
4079 pub fn new_genesis_transaction(objects: Vec<GenesisObject>) -> Self {
4080 GenesisTransaction { objects }
4081 .pipe(TransactionKind::Genesis)
4082 .pipe(Self::new_system_transaction)
4083 }
4084
4085 pub fn new_consensus_commit_prologue(
4086 epoch: u64,
4087 round: u64,
4088 commit_timestamp_ms: CheckpointTimestamp,
4089 ) -> Self {
4090 ConsensusCommitPrologue {
4091 epoch,
4092 round,
4093 commit_timestamp_ms,
4094 }
4095 .pipe(TransactionKind::ConsensusCommitPrologue)
4096 .pipe(Self::new_system_transaction)
4097 }
4098
4099 pub fn new_consensus_commit_prologue_v2(
4100 epoch: u64,
4101 round: u64,
4102 commit_timestamp_ms: CheckpointTimestamp,
4103 consensus_commit_digest: ConsensusCommitDigest,
4104 ) -> Self {
4105 ConsensusCommitPrologueV2 {
4106 epoch,
4107 round,
4108 commit_timestamp_ms,
4109 consensus_commit_digest,
4110 }
4111 .pipe(TransactionKind::ConsensusCommitPrologueV2)
4112 .pipe(Self::new_system_transaction)
4113 }
4114
4115 pub fn new_consensus_commit_prologue_v3(
4116 epoch: u64,
4117 round: u64,
4118 commit_timestamp_ms: CheckpointTimestamp,
4119 consensus_commit_digest: ConsensusCommitDigest,
4120 consensus_determined_version_assignments: ConsensusDeterminedVersionAssignments,
4121 ) -> Self {
4122 ConsensusCommitPrologueV3 {
4123 epoch,
4124 round,
4125 sub_dag_index: None,
4127 commit_timestamp_ms,
4128 consensus_commit_digest,
4129 consensus_determined_version_assignments,
4130 }
4131 .pipe(TransactionKind::ConsensusCommitPrologueV3)
4132 .pipe(Self::new_system_transaction)
4133 }
4134
4135 pub fn new_consensus_commit_prologue_v4(
4136 epoch: u64,
4137 round: u64,
4138 commit_timestamp_ms: CheckpointTimestamp,
4139 consensus_commit_digest: ConsensusCommitDigest,
4140 consensus_determined_version_assignments: ConsensusDeterminedVersionAssignments,
4141 additional_state_digest: AdditionalConsensusStateDigest,
4142 ) -> Self {
4143 ConsensusCommitPrologueV4 {
4144 epoch,
4145 round,
4146 sub_dag_index: None,
4148 commit_timestamp_ms,
4149 consensus_commit_digest,
4150 consensus_determined_version_assignments,
4151 additional_state_digest,
4152 }
4153 .pipe(TransactionKind::ConsensusCommitPrologueV4)
4154 .pipe(Self::new_system_transaction)
4155 }
4156
4157 pub fn new_authenticator_state_update(
4158 epoch: u64,
4159 round: u64,
4160 new_active_jwks: Vec<ActiveJwk>,
4161 authenticator_obj_initial_shared_version: SequenceNumber,
4162 ) -> Self {
4163 AuthenticatorStateUpdate {
4164 epoch,
4165 round,
4166 new_active_jwks,
4167 authenticator_obj_initial_shared_version,
4168 }
4169 .pipe(TransactionKind::AuthenticatorStateUpdate)
4170 .pipe(Self::new_system_transaction)
4171 }
4172
4173 pub fn new_randomness_state_update(
4174 epoch: u64,
4175 randomness_round: RandomnessRound,
4176 random_bytes: Vec<u8>,
4177 randomness_obj_initial_shared_version: SequenceNumber,
4178 ) -> Self {
4179 RandomnessStateUpdate {
4180 epoch,
4181 randomness_round,
4182 random_bytes,
4183 randomness_obj_initial_shared_version,
4184 }
4185 .pipe(TransactionKind::RandomnessStateUpdate)
4186 .pipe(Self::new_system_transaction)
4187 }
4188
4189 pub fn new_end_of_epoch_transaction(txns: Vec<EndOfEpochTransactionKind>) -> Self {
4190 TransactionKind::EndOfEpochTransaction(txns).pipe(Self::new_system_transaction)
4191 }
4192
4193 pub fn new_system_transaction(system_transaction: TransactionKind) -> Self {
4194 system_transaction
4195 .pipe(TransactionData::new_system_transaction)
4196 .pipe(|data| {
4197 SenderSignedData::new_from_sender_signature(
4198 data,
4199 Ed25519SuiSignature::from_bytes(&[0; Ed25519SuiSignature::LENGTH])
4200 .unwrap()
4201 .into(),
4202 )
4203 })
4204 .pipe(Transaction::new)
4205 .pipe(Self::new_from_verified)
4206 }
4207}
4208
4209impl VerifiedSignedTransaction {
4210 pub fn new(
4212 epoch: EpochId,
4213 transaction: VerifiedTransaction,
4214 authority: AuthorityName,
4215 secret: &dyn Signer<AuthoritySignature>,
4216 ) -> Self {
4217 Self::new_from_verified(SignedTransaction::new(
4218 epoch,
4219 transaction.into_inner().into_data(),
4220 secret,
4221 authority,
4222 ))
4223 }
4224}
4225
4226pub type Transaction = Envelope<SenderSignedData, EmptySignInfo>;
4228pub type VerifiedTransaction = VerifiedEnvelope<SenderSignedData, EmptySignInfo>;
4229pub type TrustedTransaction = TrustedEnvelope<SenderSignedData, EmptySignInfo>;
4230
4231pub type SignedTransaction = Envelope<SenderSignedData, AuthoritySignInfo>;
4233pub type VerifiedSignedTransaction = VerifiedEnvelope<SenderSignedData, AuthoritySignInfo>;
4234
4235impl Transaction {
4236 pub fn verify_signature_for_testing(
4237 &self,
4238 current_epoch: EpochId,
4239 verify_params: &VerifyParams,
4240 ) -> SuiResult {
4241 verify_sender_signed_data_message_signatures(
4242 self.data(),
4243 current_epoch,
4244 verify_params,
4245 Arc::new(VerifiedDigestCache::new_empty()),
4246 vec![],
4247 )?;
4248 Ok(())
4249 }
4250
4251 pub fn try_into_verified_for_testing(
4252 self,
4253 current_epoch: EpochId,
4254 verify_params: &VerifyParams,
4255 ) -> SuiResult<VerifiedTransaction> {
4256 self.verify_signature_for_testing(current_epoch, verify_params)?;
4257 Ok(VerifiedTransaction::new_from_verified(self))
4258 }
4259}
4260
4261impl SignedTransaction {
4262 pub fn verify_signatures_authenticated_for_testing(
4263 &self,
4264 committee: &Committee,
4265 verify_params: &VerifyParams,
4266 ) -> SuiResult {
4267 verify_sender_signed_data_message_signatures(
4268 self.data(),
4269 committee.epoch(),
4270 verify_params,
4271 Arc::new(VerifiedDigestCache::new_empty()),
4272 vec![],
4273 )?;
4274
4275 self.auth_sig().verify_secure(
4276 self.data(),
4277 Intent::sui_app(IntentScope::SenderSignedTransaction),
4278 committee,
4279 )
4280 }
4281
4282 pub fn try_into_verified_for_testing(
4283 self,
4284 committee: &Committee,
4285 verify_params: &VerifyParams,
4286 ) -> SuiResult<VerifiedSignedTransaction> {
4287 self.verify_signatures_authenticated_for_testing(committee, verify_params)?;
4288 Ok(VerifiedSignedTransaction::new_from_verified(self))
4289 }
4290}
4291
4292pub type CertifiedTransaction = Envelope<SenderSignedData, AuthorityStrongQuorumSignInfo>;
4293
4294impl CertifiedTransaction {
4295 pub fn gas_price(&self) -> u64 {
4296 self.data().transaction_data().gas_price()
4297 }
4298}
4299
4300pub type VerifiedCertificate = VerifiedEnvelope<SenderSignedData, AuthorityStrongQuorumSignInfo>;
4301pub type TrustedCertificate = TrustedEnvelope<SenderSignedData, AuthorityStrongQuorumSignInfo>;
4302
4303#[derive(Clone, Debug, Serialize, Deserialize)]
4304pub struct WithAliases<T>(
4305 T,
4306 #[serde(with = "nonempty_as_vec")] NonEmpty<(u8, Option<SequenceNumber>)>,
4307);
4308
4309impl<T> WithAliases<T> {
4310 pub fn new(tx: T, aliases: NonEmpty<(u8, Option<SequenceNumber>)>) -> Self {
4311 Self(tx, aliases)
4312 }
4313
4314 pub fn tx(&self) -> &T {
4315 &self.0
4316 }
4317
4318 pub fn aliases(&self) -> &NonEmpty<(u8, Option<SequenceNumber>)> {
4319 &self.1
4320 }
4321
4322 pub fn into_tx(self) -> T {
4323 self.0
4324 }
4325
4326 pub fn into_aliases(self) -> NonEmpty<(u8, Option<SequenceNumber>)> {
4327 self.1
4328 }
4329
4330 pub fn into_inner(self) -> (T, NonEmpty<(u8, Option<SequenceNumber>)>) {
4331 (self.0, self.1)
4332 }
4333}
4334
4335impl<T: Message, S> WithAliases<VerifiedEnvelope<T, S>> {
4336 pub fn serializable(self) -> WithAliases<TrustedEnvelope<T, S>> {
4338 WithAliases(self.0.serializable(), self.1)
4339 }
4340}
4341
4342impl<S> WithAliases<Envelope<SenderSignedData, S>> {
4343 pub fn no_aliases(tx: Envelope<SenderSignedData, S>) -> Self {
4346 let required_signers = tx.intent_message().value.required_signers();
4347 assert_eq!(required_signers.len(), tx.tx_signatures().len());
4348 let no_aliases = required_signers
4349 .iter()
4350 .enumerate()
4351 .map(|(idx, _)| (idx as u8, None))
4352 .collect::<Vec<_>>();
4353 Self::new(
4354 tx,
4355 NonEmpty::from_vec(no_aliases).expect("must have at least one required_signer"),
4356 )
4357 }
4358}
4359
4360impl<S> WithAliases<VerifiedEnvelope<SenderSignedData, S>> {
4361 pub fn no_aliases(tx: VerifiedEnvelope<SenderSignedData, S>) -> Self {
4364 let required_signers = tx.intent_message().value.required_signers();
4365 assert_eq!(required_signers.len(), tx.tx_signatures().len());
4366 let no_aliases = required_signers
4367 .iter()
4368 .enumerate()
4369 .map(|(idx, _)| (idx as u8, None))
4370 .collect::<Vec<_>>();
4371 Self::new(
4372 tx,
4373 NonEmpty::from_vec(no_aliases).expect("must have at least one required_signer"),
4374 )
4375 }
4376}
4377
4378pub type TransactionWithAliases = WithAliases<Transaction>;
4379pub type VerifiedTransactionWithAliases = WithAliases<VerifiedTransaction>;
4380pub type TrustedTransactionWithAliases = WithAliases<TrustedTransaction>;
4381
4382#[derive(Clone, Debug, Serialize, Deserialize)]
4387pub struct DeprecatedWithAliases<T>(
4388 T,
4389 #[serde(with = "nonempty_as_vec")] NonEmpty<(SuiAddress, Option<SequenceNumber>)>,
4390);
4391
4392impl<T> DeprecatedWithAliases<T> {
4393 pub fn into_inner(self) -> (T, NonEmpty<(SuiAddress, Option<SequenceNumber>)>) {
4394 (self.0, self.1)
4395 }
4396}
4397
4398impl<T: Message, S> From<WithAliases<VerifiedEnvelope<T, S>>> for WithAliases<Envelope<T, S>> {
4399 fn from(value: WithAliases<VerifiedEnvelope<T, S>>) -> Self {
4400 Self(value.0.into(), value.1)
4401 }
4402}
4403
4404impl<T: Message, S> From<WithAliases<TrustedEnvelope<T, S>>>
4405 for WithAliases<VerifiedEnvelope<T, S>>
4406{
4407 fn from(value: WithAliases<TrustedEnvelope<T, S>>) -> Self {
4408 Self(value.0.into(), value.1)
4409 }
4410}
4411
4412mod nonempty_as_vec {
4413 use super::*;
4414 use serde::{Deserialize, Deserializer, Serialize, Serializer};
4415
4416 pub fn serialize<S, T>(value: &NonEmpty<T>, serializer: S) -> Result<S::Ok, S::Error>
4417 where
4418 S: Serializer,
4419 T: Serialize,
4420 {
4421 let vec: Vec<&T> = value.iter().collect();
4422 vec.serialize(serializer)
4423 }
4424
4425 pub fn deserialize<'de, D, T>(deserializer: D) -> Result<NonEmpty<T>, D::Error>
4426 where
4427 D: Deserializer<'de>,
4428 T: Deserialize<'de> + Clone,
4429 {
4430 use serde::de::{SeqAccess, Visitor};
4431 use std::fmt;
4432 use std::marker::PhantomData;
4433
4434 struct NonEmptyVisitor<T>(PhantomData<T>);
4435
4436 impl<'de, T> Visitor<'de> for NonEmptyVisitor<T>
4437 where
4438 T: Deserialize<'de> + Clone,
4439 {
4440 type Value = NonEmpty<T>;
4441
4442 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
4443 formatter.write_str("a non-empty sequence")
4444 }
4445
4446 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
4447 where
4448 A: SeqAccess<'de>,
4449 {
4450 let head = seq
4451 .next_element()?
4452 .ok_or_else(|| serde::de::Error::custom("empty vector"))?;
4453
4454 let mut tail = Vec::new();
4455 while let Some(elem) = seq.next_element()? {
4456 tail.push(elem);
4457 }
4458
4459 Ok(NonEmpty { head, tail })
4460 }
4461 }
4462
4463 deserializer.deserialize_seq(NonEmptyVisitor(PhantomData))
4464 }
4465}
4466
4467#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
4477pub enum TransactionClaim {
4478 #[deprecated(note = "Use AddressAliasesV2")]
4480 AddressAliases(
4481 #[serde(with = "nonempty_as_vec")] NonEmpty<(SuiAddress, Option<SequenceNumber>)>,
4482 ),
4483
4484 ImmutableInputObjects(Vec<ObjectID>),
4487
4488 AddressAliasesV2(#[serde(with = "nonempty_as_vec")] NonEmpty<(u8, Option<SequenceNumber>)>),
4492}
4493
4494#[derive(Clone, Debug, Serialize, Deserialize)]
4496pub struct TransactionWithClaims<T> {
4497 tx: T,
4498 claims: Vec<TransactionClaim>,
4499}
4500
4501impl<T> TransactionWithClaims<T> {
4502 pub fn new(tx: T, claims: Vec<TransactionClaim>) -> Self {
4503 Self { tx, claims }
4504 }
4505
4506 pub fn from_aliases(tx: T, aliases: NonEmpty<(u8, Option<SequenceNumber>)>) -> Self {
4508 Self {
4509 tx,
4510 claims: vec![TransactionClaim::AddressAliasesV2(aliases)],
4511 }
4512 }
4513
4514 pub fn no_aliases(tx: T) -> Self {
4516 Self { tx, claims: vec![] }
4517 }
4518
4519 pub fn tx(&self) -> &T {
4520 &self.tx
4521 }
4522
4523 pub fn into_tx(self) -> T {
4524 self.tx
4525 }
4526
4527 pub fn aliases(&self) -> Option<NonEmpty<(u8, Option<SequenceNumber>)>> {
4529 self.claims
4530 .iter()
4531 .find_map(|c| match c {
4532 TransactionClaim::AddressAliasesV2(aliases) => Some(aliases),
4533 _ => None,
4534 })
4535 .cloned()
4536 }
4537
4538 #[allow(deprecated)]
4540 pub fn aliases_v1(&self) -> Option<NonEmpty<(SuiAddress, Option<SequenceNumber>)>> {
4541 self.claims
4542 .iter()
4543 .find_map(|c| match c {
4544 TransactionClaim::AddressAliases(aliases) => Some(aliases),
4545 _ => None,
4546 })
4547 .cloned()
4548 }
4549
4550 pub fn get_immutable_objects(&self) -> Vec<ObjectID> {
4552 self.claims
4553 .iter()
4554 .find_map(|c| match c {
4555 TransactionClaim::ImmutableInputObjects(objs) => Some(objs.clone()),
4556 _ => None,
4557 })
4558 .unwrap_or_default()
4559 }
4560}
4561
4562pub type PlainTransactionWithClaims = TransactionWithClaims<Transaction>;
4563
4564impl<T: Message, S> From<WithAliases<VerifiedEnvelope<T, S>>>
4567 for TransactionWithClaims<Envelope<T, S>>
4568{
4569 fn from(value: WithAliases<VerifiedEnvelope<T, S>>) -> Self {
4570 let (tx, aliases) = value.into_inner();
4571 Self::from_aliases(tx.into(), aliases)
4572 }
4573}
4574
4575#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord, Hash)]
4576pub enum InputObjectKind {
4577 MovePackage(ObjectID),
4579 ImmOrOwnedMoveObject(ObjectRef),
4581 SharedMoveObject {
4583 id: ObjectID,
4584 initial_shared_version: SequenceNumber,
4585 mutability: SharedObjectMutability,
4586 },
4587}
4588
4589#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord, Hash)]
4590pub enum SharedObjectMutability {
4591 Immutable,
4593 Mutable,
4594 NonExclusiveWrite,
4598}
4599
4600impl SharedObjectMutability {
4601 pub fn is_exclusive(&self) -> bool {
4602 match self {
4603 SharedObjectMutability::Mutable => true,
4604 SharedObjectMutability::Immutable => false,
4605 SharedObjectMutability::NonExclusiveWrite => false,
4606 }
4607 }
4608}
4609
4610impl InputObjectKind {
4611 pub fn object_id(&self) -> ObjectID {
4612 self.full_object_id().id()
4613 }
4614
4615 pub fn full_object_id(&self) -> FullObjectID {
4616 match self {
4617 Self::MovePackage(id) => FullObjectID::Fastpath(*id),
4618 Self::ImmOrOwnedMoveObject((id, _, _)) => FullObjectID::Fastpath(*id),
4619 Self::SharedMoveObject {
4620 id,
4621 initial_shared_version,
4622 ..
4623 } => FullObjectID::Consensus((*id, *initial_shared_version)),
4624 }
4625 }
4626
4627 pub fn version(&self) -> Option<SequenceNumber> {
4628 match self {
4629 Self::MovePackage(..) => None,
4630 Self::ImmOrOwnedMoveObject((_, version, _)) => Some(*version),
4631 Self::SharedMoveObject { .. } => None,
4632 }
4633 }
4634
4635 pub fn object_not_found_error(&self) -> UserInputError {
4636 match *self {
4637 Self::MovePackage(package_id) => {
4638 UserInputError::DependentPackageNotFound { package_id }
4639 }
4640 Self::ImmOrOwnedMoveObject((object_id, version, _)) => UserInputError::ObjectNotFound {
4641 object_id,
4642 version: Some(version),
4643 },
4644 Self::SharedMoveObject { id, .. } => UserInputError::ObjectNotFound {
4645 object_id: id,
4646 version: None,
4647 },
4648 }
4649 }
4650
4651 pub fn is_shared_object(&self) -> bool {
4652 matches!(self, Self::SharedMoveObject { .. })
4653 }
4654}
4655
4656#[derive(Clone, Debug)]
4659pub struct ObjectReadResult {
4660 pub input_object_kind: InputObjectKind,
4661 pub object: ObjectReadResultKind,
4662}
4663
4664#[derive(Clone)]
4665pub enum ObjectReadResultKind {
4666 Object(Object),
4667 ObjectConsensusStreamEnded(SequenceNumber, TransactionDigest),
4670 CancelledTransactionSharedObject(SequenceNumber),
4672}
4673
4674impl ObjectReadResultKind {
4675 pub fn is_cancelled(&self) -> bool {
4676 matches!(
4677 self,
4678 ObjectReadResultKind::CancelledTransactionSharedObject(_)
4679 )
4680 }
4681
4682 pub fn version(&self) -> SequenceNumber {
4683 match self {
4684 ObjectReadResultKind::Object(object) => object.version(),
4685 ObjectReadResultKind::ObjectConsensusStreamEnded(seq, _) => *seq,
4686 ObjectReadResultKind::CancelledTransactionSharedObject(seq) => *seq,
4687 }
4688 }
4689}
4690
4691impl std::fmt::Debug for ObjectReadResultKind {
4692 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4693 match self {
4694 ObjectReadResultKind::Object(obj) => {
4695 write!(f, "Object({:?})", obj.compute_object_reference())
4696 }
4697 ObjectReadResultKind::ObjectConsensusStreamEnded(seq, digest) => {
4698 write!(f, "ObjectConsensusStreamEnded({}, {:?})", seq, digest)
4699 }
4700 ObjectReadResultKind::CancelledTransactionSharedObject(seq) => {
4701 write!(f, "CancelledTransactionSharedObject({})", seq)
4702 }
4703 }
4704 }
4705}
4706
4707impl From<Object> for ObjectReadResultKind {
4708 fn from(object: Object) -> Self {
4709 Self::Object(object)
4710 }
4711}
4712
4713impl ObjectReadResult {
4714 pub fn new(input_object_kind: InputObjectKind, object: ObjectReadResultKind) -> Self {
4715 if let (
4716 InputObjectKind::ImmOrOwnedMoveObject(_),
4717 ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
4718 ) = (&input_object_kind, &object)
4719 {
4720 panic!("only consensus objects can be ObjectConsensusStreamEnded");
4721 }
4722
4723 if let (
4724 InputObjectKind::ImmOrOwnedMoveObject(_),
4725 ObjectReadResultKind::CancelledTransactionSharedObject(_),
4726 ) = (&input_object_kind, &object)
4727 {
4728 panic!("only consensus objects can be CancelledTransactionSharedObject");
4729 }
4730
4731 Self {
4732 input_object_kind,
4733 object,
4734 }
4735 }
4736
4737 pub fn id(&self) -> ObjectID {
4738 self.input_object_kind.object_id()
4739 }
4740
4741 pub fn as_object(&self) -> Option<&Object> {
4742 match &self.object {
4743 ObjectReadResultKind::Object(object) => Some(object),
4744 ObjectReadResultKind::ObjectConsensusStreamEnded(_, _) => None,
4745 ObjectReadResultKind::CancelledTransactionSharedObject(_) => None,
4746 }
4747 }
4748
4749 pub fn new_from_gas_object(gas: &Object) -> Self {
4750 let objref = gas.compute_object_reference();
4751 Self {
4752 input_object_kind: InputObjectKind::ImmOrOwnedMoveObject(objref),
4753 object: ObjectReadResultKind::Object(gas.clone()),
4754 }
4755 }
4756
4757 pub fn is_mutable(&self) -> bool {
4758 match (&self.input_object_kind, &self.object) {
4759 (InputObjectKind::MovePackage(_), _) => false,
4760 (InputObjectKind::ImmOrOwnedMoveObject(_), ObjectReadResultKind::Object(object)) => {
4761 !object.is_immutable()
4762 }
4763 (
4764 InputObjectKind::ImmOrOwnedMoveObject(_),
4765 ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
4766 ) => unreachable!(),
4767 (
4768 InputObjectKind::ImmOrOwnedMoveObject(_),
4769 ObjectReadResultKind::CancelledTransactionSharedObject(_),
4770 ) => unreachable!(),
4771 (InputObjectKind::SharedMoveObject { mutability, .. }, _) => match mutability {
4772 SharedObjectMutability::Mutable => true,
4773 SharedObjectMutability::Immutable => false,
4774 SharedObjectMutability::NonExclusiveWrite => false,
4775 },
4776 }
4777 }
4778
4779 pub fn is_shared_object(&self) -> bool {
4780 self.input_object_kind.is_shared_object()
4781 }
4782
4783 pub fn is_consensus_stream_ended(&self) -> bool {
4784 self.consensus_stream_end_info().is_some()
4785 }
4786
4787 pub fn consensus_stream_end_info(&self) -> Option<(SequenceNumber, TransactionDigest)> {
4788 match &self.object {
4789 ObjectReadResultKind::ObjectConsensusStreamEnded(v, tx) => Some((*v, *tx)),
4790 _ => None,
4791 }
4792 }
4793
4794 pub fn get_address_owned_objref(&self) -> Option<ObjectRef> {
4796 match (&self.input_object_kind, &self.object) {
4797 (InputObjectKind::MovePackage(_), _) => None,
4798 (
4799 InputObjectKind::ImmOrOwnedMoveObject(objref),
4800 ObjectReadResultKind::Object(object),
4801 ) => {
4802 if object.is_immutable() {
4803 None
4804 } else {
4805 Some(*objref)
4806 }
4807 }
4808 (
4809 InputObjectKind::ImmOrOwnedMoveObject(_),
4810 ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
4811 ) => unreachable!(),
4812 (
4813 InputObjectKind::ImmOrOwnedMoveObject(_),
4814 ObjectReadResultKind::CancelledTransactionSharedObject(_),
4815 ) => unreachable!(),
4816 (InputObjectKind::SharedMoveObject { .. }, _) => None,
4817 }
4818 }
4819
4820 pub fn is_address_owned(&self) -> bool {
4821 self.get_address_owned_objref().is_some()
4822 }
4823
4824 pub fn is_replay_protected_input(&self) -> bool {
4825 if let InputObjectKind::ImmOrOwnedMoveObject(obj_ref) = &self.input_object_kind
4826 && ParsedDigest::is_coin_reservation_digest(&obj_ref.2)
4827 {
4828 true
4829 } else {
4830 self.is_address_owned()
4831 }
4832 }
4833
4834 pub fn to_shared_input(&self) -> Option<SharedInput> {
4835 match self.input_object_kind {
4836 InputObjectKind::MovePackage(_) => None,
4837 InputObjectKind::ImmOrOwnedMoveObject(_) => None,
4838 InputObjectKind::SharedMoveObject { id, mutability, .. } => Some(match &self.object {
4839 ObjectReadResultKind::Object(obj) => {
4840 SharedInput::Existing(obj.compute_object_reference())
4841 }
4842 ObjectReadResultKind::ObjectConsensusStreamEnded(seq, digest) => {
4843 SharedInput::ConsensusStreamEnded((id, *seq, mutability, *digest))
4844 }
4845 ObjectReadResultKind::CancelledTransactionSharedObject(seq) => {
4846 SharedInput::Cancelled((id, *seq))
4847 }
4848 }),
4849 }
4850 }
4851
4852 pub fn get_previous_transaction(&self) -> Option<TransactionDigest> {
4853 match &self.object {
4854 ObjectReadResultKind::Object(obj) => Some(obj.previous_transaction),
4855 ObjectReadResultKind::ObjectConsensusStreamEnded(_, digest) => Some(*digest),
4856 ObjectReadResultKind::CancelledTransactionSharedObject(_) => None,
4857 }
4858 }
4859}
4860
4861#[derive(Clone)]
4862pub struct InputObjects {
4863 objects: Vec<ObjectReadResult>,
4864}
4865
4866impl std::fmt::Debug for InputObjects {
4867 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4868 f.debug_list().entries(self.objects.iter()).finish()
4869 }
4870}
4871
4872#[derive(Clone)]
4875pub struct CheckedInputObjects(InputObjects);
4876
4877impl CheckedInputObjects {
4883 pub fn new_with_checked_transaction_inputs(inputs: InputObjects) -> Self {
4885 Self(inputs)
4886 }
4887
4888 pub fn new_for_genesis(input_objects: Vec<ObjectReadResult>) -> Self {
4890 Self(InputObjects::new(input_objects))
4891 }
4892
4893 pub fn new_for_replay(input_objects: InputObjects) -> Self {
4895 Self(input_objects)
4896 }
4897
4898 pub fn inner(&self) -> &InputObjects {
4899 &self.0
4900 }
4901
4902 pub fn into_inner(self) -> InputObjects {
4903 self.0
4904 }
4905}
4906
4907impl From<Vec<ObjectReadResult>> for InputObjects {
4908 fn from(objects: Vec<ObjectReadResult>) -> Self {
4909 Self::new(objects)
4910 }
4911}
4912
4913impl InputObjects {
4914 pub fn new(objects: Vec<ObjectReadResult>) -> Self {
4915 Self { objects }
4916 }
4917
4918 pub fn len(&self) -> usize {
4919 self.objects.len()
4920 }
4921
4922 pub fn is_empty(&self) -> bool {
4923 self.objects.is_empty()
4924 }
4925
4926 pub fn contains_consensus_stream_ended_objects(&self) -> bool {
4927 self.objects
4928 .iter()
4929 .any(|obj| obj.is_consensus_stream_ended())
4930 }
4931
4932 pub fn get_cancelled_objects(&self) -> Option<(Vec<ObjectID>, SequenceNumber)> {
4935 let mut contains_cancelled = false;
4936 let mut cancel_reason = None;
4937 let mut cancelled_objects = Vec::new();
4938 for obj in &self.objects {
4939 if let ObjectReadResultKind::CancelledTransactionSharedObject(version) = obj.object {
4940 contains_cancelled = true;
4941 if version == SequenceNumber::CONGESTED
4942 || version == SequenceNumber::RANDOMNESS_UNAVAILABLE
4943 {
4944 assert!(cancel_reason.is_none() || cancel_reason == Some(version));
4946 cancel_reason = Some(version);
4947 cancelled_objects.push(obj.id());
4948 }
4949 }
4950 }
4951
4952 if !cancelled_objects.is_empty() {
4953 Some((
4954 cancelled_objects,
4955 cancel_reason
4956 .expect("there should be a cancel reason if there are cancelled objects"),
4957 ))
4958 } else {
4959 assert!(!contains_cancelled);
4960 None
4961 }
4962 }
4963
4964 pub fn filter_owned_objects(&self) -> Vec<ObjectRef> {
4965 let owned_objects: Vec<_> = self
4966 .objects
4967 .iter()
4968 .filter_map(|obj| obj.get_address_owned_objref())
4969 .collect();
4970
4971 trace!(
4972 num_mutable_objects = owned_objects.len(),
4973 "Checked locks and found mutable objects"
4974 );
4975
4976 owned_objects
4977 }
4978
4979 pub fn filter_shared_objects(&self) -> Vec<SharedInput> {
4980 self.objects
4981 .iter()
4982 .filter(|obj| obj.is_shared_object())
4983 .map(|obj| {
4984 obj.to_shared_input()
4985 .expect("already filtered for shared objects")
4986 })
4987 .collect()
4988 }
4989
4990 pub fn transaction_dependencies(&self) -> BTreeSet<TransactionDigest> {
4991 self.objects
4992 .iter()
4993 .filter_map(|obj| obj.get_previous_transaction())
4994 .collect()
4995 }
4996
4997 pub fn exclusive_mutable_inputs(&self) -> BTreeMap<ObjectID, (VersionDigest, Owner)> {
5000 self.mutables_with_input_kinds()
5001 .filter_map(|(id, (version, owner, kind))| match kind {
5002 InputObjectKind::SharedMoveObject { mutability, .. } => match mutability {
5003 SharedObjectMutability::Mutable => Some((id, (version, owner))),
5004 SharedObjectMutability::Immutable => None,
5005 SharedObjectMutability::NonExclusiveWrite => None,
5006 },
5007 _ => Some((id, (version, owner))),
5008 })
5009 .collect()
5010 }
5011
5012 pub fn non_exclusive_input_objects(&self) -> BTreeMap<ObjectID, Object> {
5013 self.objects
5014 .iter()
5015 .filter_map(|read_result| {
5016 match (read_result.as_object(), read_result.input_object_kind) {
5017 (
5018 Some(object),
5019 InputObjectKind::SharedMoveObject {
5020 mutability: SharedObjectMutability::NonExclusiveWrite,
5021 ..
5022 },
5023 ) => Some((read_result.id(), object.clone())),
5024 _ => None,
5025 }
5026 })
5027 .collect()
5028 }
5029
5030 pub fn all_mutable_inputs(&self) -> BTreeMap<ObjectID, (VersionDigest, Owner)> {
5033 self.mutables_with_input_kinds()
5034 .filter_map(|(id, (version, owner, kind))| match kind {
5035 InputObjectKind::SharedMoveObject { mutability, .. } => match mutability {
5036 SharedObjectMutability::Mutable => Some((id, (version, owner))),
5037 SharedObjectMutability::Immutable => None,
5038 SharedObjectMutability::NonExclusiveWrite => Some((id, (version, owner))),
5039 },
5040 _ => Some((id, (version, owner))),
5041 })
5042 .collect()
5043 }
5044
5045 fn mutables_with_input_kinds(
5046 &self,
5047 ) -> impl Iterator<Item = (ObjectID, (VersionDigest, Owner, InputObjectKind))> + '_ {
5048 self.objects.iter().filter_map(
5049 |ObjectReadResult {
5050 input_object_kind,
5051 object,
5052 }| match (input_object_kind, object) {
5053 (InputObjectKind::MovePackage(_), _) => None,
5054 (
5055 InputObjectKind::ImmOrOwnedMoveObject(object_ref),
5056 ObjectReadResultKind::Object(object),
5057 ) => {
5058 if object.is_immutable() {
5059 None
5060 } else {
5061 Some((
5062 object_ref.0,
5063 (
5064 (object_ref.1, object_ref.2),
5065 object.owner.clone(),
5066 *input_object_kind,
5067 ),
5068 ))
5069 }
5070 }
5071 (
5072 InputObjectKind::ImmOrOwnedMoveObject(_),
5073 ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
5074 ) => {
5075 unreachable!()
5076 }
5077 (
5078 InputObjectKind::SharedMoveObject { .. },
5079 ObjectReadResultKind::ObjectConsensusStreamEnded(_, _),
5080 ) => None,
5081 (
5082 InputObjectKind::SharedMoveObject { mutability, .. },
5083 ObjectReadResultKind::Object(object),
5084 ) => match *mutability {
5085 SharedObjectMutability::Mutable => {
5086 let oref = object.compute_object_reference();
5087 Some((
5088 oref.0,
5089 ((oref.1, oref.2), object.owner.clone(), *input_object_kind),
5090 ))
5091 }
5092 SharedObjectMutability::Immutable => None,
5093 SharedObjectMutability::NonExclusiveWrite => {
5094 let oref = object.compute_object_reference();
5095 Some((
5096 oref.0,
5097 ((oref.1, oref.2), object.owner.clone(), *input_object_kind),
5098 ))
5099 }
5100 },
5101 (
5102 InputObjectKind::ImmOrOwnedMoveObject(_),
5103 ObjectReadResultKind::CancelledTransactionSharedObject(_),
5104 ) => {
5105 unreachable!()
5106 }
5107 (
5108 InputObjectKind::SharedMoveObject { .. },
5109 ObjectReadResultKind::CancelledTransactionSharedObject(_),
5110 ) => None,
5111 },
5112 )
5113 }
5114
5115 pub fn lamport_timestamp(&self, receiving_objects: &[ObjectRef]) -> SequenceNumber {
5119 let input_versions = self
5120 .objects
5121 .iter()
5122 .filter_map(|object| match &object.object {
5123 ObjectReadResultKind::Object(object) => {
5124 object.data.try_as_move().map(MoveObject::version)
5125 }
5126 ObjectReadResultKind::ObjectConsensusStreamEnded(v, _) => Some(*v),
5127 ObjectReadResultKind::CancelledTransactionSharedObject(_) => None,
5128 })
5129 .chain(receiving_objects.iter().map(|object_ref| object_ref.1));
5130
5131 SequenceNumber::lamport_increment(input_versions)
5132 }
5133
5134 pub fn object_kinds(&self) -> impl Iterator<Item = &InputObjectKind> {
5135 self.objects.iter().map(
5136 |ObjectReadResult {
5137 input_object_kind, ..
5138 }| input_object_kind,
5139 )
5140 }
5141
5142 pub fn consensus_stream_ended_objects(&self) -> BTreeMap<ObjectID, SequenceNumber> {
5143 self.objects
5144 .iter()
5145 .filter_map(|obj| {
5146 if let InputObjectKind::SharedMoveObject {
5147 id,
5148 initial_shared_version,
5149 ..
5150 } = obj.input_object_kind
5151 {
5152 obj.is_consensus_stream_ended()
5153 .then_some((id, initial_shared_version))
5154 } else {
5155 None
5156 }
5157 })
5158 .collect()
5159 }
5160
5161 pub fn into_object_map(self) -> BTreeMap<ObjectID, Object> {
5162 self.objects
5163 .into_iter()
5164 .filter_map(|o| o.as_object().map(|object| (o.id(), object.clone())))
5165 .collect()
5166 }
5167
5168 pub fn push(&mut self, object: ObjectReadResult) {
5169 self.objects.push(object);
5170 }
5171
5172 pub fn iter(&self) -> impl Iterator<Item = &ObjectReadResult> {
5173 self.objects.iter()
5174 }
5175
5176 pub fn iter_objects(&self) -> impl Iterator<Item = &Object> {
5177 self.objects.iter().filter_map(|o| o.as_object())
5178 }
5179
5180 pub fn non_exclusive_mutable_inputs(
5181 &self,
5182 ) -> impl Iterator<Item = (ObjectID, SequenceNumber)> + '_ {
5183 self.objects.iter().filter_map(
5184 |ObjectReadResult {
5185 input_object_kind,
5186 object,
5187 }| match input_object_kind {
5188 InputObjectKind::SharedMoveObject {
5192 id,
5193 mutability: SharedObjectMutability::NonExclusiveWrite,
5194 ..
5195 } if !object.is_cancelled() => Some((*id, object.version())),
5196 _ => None,
5197 },
5198 )
5199 }
5200}
5201
5202#[derive(Clone, Debug)]
5206pub enum ReceivingObjectReadResultKind {
5207 Object(Object),
5208 PreviouslyReceivedObject,
5210}
5211
5212impl ReceivingObjectReadResultKind {
5213 pub fn as_object(&self) -> Option<&Object> {
5214 match &self {
5215 Self::Object(object) => Some(object),
5216 Self::PreviouslyReceivedObject => None,
5217 }
5218 }
5219}
5220
5221pub struct ReceivingObjectReadResult {
5222 pub object_ref: ObjectRef,
5223 pub object: ReceivingObjectReadResultKind,
5224}
5225
5226impl ReceivingObjectReadResult {
5227 pub fn new(object_ref: ObjectRef, object: ReceivingObjectReadResultKind) -> Self {
5228 Self { object_ref, object }
5229 }
5230
5231 pub fn is_previously_received(&self) -> bool {
5232 matches!(
5233 self.object,
5234 ReceivingObjectReadResultKind::PreviouslyReceivedObject
5235 )
5236 }
5237}
5238
5239impl From<Object> for ReceivingObjectReadResultKind {
5240 fn from(object: Object) -> Self {
5241 Self::Object(object)
5242 }
5243}
5244
5245pub struct ReceivingObjects {
5246 pub objects: Vec<ReceivingObjectReadResult>,
5247}
5248
5249impl ReceivingObjects {
5250 pub fn iter(&self) -> impl Iterator<Item = &ReceivingObjectReadResult> {
5251 self.objects.iter()
5252 }
5253
5254 pub fn iter_objects(&self) -> impl Iterator<Item = &Object> {
5255 self.objects.iter().filter_map(|o| o.object.as_object())
5256 }
5257}
5258
5259impl From<Vec<ReceivingObjectReadResult>> for ReceivingObjects {
5260 fn from(objects: Vec<ReceivingObjectReadResult>) -> Self {
5261 Self { objects }
5262 }
5263}
5264
5265impl Display for CertifiedTransaction {
5266 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
5267 let mut writer = String::new();
5268 writeln!(writer, "Transaction Hash: {:?}", self.digest())?;
5269 writeln!(
5270 writer,
5271 "Signed Authorities Bitmap : {:?}",
5272 self.auth_sig().signers_map
5273 )?;
5274 write!(writer, "{}", &self.data().intent_message().value.kind())?;
5275 write!(f, "{}", writer)
5276 }
5277}
5278
5279#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
5283pub enum TransactionKey {
5284 Digest(TransactionDigest),
5285 RandomnessRound(EpochId, RandomnessRound),
5286 AccumulatorSettlement(EpochId, u64 ),
5287 ConsensusCommitPrologue(EpochId, u64 , u32 ),
5288}
5289
5290impl TransactionKey {
5291 pub fn unwrap_digest(&self) -> &TransactionDigest {
5292 match self {
5293 TransactionKey::Digest(d) => d,
5294 _ => panic!("called unwrap_digest on a non-Digest TransactionKey: {self:?}"),
5295 }
5296 }
5297
5298 pub fn as_digest(&self) -> Option<&TransactionDigest> {
5299 match self {
5300 TransactionKey::Digest(d) => Some(d),
5301 _ => None,
5302 }
5303 }
5304}