Skip to main content

iota_core/
validator_tx_finalizer.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5#[cfg(any(msim, test))]
6use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
7use std::{cmp::min, ops::Add, sync::Arc, time::Duration};
8
9use arc_swap::ArcSwap;
10use iota_metrics::LATENCY_SEC_BUCKETS;
11use iota_sdk_types::TransactionDigest;
12use iota_types::{base_types::AuthorityName, transaction::VerifiedSignedTransaction};
13use prometheus_filtered::{
14    Histogram, IntCounter, Registry, register_histogram_with_registry,
15    register_int_counter_with_registry,
16};
17use tokio::{select, time::Instant};
18use tracing::{debug, error, trace};
19
20use crate::{
21    authority::authority_per_epoch_store::AuthorityPerEpochStore,
22    authority_aggregator::AuthorityAggregator, authority_client::AuthorityAPI,
23    execution_cache::TransactionCacheRead,
24};
25
26struct ValidatorTxFinalizerMetrics {
27    num_finalization_attempts: IntCounter,
28    num_successful_finalizations: IntCounter,
29    finalization_latency: Histogram,
30    validator_tx_finalizer_attempt_delay: Histogram,
31    #[cfg(any(msim, test))]
32    num_finalization_attempts_for_testing: AtomicU64,
33    #[cfg(test)]
34    num_successful_finalizations_for_testing: AtomicU64,
35}
36
37impl ValidatorTxFinalizerMetrics {
38    fn new(registry: &Registry) -> Self {
39        Self {
40            num_finalization_attempts: register_int_counter_with_registry!(
41                "validator_tx_finalizer_num_finalization_attempts",
42                "Total number of attempts to finalize a transaction",
43                registry,
44            )
45            .unwrap(),
46            num_successful_finalizations: register_int_counter_with_registry!(
47                "validator_tx_finalizer_num_successful_finalizations",
48                "Number of transactions successfully finalized",
49                registry,
50            )
51            .unwrap(),
52            finalization_latency: register_histogram_with_registry!(
53                "validator_tx_finalizer_finalization_latency",
54                "Latency of transaction finalization",
55                LATENCY_SEC_BUCKETS.to_vec(),
56                registry,
57            )
58            .unwrap(),
59            validator_tx_finalizer_attempt_delay: register_histogram_with_registry!(
60                "validator_tx_finalizer_attempt_delay",
61                "Duration that a validator in the committee waited before attempting to finalize the transaction",
62                vec![60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0],
63                registry,
64            )
65            .unwrap(),
66            #[cfg(any(msim, test))]
67            num_finalization_attempts_for_testing: AtomicU64::new(0),
68            #[cfg(test)]
69            num_successful_finalizations_for_testing: AtomicU64::new(0),
70        }
71    }
72
73    fn start_finalization(&self) -> Instant {
74        self.num_finalization_attempts.inc();
75        #[cfg(any(msim, test))]
76        self.num_finalization_attempts_for_testing
77            .fetch_add(1, Relaxed);
78        Instant::now()
79    }
80
81    fn finalization_succeeded(&self, start_time: Instant) {
82        let latency = start_time.elapsed();
83        self.num_successful_finalizations.inc();
84        self.finalization_latency.observe(latency.as_secs_f64());
85        #[cfg(test)]
86        self.num_successful_finalizations_for_testing
87            .fetch_add(1, Relaxed);
88    }
89}
90
91pub struct ValidatorTxFinalizerConfig {
92    pub tx_finalization_delay: Duration,
93    pub tx_finalization_timeout: Duration,
94    /// Incremental delay for validators to wake up to finalize a transaction.
95    pub validator_delay_increments_sec: u64,
96    pub validator_max_delay: Duration,
97}
98
99#[cfg(not(any(msim, test)))]
100impl Default for ValidatorTxFinalizerConfig {
101    fn default() -> Self {
102        Self {
103            // Only wake up the transaction finalization task for a given transaction
104            // after 1 mins of seeing it. This gives plenty of time for the transaction
105            // to become final in the normal way. We also don't want this delay to be too long
106            // to reduce memory usage held up by the finalizer threads.
107            tx_finalization_delay: Duration::from_secs(60),
108            // If a transaction can not be finalized within 1 min of being woken up, give up.
109            tx_finalization_timeout: Duration::from_secs(60),
110            validator_delay_increments_sec: 10,
111            validator_max_delay: Duration::from_secs(180),
112        }
113    }
114}
115
116#[cfg(any(msim, test))]
117impl Default for ValidatorTxFinalizerConfig {
118    fn default() -> Self {
119        Self {
120            tx_finalization_delay: Duration::from_secs(5),
121            tx_finalization_timeout: Duration::from_secs(60),
122            validator_delay_increments_sec: 1,
123            validator_max_delay: Duration::from_secs(15),
124        }
125    }
126}
127
128/// The `ValidatorTxFinalizer` is responsible for finalizing transactions that
129/// have been signed by the validator. It does this by waiting for a delay
130/// after the transaction has been signed, and then attempting to finalize
131/// the transaction if it has not yet been done by a fullnode.
132pub struct ValidatorTxFinalizer<C: Clone> {
133    agg: Arc<ArcSwap<AuthorityAggregator<C>>>,
134    name: AuthorityName,
135    config: Arc<ValidatorTxFinalizerConfig>,
136    metrics: Arc<ValidatorTxFinalizerMetrics>,
137}
138
139impl<C: Clone> ValidatorTxFinalizer<C> {
140    pub fn new(
141        agg: Arc<ArcSwap<AuthorityAggregator<C>>>,
142        name: AuthorityName,
143        registry: &Registry,
144    ) -> Self {
145        Self {
146            agg,
147            name,
148            config: Arc::new(ValidatorTxFinalizerConfig::default()),
149            metrics: Arc::new(ValidatorTxFinalizerMetrics::new(registry)),
150        }
151    }
152
153    #[cfg(test)]
154    pub(crate) fn new_for_testing(
155        agg: Arc<ArcSwap<AuthorityAggregator<C>>>,
156        name: AuthorityName,
157    ) -> Self {
158        Self::new(agg, name, &Registry::new())
159    }
160
161    #[cfg(test)]
162    pub(crate) fn auth_agg(&self) -> &Arc<ArcSwap<AuthorityAggregator<C>>> {
163        &self.agg
164    }
165
166    #[cfg(any(msim, test))]
167    pub fn num_finalization_attempts_for_testing(&self) -> u64 {
168        self.metrics
169            .num_finalization_attempts_for_testing
170            .load(Relaxed)
171    }
172}
173
174impl<C> ValidatorTxFinalizer<C>
175where
176    C: Clone + AuthorityAPI + Send + Sync + 'static,
177{
178    pub async fn track_signed_tx(
179        &self,
180        cache_read: Arc<dyn TransactionCacheRead>,
181        epoch_store: &Arc<AuthorityPerEpochStore>,
182        tx: VerifiedSignedTransaction,
183    ) {
184        let tx_digest = *tx.digest();
185        trace!(?tx_digest, "Tracking signed transaction");
186        match self
187            .delay_and_finalize_tx(cache_read, epoch_store, tx)
188            .await
189        {
190            Ok(did_run) => {
191                if did_run {
192                    debug!(?tx_digest, "Transaction finalized");
193                }
194            }
195            Err(err) => {
196                debug!(?tx_digest, "Failed to finalize transaction: {err}");
197            }
198        }
199    }
200
201    async fn delay_and_finalize_tx(
202        &self,
203        cache_read: Arc<dyn TransactionCacheRead>,
204        epoch_store: &Arc<AuthorityPerEpochStore>,
205        tx: VerifiedSignedTransaction,
206    ) -> anyhow::Result<bool> {
207        let tx_digest = *tx.digest();
208        let Some(tx_finalization_delay) = self.determine_finalization_delay(&tx_digest) else {
209            return Ok(false);
210        };
211        let digests = [tx_digest];
212        select! {
213            _ = tokio::time::sleep(tx_finalization_delay) => {
214                trace!(?tx_digest, "Waking up to finalize transaction");
215            }
216            _ = cache_read.try_notify_read_executed_effects_digests(
217                "ValidatorTxFinalizer::notify_read_executed_effects_digests",
218                &digests,
219            ) => {
220                trace!(?tx_digest, "Transaction already finalized");
221                return Ok(false);
222            }
223        }
224
225        if epoch_store.is_pending_consensus_certificate(&tx_digest) {
226            trace!(
227                ?tx_digest,
228                "Transaction has been submitted to consensus, no need to help drive finality"
229            );
230            return Ok(false);
231        }
232
233        self.metrics
234            .validator_tx_finalizer_attempt_delay
235            .observe(tx_finalization_delay.as_secs_f64());
236        let start_time = self.metrics.start_finalization();
237        debug!(
238            ?tx_digest,
239            "Invoking authority aggregator to finalize transaction"
240        );
241        tokio::time::timeout(
242            self.config.tx_finalization_timeout,
243            self.agg
244                .load()
245                .execute_transaction_block(tx.into_unsigned().inner(), None),
246        )
247        .await??;
248        self.metrics.finalization_succeeded(start_time);
249        Ok(true)
250    }
251
252    // We want to avoid all validators waking up at the same time to finalize the
253    // same transaction. That can lead to a waste of resource and flood the
254    // network unnecessarily. Here we use the transaction digest to determine an
255    // order of all validators. Validators will wake up one by one with
256    // incremental delays to finalize the transaction. The hope is that the
257    // first few should be able to finalize the transaction, and the rest will
258    // see it already executed and do not need to do anything.
259    fn determine_finalization_delay(&self, tx_digest: &TransactionDigest) -> Option<Duration> {
260        let agg = self.agg.load();
261        let order = agg.committee.shuffle_by_stake_from_tx_digest(tx_digest);
262        let Some(position) = order.iter().position(|&name| name == self.name) else {
263            // Somehow the validator is not found in the committee. This should never
264            // happen. TODO: This is where we should report system invariant
265            // violation.
266            error!("Validator {} not found in the committee", self.name);
267            return None;
268        };
269        // TODO: As an optimization, we could also limit the number of validators that
270        // would do this.
271        let extra_delay = position as u64 * self.config.validator_delay_increments_sec;
272        let delay = self
273            .config
274            .tx_finalization_delay
275            .add(Duration::from_secs(extra_delay));
276        Some(min(delay, self.config.validator_max_delay))
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use std::{
283        cmp::min,
284        collections::BTreeMap,
285        iter,
286        net::SocketAddr,
287        num::NonZeroUsize,
288        sync::{
289            Arc,
290            atomic::{AtomicBool, Ordering::Relaxed},
291        },
292    };
293
294    use arc_swap::ArcSwap;
295    use async_trait::async_trait;
296    use iota_macros::sim_test;
297    use iota_sdk_types::{Address, ObjectId, TransactionDigest, TransactionEvents};
298    use iota_swarm_config::network_config_builder::ConfigBuilder;
299    use iota_test_transaction_builder::TestTransactionBuilder;
300    use iota_types::{
301        base_types::AuthorityName,
302        committee::{CommitteeTrait, StakeUnit},
303        crypto::{AccountPrivateKey, get_account_private_key},
304        effects::TransactionEffectsAPI,
305        error::IotaError,
306        executable_transaction::VerifiedExecutableTransaction,
307        iota_system_state::IotaSystemState,
308        messages_checkpoint::{CheckpointRequest, CheckpointResponse},
309        messages_grpc::{
310            GetTxStatusRequest, HandleCapabilityNotificationRequestV1,
311            HandleCapabilityNotificationResponseV1, HandleCertificateRequestV1,
312            HandleCertificateResponseV1, HandleSoftBundleCertificatesRequestV1,
313            HandleSoftBundleCertificatesResponseV1, HandleTransactionResponse, ObjectInfoRequest,
314            ObjectInfoResponse, SystemStateRequest, TransactionInfoRequest,
315            TransactionInfoResponse, TxStatusUpdate, ValidatorHealthRequest,
316            ValidatorHealthResponse,
317        },
318        object::Object,
319        transaction::{
320            SignedTransaction, TransactionEnvelope, VerifiedCertificate, VerifiedSignedTransaction,
321            VerifiedTransaction,
322        },
323        utils::to_sender_signed_transaction,
324    };
325
326    use crate::{
327        authority::{AuthorityState, ExecutionEnv, test_authority_builder::TestAuthorityBuilder},
328        authority_aggregator::{AuthorityAggregator, AuthorityAggregatorBuilder},
329        authority_client::{
330            validator::ValidatorAPI, validator_peer::ValidatorPeerAPI, validator_v2::ValidatorV2API,
331        },
332        validator_tx_finalizer::ValidatorTxFinalizer,
333    };
334
335    #[derive(Clone)]
336    struct MockAuthorityClient {
337        authority: Arc<AuthorityState>,
338        inject_fault: Arc<AtomicBool>,
339    }
340
341    #[async_trait]
342    impl ValidatorPeerAPI for MockAuthorityClient {
343        async fn get_checkpoint_v2(
344            &self,
345            _request: CheckpointRequest,
346        ) -> Result<CheckpointResponse, IotaError> {
347            unimplemented!()
348        }
349    }
350    #[async_trait]
351    impl ValidatorV2API for MockAuthorityClient {
352        async fn submit_tx(
353            &self,
354            _transactions: Vec<TransactionEnvelope>,
355            _client_addr: Option<SocketAddr>,
356        ) -> Result<Vec<(TransactionDigest, TxStatusUpdate)>, IotaError> {
357            unimplemented!()
358        }
359        async fn get_tx_status(
360            &self,
361            _request: GetTxStatusRequest,
362            _client_addr: Option<SocketAddr>,
363        ) -> Result<Vec<(TransactionDigest, TxStatusUpdate)>, IotaError> {
364            unimplemented!()
365        }
366        async fn notify_capabilities_v2(
367            &self,
368            _request: HandleCapabilityNotificationRequestV1,
369        ) -> Result<HandleCapabilityNotificationResponseV1, IotaError> {
370            unimplemented!()
371        }
372        async fn health_check(
373            &self,
374            _request: ValidatorHealthRequest,
375        ) -> Result<ValidatorHealthResponse, IotaError> {
376            unimplemented!()
377        }
378    }
379
380    #[async_trait]
381    impl ValidatorAPI for MockAuthorityClient {
382        async fn handle_transaction(
383            &self,
384            transaction: TransactionEnvelope,
385            _client_addr: Option<SocketAddr>,
386        ) -> Result<HandleTransactionResponse, IotaError> {
387            if self.inject_fault.load(Relaxed) {
388                return Err(IotaError::Timeout);
389            }
390            let epoch_store = self.authority.epoch_store_for_testing();
391            self.authority
392                .handle_transaction(
393                    &epoch_store,
394                    VerifiedTransaction::new_unchecked(transaction),
395                )
396                .await
397        }
398
399        async fn handle_certificate_v1(
400            &self,
401            request: HandleCertificateRequestV1,
402            _client_addr: Option<SocketAddr>,
403        ) -> Result<HandleCertificateResponseV1, IotaError> {
404            let epoch_store = self.authority.epoch_store_for_testing();
405            let certificate = VerifiedCertificate::new_unchecked(request.certificate);
406            epoch_store.assign_to_a_new_commit_for_testing(&[certificate.key()]);
407            let (effects, _) = self.authority.try_execute_immediately(
408                &VerifiedExecutableTransaction::new_from_certificate(certificate),
409                ExecutionEnv::new(),
410                &epoch_store,
411            )?;
412            let events = if effects.events_digest().is_some() {
413                self.authority
414                    .get_transaction_events(effects.transaction_digest())?
415            } else {
416                TransactionEvents::default()
417            };
418            let signed_effects = self
419                .authority
420                .sign_effects(effects, &epoch_store)?
421                .into_inner();
422            Ok(HandleCertificateResponseV1 {
423                signed_effects,
424                events: Some(events),
425                input_objects: None,
426                output_objects: None,
427                auxiliary_data: None,
428            })
429        }
430
431        async fn handle_soft_bundle_certificates_v1(
432            &self,
433            _request: HandleSoftBundleCertificatesRequestV1,
434            _client_addr: Option<SocketAddr>,
435        ) -> Result<HandleSoftBundleCertificatesResponseV1, IotaError> {
436            unimplemented!()
437        }
438
439        async fn handle_object_info_request(
440            &self,
441            _request: ObjectInfoRequest,
442        ) -> Result<ObjectInfoResponse, IotaError> {
443            unimplemented!()
444        }
445
446        async fn handle_transaction_info_request(
447            &self,
448            _request: TransactionInfoRequest,
449        ) -> Result<TransactionInfoResponse, IotaError> {
450            unimplemented!()
451        }
452
453        async fn handle_checkpoint(
454            &self,
455            _request: CheckpointRequest,
456        ) -> Result<CheckpointResponse, IotaError> {
457            unimplemented!()
458        }
459
460        async fn handle_system_state_object(
461            &self,
462            _request: SystemStateRequest,
463        ) -> Result<IotaSystemState, IotaError> {
464            unimplemented!()
465        }
466
467        async fn handle_capability_notification_v1(
468            &self,
469            _request: HandleCapabilityNotificationRequestV1,
470        ) -> Result<HandleCapabilityNotificationResponseV1, IotaError> {
471            unimplemented!()
472        }
473    }
474
475    #[sim_test]
476    async fn test_validator_tx_finalizer_basic_flow() {
477        telemetry_subscribers::init_for_testing();
478        let (sender, sender_key) = get_account_private_key();
479        let gas_object = Object::with_owner_for_testing(sender);
480        let gas_object_id = gas_object.id();
481        let (states, auth_agg, clients) = create_validators(gas_object).await;
482        let finalizer1 = ValidatorTxFinalizer::new_for_testing(auth_agg.clone(), states[0].name);
483        let signed_tx = create_tx(&clients, &states[0], sender, &sender_key, gas_object_id).await;
484        let tx_digest = *signed_tx.digest();
485        let cache_read = states[0].get_transaction_cache_reader().clone();
486        let epoch_store = states[0].epoch_store_for_testing();
487        let metrics = finalizer1.metrics.clone();
488        let handle = tokio::spawn(async move {
489            finalizer1
490                .track_signed_tx(cache_read, &epoch_store, signed_tx)
491                .await;
492        });
493        handle.await.unwrap();
494        check_quorum_execution(&auth_agg.load(), &clients, &tx_digest, true);
495        assert_eq!(
496            metrics.num_finalization_attempts_for_testing.load(Relaxed),
497            1
498        );
499        assert_eq!(
500            metrics
501                .num_successful_finalizations_for_testing
502                .load(Relaxed),
503            1
504        );
505    }
506
507    #[tokio::test]
508    async fn test_validator_tx_finalizer_new_epoch() {
509        let (sender, sender_key) = get_account_private_key();
510        let gas_object = Object::with_owner_for_testing(sender);
511        let gas_object_id = gas_object.id();
512        let (states, auth_agg, clients) = create_validators(gas_object).await;
513        let finalizer1 = ValidatorTxFinalizer::new_for_testing(auth_agg.clone(), states[0].name);
514        let signed_tx = create_tx(&clients, &states[0], sender, &sender_key, gas_object_id).await;
515        let tx_digest = *signed_tx.digest();
516        let epoch_store = states[0].epoch_store_for_testing();
517        let cache_read = states[0].get_transaction_cache_reader().clone();
518
519        let metrics = finalizer1.metrics.clone();
520        let handle = tokio::spawn(async move {
521            let _ = epoch_store
522                .within_alive_epoch(finalizer1.track_signed_tx(cache_read, &epoch_store, signed_tx))
523                .await;
524        });
525        states[0].reconfigure_for_testing().await;
526        handle.await.unwrap();
527        check_quorum_execution(&auth_agg.load(), &clients, &tx_digest, false);
528        assert_eq!(
529            metrics.num_finalization_attempts_for_testing.load(Relaxed),
530            0
531        );
532        assert_eq!(
533            metrics
534                .num_successful_finalizations_for_testing
535                .load(Relaxed),
536            0
537        );
538    }
539
540    #[tokio::test]
541    async fn test_validator_tx_finalizer_auth_agg_reconfig() {
542        let (sender, _) = get_account_private_key();
543        let gas_object = Object::with_owner_for_testing(sender);
544        let (states, auth_agg, _clients) = create_validators(gas_object).await;
545        let finalizer1 = ValidatorTxFinalizer::new_for_testing(auth_agg.clone(), states[0].name);
546        let mut new_auth_agg = (**auth_agg.load()).clone();
547        let mut new_committee = (*new_auth_agg.committee).clone();
548        new_committee.epoch = 100;
549        new_auth_agg.committee = Arc::new(new_committee);
550        auth_agg.store(Arc::new(new_auth_agg));
551        assert_eq!(
552            finalizer1.auth_agg().load().committee.epoch,
553            100,
554            "AuthorityAggregator not updated"
555        );
556    }
557
558    #[tokio::test]
559    async fn test_validator_tx_finalizer_already_executed() {
560        telemetry_subscribers::init_for_testing();
561        let (sender, sender_key) = get_account_private_key();
562        let gas_object = Object::with_owner_for_testing(sender);
563        let gas_object_id = gas_object.id();
564        let (states, auth_agg, clients) = create_validators(gas_object).await;
565        let finalizer1 = ValidatorTxFinalizer::new_for_testing(auth_agg.clone(), states[0].name);
566        let signed_tx = create_tx(&clients, &states[0], sender, &sender_key, gas_object_id).await;
567        let tx_digest = *signed_tx.digest();
568        let cache_read = states[0].get_transaction_cache_reader().clone();
569        let epoch_store = states[0].epoch_store_for_testing();
570
571        let metrics = finalizer1.metrics.clone();
572        let signed_tx_clone = signed_tx.clone();
573        let handle = tokio::spawn(async move {
574            finalizer1
575                .track_signed_tx(cache_read, &epoch_store, signed_tx_clone)
576                .await;
577        });
578        auth_agg
579            .load()
580            .execute_transaction_block(&signed_tx.into_inner().into_unsigned(), None)
581            .await
582            .unwrap();
583        handle.await.unwrap();
584        check_quorum_execution(&auth_agg.load(), &clients, &tx_digest, true);
585        assert_eq!(
586            metrics.num_finalization_attempts_for_testing.load(Relaxed),
587            0
588        );
589        assert_eq!(
590            metrics
591                .num_successful_finalizations_for_testing
592                .load(Relaxed),
593            0
594        );
595    }
596
597    #[tokio::test]
598    async fn test_validator_tx_finalizer_timeout() {
599        telemetry_subscribers::init_for_testing();
600        let (sender, sender_key) = get_account_private_key();
601        let gas_object = Object::with_owner_for_testing(sender);
602        let gas_object_id = gas_object.id();
603        let (states, auth_agg, clients) = create_validators(gas_object).await;
604        let finalizer1 = ValidatorTxFinalizer::new_for_testing(auth_agg.clone(), states[0].name);
605        let signed_tx = create_tx(&clients, &states[0], sender, &sender_key, gas_object_id).await;
606        let tx_digest = *signed_tx.digest();
607        let cache_read = states[0].get_transaction_cache_reader().clone();
608        let epoch_store = states[0].epoch_store_for_testing();
609        for client in clients.values() {
610            client.inject_fault.store(true, Relaxed);
611        }
612
613        let metrics = finalizer1.metrics.clone();
614        let signed_tx_clone = signed_tx.clone();
615        let handle = tokio::spawn(async move {
616            finalizer1
617                .track_signed_tx(cache_read, &epoch_store, signed_tx_clone)
618                .await;
619        });
620        handle.await.unwrap();
621        check_quorum_execution(&auth_agg.load(), &clients, &tx_digest, false);
622        assert_eq!(
623            metrics.num_finalization_attempts_for_testing.load(Relaxed),
624            1
625        );
626        assert_eq!(
627            metrics
628                .num_successful_finalizations_for_testing
629                .load(Relaxed),
630            0
631        );
632    }
633
634    #[tokio::test]
635    async fn test_validator_tx_finalizer_determine_finalization_delay() {
636        const COMMITTEE_SIZE: usize = 15;
637        let network_config = ConfigBuilder::new_with_temp_dir()
638            .committee_size(NonZeroUsize::new(COMMITTEE_SIZE).unwrap())
639            .build();
640        let (auth_agg, _) = AuthorityAggregatorBuilder::from_genesis(&network_config.genesis)
641            .build_network_clients();
642        let auth_agg = Arc::new(auth_agg);
643        let finalizers = (0..COMMITTEE_SIZE)
644            .map(|idx| {
645                ValidatorTxFinalizer::new_for_testing(
646                    Arc::new(ArcSwap::new(auth_agg.clone())),
647                    auth_agg.committee.voting_rights[idx].0,
648                )
649            })
650            .collect::<Vec<_>>();
651        let config = finalizers[0].config.clone();
652        for _ in 0..100 {
653            let tx_digest = TransactionDigest::random();
654            let mut delays: Vec<_> = finalizers
655                .iter()
656                .map(|finalizer| {
657                    finalizer
658                        .determine_finalization_delay(&tx_digest)
659                        .map(|delay| delay.as_secs())
660                        .unwrap()
661                })
662                .collect();
663            delays.sort();
664            for (idx, delay) in delays.iter().enumerate() {
665                assert_eq!(
666                    *delay,
667                    min(
668                        config.validator_max_delay.as_secs(),
669                        config.tx_finalization_delay.as_secs()
670                            + idx as u64 * config.validator_delay_increments_sec
671                    )
672                );
673            }
674        }
675    }
676
677    async fn create_validators(
678        gas_object: Object,
679    ) -> (
680        Vec<Arc<AuthorityState>>,
681        Arc<ArcSwap<AuthorityAggregator<MockAuthorityClient>>>,
682        BTreeMap<AuthorityName, MockAuthorityClient>,
683    ) {
684        let network_config = ConfigBuilder::new_with_temp_dir()
685            .committee_size(NonZeroUsize::new(4).unwrap())
686            .with_objects(iter::once(gas_object))
687            .build();
688        let mut authority_states = vec![];
689        for idx in 0..4 {
690            let state = TestAuthorityBuilder::new()
691                .with_network_config(&network_config, idx)
692                .build()
693                .await;
694            authority_states.push(state);
695        }
696        let clients: BTreeMap<_, _> = authority_states
697            .iter()
698            .map(|state| {
699                (
700                    state.name,
701                    MockAuthorityClient {
702                        authority: state.clone(),
703                        inject_fault: Arc::new(AtomicBool::new(false)),
704                    },
705                )
706            })
707            .collect();
708        let auth_agg = AuthorityAggregatorBuilder::from_genesis(&network_config.genesis)
709            .build_custom_clients(clients.clone());
710        (
711            authority_states,
712            Arc::new(ArcSwap::new(Arc::new(auth_agg))),
713            clients,
714        )
715    }
716
717    async fn create_tx(
718        clients: &BTreeMap<AuthorityName, MockAuthorityClient>,
719        state: &Arc<AuthorityState>,
720        sender: Address,
721        private_key: &AccountPrivateKey,
722        gas_object_id: ObjectId,
723    ) -> VerifiedSignedTransaction {
724        let gas_object_ref = state.get_object(&gas_object_id).unwrap().object_ref();
725        let tx_data = TestTransactionBuilder::new(
726            sender,
727            gas_object_ref,
728            state.reference_gas_price_for_testing().unwrap(),
729        )
730        .transfer_iota(None, sender)
731        .build();
732        let tx = to_sender_signed_transaction(tx_data, private_key);
733        let response = clients
734            .get(&state.name)
735            .unwrap()
736            .handle_transaction(tx.clone(), None)
737            .await
738            .unwrap();
739        VerifiedSignedTransaction::new_unchecked(SignedTransaction::new_from_data_and_sig(
740            tx.into_data(),
741            response.status.into_signed_for_testing(),
742        ))
743    }
744
745    fn check_quorum_execution(
746        auth_agg: &Arc<AuthorityAggregator<MockAuthorityClient>>,
747        clients: &BTreeMap<AuthorityName, MockAuthorityClient>,
748        tx_digest: &TransactionDigest,
749        expected: bool,
750    ) {
751        let quorum = auth_agg.committee.quorum_threshold();
752        let executed_weight: StakeUnit = clients
753            .iter()
754            .filter_map(|(name, client)| {
755                client
756                    .authority
757                    .is_tx_already_executed(tx_digest)
758                    .then_some(auth_agg.committee.weight(name))
759            })
760            .sum();
761        assert_eq!(executed_weight >= quorum, expected);
762    }
763}