Skip to main content

iota_types/
transaction.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// Modifications Copyright (c) 2024 IOTA Stiftung
4// SPDX-License-Identifier: Apache-2.0
5
6// zkLogin/AuthenticatorStateUpdate types are kept (deprecated) for
7// serialization compatibility only.
8
9use std::{
10    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
11    fmt::{Debug, Display, Formatter, Write},
12    hash::Hash,
13    iter::{self},
14};
15
16use anyhow::bail;
17use fastcrypto::{encoding::Base64, hash::HashFunction};
18use iota_protocol_config::ProtocolConfig;
19use iota_sdk_types::{
20    AccountClaimKind, Address, Argument, CanceledTransaction, CertificateDigest, Command,
21    ConsensusCommitDigest, ConsensusCommitPrologueV1, ConsensusDeterminedVersionAssignments,
22    EndOfEpochTransactionKind, Event, GasPayment, GenesisObject, GenesisTransaction, Identifier,
23    Input, MakeMoveVector, MergeCoins, MoveAuthenticator, MoveCall, MoveStruct, ObjectDigest,
24    ObjectId, ObjectReference, Owner, ProgrammableTransaction, Publish, RandomnessRound,
25    RandomnessStateUpdate, SenderSignedTransaction, SharedObjectReference, SignatureScheme,
26    SplitCoins, Transaction, TransactionDenyRulesUpdate, TransactionDigest, TransactionExpiration,
27    TransactionKind, TransactionV1, TransferObjects, TypeTag, Upgrade, UserSignature, Version,
28    crypto::{Intent, IntentMessage, IntentScope, SimpleSignature},
29};
30use itertools::Either;
31use nonempty::{NonEmpty, nonempty};
32use serde::{Deserialize, Serialize};
33use tap::Pipe;
34use tracing::{instrument, trace};
35
36use super::{base_types::*, error::*};
37use crate::{
38    IOTA_CLOCK_OBJECT_SHARED_VERSION, IOTA_SYSTEM_STATE_OBJECT_SHARED_VERSION,
39    committee::{Committee, EpochId},
40    crypto::{
41        AuthoritySignInfo, AuthoritySignInfoTrait, AuthoritySignature,
42        AuthorityStrongQuorumSignInfo, DefaultHash, EmptySignInfo, Signer, zero_ed25519_signature,
43    },
44    execution::SharedInput,
45    message_envelope::{Envelope, Message, TrustedEnvelope, VerifiedEnvelope},
46    messages_checkpoint::CheckpointTimestamp,
47    move_authenticator::MoveAuthenticatorExt,
48    move_public_key::MovePublicKey,
49    object::Object,
50    programmable_transaction_builder::ProgrammableTransactionBuilder,
51    signature::VerifyParams,
52    signature_verification::verify_sender_signed_data_message_signatures,
53};
54
55pub const TEST_ONLY_GAS_UNIT_FOR_TRANSFER: u64 = 10_000;
56pub const TEST_ONLY_GAS_UNIT_FOR_OBJECT_BASICS: u64 = 50_000;
57pub const TEST_ONLY_GAS_UNIT_FOR_PUBLISH: u64 = 50_000;
58pub const TEST_ONLY_GAS_UNIT_FOR_STAKING: u64 = 50_000;
59pub const TEST_ONLY_GAS_UNIT_FOR_GENERIC: u64 = 50_000;
60pub const TEST_ONLY_GAS_UNIT_FOR_SPLIT_COIN: u64 = 10_000;
61// For some transactions we may either perform heavy operations or touch
62// objects that are storage expensive. That may happen (and often is the case)
63// because the object touched are set up in genesis and carry no storage cost
64// (and thus rebate) on first usage.
65pub const TEST_ONLY_GAS_UNIT_FOR_HEAVY_COMPUTATION_STORAGE: u64 = 5_000_000;
66
67pub const GAS_PRICE_FOR_SYSTEM_TX: u64 = 1;
68
69pub const DEFAULT_VALIDATOR_GAS_PRICE: u64 = 1000;
70
71/// The most inputs a programmable transaction may declare.
72pub const MAX_PROGRAMMABLE_TX_INPUTS: usize = u16::MAX as usize;
73
74const BLOCKED_MOVE_FUNCTIONS: [(ObjectId, &str, &str); 0] = [];
75
76#[cfg(test)]
77#[path = "unit_tests/messages_tests.rs"]
78mod messages_tests;
79
80#[cfg(test)]
81#[path = "unit_tests/claim_account_validity_tests.rs"]
82mod claim_account_validity_tests;
83
84/// Type alias for the SDK's `Input` type, used as transaction call arguments.
85pub type CallArg = Input;
86
87/// Rejects a version that a transaction names for an input object when it is
88/// at or above `Version::MAX_VALID_EXCL`, the range assigned to the objects of
89/// canceled transactions, or right below it. The version of a transaction's
90/// outputs is one more than its largest input version, and version assignment
91/// halts the node when that result is not a valid version, so both are refused
92/// from the transaction bytes, before any object is loaded.
93fn input_object_version_validity_check(version: Version) -> UserInputResult {
94    fp_ensure!(
95        version.next().is_ok_and(|next| next.is_valid()),
96        UserInputError::InvalidSequenceNumber
97    );
98
99    Ok(())
100}
101
102/// Rejects an identifier that move-core rejects. The SDK `Identifier` also
103/// accepts `<SELF>`, which no module or type can be named.
104pub fn move_core_identifier_validity_check(identifier: &Identifier) -> UserInputResult {
105    fp_ensure!(
106        move_core_types::identifier::Identifier::is_valid(identifier.as_str()),
107        UserInputError::InvalidIdentifier {
108            error: identifier.to_string()
109        }
110    );
111    Ok(())
112}
113
114/// Rejects an identifier that move-core rejects in the module or name of any
115/// struct type in `type_tags`, nested type parameters included.
116pub fn type_tags_identifiers_validity_check<'a>(
117    type_tags: impl IntoIterator<Item = &'a TypeTag>,
118) -> UserInputResult {
119    let mut stack: Vec<&TypeTag> = type_tags.into_iter().collect();
120    while let Some(type_tag) = stack.pop() {
121        match type_tag {
122            TypeTag::Vector(inner) => stack.push(inner.as_ref()),
123            TypeTag::Struct(s) => {
124                move_core_identifier_validity_check(s.module())?;
125                move_core_identifier_validity_check(s.name())?;
126                stack.extend(s.type_params());
127            }
128            TypeTag::Bool
129            | TypeTag::U8
130            | TypeTag::U16
131            | TypeTag::U32
132            | TypeTag::U64
133            | TypeTag::U128
134            | TypeTag::U256
135            | TypeTag::Address
136            | TypeTag::Signer => {}
137        }
138    }
139    Ok(())
140}
141
142/// Rejects an identifier that move-core rejects in a command: the module and
143/// function names and the type arguments of a Move call, or the element type
144/// of a `MakeMoveVector`.
145fn command_identifiers_validity_check(command: &Command) -> UserInputResult {
146    match command {
147        Command::MoveCall(call) => {
148            move_core_identifier_validity_check(&call.module)?;
149            move_core_identifier_validity_check(&call.function)?;
150            type_tags_identifiers_validity_check(&call.type_arguments)
151        }
152        Command::MakeMoveVector(MakeMoveVector {
153            type_tag: Some(type_tag),
154            ..
155        }) => type_tags_identifiers_validity_check([type_tag]),
156        Command::MakeMoveVector(MakeMoveVector { type_tag: None, .. })
157        | Command::TransferObjects(_)
158        | Command::SplitCoins(_)
159        | Command::MergeCoins(_)
160        | Command::Publish(_)
161        | Command::Upgrade(_) => Ok(()),
162        _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
163    }
164}
165
166/// Rejects an identifier that move-core rejects in the type arguments of a
167/// Move authenticator.
168pub(crate) fn move_authenticator_identifiers_validity_check(
169    authenticator: &impl MoveAuthenticatorExt,
170) -> UserInputResult {
171    type_tags_identifiers_validity_check(authenticator.type_args())
172}
173
174pub fn type_tag_validity_check(
175    tag: &TypeTag,
176    config: &ProtocolConfig,
177    starting_count: &mut usize,
178) -> UserInputResult<()> {
179    let mut stack = vec![(tag, 1)];
180    while let Some((tag, depth)) = stack.pop() {
181        *starting_count += 1;
182        fp_ensure!(
183            *starting_count < config.max_type_arguments() as usize,
184            UserInputError::SizeLimitExceeded {
185                limit: "maximum type arguments in a call transaction".to_string(),
186                value: config.max_type_arguments().to_string()
187            }
188        );
189        fp_ensure!(
190            depth < config.max_type_argument_depth(),
191            UserInputError::SizeLimitExceeded {
192                limit: "maximum type argument depth in a call transaction".to_string(),
193                value: config.max_type_argument_depth().to_string()
194            }
195        );
196        match tag {
197            TypeTag::Bool
198            | TypeTag::U8
199            | TypeTag::U64
200            | TypeTag::U128
201            | TypeTag::Address
202            | TypeTag::Signer
203            | TypeTag::U16
204            | TypeTag::U32
205            | TypeTag::U256 => (),
206            TypeTag::Vector(t) => {
207                stack.push((t, depth + 1));
208            }
209            TypeTag::Struct(s) => {
210                let next_depth = depth + 1;
211                if config.validate_identifier_inputs() {
212                    fp_ensure!(
213                        Identifier::is_valid(s.module().as_str()),
214                        UserInputError::InvalidIdentifier {
215                            error: s.module().as_str().to_owned()
216                        }
217                    );
218                    fp_ensure!(
219                        Identifier::is_valid(s.name().as_str()),
220                        UserInputError::InvalidIdentifier {
221                            error: s.name().as_str().to_owned()
222                        }
223                    );
224                }
225                stack.extend(s.type_params().iter().map(|t| (t, next_depth)));
226            }
227        }
228    }
229    Ok(())
230}
231
232/// Extension trait for [`EndOfEpochTransactionKind`] that adds methods
233/// requiring iota-types-specific types (like [`InputObjectKind`] and
234/// [`ProtocolConfig`]) that are not available in the SDK.
235pub(crate) trait EndOfEpochTransactionKindExt {
236    fn input_objects(&self) -> Vec<InputObjectKind>;
237    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
238}
239
240impl EndOfEpochTransactionKindExt for EndOfEpochTransactionKind {
241    fn input_objects(&self) -> Vec<InputObjectKind> {
242        match self {
243            Self::ChangeEpoch(_)
244            | Self::ChangeEpochV2(_)
245            | Self::ChangeEpochV3(_)
246            | Self::ChangeEpochV4(_) => {
247                vec![InputObjectKind::SharedMoveObject {
248                    id: ObjectId::SYSTEM_STATE,
249                    initial_shared_version: IOTA_SYSTEM_STATE_OBJECT_SHARED_VERSION,
250                    mutable: true,
251                }]
252            }
253            // Creates the TransactionDenyRules object; there is no input to
254            // reference yet.
255            Self::TransactionDenyRulesCreate => vec![],
256            _ => unimplemented!(
257                "a new EndOfEpochTransactionKind enum variant was added and needs to be handled"
258            ),
259        }
260    }
261
262    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
263        match self {
264            Self::ChangeEpoch(_) => {
265                if config.protocol_defined_base_fee() {
266                    return Err(UserInputError::Unsupported(
267                        "protocol defined base fee not supported".to_string(),
268                    ));
269                }
270                if config.select_committee_from_eligible_validators() {
271                    return Err(UserInputError::Unsupported(
272                        "selecting committee only among validators supporting the protocol version not supported".to_string(),
273                    ));
274                }
275                if config.pass_validator_scores_to_advance_epoch() {
276                    return Err(UserInputError::Unsupported(
277                        "passing of validator scores not supported".to_string(),
278                    ));
279                }
280                if config.adjust_rewards_by_score() {
281                    return Err(UserInputError::Unsupported(
282                        "adjusting rewards by score not supported".to_string(),
283                    ));
284                }
285            }
286            Self::ChangeEpochV2(_) => {
287                if !config.protocol_defined_base_fee() {
288                    return Err(UserInputError::Unsupported(
289                        "protocol defined base fee required".to_string(),
290                    ));
291                }
292                if config.select_committee_from_eligible_validators() {
293                    return Err(UserInputError::Unsupported(
294                        "selecting committee only among validators supporting the protocol version not supported".to_string(),
295                    ));
296                }
297                if config.pass_validator_scores_to_advance_epoch() {
298                    return Err(UserInputError::Unsupported(
299                        "passing of validator scores not supported".to_string(),
300                    ));
301                }
302                if config.adjust_rewards_by_score() {
303                    return Err(UserInputError::Unsupported(
304                        "adjusting rewards by score not supported".to_string(),
305                    ));
306                }
307            }
308            Self::ChangeEpochV3(_) => {
309                if !config.protocol_defined_base_fee() {
310                    return Err(UserInputError::Unsupported(
311                        "protocol defined base fee required".to_string(),
312                    ));
313                }
314                if !config.select_committee_from_eligible_validators() {
315                    return Err(UserInputError::Unsupported(
316                        "selecting committee only among validators supporting the protocol version required".to_string(),
317                    ));
318                }
319                if config.pass_validator_scores_to_advance_epoch() {
320                    return Err(UserInputError::Unsupported(
321                        "passing of validator scores not supported".to_string(),
322                    ));
323                }
324                if config.adjust_rewards_by_score() {
325                    return Err(UserInputError::Unsupported(
326                        "adjusting rewards by score not supported".to_string(),
327                    ));
328                }
329            }
330            Self::ChangeEpochV4(_) => {
331                if !config.protocol_defined_base_fee() {
332                    return Err(UserInputError::Unsupported(
333                        "protocol defined base fee required".to_string(),
334                    ));
335                }
336                if !config.select_committee_from_eligible_validators() {
337                    return Err(UserInputError::Unsupported(
338                        "selecting committee only among validators supporting the protocol version required".to_string(),
339                    ));
340                }
341                if !config.pass_validator_scores_to_advance_epoch() {
342                    return Err(UserInputError::Unsupported(
343                        "passing of validator scores required".to_string(),
344                    ));
345                }
346            }
347            Self::TransactionDenyRulesCreate => {
348                if !config.enable_pcool_flow() {
349                    return Err(UserInputError::Unsupported(
350                        "on-chain deny rule governance not supported at current protocol version"
351                            .to_string(),
352                    ));
353                }
354            }
355            _ => unimplemented!(
356                "a new EndOfEpochTransactionKind enum variant was added and needs to be handled"
357            ),
358        }
359        Ok(())
360    }
361}
362
363mod call_arg_ext {
364    pub trait Sealed {}
365    impl Sealed for super::CallArg {}
366}
367
368/// Extension trait for [`CallArg`] providing helper methods.
369pub trait CallArgExt: Sized + call_arg_ext::Sealed {
370    /// Returns the input object kind for this argument, excluding receiving
371    /// objects.
372    fn input_object_kind(&self) -> Option<InputObjectKind>;
373
374    /// Validity check for this argument against the given protocol config.
375    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
376}
377
378impl CallArgExt for CallArg {
379    fn input_object_kind(&self) -> Option<InputObjectKind> {
380        match self {
381            CallArg::ImmutableOrOwned(object_ref) => {
382                Some(InputObjectKind::ImmOrOwnedMoveObject(*object_ref))
383            }
384            CallArg::Shared(SharedObjectReference {
385                object_id,
386                initial_shared_version,
387                mutable,
388            }) => Some(InputObjectKind::SharedMoveObject {
389                id: *object_id,
390                initial_shared_version: *initial_shared_version,
391                mutable: *mutable,
392            }),
393            CallArg::Pure(_) | CallArg::Receiving(_) | CallArg::TransactionDependency(_) => None,
394            _ => unimplemented!("a new CallArg enum variant was added and needs to be handled"),
395        }
396    }
397
398    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
399        match self {
400            CallArg::TransactionDependency(_) => {
401                fp_ensure!(
402                    config.enable_transaction_dependencies(),
403                    UserInputError::Unsupported(
404                        "transaction dependency inputs are not enabled".to_string()
405                    )
406                );
407            }
408            CallArg::Pure(bytes) => {
409                fp_ensure!(
410                    bytes.len() < config.max_pure_argument_size() as usize,
411                    UserInputError::SizeLimitExceeded {
412                        limit: "maximum pure argument size".to_string(),
413                        value: config.max_pure_argument_size().to_string()
414                    }
415                );
416            }
417            CallArg::ImmutableOrOwned(ObjectReference { version, .. })
418            | CallArg::Receiving(ObjectReference { version, .. })
419            | CallArg::Shared(SharedObjectReference {
420                initial_shared_version: version,
421                ..
422            }) => {
423                if config.validate_input_object_versions() {
424                    input_object_version_validity_check(*version)?;
425                }
426            }
427            _ => unimplemented!("a new CallArg enum variant was added and needs to be handled"),
428        }
429        Ok(())
430    }
431}
432
433// Add package IDs, `ObjectId`, for types defined in modules.
434pub(crate) fn add_type_tag_packages(packages: &mut BTreeSet<ObjectId>, type_argument: &TypeTag) {
435    let mut stack = vec![type_argument];
436    while let Some(cur) = stack.pop() {
437        match cur {
438            TypeTag::U8
439            | TypeTag::U16
440            | TypeTag::U32
441            | TypeTag::U64
442            | TypeTag::U128
443            | TypeTag::U256
444            | TypeTag::Bool
445            | TypeTag::Address
446            | TypeTag::Signer => (),
447            TypeTag::Vector(inner) => stack.push(inner),
448            TypeTag::Struct(struct_tag) => {
449                packages.insert(ObjectId::new(struct_tag.address().into_bytes()));
450                stack.extend(struct_tag.type_params().iter())
451            }
452        }
453    }
454}
455
456mod move_call_ext {
457    pub trait Sealed {}
458    impl Sealed for super::MoveCall {}
459}
460
461pub trait MoveCallExt: Sized + move_call_ext::Sealed {
462    fn input_objects(&self) -> Vec<InputObjectKind>;
463    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
464    fn is_input_arg_used(&self, arg: usize) -> bool;
465}
466
467impl MoveCallExt for MoveCall {
468    fn input_objects(&self) -> Vec<InputObjectKind> {
469        let mut packages = BTreeSet::from([self.package]);
470        for type_argument in &self.type_arguments {
471            add_type_tag_packages(&mut packages, type_argument);
472        }
473        packages
474            .into_iter()
475            .map(InputObjectKind::MovePackage)
476            .collect()
477    }
478
479    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
480        let is_blocked = BLOCKED_MOVE_FUNCTIONS.contains(&(
481            self.package,
482            self.module.as_str(),
483            self.function.as_str(),
484        ));
485        fp_ensure!(!is_blocked, UserInputError::BlockedMoveFunction);
486        let mut type_arguments_count = 0;
487        for tag in &self.type_arguments {
488            type_tag_validity_check(tag, config, &mut type_arguments_count)?;
489        }
490        fp_ensure!(
491            self.arguments.len() < config.max_arguments() as usize,
492            UserInputError::SizeLimitExceeded {
493                limit: "maximum arguments in a move call".to_string(),
494                value: config.max_arguments().to_string()
495            }
496        );
497        if config.validate_identifier_inputs() {
498            fp_ensure!(
499                Identifier::is_valid(&self.module),
500                UserInputError::InvalidIdentifier {
501                    error: self.module.to_string()
502                }
503            );
504            fp_ensure!(
505                Identifier::is_valid(&self.function),
506                UserInputError::InvalidIdentifier {
507                    error: self.function.to_string()
508                }
509            );
510        }
511        Ok(())
512    }
513
514    fn is_input_arg_used(&self, arg: usize) -> bool {
515        self.arguments
516            .iter()
517            .any(|a| matches!(a, Argument::Input(inp) if usize::from(*inp) == arg))
518    }
519}
520
521mod command_ext {
522    pub trait Sealed {}
523    impl Sealed for super::Command {}
524}
525
526pub trait CommandExt: Sized + command_ext::Sealed {
527    fn input_objects(&self) -> Vec<InputObjectKind>;
528    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
529    fn non_system_packages_to_be_published(&self) -> Option<&Vec<Vec<u8>>>;
530    fn is_input_arg_used(&self, input_arg: usize) -> bool;
531}
532
533impl CommandExt for Command {
534    fn input_objects(&self) -> Vec<InputObjectKind> {
535        match self {
536            Command::MoveCall(cmd) => cmd.input_objects(),
537            Command::Upgrade(cmd) => cmd
538                .dependencies
539                .iter()
540                .map(|id| InputObjectKind::MovePackage(*id))
541                .chain(Some(InputObjectKind::MovePackage(cmd.package)))
542                .collect(),
543            Command::Publish(cmd) => cmd
544                .dependencies
545                .iter()
546                .map(|id| InputObjectKind::MovePackage(*id))
547                .collect(),
548            Command::MakeMoveVector(MakeMoveVector {
549                type_tag: Some(t), ..
550            }) => {
551                let mut packages = BTreeSet::new();
552                add_type_tag_packages(&mut packages, t);
553                packages
554                    .into_iter()
555                    .map(InputObjectKind::MovePackage)
556                    .collect()
557            }
558            Command::MakeMoveVector(MakeMoveVector { type_tag: None, .. })
559            | Command::TransferObjects(_)
560            | Command::SplitCoins(_)
561            | Command::MergeCoins(_) => vec![],
562            _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
563        }
564    }
565
566    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
567        match self {
568            Command::MoveCall(call) => call.validity_check(config)?,
569            Command::TransferObjects(TransferObjects { objects: args, .. })
570            | Command::MergeCoins(MergeCoins {
571                coins_to_merge: args,
572                ..
573            })
574            | Command::SplitCoins(SplitCoins { amounts: args, .. }) => {
575                fp_ensure!(!args.is_empty(), UserInputError::EmptyCommandInput);
576                fp_ensure!(
577                    args.len() < config.max_arguments() as usize,
578                    UserInputError::SizeLimitExceeded {
579                        limit: "maximum arguments in a programmable transaction command"
580                            .to_string(),
581                        value: config.max_arguments().to_string()
582                    }
583                );
584            }
585            Command::MakeMoveVector(MakeMoveVector {
586                type_tag: ty_opt,
587                elements: args,
588            }) => {
589                // ty_opt.is_none() ==> !args.is_empty()
590                fp_ensure!(
591                    ty_opt.is_some() || !args.is_empty(),
592                    UserInputError::EmptyCommandInput
593                );
594                if let Some(ty) = ty_opt {
595                    let mut type_arguments_count = 0;
596                    type_tag_validity_check(ty, config, &mut type_arguments_count)?;
597                }
598                fp_ensure!(
599                    args.len() < config.max_arguments() as usize,
600                    UserInputError::SizeLimitExceeded {
601                        limit: "maximum arguments in a programmable transaction command"
602                            .to_string(),
603                        value: config.max_arguments().to_string()
604                    }
605                );
606            }
607            Command::Publish(Publish {
608                modules,
609                dependencies,
610            })
611            | Command::Upgrade(Upgrade {
612                modules,
613                dependencies,
614                ..
615            }) => {
616                fp_ensure!(!modules.is_empty(), UserInputError::EmptyCommandInput);
617                fp_ensure!(
618                    modules.len() < config.max_modules_in_publish() as usize,
619                    UserInputError::SizeLimitExceeded {
620                        limit: "maximum modules in a programmable transaction upgrade command"
621                            .to_string(),
622                        value: config.max_modules_in_publish().to_string()
623                    }
624                );
625                if let Some(max_package_dependencies) = config.max_package_dependencies_as_option()
626                {
627                    fp_ensure!(
628                        dependencies.len() < max_package_dependencies as usize,
629                        UserInputError::SizeLimitExceeded {
630                            limit: "maximum package dependencies".to_string(),
631                            value: max_package_dependencies.to_string()
632                        }
633                    );
634                };
635            }
636            _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
637        };
638        if config.disallow_self_identifier_in_transactions() {
639            command_identifiers_validity_check(self)?;
640        }
641
642        Ok(())
643    }
644
645    fn non_system_packages_to_be_published(&self) -> Option<&Vec<Vec<u8>>> {
646        match self {
647            Command::Publish(cmd) => Some(&cmd.modules),
648            Command::Upgrade(cmd) => Some(&cmd.modules),
649            Command::MoveCall(_)
650            | Command::TransferObjects(_)
651            | Command::SplitCoins(_)
652            | Command::MergeCoins(_)
653            | Command::MakeMoveVector(_) => None,
654            _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
655        }
656    }
657
658    fn is_input_arg_used(&self, input_arg: usize) -> bool {
659        match self {
660            Command::MoveCall(c) => c.is_input_arg_used(input_arg),
661            Command::TransferObjects(TransferObjects {
662                objects: args,
663                address: arg,
664            })
665            | Command::MergeCoins(MergeCoins {
666                coins_to_merge: args,
667                coin: arg,
668            })
669            | Command::SplitCoins(SplitCoins {
670                amounts: args,
671                coin: arg,
672            }) => args.iter().chain(iter::once(arg)).any(
673                |arg| matches!(arg, Argument::Input(input) if usize::from(*input) == input_arg),
674            ),
675            Command::MakeMoveVector(MakeMoveVector { elements, .. }) => elements.iter().any(
676                |arg| matches!(arg, Argument::Input(input) if usize::from(*input) == input_arg),
677            ),
678            Command::Upgrade(Upgrade { ticket, .. }) => {
679                matches!(ticket, Argument::Input(input) if usize::from(*input) == input_arg)
680            }
681            Command::Publish(_) => false,
682            _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
683        }
684    }
685}
686
687/// Iterates over arguments in command-argument order.
688fn command_arguments(command: &Command) -> Box<dyn Iterator<Item = &Argument> + '_> {
689    match command {
690        Command::MoveCall(c) => Box::new(c.arguments.iter()),
691        Command::TransferObjects(TransferObjects { objects, address }) => {
692            Box::new(objects.iter().chain(iter::once(address)))
693        }
694        Command::SplitCoins(SplitCoins { coin, amounts }) => {
695            Box::new(iter::once(coin).chain(amounts))
696        }
697        Command::MergeCoins(MergeCoins {
698            coin,
699            coins_to_merge,
700        }) => Box::new(iter::once(coin).chain(coins_to_merge)),
701        Command::MakeMoveVector(MakeMoveVector { elements, .. }) => Box::new(elements.iter()),
702        Command::Upgrade(Upgrade { ticket, .. }) => Box::new(iter::once(ticket)),
703        Command::Publish(_) => Box::new(iter::empty()),
704        _ => unimplemented!("a new Command enum variant was added and needs to be handled"),
705    }
706}
707
708mod programmable_transaction_ext {
709    pub trait Sealed {}
710    impl Sealed for super::ProgrammableTransaction {}
711}
712
713pub trait ProgrammableTransactionExt: Sized + programmable_transaction_ext::Sealed {
714    fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>>;
715    fn receiving_objects(&self) -> Vec<ObjectReference>;
716    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
717    fn validate_argument_indices(&self) -> UserInputResult;
718    /// The index and digest of the first transaction dependency input, if any.
719    fn dependency_input(&self) -> Option<(usize, TransactionDigest)>;
720    /// The digest named by the transaction dependency input, if any.
721    fn transaction_dependency(&self) -> Option<TransactionDigest>;
722    /// Checks that at most one input is a transaction dependency and that no
723    /// command uses it.
724    fn validate_transaction_dependency_inputs(&self) -> UserInputResult;
725    fn shared_input_objects(&self) -> impl Iterator<Item = SharedObjectReference>;
726    fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)>;
727    fn non_system_packages_to_be_published(&self) -> impl Iterator<Item = &Vec<Vec<u8>>>;
728}
729
730impl ProgrammableTransactionExt for ProgrammableTransaction {
731    fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
732        let ProgrammableTransaction { inputs, commands } = self;
733        let input_arg_objects = inputs
734            .iter()
735            .filter_map(|arg| arg.input_object_kind())
736            .collect::<Vec<_>>();
737        // all objects, not just mutable, must be unique
738        let mut used = HashSet::new();
739        if !input_arg_objects.iter().all(|o| used.insert(o.object_id())) {
740            return Err(UserInputError::DuplicateObjectRefInput);
741        }
742        // do not duplicate packages referred to in commands
743        let command_input_objects: BTreeSet<InputObjectKind> = commands
744            .iter()
745            .flat_map(|command| command.input_objects())
746            .collect();
747        Ok(input_arg_objects
748            .into_iter()
749            .chain(command_input_objects)
750            .collect())
751    }
752
753    fn receiving_objects(&self) -> Vec<ObjectReference> {
754        let ProgrammableTransaction { inputs, .. } = self;
755        inputs
756            .iter()
757            .filter_map(|arg| arg.as_opt_receiving().copied())
758            .collect()
759    }
760
761    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
762        let ProgrammableTransaction { inputs, commands } = self;
763        fp_ensure!(
764            commands.len() < config.max_programmable_tx_commands() as usize,
765            UserInputError::SizeLimitExceeded {
766                limit: "maximum commands in a programmable transaction".to_string(),
767                value: config.max_programmable_tx_commands().to_string()
768            }
769        );
770        // `max_input_objects` below does not count pure inputs, so it does not
771        // bound the list.
772        fp_ensure!(
773            inputs.len() <= MAX_PROGRAMMABLE_TX_INPUTS,
774            UserInputError::SizeLimitExceeded {
775                limit: "maximum inputs in a programmable transaction".to_string(),
776                value: MAX_PROGRAMMABLE_TX_INPUTS.to_string(),
777            }
778        );
779        let total_inputs = self.input_objects()?.len() + self.receiving_objects().len();
780        fp_ensure!(
781            total_inputs <= config.max_input_objects() as usize,
782            UserInputError::SizeLimitExceeded {
783                limit: "maximum input + receiving objects in a transaction".to_string(),
784                value: config.max_input_objects().to_string()
785            }
786        );
787        for input in inputs {
788            input.validity_check(config)?
789        }
790        self.validate_transaction_dependency_inputs()?;
791        if let Some(max_publish_commands) = config.max_publish_or_upgrade_per_ptb_as_option() {
792            let publish_count = commands
793                .iter()
794                .filter(|c| c.is_publish() || c.is_upgrade())
795                .count() as u64;
796            fp_ensure!(
797                publish_count <= max_publish_commands,
798                UserInputError::MaxPublishCountExceeded {
799                    max_publish_commands,
800                    publish_count,
801                }
802            );
803        }
804        for command in commands {
805            command.validity_check(config)?;
806        }
807        if config.validate_ptb_argument_indices() {
808            self.validate_argument_indices()?;
809        }
810
811        // If randomness is used, it must be enabled by protocol config.
812        // A command that uses Random can only be followed by TransferObjects or
813        // MergeCoins.
814        if let Some(random_index) = inputs.iter().position(|obj| {
815            matches!(obj, CallArg::Shared(SharedObjectReference { object_id, .. }) if *object_id == ObjectId::RANDOMNESS_STATE)
816        }) {
817            let mut used_random_object = false;
818            for command in commands {
819                if !used_random_object {
820                    used_random_object = command.is_input_arg_used(random_index);
821                } else {
822                    fp_ensure!(
823                        command.is_transfer_objects() || command.is_merge_coins(),
824                        UserInputError::PostRandomCommandRestrictions
825                    );
826                }
827            }
828        }
829
830        Ok(())
831    }
832
833    fn dependency_input(&self) -> Option<(usize, TransactionDigest)> {
834        self.inputs
835            .iter()
836            .enumerate()
837            .find_map(|(index, input)| match input {
838                CallArg::TransactionDependency(digest) => Some((index, *digest)),
839                _ => None,
840            })
841    }
842
843    fn transaction_dependency(&self) -> Option<TransactionDigest> {
844        self.dependency_input().map(|(_, digest)| digest)
845    }
846
847    fn validate_transaction_dependency_inputs(&self) -> UserInputResult {
848        let dep_index = match self.dependency_input() {
849            Some((index, _)) => index,
850            None => return Ok(()),
851        };
852        // At most one dependency input.
853        fp_ensure!(
854            self.inputs[dep_index + 1..]
855                .iter()
856                .all(|input| !matches!(input, CallArg::TransactionDependency(_))),
857            UserInputError::SizeLimitExceeded {
858                limit: "maximum transaction dependency inputs in a programmable transaction"
859                    .to_string(),
860                value: "1".to_string(),
861            }
862        );
863        // No command may use it.
864        for (command_idx, command) in self.commands.iter().enumerate() {
865            for (argument_idx, argument) in command_arguments(command).enumerate() {
866                if let Argument::Input(index) = argument {
867                    if *index as usize == dep_index {
868                        return Err(UserInputError::TransactionDependencyInputUsed {
869                            command_idx,
870                            argument_idx,
871                        });
872                    }
873                }
874            }
875        }
876        Ok(())
877    }
878
879    fn validate_argument_indices(&self) -> UserInputResult {
880        for (command_idx, command) in self.commands.iter().enumerate() {
881            for (argument_idx, argument) in command_arguments(command).enumerate() {
882                let index = match argument {
883                    Argument::Input(index) if *index as usize >= self.inputs.len() => *index,
884                    Argument::Result(index) | Argument::NestedResult(index, _)
885                        if *index as usize >= command_idx =>
886                    {
887                        *index
888                    }
889                    Argument::Gas
890                    | Argument::Input(_)
891                    | Argument::Result(_)
892                    | Argument::NestedResult(_, _) => continue,
893                    _ => unimplemented!(
894                        "a new Argument enum variant was added and needs to be handled"
895                    ),
896                };
897                return Err(UserInputError::InvalidArgumentIndex {
898                    command_idx,
899                    argument_idx,
900                    index,
901                });
902            }
903        }
904        Ok(())
905    }
906
907    fn shared_input_objects(&self) -> impl Iterator<Item = SharedObjectReference> {
908        self.inputs.iter().filter_map(|arg| match arg {
909            CallArg::Shared(shared) => Some(*shared),
910            CallArg::Pure(_)
911            | CallArg::Receiving(_)
912            | CallArg::ImmutableOrOwned(_)
913            | CallArg::TransactionDependency(_) => None,
914            _ => unimplemented!("a new CallArg enum variant was added and needs to be handled"),
915        })
916    }
917
918    fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)> {
919        self.commands
920            .iter()
921            .filter_map(|command| match command {
922                Command::MoveCall(m) => Some((&m.package, m.module.as_str(), m.function.as_str())),
923                _ => None,
924            })
925            .collect()
926    }
927
928    fn non_system_packages_to_be_published(&self) -> impl Iterator<Item = &Vec<Vec<u8>>> {
929        self.commands
930            .iter()
931            .filter_map(|q| q.non_system_packages_to_be_published())
932    }
933}
934
935/// Merges `other` into `this` shared input object.
936/// If there is a conflict in mutability, the resulting object will be
937/// mutable. Errors if the id or initial_shared_version do not match.
938fn left_union_shared_input_objects(
939    this: &mut SharedObjectReference,
940    other: &SharedObjectReference,
941) -> UserInputResult<()> {
942    fp_ensure!(
943        this.object_id == other.object_id,
944        UserInputError::SharedObjectIdMismatch
945    );
946    fp_ensure!(
947        this.initial_shared_version == other.initial_shared_version,
948        UserInputError::SharedObjectStartingVersionMismatch
949    );
950
951    if !this.mutable && other.mutable {
952        this.mutable = other.mutable;
953    }
954
955    Ok(())
956}
957
958mod transaction_kind_ext {
959    pub trait Sealed {}
960    impl Sealed for super::TransactionKind {}
961}
962
963pub trait TransactionKindExt: Sized + transaction_kind_ext::Sealed {
964    /// If this is an advance epoch transaction, returns (total gas charged,
965    /// total gas rebated). TODO: We should use `GasCostSummary` directly in
966    /// `ChangeEpoch` struct, and return that directly.
967    fn get_advance_epoch_tx_gas_summary(&self) -> Option<(u64, u64)>;
968    /// Returns `true` if the transaction contains at least one shared object.
969    fn contains_shared_object(&self) -> bool;
970    /// Returns an iterator of all shared input objects used by this
971    /// transaction.
972    fn shared_input_objects(&self) -> impl Iterator<Item = SharedObjectReference> + '_;
973    /// Returns the move calls made by this transaction as a list of
974    /// (package, module, function) tuples.
975    fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)>;
976    /// Returns the objects received by this transaction.
977    fn receiving_objects(&self) -> Vec<ObjectReference>;
978    /// Return the metadata of each of the input objects for the transaction.
979    /// For a Move object, we attach the object reference;
980    /// for a Move package, we provide the object id only since they never
981    /// change on chain. TODO: use an iterator over references here instead
982    /// of a `Vec` to avoid allocations.
983    fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>>;
984    /// Validates the transaction against the given protocol config.
985    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
986    /// Returns an iterator over the commands in this transaction.
987    fn iter_commands(&self) -> impl Iterator<Item = &Command>;
988    /// Returns a human-readable name for this transaction kind.
989    fn name(&self) -> &'static str;
990}
991
992impl TransactionKindExt for TransactionKind {
993    fn get_advance_epoch_tx_gas_summary(&self) -> Option<(u64, u64)> {
994        match self {
995            Self::EndOfEpoch(txns) => {
996                match txns.last().expect("at least one end-of-epoch txn required") {
997                    EndOfEpochTransactionKind::ChangeEpoch(e) => {
998                        Some((e.computation_charge + e.storage_charge, e.storage_rebate))
999                    }
1000                    EndOfEpochTransactionKind::ChangeEpochV2(e) => {
1001                        Some((e.computation_charge + e.storage_charge, e.storage_rebate))
1002                    }
1003                    EndOfEpochTransactionKind::ChangeEpochV3(e) => {
1004                        Some((e.computation_charge + e.storage_charge, e.storage_rebate))
1005                    }
1006                    EndOfEpochTransactionKind::ChangeEpochV4(e) => {
1007                        Some((e.computation_charge + e.storage_charge, e.storage_rebate))
1008                    }
1009                    // Never the last end-of-epoch kind; a change-epoch kind
1010                    // always follows it.
1011                    EndOfEpochTransactionKind::TransactionDenyRulesCreate => None,
1012                    _ => unimplemented!(
1013                        "a new EndOfEpochTransactionKind enum variant was added and needs to be handled"
1014                    ),
1015                }
1016            }
1017            _ => None,
1018        }
1019    }
1020
1021    fn contains_shared_object(&self) -> bool {
1022        self.shared_input_objects().next().is_some()
1023    }
1024
1025    fn shared_input_objects(&self) -> impl Iterator<Item = SharedObjectReference> + '_ {
1026        match &self {
1027            Self::ConsensusCommitPrologueV1(_) => Either::Left(Either::Left(iter::once(
1028                SharedObjectReference::new(ObjectId::CLOCK, IOTA_CLOCK_OBJECT_SHARED_VERSION, true),
1029            ))),
1030            #[allow(deprecated)]
1031            Self::AuthenticatorStateUpdateV1Deprecated => {
1032                // Deprecated: Authenticator state (JWK) is deprecated and
1033                // was never enabled. These transaction kinds are retained
1034                // only for BCS enum variant compatibility.
1035                Either::Right(Either::Right(iter::empty()))
1036            }
1037            Self::RandomnessStateUpdate(update) => {
1038                Either::Left(Either::Left(iter::once(SharedObjectReference::new(
1039                    ObjectId::RANDOMNESS_STATE,
1040                    update.randomness_obj_initial_shared_version,
1041                    true,
1042                ))))
1043            }
1044            Self::TransactionDenyRulesUpdate(update) => {
1045                Either::Left(Either::Left(iter::once(SharedObjectReference::new(
1046                    ObjectId::TRANSACTION_DENY_RULES,
1047                    update.deny_rules_obj_initial_shared_version,
1048                    true,
1049                ))))
1050            }
1051            Self::EndOfEpoch(txns) => Either::Left(Either::Right(
1052                txns.iter().flat_map(|txn| txn.shared_input_objects()),
1053            )),
1054            Self::Programmable(pt) => Either::Right(Either::Left(pt.shared_input_objects())),
1055            _ => Either::Right(Either::Right(iter::empty())),
1056        }
1057    }
1058
1059    fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)> {
1060        match &self {
1061            Self::Programmable(pt) => pt.move_calls(),
1062            _ => vec![],
1063        }
1064    }
1065
1066    fn receiving_objects(&self) -> Vec<ObjectReference> {
1067        match &self {
1068            #[allow(deprecated)]
1069            TransactionKind::Genesis(_)
1070            | TransactionKind::ConsensusCommitPrologueV1(_)
1071            | TransactionKind::AuthenticatorStateUpdateV1Deprecated
1072            | TransactionKind::RandomnessStateUpdate(_)
1073            | TransactionKind::TransactionDenyRulesUpdate(_)
1074            | TransactionKind::EndOfEpoch(_)
1075            | TransactionKind::ClaimAccount(_) => vec![],
1076            TransactionKind::Programmable(pt) => pt.receiving_objects(),
1077            _ => unimplemented!(
1078                "a new TransactionKind enum variant was added and needs to be handled"
1079            ),
1080        }
1081    }
1082
1083    fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
1084        let input_objects = match &self {
1085            Self::Genesis(_) => {
1086                vec![]
1087            }
1088            Self::ConsensusCommitPrologueV1(_) => {
1089                vec![InputObjectKind::SharedMoveObject {
1090                    id: ObjectId::CLOCK,
1091                    initial_shared_version: IOTA_CLOCK_OBJECT_SHARED_VERSION,
1092                    mutable: true,
1093                }]
1094            }
1095            #[allow(deprecated)]
1096            Self::AuthenticatorStateUpdateV1Deprecated => {
1097                // Deprecated: Authenticator state (JWK) is deprecated and
1098                // was never enabled. These transaction kinds are retained
1099                // only for BCS enum variant compatibility.
1100                vec![]
1101            }
1102            Self::RandomnessStateUpdate(update) => {
1103                vec![InputObjectKind::SharedMoveObject {
1104                    id: ObjectId::RANDOMNESS_STATE,
1105                    initial_shared_version: update.randomness_obj_initial_shared_version,
1106                    mutable: true,
1107                }]
1108            }
1109            Self::TransactionDenyRulesUpdate(update) => {
1110                vec![InputObjectKind::SharedMoveObject {
1111                    id: ObjectId::TRANSACTION_DENY_RULES,
1112                    initial_shared_version: update.deny_rules_obj_initial_shared_version,
1113                    mutable: true,
1114                }]
1115            }
1116            Self::EndOfEpoch(txns) => {
1117                // Dedup since transactions may have an overlap in input objects.
1118                // Note: it's critical to ensure the order of inputs are deterministic.
1119                let before_dedup: Vec<_> =
1120                    txns.iter().flat_map(|txn| txn.input_objects()).collect();
1121                let mut has_seen = HashSet::new();
1122                let mut after_dedup = vec![];
1123                for obj in before_dedup {
1124                    if has_seen.insert(obj) {
1125                        after_dedup.push(obj);
1126                    }
1127                }
1128                after_dedup
1129            }
1130            Self::Programmable(p) => return p.input_objects(),
1131            Self::ClaimAccount(_) => vec![],
1132            _ => unimplemented!(
1133                "a new TransactionKind enum variant was added and needs to be handled"
1134            ),
1135        };
1136        // Ensure that there are no duplicate inputs. This cannot be removed because:
1137        // In [`AuthorityState::check_locks`], we check that there are no duplicate
1138        // mutable input objects, which would have made this check here
1139        // unnecessary. However, we do plan to allow shared objects show up more
1140        // than once in multiple single transactions down the line. Once we have
1141        // that, we need check here to make sure the same shared object doesn't
1142        // show up more than once in the same single transaction.
1143        let mut used = HashSet::new();
1144        if !input_objects.iter().all(|o| used.insert(o.object_id())) {
1145            return Err(UserInputError::DuplicateObjectRefInput);
1146        }
1147        Ok(input_objects)
1148    }
1149
1150    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
1151        match self {
1152            TransactionKind::Programmable(p) => p.validity_check(config)?,
1153            // All transaction kinds below are assumed to be system,
1154            // and no validity or limit checks are performed.
1155            TransactionKind::Genesis(_) | TransactionKind::ConsensusCommitPrologueV1(_) => (),
1156            TransactionKind::EndOfEpoch(txns) => {
1157                for tx in txns {
1158                    tx.validity_check(config)?;
1159                }
1160            }
1161
1162            #[allow(deprecated)]
1163            TransactionKind::AuthenticatorStateUpdateV1Deprecated => {
1164                // Deprecated: Authenticator state (JWK) is deprecated and
1165                // was never enabled. These transaction kinds are retained
1166                // only for BCS enum variant compatibility.
1167                return Err(UserInputError::Unsupported(
1168                    "authenticator state transactions are deprecated and were never created on IOTA"
1169                        .to_string(),
1170                ));
1171            }
1172            TransactionKind::RandomnessStateUpdate(_) => (),
1173            TransactionKind::TransactionDenyRulesUpdate(_) => {
1174                if !config.enable_pcool_flow() {
1175                    return Err(UserInputError::Unsupported(
1176                        "on-chain deny rule governance not supported at current protocol version"
1177                            .to_string(),
1178                    ));
1179                }
1180            }
1181            TransactionKind::ClaimAccount(claim) => {
1182                fp_ensure!(
1183                    config.enable_claim_account_transaction(),
1184                    UserInputError::Unsupported(
1185                        "claim account transactions are not enabled on this network".to_string()
1186                    )
1187                );
1188                match &claim.kind {
1189                    AccountClaimKind::SmartAccount(smart) => {
1190                        // Apply `public_key::create`'s validation here, so that a
1191                        // claim with an invalid key is rejected before execution
1192                        // rather than aborting in it.
1193                        let scheme =
1194                            SignatureScheme::from_byte(smart.public_key_scheme).map_err(|e| {
1195                                UserInputError::Unsupported(format!(
1196                                    "invalid claim account public key scheme: {e}"
1197                                ))
1198                            })?;
1199                        MovePublicKey::new(scheme, smart.public_key_raw_bytes.clone()).map_err(
1200                            |e| {
1201                                UserInputError::Unsupported(format!(
1202                                    "invalid claim account public key: {e}"
1203                                ))
1204                            },
1205                        )?;
1206                    }
1207                    _ => unimplemented!(
1208                        "a new AccountClaimKind enum variant was added and needs to be handled"
1209                    ),
1210                }
1211            }
1212            _ => unimplemented!(
1213                "a new TransactionKind enum variant was added and needs to be handled"
1214            ),
1215        };
1216        Ok(())
1217    }
1218
1219    fn iter_commands(&self) -> impl Iterator<Item = &Command> {
1220        match self {
1221            TransactionKind::Programmable(pt) => pt.commands.iter(),
1222            _ => [].iter(),
1223        }
1224    }
1225
1226    fn name(&self) -> &'static str {
1227        match self {
1228            Self::Genesis(_) => "Genesis",
1229            Self::ConsensusCommitPrologueV1(_) => "ConsensusCommitPrologueV1",
1230            Self::Programmable(_) => "Programmable",
1231            #[allow(deprecated)]
1232            Self::AuthenticatorStateUpdateV1Deprecated => "AuthenticatorStateUpdateV1Deprecated",
1233            Self::RandomnessStateUpdate(_) => "RandomnessStateUpdate",
1234            Self::TransactionDenyRulesUpdate(_) => "TransactionDenyRulesUpdate",
1235            Self::EndOfEpoch(_) => "EndOfEpoch",
1236            Self::ClaimAccount(_) => "ClaimAccount",
1237            _ => unimplemented!(
1238                "a new TransactionKind enum variant was added and needs to be handled"
1239            ),
1240        }
1241    }
1242}
1243
1244/// API for accessing and constructing [`Transaction`].
1245///
1246/// This trait provides node-internal methods for:
1247/// - **Accessors**: reading transaction fields (sender, kind, gas, expiration, etc.)
1248/// - **Queries**: inspecting transaction properties (shared objects, Move calls, sponsorship)
1249/// - **Validation**: checking transaction validity against protocol config
1250/// - **Constructors**: building new transactions (transfers, Move calls, programmable txs, etc.)
1251///
1252/// Note: The `iota-rust-sdk` crate (`iota-sdk-types`) defines additional
1253/// client-facing methods on [`Transaction`] itself.
1254pub trait TransactionAPI {
1255    /// Returns the address of the transaction sender.
1256    fn sender(&self) -> Address;
1257
1258    /// Returns a reference to the transaction kind.
1259    fn kind(&self) -> &TransactionKind;
1260
1261    /// Returns a mutable reference to the transaction kind.
1262    fn kind_mut(&mut self) -> &mut TransactionKind;
1263
1264    /// Consumes self and returns the transaction kind.
1265    fn into_kind(self) -> TransactionKind;
1266
1267    /// Returns the transaction signer(s). Includes both the sender and the gas
1268    /// owner if they differ (i.e. for sponsored transactions).
1269    fn signers(&self) -> NonEmpty<Address>;
1270
1271    /// Returns a reference to the gas data (owner, payment objects, price,
1272    /// budget).
1273    fn gas_data(&self) -> &GasPayment;
1274
1275    /// Returns the address that owns the gas payment objects.
1276    fn gas_owner(&self) -> Address;
1277
1278    /// Returns the gas payment object references.
1279    fn gas(&self) -> &[ObjectReference];
1280
1281    /// Returns the gas price for this transaction.
1282    fn gas_price(&self) -> u64;
1283
1284    /// Returns the gas budget for this transaction.
1285    fn gas_budget(&self) -> u64;
1286
1287    /// Returns the transaction expiration.
1288    fn expiration(&self) -> &TransactionExpiration;
1289
1290    /// Returns the digest of the transaction this transaction depends on, if
1291    /// it carries a transaction dependency input: it executes after that
1292    /// transaction, and fails if that transaction failed.
1293    fn transaction_dependency(&self) -> Option<TransactionDigest>;
1294
1295    /// Returns a list of the transaction data shared input objects.
1296    ///
1297    /// IMPORTANT: This function does not return shared objects associated with
1298    /// `MoveAuthenticator` signatures. To check those objects as well, use the
1299    /// corresponding function from `SenderSignedTransaction`.
1300    fn shared_input_objects(&self) -> Vec<SharedObjectReference>;
1301
1302    /// Returns a list of Move calls as `(package_id, module_name,
1303    /// function_name)` tuples.
1304    fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)>;
1305
1306    /// Returns the input objects required by the transaction body.
1307    ///
1308    /// Note: this does NOT include the objects read by any `MoveAuthenticator`s
1309    /// (abstract-account authenticators); those are carried by the transaction
1310    /// envelope, not by `TransactionData`. For the full set including
1311    /// authenticator inputs, use `SenderSignedData::input_objects` or
1312    /// `SenderSignedData::collect_all_input_object_kind_for_reading`.
1313    fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>>;
1314
1315    /// Returns object references for all objects being received in this
1316    /// transaction.
1317    fn receiving_objects(&self) -> Vec<ObjectReference>;
1318
1319    /// Validates the transaction data against the given protocol config,
1320    /// including gas checks.
1321    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult;
1322
1323    /// Validates the transaction data against the given protocol config,
1324    /// skipping gas-related checks.
1325    fn validity_check_no_gas_check(&self, config: &ProtocolConfig) -> UserInputResult;
1326
1327    /// Checks the BCS size of the transaction data against the protocol's
1328    /// `max_tx_size_bytes`.
1329    fn check_serialized_size(&self, config: &ProtocolConfig) -> IotaResult;
1330
1331    /// Checks the gas payment against the protocol's cap on how many objects it
1332    /// may name.
1333    fn check_gas_payment_size(&self, config: &ProtocolConfig) -> UserInputResult;
1334
1335    /// Check if the transaction is compliant with sponsorship.
1336    fn check_sponsorship(&self) -> UserInputResult;
1337
1338    /// Returns `true` if this is a system transaction.
1339    fn is_system_tx(&self) -> bool;
1340    /// Returns `true` if this is the genesis transaction.
1341    fn is_genesis_tx(&self) -> bool;
1342
1343    /// returns true if the transaction is one that is specially sequenced to
1344    /// run at the very end of the epoch
1345    fn is_end_of_epoch_tx(&self) -> bool;
1346
1347    /// Check if the transaction is sponsored (namely gas owner != sender)
1348    fn is_sponsored_tx(&self) -> bool;
1349
1350    /// Returns a mutable reference to the sender address. **Testing only.**
1351    fn sender_mut_for_testing(&mut self) -> &mut Address;
1352
1353    /// Returns a mutable reference to the gas data.
1354    fn gas_data_mut(&mut self) -> &mut GasPayment;
1355
1356    /// Returns a mutable reference to the expiration. **Testing only.**
1357    fn expiration_mut_for_testing(&mut self) -> &mut TransactionExpiration;
1358
1359    /// Creates a new system transaction with no gas payment. Used for
1360    /// validator-initiated transactions (epoch changes, checkpoints, etc.).
1361    fn new_system_transaction(kind: TransactionKind) -> Transaction;
1362
1363    /// Creates a new transaction with a single gas payment coin. The sender
1364    /// is also the gas owner.
1365    #[allow(clippy::new_ret_no_self)]
1366    fn new(
1367        kind: TransactionKind,
1368        sender: Address,
1369        gas_payment: ObjectReference,
1370        gas_budget: u64,
1371        gas_price: u64,
1372    ) -> Transaction;
1373
1374    /// Creates a new transaction with multiple gas payment coins. The sender
1375    /// is also the gas owner.
1376    fn new_with_gas_coins(
1377        kind: TransactionKind,
1378        sender: Address,
1379        gas_payment: Vec<ObjectReference>,
1380        gas_budget: u64,
1381        gas_price: u64,
1382    ) -> Transaction;
1383
1384    /// Creates a new transaction with multiple gas payment coins and a
1385    /// separate gas sponsor. Use this for sponsored transactions where
1386    /// the gas owner differs from the sender.
1387    fn new_with_gas_coins_allow_sponsor(
1388        kind: TransactionKind,
1389        sender: Address,
1390        gas_payment: Vec<ObjectReference>,
1391        gas_budget: u64,
1392        gas_price: u64,
1393        gas_sponsor: Address,
1394    ) -> Transaction;
1395
1396    /// Creates a new transaction from a pre-built [`GasPayment`] struct.
1397    fn new_with_gas_data(
1398        kind: TransactionKind,
1399        sender: Address,
1400        gas_data: GasPayment,
1401    ) -> Transaction;
1402
1403    /// Creates a transaction that calls a single Move function with a single
1404    /// gas payment coin.
1405    fn new_move_call(
1406        sender: Address,
1407        package: ObjectId,
1408        module: Identifier,
1409        function: Identifier,
1410        type_arguments: Vec<TypeTag>,
1411        gas_payment: ObjectReference,
1412        arguments: Vec<CallArg>,
1413        gas_budget: u64,
1414        gas_price: u64,
1415    ) -> anyhow::Result<Transaction>;
1416
1417    /// Creates a transaction that calls a single Move function with multiple
1418    /// gas payment coins.
1419    fn new_move_call_with_gas_coins(
1420        sender: Address,
1421        package: ObjectId,
1422        module: Identifier,
1423        function: Identifier,
1424        type_arguments: Vec<TypeTag>,
1425        gas_payment: Vec<ObjectReference>,
1426        arguments: Vec<CallArg>,
1427        gas_budget: u64,
1428        gas_price: u64,
1429    ) -> anyhow::Result<Transaction>;
1430
1431    /// Creates a transaction that transfers an object to a recipient.
1432    fn new_transfer(
1433        recipient: Address,
1434        object_ref: ObjectReference,
1435        sender: Address,
1436        gas_payment: ObjectReference,
1437        gas_budget: u64,
1438        gas_price: u64,
1439    ) -> Transaction;
1440
1441    /// Creates a transaction that transfers IOTA coins to a recipient.
1442    /// If `amount` is `None`, the entire gas coin balance (minus gas fees)
1443    /// is transferred.
1444    fn new_transfer_iota(
1445        recipient: Address,
1446        sender: Address,
1447        amount: Option<u64>,
1448        gas_payment: ObjectReference,
1449        gas_budget: u64,
1450        gas_price: u64,
1451    ) -> Transaction;
1452
1453    /// Creates a sponsored transaction that transfers IOTA coins to a
1454    /// recipient. If `amount` is `None`, the entire gas coin balance
1455    /// (minus gas fees) is transferred.
1456    fn new_transfer_iota_allow_sponsor(
1457        recipient: Address,
1458        sender: Address,
1459        amount: Option<u64>,
1460        gas_payment: ObjectReference,
1461        gas_budget: u64,
1462        gas_price: u64,
1463        gas_sponsor: Address,
1464    ) -> Transaction;
1465
1466    /// Creates a transaction that pays multiple recipients from a set of
1467    /// input coins. The coins are merged and then split to satisfy the
1468    /// specified amounts.
1469    fn new_pay(
1470        sender: Address,
1471        coins: Vec<ObjectReference>,
1472        recipients: Vec<Address>,
1473        amounts: Vec<u64>,
1474        gas_payment: ObjectReference,
1475        gas_budget: u64,
1476        gas_price: u64,
1477    ) -> anyhow::Result<Transaction>;
1478
1479    /// Creates a transaction that pays multiple recipients using IOTA coins.
1480    /// Similar to [`Self::new_pay`] but the gas coin is also used as an
1481    /// input coin.
1482    fn new_pay_iota(
1483        sender: Address,
1484        coins: Vec<ObjectReference>,
1485        recipients: Vec<Address>,
1486        amounts: Vec<u64>,
1487        gas_payment: ObjectReference,
1488        gas_budget: u64,
1489        gas_price: u64,
1490    ) -> anyhow::Result<Transaction>;
1491
1492    /// Creates a transaction that sends all IOTA from the given coins to a
1493    /// single recipient. The gas coin is included as an input coin.
1494    fn new_pay_all_iota(
1495        sender: Address,
1496        coins: Vec<ObjectReference>,
1497        recipient: Address,
1498        gas_payment: ObjectReference,
1499        gas_budget: u64,
1500        gas_price: u64,
1501    ) -> Transaction;
1502
1503    /// Creates a transaction that splits a coin into multiple coins with the
1504    /// specified amounts.
1505    fn new_split_coin(
1506        sender: Address,
1507        coin: ObjectReference,
1508        amounts: Vec<u64>,
1509        gas_payment: ObjectReference,
1510        gas_budget: u64,
1511        gas_price: u64,
1512    ) -> Transaction;
1513
1514    /// Creates a transaction that publishes new Move modules.
1515    fn new_module(
1516        sender: Address,
1517        gas_payment: ObjectReference,
1518        modules: Vec<Vec<u8>>,
1519        dep_ids: Vec<ObjectId>,
1520        gas_budget: u64,
1521        gas_price: u64,
1522    ) -> Transaction;
1523
1524    /// Creates a transaction that upgrades an existing Move package.
1525    /// Requires the upgrade capability object and the upgrade policy.
1526    fn new_upgrade(
1527        sender: Address,
1528        gas_payment: ObjectReference,
1529        package_id: ObjectId,
1530        modules: Vec<Vec<u8>>,
1531        dep_ids: Vec<ObjectId>,
1532        upgrade_capability_and_owner: (ObjectReference, Owner),
1533        upgrade_policy: u8,
1534        digest: Vec<u8>,
1535        gas_budget: u64,
1536        gas_price: u64,
1537    ) -> anyhow::Result<Transaction>;
1538
1539    /// Creates a programmable transaction with multiple gas payment coins.
1540    /// The sender is also the gas owner.
1541    fn new_programmable(
1542        sender: Address,
1543        gas_payment: Vec<ObjectReference>,
1544        pt: ProgrammableTransaction,
1545        gas_budget: u64,
1546        gas_price: u64,
1547    ) -> Transaction;
1548
1549    /// Creates a programmable transaction with multiple gas payment coins
1550    /// and a separate gas sponsor.
1551    fn new_programmable_allow_sponsor(
1552        sender: Address,
1553        gas_payment: Vec<ObjectReference>,
1554        pt: ProgrammableTransaction,
1555        gas_budget: u64,
1556        gas_price: u64,
1557        sponsor: Address,
1558    ) -> Transaction;
1559
1560    /// Returns the internal message version number.
1561    fn message_version(&self) -> u64;
1562
1563    /// Consumes self and returns the transaction kind, sender address, and
1564    /// gas payment object references as a tuple.
1565    fn execution_parts(&self) -> (TransactionKind, Address, GasPayment);
1566}
1567
1568fn tx_bcs_size<T: Serialize>(tx: &T) -> IotaResult<usize> {
1569    bcs::serialized_size(tx).map_err(|e| IotaError::TransactionSerialization {
1570        error: e.to_string(),
1571    })
1572}
1573
1574/// Checks the BCS size of `transaction` against the protocol's
1575/// `max_tx_size_bytes` and returns it.
1576fn check_transaction_size<T: Serialize>(
1577    transaction: &T,
1578    config: &ProtocolConfig,
1579) -> IotaResult<usize> {
1580    let tx_size = tx_bcs_size(transaction)?;
1581    let max_tx_size_bytes = config.max_tx_size_bytes();
1582    fp_ensure!(
1583        tx_size as u64 <= max_tx_size_bytes,
1584        IotaError::UserInput {
1585            error: UserInputError::SizeLimitExceeded {
1586                limit: format!(
1587                    "serialized transaction size exceeded maximum of {max_tx_size_bytes}"
1588                ),
1589                value: tx_size.to_string(),
1590            }
1591        }
1592    );
1593    Ok(tx_size)
1594}
1595
1596impl TransactionAPI for Transaction {
1597    fn check_serialized_size(&self, config: &ProtocolConfig) -> IotaResult {
1598        check_transaction_size(self, config).map(|_| ())
1599    }
1600
1601    fn sender(&self) -> Address {
1602        match self {
1603            Self::V1(v1) => v1.sender,
1604            _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1605        }
1606    }
1607
1608    fn kind(&self) -> &TransactionKind {
1609        match self {
1610            Self::V1(v1) => &v1.kind,
1611            _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1612        }
1613    }
1614
1615    fn kind_mut(&mut self) -> &mut TransactionKind {
1616        match self {
1617            Self::V1(v1) => &mut v1.kind,
1618            _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1619        }
1620    }
1621
1622    fn into_kind(self) -> TransactionKind {
1623        match self {
1624            Self::V1(v1) => v1.kind,
1625            _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1626        }
1627    }
1628
1629    fn signers(&self) -> NonEmpty<Address> {
1630        let mut signers = nonempty![self.sender()];
1631        if self.gas_owner() != self.sender() {
1632            signers.push(self.gas_owner());
1633        }
1634        signers
1635    }
1636
1637    fn gas_data(&self) -> &GasPayment {
1638        match self {
1639            Self::V1(v1) => &v1.gas_payment,
1640            _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1641        }
1642    }
1643
1644    fn gas_owner(&self) -> Address {
1645        self.gas_data().owner
1646    }
1647
1648    fn gas(&self) -> &[ObjectReference] {
1649        &self.gas_data().objects
1650    }
1651
1652    fn gas_price(&self) -> u64 {
1653        self.gas_data().price
1654    }
1655
1656    fn gas_budget(&self) -> u64 {
1657        self.gas_data().budget
1658    }
1659
1660    fn expiration(&self) -> &TransactionExpiration {
1661        match self {
1662            Self::V1(v1) => &v1.expiration,
1663            _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1664        }
1665    }
1666
1667    fn shared_input_objects(&self) -> Vec<SharedObjectReference> {
1668        self.kind().shared_input_objects().collect()
1669    }
1670
1671    fn move_calls(&self) -> Vec<(&ObjectId, &str, &str)> {
1672        self.kind().move_calls()
1673    }
1674
1675    fn input_objects(&self) -> UserInputResult<Vec<InputObjectKind>> {
1676        let mut inputs = self.kind().input_objects()?;
1677
1678        if !self.kind().is_system() {
1679            inputs.extend(
1680                self.gas()
1681                    .iter()
1682                    .map(|obj_ref| InputObjectKind::ImmOrOwnedMoveObject(*obj_ref)),
1683            );
1684        }
1685        Ok(inputs)
1686    }
1687
1688    fn receiving_objects(&self) -> Vec<ObjectReference> {
1689        self.kind().receiving_objects()
1690    }
1691
1692    fn validity_check(&self, config: &ProtocolConfig) -> UserInputResult {
1693        fp_ensure!(!self.gas().is_empty(), UserInputError::MissingGasPayment);
1694        self.check_gas_payment_size(config)?;
1695        if config.validate_input_object_versions() {
1696            for gas_object in self.gas() {
1697                input_object_version_validity_check(gas_object.version)?;
1698            }
1699        }
1700        check_claim_account_gas_budget(self, config)?;
1701        self.validity_check_no_gas_check(config)
1702    }
1703
1704    #[instrument(level = "trace", skip_all)]
1705    fn validity_check_no_gas_check(&self, config: &ProtocolConfig) -> UserInputResult {
1706        self.kind().validity_check(config)?;
1707        if self.transaction_dependency().is_some() {
1708            fp_ensure!(
1709                matches!(self.expiration(), TransactionExpiration::Epoch(_)),
1710                UserInputError::TransactionDependencyRequiresExpiration
1711            );
1712        }
1713        check_claimed_key_derives_sender(self)?;
1714        self.check_sponsorship()
1715    }
1716
1717    fn transaction_dependency(&self) -> Option<TransactionDigest> {
1718        match self.kind() {
1719            TransactionKind::Programmable(ptb) => ptb.transaction_dependency(),
1720            _ => None,
1721        }
1722    }
1723
1724    fn check_gas_payment_size(&self, config: &ProtocolConfig) -> UserInputResult {
1725        fp_ensure!(
1726            self.gas().len() < config.max_gas_payment_objects() as usize,
1727            UserInputError::SizeLimitExceeded {
1728                limit: "maximum number of gas payment objects".to_string(),
1729                value: config.max_gas_payment_objects().to_string()
1730            }
1731        );
1732        Ok(())
1733    }
1734
1735    fn is_sponsored_tx(&self) -> bool {
1736        self.gas_owner() != self.sender()
1737    }
1738
1739    fn check_sponsorship(&self) -> UserInputResult {
1740        if self.gas_owner() == self.sender() {
1741            return Ok(());
1742        }
1743        if matches!(
1744            self.kind(),
1745            TransactionKind::Programmable(_) | TransactionKind::ClaimAccount(_)
1746        ) {
1747            return Ok(());
1748        }
1749        Err(UserInputError::UnsupportedSponsoredTransactionKind)
1750    }
1751
1752    fn is_end_of_epoch_tx(&self) -> bool {
1753        matches!(self.kind(), TransactionKind::EndOfEpoch(_))
1754    }
1755
1756    fn is_system_tx(&self) -> bool {
1757        self.kind().is_system()
1758    }
1759
1760    fn is_genesis_tx(&self) -> bool {
1761        matches!(self.kind(), TransactionKind::Genesis(_))
1762    }
1763
1764    fn sender_mut_for_testing(&mut self) -> &mut Address {
1765        match self {
1766            Self::V1(v1) => &mut v1.sender,
1767            _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1768        }
1769    }
1770
1771    fn gas_data_mut(&mut self) -> &mut GasPayment {
1772        match self {
1773            Self::V1(v1) => &mut v1.gas_payment,
1774            _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1775        }
1776    }
1777
1778    fn expiration_mut_for_testing(&mut self) -> &mut TransactionExpiration {
1779        match self {
1780            Self::V1(v1) => &mut v1.expiration,
1781            _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
1782        }
1783    }
1784
1785    fn new_system_transaction(kind: TransactionKind) -> Transaction {
1786        assert!(kind.is_system());
1787        let sender = Address::ZERO;
1788        Transaction::V1(TransactionV1 {
1789            kind,
1790            sender,
1791            gas_payment: GasPayment {
1792                price: GAS_PRICE_FOR_SYSTEM_TX,
1793                owner: sender,
1794                objects: vec![ObjectReference::new(
1795                    ObjectId::ZERO,
1796                    Version::default(),
1797                    ObjectDigest::MIN,
1798                )],
1799                budget: 0,
1800            },
1801            expiration: TransactionExpiration::None,
1802        })
1803    }
1804
1805    fn new(
1806        kind: TransactionKind,
1807        sender: Address,
1808        gas_payment: ObjectReference,
1809        gas_budget: u64,
1810        gas_price: u64,
1811    ) -> Transaction {
1812        Transaction::V1(TransactionV1 {
1813            kind,
1814            sender,
1815            gas_payment: GasPayment {
1816                price: gas_price,
1817                owner: sender,
1818                objects: vec![gas_payment],
1819                budget: gas_budget,
1820            },
1821            expiration: TransactionExpiration::None,
1822        })
1823    }
1824
1825    fn new_with_gas_coins(
1826        kind: TransactionKind,
1827        sender: Address,
1828        gas_payment: Vec<ObjectReference>,
1829        gas_budget: u64,
1830        gas_price: u64,
1831    ) -> Transaction {
1832        Transaction::new_with_gas_coins_allow_sponsor(
1833            kind,
1834            sender,
1835            gas_payment,
1836            gas_budget,
1837            gas_price,
1838            sender,
1839        )
1840    }
1841
1842    fn new_with_gas_coins_allow_sponsor(
1843        kind: TransactionKind,
1844        sender: Address,
1845        gas_payment: Vec<ObjectReference>,
1846        gas_budget: u64,
1847        gas_price: u64,
1848        gas_sponsor: Address,
1849    ) -> Transaction {
1850        Transaction::V1(TransactionV1 {
1851            kind,
1852            sender,
1853            gas_payment: GasPayment {
1854                price: gas_price,
1855                owner: gas_sponsor,
1856                objects: gas_payment,
1857                budget: gas_budget,
1858            },
1859            expiration: TransactionExpiration::None,
1860        })
1861    }
1862
1863    fn new_with_gas_data(
1864        kind: TransactionKind,
1865        sender: Address,
1866        gas_data: GasPayment,
1867    ) -> Transaction {
1868        Transaction::V1(TransactionV1 {
1869            kind,
1870            sender,
1871            gas_payment: gas_data,
1872            expiration: TransactionExpiration::None,
1873        })
1874    }
1875
1876    fn new_move_call(
1877        sender: Address,
1878        package: ObjectId,
1879        module: Identifier,
1880        function: Identifier,
1881        type_arguments: Vec<TypeTag>,
1882        gas_payment: ObjectReference,
1883        arguments: Vec<CallArg>,
1884        gas_budget: u64,
1885        gas_price: u64,
1886    ) -> anyhow::Result<Transaction> {
1887        Transaction::new_move_call_with_gas_coins(
1888            sender,
1889            package,
1890            module,
1891            function,
1892            type_arguments,
1893            vec![gas_payment],
1894            arguments,
1895            gas_budget,
1896            gas_price,
1897        )
1898    }
1899
1900    fn new_move_call_with_gas_coins(
1901        sender: Address,
1902        package: ObjectId,
1903        module: Identifier,
1904        function: Identifier,
1905        type_arguments: Vec<TypeTag>,
1906        gas_payment: Vec<ObjectReference>,
1907        arguments: Vec<CallArg>,
1908        gas_budget: u64,
1909        gas_price: u64,
1910    ) -> anyhow::Result<Transaction> {
1911        let pt = {
1912            let mut builder = ProgrammableTransactionBuilder::new();
1913            builder.move_call(package, module, function, type_arguments, arguments)?;
1914            builder.finish()
1915        };
1916        Ok(Transaction::new_programmable(
1917            sender,
1918            gas_payment,
1919            pt,
1920            gas_budget,
1921            gas_price,
1922        ))
1923    }
1924
1925    fn new_transfer(
1926        recipient: Address,
1927        object_ref: ObjectReference,
1928        sender: Address,
1929        gas_payment: ObjectReference,
1930        gas_budget: u64,
1931        gas_price: u64,
1932    ) -> Transaction {
1933        let pt = {
1934            let mut builder = ProgrammableTransactionBuilder::new();
1935            builder.transfer_object(recipient, object_ref).unwrap();
1936            builder.finish()
1937        };
1938        Transaction::new_programmable(sender, vec![gas_payment], pt, gas_budget, gas_price)
1939    }
1940
1941    fn new_transfer_iota(
1942        recipient: Address,
1943        sender: Address,
1944        amount: Option<u64>,
1945        gas_payment: ObjectReference,
1946        gas_budget: u64,
1947        gas_price: u64,
1948    ) -> Transaction {
1949        Transaction::new_transfer_iota_allow_sponsor(
1950            recipient,
1951            sender,
1952            amount,
1953            gas_payment,
1954            gas_budget,
1955            gas_price,
1956            sender,
1957        )
1958    }
1959
1960    fn new_transfer_iota_allow_sponsor(
1961        recipient: Address,
1962        sender: Address,
1963        amount: Option<u64>,
1964        gas_payment: ObjectReference,
1965        gas_budget: u64,
1966        gas_price: u64,
1967        gas_sponsor: Address,
1968    ) -> Transaction {
1969        let pt = {
1970            let mut builder = ProgrammableTransactionBuilder::new();
1971            builder.transfer_iota(recipient, amount);
1972            builder.finish()
1973        };
1974        Transaction::new_programmable_allow_sponsor(
1975            sender,
1976            vec![gas_payment],
1977            pt,
1978            gas_budget,
1979            gas_price,
1980            gas_sponsor,
1981        )
1982    }
1983
1984    fn new_pay(
1985        sender: Address,
1986        coins: Vec<ObjectReference>,
1987        recipients: Vec<Address>,
1988        amounts: Vec<u64>,
1989        gas_payment: ObjectReference,
1990        gas_budget: u64,
1991        gas_price: u64,
1992    ) -> anyhow::Result<Transaction> {
1993        let pt = {
1994            let mut builder = ProgrammableTransactionBuilder::new();
1995            builder.pay(coins, recipients, amounts)?;
1996            builder.finish()
1997        };
1998        Ok(Transaction::new_programmable(
1999            sender,
2000            vec![gas_payment],
2001            pt,
2002            gas_budget,
2003            gas_price,
2004        ))
2005    }
2006
2007    fn new_pay_iota(
2008        sender: Address,
2009        mut coins: Vec<ObjectReference>,
2010        recipients: Vec<Address>,
2011        amounts: Vec<u64>,
2012        gas_payment: ObjectReference,
2013        gas_budget: u64,
2014        gas_price: u64,
2015    ) -> anyhow::Result<Transaction> {
2016        coins.insert(0, gas_payment);
2017        let pt = {
2018            let mut builder = ProgrammableTransactionBuilder::new();
2019            builder.pay_iota(recipients, amounts)?;
2020            builder.finish()
2021        };
2022        Ok(Transaction::new_programmable(
2023            sender, coins, pt, gas_budget, gas_price,
2024        ))
2025    }
2026
2027    fn new_pay_all_iota(
2028        sender: Address,
2029        mut coins: Vec<ObjectReference>,
2030        recipient: Address,
2031        gas_payment: ObjectReference,
2032        gas_budget: u64,
2033        gas_price: u64,
2034    ) -> Transaction {
2035        coins.insert(0, gas_payment);
2036        let pt = {
2037            let mut builder = ProgrammableTransactionBuilder::new();
2038            builder.pay_all_iota(recipient);
2039            builder.finish()
2040        };
2041        Transaction::new_programmable(sender, coins, pt, gas_budget, gas_price)
2042    }
2043
2044    fn new_split_coin(
2045        sender: Address,
2046        coin: ObjectReference,
2047        amounts: Vec<u64>,
2048        gas_payment: ObjectReference,
2049        gas_budget: u64,
2050        gas_price: u64,
2051    ) -> Transaction {
2052        let pt = {
2053            let mut builder = ProgrammableTransactionBuilder::new();
2054            builder.split_coin(sender, coin, amounts);
2055            builder.finish()
2056        };
2057        Transaction::new_programmable(sender, vec![gas_payment], pt, gas_budget, gas_price)
2058    }
2059
2060    fn new_module(
2061        sender: Address,
2062        gas_payment: ObjectReference,
2063        modules: Vec<Vec<u8>>,
2064        dep_ids: Vec<ObjectId>,
2065        gas_budget: u64,
2066        gas_price: u64,
2067    ) -> Transaction {
2068        let pt = {
2069            let mut builder = ProgrammableTransactionBuilder::new();
2070            let upgrade_cap = builder.publish_upgradeable(modules, dep_ids);
2071            builder.transfer_arg(sender, upgrade_cap);
2072            builder.finish()
2073        };
2074        Transaction::new_programmable(sender, vec![gas_payment], pt, gas_budget, gas_price)
2075    }
2076
2077    fn new_upgrade(
2078        sender: Address,
2079        gas_payment: ObjectReference,
2080        package_id: ObjectId,
2081        modules: Vec<Vec<u8>>,
2082        dep_ids: Vec<ObjectId>,
2083        (upgrade_capability, capability_owner): (ObjectReference, Owner),
2084        upgrade_policy: u8,
2085        digest: Vec<u8>,
2086        gas_budget: u64,
2087        gas_price: u64,
2088    ) -> anyhow::Result<Transaction> {
2089        let pt = {
2090            let mut builder = ProgrammableTransactionBuilder::new();
2091            let capability_arg = match capability_owner {
2092                Owner::Address(_) => CallArg::ImmutableOrOwned(upgrade_capability),
2093                Owner::Shared(initial_shared_version) => {
2094                    CallArg::Shared(SharedObjectReference::new(
2095                        upgrade_capability.object_id,
2096                        initial_shared_version,
2097                        true,
2098                    ))
2099                }
2100                Owner::Immutable => {
2101                    bail!("Upgrade capability is stored immutably and cannot be used for upgrades");
2102                }
2103                Owner::Object(_) => {
2104                    bail!("Upgrade capability controlled by object");
2105                }
2106                _ => unimplemented!("a new Owner enum variant was added and needs to be handled"),
2107            };
2108            builder.obj(capability_arg).unwrap();
2109            let upgrade_arg = builder.pure(upgrade_policy).unwrap();
2110            let digest_arg = builder.pure(digest).unwrap();
2111            let upgrade_ticket = builder.programmable_move_call(
2112                ObjectId::FRAMEWORK,
2113                Identifier::PACKAGE_MODULE,
2114                Identifier::from_static("authorize_upgrade"),
2115                vec![],
2116                vec![Argument::Input(0), upgrade_arg, digest_arg],
2117            );
2118            let upgrade_receipt = builder.upgrade(package_id, upgrade_ticket, dep_ids, modules);
2119
2120            builder.programmable_move_call(
2121                ObjectId::FRAMEWORK,
2122                Identifier::PACKAGE_MODULE,
2123                Identifier::from_static("commit_upgrade"),
2124                vec![],
2125                vec![Argument::Input(0), upgrade_receipt],
2126            );
2127
2128            builder.finish()
2129        };
2130        Ok(Transaction::new_programmable(
2131            sender,
2132            vec![gas_payment],
2133            pt,
2134            gas_budget,
2135            gas_price,
2136        ))
2137    }
2138
2139    fn new_programmable(
2140        sender: Address,
2141        gas_payment: Vec<ObjectReference>,
2142        pt: ProgrammableTransaction,
2143        gas_budget: u64,
2144        gas_price: u64,
2145    ) -> Transaction {
2146        Transaction::new_programmable_allow_sponsor(
2147            sender,
2148            gas_payment,
2149            pt,
2150            gas_budget,
2151            gas_price,
2152            sender,
2153        )
2154    }
2155
2156    fn new_programmable_allow_sponsor(
2157        sender: Address,
2158        gas_payment: Vec<ObjectReference>,
2159        pt: ProgrammableTransaction,
2160        gas_budget: u64,
2161        gas_price: u64,
2162        sponsor: Address,
2163    ) -> Transaction {
2164        let kind = TransactionKind::Programmable(pt);
2165        Transaction::new_with_gas_coins_allow_sponsor(
2166            kind,
2167            sender,
2168            gas_payment,
2169            gas_budget,
2170            gas_price,
2171            sponsor,
2172        )
2173    }
2174
2175    fn message_version(&self) -> u64 {
2176        match self {
2177            Transaction::V1(_) => 1,
2178            _ => unimplemented!("a new Transaction enum variant was added and needs to be handled"),
2179        }
2180    }
2181
2182    fn execution_parts(&self) -> (TransactionKind, Address, GasPayment) {
2183        (self.kind().clone(), self.sender(), self.gas_data().clone())
2184    }
2185}
2186
2187pub struct TxValidityCheckContext<'a> {
2188    pub config: &'a ProtocolConfig,
2189    pub epoch: EpochId,
2190}
2191
2192/// Merge every [`MoveAuthenticator`]'s input objects into `input_objects`,
2193/// with the packages named by its type arguments if
2194/// `include_type_arg_packages` is set.
2195///
2196/// Objects not yet present are appended; for an object that appears in both
2197/// sets the kinds are checked for consistency and unioned via
2198/// [`InputObjectKind::left_union_with_checks`] (in particular, a shared object
2199/// may differ in mutability but not in initial shared version).
2200///
2201/// The packages named by the type arguments are appended after every
2202/// authenticator's objects, each only if its id is not present yet, so they
2203/// never fail the merge. A type argument that names an object's id is rejected
2204/// by the validity check, or when the id is read as a package.
2205pub fn merge_authenticator_input_objects<'a>(
2206    move_authenticators: impl IntoIterator<Item = &'a MoveAuthenticator>,
2207    include_type_arg_packages: bool,
2208    input_objects: &mut Vec<InputObjectKind>,
2209) -> UserInputResult<()> {
2210    let mut type_arg_packages = Vec::new();
2211    for move_authenticator in move_authenticators {
2212        for auth_object in move_authenticator.input_objects(false) {
2213            let entry = input_objects
2214                .iter_mut()
2215                .find(|o| o.object_id() == auth_object.object_id());
2216
2217            match entry {
2218                None => input_objects.push(auth_object),
2219                Some(existing) => existing.left_union_with_checks(&auth_object)?,
2220            }
2221        }
2222        if include_type_arg_packages {
2223            type_arg_packages.extend(move_authenticator.type_arg_packages());
2224        }
2225    }
2226    for package_id in type_arg_packages {
2227        if input_objects.iter().all(|o| o.object_id() != package_id) {
2228            input_objects.push(InputObjectKind::MovePackage(package_id));
2229        }
2230    }
2231    Ok(())
2232}
2233
2234/// API for accessing and constructing [`SenderSignedTransaction`].
2235///
2236/// This trait provides node-internal methods on the SDK's
2237/// [`SenderSignedTransaction`], which carries the transaction data together
2238/// with the signatures of all transaction participants. A non-participant
2239/// signature must not be present, and the signature order does not matter.
2240pub trait SenderSignedTransactionAPI {
2241    /// Creates a new [`SenderSignedTransaction`] with a single sender
2242    /// signature.
2243    fn new_from_sender_signature(
2244        tx: Transaction,
2245        tx_signature: SimpleSignature,
2246    ) -> SenderSignedTransaction;
2247
2248    /// Adds a signature. Does not check the validity of the signature or
2249    /// perform any de-dup checks.
2250    fn add_signature(&mut self, new_signature: SimpleSignature);
2251
2252    /// Returns a mapping from the address each signature commits to, to the
2253    /// signature itself.
2254    fn get_signer_sig_mapping(&self) -> IotaResult<BTreeMap<Address, &UserSignature>>;
2255
2256    /// Returns `true` if any signature is a multisig.
2257    fn has_multisig(&self) -> bool;
2258
2259    /// Returns a mutable reference to the transaction. **Testing only.**
2260    fn transaction_mut_for_testing(&mut self) -> &mut Transaction;
2261
2262    /// Returns a mutable reference to the signatures. **Testing only.**
2263    fn tx_signatures_mut_for_testing(&mut self) -> &mut Vec<UserSignature>;
2264
2265    /// Returns the BCS serialized size in bytes.
2266    fn serialized_size(&self) -> IotaResult<usize>;
2267
2268    /// Validate untrusted user transaction, including its size, input count,
2269    /// command count, etc.
2270    /// Returns the certificate serialised bytes size.
2271    fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> Result<usize, IotaError>;
2272
2273    /// Returns all unique input objects including those from
2274    /// `MoveAuthenticator`s if any for reading, with the packages named by
2275    /// their type arguments if `include_type_arg_packages` is set, in the
2276    /// order the transaction and then each authenticator name them.
2277    ///
2278    /// Although some shared objects (with a different mutability flag, for
2279    /// example) can be duplicated in the transaction and authenticators, each
2280    /// of their distinct kinds is returned, to make it possible to analyze the
2281    /// inputs in the transaction checkers. A caller that reads the inputs must
2282    /// read such an object once for all its kinds: the checkers assert that
2283    /// all kinds of one object got the same read result.
2284    fn collect_all_input_object_kind_for_reading(
2285        &self,
2286        include_type_arg_packages: bool,
2287    ) -> IotaResult<Vec<InputObjectKind>>;
2288
2289    /// Splits the provided input objects, read for the kinds
2290    /// [`Self::collect_all_input_object_kind_for_reading`] returns, into
2291    /// groups:
2292    /// 1. Input objects required by the transaction itself; may contain duplicates if an IOTA coin
2293    ///    is used both as an input and a gas coin.
2294    /// 2. A list of input objects required by each `MoveAuthenticator` (including the object to
2295    ///    authenticate, and the packages named by its type arguments that were read and that the
2296    ///    transaction does not name itself) + the object to authenticate.
2297    fn split_input_objects_into_groups_for_reading(
2298        &self,
2299        input_objects: InputObjects,
2300    ) -> IotaResult<(InputObjects, Vec<(InputObjects, ObjectReadResult)>)>;
2301
2302    /// Checks if [`SenderSignedTransaction`] contains at least one shared
2303    /// object. This function checks shared objects from the
2304    /// `MoveAuthenticator`s if any.
2305    ///
2306    /// Unlike [`Self::shared_input_objects`], it does not combine the shared
2307    /// objects of the transaction and its authenticators, so it does not panic
2308    /// when two of them name the same object with different initial versions.
2309    fn contains_shared_object(&self) -> bool;
2310
2311    /// Returns an iterator over all shared input objects related to this
2312    /// transaction, including those from `MoveAuthenticator`s if any.
2313    ///
2314    /// If a shared object appears with the same version but different
2315    /// mutability, only one instance which is mutable is returned.
2316    ///
2317    /// Panics if there are shared objects with the same ID but different
2318    /// initial versions.
2319    fn shared_input_objects(&self) -> Vec<SharedObjectReference>;
2320
2321    /// Returns an iterator over all input objects related to this
2322    /// transaction, including those from the `MoveAuthenticator`s if any.
2323    ///
2324    /// If an IOTA coin is used both as an input and as a gas coin, it will
2325    /// appear two times in the returned iterator.
2326    ///
2327    /// If a shared object appears both in the transaction and authenticator
2328    /// with different mutability, only one instance which is mutable is
2329    /// returned.
2330    ///
2331    /// Shared objects with the same ID but different versions are not allowed.
2332    ///
2333    /// The packages named by the `MoveAuthenticator`s' type arguments are
2334    /// included if `include_type_arg_packages` is set, each only if no other
2335    /// input has its id.
2336    fn input_objects(&self, include_type_arg_packages: bool) -> IotaResult<Vec<InputObjectKind>>;
2337
2338    /// Checks if [`SenderSignedTransaction`] contains the `Random` object as an
2339    /// input.
2340    /// This function checks shared objects from the `MoveAuthenticator`s if
2341    /// any.
2342    fn uses_randomness(&self) -> bool;
2343}
2344
2345impl SenderSignedTransactionAPI for SenderSignedTransaction {
2346    fn new_from_sender_signature(
2347        tx: Transaction,
2348        tx_signature: SimpleSignature,
2349    ) -> SenderSignedTransaction {
2350        Self::new(tx, vec![tx_signature.into()])
2351    }
2352
2353    fn add_signature(&mut self, new_signature: SimpleSignature) {
2354        self.signed_transaction_mut()
2355            .signatures
2356            .push(new_signature.into());
2357    }
2358
2359    fn get_signer_sig_mapping(&self) -> IotaResult<BTreeMap<Address, &UserSignature>> {
2360        let mut mapping = BTreeMap::new();
2361        for sig in &self.signed_transaction().signatures {
2362            let address = sig.derive_address();
2363            mapping.insert(address, sig);
2364        }
2365        Ok(mapping)
2366    }
2367
2368    fn has_multisig(&self) -> bool {
2369        self.signatures().iter().any(|sig| sig.is_multisig())
2370    }
2371
2372    fn transaction_mut_for_testing(&mut self) -> &mut Transaction {
2373        &mut self.signed_transaction_mut().transaction
2374    }
2375
2376    fn tx_signatures_mut_for_testing(&mut self) -> &mut Vec<UserSignature> {
2377        &mut self.signed_transaction_mut().signatures
2378    }
2379
2380    fn serialized_size(&self) -> IotaResult<usize> {
2381        tx_bcs_size(self)
2382    }
2383
2384    fn validity_check(&self, context: &TxValidityCheckContext<'_>) -> Result<usize, IotaError> {
2385        // Check that the features used by the user signatures are enabled on the
2386        // network.
2387        check_user_signature_protocol_compatibility(self, context.config)?;
2388
2389        // CRITICAL!!
2390        // Users cannot send system transactions.
2391        let tx = self.transaction();
2392        fp_ensure!(
2393            !tx.is_system_tx(),
2394            IotaError::UserInput {
2395                error: UserInputError::Unsupported(
2396                    "SenderSignedTransaction must not contain system transaction".to_string()
2397                )
2398            }
2399        );
2400
2401        // Checks to see if the transaction has expired
2402        if match &tx.expiration() {
2403            TransactionExpiration::None => false,
2404            TransactionExpiration::Epoch(exp_poch) => *exp_poch < context.epoch,
2405            _ => unimplemented!(
2406                "a new TransactionExpiration enum variant was added and needs to be handled"
2407            ),
2408        } {
2409            return Err(IotaError::TransactionExpired);
2410        }
2411
2412        // Enforce overall transaction size limit.
2413        let tx_size = check_transaction_size(self, context.config)?;
2414
2415        tx.validity_check(context.config)
2416            .map_err(Into::<IotaError>::into)?;
2417
2418        // A dependency can only be satisfied within one epoch, so a dependent
2419        // has to expire with the current one. An earlier epoch was refused
2420        // above as expired.
2421        if tx.transaction_dependency().is_some() {
2422            fp_ensure!(
2423                matches!(tx.expiration(), TransactionExpiration::Epoch(epoch) if *epoch == context.epoch),
2424                IotaError::UserInput {
2425                    error: UserInputError::TransactionDependencyRequiresExpiration
2426                }
2427            );
2428        }
2429
2430        move_authenticators_validity_check(self, context.config)?;
2431
2432        Ok(tx_size)
2433    }
2434
2435    fn collect_all_input_object_kind_for_reading(
2436        &self,
2437        include_type_arg_packages: bool,
2438    ) -> IotaResult<Vec<InputObjectKind>> {
2439        let mut seen = HashSet::new();
2440        Ok(self
2441            .transaction()
2442            .input_objects()?
2443            .into_iter()
2444            .chain(
2445                self.move_authenticators()
2446                    .into_iter()
2447                    .flat_map(|authenticator| {
2448                        authenticator.input_objects(include_type_arg_packages)
2449                    }),
2450            )
2451            .filter(|kind| seen.insert(*kind))
2452            .collect())
2453    }
2454
2455    fn split_input_objects_into_groups_for_reading(
2456        &self,
2457        input_objects: InputObjects,
2458    ) -> IotaResult<(InputObjects, Vec<(InputObjects, ObjectReadResult)>)> {
2459        let input_objects_map = input_objects
2460            .iter()
2461            .map(|o| (&o.input_object_kind, o))
2462            .collect::<HashMap<_, _>>();
2463
2464        let tx_input_object_kinds = self.transaction().input_objects()?;
2465        let mut tx_input_objects: InputObjects = tx_input_object_kinds
2466            .iter()
2467            .map(|k| {
2468                input_objects_map
2469                    .get(k)
2470                    .map(|&r| r.clone())
2471                    .expect("All transaction input objects are expected to be present")
2472            })
2473            .collect::<Vec<_>>()
2474            .into();
2475        if let Some((gas_object_id, version)) = input_objects.gas_object_cancellation() {
2476            tx_input_objects.set_gas_object_cancellation(gas_object_id, version);
2477        }
2478        if let Some(dependency) = input_objects.transaction_dependency() {
2479            tx_input_objects.set_transaction_dependency(dependency);
2480        }
2481
2482        let per_authenticator_inputs =
2483            self.move_authenticators()
2484                .into_iter()
2485                .map(|move_authenticator| {
2486                    // The packages named by the type arguments were read only
2487                    // if the protocol config makes them inputs. A package the
2488                    // transaction names itself goes only to the transaction's group.
2489                    let type_arg_packages = move_authenticator
2490                        .type_arg_packages()
2491                        .into_iter()
2492                        .map(InputObjectKind::MovePackage)
2493                        .filter(|k| !tx_input_object_kinds.contains(k))
2494                        .filter_map(|k| input_objects_map.get(&k).map(|&r| r.clone()));
2495                    let authenticator_input_objects = move_authenticator
2496                        .input_objects(false)
2497                        .iter()
2498                        .map(|k| {
2499                            input_objects_map.get(k).map(|&r| r.clone()).expect(
2500                                "All authenticator input objects are expected to be present",
2501                            )
2502                        })
2503                        .chain(type_arg_packages)
2504                        .collect::<Vec<_>>()
2505                        .into();
2506
2507                    let account_objects = move_authenticator
2508                        .object_to_authenticate()
2509                        .input_object_kind()
2510                        .iter()
2511                        .map(|k| {
2512                            input_objects_map
2513                                .get(k)
2514                                .map(|&r| r.clone())
2515                                .expect("Account object is expected to be present")
2516                        })
2517                        .collect::<Vec<_>>();
2518
2519                    debug_assert!(
2520                        account_objects.len() == 1,
2521                        "Only one account object must be loaded"
2522                    );
2523
2524                    (
2525                        authenticator_input_objects,
2526                        account_objects
2527                            .into_iter()
2528                            .next()
2529                            .expect("Account object is expected to be present"),
2530                    )
2531                })
2532                .collect();
2533
2534        Ok((tx_input_objects, per_authenticator_inputs))
2535    }
2536
2537    fn contains_shared_object(&self) -> bool {
2538        self.transaction().kind().contains_shared_object()
2539            || self
2540                .move_authenticators()
2541                .iter()
2542                .any(|move_authenticator| !move_authenticator.shared_objects().is_empty())
2543    }
2544
2545    fn shared_input_objects(&self) -> Vec<SharedObjectReference> {
2546        // Vector is used to preserve the order of input objects.
2547        let mut input_objects = self.transaction().shared_input_objects();
2548
2549        // Add Move authenticator shared objects if any.
2550        self.move_authenticators()
2551            .into_iter()
2552            .for_each(|move_authenticator| {
2553                for auth_shared_object in move_authenticator.shared_objects() {
2554                    let entry = input_objects
2555                        .iter_mut()
2556                        .find(|o| o.object_id == auth_shared_object.object_id);
2557
2558                    match entry {
2559                        None => input_objects.push(auth_shared_object),
2560                        Some(existing) => {
2561                            left_union_shared_input_objects(existing, &auth_shared_object)
2562                                .expect("union of shared objects should not fail")
2563                        }
2564                    }
2565                }
2566            });
2567
2568        input_objects
2569    }
2570
2571    fn input_objects(&self, include_type_arg_packages: bool) -> IotaResult<Vec<InputObjectKind>> {
2572        // Can contain duplicates in case of using the same IOTA coin as an input and as
2573        // a gas coin.
2574        let mut input_objects = self.transaction().input_objects()?;
2575
2576        // Add the `MoveAuthenticator` shared objects if any.
2577        merge_authenticator_input_objects(
2578            self.move_authenticators(),
2579            include_type_arg_packages,
2580            &mut input_objects,
2581        )?;
2582
2583        Ok(input_objects)
2584    }
2585
2586    fn uses_randomness(&self) -> bool {
2587        self.shared_input_objects()
2588            .iter()
2589            .any(|obj| obj.object_id == ObjectId::RANDOMNESS_STATE)
2590    }
2591}
2592
2593fn check_user_signature_protocol_compatibility(
2594    signed_tx: &SenderSignedTransaction,
2595    config: &ProtocolConfig,
2596) -> IotaResult {
2597    for sig in signed_tx.signatures() {
2598        match sig {
2599            UserSignature::PasskeyAuthenticator(_) => {
2600                if !config.passkey_auth() {
2601                    return Err(IotaError::UserInput {
2602                        error: UserInputError::Unsupported(
2603                            "passkey is not enabled on this network".to_string(),
2604                        ),
2605                    });
2606                }
2607            }
2608            UserSignature::MoveAuthenticator(_) => {
2609                if !config.enable_move_authentication() {
2610                    return Err(IotaError::UserInput {
2611                        error: UserInputError::Unsupported(
2612                            "`Move authentication` is not enabled on this network".to_string(),
2613                        ),
2614                    });
2615                }
2616            }
2617            UserSignature::Simple(_) | UserSignature::Multisig(_) => (),
2618            _ => {
2619                unimplemented!("a new UserSignature variant was added and needs to be handled")
2620            }
2621        }
2622    }
2623
2624    Ok(())
2625}
2626
2627/// Rejects a signed transaction that carries a system transaction kind, or an
2628/// identifier move-core rejects: in Move call module and function names, and in
2629/// the type arguments of Move calls, `MakeMoveVector` commands and Move
2630/// authenticators.
2631///
2632/// Independent of the protocol config, so the caller gates it; the consensus
2633/// block verifier uses it to reject exactly the blocks a decoder that follows
2634/// the move-core rules would fail to decode.
2635pub fn transaction_identifiers_validity_check(
2636    signed_tx: &SenderSignedTransaction,
2637) -> UserInputResult {
2638    // A system transaction needs no signature and can carry identifiers in
2639    // genesis objects and events, so it is rejected instead of walked.
2640    fp_ensure!(
2641        !signed_tx.transaction().is_system_tx(),
2642        UserInputError::Unsupported(
2643            "SenderSignedTransaction must not contain system transaction".to_string()
2644        )
2645    );
2646    if let TransactionKind::Programmable(pt) = signed_tx.transaction().kind() {
2647        pt.commands
2648            .iter()
2649            .try_for_each(command_identifiers_validity_check)?;
2650    }
2651    signed_tx
2652        .move_authenticators()
2653        .into_iter()
2654        .try_for_each(move_authenticator_identifiers_validity_check)
2655}
2656
2657fn move_authenticators_validity_check(
2658    signed_tx: &SenderSignedTransaction,
2659    config: &ProtocolConfig,
2660) -> IotaResult {
2661    let authenticators = signed_tx.move_authenticators();
2662
2663    // Check each `MoveAuthenticator` validity.
2664    authenticators
2665        .iter()
2666        .try_for_each(|authenticator| authenticator.validity_check(config))?;
2667
2668    // Additional checks when `MoveAuthenticators` are present.
2669    let authenticators_num = authenticators.len();
2670    if authenticators_num > 0 {
2671        let tx = signed_tx.transaction();
2672
2673        fp_ensure!(
2674            tx.kind().is_programmable(),
2675            UserInputError::Unsupported(
2676                "SenderSignedTransaction with MoveAuthenticator must be a programmable transaction"
2677                    .to_string(),
2678            )
2679            .into()
2680        );
2681
2682        if !config.enable_move_authentication_for_sponsor() {
2683            fp_ensure!(
2684                authenticators_num == 1,
2685                UserInputError::Unsupported(
2686                    "SenderSignedTransaction with more than one MoveAuthenticator is not supported"
2687                        .to_string(),
2688                )
2689                .into()
2690            );
2691
2692            fp_ensure!(
2693                signed_tx.sender_move_authenticator().is_some(),
2694                UserInputError::Unsupported(
2695                    "SenderSignedTransaction can have MoveAuthenticator only for the sender"
2696                        .to_string(),
2697                )
2698                .into()
2699            );
2700        }
2701
2702        check_move_authenticators_input_consistency(
2703            tx,
2704            &authenticators,
2705            config.move_authenticator_type_arg_packages_as_inputs(),
2706        )?;
2707    }
2708
2709    Ok(())
2710}
2711
2712fn check_move_authenticators_input_consistency(
2713    tx: &Transaction,
2714    authenticators: &[&MoveAuthenticator],
2715    include_type_arg_packages: bool,
2716) -> IotaResult {
2717    // Get the input objects from the transaction data kind to skip the gas coins.
2718    let mut checked_inputs = tx
2719        .kind()
2720        .input_objects()?
2721        .into_iter()
2722        .map(|o| (o.object_id(), o))
2723        .collect::<HashMap<_, _>>();
2724
2725    authenticators.iter().try_for_each(|authenticator| {
2726        authenticator
2727            .input_objects(include_type_arg_packages)
2728            .iter()
2729            .try_for_each(|auth_input_object| {
2730                match checked_inputs.get(&auth_input_object.object_id()) {
2731                    Some(existing) => {
2732                        auth_input_object.check_consistency_for_authentication(existing)?
2733                    }
2734                    None => {
2735                        checked_inputs.insert(auth_input_object.object_id(), *auth_input_object);
2736                    }
2737                };
2738
2739                Ok(())
2740            })
2741    })
2742}
2743
2744impl Message for SenderSignedTransaction {
2745    type DigestType = TransactionDigest;
2746    const SCOPE: IntentScope = IntentScope::SenderSignedTransaction;
2747
2748    /// Computes the tx digest that encodes the Rust type prefix from Signable
2749    /// trait.
2750    fn digest(&self) -> Self::DigestType {
2751        self.transaction().digest()
2752    }
2753}
2754
2755impl<S> Envelope<SenderSignedTransaction, S> {
2756    pub fn sender_address(&self) -> Address {
2757        self.data().transaction().sender()
2758    }
2759
2760    pub fn gas(&self) -> &[ObjectReference] {
2761        self.data().transaction().gas()
2762    }
2763
2764    // Returns the primary key for this transaction.
2765    pub fn key(&self) -> TransactionKey {
2766        match &self.data().transaction().kind() {
2767            TransactionKind::RandomnessStateUpdate(rsu) => {
2768                TransactionKey::RandomnessRound(rsu.epoch, rsu.randomness_round)
2769            }
2770            _ => TransactionKey::Digest(*self.digest()),
2771        }
2772    }
2773
2774    // Returns non-Digest keys that could be used to refer to this transaction.
2775    //
2776    // At the moment this returns a single Option for efficiency, but if more key
2777    // types are added, the return type could change to Vec<TransactionKey>.
2778    pub fn non_digest_key(&self) -> Option<TransactionKey> {
2779        match &self.data().transaction().kind() {
2780            TransactionKind::RandomnessStateUpdate(rsu) => Some(TransactionKey::RandomnessRound(
2781                rsu.epoch,
2782                rsu.randomness_round,
2783            )),
2784            _ => None,
2785        }
2786    }
2787
2788    pub fn is_system_tx(&self) -> bool {
2789        self.data().transaction().is_system_tx()
2790    }
2791
2792    pub fn is_sponsored_tx(&self) -> bool {
2793        self.data().transaction().is_sponsored_tx()
2794    }
2795}
2796
2797impl TransactionEnvelope {
2798    pub fn from_data_and_signer(
2799        tx: Transaction,
2800        signers: Vec<&impl iota_sdk_crypto::Signer<SimpleSignature>>,
2801    ) -> Self {
2802        let signatures = {
2803            let digest = tx.signing_digest();
2804            signers.into_iter().map(|s| s.sign(&digest)).collect()
2805        };
2806        Self::from_data(tx, signatures)
2807    }
2808
2809    // TODO: Rename this function and above to make it clearer.
2810    pub fn from_data(tx: Transaction, signatures: Vec<SimpleSignature>) -> Self {
2811        Self::from_user_sig_data(tx, signatures.into_iter().map(|s| s.into()).collect())
2812    }
2813
2814    pub fn signature_from_signer(
2815        tx: Transaction,
2816        intent: Intent,
2817        signer: &impl iota_sdk_crypto::Signer<SimpleSignature>,
2818    ) -> SimpleSignature {
2819        let digest = IntentMessage::new(intent, tx).signing_digest();
2820        signer.sign(&digest)
2821    }
2822
2823    pub fn from_user_sig_data(tx: Transaction, signatures: Vec<UserSignature>) -> Self {
2824        Self::new(SenderSignedTransaction::new(tx, signatures))
2825    }
2826
2827    /// Returns the Base64 encoded tx_bytes
2828    /// and a list of Base64 encoded [`UserSignature`].
2829    pub fn to_tx_bytes_and_signatures(&self) -> (Base64, Vec<Base64>) {
2830        (
2831            Base64::from_bytes(&self.data().transaction().to_bcs()),
2832            self.data()
2833                .signatures()
2834                .iter()
2835                .map(|s| Base64::from_bytes(&s.to_bytes()))
2836                .collect(),
2837        )
2838    }
2839}
2840
2841impl VerifiedTransaction {
2842    pub fn new_genesis_transaction(objects: Vec<GenesisObject>, events: Vec<Event>) -> Self {
2843        GenesisTransaction { objects, events }
2844            .pipe(TransactionKind::Genesis)
2845            .pipe(Self::new_system_transaction)
2846    }
2847
2848    pub fn new_consensus_commit_prologue_v1(
2849        epoch: u64,
2850        round: u64,
2851        commit_timestamp_ms: CheckpointTimestamp,
2852        consensus_commit_digest: ConsensusCommitDigest,
2853        canceled_transactions: Vec<CanceledTransaction>,
2854    ) -> Self {
2855        ConsensusCommitPrologueV1 {
2856            epoch,
2857            round,
2858            // sub_dag_index is reserved for when we have multi commits per round.
2859            sub_dag_index: None,
2860            commit_timestamp_ms,
2861            consensus_commit_digest,
2862            consensus_determined_version_assignments:
2863                ConsensusDeterminedVersionAssignments::CanceledTransactions {
2864                    canceled_transactions,
2865                },
2866        }
2867        .pipe(TransactionKind::ConsensusCommitPrologueV1)
2868        .pipe(Self::new_system_transaction)
2869    }
2870
2871    pub fn new_randomness_state_update(
2872        epoch: u64,
2873        randomness_round: RandomnessRound,
2874        random_bytes: Vec<u8>,
2875        randomness_obj_initial_shared_version: Version,
2876    ) -> Self {
2877        RandomnessStateUpdate {
2878            epoch,
2879            randomness_round,
2880            random_bytes,
2881            randomness_obj_initial_shared_version,
2882        }
2883        .pipe(TransactionKind::RandomnessStateUpdate)
2884        .pipe(Self::new_system_transaction)
2885    }
2886
2887    pub fn new_end_of_epoch_transaction(txns: Vec<EndOfEpochTransactionKind>) -> Self {
2888        TransactionKind::EndOfEpoch(txns).pipe(Self::new_system_transaction)
2889    }
2890
2891    pub fn new_transaction_deny_rules_update(update: TransactionDenyRulesUpdate) -> Self {
2892        TransactionKind::TransactionDenyRulesUpdate(update).pipe(Self::new_system_transaction)
2893    }
2894
2895    fn new_system_transaction(system_transaction: TransactionKind) -> Self {
2896        system_transaction
2897            .pipe(Transaction::new_system_transaction)
2898            .pipe(|data| {
2899                SenderSignedTransaction::new_from_sender_signature(data, zero_ed25519_signature())
2900            })
2901            .pipe(TransactionEnvelope::new)
2902            .pipe(Self::new_from_verified)
2903    }
2904}
2905
2906impl VerifiedSignedTransaction {
2907    /// Use signing key to create a signed object.
2908    #[instrument(level = "trace", skip_all)]
2909    pub fn new(
2910        epoch: EpochId,
2911        transaction: VerifiedTransaction,
2912        authority: AuthorityName,
2913        secret: &dyn Signer<AuthoritySignature>,
2914    ) -> Self {
2915        Self::new_from_verified(SignedTransaction::new(
2916            epoch,
2917            transaction.into_inner().into_data(),
2918            secret,
2919            authority,
2920        ))
2921    }
2922}
2923
2924/// Requires a `ClaimAccount`'s public key to derive the transaction sender,
2925/// the address the claim mints the account object at. A no-op for every
2926/// other transaction kind.
2927///
2928/// This is the authoritative check: a claim that fails it is rejected at
2929/// validation, before it is signed, sequenced or paid for.
2930/// `claim::claim_address` asserts the same in Move, but only at execution.
2931/// Must run after `TransactionKind::validity_check`, which already rejects a
2932/// disabled claim kind, an unknown scheme and malformed key bytes.
2933fn check_claimed_key_derives_sender(data: &Transaction) -> UserInputResult {
2934    let TransactionKind::ClaimAccount(claim) = data.kind() else {
2935        return Ok(());
2936    };
2937    let smart = match &claim.kind {
2938        AccountClaimKind::SmartAccount(smart) => smart,
2939        _ => {
2940            unimplemented!("a new AccountClaimKind enum variant was added and needs to be handled")
2941        }
2942    };
2943
2944    // Infallible here: the kind-level check has already validated both.
2945    let scheme = SignatureScheme::from_byte(smart.public_key_scheme).map_err(|error| {
2946        UserInputError::IncorrectUserSignature {
2947            error: format!("invalid claimed public key: {error}"),
2948        }
2949    })?;
2950    let public_key =
2951        MovePublicKey::new(scheme, smart.public_key_raw_bytes.clone()).map_err(|error| {
2952            UserInputError::IncorrectUserSignature {
2953                error: format!("invalid claimed public key: {error}"),
2954            }
2955        })?;
2956    let derived = public_key
2957        .address()
2958        .map_err(|error| UserInputError::IncorrectUserSignature {
2959            error: format!("invalid claimed public key: {error}"),
2960        })?;
2961    fp_ensure!(
2962        derived == data.sender(),
2963        UserInputError::IncorrectUserSignature {
2964            error: format!(
2965                "claimed public key derives {} but the sender is {}",
2966                derived,
2967                data.sender()
2968            ),
2969        }
2970    );
2971    Ok(())
2972}
2973
2974/// Smallest gas budget a `ClaimAccount` carrying `public_key_len` raw key
2975/// bytes may declare at `gas_price`: the pipeline's computation bound charged
2976/// at that price plus the storage it creates, from the protocol parameters
2977/// `claim_account_max_computation_units` and
2978/// `claim_account_storage_bytes_bound`. Requires
2979/// `enable_claim_account_transaction`.
2980pub fn claim_account_min_gas_budget(
2981    config: &ProtocolConfig,
2982    gas_price: u64,
2983    public_key_len: u64,
2984) -> u64 {
2985    let computation = config
2986        .claim_account_max_computation_units()
2987        .saturating_mul(gas_price);
2988    let storage = config
2989        .claim_account_storage_bytes_bound()
2990        .saturating_add(public_key_len)
2991        .saturating_mul(config.obj_data_cost_refundable())
2992        .saturating_mul(config.storage_gas_price());
2993    computation.saturating_add(storage)
2994}
2995
2996/// [`claim_account_min_gas_budget`] of `data` at its own gas price and key
2997/// size. `None` for every transaction kind other than `ClaimAccount`, and when
2998/// the claim kind is disabled.
2999pub(crate) fn claim_account_min_gas_budget_of_transaction(
3000    data: &Transaction,
3001    config: &ProtocolConfig,
3002) -> Option<u64> {
3003    if !config.enable_claim_account_transaction() {
3004        return None;
3005    }
3006    let TransactionKind::ClaimAccount(claim) = data.kind() else {
3007        return None;
3008    };
3009    let smart = match &claim.kind {
3010        AccountClaimKind::SmartAccount(smart) => smart,
3011        _ => {
3012            unimplemented!("a new AccountClaimKind enum variant was added and needs to be handled")
3013        }
3014    };
3015    // The cost scales with the declared gas price and the key bytes the claim
3016    // stores, so the floor does too.
3017    Some(claim_account_min_gas_budget(
3018        config,
3019        data.gas_price(),
3020        smart.public_key_raw_bytes.len() as u64,
3021    ))
3022}
3023
3024/// Requires a `ClaimAccount`'s gas budget to cover the claim pipeline at the
3025/// transaction's own gas price and key size, so a claim that is accepted
3026/// cannot run out of gas at execution. A no-op for every other transaction
3027/// kind, and when the claim kind is disabled.
3028///
3029/// Reads the gas price and the gas budget, so a simulation can only run it
3030/// once it has filled in the ones its caller left unset.
3031pub fn check_claim_account_gas_budget(
3032    data: &Transaction,
3033    config: &ProtocolConfig,
3034) -> UserInputResult {
3035    let Some(min_budget) = claim_account_min_gas_budget_of_transaction(data, config) else {
3036        return Ok(());
3037    };
3038    fp_ensure!(
3039        data.gas_budget() >= min_budget,
3040        UserInputError::GasBudgetTooLow {
3041            gas_budget: data.gas_budget(),
3042            min_budget,
3043        }
3044    );
3045    Ok(())
3046}
3047
3048/// A transaction that is signed by a sender but not yet by an authority.
3049pub type TransactionEnvelope = Envelope<SenderSignedTransaction, EmptySignInfo>;
3050pub type VerifiedTransaction = VerifiedEnvelope<SenderSignedTransaction, EmptySignInfo>;
3051pub type TrustedTransaction = TrustedEnvelope<SenderSignedTransaction, EmptySignInfo>;
3052
3053/// A transaction that is signed by a sender and also by an authority.
3054pub type SignedTransaction = Envelope<SenderSignedTransaction, AuthoritySignInfo>;
3055pub type VerifiedSignedTransaction = VerifiedEnvelope<SenderSignedTransaction, AuthoritySignInfo>;
3056
3057impl TransactionEnvelope {
3058    pub fn verify_signature_for_testing(&self, verify_params: &VerifyParams) -> IotaResult {
3059        verify_sender_signed_data_message_signatures(self.data(), verify_params)
3060    }
3061
3062    pub fn try_into_verified_for_testing(
3063        self,
3064        verify_params: &VerifyParams,
3065    ) -> IotaResult<VerifiedTransaction> {
3066        self.verify_signature_for_testing(verify_params)?;
3067        Ok(VerifiedTransaction::new_from_verified(self))
3068    }
3069
3070    pub fn gas_price(&self) -> u64 {
3071        self.data().transaction().gas_price()
3072    }
3073}
3074
3075impl SignedTransaction {
3076    pub fn verify_signatures_authenticated_for_testing(
3077        &self,
3078        committee: &Committee,
3079        verify_params: &VerifyParams,
3080    ) -> IotaResult {
3081        verify_sender_signed_data_message_signatures(self.data(), verify_params)?;
3082
3083        self.auth_sig().verify_secure(
3084            self.data(),
3085            Intent::iota_app(IntentScope::SenderSignedTransaction),
3086            committee,
3087        )
3088    }
3089
3090    pub fn try_into_verified_for_testing(
3091        self,
3092        committee: &Committee,
3093        verify_params: &VerifyParams,
3094    ) -> IotaResult<VerifiedSignedTransaction> {
3095        self.verify_signatures_authenticated_for_testing(committee, verify_params)?;
3096        Ok(VerifiedSignedTransaction::new_from_verified(self))
3097    }
3098}
3099
3100pub type CertifiedTransaction = Envelope<SenderSignedTransaction, AuthorityStrongQuorumSignInfo>;
3101
3102impl CertifiedTransaction {
3103    pub fn certificate_digest(&self) -> CertificateDigest {
3104        let mut digest = DefaultHash::default();
3105        bcs::serialize_into(&mut digest, self).expect("serialization should not fail");
3106        let hash = digest.finalize();
3107        CertificateDigest::new(hash.into())
3108    }
3109
3110    pub fn gas_price(&self) -> u64 {
3111        self.data().transaction().gas_price()
3112    }
3113
3114    // TODO: Eventually we should remove all calls to verify_signature
3115    // and make sure they all call verify to avoid repeated verifications.
3116    #[instrument(level = "trace", skip_all)]
3117    pub fn verify_signatures_authenticated(
3118        &self,
3119        committee: &Committee,
3120        verify_params: &VerifyParams,
3121    ) -> IotaResult {
3122        verify_sender_signed_data_message_signatures(self.data(), verify_params)?;
3123        self.verify_committee_sigs_only(committee)
3124    }
3125
3126    pub fn try_into_verified_for_testing(
3127        self,
3128        committee: &Committee,
3129        verify_params: &VerifyParams,
3130    ) -> IotaResult<VerifiedCertificate> {
3131        self.verify_signatures_authenticated(committee, verify_params)?;
3132        Ok(VerifiedCertificate::new_from_verified(self))
3133    }
3134
3135    pub fn verify_committee_sigs_only(&self, committee: &Committee) -> IotaResult {
3136        self.auth_sig().verify_secure(
3137            self.data(),
3138            Intent::iota_app(IntentScope::SenderSignedTransaction),
3139            committee,
3140        )
3141    }
3142}
3143
3144pub type VerifiedCertificate =
3145    VerifiedEnvelope<SenderSignedTransaction, AuthorityStrongQuorumSignInfo>;
3146pub type TrustedCertificate =
3147    TrustedEnvelope<SenderSignedTransaction, AuthorityStrongQuorumSignInfo>;
3148
3149#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, PartialOrd, Ord, Hash)]
3150pub enum InputObjectKind {
3151    // A Move package, must be immutable.
3152    MovePackage(ObjectId),
3153    // A Move object, either immutable, or owned mutable.
3154    ImmOrOwnedMoveObject(ObjectReference),
3155    // A Move object that's shared and mutable.
3156    SharedMoveObject {
3157        id: ObjectId,
3158        initial_shared_version: Version,
3159        mutable: bool,
3160    },
3161}
3162
3163impl InputObjectKind {
3164    pub fn object_id(&self) -> ObjectId {
3165        match self {
3166            Self::MovePackage(id) => *id,
3167            Self::ImmOrOwnedMoveObject(object_ref) => object_ref.object_id,
3168            Self::SharedMoveObject { id, .. } => *id,
3169        }
3170    }
3171
3172    pub fn version(&self) -> Option<Version> {
3173        match self {
3174            Self::MovePackage(..) => None,
3175            Self::ImmOrOwnedMoveObject(object_ref) => Some(object_ref.version),
3176            Self::SharedMoveObject { .. } => None,
3177        }
3178    }
3179
3180    pub fn object_not_found_error(&self) -> UserInputError {
3181        match *self {
3182            Self::MovePackage(package_id) => {
3183                UserInputError::DependentPackageNotFound { package_id }
3184            }
3185            Self::ImmOrOwnedMoveObject(object_ref) => UserInputError::ObjectNotFound {
3186                object_id: object_ref.object_id,
3187                version: Some(object_ref.version),
3188            },
3189            Self::SharedMoveObject { id, .. } => UserInputError::ObjectNotFound {
3190                object_id: id,
3191                version: None,
3192            },
3193        }
3194    }
3195
3196    /// The error for an input that a validator drops at the consensus commit
3197    /// for good: every validator drops it there, and it cannot become
3198    /// available later.
3199    pub fn not_available_at_commit_error(&self) -> UserInputError {
3200        let (object_id, version) = match *self {
3201            Self::MovePackage(package_id) => (package_id, None),
3202            Self::ImmOrOwnedMoveObject(object_ref) => {
3203                (object_ref.object_id, Some(object_ref.version))
3204            }
3205            Self::SharedMoveObject { id, .. } => (id, None),
3206        };
3207        UserInputError::InputObjectNotAvailableAtCommit { object_id, version }
3208    }
3209
3210    pub fn is_shared_object(&self) -> bool {
3211        matches!(self, Self::SharedMoveObject { .. })
3212    }
3213
3214    pub fn is_mutable(&self) -> bool {
3215        match self {
3216            Self::MovePackage(..) => false,
3217            Self::ImmOrOwnedMoveObject(_) => true,
3218            Self::SharedMoveObject { mutable, .. } => *mutable,
3219        }
3220    }
3221
3222    /// Merges another InputObjectKind into self.
3223    ///
3224    /// For shared objects, if either is mutable, the result is mutable. Fails
3225    /// if the IDs or initial versions do not match.
3226    /// For non-shared objects, fails if they are not equal.
3227    pub fn left_union_with_checks(&mut self, other: &InputObjectKind) -> UserInputResult<()> {
3228        match self {
3229            InputObjectKind::MovePackage(_) | InputObjectKind::ImmOrOwnedMoveObject(_) => {
3230                fp_ensure!(
3231                    self == other,
3232                    UserInputError::InconsistentInput {
3233                        object_id: other.object_id(),
3234                    }
3235                );
3236            }
3237            InputObjectKind::SharedMoveObject {
3238                id,
3239                initial_shared_version,
3240                mutable,
3241            } => match other {
3242                InputObjectKind::MovePackage(_) | InputObjectKind::ImmOrOwnedMoveObject(_) => {
3243                    fp_bail!(UserInputError::NotSharedObject)
3244                }
3245                InputObjectKind::SharedMoveObject {
3246                    id: other_id,
3247                    initial_shared_version: other_initial_shared_version,
3248                    mutable: other_mutable,
3249                } => {
3250                    fp_ensure!(id == other_id, UserInputError::SharedObjectIdMismatch);
3251                    fp_ensure!(
3252                        initial_shared_version == other_initial_shared_version,
3253                        UserInputError::SharedObjectStartingVersionMismatch
3254                    );
3255
3256                    if !*mutable && *other_mutable {
3257                        *mutable = *other_mutable;
3258                    }
3259                }
3260            },
3261        }
3262
3263        Ok(())
3264    }
3265
3266    /// Checks that `self` and `other` are equal for non-shared objects.
3267    /// For shared objects, checks that IDs and initial versions match while
3268    /// mutability can be different.
3269    pub fn check_consistency_for_authentication(
3270        &self,
3271        other: &InputObjectKind,
3272    ) -> UserInputResult<()> {
3273        match self {
3274            InputObjectKind::MovePackage(_) | InputObjectKind::ImmOrOwnedMoveObject(_) => {
3275                fp_ensure!(
3276                    self == other,
3277                    UserInputError::InconsistentInput {
3278                        object_id: self.object_id()
3279                    }
3280                );
3281            }
3282            InputObjectKind::SharedMoveObject {
3283                id,
3284                initial_shared_version,
3285                mutable: _,
3286            } => match other {
3287                InputObjectKind::MovePackage(_) | InputObjectKind::ImmOrOwnedMoveObject(_) => {
3288                    fp_bail!(UserInputError::InconsistentInput {
3289                        object_id: self.object_id()
3290                    })
3291                }
3292                InputObjectKind::SharedMoveObject {
3293                    id: other_id,
3294                    initial_shared_version: other_initial_shared_version,
3295                    mutable: _,
3296                } => {
3297                    fp_ensure!(
3298                        id == other_id,
3299                        UserInputError::InconsistentInput { object_id: *id }
3300                    );
3301                    fp_ensure!(
3302                        initial_shared_version == other_initial_shared_version,
3303                        UserInputError::InconsistentInput { object_id: *id }
3304                    );
3305                }
3306            },
3307        }
3308
3309        Ok(())
3310    }
3311}
3312
3313/// The result of reading an object for execution. Because shared objects may be
3314/// deleted, one possible result of reading a shared object is that
3315/// ObjectReadResultKind::Deleted is returned.
3316#[derive(Clone, Debug)]
3317pub struct ObjectReadResult {
3318    pub input_object_kind: InputObjectKind,
3319    pub object: ObjectReadResultKind,
3320}
3321
3322#[derive(Clone, PartialEq)]
3323pub enum ObjectReadResultKind {
3324    Object(Object),
3325    // The version of the object that the transaction intended to read, and the digest of the tx
3326    // that deleted it.
3327    DeletedSharedObject(Version, TransactionDigest),
3328    // A shared object in a cancelled transaction. The sequence number embeds cancellation reason.
3329    CancelledTransactionObject(Version),
3330    // A shared object that exists and is shared at the declared initial version, whose contents
3331    // were not read. Only post-consensus validation lists it: the version and contents a
3332    // validator holds there differ between validators, and execution reads the object at the
3333    // version consensus assigned.
3334    UnreadSharedObject,
3335}
3336
3337impl std::fmt::Debug for ObjectReadResultKind {
3338    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3339        match self {
3340            ObjectReadResultKind::Object(obj) => {
3341                write!(f, "Object({:?})", obj.object_ref())
3342            }
3343            ObjectReadResultKind::DeletedSharedObject(seq, digest) => {
3344                write!(f, "DeletedSharedObject({seq}, {digest})")
3345            }
3346            ObjectReadResultKind::CancelledTransactionObject(seq) => {
3347                write!(f, "CancelledTransactionObject({seq})")
3348            }
3349            ObjectReadResultKind::UnreadSharedObject => write!(f, "UnreadSharedObject"),
3350        }
3351    }
3352}
3353
3354impl From<Object> for ObjectReadResultKind {
3355    fn from(object: Object) -> Self {
3356        Self::Object(object)
3357    }
3358}
3359
3360impl ObjectReadResult {
3361    pub fn new(input_object_kind: InputObjectKind, object: ObjectReadResultKind) -> Self {
3362        if let (
3363            InputObjectKind::ImmOrOwnedMoveObject(_),
3364            ObjectReadResultKind::DeletedSharedObject(_, _),
3365        ) = (&input_object_kind, &object)
3366        {
3367            panic!("only shared objects can be DeletedSharedObject");
3368        }
3369
3370        if let (
3371            InputObjectKind::ImmOrOwnedMoveObject(_),
3372            ObjectReadResultKind::CancelledTransactionObject(_),
3373        ) = (&input_object_kind, &object)
3374        {
3375            panic!("only shared objects can be CancelledTransactionObject");
3376        }
3377
3378        if let (
3379            InputObjectKind::ImmOrOwnedMoveObject(_),
3380            ObjectReadResultKind::UnreadSharedObject,
3381        ) = (&input_object_kind, &object)
3382        {
3383            panic!("only shared objects can be UnreadSharedObject");
3384        }
3385
3386        Self {
3387            input_object_kind,
3388            object,
3389        }
3390    }
3391
3392    pub fn id(&self) -> ObjectId {
3393        self.input_object_kind.object_id()
3394    }
3395
3396    pub fn as_object(&self) -> Option<&Object> {
3397        match &self.object {
3398            ObjectReadResultKind::Object(object) => Some(object),
3399            ObjectReadResultKind::DeletedSharedObject(_, _) => None,
3400            ObjectReadResultKind::CancelledTransactionObject(_) => None,
3401            ObjectReadResultKind::UnreadSharedObject => None,
3402        }
3403    }
3404
3405    /// The version this read resolved to, including deletion and cancellation
3406    /// markers.
3407    pub fn version(&self) -> Version {
3408        match &self.object {
3409            ObjectReadResultKind::Object(object) => object.version(),
3410            ObjectReadResultKind::DeletedSharedObject(version, _) => *version,
3411            ObjectReadResultKind::CancelledTransactionObject(version) => *version,
3412            ObjectReadResultKind::UnreadSharedObject => {
3413                unreachable!("an unread shared object has no version to execute at")
3414            }
3415        }
3416    }
3417
3418    pub fn new_from_gas_object(gas: &Object) -> Self {
3419        let objref = gas.object_ref();
3420        Self {
3421            input_object_kind: InputObjectKind::ImmOrOwnedMoveObject(objref),
3422            object: ObjectReadResultKind::Object(gas.clone()),
3423        }
3424    }
3425
3426    pub fn is_mutable(&self) -> bool {
3427        match (&self.input_object_kind, &self.object) {
3428            (InputObjectKind::MovePackage(_), _) => false,
3429            (InputObjectKind::ImmOrOwnedMoveObject(_), ObjectReadResultKind::Object(object)) => {
3430                !object.is_immutable()
3431            }
3432            (
3433                InputObjectKind::ImmOrOwnedMoveObject(_),
3434                ObjectReadResultKind::DeletedSharedObject(_, _),
3435            ) => unreachable!(),
3436            (
3437                InputObjectKind::ImmOrOwnedMoveObject(_),
3438                ObjectReadResultKind::CancelledTransactionObject(_),
3439            ) => unreachable!(),
3440            (
3441                InputObjectKind::ImmOrOwnedMoveObject(_),
3442                ObjectReadResultKind::UnreadSharedObject,
3443            ) => unreachable!(),
3444            (InputObjectKind::SharedMoveObject { mutable, .. }, _) => *mutable,
3445        }
3446    }
3447
3448    pub fn is_shared_object(&self) -> bool {
3449        self.input_object_kind.is_shared_object()
3450    }
3451
3452    pub fn is_deleted_shared_object(&self) -> bool {
3453        self.deletion_info().is_some()
3454    }
3455
3456    pub fn deletion_info(&self) -> Option<(Version, TransactionDigest)> {
3457        match &self.object {
3458            ObjectReadResultKind::DeletedSharedObject(v, tx) => Some((*v, *tx)),
3459            _ => None,
3460        }
3461    }
3462
3463    /// Return the object ref iff the object is an owned object (i.e. not
3464    /// shared, not immutable).
3465    pub fn get_owned_objref(&self) -> Option<ObjectReference> {
3466        match (&self.input_object_kind, &self.object) {
3467            (InputObjectKind::MovePackage(_), _) => None,
3468            (
3469                InputObjectKind::ImmOrOwnedMoveObject(objref),
3470                ObjectReadResultKind::Object(object),
3471            ) => {
3472                if object.is_immutable() {
3473                    None
3474                } else {
3475                    Some(*objref)
3476                }
3477            }
3478            (
3479                InputObjectKind::ImmOrOwnedMoveObject(_),
3480                ObjectReadResultKind::DeletedSharedObject(_, _),
3481            ) => unreachable!(),
3482            (
3483                InputObjectKind::ImmOrOwnedMoveObject(_),
3484                ObjectReadResultKind::CancelledTransactionObject(_),
3485            ) => unreachable!(),
3486            (
3487                InputObjectKind::ImmOrOwnedMoveObject(_),
3488                ObjectReadResultKind::UnreadSharedObject,
3489            ) => unreachable!(),
3490            (InputObjectKind::SharedMoveObject { .. }, _) => None,
3491        }
3492    }
3493
3494    pub fn is_owned(&self) -> bool {
3495        self.get_owned_objref().is_some()
3496    }
3497
3498    pub fn to_shared_input(&self) -> Option<SharedInput> {
3499        match self.input_object_kind {
3500            InputObjectKind::MovePackage(_) => None,
3501            InputObjectKind::ImmOrOwnedMoveObject(_) => None,
3502            InputObjectKind::SharedMoveObject { id, mutable, .. } => Some(match &self.object {
3503                ObjectReadResultKind::Object(obj) => SharedInput::Existing(obj.object_ref()),
3504                ObjectReadResultKind::DeletedSharedObject(seq, digest) => {
3505                    SharedInput::Deleted((id, *seq, mutable, *digest))
3506                }
3507                ObjectReadResultKind::CancelledTransactionObject(seq) => {
3508                    SharedInput::Cancelled((id, *seq))
3509                }
3510                ObjectReadResultKind::UnreadSharedObject => {
3511                    unreachable!("an unread shared object has no version to execute at")
3512                }
3513            }),
3514        }
3515    }
3516
3517    pub fn get_previous_transaction(&self) -> Option<TransactionDigest> {
3518        match &self.object {
3519            ObjectReadResultKind::Object(obj) => Some(obj.previous_transaction),
3520            ObjectReadResultKind::DeletedSharedObject(_, digest) => Some(*digest),
3521            ObjectReadResultKind::CancelledTransactionObject(_) => None,
3522            ObjectReadResultKind::UnreadSharedObject => None,
3523        }
3524    }
3525}
3526
3527/// The input objects that carry a cancelled transaction's cancellation
3528/// version, and therefore the objects reported to the client as the cause.
3529#[derive(Clone, Debug, PartialEq, Eq)]
3530pub enum CancelledObjects {
3531    /// The transaction's shared inputs, reported as the congested objects.
3532    SharedObjects(Vec<ObjectId>),
3533    /// The gas object of a transaction without shared inputs. Consensus only
3534    /// assigns a cancellation version there when the execution workers are
3535    /// congested, so no individual object is responsible and none is
3536    /// reported.
3537    GasObject,
3538}
3539
3540#[derive(Clone)]
3541pub struct InputObjects {
3542    objects: Vec<ObjectReadResult>,
3543    /// Cancellation version assigned to the gas object when a transaction
3544    /// without shared inputs is cancelled by consensus (execution-worker
3545    /// congestion). Transactions with shared inputs carry cancellation
3546    /// versions on their shared object read results instead. Unlike those,
3547    /// the gas object itself is still read normally, because the cancelled
3548    /// execution must charge gas to it.
3549    gas_object_cancellation: Option<(ObjectId, Version)>,
3550    /// The transaction named by the transaction dependency input, with
3551    /// whether it executed successfully. Set when the input objects are read
3552    /// for execution; absent when the transaction has no dependency or is
3553    /// cancelled at sequencing, which never waits for the dependency.
3554    transaction_dependency: Option<TransactionDependencyReadResult>,
3555}
3556
3557/// The outcome of the transaction named by a transaction dependency input, as
3558/// read when the dependent is executed.
3559#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
3560pub struct TransactionDependencyReadResult {
3561    pub digest: TransactionDigest,
3562    pub succeeded: bool,
3563}
3564
3565impl std::fmt::Debug for InputObjects {
3566    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3567        match (&self.gas_object_cancellation, &self.transaction_dependency) {
3568            (None, None) => f.debug_list().entries(self.objects.iter()).finish(),
3569            (gas_object_cancellation, transaction_dependency) => f
3570                .debug_struct("InputObjects")
3571                .field("objects", &self.objects)
3572                .field("gas_object_cancellation", gas_object_cancellation)
3573                .field("transaction_dependency", transaction_dependency)
3574                .finish(),
3575        }
3576    }
3577}
3578
3579// An InputObjects new-type that has been verified by iota-transaction-checks,
3580// and can be safely passed to execution.
3581pub struct CheckedInputObjects(InputObjects);
3582
3583// DO NOT CALL outside of iota-transaction-checks, genesis, or replay.
3584//
3585// CheckedInputObjects should really be defined in iota-transaction-checks so
3586// that we can make public construction impossible. But we can't do that because
3587// it would result in circular dependencies.
3588impl CheckedInputObjects {
3589    // Only called by iota-transaction-checks.
3590    pub fn new_with_checked_transaction_inputs(inputs: InputObjects) -> Self {
3591        Self(inputs)
3592    }
3593
3594    // Only called when building the genesis transaction
3595    pub fn new_for_genesis(input_objects: Vec<ObjectReadResult>) -> Self {
3596        Self(InputObjects::new(input_objects))
3597    }
3598
3599    // Only called from the replay tool.
3600    pub fn new_for_replay(input_objects: InputObjects) -> Self {
3601        Self(input_objects)
3602    }
3603
3604    pub fn inner(&self) -> &InputObjects {
3605        &self.0
3606    }
3607
3608    pub fn into_inner(self) -> InputObjects {
3609        self.0
3610    }
3611}
3612
3613impl From<Vec<ObjectReadResult>> for InputObjects {
3614    fn from(objects: Vec<ObjectReadResult>) -> Self {
3615        Self::new(objects)
3616    }
3617}
3618
3619impl InputObjects {
3620    pub fn new(objects: Vec<ObjectReadResult>) -> Self {
3621        Self {
3622            objects,
3623            gas_object_cancellation: None,
3624            transaction_dependency: None,
3625        }
3626    }
3627
3628    /// Marks this transaction as cancelled via the version assigned to its
3629    /// gas object. Only valid for transactions without shared inputs; a
3630    /// transaction with shared inputs carries cancellation versions on its
3631    /// shared object read results.
3632    pub fn set_gas_object_cancellation(&mut self, gas_object_id: ObjectId, version: Version) {
3633        assert!(
3634            version.is_canceled(),
3635            "gas object cancellation must use a cancellation version, got {version:?}"
3636        );
3637        assert!(
3638            !self.objects.iter().any(|obj| obj.is_shared_object()),
3639            "transactions with shared inputs carry cancellation on their shared objects"
3640        );
3641        self.gas_object_cancellation = Some((gas_object_id, version));
3642    }
3643
3644    pub fn gas_object_cancellation(&self) -> Option<(ObjectId, Version)> {
3645        self.gas_object_cancellation
3646    }
3647
3648    pub fn len(&self) -> usize {
3649        self.objects.len()
3650    }
3651
3652    pub fn is_empty(&self) -> bool {
3653        self.objects.is_empty()
3654    }
3655
3656    pub fn contains_deleted_objects(&self) -> bool {
3657        self.objects
3658            .iter()
3659            .any(|obj| obj.is_deleted_shared_object())
3660    }
3661
3662    // Returns the objects responsible for a transaction being cancelled, and the
3663    // corresponding reason for cancellation.
3664    pub fn get_cancelled_objects(&self) -> Option<(CancelledObjects, Version)> {
3665        if let Some((_, version)) = &self.gas_object_cancellation {
3666            return Some((CancelledObjects::GasObject, *version));
3667        }
3668
3669        let mut contains_cancelled = false;
3670        let mut cancel_reason = None;
3671        let mut cancelled_objects = Vec::new();
3672        for obj in &self.objects {
3673            if let ObjectReadResultKind::CancelledTransactionObject(version) = obj.object {
3674                contains_cancelled = true;
3675                if version.is_congested() || version == Version::RANDOMNESS_UNAVAILABLE {
3676                    // Verify we don't have multiple cancellation reasons.
3677                    assert!(cancel_reason.is_none() || cancel_reason == Some(version));
3678                    cancel_reason = Some(version);
3679                    cancelled_objects.push(obj.id());
3680                }
3681            }
3682        }
3683
3684        if !cancelled_objects.is_empty() {
3685            Some((
3686                CancelledObjects::SharedObjects(cancelled_objects),
3687                cancel_reason
3688                    .expect("there should be a cancel reason if there are cancelled objects"),
3689            ))
3690        } else {
3691            assert!(!contains_cancelled);
3692            None
3693        }
3694    }
3695
3696    pub fn filter_owned_objects(&self) -> Vec<ObjectReference> {
3697        let owned_objects: Vec<_> = self
3698            .objects
3699            .iter()
3700            .filter_map(|obj| obj.get_owned_objref())
3701            .collect();
3702
3703        trace!(
3704            num_mutable_objects = owned_objects.len(),
3705            "Checked locks and found mutable objects"
3706        );
3707
3708        owned_objects
3709    }
3710
3711    pub fn filter_shared_objects(&self) -> Vec<SharedInput> {
3712        self.objects
3713            .iter()
3714            .filter(|obj| obj.is_shared_object())
3715            .map(|obj| {
3716                obj.to_shared_input()
3717                    .expect("already filtered for shared objects")
3718            })
3719            .collect()
3720    }
3721
3722    pub fn transaction_dependencies(&self) -> BTreeSet<TransactionDigest> {
3723        self.objects
3724            .iter()
3725            .filter_map(|obj| obj.get_previous_transaction())
3726            .chain(
3727                self.transaction_dependency
3728                    .map(|dependency| dependency.digest),
3729            )
3730            .collect()
3731    }
3732
3733    pub fn set_transaction_dependency(&mut self, dependency: TransactionDependencyReadResult) {
3734        self.transaction_dependency = Some(dependency);
3735    }
3736
3737    pub fn transaction_dependency(&self) -> Option<TransactionDependencyReadResult> {
3738        self.transaction_dependency
3739    }
3740
3741    /// The transaction named by the dependency input when it did not execute
3742    /// successfully. This transaction then fails with
3743    /// `TransactionDependencyFailed` without running its commands.
3744    pub fn failed_transaction_dependency(&self) -> Option<TransactionDigest> {
3745        self.transaction_dependency
3746            .filter(|dependency| !dependency.succeeded)
3747            .map(|dependency| dependency.digest)
3748    }
3749
3750    pub fn mutable_inputs(&self) -> BTreeMap<ObjectId, (VersionDigest, Owner)> {
3751        self.objects
3752            .iter()
3753            .filter_map(
3754                |ObjectReadResult {
3755                     input_object_kind,
3756                     object,
3757                 }| match (input_object_kind, object) {
3758                    (InputObjectKind::MovePackage(_), _) => None,
3759                    (
3760                        InputObjectKind::ImmOrOwnedMoveObject(object_ref),
3761                        ObjectReadResultKind::Object(object),
3762                    ) => {
3763                        if object.is_immutable() {
3764                            None
3765                        } else {
3766                            Some((
3767                                object_ref.object_id,
3768                                ((object_ref.version, object_ref.digest), object.owner),
3769                            ))
3770                        }
3771                    }
3772                    (
3773                        InputObjectKind::ImmOrOwnedMoveObject(_),
3774                        ObjectReadResultKind::DeletedSharedObject(_, _),
3775                    ) => {
3776                        unreachable!()
3777                    }
3778                    (
3779                        InputObjectKind::SharedMoveObject { .. },
3780                        ObjectReadResultKind::DeletedSharedObject(_, _),
3781                    ) => None,
3782                    (
3783                        InputObjectKind::SharedMoveObject { mutable, .. },
3784                        ObjectReadResultKind::Object(object),
3785                    ) => {
3786                        if *mutable {
3787                            let oref = object.object_ref();
3788                            Some((oref.object_id, ((oref.version, oref.digest), object.owner)))
3789                        } else {
3790                            None
3791                        }
3792                    }
3793                    (
3794                        InputObjectKind::ImmOrOwnedMoveObject(_),
3795                        ObjectReadResultKind::CancelledTransactionObject(_),
3796                    ) => {
3797                        unreachable!()
3798                    }
3799                    (
3800                        InputObjectKind::SharedMoveObject { .. },
3801                        ObjectReadResultKind::CancelledTransactionObject(_),
3802                    ) => None,
3803                    (
3804                        InputObjectKind::ImmOrOwnedMoveObject(_),
3805                        ObjectReadResultKind::UnreadSharedObject,
3806                    ) => {
3807                        unreachable!()
3808                    }
3809                    (
3810                        InputObjectKind::SharedMoveObject { .. },
3811                        ObjectReadResultKind::UnreadSharedObject,
3812                    ) => {
3813                        unreachable!("an unread shared object has no version, digest or owner")
3814                    }
3815                },
3816            )
3817            .collect()
3818    }
3819
3820    /// The version to set on objects created by the computation that `self` is
3821    /// input to. Guaranteed to be strictly greater than the versions of all
3822    /// input objects and objects received in the transaction.
3823    pub fn lamport_timestamp(&self, receiving_objects: &[ObjectReference]) -> Version {
3824        let input_versions = self
3825            .objects
3826            .iter()
3827            .filter_map(|object| match &object.object {
3828                ObjectReadResultKind::Object(object) => {
3829                    object.data.as_opt_struct().map(MoveStruct::version)
3830                }
3831                ObjectReadResultKind::DeletedSharedObject(v, _) => Some(*v),
3832                ObjectReadResultKind::CancelledTransactionObject(_) => None,
3833                ObjectReadResultKind::UnreadSharedObject => {
3834                    unreachable!("an unread shared object has no version to exceed")
3835                }
3836            })
3837            .chain(
3838                receiving_objects
3839                    .iter()
3840                    .map(|object_ref| object_ref.version),
3841            );
3842
3843        Version::lamport_increment(input_versions).unwrap()
3844    }
3845
3846    pub fn object_kinds(&self) -> impl Iterator<Item = &InputObjectKind> {
3847        self.objects.iter().map(
3848            |ObjectReadResult {
3849                 input_object_kind, ..
3850             }| input_object_kind,
3851        )
3852    }
3853
3854    pub fn into_object_map(self) -> BTreeMap<ObjectId, Object> {
3855        self.objects
3856            .into_iter()
3857            .filter_map(|o| o.as_object().map(|object| (o.id(), object.clone())))
3858            .collect()
3859    }
3860
3861    pub fn push(&mut self, object: ObjectReadResult) {
3862        self.objects.push(object);
3863    }
3864
3865    // If it contains then it returns the ObjectReadResult
3866    pub fn find_object_id_mut(&mut self, object_id: ObjectId) -> Option<&mut ObjectReadResult> {
3867        self.objects.iter_mut().find(|o| o.id() == object_id)
3868    }
3869
3870    pub fn iter(&self) -> impl Iterator<Item = &ObjectReadResult> {
3871        self.objects.iter()
3872    }
3873
3874    pub fn iter_objects(&self) -> impl Iterator<Item = &Object> {
3875        self.objects.iter().filter_map(|o| o.as_object())
3876    }
3877}
3878
3879// Result of attempting to read a receiving object (currently only at signing
3880// time). Because an object may have been previously received and deleted, the
3881// result may be ReceivingObjectReadResultKind::PreviouslyReceivedObject.
3882#[derive(Clone, Debug)]
3883pub enum ReceivingObjectReadResultKind {
3884    Object(Object),
3885    // The object was received by some other transaction, and we were not able to read it
3886    PreviouslyReceivedObject,
3887}
3888
3889impl ReceivingObjectReadResultKind {
3890    pub fn as_object(&self) -> Option<&Object> {
3891        match &self {
3892            Self::Object(object) => Some(object),
3893            Self::PreviouslyReceivedObject => None,
3894        }
3895    }
3896}
3897
3898pub struct ReceivingObjectReadResult {
3899    pub object_ref: ObjectReference,
3900    pub object: ReceivingObjectReadResultKind,
3901}
3902
3903impl ReceivingObjectReadResult {
3904    pub fn new(object_ref: ObjectReference, object: ReceivingObjectReadResultKind) -> Self {
3905        Self { object_ref, object }
3906    }
3907
3908    pub fn is_previously_received(&self) -> bool {
3909        matches!(
3910            self.object,
3911            ReceivingObjectReadResultKind::PreviouslyReceivedObject
3912        )
3913    }
3914}
3915
3916impl From<Object> for ReceivingObjectReadResultKind {
3917    fn from(object: Object) -> Self {
3918        Self::Object(object)
3919    }
3920}
3921
3922pub struct ReceivingObjects {
3923    pub objects: Vec<ReceivingObjectReadResult>,
3924}
3925
3926impl ReceivingObjects {
3927    pub fn iter(&self) -> impl Iterator<Item = &ReceivingObjectReadResult> {
3928        self.objects.iter()
3929    }
3930
3931    pub fn iter_objects(&self) -> impl Iterator<Item = &Object> {
3932        self.objects.iter().filter_map(|o| o.object.as_object())
3933    }
3934}
3935
3936impl From<Vec<ReceivingObjectReadResult>> for ReceivingObjects {
3937    fn from(objects: Vec<ReceivingObjectReadResult>) -> Self {
3938        Self { objects }
3939    }
3940}
3941
3942impl Display for CertifiedTransaction {
3943    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
3944        let mut writer = String::new();
3945        writeln!(writer, "Transaction Hash: {:?}", self.digest())?;
3946        writeln!(
3947            writer,
3948            "Signed Authorities Bitmap : {:?}",
3949            self.auth_sig().signers_map
3950        )?;
3951        write!(writer, "{}", self.data().transaction().kind())?;
3952        write!(f, "{writer}")
3953    }
3954}
3955
3956/// TransactionKey uniquely identifies a transaction across all epochs.
3957/// Note that a single transaction may have multiple keys, for example a
3958/// RandomnessStateUpdate could be identified by both `Digest` and
3959/// `RandomnessRound`.
3960#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
3961pub enum TransactionKey {
3962    Digest(TransactionDigest),
3963    RandomnessRound(EpochId, RandomnessRound),
3964}
3965
3966impl TransactionKey {
3967    pub fn unwrap_digest(&self) -> &TransactionDigest {
3968        match self {
3969            TransactionKey::Digest(d) => d,
3970            _ => panic!("called expect_digest on a non-Digest TransactionKey: {self:?}"),
3971        }
3972    }
3973
3974    pub fn as_digest(&self) -> Option<&TransactionDigest> {
3975        match self {
3976            TransactionKey::Digest(d) => Some(d),
3977            _ => None,
3978        }
3979    }
3980}