1use std::{
5 collections::{BTreeSet, HashMap, HashSet},
6 sync::Arc,
7};
8
9use consensus_core::{TransactionVerifier, ValidationError};
10use consensus_types::block::{BlockRef, TransactionIndex};
11use fastcrypto_threshold::dkg_v1;
12use itertools::Itertools;
13use mysten_common::ZipDebugEqIteratorExt;
14use mysten_common::assert_reachable;
15use mysten_metrics::monitored_scope;
16use nonempty::NonEmpty;
17use prometheus::{
18 IntCounter, IntCounterVec, Registry, register_int_counter_vec_with_registry,
19 register_int_counter_with_registry,
20};
21use sui_macros::fail_point_arg;
22#[cfg(msim)]
23use sui_types::base_types::AuthorityName;
24use sui_types::{
25 base_types::{ObjectID, ObjectRef},
26 error::{SuiError, SuiErrorKind, SuiResult, UserInputError},
27 messages_consensus::{
28 ConsensusPosition, ConsensusTransaction, ConsensusTransactionKind,
29 SharedTransactionDenyConfig,
30 },
31 transaction::{InputObjectKind, PlainTransactionWithClaims, TransactionDataAPI},
32};
33use tap::TapFallible;
34use tracing::{debug, info, instrument, warn};
35
36use crate::{
37 authority::{AuthorityState, authority_per_epoch_store::AuthorityPerEpochStore},
38 checkpoints::CheckpointServiceNotify,
39};
40
41#[derive(Clone)]
44pub struct SuiTxValidator {
45 authority_state: Arc<AuthorityState>,
46 epoch_store: Arc<AuthorityPerEpochStore>,
47 checkpoint_service: Arc<dyn CheckpointServiceNotify + Send + Sync>,
48 metrics: Arc<SuiTxValidatorMetrics>,
49}
50
51impl SuiTxValidator {
52 pub fn new(
53 authority_state: Arc<AuthorityState>,
54 epoch_store: Arc<AuthorityPerEpochStore>,
55 checkpoint_service: Arc<dyn CheckpointServiceNotify + Send + Sync>,
56 metrics: Arc<SuiTxValidatorMetrics>,
57 ) -> Self {
58 info!(
59 "SuiTxValidator constructed for epoch {}",
60 epoch_store.epoch()
61 );
62 Self {
63 authority_state,
64 epoch_store,
65 checkpoint_service,
66 metrics,
67 }
68 }
69
70 fn validate_transactions(
71 &self,
72 block_ref: &BlockRef,
73 txs: &[ConsensusTransactionKind],
74 ) -> Result<(), SuiError> {
75 let epoch_store = &self.epoch_store;
76 let proposer = block_ref.author.value_u32();
78 let mut ckpt_messages = Vec::new();
79 let mut ckpt_batch = Vec::new();
80 for tx in txs.iter() {
81 match tx {
82 ConsensusTransactionKind::CertifiedTransaction(_) => {
83 return Err(SuiErrorKind::UnexpectedMessage(
84 "CertifiedTransaction cannot be used when preconsensus locking is disabled"
85 .to_string(),
86 )
87 .into());
88 }
89 ConsensusTransactionKind::CheckpointSignature(_) => {
90 return Err(SuiErrorKind::UnexpectedMessage(
91 "CheckpointSignature V1 is no longer supported".to_string(),
92 )
93 .into());
94 }
95 ConsensusTransactionKind::CheckpointSignatureV2(signature) => {
96 ckpt_messages.push(signature.as_ref());
97 ckpt_batch.push(&signature.summary);
98 }
99 ConsensusTransactionKind::RandomnessDkgMessage(_, bytes) => {
100 if bytes.len() > dkg_v1::DKG_MESSAGES_MAX_SIZE {
101 warn!("batch verification error: DKG Message too large");
102 return Err(SuiErrorKind::InvalidDkgMessageSize.into());
103 }
104 }
105 ConsensusTransactionKind::RandomnessDkgConfirmation(_, bytes) => {
106 if bytes.len() > dkg_v1::DKG_MESSAGES_MAX_SIZE {
107 warn!("batch verification error: DKG Confirmation too large");
108 return Err(SuiErrorKind::InvalidDkgMessageSize.into());
109 }
110 }
111
112 ConsensusTransactionKind::CapabilityNotification(_) => {
113 return Err(SuiErrorKind::UnexpectedMessage(
114 "CapabilityNotification V1 is no longer supported".to_string(),
115 )
116 .into());
117 }
118
119 ConsensusTransactionKind::RandomnessStateUpdate(_, _) => {
120 return Err(SuiErrorKind::UnexpectedMessage(
121 "RandomnessStateUpdate is no longer supported".to_string(),
122 )
123 .into());
124 }
125
126 ConsensusTransactionKind::EndOfPublish(_)
127 | ConsensusTransactionKind::NewJWKFetched(_, _, _)
128 | ConsensusTransactionKind::CapabilityNotificationV2(_) => {}
129
130 ConsensusTransactionKind::UserTransaction(_) => {
131 return Err(SuiErrorKind::UnexpectedMessage(
132 "ConsensusTransactionKind::UserTransaction cannot be used when address aliases is enabled or preconsensus locking is disabled".to_string(),
133 )
134 .into());
135 }
136
137 ConsensusTransactionKind::UserTransactionV2(tx) => {
138 if epoch_store.protocol_config().address_aliases() {
139 let has_aliases = if epoch_store
140 .protocol_config()
141 .fix_checkpoint_signature_mapping()
142 {
143 tx.aliases().is_some()
144 } else {
145 tx.aliases_v1().is_some()
146 };
147 if !has_aliases {
148 return Err(SuiErrorKind::UnexpectedMessage(
149 "ConsensusTransactionKind::UserTransactionV2 must contain an aliases claim".to_string(),
150 )
151 .into());
152 }
153 }
154
155 if let Some(aliases) = tx.aliases() {
156 let num_sigs = tx.tx().tx_signatures().len();
157 for (sig_idx, _) in aliases.iter() {
158 if (*sig_idx as usize) >= num_sigs {
159 return Err(SuiErrorKind::UnexpectedMessage(format!(
160 "UserTransactionV2 alias contains out-of-bounds signature index {sig_idx} (transaction has {num_sigs} signatures)",
161 )).into());
162 }
163 }
164 }
165
166 epoch_store
169 .check_allowed_proposer(tx.tx().data().transaction_data(), proposer)?;
170
171 }
173
174 ConsensusTransactionKind::ExecutionTimeObservation(obs) => {
175 if obs.estimates.len()
177 > epoch_store
178 .protocol_config()
179 .max_programmable_tx_commands()
180 .try_into()
181 .unwrap()
182 {
183 return Err(SuiErrorKind::UnexpectedMessage(format!(
184 "ExecutionTimeObservation contains too many estimates: {}",
185 obs.estimates.len()
186 ))
187 .into());
188 }
189 }
190
191 ConsensusTransactionKind::UpdateTransactionDenyConfig(msg) => {
192 if !epoch_store
193 .protocol_config()
194 .share_transaction_deny_config_in_consensus()
195 {
196 return Err(SuiErrorKind::UnexpectedMessage(
197 "UpdateTransactionDenyConfig is not supported by current protocol \
198 version"
199 .to_string(),
200 )
201 .into());
202 }
203 if let Some(rules) = msg.rules() {
204 rules.check_share_limits().map_err(|e| -> SuiError {
205 SuiErrorKind::UnexpectedMessage(format!(
206 "UpdateTransactionDenyConfig: {e}"
207 ))
208 .into()
209 })?;
210 }
211 }
212 }
213 }
214
215 let ckpt_count = ckpt_batch.len();
216
217 crate::signature_verifier::batch_verify_checkpoints(epoch_store.committee(), &ckpt_batch)
218 .tap_err(|e| warn!("batch verification error: {}", e))?;
219
220 for ckpt in ckpt_messages {
222 self.checkpoint_service.notify_checkpoint_signature(ckpt)?;
223 }
224
225 self.metrics
226 .checkpoint_signatures_verified
227 .inc_by(ckpt_count as u64);
228 Ok(())
229 }
230
231 fn apply_deny_config_updates(
236 &self,
237 block_ref: &BlockRef,
238 updates: Vec<SharedTransactionDenyConfig>,
239 ) {
240 if updates.is_empty() {
241 return;
242 }
243 let committee = self.epoch_store.committee();
244 let Some(author) = committee.authority_by_index(block_ref.author.value_u32()) else {
245 warn!(
246 "Dropping UpdateTransactionDenyConfig batch: block author index {} not in committee",
247 block_ref.author
248 );
249 return;
250 };
251 self.authority_state
252 .transaction_deny_config_manager()
253 .apply_updates(*author, updates);
254 }
255
256 #[instrument(level = "debug", skip_all, fields(block_ref))]
257 fn vote_transactions(
258 &self,
259 block_ref: &BlockRef,
260 txs: Vec<ConsensusTransactionKind>,
261 ) -> Vec<TransactionIndex> {
262 let epoch_store = &self.epoch_store;
263 let mut reject_txn_votes = Vec::new();
264 for (i, tx) in txs.into_iter().enumerate() {
265 let tx: PlainTransactionWithClaims = match tx {
266 ConsensusTransactionKind::UserTransactionV2(tx) => *tx,
267 _ => continue,
268 };
269
270 let tx_digest = *tx.tx().digest();
271 if let Err(error) = self.vote_transaction(epoch_store, tx) {
272 debug!(?tx_digest, "Voting to reject transaction: {error}");
273 self.metrics
274 .transaction_reject_votes
275 .with_label_values(&[error.to_variant_name()])
276 .inc();
277 reject_txn_votes.push(i as TransactionIndex);
278 epoch_store.set_rejection_vote_reason(
280 ConsensusPosition {
281 epoch: epoch_store.epoch(),
282 block: *block_ref,
283 index: i as TransactionIndex,
284 },
285 &error,
286 );
287 } else {
288 debug!(?tx_digest, "Voting to accept transaction");
289 }
290 }
291
292 reject_txn_votes
293 }
294
295 #[instrument(level = "debug", skip_all, err(level = "debug"), fields(tx_digest = ?tx.tx().digest()))]
296 fn vote_transaction(
297 &self,
298 epoch_store: &Arc<AuthorityPerEpochStore>,
299 tx: PlainTransactionWithClaims,
300 ) -> SuiResult<()> {
301 let aliases_v2 = tx.aliases();
303 let aliases_v1 = tx.aliases_v1();
304 let claimed_immutable_ids = tx.get_immutable_objects();
305 let inner_tx = tx.into_tx();
306
307 inner_tx.validity_check(&epoch_store.tx_validity_check_context())?;
310 epoch_store.check_timestamp_expiration_for_vote(inner_tx.data().transaction_data())?;
311
312 self.authority_state.check_system_overload(
313 inner_tx.data(),
314 self.authority_state.check_system_overload_at_signing(),
315 )?;
316
317 #[allow(unused_mut)]
318 let mut fail_point_always_report_aliases_changed = false;
319 fail_point_arg!(
320 "consensus-validator-always-report-aliases-changed",
321 |for_validators: Vec<AuthorityName>| {
322 if for_validators.contains(&self.authority_state.name) {
323 fail_point_always_report_aliases_changed = true;
325 }
326 }
327 );
328
329 let verified_tx = epoch_store.verify_transaction_with_current_aliases(inner_tx)?;
330
331 if epoch_store.protocol_config().address_aliases() {
333 let aliases_match = if epoch_store
334 .protocol_config()
335 .fix_checkpoint_signature_mapping()
336 {
337 let Some(claimed_v2) = aliases_v2 else {
339 return Err(
340 SuiErrorKind::InvalidRequest("missing address alias claim".into()).into(),
341 );
342 };
343 *verified_tx.aliases() == claimed_v2
344 } else {
345 let Some(claimed_v1) = aliases_v1 else {
347 return Err(
348 SuiErrorKind::InvalidRequest("missing address alias claim".into()).into(),
349 );
350 };
351 let computed_v1: Vec<_> = verified_tx
352 .tx()
353 .data()
354 .intent_message()
355 .value
356 .required_signers()
357 .into_iter()
358 .zip_eq(verified_tx.aliases().iter().map(|(_, seq)| *seq))
359 .collect();
360 let computed_v1 =
361 NonEmpty::from_vec(computed_v1).expect("must have at least one signer");
362 computed_v1 == claimed_v1
363 };
364
365 if !aliases_match || fail_point_always_report_aliases_changed {
366 return Err(SuiErrorKind::AliasesChanged.into());
367 }
368 }
369
370 let inner_tx = verified_tx.into_tx();
371 self.authority_state
372 .handle_vote_transaction(epoch_store, inner_tx.clone())?;
373
374 if !claimed_immutable_ids.is_empty() {
375 assert_reachable!("transaction has immutable input object claims");
376 let owned_object_refs: HashSet<ObjectRef> = inner_tx
377 .data()
378 .transaction_data()
379 .input_objects()?
380 .iter()
381 .filter_map(|obj| match obj {
382 InputObjectKind::ImmOrOwnedMoveObject(obj_ref) => Some(*obj_ref),
383 _ => None,
384 })
385 .collect();
386 self.verify_immutable_object_claims(&claimed_immutable_ids, owned_object_refs)?;
387 }
388
389 Ok(())
390 }
391
392 fn verify_immutable_object_claims(
396 &self,
397 claimed_ids: &[ObjectID],
398 owned_object_refs: HashSet<ObjectRef>,
399 ) -> SuiResult<()> {
400 let input_refs_by_id: HashMap<ObjectID, ObjectRef> = owned_object_refs
402 .iter()
403 .map(|obj_ref| (obj_ref.0, *obj_ref))
404 .collect();
405
406 for claimed_id in claimed_ids {
408 if !input_refs_by_id.contains_key(claimed_id) {
409 return Err(SuiErrorKind::ImmutableObjectClaimNotFoundInInput {
410 object_id: *claimed_id,
411 }
412 .into());
413 }
414 }
415
416 let input_ids: Vec<ObjectID> = input_refs_by_id.keys().copied().collect();
419 let objects = self
420 .authority_state
421 .get_object_cache_reader()
422 .get_objects(&input_ids);
423
424 let claimed_immutable_ids = claimed_ids.iter().cloned().collect::<BTreeSet<_>>();
425 let mut found_immutable_ids = BTreeSet::new();
426
427 for (obj_opt, object_id) in objects.into_iter().zip_debug_eq(input_ids.iter()) {
428 let input_ref = input_refs_by_id.get(object_id).unwrap();
429 match obj_opt {
430 Some(o) => {
431 let actual_ref = o.compute_object_reference();
434 if actual_ref != *input_ref {
435 return Err(SuiErrorKind::UserInputError {
436 error: UserInputError::ObjectVersionUnavailableForConsumption {
437 provided_obj_ref: *input_ref,
438 current_version: actual_ref.1,
439 },
440 }
441 .into());
442 }
443 if o.is_immutable() {
444 found_immutable_ids.insert(*object_id);
445 }
446 }
447 None => {
448 return Err(SuiErrorKind::UserInputError {
451 error: UserInputError::ObjectNotFound {
452 object_id: *object_id,
453 version: Some(input_ref.1),
454 },
455 }
456 .into());
457 }
458 }
459 }
460
461 if let Some(claimed_id) = claimed_immutable_ids
463 .difference(&found_immutable_ids)
464 .next()
465 {
466 let input_ref = input_refs_by_id.get(claimed_id).unwrap();
467 return Err(SuiErrorKind::InvalidImmutableObjectClaim {
468 claimed_object_id: *claimed_id,
469 found_object_ref: *input_ref,
470 }
471 .into());
472 }
473 if let Some(found_id) = found_immutable_ids
474 .difference(&claimed_immutable_ids)
475 .next()
476 {
477 return Err(SuiErrorKind::ImmutableObjectNotClaimed {
478 object_id: *found_id,
479 }
480 .into());
481 }
482
483 Ok(())
484 }
485}
486
487fn tx_kind_from_bytes(tx: &[u8]) -> Result<ConsensusTransactionKind, ValidationError> {
488 bcs::from_bytes::<ConsensusTransaction>(tx)
489 .map_err(|e| {
490 ValidationError::InvalidTransaction(format!(
491 "Failed to parse transaction bytes: {:?}",
492 e
493 ))
494 })
495 .map(|tx| tx.kind)
496}
497
498impl TransactionVerifier for SuiTxValidator {
499 fn verify_batch(&self, block_ref: &BlockRef, batch: &[&[u8]]) -> Result<(), ValidationError> {
500 let _scope = monitored_scope("ValidateBatch");
501
502 let txs: Vec<_> = batch
503 .iter()
504 .map(|tx| tx_kind_from_bytes(tx))
505 .collect::<Result<Vec<_>, _>>()?;
506
507 self.validate_transactions(block_ref, &txs)
508 .map_err(|e| ValidationError::InvalidTransaction(e.to_string()))
509 }
510
511 fn verify_and_vote_batch(
512 &self,
513 block_ref: &BlockRef,
514 batch: &[&[u8]],
515 ) -> Result<Vec<TransactionIndex>, ValidationError> {
516 let _scope = monitored_scope("VerifyAndVoteBatch");
517
518 let txs: Vec<_> = batch
519 .iter()
520 .map(|tx| tx_kind_from_bytes(tx))
521 .collect::<Result<Vec<_>, _>>()?;
522
523 self.validate_transactions(block_ref, &txs)
524 .map_err(|e| ValidationError::InvalidTransaction(e.to_string()))?;
525
526 let deny_config_updates: Vec<_> = txs
527 .iter()
528 .filter_map(|tx| match tx {
529 ConsensusTransactionKind::UpdateTransactionDenyConfig(msg) => Some((**msg).clone()),
530 _ => None,
531 })
532 .collect();
533 self.apply_deny_config_updates(block_ref, deny_config_updates);
534
535 Ok(self.vote_transactions(block_ref, txs))
536 }
537}
538
539pub struct SuiTxValidatorMetrics {
540 checkpoint_signatures_verified: IntCounter,
541 transaction_reject_votes: IntCounterVec,
542}
543
544impl SuiTxValidatorMetrics {
545 pub fn new(registry: &Registry) -> Arc<Self> {
546 Arc::new(Self {
547 checkpoint_signatures_verified: register_int_counter_with_registry!(
548 "tx_validator_checkpoint_signatures_verified",
549 "Number of checkpoint verified in consensus batch verifier",
550 registry
551 )
552 .unwrap(),
553 transaction_reject_votes: register_int_counter_vec_with_registry!(
554 "tx_validator_transaction_reject_votes",
555 "Number of reject transaction votes per reason",
556 &["reason"],
557 registry
558 )
559 .unwrap(),
560 })
561 }
562}
563
564#[cfg(test)]
565mod tests {
566 use std::collections::HashSet;
567 use std::num::NonZeroUsize;
568 use std::sync::Arc;
569
570 use consensus_config::AuthorityIndex;
571 use consensus_core::TransactionVerifier as _;
572 use consensus_types::block::{BlockDigest, BlockRef};
573 use fastcrypto::traits::KeyPair;
574 use sui_config::transaction_deny_config::TransactionDenyConfigBuilder;
575 use sui_macros::sim_test;
576 use sui_protocol_config::ProtocolConfig;
577 use sui_types::crypto::deterministic_random_account_key;
578 use sui_types::error::{SuiErrorKind, UserInputError};
579 use sui_types::executable_transaction::VerifiedExecutableTransaction;
580 use sui_types::messages_checkpoint::{
581 CheckpointContents, CheckpointSignatureMessage, CheckpointSummary, SignedCheckpointSummary,
582 };
583 use sui_types::messages_consensus::ConsensusPosition;
584 use sui_types::{
585 base_types::{ExecutionDigests, ObjectID, ObjectRef},
586 crypto::Ed25519SuiSignature,
587 effects::TransactionEffectsAPI as _,
588 messages_consensus::{
589 ConsensusTransaction, SharedTransactionDenyConfig, SharedTransactionDenyConfigV1,
590 },
591 object::Object,
592 signature::GenericSignature,
593 transaction::{
594 AllowedProposers, PlainTransactionWithClaims, Transaction, TransactionDataAPI as _,
595 TransactionExpiration,
596 },
597 };
598
599 use crate::authority::ExecutionEnv;
600 use crate::{
601 authority::test_authority_builder::TestAuthorityBuilder,
602 checkpoints::CheckpointServiceNoop,
603 consensus_adapter::consensus_tests::{
604 test_gas_objects, test_user_transaction, test_user_transaction_with_expiration,
605 test_user_transactions,
606 },
607 consensus_validator::{SuiTxValidator, SuiTxValidatorMetrics},
608 };
609
610 #[sim_test]
611 async fn accept_valid_transaction() {
612 let mut objects = test_gas_objects();
614 let shared_object = Object::shared_for_testing();
615 objects.push(shared_object.clone());
616
617 let network_config =
618 sui_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
619 .with_objects(objects.clone())
620 .build();
621
622 let state = TestAuthorityBuilder::new()
623 .with_network_config(&network_config, 0)
624 .build()
625 .await;
626 let name1 = state.name;
627 let transactions = test_user_transactions(&state, shared_object).await;
628
629 let first_transaction = transactions[0].clone();
630 let first_transaction_bytes: Vec<u8> =
631 bcs::to_bytes(&ConsensusTransaction::new_user_transaction_v2_message(
632 &name1,
633 first_transaction.into(),
634 ))
635 .unwrap();
636
637 let metrics = SuiTxValidatorMetrics::new(&Default::default());
638 let validator = SuiTxValidator::new(
639 state.clone(),
640 state.epoch_store_for_testing().clone(),
641 Arc::new(CheckpointServiceNoop {}),
642 metrics,
643 );
644 let res = validator.verify_batch(&BlockRef::MIN, &[&first_transaction_bytes]);
645 assert!(res.is_ok(), "{res:?}");
646
647 let transaction_bytes: Vec<_> = transactions
648 .clone()
649 .into_iter()
650 .map(|tx| {
651 bcs::to_bytes(&ConsensusTransaction::new_user_transaction_v2_message(
652 &name1,
653 tx.into(),
654 ))
655 .unwrap()
656 })
657 .collect();
658
659 let batch: Vec<_> = transaction_bytes.iter().map(|t| t.as_slice()).collect();
660 let res_batch = validator.verify_batch(&BlockRef::MIN, &batch);
661 assert!(res_batch.is_ok(), "{res_batch:?}");
662
663 let bogus_transaction_bytes: Vec<_> = transactions
664 .into_iter()
665 .map(|tx| {
666 let aliases = tx.aliases().clone();
668 let mut signed_tx: Transaction = tx.into_tx().into();
669 signed_tx.tx_signatures_mut_for_testing()[0] =
670 GenericSignature::Signature(sui_types::crypto::Signature::Ed25519SuiSignature(
671 Ed25519SuiSignature::default(),
672 ));
673 let tx_with_claims = PlainTransactionWithClaims::from_aliases(signed_tx, aliases);
674 bcs::to_bytes(&ConsensusTransaction::new_user_transaction_v2_message(
675 &name1,
676 tx_with_claims,
677 ))
678 .unwrap()
679 })
680 .collect();
681
682 let batch: Vec<_> = bogus_transaction_bytes
683 .iter()
684 .map(|t| t.as_slice())
685 .collect();
686 let res_batch = validator.verify_and_vote_batch(&BlockRef::MIN, &batch);
689 assert!(res_batch.is_ok());
690 let rejections = res_batch.unwrap();
692 assert_eq!(
693 rejections.len(),
694 batch.len(),
695 "All bogus transactions should be rejected"
696 );
697 }
698
699 #[sim_test]
700 async fn test_verify_and_vote_batch() {
701 let (sender, keypair) = deterministic_random_account_key();
703
704 let gas_objects: Vec<Object> = (0..8)
706 .map(|_| Object::with_id_owner_for_testing(ObjectID::random(), sender))
707 .collect();
708
709 let owned_objects: Vec<Object> = (0..2)
711 .map(|_| Object::with_id_owner_for_testing(ObjectID::random(), sender))
712 .collect();
713 let denied_object = owned_objects[1].clone();
714
715 let mut objects = gas_objects.clone();
716 objects.extend(owned_objects.clone());
717
718 let network_config =
719 sui_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
720 .committee_size(NonZeroUsize::new(1).unwrap())
721 .with_objects(objects.clone())
722 .build();
723
724 let transaction_deny_config = TransactionDenyConfigBuilder::new()
726 .add_denied_object(denied_object.id())
727 .build();
728 let state = TestAuthorityBuilder::new()
729 .with_network_config(&network_config, 0)
730 .with_transaction_deny_config(transaction_deny_config)
731 .build()
732 .await;
733
734 let valid_transaction = test_user_transaction(
738 &state,
739 sender,
740 &keypair,
741 gas_objects[0].clone(),
742 vec![owned_objects[0].clone()],
743 )
744 .await;
745
746 let invalid_transaction = test_user_transaction(
748 &state,
749 sender,
750 &keypair,
751 gas_objects[1].clone(),
752 vec![denied_object.clone()],
753 )
754 .await;
755
756 let transactions = vec![valid_transaction, invalid_transaction];
758 let serialized_transactions: Vec<_> = transactions
759 .into_iter()
760 .map(|t| {
761 bcs::to_bytes(&ConsensusTransaction::new_user_transaction_v2_message(
762 &state.name,
763 t.into(),
764 ))
765 .unwrap()
766 })
767 .collect();
768 let batch: Vec<_> = serialized_transactions
769 .iter()
770 .map(|t| t.as_slice())
771 .collect();
772
773 let validator = SuiTxValidator::new(
774 state.clone(),
775 state.epoch_store_for_testing().clone(),
776 Arc::new(CheckpointServiceNoop {}),
777 SuiTxValidatorMetrics::new(&Default::default()),
778 );
779
780 let rejected_transactions = validator
782 .verify_and_vote_batch(&BlockRef::MAX, &batch)
783 .unwrap();
784
785 assert_eq!(rejected_transactions, vec![1]);
788
789 let epoch_store = state.load_epoch_store_one_call_per_task();
792 let reason = epoch_store
793 .get_rejection_vote_reason(ConsensusPosition {
794 epoch: state.load_epoch_store_one_call_per_task().epoch(),
795 block: BlockRef::MAX,
796 index: 1,
797 })
798 .expect("Rejection vote reason should be set");
799
800 assert_eq!(
801 reason,
802 SuiErrorKind::UserInputError {
803 error: UserInputError::TransactionDenied {
804 error: format!(
805 "Access to input object {:?} is temporarily disabled",
806 denied_object.id()
807 )
808 }
809 }
810 );
811 }
812
813 #[sim_test]
814 async fn accept_checkpoint_signature_v2() {
815 let network_config =
816 sui_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir().build();
817
818 let state = TestAuthorityBuilder::new()
819 .with_network_config(&network_config, 0)
820 .build()
821 .await;
822
823 let epoch_store = state.load_epoch_store_one_call_per_task();
824
825 let checkpoint_summary = CheckpointSummary::new(
827 &ProtocolConfig::get_for_max_version_UNSAFE(),
828 epoch_store.epoch(),
829 0,
830 0,
831 &CheckpointContents::new_with_digests_only_for_tests([ExecutionDigests::random()]),
832 None,
833 Default::default(),
834 None,
835 0,
836 Vec::new(),
837 Vec::new(),
838 );
839
840 let keypair = network_config.validator_configs()[0].protocol_key_pair();
841 let authority = keypair.public().into();
842 let signed = SignedCheckpointSummary::new(
843 epoch_store.epoch(),
844 checkpoint_summary,
845 keypair,
846 authority,
847 );
848 let message = CheckpointSignatureMessage { summary: signed };
849
850 let tx = ConsensusTransaction::new_checkpoint_signature_message_v2(message);
851 let bytes = bcs::to_bytes(&tx).unwrap();
852
853 let validator = SuiTxValidator::new(
854 state.clone(),
855 state.epoch_store_for_testing().clone(),
856 Arc::new(CheckpointServiceNoop {}),
857 SuiTxValidatorMetrics::new(&Default::default()),
858 );
859
860 let res = validator.verify_batch(&BlockRef::MIN, &[&bytes]);
861 assert!(res.is_ok(), "{res:?}");
862 }
863
864 #[sim_test]
865 async fn test_verify_immutable_object_claims() {
866 let (sender, _keypair) = deterministic_random_account_key();
867
868 let owned_object1 = Object::with_id_owner_for_testing(ObjectID::random(), sender);
870 let owned_object2 = Object::with_id_owner_for_testing(ObjectID::random(), sender);
871
872 let immutable_object1 = Object::immutable_with_id_for_testing(ObjectID::random());
874 let immutable_object2 = Object::immutable_with_id_for_testing(ObjectID::random());
875
876 let owned_id1 = owned_object1.id();
878 let owned_id2 = owned_object2.id();
879 let immutable_id1 = immutable_object1.id();
880 let immutable_id2 = immutable_object2.id();
881
882 let all_objects = vec![
883 owned_object1,
884 owned_object2,
885 immutable_object1,
886 immutable_object2,
887 ];
888
889 let network_config =
890 sui_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
891 .committee_size(NonZeroUsize::new(1).unwrap())
892 .with_objects(all_objects)
893 .build();
894
895 let state = TestAuthorityBuilder::new()
896 .with_network_config(&network_config, 0)
897 .build()
898 .await;
899
900 let cache_reader = state.get_object_cache_reader();
902 let owned_ref1 = cache_reader
903 .get_object(&owned_id1)
904 .expect("owned_id1 not found")
905 .compute_object_reference();
906 let owned_ref2 = cache_reader
907 .get_object(&owned_id2)
908 .expect("owned_id2 not found")
909 .compute_object_reference();
910 let immutable_ref1 = cache_reader
911 .get_object(&immutable_id1)
912 .expect("immutable_id1 not found")
913 .compute_object_reference();
914 let immutable_ref2 = cache_reader
915 .get_object(&immutable_id2)
916 .expect("immutable_id2 not found")
917 .compute_object_reference();
918
919 let validator = SuiTxValidator::new(
920 state.clone(),
921 state.epoch_store_for_testing().clone(),
922 Arc::new(CheckpointServiceNoop {}),
923 SuiTxValidatorMetrics::new(&Default::default()),
924 );
925
926 {
928 let owned_refs: HashSet<ObjectRef> = [owned_ref1, owned_ref2].into_iter().collect();
929
930 let result = validator.verify_immutable_object_claims(&[], owned_refs);
931 assert!(
932 result.is_ok(),
933 "Empty claims with only owned objects should pass, got error: {:?}",
934 result.err()
935 );
936 }
937
938 {
940 let refs: HashSet<ObjectRef> = [owned_ref1, immutable_ref1].into_iter().collect();
941
942 let claimed_ids = vec![immutable_id1];
943 let result = validator.verify_immutable_object_claims(&claimed_ids, refs);
944 assert!(result.is_ok(), "Correct immutable object claim should pass");
945 }
946
947 {
949 let refs: HashSet<ObjectRef> = [owned_ref1, immutable_ref1, immutable_ref2]
950 .into_iter()
951 .collect();
952
953 let claimed_ids = vec![immutable_id1, immutable_id2];
954 let result = validator.verify_immutable_object_claims(&claimed_ids, refs);
955 assert!(
956 result.is_ok(),
957 "Multiple correct immutable claims should pass"
958 );
959 }
960
961 {
963 let refs: HashSet<ObjectRef> = [owned_ref1, immutable_ref1].into_iter().collect();
964
965 let claimed_ids: Vec<ObjectID> = vec![];
966 let result = validator.verify_immutable_object_claims(&claimed_ids, refs);
967 assert!(result.is_err(), "Missing immutable claim should fail");
968
969 let err = result.unwrap_err();
970 assert!(
971 matches!(
972 err.as_inner(),
973 SuiErrorKind::ImmutableObjectNotClaimed { object_id }
974 if *object_id == immutable_id1
975 ),
976 "Expected ImmutableObjectNotClaimed error, got: {:?}",
977 err.as_inner()
978 );
979 }
980
981 {
983 let refs: HashSet<ObjectRef> = [owned_ref1, owned_ref2].into_iter().collect();
984
985 let claimed_ids = vec![owned_id1];
986 let result = validator.verify_immutable_object_claims(&claimed_ids, refs);
987 assert!(
988 result.is_err(),
989 "False immutable claim on owned object should fail"
990 );
991
992 let err = result.unwrap_err();
993 assert!(
994 matches!(
995 err.as_inner(),
996 SuiErrorKind::InvalidImmutableObjectClaim { claimed_object_id, .. }
997 if *claimed_object_id == owned_id1
998 ),
999 "Expected InvalidImmutableObjectClaim error, got: {:?}",
1000 err.as_inner()
1001 );
1002 }
1003
1004 {
1006 let refs: HashSet<ObjectRef> = [owned_ref1, owned_ref2].into_iter().collect();
1007
1008 let claimed_ids = vec![immutable_id1];
1009 let result = validator.verify_immutable_object_claims(&claimed_ids, refs);
1010 assert!(result.is_err(), "Claim not in inputs should fail");
1011
1012 let err = result.unwrap_err();
1013 assert!(
1014 matches!(
1015 err.as_inner(),
1016 SuiErrorKind::ImmutableObjectClaimNotFoundInInput { object_id }
1017 if *object_id == immutable_id1
1018 ),
1019 "Expected ImmutableObjectClaimNotFoundInInput error, got: {:?}",
1020 err.as_inner()
1021 );
1022 }
1023
1024 {
1026 let non_existent_id = ObjectID::random();
1027 let fake_ref = (
1028 non_existent_id,
1029 sui_types::base_types::SequenceNumber::new(),
1030 sui_types::digests::ObjectDigest::random(),
1031 );
1032 let refs: HashSet<ObjectRef> = [owned_ref1, fake_ref].into_iter().collect();
1033
1034 let claimed_ids: Vec<ObjectID> = vec![];
1035 let result = validator.verify_immutable_object_claims(&claimed_ids, refs);
1036 assert!(result.is_err(), "Non-existent object should fail");
1037
1038 let err = result.unwrap_err();
1039 assert!(
1040 matches!(
1041 err.as_inner(),
1042 SuiErrorKind::UserInputError { error: UserInputError::ObjectNotFound { object_id, .. } }
1043 if *object_id == non_existent_id
1044 ),
1045 "Expected ObjectNotFound error, got: {:?}",
1046 err.as_inner()
1047 );
1048 }
1049
1050 {
1052 let wrong_version_ref = (
1054 immutable_ref1.0,
1055 sui_types::base_types::SequenceNumber::from_u64(999),
1056 immutable_ref1.2,
1057 );
1058
1059 let refs: HashSet<ObjectRef> = [owned_ref1, wrong_version_ref].into_iter().collect();
1060
1061 let claimed_ids = vec![immutable_id1];
1062 let result = validator.verify_immutable_object_claims(&claimed_ids, refs);
1063 assert!(result.is_err(), "Version mismatch should fail");
1064
1065 let err = result.unwrap_err();
1066 assert!(
1067 matches!(
1068 err.as_inner(),
1069 SuiErrorKind::UserInputError { error: UserInputError::ObjectVersionUnavailableForConsumption { provided_obj_ref, current_version: _ } }
1070 if provided_obj_ref.0 == immutable_id1
1071 ),
1072 "Expected ObjectVersionUnavailableForConsumption error, got: {:?}",
1073 err.as_inner()
1074 );
1075 }
1076 }
1077
1078 #[sim_test]
1079 async fn accept_already_executed_transaction() {
1080 let (sender, keypair) = deterministic_random_account_key();
1081
1082 let gas_object = Object::with_id_owner_for_testing(ObjectID::random(), sender);
1083 let owned_object = Object::with_id_owner_for_testing(ObjectID::random(), sender);
1084
1085 let network_config =
1086 sui_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
1087 .committee_size(NonZeroUsize::new(1).unwrap())
1088 .with_objects(vec![gas_object.clone(), owned_object.clone()])
1089 .build();
1090
1091 let state = TestAuthorityBuilder::new()
1092 .with_network_config(&network_config, 0)
1093 .build()
1094 .await;
1095
1096 let epoch_store = state.load_epoch_store_one_call_per_task();
1097
1098 let transaction = test_user_transaction(
1100 &state,
1101 sender,
1102 &keypair,
1103 gas_object.clone(),
1104 vec![owned_object.clone()],
1105 )
1106 .await;
1107 let tx_digest = *transaction.tx().digest();
1108 let cert =
1109 VerifiedExecutableTransaction::new_from_consensus(transaction.clone().into_tx(), 0);
1110 let (executed_effects, _) = state
1111 .try_execute_immediately(&cert, ExecutionEnv::new(), &state.epoch_store_for_testing())
1112 .unwrap();
1113
1114 let read_effects = state
1116 .get_transaction_cache_reader()
1117 .get_executed_effects(&tx_digest)
1118 .expect("Transaction should be executed");
1119 assert_eq!(read_effects, executed_effects);
1120 assert_eq!(read_effects.executed_epoch(), epoch_store.epoch());
1121
1122 let serialized_tx = bcs::to_bytes(&ConsensusTransaction::new_user_transaction_v2_message(
1124 &state.name,
1125 transaction.into(),
1126 ))
1127 .unwrap();
1128 let validator = SuiTxValidator::new(
1129 state.clone(),
1130 state.epoch_store_for_testing().clone(),
1131 Arc::new(CheckpointServiceNoop {}),
1132 SuiTxValidatorMetrics::new(&Default::default()),
1133 );
1134 let rejected_transactions = validator
1135 .verify_and_vote_batch(&BlockRef::MAX, &[&serialized_tx])
1136 .expect("Verify and vote should succeed");
1137
1138 assert!(rejected_transactions.is_empty());
1140 }
1141
1142 #[sim_test]
1143 async fn test_reject_invalid_alias_signature_index() {
1144 let (sender, keypair) = deterministic_random_account_key();
1145
1146 let gas_object = Object::with_id_owner_for_testing(ObjectID::random(), sender);
1147 let owned_object = Object::with_id_owner_for_testing(ObjectID::random(), sender);
1148
1149 let network_config =
1150 sui_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
1151 .committee_size(NonZeroUsize::new(1).unwrap())
1152 .with_objects(vec![gas_object.clone(), owned_object.clone()])
1153 .build();
1154
1155 let state = TestAuthorityBuilder::new()
1156 .with_network_config(&network_config, 0)
1157 .build()
1158 .await;
1159
1160 let transaction = test_user_transaction(
1161 &state,
1162 sender,
1163 &keypair,
1164 gas_object.clone(),
1165 vec![owned_object.clone()],
1166 )
1167 .await;
1168
1169 let inner_tx: Transaction = transaction.into_tx().into();
1172 let bogus_aliases = nonempty::nonempty![(255u8, None)];
1173 let tx_with_bogus_alias = PlainTransactionWithClaims::from_aliases(inner_tx, bogus_aliases);
1174
1175 let serialized_tx = bcs::to_bytes(&ConsensusTransaction::new_user_transaction_v2_message(
1176 &state.name,
1177 tx_with_bogus_alias,
1178 ))
1179 .unwrap();
1180
1181 let validator = SuiTxValidator::new(
1182 state.clone(),
1183 state.epoch_store_for_testing().clone(),
1184 Arc::new(CheckpointServiceNoop {}),
1185 SuiTxValidatorMetrics::new(&Default::default()),
1186 );
1187
1188 let res = validator.verify_batch(&BlockRef::MIN, &[&serialized_tx]);
1189 assert!(
1190 res.is_err(),
1191 "Should reject transaction with out-of-bounds alias signature index"
1192 );
1193 }
1194
1195 #[sim_test]
1198 async fn test_reject_disallowed_proposer() {
1199 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut c| {
1200 c.set_allowed_proposers_for_testing(true);
1201 c
1202 });
1203
1204 let (sender, keypair) = deterministic_random_account_key();
1205 let gas_object = Object::with_id_owner_for_testing(ObjectID::random(), sender);
1206 let owned_object = Object::with_id_owner_for_testing(ObjectID::random(), sender);
1207
1208 let network_config =
1209 sui_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
1210 .committee_size(NonZeroUsize::new(4).unwrap())
1211 .with_objects(vec![gas_object.clone(), owned_object.clone()])
1212 .build();
1213
1214 let state = TestAuthorityBuilder::new()
1215 .with_network_config(&network_config, 0)
1216 .build()
1217 .await;
1218
1219 let transaction =
1220 test_user_transaction(&state, sender, &keypair, gas_object, vec![owned_object]).await;
1221
1222 let aliases = transaction.aliases().clone();
1225 let mut inner_tx: Transaction = transaction.into_tx().into();
1226 *inner_tx
1227 .data_mut_for_testing()
1228 .inner_mut()
1229 .intent_message
1230 .value
1231 .expiration_mut_for_testing() = TransactionExpiration::Validity {
1232 min_epoch: Some(0),
1233 max_epoch: Some(0),
1234 min_timestamp: None,
1235 max_timestamp: None,
1236 chain: state.get_chain_identifier(),
1237 nonce: 0,
1238 allowed_proposers: Some(AllowedProposers {
1239 epoch: state.epoch_store_for_testing().epoch(),
1240 proposers: nonempty::nonempty![2],
1241 }),
1242 };
1243
1244 let serialized_tx = bcs::to_bytes(&ConsensusTransaction::new_user_transaction_v2_message(
1245 &state.name,
1246 PlainTransactionWithClaims::from_aliases(inner_tx, aliases),
1247 ))
1248 .unwrap();
1249
1250 let validator = SuiTxValidator::new(
1251 state.clone(),
1252 state.epoch_store_for_testing().clone(),
1253 Arc::new(CheckpointServiceNoop {}),
1254 SuiTxValidatorMetrics::new(&Default::default()),
1255 );
1256
1257 let block_from = |author: u32| {
1258 BlockRef::new(
1259 1,
1260 AuthorityIndex::new_for_test(author),
1261 BlockDigest::default(),
1262 )
1263 };
1264 for disallowed in [0, 1, 3] {
1265 assert!(
1266 validator
1267 .verify_batch(&block_from(disallowed), &[&serialized_tx])
1268 .is_err(),
1269 "block from authority {disallowed} should be rejected"
1270 );
1271 }
1272 let res = validator.verify_batch(&block_from(2), &[&serialized_tx]);
1273 assert!(res.is_ok(), "{res:?}");
1274 }
1275
1276 #[sim_test]
1280 async fn test_vote_on_timestamp_window() {
1281 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
1283 config.set_enable_timestamp_transaction_expiration_for_testing(true);
1284 config
1285 });
1286 let (sender, keypair) = deterministic_random_account_key();
1287 let gas_objects: Vec<Object> = (0..3)
1288 .map(|_| Object::with_id_owner_for_testing(ObjectID::random(), sender))
1289 .collect();
1290 let network_config =
1291 sui_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
1292 .committee_size(NonZeroUsize::new(1).unwrap())
1293 .with_objects(gas_objects.clone())
1294 .build();
1295 let state = TestAuthorityBuilder::new()
1296 .with_network_config(&network_config, 0)
1297 .build()
1298 .await;
1299 let epoch_store = state.epoch_store_for_testing();
1300 let now_secs = std::time::SystemTime::now()
1301 .duration_since(std::time::UNIX_EPOCH)
1302 .unwrap()
1303 .as_secs();
1304 let expiration = |min_timestamp, max_timestamp| TransactionExpiration::ValidDuring {
1305 min_epoch: Some(epoch_store.epoch()),
1306 max_epoch: Some(epoch_store.epoch()),
1307 min_timestamp,
1308 max_timestamp,
1309 chain: state.get_chain_identifier(),
1310 nonce: 0,
1311 };
1312
1313 let expired = test_user_transaction_with_expiration(
1314 &state,
1315 sender,
1316 &keypair,
1317 gas_objects[0].clone(),
1318 vec![],
1319 expiration(None, Some(now_secs - 60)),
1320 )
1321 .await;
1322 let early = test_user_transaction_with_expiration(
1323 &state,
1324 sender,
1325 &keypair,
1326 gas_objects[1].clone(),
1327 vec![],
1328 expiration(Some(now_secs + 3_600), None),
1329 )
1330 .await;
1331 let open = test_user_transaction_with_expiration(
1332 &state,
1333 sender,
1334 &keypair,
1335 gas_objects[2].clone(),
1336 vec![],
1337 expiration(Some(now_secs - 60), Some(now_secs + 3_600)),
1338 )
1339 .await;
1340 let serialized: Vec<_> = [expired, early, open]
1341 .into_iter()
1342 .map(|t| {
1343 bcs::to_bytes(&ConsensusTransaction::new_user_transaction_v2_message(
1344 &state.name,
1345 t.into(),
1346 ))
1347 .unwrap()
1348 })
1349 .collect();
1350 let batch: Vec<_> = serialized.iter().map(|t| t.as_slice()).collect();
1351
1352 let validator = SuiTxValidator::new(
1353 state.clone(),
1354 epoch_store.clone(),
1355 Arc::new(CheckpointServiceNoop {}),
1356 SuiTxValidatorMetrics::new(&Default::default()),
1357 );
1358 let rejected = validator
1359 .verify_and_vote_batch(&BlockRef::MAX, &batch)
1360 .unwrap();
1361 assert_eq!(rejected, vec![1]);
1362 assert!(matches!(
1363 epoch_store
1364 .get_rejection_vote_reason(ConsensusPosition {
1365 epoch: epoch_store.epoch(),
1366 block: BlockRef::MAX,
1367 index: 1,
1368 })
1369 .map(|e| e.into_inner()),
1370 Some(SuiErrorKind::TransactionNotYetValid { .. })
1371 ));
1372 }
1373
1374 #[sim_test]
1379 async fn deny_config_updates_applied_at_verification() {
1380 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut c| {
1381 c.set_share_transaction_deny_config_in_consensus_for_testing(true);
1382 c
1383 });
1384
1385 let network_config =
1388 sui_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
1389 .committee_size(NonZeroUsize::new(1).unwrap())
1390 .build();
1391 let state = TestAuthorityBuilder::new()
1392 .with_network_config(&network_config, 0)
1393 .build()
1394 .await;
1395 let validator = SuiTxValidator::new(
1396 state.clone(),
1397 state.epoch_store_for_testing().clone(),
1398 Arc::new(CheckpointServiceNoop {}),
1399 SuiTxValidatorMetrics::new(&Default::default()),
1400 );
1401 let manager = state.transaction_deny_config_manager().clone();
1402
1403 let now_ms = crate::authority::AuthorityState::unixtime_now_ms();
1404 let msg_bytes = |authority, generation| {
1405 bcs::to_bytes(&ConsensusTransaction::new_update_transaction_deny_config(
1406 SharedTransactionDenyConfig::V1(SharedTransactionDenyConfigV1 {
1407 authority,
1408 generation,
1409 rules: Some(sui_types::transaction_deny_rules::TransactionDenyRules {
1410 package_publish_disabled: true,
1411 ..Default::default()
1412 }),
1413 }),
1414 ))
1415 .unwrap()
1416 };
1417
1418 let far_future = msg_bytes(
1420 state.name,
1421 now_ms + SharedTransactionDenyConfig::MAX_GENERATION_FUTURE_DRIFT_MS + 600_000,
1422 );
1423 assert!(
1424 validator
1425 .verify_and_vote_batch(&BlockRef::MIN, &[&far_future])
1426 .is_ok()
1427 );
1428 assert!(manager.peer_configs_snapshot().is_empty());
1429
1430 let spoofed = msg_bytes(sui_types::base_types::AuthorityName::ZERO, now_ms);
1433 assert!(
1434 validator
1435 .verify_and_vote_batch(&BlockRef::MIN, &[&spoofed])
1436 .is_ok()
1437 );
1438 assert!(manager.peer_configs_snapshot().is_empty());
1439
1440 let sane = msg_bytes(state.name, now_ms);
1442 assert!(
1443 validator
1444 .verify_and_vote_batch(&BlockRef::MIN, &[&sane])
1445 .is_ok()
1446 );
1447 let snapshot = manager.peer_configs_snapshot();
1448 assert_eq!(snapshot.get(&state.name).unwrap().generation(), now_ms);
1449 }
1450}