1use 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#[derive(Debug, Clone)]
22pub struct ExecutionOrEarlyError {
23 early_errors: Option<NonEmpty<ExecutionErrorKind>>,
24 accumulator_version: Option<SequenceNumber>,
28}
29
30impl ExecutionOrEarlyError {
31 pub fn ok(accumulator_version: Option<SequenceNumber>) -> Self {
33 Self {
34 early_errors: None,
35 accumulator_version,
36 }
37 }
38
39 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 pub fn early_errors(&self) -> Option<&NonEmpty<ExecutionErrorKind>> {
56 self.early_errors.as_ref()
57 }
58
59 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 MaybeSufficient,
76 Insufficient,
80}
81
82pub 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 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
141fn 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#[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 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 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 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 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 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 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, 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 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}