Skip to main content

iota_transaction_checks/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5pub mod deny;
6
7pub use checked::*;
8
9#[iota_macros::with_checked_arithmetic]
10mod checked {
11    use std::{
12        collections::{BTreeMap, HashSet},
13        sync::Arc,
14    };
15
16    use iota_config::verifier_signing_config::VerifierSigningConfig;
17    use iota_protocol_config::ProtocolConfig;
18    use iota_sdk_types::{
19        Address, ObjectId, ObjectReference, Owner, Transaction, TransactionKind, Version,
20    };
21    use iota_types::{
22        IOTA_CLOCK_OBJECT_SHARED_VERSION,
23        error::{IotaError, IotaResult, UserInputError, UserInputResult},
24        executable_transaction::VerifiedExecutableTransaction,
25        fp_bail, fp_ensure,
26        gas::IotaGasStatus,
27        metrics::BytecodeVerifierMetrics,
28        object::Object,
29        transaction::{
30            CheckedInputObjects, InputObjectKind, InputObjects, ObjectReadResult,
31            ObjectReadResultKind, ProgrammableTransactionExt, ReceivingObjectReadResult,
32            ReceivingObjects, TransactionAPI,
33        },
34        transaction_executor::InputCheckRules,
35    };
36    use tracing::{error, instrument};
37
38    trait IntoChecked {
39        fn into_checked(self) -> CheckedInputObjects;
40    }
41
42    impl IntoChecked for InputObjects {
43        fn into_checked(self) -> CheckedInputObjects {
44            CheckedInputObjects::new_with_checked_transaction_inputs(self)
45        }
46    }
47
48    // Entry point for all checks related to gas.
49    // Called on both signing and execution.
50    // On success the gas part of the transaction (gas data and gas coins)
51    // is verified and good to go
52    fn get_gas_status(
53        objects: &InputObjects,
54        gas: &[ObjectReference],
55        protocol_config: &ProtocolConfig,
56        reference_gas_price: u64,
57        transaction: &Transaction,
58        authentication_gas_budget: u64,
59        is_execute_transaction_to_effects: bool,
60        input_checks: InputCheckRules,
61    ) -> IotaResult<IotaGasStatus> {
62        if transaction.is_system_tx() {
63            Ok(IotaGasStatus::new_unmetered())
64        } else {
65            check_gas(
66                objects,
67                protocol_config,
68                reference_gas_price,
69                gas,
70                transaction.gas_price(),
71                transaction.gas_budget(),
72                authentication_gas_budget,
73                is_execute_transaction_to_effects,
74                input_checks,
75            )
76        }
77    }
78
79    /// Where the metered bytecode verifier takes its limits from when
80    /// it checks the packages a transaction publishes.
81    #[derive(Clone, Copy, Debug)]
82    pub enum VerifierLimitsSource<'a> {
83        /// The validator's own `VerifierSigningConfig`. Operators may set it
84        /// differently on each validator, so this is only for decisions that
85        /// stay local to one validator: signing, admission, and simulation.
86        NodeConfig(&'a VerifierSigningConfig),
87
88        /// The protocol config, which is the same on every validator. Required
89        /// wherever the verdict has to agree across validators, as in
90        /// post-consensus validation.
91        ProtocolConfig,
92    }
93
94    /// Cheap validity checks for a transaction that has not been through
95    /// signing, to run before any object is loaded.
96    ///
97    /// Rejects a system transaction, then runs the transaction's own validity
98    /// checks except the two on the gas payment objects: that there is at least
99    /// one, and the version check on each of them. A caller can then supply the
100    /// gas payment itself. The limit on the number of gas payment objects still
101    /// applies.
102    ///
103    /// Signing rejects a system transaction before [`check_transaction_input`]
104    /// runs, and [`check_transaction_input`] itself accepts one, so a caller
105    /// with a transaction that has not been signed must call this first.
106    pub fn check_user_transaction_validity(
107        transaction: &Transaction,
108        protocol_config: &ProtocolConfig,
109    ) -> IotaResult {
110        if transaction.kind().is_system() {
111            return Err(IotaError::UnsupportedFeature {
112                error: "system transactions are not supported".to_string(),
113            });
114        }
115        transaction.check_serialized_size(protocol_config)?;
116        transaction.validity_check_no_gas_check(protocol_config)?;
117        transaction.check_gas_payment_size(protocol_config)?;
118        Ok(())
119    }
120
121    /// Checks whether a transaction may be signed or simulated. Certificates go
122    /// through [`check_certificate_input`] or
123    /// [`check_certificate_and_move_authenticator_input`] instead, which apply
124    /// [`InputCheckRules::STRICT`] themselves.
125    ///
126    /// `input_checks` names the checks the caller drops: a simulation with
127    /// [`VmChecks::Disabled`](iota_types::transaction_executor::VmChecks::Disabled)
128    /// passes [`InputCheckRules::RELAXED_UNSAFE`], everything bound for
129    /// execution [`InputCheckRules::STRICT`]. A caller that needs a check
130    /// relaxed must name it in [`InputCheckRules`] rather than validate its
131    /// inputs elsewhere, so that a check added here applies to every caller
132    /// until someone says otherwise.
133    #[instrument(level = "trace", skip_all, fields(tx_digest = ?transaction.digest()))]
134    pub fn check_transaction_input(
135        protocol_config: &ProtocolConfig,
136        reference_gas_price: u64,
137        transaction: &Transaction,
138        input_objects: InputObjects,
139        receiving_objects: &ReceivingObjects,
140        metrics: &Arc<BytecodeVerifierMetrics>,
141        verifier_limits_source: VerifierLimitsSource<'_>,
142        authentication_gas_budget: u64,
143        is_execute_transaction_to_effects: bool,
144        input_checks: InputCheckRules,
145    ) -> IotaResult<(IotaGasStatus, CheckedInputObjects)> {
146        let gas_status = check_transaction_input_inner(
147            protocol_config,
148            reference_gas_price,
149            transaction,
150            &input_objects,
151            &[],
152            authentication_gas_budget,
153            is_execute_transaction_to_effects,
154            input_checks,
155        )?;
156        check_receiving_objects(&input_objects, receiving_objects, input_checks)?;
157        // Runs verifier, which could be expensive.
158        check_non_system_packages_to_be_published(
159            transaction,
160            protocol_config,
161            metrics,
162            verifier_limits_source,
163        )?;
164
165        Ok((gas_status, input_objects.into_checked()))
166    }
167
168    #[instrument(level = "trace", skip_all, fields(tx_digest = ?transaction.digest()))]
169    pub fn check_transaction_input_with_given_gas(
170        protocol_config: &ProtocolConfig,
171        reference_gas_price: u64,
172        transaction: &Transaction,
173        mut input_objects: InputObjects,
174        receiving_objects: ReceivingObjects,
175        gas_object: Object,
176        metrics: &Arc<BytecodeVerifierMetrics>,
177        verifier_limits_source: VerifierLimitsSource<'_>,
178    ) -> IotaResult<(IotaGasStatus, CheckedInputObjects)> {
179        let gas_object_ref = gas_object.object_ref();
180        input_objects.push(ObjectReadResult::new_from_gas_object(&gas_object));
181
182        let gas_status = check_transaction_input_inner(
183            protocol_config,
184            reference_gas_price,
185            transaction,
186            &input_objects,
187            &[gas_object_ref],
188            0,
189            true,
190            InputCheckRules::STRICT,
191        )?;
192        check_receiving_objects(&input_objects, &receiving_objects, InputCheckRules::STRICT)?;
193        // Runs verifier, which could be expensive.
194        check_non_system_packages_to_be_published(
195            transaction,
196            protocol_config,
197            metrics,
198            verifier_limits_source,
199        )?;
200
201        Ok((gas_status, input_objects.into_checked()))
202    }
203
204    // Since the purpose of this function is to audit certified transactions,
205    // the checks here should be a strict subset of the checks in
206    // check_transaction_input(). For checks not performed in this function but
207    // in check_transaction_input(), we should add a comment calling out the
208    // difference.
209    #[instrument(level = "trace", skip_all)]
210    pub fn check_certificate_input(
211        cert: &VerifiedExecutableTransaction,
212        input_objects: InputObjects,
213        protocol_config: &ProtocolConfig,
214        reference_gas_price: u64,
215    ) -> IotaResult<(IotaGasStatus, CheckedInputObjects)> {
216        let transaction = cert.data().transaction();
217        let gas_status = check_transaction_input_inner(
218            protocol_config,
219            reference_gas_price,
220            transaction,
221            &input_objects,
222            &[],
223            0,
224            true,
225            InputCheckRules::STRICT,
226        )?;
227        // NB: We do not check receiving objects when executing. Only at signing
228        // time do we check. NB: move verifier is only checked at
229        // signing time, not at execution.
230
231        Ok((gas_status, input_objects.into_checked()))
232    }
233
234    /// A common function to check the `MoveAuthenticator` inputs for signing.
235    ///
236    /// Checks that the authenticator inputs meet the requirements and returns
237    /// checked authenticator input objects, among which we also find the
238    /// account object.
239    #[instrument(level = "trace", skip_all)]
240    pub fn check_move_authenticator_input_for_validation(
241        authenticator_input_objects: InputObjects,
242    ) -> IotaResult<CheckedInputObjects> {
243        check_move_authenticator_objects(&authenticator_input_objects)?;
244
245        Ok(authenticator_input_objects.into_checked())
246    }
247
248    /// A function to aggregate the checked authenticator input objects for
249    /// multiple `MoveAuthenticators` into one `CheckedInputObjects` to be used
250    /// for execution.
251    pub fn aggregate_authenticator_input_objects(
252        per_authenticator_checked_input_objects: &[&CheckedInputObjects],
253    ) -> IotaResult<CheckedInputObjects> {
254        let mut aggregated_authenticator_input_objects =
255            CheckedInputObjects::new_with_checked_transaction_inputs(InputObjects::new(vec![]));
256
257        for authenticator_checked_input_objects in per_authenticator_checked_input_objects.iter() {
258            aggregated_authenticator_input_objects = checked_input_objects_union(
259                aggregated_authenticator_input_objects,
260                authenticator_checked_input_objects,
261            )?;
262        }
263
264        Ok(aggregated_authenticator_input_objects)
265    }
266
267    /// Checks the inputs of a transaction bound for execution: the Move
268    /// authenticator inputs, gas, the transaction's own inputs and their
269    /// union, and the receiving objects when given. Returns an execution-mode
270    /// gas status plus the checked input objects. Post-consensus validation of
271    /// an attested transaction runs this same function, with the receiving
272    /// objects it loaded, so the two cannot drift; execution gives none, since
273    /// the Move runtime resolves receives.
274    #[instrument(level = "trace", skip_all)]
275    pub fn check_certificate_and_move_authenticator_input(
276        transaction: &Transaction,
277        tx_input_objects: InputObjects,
278        per_authenticator_input_objects: Vec<InputObjects>,
279        receiving_objects: Option<&ReceivingObjects>,
280        authenticator_gas_budget: u64,
281        protocol_config: &ProtocolConfig,
282        reference_gas_price: u64,
283    ) -> IotaResult<(IotaGasStatus, Vec<CheckedInputObjects>, CheckedInputObjects)> {
284        // Check Move authenticator inputs first.
285        per_authenticator_input_objects
286            .iter()
287            .try_for_each(check_move_authenticator_objects)?;
288
289        // Check transaction inputs next.
290        let gas_status = check_transaction_input_inner(
291            protocol_config,
292            reference_gas_price,
293            transaction,
294            &tx_input_objects,
295            &[],
296            authenticator_gas_budget,
297            true, // execution mode — full transaction_gas_budget
298            InputCheckRules::STRICT,
299        )?;
300        if let Some(receiving_objects) = receiving_objects {
301            check_receiving_objects(
302                &tx_input_objects,
303                receiving_objects,
304                InputCheckRules::STRICT,
305            )?;
306        }
307
308        let per_authenticator_checked_input_objects = per_authenticator_input_objects
309            .into_iter()
310            .map(|objects| objects.into_checked())
311            .collect::<Vec<_>>();
312
313        // Create a checked union of input objects.
314        let mut input_objects_union = tx_input_objects.into_checked();
315        for objects in per_authenticator_checked_input_objects.iter() {
316            input_objects_union = checked_input_objects_union(input_objects_union, objects)?;
317        }
318
319        Ok((
320            gas_status,
321            per_authenticator_checked_input_objects,
322            input_objects_union,
323        ))
324    }
325
326    // Common checks performed for transactions and certificates.
327    fn check_transaction_input_inner(
328        protocol_config: &ProtocolConfig,
329        reference_gas_price: u64,
330        transaction: &Transaction,
331        input_objects: &InputObjects,
332        // Overrides the gas objects in the transaction.
333        gas_override: &[ObjectReference],
334        authentication_gas_budget: u64,
335        is_execute_transaction_to_effects: bool,
336        input_checks: InputCheckRules,
337    ) -> IotaResult<IotaGasStatus> {
338        // Cheap validity checks that is ok to run multiple times during processing.
339        let gas = if gas_override.is_empty() {
340            transaction.gas()
341        } else {
342            gas_override
343        };
344
345        let gas_status = get_gas_status(
346            input_objects,
347            gas,
348            protocol_config,
349            reference_gas_price,
350            transaction,
351            authentication_gas_budget,
352            is_execute_transaction_to_effects,
353            input_checks,
354        )?;
355        check_objects(transaction, input_objects, input_checks)?;
356
357        Ok(gas_status)
358    }
359
360    fn input_object_ids(input_objects: &InputObjects) -> HashSet<ObjectId> {
361        input_objects
362            .object_kinds()
363            .map(|x| x.object_id())
364            .collect()
365    }
366
367    fn check_receiving_version_bound(object_ref: &ObjectReference) -> Result<(), IotaError> {
368        fp_ensure!(
369            object_ref.version < Version::MAX_VALID_EXCL,
370            UserInputError::InvalidSequenceNumber.into()
371        );
372        Ok(())
373    }
374
375    fn check_not_already_in_transaction(
376        objects_in_txn: &mut HashSet<ObjectId>,
377        object_ref: &ObjectReference,
378    ) -> Result<(), IotaError> {
379        fp_ensure!(
380            objects_in_txn.insert(object_ref.object_id),
381            UserInputError::DuplicateObjectRefInput.into()
382        );
383        Ok(())
384    }
385
386    /// Checks the receiving references against the objects they name.
387    ///
388    /// Two separable things happen here. Whether each reference is current —
389    /// its version and digest match the loaded object — can be dropped per
390    /// half by
391    /// [`InputCheckRules::any_receiving_object_version`] and
392    /// [`InputCheckRules::any_receiving_object_digest`].
393    /// What the object is, and that no reference duplicates another or collides
394    /// with an input object, is not relaxed by anything: the duplicate
395    /// rejection below is the only one there is, since `CallArg::Receiving`
396    /// is not part of `input_objects()` and so escapes its
397    /// `DuplicateObjectRefInput` dedup. Without it a duplicated receiving
398    /// ticket reaches the object runtime, which treats receiving the same
399    /// object twice as impossible.
400    #[instrument(level = "trace", skip_all)]
401    fn check_receiving_objects(
402        input_objects: &InputObjects,
403        receiving_objects: &ReceivingObjects,
404        input_checks: InputCheckRules,
405    ) -> Result<(), IotaError> {
406        let mut objects_in_txn = input_object_ids(input_objects);
407
408        // Since we're at signing we check that every object reference that we are
409        // receiving is the most recent version of that object. If it's been
410        // received at the version specified we let it through to allow the
411        // transaction to run and fail to unlock any other objects in
412        // the transaction. Otherwise, we return an error.
413        //
414        // If there are any object IDs in common (either between receiving objects and
415        // input objects) we return an error.
416        for ReceivingObjectReadResult { object_ref, object } in receiving_objects.iter() {
417            check_receiving_version_bound(object_ref)?;
418
419            let Some(object) = object.as_object() else {
420                // object was previously received
421                continue;
422            };
423
424            // A reference is fine if it names an address-owned object and matches
425            // it on both counts the caller still cares about, so the block below
426            // is for the ones that are not. Relax each equality here rather than
427            // reordering the block: which error a caller gets when a reference
428            // fails more than one test is observable.
429            //
430            // Keep the two conditions in step with the two `fp_ensure!`s inside.
431            // The trailing `match object.owner` has no gate of its own, and its
432            // `Owner::Address` arm is a `debug_assert!(false)` — dead only
433            // because every path that enters here with an address owner bails at
434            // whichever `fp_ensure!` let it in. Skipping a test while still
435            // admitting the references it would have rejected makes that arm
436            // reachable, which panics in a debug build.
437            if !(object.owner.is_address()
438                && (input_checks.any_receiving_object_version
439                    || object.version() == object_ref.version)
440                && (input_checks.any_receiving_object_digest
441                    || object.digest() == object_ref.digest))
442            {
443                if !input_checks.any_receiving_object_version {
444                    // Version mismatch
445                    fp_ensure!(
446                        object.version() == object_ref.version,
447                        UserInputError::ObjectVersionUnavailableForConsumption {
448                            provided_obj_ref: *object_ref,
449                            current_version: object.version(),
450                        }
451                        .into()
452                    );
453                }
454
455                // Tried to receive a package
456                fp_ensure!(
457                    !object.is_package(),
458                    UserInputError::MovePackageAsObject {
459                        object_id: object_ref.object_id
460                    }
461                    .into()
462                );
463
464                if !input_checks.any_receiving_object_digest {
465                    // Digest mismatch
466                    let expected_digest = object.digest();
467                    fp_ensure!(
468                        expected_digest == object_ref.digest,
469                        UserInputError::InvalidObjectDigest {
470                            object_id: object_ref.object_id,
471                            expected_digest
472                        }
473                        .into()
474                    );
475                }
476
477                match object.owner {
478                    Owner::Address(_) => {
479                        debug_assert!(
480                            false,
481                            "Receiving object {object_ref:?} is invalid but we expect it should be valid. {object:?}"
482                        );
483                        error!(
484                            "Receiving object {:?} is invalid but we expect it should be valid. {:?}",
485                            object_ref, object
486                        );
487                        // We should never get here, but if for some reason we do just default to
488                        // object not found and reject signing the transaction.
489                        fp_bail!(
490                            UserInputError::ObjectNotFound {
491                                object_id: object_ref.object_id,
492                                version: Some(object_ref.version),
493                            }
494                            .into()
495                        )
496                    }
497                    Owner::Object(owner) => {
498                        fp_bail!(
499                            UserInputError::InvalidChildObjectArgument {
500                                child_id: object.id(),
501                                parent_id: owner,
502                            }
503                            .into()
504                        )
505                    }
506                    Owner::Shared(_) => fp_bail!(UserInputError::NotSharedObject.into()),
507                    Owner::Immutable => fp_bail!(
508                        UserInputError::MutableParameterExpected {
509                            object_id: object_ref.object_id
510                        }
511                        .into()
512                    ),
513                    _ => {
514                        unimplemented!("a new Owner enum variant was added and needs to be handled")
515                    }
516                };
517            }
518
519            check_not_already_in_transaction(&mut objects_in_txn, object_ref)?;
520        }
521        Ok(())
522    }
523
524    /// Check transaction gas data/info and gas coins consistency.
525    /// Return the gas status to be used for the lifecycle of the transaction.
526    #[instrument(level = "trace", skip_all)]
527    fn check_gas(
528        objects: &InputObjects,
529        protocol_config: &ProtocolConfig,
530        reference_gas_price: u64,
531        gas: &[ObjectReference],
532        gas_price: u64,
533        transaction_gas_budget: u64,
534        authentication_gas_budget: u64,
535        is_execute_transaction_to_effects: bool,
536        input_checks: InputCheckRules,
537    ) -> IotaResult<IotaGasStatus> {
538        let gas_budget_to_set = if authentication_gas_budget > 0 {
539            // If there is an authentication gas budget, then we are checking if
540            // max_gas_budget is Some. If not, that is UserInputError.
541            let protocol_max_auth_gas =
542                protocol_config.max_auth_gas_as_option().ok_or_else(|| {
543                    UserInputError::Unsupported(
544                        "Transaction requires authentication gas but max_auth_gas is not enabled"
545                            .to_string(),
546                    )
547                })?;
548
549            // Execution phase:
550            //  - meter transaction + authentication;
551            //  - it needs the full budget.
552            // Signing phase:
553            //  - meter only authentication;
554            //  - it only needs authentication budget.
555            if is_execute_transaction_to_effects {
556                transaction_gas_budget
557            } else {
558                authentication_gas_budget.min(protocol_max_auth_gas)
559            }
560        } else {
561            // If there is no authentication gas budget, then we are only checking the
562            // transaction gas budget.
563            transaction_gas_budget
564        };
565
566        // Budget to check is always the one set by the user (which should cover full
567        // transaction + authentication costs).
568        let gas_budget_to_check = transaction_gas_budget;
569
570        let gas_status = IotaGasStatus::new(
571            gas_budget_to_set,
572            gas_price,
573            reference_gas_price,
574            protocol_config,
575        )?;
576
577        // Check balance and coins consistency
578        // Load all gas coins
579        let objects: BTreeMap<_, _> = objects.iter().map(|o| (o.id(), o)).collect();
580        let mut gas_objects = vec![];
581        for obj_ref in gas {
582            let obj = objects.get(&obj_ref.object_id);
583            let obj = *obj.ok_or(UserInputError::ObjectNotFound {
584                object_id: obj_ref.object_id,
585                version: Some(obj_ref.version),
586            })?;
587            gas_objects.push(obj);
588        }
589        gas_status.check_gas_balance(
590            &gas_objects,
591            gas_budget_to_check,
592            !input_checks.unbounded_gas_budget,
593        )?;
594        Ok(gas_status)
595    }
596
597    /// Check all the objects used in the transaction against the database, and
598    /// ensure that they are all the correct version and number.
599    #[instrument(level = "trace", skip_all)]
600    fn check_objects(
601        transaction: &Transaction,
602        objects: &InputObjects,
603        input_checks: InputCheckRules,
604    ) -> UserInputResult<()> {
605        // We require that mutable objects cannot show up more than once.
606        let mut used_objects: HashSet<Address> = HashSet::new();
607        for object in objects.iter() {
608            if object.is_mutable() {
609                fp_ensure!(
610                    used_objects.insert(object.id().into()),
611                    UserInputError::MutableObjectUsedMoreThanOnce {
612                        object_id: object.id()
613                    }
614                );
615            }
616        }
617
618        if !transaction.is_genesis_tx() && objects.is_empty() {
619            return Err(UserInputError::ObjectInputArityViolation);
620        }
621
622        let gas_coins: HashSet<ObjectId> =
623            HashSet::from_iter(transaction.gas().iter().map(|obj_ref| obj_ref.object_id));
624        for object in objects.iter() {
625            let input_object_kind = object.input_object_kind;
626
627            match &object.object {
628                ObjectReadResultKind::Object(object) => {
629                    // For Gas Object, we check the object is owned by gas owner
630                    let owner_address = if gas_coins.contains(&object.id()) {
631                        transaction.gas_owner()
632                    } else {
633                        transaction.sender()
634                    };
635                    // Check if the object contents match the type of lock we need for
636                    // this object.
637                    let system_transaction = transaction.is_system_tx();
638                    check_one_object(
639                        &owner_address,
640                        input_object_kind,
641                        object,
642                        system_transaction,
643                        input_checks,
644                    )?;
645                }
646                // We skip checking a deleted shared object because it no longer exists
647                ObjectReadResultKind::DeletedSharedObject(_, _) => (),
648                // We skip checking shared objects from cancelled transactions since we are not
649                // reading it.
650                ObjectReadResultKind::CancelledTransactionObject(_) => (),
651                // An unread shared object has no contents to check. Only the rules on how
652                // the transaction declares it apply.
653                ObjectReadResultKind::UnreadSharedObject => {
654                    check_shared_object_declaration(
655                        &input_object_kind,
656                        transaction.is_system_tx(),
657                        input_checks,
658                    )?;
659                }
660            }
661        }
662
663        Ok(())
664    }
665
666    /// Check one object against a reference
667    fn check_one_object(
668        owner: &Address,
669        object_kind: InputObjectKind,
670        object: &Object,
671        system_transaction: bool,
672        input_checks: InputCheckRules,
673    ) -> UserInputResult {
674        match object_kind {
675            InputObjectKind::MovePackage(package_id) => {
676                fp_ensure!(
677                    object.data.as_opt_package().is_some(),
678                    UserInputError::MoveObjectAsPackage {
679                        object_id: package_id
680                    }
681                );
682            }
683            InputObjectKind::ImmOrOwnedMoveObject(object_ref) => {
684                fp_ensure!(
685                    !object.is_package(),
686                    UserInputError::MovePackageAsObject {
687                        object_id: object_ref.object_id
688                    }
689                );
690                fp_ensure!(
691                    object_ref.version < Version::MAX_VALID_EXCL,
692                    UserInputError::InvalidSequenceNumber
693                );
694
695                // This is an invariant - we just load the object with the given ID and version.
696                assert_eq!(
697                    object.version(),
698                    object_ref.version,
699                    "The fetched object version {} does not match the requested version {}, object id: {}",
700                    object.version(),
701                    object_ref.version,
702                    object.id(),
703                );
704
705                // Check the digest matches - user could give a mismatched ObjectDigest
706                if !input_checks.any_object_digest {
707                    let expected_digest = object.digest();
708                    fp_ensure!(
709                        expected_digest == object_ref.digest,
710                        UserInputError::InvalidObjectDigest {
711                            object_id: object_ref.object_id,
712                            expected_digest
713                        }
714                    );
715                }
716
717                match object.owner {
718                    Owner::Immutable => {
719                        // Nothing else to check for Immutable.
720                    }
721                    Owner::Address(actual_owner) => {
722                        // Check the owner is correct.
723                        if !input_checks.any_object_owner {
724                            fp_ensure!(
725                                owner == &actual_owner,
726                                UserInputError::IncorrectUserSignature {
727                                    error: format!(
728                                        "Object {} is owned by account address {}, but given owner/signer address is {}",
729                                        object_ref.object_id, actual_owner, owner
730                                    ),
731                                }
732                            );
733                        }
734                    }
735                    Owner::Object(owner) => {
736                        return Err(UserInputError::InvalidChildObjectArgument {
737                            child_id: object.id(),
738                            parent_id: owner,
739                        });
740                    }
741                    Owner::Shared(_) => {
742                        // This object is a mutable shared object. However the transaction
743                        // specifies it as an owned object. This is inconsistent.
744                        //
745                        // The relaxation stays off for the system objects
746                        // `check_shared_object_declaration` restricts, since it matches on
747                        // the declared input kind and an owned input would never reach it.
748                        fp_ensure!(
749                            input_checks.shared_object_as_owned_input
750                                && !is_restricted_system_object(object_ref.object_id),
751                            UserInputError::NotSharedObject
752                        );
753                    }
754                    _ => {
755                        unimplemented!("a new Owner enum variant was added and needs to be handled")
756                    }
757                };
758            }
759            InputObjectKind::SharedMoveObject {
760                initial_shared_version: input_initial_shared_version,
761                ..
762            } => {
763                if check_shared_object_declaration(&object_kind, system_transaction, input_checks)?
764                {
765                    return Ok(());
766                }
767
768                fp_ensure!(
769                    object.version() < Version::MAX_VALID_EXCL,
770                    UserInputError::InvalidSequenceNumber
771                );
772
773                match object.owner {
774                    Owner::Address(_) | Owner::Object(_) | Owner::Immutable => {
775                        // When someone locks an object as shared it must be shared already.
776                        return Err(UserInputError::NotSharedObject);
777                    }
778                    Owner::Shared(actual_initial_shared_version) => {
779                        fp_ensure!(
780                            input_checks.any_initial_shared_version
781                                || input_initial_shared_version == actual_initial_shared_version,
782                            UserInputError::SharedObjectStartingVersionMismatch
783                        )
784                    }
785                    _ => {
786                        unimplemented!("a new Owner enum variant was added and needs to be handled")
787                    }
788                }
789            }
790        };
791
792        Ok(())
793    }
794
795    /// Checks a shared input against the rules on system objects, which depend
796    /// only on how the transaction declares it: only a system transaction may
797    /// name the authenticator state or the deny rules object, or name the clock
798    /// or the randomness state as mutable. Fails if a rule forbids the input.
799    /// Returns `true` if a rule allows it, so no further check is needed, and
800    /// `false` if no rule covers it.
801    ///
802    /// With [`InputCheckRules::any_initial_shared_version`] set, a mutable
803    /// clock is rejected whatever initial shared version it is declared with.
804    fn check_shared_object_declaration(
805        object_kind: &InputObjectKind,
806        system_transaction: bool,
807        input_checks: InputCheckRules,
808    ) -> UserInputResult<bool> {
809        match object_kind {
810            InputObjectKind::SharedMoveObject {
811                id: ObjectId::CLOCK,
812                initial_shared_version,
813                mutable: true,
814            } if *initial_shared_version == IOTA_CLOCK_OBJECT_SHARED_VERSION
815                || input_checks.any_initial_shared_version =>
816            {
817                // Only system transactions can accept the Clock
818                // object as a mutable parameter.
819                if system_transaction {
820                    Ok(true)
821                } else {
822                    Err(UserInputError::ImmutableParameterExpected {
823                        object_id: ObjectId::CLOCK,
824                    })
825                }
826            }
827            InputObjectKind::SharedMoveObject {
828                id: ObjectId::AUTHENTICATOR_STATE,
829                ..
830            } => {
831                if system_transaction {
832                    Ok(true)
833                } else {
834                    Err(UserInputError::InaccessibleSystemObject {
835                        object_id: ObjectId::AUTHENTICATOR_STATE,
836                    })
837                }
838            }
839            InputObjectKind::SharedMoveObject {
840                id: ObjectId::RANDOMNESS_STATE,
841                mutable: true,
842                ..
843            } => {
844                // Only system transactions can accept the Random
845                // object as a mutable parameter.
846                if system_transaction {
847                    Ok(true)
848                } else {
849                    Err(UserInputError::ImmutableParameterExpected {
850                        object_id: ObjectId::RANDOMNESS_STATE,
851                    })
852                }
853            }
854            InputObjectKind::SharedMoveObject {
855                id: ObjectId::TRANSACTION_DENY_RULES,
856                ..
857            } => {
858                // The deny rules object is written only by system
859                // transactions and has no user-callable readers.
860                if system_transaction {
861                    Ok(true)
862                } else {
863                    Err(UserInputError::InaccessibleSystemObject {
864                        object_id: ObjectId::TRANSACTION_DENY_RULES,
865                    })
866                }
867            }
868            _ => Ok(false),
869        }
870    }
871
872    /// Whether [`check_shared_object_declaration`] restricts how a user
873    /// transaction may take this object as an input.
874    fn is_restricted_system_object(id: ObjectId) -> bool {
875        matches!(
876            id,
877            ObjectId::CLOCK
878                | ObjectId::RANDOMNESS_STATE
879                | ObjectId::AUTHENTICATOR_STATE
880                | ObjectId::TRANSACTION_DENY_RULES
881        )
882    }
883
884    /// Check all the `MoveAuthenticator` related input objects against the
885    /// database. An unread shared object is checked only on how it is
886    /// declared.
887    #[instrument(level = "trace", skip_all)]
888    fn check_move_authenticator_objects(
889        authenticator_objects: &InputObjects,
890    ) -> UserInputResult<()> {
891        for object in authenticator_objects.iter() {
892            let input_object_kind = object.input_object_kind;
893
894            match &object.object {
895                ObjectReadResultKind::Object(object) => {
896                    check_one_move_authenticator_object(input_object_kind, object)?;
897                }
898                // We skip checking a deleted shared object because it no longer exists.
899                ObjectReadResultKind::DeletedSharedObject(_, _) => (),
900                // We skip checking shared objects from cancelled transactions since we are not
901                // reading it.
902                ObjectReadResultKind::CancelledTransactionObject(_) => (),
903                // An unread shared object has no contents to check. Only the rules on how
904                // the authenticator declares it apply.
905                ObjectReadResultKind::UnreadSharedObject => {
906                    check_move_authenticator_shared_object_declaration(&input_object_kind)?;
907                }
908            }
909        }
910
911        Ok(())
912    }
913
914    /// Check one `MoveAuthenticator` input object.
915    fn check_one_move_authenticator_object(
916        object_kind: InputObjectKind,
917        object: &Object,
918    ) -> UserInputResult {
919        match object_kind {
920            InputObjectKind::MovePackage(package_id) => {
921                fp_ensure!(
922                    object.data.as_opt_package().is_some(),
923                    UserInputError::MoveObjectAsPackage {
924                        object_id: package_id
925                    }
926                );
927            }
928            InputObjectKind::ImmOrOwnedMoveObject(object_ref) => {
929                fp_ensure!(
930                    !object.is_package(),
931                    UserInputError::MovePackageAsObject {
932                        object_id: object_ref.object_id
933                    }
934                );
935                fp_ensure!(
936                    object_ref.version < Version::MAX_VALID_EXCL,
937                    UserInputError::InvalidSequenceNumber
938                );
939
940                // This is an invariant - we just load the object with the given ID and version.
941                assert_eq!(
942                    object.version(),
943                    object_ref.version,
944                    "The fetched object version {} does not match the requested version {}, object id: {}",
945                    object.version(),
946                    object_ref.version,
947                    object.id(),
948                );
949
950                // Check the digest matches - user could give a mismatched `ObjectDigest`.
951                let expected_digest = object.digest();
952                fp_ensure!(
953                    expected_digest == object_ref.digest,
954                    UserInputError::InvalidObjectDigest {
955                        object_id: object_ref.object_id,
956                        expected_digest
957                    }
958                );
959
960                match object.owner {
961                    Owner::Immutable => {
962                        // Nothing else to check for Immutable.
963                    }
964                    Owner::Address(_) => {
965                        return Err(UserInputError::AddressOwnedIsInMoveAuthenticatorInput {
966                            object_id: object.id(),
967                        });
968                    }
969                    Owner::Object(_) => {
970                        return Err(UserInputError::ObjectOwnedIsInMoveAuthenticatorInput {
971                            object_id: object.id(),
972                        });
973                    }
974                    Owner::Shared(_) => {
975                        // This object is a mutable shared object. However the transaction
976                        // specifies it as an owned object. This is inconsistent.
977                        return Err(UserInputError::NotSharedObject);
978                    }
979                    _ => {
980                        unimplemented!("a new Owner enum variant was added and needs to be handled")
981                    }
982                };
983            }
984            InputObjectKind::SharedMoveObject {
985                id: ObjectId::AUTHENTICATOR_STATE,
986                ..
987            } => {
988                return Err(UserInputError::InaccessibleSystemObject {
989                    object_id: ObjectId::AUTHENTICATOR_STATE,
990                });
991            }
992            InputObjectKind::SharedMoveObject {
993                id, mutable: true, ..
994            } => {
995                return Err(UserInputError::MutableSharedIsInMoveAuthenticatorInput {
996                    object_id: id,
997                });
998            }
999            InputObjectKind::SharedMoveObject {
1000                initial_shared_version: input_initial_shared_version,
1001                ..
1002            } => {
1003                fp_ensure!(
1004                    object.version() < Version::MAX_VALID_EXCL,
1005                    UserInputError::InvalidSequenceNumber
1006                );
1007
1008                match object.owner {
1009                    Owner::Address(_) | Owner::Object(_) | Owner::Immutable => {
1010                        // When someone locks an object as shared it must be shared already.
1011                        return Err(UserInputError::NotSharedObject);
1012                    }
1013                    Owner::Shared(actual_initial_shared_version) => {
1014                        fp_ensure!(
1015                            input_initial_shared_version == actual_initial_shared_version,
1016                            UserInputError::SharedObjectStartingVersionMismatch
1017                        )
1018                    }
1019                    _ => {
1020                        unimplemented!("a new Owner enum variant was added and needs to be handled")
1021                    }
1022                }
1023            }
1024        };
1025        Ok(())
1026    }
1027
1028    /// Checks a shared `MoveAuthenticator` input against the rules that depend
1029    /// only on how it is declared: it may not be the authenticator state
1030    /// object, and it may not be declared mutable.
1031    fn check_move_authenticator_shared_object_declaration(
1032        object_kind: &InputObjectKind,
1033    ) -> UserInputResult {
1034        match object_kind {
1035            InputObjectKind::SharedMoveObject {
1036                id: ObjectId::AUTHENTICATOR_STATE,
1037                ..
1038            } => Err(UserInputError::InaccessibleSystemObject {
1039                object_id: ObjectId::AUTHENTICATOR_STATE,
1040            }),
1041            InputObjectKind::SharedMoveObject {
1042                id, mutable: true, ..
1043            } => Err(UserInputError::MutableSharedIsInMoveAuthenticatorInput { object_id: *id }),
1044            _ => Ok(()),
1045        }
1046    }
1047
1048    /// Create a union of two CheckedInputObjects, ensuring consistency
1049    /// for objects that appear in both sets. The base_set is consumed and
1050    /// returned with the union. The other_set is borrowed.
1051    /// In the case of shared objects, the mutability can differ, but the
1052    /// initial shared version must match. For other object kinds, they must
1053    /// match exactly.
1054    pub fn checked_input_objects_union(
1055        base_set: CheckedInputObjects,
1056        other_set: &CheckedInputObjects,
1057    ) -> IotaResult<CheckedInputObjects> {
1058        let mut base_set = base_set.into_inner();
1059        for other_object in other_set.inner().iter() {
1060            if let Some(base_object) = base_set.find_object_id_mut(other_object.id()) {
1061                // This is an invariant
1062                assert_eq!(
1063                    base_object.object, other_object.object,
1064                    "The object read result for input objects with the same id must be equal"
1065                );
1066
1067                // In the case of an alive object, check that the object kind matches exactly,
1068                // or that, if it is a shared object, only the mutability changes
1069                if let ObjectReadResultKind::Object(_) = &other_object.object {
1070                    base_object
1071                        .input_object_kind
1072                        .left_union_with_checks(&other_object.input_object_kind)?;
1073                }
1074            } else {
1075                base_set.push(other_object.clone());
1076            }
1077        }
1078        Ok(base_set.into_checked())
1079    }
1080
1081    /// Check package verification timeout
1082    #[instrument(level = "trace", skip_all)]
1083    pub fn check_non_system_packages_to_be_published(
1084        transaction: &Transaction,
1085        protocol_config: &ProtocolConfig,
1086        metrics: &Arc<BytecodeVerifierMetrics>,
1087        verifier_limits_source: VerifierLimitsSource<'_>,
1088    ) -> UserInputResult<()> {
1089        // Only meter non-system programmable transaction blocks
1090        if transaction.is_system_tx() {
1091            return Ok(());
1092        }
1093
1094        let TransactionKind::Programmable(pt) = transaction.kind() else {
1095            return Ok(());
1096        };
1097
1098        // Use the same verifier and meter for all packages.
1099        let (verifier_config, meter_config) = match verifier_limits_source {
1100            VerifierLimitsSource::NodeConfig(config) => (
1101                protocol_config.verifier_config(Some(config.limits_for_signing())),
1102                config.meter_config_for_signing(),
1103            ),
1104            VerifierLimitsSource::ProtocolConfig => (
1105                protocol_config.post_consensus_verifier_config(),
1106                protocol_config.meter_config(),
1107            ),
1108        };
1109        let mut verifier = iota_execution::verifier(protocol_config, verifier_config, metrics);
1110        let mut meter = verifier.meter(meter_config);
1111
1112        // Measure time for verifying all packages in the PTB
1113        let shared_meter_verifier_timer = metrics
1114            .verifier_runtime_per_ptb_success_latency
1115            .start_timer();
1116
1117        let verifier_status = pt
1118            .non_system_packages_to_be_published()
1119            .try_for_each(|module_bytes| {
1120                verifier.meter_module_bytes(protocol_config, module_bytes, meter.as_mut())
1121            })
1122            .map_err(|e| UserInputError::PackageVerificationTimedout { err: e.to_string() });
1123
1124        match verifier_status {
1125            Ok(_) => {
1126                // Success: stop and record the success timer
1127                shared_meter_verifier_timer.stop_and_record();
1128            }
1129            Err(err) => {
1130                // Failure: redirect the success timers output to the failure timer and
1131                // discard the success timer
1132                metrics
1133                    .verifier_runtime_per_ptb_timeout_latency
1134                    .observe(shared_meter_verifier_timer.stop_and_discard());
1135                return Err(err);
1136            }
1137        };
1138
1139        Ok(())
1140    }
1141
1142    #[cfg(test)]
1143    mod tests {
1144        use iota_sdk_types::{MovePackage, TransactionDigest};
1145
1146        use super::*;
1147
1148        fn package(id: ObjectId) -> Object {
1149            Object::new_from_package(
1150                MovePackage::new(
1151                    id,
1152                    Version::OBJECT_START,
1153                    BTreeMap::new(),
1154                    vec![],
1155                    BTreeMap::new(),
1156                ),
1157                TransactionDigest::genesis_marker(),
1158            )
1159        }
1160
1161        /// `object`, read for the kind `MovePackage(id)`.
1162        fn read_as_package(id: ObjectId, object: Object) -> InputObjects {
1163            InputObjects::new(vec![ObjectReadResult::new(
1164                InputObjectKind::MovePackage(id),
1165                object.into(),
1166            )])
1167        }
1168
1169        #[test]
1170        fn authenticator_check_accepts_its_type_arg_package() {
1171            let id = ObjectId::random();
1172            check_move_authenticator_objects(&read_as_package(id, package(id))).unwrap();
1173        }
1174
1175        #[test]
1176        fn authenticator_check_rejects_an_object_named_as_a_type_arg_package() {
1177            let id = ObjectId::random();
1178            assert_eq!(
1179                check_move_authenticator_objects(&read_as_package(
1180                    id,
1181                    Object::immutable_with_id_for_testing(id)
1182                ))
1183                .unwrap_err(),
1184                UserInputError::MoveObjectAsPackage { object_id: id }
1185            );
1186        }
1187
1188        /// `validate_input_object_versions` refuses such a reference from the
1189        /// transaction bytes before any object is loaded, so this bound is only
1190        /// reached with that flag off. No rule set relaxes it: without it a
1191        /// strict check would report a version mismatch and a relaxed one would
1192        /// accept the reference.
1193        #[test]
1194        fn receiving_version_bound_holds_under_every_rule_set() {
1195            let object = Object::with_id_owner_for_testing(ObjectId::random(), Address::ZERO);
1196            let current = object.object_ref();
1197            let invalid_ref =
1198                ObjectReference::new(current.object_id, Version::MAX_VALID_EXCL, current.digest);
1199            let receiving_objects = ReceivingObjects::from(vec![ReceivingObjectReadResult::new(
1200                invalid_ref,
1201                object.into(),
1202            )]);
1203
1204            for input_checks in [InputCheckRules::STRICT, InputCheckRules::RELAXED_UNSAFE] {
1205                let error = check_receiving_objects(
1206                    &InputObjects::new(vec![]),
1207                    &receiving_objects,
1208                    input_checks,
1209                )
1210                .unwrap_err();
1211                assert!(
1212                    matches!(
1213                        error,
1214                        IotaError::UserInput {
1215                            error: UserInputError::InvalidSequenceNumber
1216                        }
1217                    ),
1218                    "{input_checks:?}: {error:?}"
1219                );
1220            }
1221        }
1222    }
1223}