Skip to main content

sui_types/
execution_params.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::collections::HashSet;
5
6use mysten_common::assert_reachable;
7use nonempty::NonEmpty;
8use once_cell::sync::Lazy;
9
10use crate::{
11    base_types::SequenceNumber,
12    digests::TransactionDigest,
13    execution_status::CongestedObjects,
14    execution_status::ExecutionErrorKind,
15    transaction::{CheckedInputObjects, TransactionExpiration},
16};
17
18/// Execution inputs computed before running a transaction: whether to fail it early (and with
19/// which errors), plus context for gas charging. An execution input only - never serialized into
20/// `TransactionEffects`, so adding fields here does not change effects or their digests.
21#[derive(Debug, Clone)]
22pub struct ExecutionOrEarlyError {
23    early_errors: Option<NonEmpty<ExecutionErrorKind>>,
24    /// Accumulator (settlement) root version assigned to this transaction. Gates the mainnet
25    /// address-balance gas-smash short-circuit. Populated only for mainnet committed execution;
26    /// `None` elsewhere, leaving that gate inert.
27    accumulator_version: Option<SequenceNumber>,
28}
29
30impl ExecutionOrEarlyError {
31    /// Execute the transaction normally (no predetermined early error).
32    pub fn ok(accumulator_version: Option<SequenceNumber>) -> Self {
33        Self {
34            early_errors: None,
35            accumulator_version,
36        }
37    }
38
39    /// Skip execution and fail the transaction with `errors`.
40    pub fn failed(
41        errors: NonEmpty<ExecutionErrorKind>,
42        accumulator_version: Option<SequenceNumber>,
43    ) -> Self {
44        Self {
45            early_errors: Some(errors),
46            accumulator_version,
47        }
48    }
49
50    pub fn is_ok(&self) -> bool {
51        self.early_errors.is_none()
52    }
53
54    /// The predetermined early errors, if any.
55    pub fn early_errors(&self) -> Option<&NonEmpty<ExecutionErrorKind>> {
56        self.early_errors.as_ref()
57    }
58
59    /// Consume self, returning the predetermined early errors, if any.
60    pub fn into_early_errors(self) -> Option<NonEmpty<ExecutionErrorKind>> {
61        self.early_errors
62    }
63
64    pub fn accumulator_version(&self) -> Option<SequenceNumber> {
65        self.accumulator_version
66    }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum FundsWithdrawStatus {
71    /// Either we don't know yet whether the funds withdrawals are sufficient or not,
72    /// or we know for sure that the funds withdrawals are sufficient.
73    /// The reason we don't need to distinguish between unknown and sufficient funds is that
74    /// in either case we would have to go ahead and execute the transaction anyway.
75    MaybeSufficient,
76    // TODO(address-funds): Add information on the address and type?
77    /// We know for sure that the funds withdrawals in this transaction do not all have enough funds.
78    /// This takes account of both address and object funds withdrawals.
79    Insufficient,
80}
81
82/// Determine if a transaction is predetermined to fail execution.
83/// Returns all matching error kinds, or `None` if there is no early failure.
84/// When we pass this to the execution engine, we will not execute the transaction
85/// if it is predetermined to fail execution.
86pub fn get_early_execution_error(
87    transaction_digest: &TransactionDigest,
88    input_objects: &CheckedInputObjects,
89    config_certificate_deny_set: &HashSet<TransactionDigest>,
90    funds_withdraw_status: &FundsWithdrawStatus,
91    expiration: &TransactionExpiration,
92    consensus_commit_timestamp_ms: Option<u64>,
93) -> Option<NonEmpty<ExecutionErrorKind>> {
94    let mut errors = vec![];
95    if is_certificate_denied(transaction_digest, config_certificate_deny_set) {
96        errors.push(ExecutionErrorKind::CertificateDenied);
97    }
98
99    if input_objects
100        .inner()
101        .contains_consensus_stream_ended_objects()
102    {
103        errors.push(ExecutionErrorKind::InputObjectDeleted);
104    }
105
106    let cancelled_objects = input_objects.inner().get_cancelled_objects();
107    if let Some((cancelled_objects, reason)) = cancelled_objects {
108        match reason {
109            SequenceNumber::CONGESTED => {
110                errors.push(
111                    ExecutionErrorKind::ExecutionCancelledDueToSharedObjectCongestion {
112                        congested_objects: CongestedObjects(cancelled_objects),
113                    },
114                );
115            }
116            SequenceNumber::RANDOMNESS_UNAVAILABLE => {
117                errors.push(ExecutionErrorKind::ExecutionCancelledDueToRandomnessUnavailable);
118            }
119            _ => panic!("invalid cancellation reason SequenceNumber: {reason}"),
120        }
121    }
122
123    if matches!(funds_withdraw_status, FundsWithdrawStatus::Insufficient) {
124        assert_reachable!("insufficient funds for withdraw");
125        errors.push(ExecutionErrorKind::InsufficientFundsForWithdraw);
126    }
127
128    // Expiry goes last, so that effects report any other early error, and the insufficient-funds
129    // short-circuit still applies. Checkpoint execution depends on this order: it sets the
130    // timestamp only when effects report `TransactionExpired` as the head error, so it must get
131    // the same effects when expiry follows another error that it reproduces without expiry.
132    // Do not add an early error after this one, or make execution depend on expiry when it is
133    // not the head error.
134    if consensus_commit_timestamp_ms.is_some_and(|ts| expiration.is_expired_at(ts)) {
135        errors.push(ExecutionErrorKind::TransactionExpired);
136    }
137
138    NonEmpty::from_vec(errors)
139}
140
141/// If a transaction digest shows up in this list, when executing such transaction,
142/// we will always return `ExecutionError::CertificateDenied` without executing it (but still do
143/// gas smashing). Because this list is not gated by protocol version, there are a few important
144/// criteria for adding a digest to this list:
145/// 1. The certificate must be causing all validators to either panic or hang forever deterministically.
146/// 2. If we ever ship a fix to make it no longer panic or hang when executing such transaction, we
147///    must make sure the transaction is already in this list. Otherwise nodes running the newer
148///    version without these transactions in the list will generate forked result.
149///
150/// Below is a scenario of when we need to use this list:
151/// 1. We detect that a specific transaction is causing all validators to either panic or hang forever deterministically.
152/// 2. We push a CertificateDenyConfig to deny such transaction to all validators asap.
153/// 3. To make sure that all fullnodes are able to sync to the latest version, we need to add the
154///    transaction digest to this list as well asap, and ship this binary to all fullnodes, so that
155///    they can sync past this transaction.
156/// 4. We then can start fixing the issue, and ship the fix to all nodes.
157/// 5. Unfortunately, we can't remove the transaction digest from this list, because if we do so,
158///    any future node that sync from genesis will fork on this transaction. We may be able to
159///    remove it once we have stable snapshots and the binary has a minimum supported protocol
160///    version past the epoch.
161fn get_denied_certificates() -> &'static HashSet<TransactionDigest> {
162    static DENIED_CERTIFICATES: Lazy<HashSet<TransactionDigest>> = Lazy::new(|| HashSet::from([]));
163    Lazy::force(&DENIED_CERTIFICATES)
164}
165
166// This is needed to initialize static variables in the simtest environment.
167#[cfg(msim)]
168pub fn get_denied_certificates_for_sim_test() -> &'static HashSet<TransactionDigest> {
169    get_denied_certificates()
170}
171
172fn is_certificate_denied(
173    transaction_digest: &TransactionDigest,
174    certificate_deny_set: &HashSet<TransactionDigest>,
175) -> bool {
176    certificate_deny_set.contains(transaction_digest)
177        || get_denied_certificates().contains(transaction_digest)
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use crate::{
184        base_types::ObjectID,
185        transaction::{
186            CheckedInputObjects, InputObjectKind, InputObjects, ObjectReadResult,
187            ObjectReadResultKind, SharedObjectMutability,
188        },
189    };
190
191    fn create_test_input_objects() -> CheckedInputObjects {
192        let input_objects = InputObjects::new(vec![]);
193        CheckedInputObjects::new_for_replay(input_objects)
194    }
195
196    #[test]
197    fn test_early_execution_error_insufficient_balance() {
198        let tx_digest = crate::digests::TransactionDigest::random();
199        let input_objects = create_test_input_objects();
200        let deny_set = HashSet::new();
201
202        // Test with insufficient balance
203        let result = get_early_execution_error(
204            &tx_digest,
205            &input_objects,
206            &deny_set,
207            &FundsWithdrawStatus::Insufficient,
208            &TransactionExpiration::None,
209            None,
210        );
211        assert_eq!(
212            result.unwrap().into_iter().collect::<Vec<_>>(),
213            vec![ExecutionErrorKind::InsufficientFundsForWithdraw],
214        );
215
216        // Test with sufficient balance
217        let result = get_early_execution_error(
218            &tx_digest,
219            &input_objects,
220            &deny_set,
221            &FundsWithdrawStatus::MaybeSufficient,
222            &TransactionExpiration::None,
223            None,
224        );
225        assert!(result.is_none());
226    }
227
228    #[test]
229    fn test_early_execution_error_expired() {
230        let tx_digest = crate::digests::TransactionDigest::random();
231        let input_objects = create_test_input_objects();
232        let deny_set = HashSet::new();
233        let expiration = TransactionExpiration::ValidDuring {
234            min_epoch: None,
235            max_epoch: None,
236            min_timestamp: Some(1000),
237            max_timestamp: Some(2000),
238            chain: crate::digests::ChainIdentifier::default(),
239            nonce: 0,
240        };
241        let errors = |status: &FundsWithdrawStatus, timestamp_ms: Option<u64>| {
242            get_early_execution_error(
243                &tx_digest,
244                &input_objects,
245                &deny_set,
246                status,
247                &expiration,
248                timestamp_ms,
249            )
250            .map(|e| e.into_iter().collect::<Vec<_>>())
251        };
252
253        // `max_timestamp` covers the whole second, and `min_timestamp` is not checked.
254        assert_eq!(errors(&FundsWithdrawStatus::MaybeSufficient, None), None);
255        assert_eq!(errors(&FundsWithdrawStatus::MaybeSufficient, Some(0)), None);
256        assert_eq!(
257            errors(&FundsWithdrawStatus::MaybeSufficient, Some(2_000_999)),
258            None
259        );
260        assert_eq!(
261            errors(&FundsWithdrawStatus::MaybeSufficient, Some(2_001_000)),
262            Some(vec![ExecutionErrorKind::TransactionExpired])
263        );
264        // Expiry follows other early errors.
265        assert_eq!(
266            errors(&FundsWithdrawStatus::Insufficient, Some(2_001_000)),
267            Some(vec![
268                ExecutionErrorKind::InsufficientFundsForWithdraw,
269                ExecutionErrorKind::TransactionExpired,
270            ])
271        );
272        assert_eq!(expiration.first_expired_timestamp_ms(), Some(2_001_000));
273    }
274
275    #[test]
276    fn test_early_execution_error_collects_all() {
277        let tx_digest = crate::digests::TransactionDigest::random();
278        let input_objects = create_test_input_objects();
279
280        // Certificate denial + insufficient balance collected together.
281        let mut deny_set = HashSet::new();
282        deny_set.insert(tx_digest);
283        let result = get_early_execution_error(
284            &tx_digest,
285            &input_objects,
286            &deny_set,
287            &FundsWithdrawStatus::Insufficient,
288            &TransactionExpiration::None,
289            None,
290        );
291        assert_eq!(
292            result.unwrap().into_iter().collect::<Vec<_>>(),
293            vec![
294                ExecutionErrorKind::CertificateDenied,
295                ExecutionErrorKind::InsufficientFundsForWithdraw,
296            ],
297        );
298
299        // Deleted input objects + insufficient balance.
300        let input_objects = InputObjects::new(vec![ObjectReadResult {
301            input_object_kind: InputObjectKind::SharedMoveObject {
302                id: ObjectID::random(),
303                initial_shared_version: SequenceNumber::MIN,
304                mutability: SharedObjectMutability::Immutable,
305            },
306            object: ObjectReadResultKind::ObjectConsensusStreamEnded(
307                SequenceNumber::MIN, // doesn't matter
308                tx_digest,
309            ),
310        }]);
311        deny_set.clear();
312        let result = get_early_execution_error(
313            &tx_digest,
314            &CheckedInputObjects::new_for_replay(input_objects),
315            &deny_set,
316            &FundsWithdrawStatus::Insufficient,
317            &TransactionExpiration::None,
318            None,
319        );
320        assert_eq!(
321            result.unwrap().into_iter().collect::<Vec<_>>(),
322            vec![
323                ExecutionErrorKind::InputObjectDeleted,
324                ExecutionErrorKind::InsufficientFundsForWithdraw,
325            ],
326        );
327
328        // Cancelled (congestion) + insufficient balance.
329        let input_objects = InputObjects::new(vec![ObjectReadResult {
330            input_object_kind: InputObjectKind::SharedMoveObject {
331                id: ObjectID::random(),
332                initial_shared_version: SequenceNumber::MIN,
333                mutability: SharedObjectMutability::Immutable,
334            },
335            object: ObjectReadResultKind::CancelledTransactionSharedObject(
336                SequenceNumber::CONGESTED,
337            ),
338        }]);
339        let result = get_early_execution_error(
340            &tx_digest,
341            &CheckedInputObjects::new_for_replay(input_objects),
342            &deny_set,
343            &FundsWithdrawStatus::Insufficient,
344            &TransactionExpiration::None,
345            None,
346        );
347        let result: Vec<_> = result.unwrap().into_iter().collect();
348        assert_eq!(result.len(), 2);
349        assert!(matches!(
350            result[0],
351            ExecutionErrorKind::ExecutionCancelledDueToSharedObjectCongestion { .. }
352        ));
353        assert_eq!(result[1], ExecutionErrorKind::InsufficientFundsForWithdraw);
354    }
355}