1use std::sync::Arc;
6
7use eyre::WrapErr;
8use fastcrypto_threshold::dkg_v1;
9use iota_metrics::monitored_scope;
10use iota_sdk_types::{SenderSignedTransaction, TransactionKind};
11use iota_types::{
12 base_types::ConciseableName,
13 error::IotaError,
14 messages_consensus::{ConsensusTransaction, ConsensusTransactionKind},
15 move_authenticator::MoveAuthenticatorExt,
16 transaction::{CallArg, TransactionAPI, transaction_identifiers_validity_check},
17};
18use prometheus_filtered::{IntCounter, Registry, register_int_counter_with_registry};
19use starfish_core;
20use tap::TapFallible;
21use tracing::{info, instrument, warn};
22
23use crate::{
24 authority::authority_per_epoch_store::AuthorityPerEpochStore,
25 checkpoints::CheckpointServiceNotify,
26};
27
28#[derive(Clone)]
30pub struct IotaTxValidator {
31 epoch_store: Arc<AuthorityPerEpochStore>,
32 checkpoint_service: Arc<dyn CheckpointServiceNotify + Send + Sync>,
33 metrics: Arc<IotaTxValidatorMetrics>,
34}
35
36impl IotaTxValidator {
37 pub fn new(
38 epoch_store: Arc<AuthorityPerEpochStore>,
39 checkpoint_service: Arc<dyn CheckpointServiceNotify + Send + Sync>,
40 metrics: Arc<IotaTxValidatorMetrics>,
41 ) -> Self {
42 info!(
43 "IotaTxValidator constructed for epoch {}",
44 epoch_store.epoch()
45 );
46 Self {
47 epoch_store,
48 checkpoint_service,
49 metrics,
50 }
51 }
52
53 fn identifiers_check(&self, signed_tx: &SenderSignedTransaction) -> Result<(), IotaError> {
58 if self
59 .epoch_store
60 .protocol_config()
61 .disallow_self_identifier_in_transactions()
62 {
63 transaction_identifiers_validity_check(signed_tx)?;
64 }
65 Ok(())
66 }
67
68 fn transaction_dependency_check(
74 &self,
75 signed_tx: &SenderSignedTransaction,
76 ) -> Result<(), IotaError> {
77 let in_authenticator = signed_tx
80 .move_authenticators()
81 .into_iter()
82 .flat_map(|authenticator| authenticator.call_args())
83 .any(|input| matches!(input, CallArg::TransactionDependency(_)));
84 if in_authenticator {
85 return Err(IotaError::UnsupportedFeature {
86 error: "transaction dependency input not supported in a Move authenticator".into(),
87 });
88 }
89 if !self
90 .epoch_store
91 .protocol_config()
92 .enable_transaction_dependencies()
93 && signed_tx.transaction().transaction_dependency().is_some()
94 {
95 return Err(IotaError::UnsupportedFeature {
96 error: "transaction dependency input not supported at current protocol version"
97 .into(),
98 });
99 }
100 Ok(())
101 }
102
103 fn claim_account_check(&self, signed_tx: &SenderSignedTransaction) -> Result<(), IotaError> {
108 if !self
109 .epoch_store
110 .protocol_config()
111 .enable_claim_account_transaction()
112 && matches!(
113 signed_tx.transaction().kind(),
114 TransactionKind::ClaimAccount(_)
115 )
116 {
117 return Err(IotaError::UnsupportedFeature {
118 error: "ClaimAccount not supported at current protocol version".into(),
119 });
120 }
121 Ok(())
122 }
123
124 #[instrument(level = "trace", skip_all)]
125 fn validate_transactions(&self, txs: Vec<ConsensusTransactionKind>) -> Result<(), IotaError> {
126 let mut cert_batch = Vec::new();
127 let mut ckpt_messages = Vec::new();
128 let mut ckpt_batch = Vec::new();
129 let mut authority_cap_batch = Vec::new();
130 let mut user_tx_count: u64 = 0;
131
132 for tx in txs.iter() {
133 match tx {
134 ConsensusTransactionKind::CertifiedTransaction(certificate) => {
135 self.identifiers_check(certificate.data())?;
136 self.transaction_dependency_check(certificate.data())?;
137 self.claim_account_check(certificate.data())?;
138 if self
141 .epoch_store
142 .protocol_config()
143 .enable_validator_attestation()
144 {
145 return Err(IotaError::UnsupportedFeature {
146 error: "CertifiedTransaction not allowed when validator attestation \
147 is enabled"
148 .into(),
149 });
150 }
151 cert_batch.push(certificate.as_ref());
152 }
153 ConsensusTransactionKind::CheckpointSignature(signature) => {
154 ckpt_messages.push(signature.as_ref());
155 ckpt_batch.push(&signature.summary);
156 }
157 ConsensusTransactionKind::RandomnessDkgMessage(_, bytes) => {
158 if bytes.len() > dkg_v1::DKG_MESSAGES_MAX_SIZE {
159 warn!("batch verification error: DKG Message too large");
160 return Err(IotaError::InvalidDkgMessageSize);
161 }
162 }
163 ConsensusTransactionKind::RandomnessDkgConfirmation(_, bytes) => {
164 if bytes.len() > dkg_v1::DKG_MESSAGES_MAX_SIZE {
165 warn!("batch verification error: DKG Confirmation too large");
166 return Err(IotaError::InvalidDkgMessageSize);
167 }
168 }
169 ConsensusTransactionKind::SignedCapabilityNotificationV1(signed_cap) => {
170 authority_cap_batch.push(signed_cap);
171 }
172
173 ConsensusTransactionKind::MisbehaviorReport(_) => {
174 if !self
175 .epoch_store
176 .protocol_config()
177 .calculate_validator_scores()
178 {
179 return Err(IotaError::UnsupportedFeature {
180 error: "MisbehaviorReport not supported at current protocol version"
181 .into(),
182 });
183 }
184 }
185 #[allow(deprecated)]
186 ConsensusTransactionKind::NewJWKFetchedDeprecated => {
187 return Err(IotaError::UnsupportedFeature {
188 error: "NewJWKFetched (zkLogin) is deprecated and not supported".into(),
189 });
190 }
191
192 ConsensusTransactionKind::UserTransactionV1(attested_tx) => {
193 if !self.epoch_store.protocol_config().enable_pcool_flow() {
194 return Err(IotaError::UnsupportedFeature {
195 error: "UserTransactionV1 not supported at current protocol version"
196 .into(),
197 });
198 }
199 self.identifiers_check(attested_tx.transaction.data())?;
200 self.transaction_dependency_check(attested_tx.transaction.data())?;
201 self.claim_account_check(attested_tx.transaction.data())?;
202 let attested = attested_tx.attestation.is_some();
206 let attestation_enabled = self
207 .epoch_store
208 .protocol_config()
209 .enable_validator_attestation();
210 if attested != attestation_enabled {
211 return Err(IotaError::UnsupportedFeature {
212 error: if attested {
213 "attested UserTransactionV1 not supported at current protocol \
214 version"
215 } else {
216 "UserTransactionV1 must carry an attestation when validator \
217 attestation is enabled"
218 }
219 .into(),
220 });
221 }
222 self.epoch_store
226 .signature_verifier
227 .verify_tx(attested_tx.transaction.data())
228 .tap_err(|e| {
229 warn!("UserTransactionV1 signature verification failed: {}", e)
230 })?;
231 user_tx_count += 1;
232 }
233
234 ConsensusTransactionKind::EndOfPublish(_)
235 | ConsensusTransactionKind::CapabilityNotificationV1(_) => {}
236
237 ConsensusTransactionKind::OverloadNotificationV1(authority_name, _, percentage) => {
238 if !self.epoch_store.protocol_config().enable_pcool_flow() {
239 return Err(IotaError::UnsupportedFeature {
240 error:
241 "OverloadNotificationV1 not supported at current protocol version"
242 .into(),
243 });
244 }
245 if *percentage > 100 {
246 return Err(IotaError::HandleConsensusTransactionFailure(format!(
247 "OverloadNotificationV1 with invalid percentage {percentage} from \
248 authority {}",
249 authority_name.concise(),
250 )));
251 }
252 }
253
254 ConsensusTransactionKind::TransactionDenyRuleProposal(_) => {
258 if !self.epoch_store.protocol_config().enable_pcool_flow() {
259 return Err(IotaError::UnsupportedFeature {
260 error: "TransactionDenyRuleProposal not supported at current protocol version"
261 .into(),
262 });
263 }
264 }
265 }
266 }
267
268 let cert_count = cert_batch.len();
270 let ckpt_count = ckpt_batch.len();
271 let authority_cap_count = authority_cap_batch.len();
272
273 self.epoch_store
274 .signature_verifier
275 .verify_certs_and_checkpoints(cert_batch, ckpt_batch, authority_cap_batch)
276 .tap_err(|e| warn!("batch verification error: {}", e))?;
277
278 for ckpt in ckpt_messages {
281 if let Err(e) = self
282 .checkpoint_service
283 .notify_checkpoint_signature(&self.epoch_store, ckpt)
284 {
285 warn!(
286 "Failed to forward checkpoint signature {}: {e}",
287 ckpt.summary.sequence_number
288 );
289 }
290 }
291
292 self.metrics
293 .certificate_signatures_verified
294 .inc_by(cert_count as u64);
295 self.metrics
296 .checkpoint_signatures_verified
297 .inc_by(ckpt_count as u64);
298 self.metrics
299 .authority_capabilities_verified
300 .inc_by(authority_cap_count as u64);
301 self.metrics
302 .user_transaction_signatures_verified
303 .inc_by(user_tx_count);
304 Ok(())
305
306 }
316}
317
318fn tx_from_bytes(tx: &[u8]) -> Result<ConsensusTransaction, eyre::Report> {
319 bcs::from_bytes::<ConsensusTransaction>(tx)
320 .wrap_err("Malformed transaction (failed to deserialize)")
321}
322
323impl starfish_core::TransactionVerifier for IotaTxValidator {
324 #[instrument(level = "trace", skip_all)]
325 fn verify_batch(
326 &self,
327 batch: &[&[u8]],
328 ) -> core::result::Result<(), starfish_core::ValidationError> {
329 let _scope = monitored_scope("ValidateBatch");
330
331 let txs = batch
332 .iter()
333 .map(|tx| {
334 tx_from_bytes(tx)
335 .map(|tx| tx.kind)
336 .map_err(|e| starfish_core::ValidationError::InvalidTransaction(e.to_string()))
337 })
338 .collect::<core::result::Result<Vec<_>, _>>()?;
339
340 self.validate_transactions(txs)
341 .map_err(|e| starfish_core::ValidationError::InvalidTransaction(e.to_string()))
342 }
343}
344
345pub struct IotaTxValidatorMetrics {
346 certificate_signatures_verified: IntCounter,
347 checkpoint_signatures_verified: IntCounter,
348 authority_capabilities_verified: IntCounter,
349 user_transaction_signatures_verified: IntCounter,
350}
351
352impl IotaTxValidatorMetrics {
353 pub fn new(registry: &Registry) -> Arc<Self> {
354 Arc::new(Self {
355 certificate_signatures_verified: register_int_counter_with_registry!(
356 "certificate_signatures_verified",
357 "Number of certificates verified in consensus batch verifier",
358 registry
359 )
360 .unwrap(),
361 checkpoint_signatures_verified: register_int_counter_with_registry!(
362 "checkpoint_signatures_verified",
363 "Number of checkpoint verified in consensus batch verifier",
364 registry
365 )
366 .unwrap(),
367 authority_capabilities_verified: register_int_counter_with_registry!(
368 "authority_capabilities_verified",
369 "Number of signed authority capabilities verified in consensus batch verifier",
370 registry
371 )
372 .unwrap(),
373 user_transaction_signatures_verified: register_int_counter_with_registry!(
374 "user_transaction_signatures_verified",
375 "Number of UserTransactionV1 signatures verified in consensus validator",
376 registry
377 )
378 .unwrap(),
379 })
380 }
381}
382
383#[cfg(test)]
384mod tests {
385 use std::sync::Arc;
386
387 use fastcrypto::traits::KeyPair as _;
388 use iota_macros::sim_test;
389 use iota_protocol_config::{Chain, OverrideGuard, ProtocolConfig, ProtocolVersion};
390 use iota_sdk_types::{
391 Identifier, ObjectId, SharedObjectReference, TransactionDigest, UserSignature,
392 };
393 use iota_types::{
394 attestation::{Attestation, AttestationData, AttestedTransaction},
395 crypto::AuthorityKeyPair,
396 error::{IotaError, IotaResult, UserInputError},
397 messages_checkpoint::{CheckpointSignatureMessage, SignedCheckpointSummary},
398 messages_consensus::{
399 ConsensusTransaction, ConsensusTransactionKind, MisbehaviorObservationsV1,
400 VersionedMisbehaviorReport,
401 },
402 object::Object,
403 transaction::{
404 CallArg, CertifiedTransaction, SenderSignedTransactionAPI, TransactionEnvelope,
405 },
406 };
407 use starfish_core::TransactionVerifier as _;
408
409 use crate::{
410 authority::{
411 AuthorityState, authority_per_epoch_store::AuthorityPerEpochStore,
412 test_authority_builder::TestAuthorityBuilder,
413 },
414 checkpoints::{CheckpointServiceNoop, CheckpointServiceNotify},
415 consensus_adapter::consensus_tests::{test_certificates, test_gas_objects},
416 consensus_validator::{IotaTxValidator, IotaTxValidatorMetrics},
417 test_utils::{certified_summary, consensus_transaction_feature_gate},
418 };
419
420 #[sim_test]
421 async fn accept_valid_transaction() {
422 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
425 config.set_enable_validator_attestation_for_testing(false);
426 config
427 });
428
429 let mut objects = test_gas_objects();
432 let shared_object = Object::shared_for_testing();
433 objects.push(shared_object.clone());
434
435 let network_config =
436 iota_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
437 .with_objects(objects.clone())
438 .build();
439
440 let state = TestAuthorityBuilder::new()
441 .with_network_config(&network_config, 0)
442 .build()
443 .await;
444 let name1 = state.name;
445 let certificates = test_certificates(&state, shared_object).await;
446
447 let first_transaction = certificates[0].clone();
448 let first_transaction_bytes: Vec<u8> = bcs::to_bytes(
449 &ConsensusTransaction::new_certificate_message(&name1, first_transaction),
450 )
451 .unwrap();
452
453 let metrics = IotaTxValidatorMetrics::new(&Default::default());
454 let validator = IotaTxValidator::new(
455 state.epoch_store_for_testing().clone(),
456 Arc::new(CheckpointServiceNoop {}),
457 metrics,
458 );
459 let res = validator.verify_batch(&[&first_transaction_bytes]);
460 assert!(res.is_ok(), "{res:?}");
461
462 let transaction_bytes: Vec<_> = certificates
463 .clone()
464 .into_iter()
465 .map(|cert| {
466 bcs::to_bytes(&ConsensusTransaction::new_certificate_message(&name1, cert)).unwrap()
467 })
468 .collect();
469
470 let batch: Vec<_> = transaction_bytes.iter().map(|t| t.as_slice()).collect();
471 let res_batch = validator.verify_batch(&batch);
472 assert!(res_batch.is_ok(), "{res_batch:?}");
473
474 let bogus_transaction_bytes: Vec<_> = certificates
475 .into_iter()
476 .map(|mut cert| {
477 cert.tx_signatures_mut_for_testing()[0] =
479 UserSignature::Simple(iota_types::crypto::zero_ed25519_signature());
480 bcs::to_bytes(&ConsensusTransaction::new_certificate_message(&name1, cert)).unwrap()
481 })
482 .collect();
483
484 let batch: Vec<_> = bogus_transaction_bytes
485 .iter()
486 .map(|t| t.as_slice())
487 .collect();
488 let res_batch = validator.verify_batch(&batch);
489 assert!(res_batch.is_err());
490 }
491
492 #[sim_test]
493 async fn verify_batch_checks_user_transaction_v1_signature() {
494 use iota_types::crypto::{AccountPrivateKey, deterministic_random_account_private_key};
495
496 use crate::test_utils::make_transfer_iota_transaction;
497
498 let (sender, sender_key): (_, AccountPrivateKey) =
499 deterministic_random_account_private_key();
500 let gas_object_id = ObjectId::random();
501 let gas_object = Object::with_id_owner_for_testing(gas_object_id, sender);
502 let network_config =
503 iota_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
504 .with_objects(vec![gas_object])
505 .build();
506 let _guard = validator_attestation_off();
507 let state = TestAuthorityBuilder::new()
508 .with_network_config(&network_config, 0)
509 .build()
510 .await;
511 let epoch_store = state.epoch_store_for_testing().clone();
512 assert!(epoch_store.protocol_config().enable_pcool_flow());
513
514 let rgp = epoch_store.reference_gas_price();
515 let gas_ref = state.get_object(&gas_object_id).unwrap().object_ref();
516 let valid_tx = make_transfer_iota_transaction(
517 gas_ref,
518 iota_sdk_types::Address::random(),
519 None,
520 sender,
521 &sender_key,
522 rgp,
523 );
524 let mut other_tx = make_transfer_iota_transaction(
527 gas_ref,
528 iota_sdk_types::Address::random(),
529 None,
530 sender,
531 &sender_key,
532 rgp,
533 );
534 let mut bad_tx = valid_tx.clone();
535 bad_tx.tx_signatures_mut_for_testing()[0] =
536 other_tx.tx_signatures_mut_for_testing()[0].clone();
537
538 let expected_error = epoch_store
539 .signature_verifier
540 .verify_tx(bad_tx.data())
541 .unwrap_err();
542 assert!(
543 matches!(expected_error, IotaError::InvalidSignature { .. }),
544 "{expected_error:?}"
545 );
546
547 let to_bytes = |tx: &iota_types::transaction::TransactionEnvelope| {
548 bcs::to_bytes(&ConsensusTransaction::new_user_transaction(tx.clone())).unwrap()
549 };
550 let valid_bytes = to_bytes(&valid_tx);
551 let bad_bytes = to_bytes(&bad_tx);
552
553 let metrics = IotaTxValidatorMetrics::new(&Default::default());
554 let validator = IotaTxValidator::new(
555 epoch_store,
556 Arc::new(CheckpointServiceNoop {}),
557 metrics.clone(),
558 );
559
560 let res = validator.verify_batch(&[&valid_bytes]);
561 assert!(res.is_ok(), "{res:?}");
562 assert_eq!(metrics.user_transaction_signatures_verified.get(), 1);
563
564 for batch in [vec![&bad_bytes[..]], vec![&valid_bytes[..], &bad_bytes[..]]] {
565 let res = validator.verify_batch(&batch);
566 assert!(
567 matches!(
568 &res,
569 Err(starfish_core::ValidationError::InvalidTransaction(msg))
570 if *msg == expected_error.to_string()
571 ),
572 "{res:?}"
573 );
574 }
575 assert_eq!(metrics.user_transaction_signatures_verified.get(), 1);
576 }
577
578 #[sim_test]
589 async fn validate_transactions_feature_gating_with_gated_features_enabled() {
590 validate_transactions_feature_gating(true).await;
591 }
592
593 #[sim_test]
594 async fn validate_transactions_feature_gating_with_gated_features_disabled() {
595 validate_transactions_feature_gating(false).await;
596 }
597
598 async fn validate_transactions_feature_gating(gated_features_enabled: bool) {
599 use iota_types::crypto::{
600 AccountPrivateKey, AuthorityPublicKeyBytes, deterministic_random_account_private_key,
601 };
602
603 use crate::test_utils::make_transfer_iota_transaction;
604
605 let (sender, sender_key): (_, AccountPrivateKey) =
606 deterministic_random_account_private_key();
607 let gas_object_id = ObjectId::random();
608 let gas_object = Object::with_id_owner_for_testing(gas_object_id, sender);
609
610 let network_config =
611 iota_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir()
612 .with_objects(vec![gas_object.clone()])
613 .build();
614
615 let _guard = ProtocolConfig::apply_overrides_for_testing(move |_, mut config| {
616 config.set_enable_pcool_flow_for_testing(gated_features_enabled);
617 config.set_calculate_validator_scores_for_testing(gated_features_enabled);
618 config.set_enable_validator_attestation_for_testing(false);
620 config
621 });
622 let state = TestAuthorityBuilder::new()
623 .with_network_config(&network_config, 0)
624 .build()
625 .await;
626
627 let rgp = state.epoch_store_for_testing().reference_gas_price();
628 let gas_ref = state.get_object(&gas_object_id).unwrap().object_ref();
629 let recipient = iota_sdk_types::Address::random();
630 let signed_tx =
631 make_transfer_iota_transaction(gas_ref, recipient, None, sender, &sender_key, rgp);
632
633 let metrics = IotaTxValidatorMetrics::new(&Default::default());
634 let validator = IotaTxValidator::new(
635 state.epoch_store_for_testing().clone(),
636 Arc::new(CheckpointServiceNoop {}),
637 metrics,
638 );
639
640 let protocol_config = validator.epoch_store.protocol_config();
641 assert_eq!(protocol_config.enable_pcool_flow(), gated_features_enabled);
642 assert_eq!(
643 protocol_config.calculate_validator_scores(),
644 gated_features_enabled
645 );
646 let authority = AuthorityPublicKeyBytes::default();
647
648 #[allow(deprecated)]
656 let testable_variants: Vec<(&str, ConsensusTransactionKind)> = vec![
657 (
658 "EndOfPublish",
659 ConsensusTransactionKind::EndOfPublish(authority),
660 ),
661 (
662 "NewJWKFetchedDeprecated",
663 ConsensusTransactionKind::NewJWKFetchedDeprecated,
664 ),
665 (
666 "CapabilityNotificationV1",
667 ConsensusTransactionKind::CapabilityNotificationV1(
668 iota_types::messages_consensus::AuthorityCapabilitiesV1::new(
669 authority,
670 Chain::Mainnet,
671 iota_types::supported_protocol_versions::SupportedProtocolVersions::SYSTEM_DEFAULT,
672 vec![],
673 ),
674 ),
675 ),
676 (
677 "RandomnessDkgMessage",
678 ConsensusTransactionKind::RandomnessDkgMessage(authority, vec![]),
679 ),
680 (
681 "RandomnessDkgConfirmation",
682 ConsensusTransactionKind::RandomnessDkgConfirmation(authority, vec![]),
683 ),
684 (
685 "MisbehaviorReport",
686 ConsensusTransactionKind::MisbehaviorReport(VersionedMisbehaviorReport::new_v1(
687 authority,
688 0,
689 MisbehaviorObservationsV1 {
690 faulty_blocks_provable: vec![],
691 faulty_blocks_unprovable: vec![],
692 missing_proposals: vec![],
693 equivocations: vec![],
694 },
695 )),
696 ),
697 (
698 "UserTransactionV1",
699 ConsensusTransactionKind::UserTransactionV1(Box::new(AttestedTransaction::new(
700 signed_tx, None,
701 ))),
702 ),
703 (
704 "OverloadNotificationV1",
705 ConsensusTransactionKind::OverloadNotificationV1(authority, 0, 50),
706 ),
707 (
708 "TransactionDenyRuleProposal",
709 ConsensusTransactionKind::TransactionDenyRuleProposal(
710 iota_types::messages_consensus::TransactionDenyRuleProposal {
711 authority,
712 generation: 0,
713 proposed_rules: Default::default(),
714 },
715 ),
716 ),
717 ];
718
719 for (name, kind) in testable_variants {
720 let gated = consensus_transaction_feature_gate(&kind, protocol_config);
721 let result = validator.validate_transactions(vec![kind]);
722
723 match gated {
724 Some(false) => {
725 assert!(
727 matches!(&result, Err(IotaError::UnsupportedFeature { .. })),
728 "{name}: feature flag is disabled, expected UnsupportedFeature, \
729 got {result:?}",
730 );
731 }
732 Some(true) | None => {
733 assert!(
736 !matches!(&result, Err(IotaError::UnsupportedFeature { .. })),
737 "{name}: should not be rejected as UnsupportedFeature, got {result:?}",
738 );
739 }
740 }
741 }
742 }
743 fn validator_attestation_off() -> OverrideGuard {
747 ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
748 config.set_enable_validator_attestation_for_testing(false);
749 config
750 })
751 }
752
753 async fn self_identifier_fixture(
757 protocol_version: Option<ProtocolVersion>,
758 ) -> (Arc<AuthorityState>, AuthorityKeyPair, IotaTxValidator) {
759 let mut network_config_builder =
760 iota_swarm_config::network_config_builder::ConfigBuilder::new_with_temp_dir();
761 if let Some(version) = protocol_version {
762 network_config_builder = network_config_builder.with_protocol_version(version);
763 }
764 let network_config = network_config_builder.build();
765 let keypair = network_config.validator_configs()[0]
766 .authority_key_pair()
767 .copy();
768 let mut builder = TestAuthorityBuilder::new().with_network_config(&network_config, 0);
769 if let Some(version) = protocol_version {
770 builder = builder
771 .with_protocol_config(ProtocolConfig::get_for_version(version, Chain::Unknown));
772 }
773 let state = builder.build().await;
774 let validator = IotaTxValidator::new(
775 state.epoch_store_for_testing().clone(),
776 Arc::new(CheckpointServiceNoop {}),
777 IotaTxValidatorMetrics::new(&Default::default()),
778 );
779 (state, keypair, validator)
780 }
781
782 fn move_call_with_type_name(
784 state: &AuthorityState,
785 type_name: Identifier,
786 ) -> TransactionEnvelope {
787 use iota_sdk_types::{Address, StructTag, Transaction, TypeTag};
788 use iota_types::{
789 base_types::random_object_ref,
790 crypto::{AccountPrivateKey, deterministic_random_account_private_key},
791 programmable_transaction_builder::ProgrammableTransactionBuilder,
792 transaction::{TEST_ONLY_GAS_UNIT_FOR_TRANSFER, TransactionAPI},
793 utils::to_sender_signed_transaction,
794 };
795
796 let (sender, sender_key): (_, AccountPrivateKey) =
797 deterministic_random_account_private_key();
798 let gas_price = state.epoch_store_for_testing().reference_gas_price();
799 let type_arg = TypeTag::Struct(Box::new(StructTag::new(
800 "0x2".parse::<Address>().unwrap(),
801 Identifier::from_static("iota"),
802 type_name,
803 vec![],
804 )));
805 let mut builder = ProgrammableTransactionBuilder::new();
806 builder.programmable_move_call(
807 ObjectId::from("0x2".parse::<Address>().unwrap()),
808 Identifier::from_static("coin"),
809 Identifier::from_static("zero"),
810 vec![type_arg],
811 vec![],
812 );
813 let transaction = Transaction::new_programmable(
814 sender,
815 vec![random_object_ref()],
816 builder.finish(),
817 gas_price * TEST_ONLY_GAS_UNIT_FOR_TRANSFER,
818 gas_price,
819 );
820 to_sender_signed_transaction(transaction, &sender_key)
821 }
822
823 fn user_transaction(signed_tx: TransactionEnvelope) -> ConsensusTransactionKind {
824 ConsensusTransactionKind::UserTransactionV1(Box::new(AttestedTransaction::new(
825 signed_tx, None,
826 )))
827 }
828
829 fn attested_user_transaction(signed_tx: TransactionEnvelope) -> ConsensusTransactionKind {
832 let attestation = Attestation::new_authority(
833 AttestationData::V1 {
834 computation_units: 0,
835 shared_object_versions: vec![],
836 },
837 0,
838 );
839
840 ConsensusTransactionKind::UserTransactionV1(Box::new(AttestedTransaction::new(
841 signed_tx,
842 Some(attestation),
843 )))
844 }
845
846 fn certificate(
848 signed_tx: TransactionEnvelope,
849 state: &AuthorityState,
850 keypair: &AuthorityKeyPair,
851 ) -> ConsensusTransactionKind {
852 ConsensusTransactionKind::CertifiedTransaction(Box::new(
853 CertifiedTransaction::new_from_keypairs_for_testing(
854 signed_tx.into_data(),
855 std::slice::from_ref(keypair),
856 &state.clone_committee_for_testing(),
857 ),
858 ))
859 }
860
861 fn assert_self_identifier_rejected(result: &Result<(), IotaError>) {
862 assert!(
863 matches!(
864 result,
865 Err(IotaError::UserInput {
866 error: UserInputError::InvalidIdentifier { error }
867 }) if error == "<SELF>"
868 ),
869 "{result:?}"
870 );
871 }
872
873 #[tokio::test]
874 async fn reject_identifier_move_core_rejects_in_user_transaction() {
875 let _guard = validator_attestation_off();
876 let (state, _, validator) = self_identifier_fixture(None).await;
877 assert!(
878 validator
879 .epoch_store
880 .protocol_config()
881 .disallow_self_identifier_in_transactions()
882 );
883
884 let result = validator.validate_transactions(vec![user_transaction(
885 move_call_with_type_name(&state, Identifier::new_unchecked("<SELF>")),
886 )]);
887 assert_self_identifier_rejected(&result);
888
889 validator
890 .validate_transactions(vec![user_transaction(move_call_with_type_name(
891 &state,
892 Identifier::from_static("IOTA"),
893 ))])
894 .unwrap();
895 }
896
897 #[tokio::test]
900 async fn reject_identifier_move_core_rejects_in_attested_user_transaction() {
901 let (state, _, validator) = self_identifier_fixture(None).await;
902 let protocol_config = validator.epoch_store.protocol_config();
903 assert!(protocol_config.disallow_self_identifier_in_transactions());
904 assert!(protocol_config.enable_validator_attestation());
905
906 let result = validator.validate_transactions(vec![attested_user_transaction(
907 move_call_with_type_name(&state, Identifier::new_unchecked("<SELF>")),
908 )]);
909 assert_self_identifier_rejected(&result);
910
911 validator
912 .validate_transactions(vec![attested_user_transaction(move_call_with_type_name(
913 &state,
914 Identifier::from_static("IOTA"),
915 ))])
916 .unwrap();
917 }
918
919 #[tokio::test]
920 async fn reject_identifier_move_core_rejects_in_certificate() {
921 let _guard = validator_attestation_off();
922 let (state, keypair, validator) = self_identifier_fixture(None).await;
923 assert!(
924 validator
925 .epoch_store
926 .protocol_config()
927 .disallow_self_identifier_in_transactions()
928 );
929
930 let result = validator.validate_transactions(vec![certificate(
931 move_call_with_type_name(&state, Identifier::new_unchecked("<SELF>")),
932 &state,
933 &keypair,
934 )]);
935 assert_self_identifier_rejected(&result);
936
937 validator
938 .validate_transactions(vec![certificate(
939 move_call_with_type_name(&state, Identifier::from_static("IOTA")),
940 &state,
941 &keypair,
942 )])
943 .unwrap();
944 }
945
946 #[tokio::test]
947 async fn reject_system_transaction_in_user_transaction() {
948 use iota_sdk_types::{
949 Address, Event, GenesisTransaction, SenderSignedTransaction, StructTag, Transaction,
950 TransactionKind,
951 };
952 use iota_types::transaction::TransactionAPI;
953
954 let (_, _, validator) = self_identifier_fixture(None).await;
955 assert!(
956 validator
957 .epoch_store
958 .protocol_config()
959 .disallow_self_identifier_in_transactions()
960 );
961
962 let event = Event {
965 package_id: ObjectId::random(),
966 module: Identifier::new_unchecked("<SELF>"),
967 sender: Address::random(),
968 struct_tag: StructTag::new(
969 "0x2".parse::<Address>().unwrap(),
970 Identifier::from_static("iota"),
971 Identifier::from_static("IOTA"),
972 vec![],
973 ),
974 contents: vec![],
975 };
976 let signed_tx = TransactionEnvelope::new(SenderSignedTransaction::new(
977 Transaction::new_system_transaction(TransactionKind::Genesis(GenesisTransaction {
978 objects: vec![],
979 events: vec![event],
980 })),
981 vec![],
982 ));
983 let result = validator.validate_transactions(vec![user_transaction(signed_tx)]);
984 assert!(
985 matches!(
986 &result,
987 Err(IotaError::UserInput {
988 error: UserInputError::Unsupported(_)
989 })
990 ),
991 "{result:?}"
992 );
993 }
994
995 #[tokio::test]
996 async fn accept_identifier_move_core_rejects_before_the_flag() {
997 let (state, keypair, validator) =
998 self_identifier_fixture(Some(ProtocolVersion::new(39))).await;
999 assert!(
1000 !validator
1001 .epoch_store
1002 .protocol_config()
1003 .disallow_self_identifier_in_transactions()
1004 );
1005
1006 validator
1007 .validate_transactions(vec![
1008 user_transaction(move_call_with_type_name(
1009 &state,
1010 Identifier::new_unchecked("<SELF>"),
1011 )),
1012 certificate(
1013 move_call_with_type_name(&state, Identifier::new_unchecked("<SELF>")),
1014 &state,
1015 &keypair,
1016 ),
1017 ])
1018 .unwrap();
1019 }
1020
1021 #[tokio::test]
1024 async fn reject_certificate_with_validator_attestation_on() {
1025 let _guard = ProtocolConfig::apply_overrides_for_testing(|_, mut config| {
1026 config.set_enable_pcool_flow_for_testing(true);
1027 config.set_enable_validator_attestation_for_testing(true);
1028 config.set_checkpoint_summary_version_specific_data_for_testing(2);
1029 config
1030 });
1031 let (state, keypair, validator) = self_identifier_fixture(None).await;
1032 assert!(
1033 validator
1034 .epoch_store
1035 .protocol_config()
1036 .enable_validator_attestation()
1037 );
1038
1039 let result = validator.validate_transactions(vec![certificate(
1040 move_call_with_type_name(&state, Identifier::from_static("IOTA")),
1041 &state,
1042 &keypair,
1043 )]);
1044 assert!(
1045 matches!(&result, Err(IotaError::UnsupportedFeature { .. })),
1046 "{result:?}"
1047 );
1048 }
1049
1050 #[tokio::test]
1051 async fn accept_checkpoint_signature_when_forwarding_fails() {
1052 struct FailingCheckpointService;
1053 impl CheckpointServiceNotify for FailingCheckpointService {
1054 fn notify_checkpoint_signature(
1055 &self,
1056 _: &AuthorityPerEpochStore,
1057 _: &CheckpointSignatureMessage,
1058 ) -> IotaResult {
1059 Err(IotaError::Storage("disk failure".to_string()))
1060 }
1061
1062 fn notify_checkpoint(&self) -> IotaResult {
1063 Ok(())
1064 }
1065 }
1066
1067 let state = TestAuthorityBuilder::new().build().await;
1068 let epoch_store = state.epoch_store_for_testing().clone();
1069 let summary = certified_summary(epoch_store.epoch(), 1, None).into_data();
1070 let transaction =
1071 ConsensusTransaction::new_checkpoint_signature_message(CheckpointSignatureMessage {
1072 summary: SignedCheckpointSummary::new(
1073 epoch_store.epoch(),
1074 summary,
1075 &*state.secret,
1076 state.name,
1077 ),
1078 });
1079 let bytes = bcs::to_bytes(&transaction).unwrap();
1080
1081 let validator = IotaTxValidator::new(
1082 epoch_store,
1083 Arc::new(FailingCheckpointService),
1084 IotaTxValidatorMetrics::new(&Default::default()),
1085 );
1086 let result = validator.verify_batch(&[&bytes]);
1087 assert!(result.is_ok(), "{result:?}");
1088 }
1089
1090 fn transaction_dependencies_enabled(enabled: bool) -> OverrideGuard {
1093 ProtocolConfig::apply_overrides_for_testing(move |_, mut config| {
1094 config.set_enable_validator_attestation_for_testing(false);
1095 config.set_enable_transaction_dependencies_for_testing(enabled);
1096 config
1097 })
1098 }
1099
1100 fn transfer_with_dependency(
1103 state: &AuthorityState,
1104 dependency: Option<TransactionDigest>,
1105 ) -> TransactionEnvelope {
1106 use iota_sdk_types::Address;
1107 use iota_test_transaction_builder::TestTransactionBuilder;
1108 use iota_types::{
1109 base_types::random_object_ref,
1110 crypto::{AccountPrivateKey, deterministic_random_account_private_key},
1111 };
1112
1113 let (sender, sender_key): (_, AccountPrivateKey) =
1114 deterministic_random_account_private_key();
1115 let epoch_store = state.epoch_store_for_testing();
1116 let mut builder = TestTransactionBuilder::new(
1117 sender,
1118 random_object_ref(),
1119 epoch_store.reference_gas_price(),
1120 )
1121 .transfer_iota(None, Address::random());
1122 if let Some(dependency) = dependency {
1123 builder = builder.with_transaction_dependency(dependency, epoch_store.epoch());
1124 }
1125 builder.build_and_sign(&sender_key)
1126 }
1127
1128 fn move_account_transfer(state: &AuthorityState, call_arg: CallArg) -> TransactionEnvelope {
1131 use iota_sdk_types::{Address, MoveAuthenticator, MoveAuthenticatorV1, Version};
1132 use iota_test_transaction_builder::TestTransactionBuilder;
1133 use iota_types::base_types::random_object_ref;
1134
1135 let authenticator = MoveAuthenticatorV1::new(
1136 vec![call_arg],
1137 vec![],
1138 SharedObjectReference::new(ObjectId::random(), Version::INITIAL_SHARED_VERSION, false),
1139 );
1140 let transaction = TestTransactionBuilder::new(
1141 authenticator.address(),
1142 random_object_ref(),
1143 state.epoch_store_for_testing().reference_gas_price(),
1144 )
1145 .transfer_iota(None, Address::random())
1146 .build();
1147 TransactionEnvelope::from_user_sig_data(
1148 transaction,
1149 vec![UserSignature::MoveAuthenticator(MoveAuthenticator::V1(
1150 authenticator,
1151 ))],
1152 )
1153 }
1154
1155 #[tokio::test]
1156 async fn reject_transaction_dependency_before_the_flag() {
1157 let _guard = transaction_dependencies_enabled(false);
1158 let (state, keypair, validator) = self_identifier_fixture(None).await;
1159 let dependency = TransactionDigest::random();
1160
1161 for (case, kind) in [
1162 (
1163 "user transaction",
1164 user_transaction(transfer_with_dependency(&state, Some(dependency))),
1165 ),
1166 (
1167 "certificate",
1168 certificate(
1169 transfer_with_dependency(&state, Some(dependency)),
1170 &state,
1171 &keypair,
1172 ),
1173 ),
1174 (
1175 "Move authenticator argument",
1176 user_transaction(move_account_transfer(
1177 &state,
1178 CallArg::TransactionDependency(dependency),
1179 )),
1180 ),
1181 ] {
1182 let result = validator.validate_transactions(vec![kind]);
1183 assert!(
1184 matches!(&result, Err(IotaError::UnsupportedFeature { .. })),
1185 "{case}: {result:?}"
1186 );
1187 }
1188
1189 validator
1190 .validate_transactions(vec![
1191 user_transaction(transfer_with_dependency(&state, None)),
1192 certificate(transfer_with_dependency(&state, None), &state, &keypair),
1193 user_transaction(move_account_transfer(&state, CallArg::Pure(vec![]))),
1194 ])
1195 .unwrap();
1196 }
1197
1198 fn claim_account() -> TransactionEnvelope {
1200 use iota_sdk_types::{
1201 ClaimAccountTransaction, SmartAccountClaim, Transaction, TransactionKind,
1202 crypto::PublicKey,
1203 };
1204 use iota_types::{
1205 base_types::random_object_ref,
1206 crypto::{AccountPrivateKey, deterministic_random_account_private_key},
1207 transaction::TransactionAPI,
1208 utils::to_sender_signed_transaction,
1209 };
1210
1211 let (sender, sender_key): (_, AccountPrivateKey) =
1212 deterministic_random_account_private_key();
1213 let claim = SmartAccountClaim::new(&PublicKey::Ed25519(sender_key.public_key()));
1214 let transaction = Transaction::new(
1215 TransactionKind::new_claim_account(ClaimAccountTransaction::new_smart_account(claim)),
1216 sender,
1217 random_object_ref(),
1218 100_000_000,
1219 1,
1220 );
1221 to_sender_signed_transaction(transaction, &sender_key)
1222 }
1223
1224 fn claim_account_enabled(enabled: bool) -> OverrideGuard {
1227 ProtocolConfig::apply_overrides_for_testing(move |_, mut config| {
1228 config.set_enable_validator_attestation_for_testing(false);
1229 if enabled {
1230 config.set_claim_account_max_computation_units_for_testing(5_000);
1231 config.set_claim_account_storage_bytes_bound_for_testing(2_000);
1232 }
1233 config.set_enable_claim_account_transaction_for_testing(enabled);
1234 config
1235 })
1236 }
1237
1238 #[tokio::test]
1239 async fn reject_claim_account_before_the_flag() {
1240 let _guard = claim_account_enabled(false);
1241 let (state, keypair, validator) = self_identifier_fixture(None).await;
1242
1243 for (case, kind) in [
1244 ("user transaction", user_transaction(claim_account())),
1245 (
1246 "certificate",
1247 certificate(claim_account(), &state, &keypair),
1248 ),
1249 ] {
1250 let result = validator.validate_transactions(vec![kind]);
1251 assert!(
1252 matches!(&result, Err(IotaError::UnsupportedFeature { .. })),
1253 "{case}: {result:?}"
1254 );
1255 }
1256 }
1257
1258 #[tokio::test]
1259 async fn accept_claim_account_with_the_flag() {
1260 let _guard = claim_account_enabled(true);
1261 let (state, keypair, validator) = self_identifier_fixture(None).await;
1262
1263 validator
1264 .validate_transactions(vec![
1265 user_transaction(claim_account()),
1266 certificate(claim_account(), &state, &keypair),
1267 ])
1268 .unwrap();
1269 }
1270
1271 #[tokio::test]
1272 async fn accept_transaction_dependency_with_the_flag() {
1273 let _guard = transaction_dependencies_enabled(true);
1274 let (state, keypair, validator) = self_identifier_fixture(None).await;
1275 let dependency = Some(TransactionDigest::random());
1276
1277 validator
1278 .validate_transactions(vec![
1279 user_transaction(transfer_with_dependency(&state, dependency)),
1280 certificate(
1281 transfer_with_dependency(&state, dependency),
1282 &state,
1283 &keypair,
1284 ),
1285 ])
1286 .unwrap();
1287 }
1288
1289 #[tokio::test]
1290 async fn reject_transaction_dependency_in_a_move_authenticator_with_the_flag() {
1291 let _guard = transaction_dependencies_enabled(true);
1292 let (state, _keypair, validator) = self_identifier_fixture(None).await;
1293
1294 let result =
1295 validator.validate_transactions(vec![user_transaction(move_account_transfer(
1296 &state,
1297 CallArg::TransactionDependency(TransactionDigest::random()),
1298 ))]);
1299 assert!(
1300 matches!(&result, Err(IotaError::UnsupportedFeature { .. })),
1301 "{result:?}"
1302 );
1303 }
1304}