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