Skip to main content

consensus_core/
authority_node.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    sync::{Arc, Weak},
6    time::{Duration, Instant},
7};
8
9use consensus_config::{
10    Committee, ConsensusProtocolConfig, NetworkKeyPair, NetworkPublicKey, Parameters,
11    ProtocolKeyPair,
12};
13use consensus_types::block::Round;
14use itertools::Itertools;
15use mysten_common::debug_fatal;
16use mysten_network::Multiaddr;
17use parking_lot::RwLock;
18use prometheus::Registry;
19use tracing::{info, warn};
20
21use crate::{
22    BlockAPI as _, CommitConsumerArgs, RandomnessSignatureHandler,
23    authority_service::AuthorityService,
24    block_manager::BlockManager,
25    block_sync_service::BlockSyncService,
26    block_verifier::SignedBlockVerifier,
27    commit_observer::CommitObserver,
28    commit_syncer::{CommitSyncer, CommitSyncerHandle},
29    commit_vote_monitor::CommitVoteMonitor,
30    context::{Clock, Context},
31    core::{Core, CoreSignals},
32    core_thread::{ChannelCoreThreadDispatcher, CoreThreadHandle},
33    dag_state::DagState,
34    leader_schedule::LeaderSchedule,
35    leader_timeout::{LeaderTimeoutTask, LeaderTimeoutTaskHandle},
36    metrics::initialise_metrics,
37    network::{
38        CommitSyncerClient, NetworkManager, PeerId, SynchronizerClient, tonic_network::TonicManager,
39    },
40    observer_service::ObserverService,
41    observer_subscriber::ObserverSubscriber,
42    peers_pool::PeersPool,
43    round_prober::{RoundProber, RoundProberHandle},
44    round_tracker::RoundTracker,
45    storage::rocksdb_store::RocksDBStore,
46    subscriber::Subscriber,
47    synchronizer::{Synchronizer, SynchronizerHandle},
48    transaction::{
49        TransactionClient, TransactionConsumer, TransactionConsumerPool, TransactionPool,
50        TransactionVerifier,
51    },
52    transaction_vote_tracker::TransactionVoteTracker,
53};
54
55/// ConsensusAuthority is used by Sui to manage the lifetime of AuthorityNode.
56/// It hides the details of the implementation from the caller, MysticetiManager.
57#[allow(private_interfaces)]
58pub enum ConsensusAuthority {
59    WithTonic(AuthorityNode<TonicManager>),
60}
61
62impl ConsensusAuthority {
63    pub async fn start(
64        network_type: NetworkType,
65        epoch_start_timestamp_ms: u64,
66        committee: Committee,
67        parameters: Parameters,
68        protocol_config: ConsensusProtocolConfig,
69        // Only required for validator nodes. Observer nodes don't have a protocol keypair.
70        protocol_keypair: Option<ProtocolKeyPair>,
71        network_keypair: NetworkKeyPair,
72        clock: Arc<Clock>,
73        transaction_verifier: Arc<dyn TransactionVerifier>,
74        // When provided, the proposer takes transactions from this pool and the
75        // `TransactionClient` submission path is unused. Only relevant for validator nodes.
76        transaction_pool: Option<Arc<dyn TransactionPool>>,
77        commit_consumer: CommitConsumerArgs,
78        registry: Registry,
79        // A counter that keeps track of how many times the consensus authority has been booted while the process
80        // has been running. It's useful for making decisions on whether amnesia recovery should run.
81        // When `boot_counter` is 0, `ConsensusAuthority` will initiate the process of amnesia recovery if that's enabled in the parameters.
82        boot_counter: u64,
83        randomness_signature_handler: Option<Arc<dyn RandomnessSignatureHandler>>,
84    ) -> Self {
85        match network_type {
86            NetworkType::Tonic => {
87                let authority = AuthorityNode::start(
88                    epoch_start_timestamp_ms,
89                    committee,
90                    parameters,
91                    protocol_config,
92                    protocol_keypair,
93                    network_keypair,
94                    clock,
95                    transaction_verifier,
96                    transaction_pool,
97                    commit_consumer,
98                    registry,
99                    boot_counter,
100                    randomness_signature_handler,
101                )
102                .await;
103                Self::WithTonic(authority)
104            }
105        }
106    }
107
108    pub async fn stop(self) {
109        match self {
110            Self::WithTonic(authority) => authority.stop().await,
111        }
112    }
113
114    pub fn update_peer_address(
115        &self,
116        network_pubkey: NetworkPublicKey,
117        address: Option<Multiaddr>,
118    ) {
119        match self {
120            Self::WithTonic(authority) => authority.update_peer_address(network_pubkey, address),
121        }
122    }
123
124    pub fn transaction_client(&self) -> Arc<TransactionClient> {
125        match self {
126            Self::WithTonic(authority) => authority.transaction_client(),
127        }
128    }
129
130    pub fn store(&self) -> Arc<RocksDBStore> {
131        match self {
132            Self::WithTonic(authority) => authority.store(),
133        }
134    }
135
136    #[cfg(test)]
137    fn context(&self) -> &Arc<Context> {
138        match self {
139            Self::WithTonic(authority) => &authority.context,
140        }
141    }
142}
143
144#[derive(Clone, Copy, PartialEq, Eq, Debug)]
145pub enum NetworkType {
146    Tonic,
147}
148
149/// Enum to handle different subscriber types based on whether the node is a validator or observer
150enum SubscriberType<N: NetworkManager> {
151    Validator(Subscriber<N::ValidatorClient, AuthorityService<ChannelCoreThreadDispatcher>>),
152    Observer(ObserverSubscriber<N::ObserverClient, ObserverService>),
153}
154
155impl<N: NetworkManager> SubscriberType<N> {
156    async fn stop(&self) {
157        match self {
158            SubscriberType::Validator(subscriber) => subscriber.stop().await,
159            SubscriberType::Observer(subscriber) => subscriber.stop().await,
160        }
161    }
162}
163
164pub(crate) struct AuthorityNode<N>
165where
166    N: NetworkManager,
167{
168    context: Arc<Context>,
169    start_time: Instant,
170    transaction_client: Arc<TransactionClient>,
171    synchronizer: Arc<SynchronizerHandle>,
172    store: Arc<RocksDBStore>,
173    // Only use for verification and logging during shutdown.
174    // To avoid keeping the DagState alive at the end of shutdown, this is only a weak reference.
175    dag_state: Weak<RwLock<DagState>>,
176
177    commit_syncer_handle: CommitSyncerHandle,
178    round_prober_handle: Option<RoundProberHandle>,
179    leader_timeout_handle: LeaderTimeoutTaskHandle,
180    core_thread_handle: CoreThreadHandle,
181    subscriber: SubscriberType<N>,
182    // Network proxies hold ObserverService weakly, so AuthorityNode keeps the service alive until
183    // the network servers have stopped.
184    observer_service: Option<Arc<ObserverService>>,
185    network_manager: N,
186}
187
188impl<N> AuthorityNode<N>
189where
190    N: NetworkManager,
191{
192    // See comments above ConsensusAuthority::start() for details on the input.
193    pub(crate) async fn start(
194        epoch_start_timestamp_ms: u64,
195        committee: Committee,
196        parameters: Parameters,
197        protocol_config: ConsensusProtocolConfig,
198        protocol_keypair: Option<ProtocolKeyPair>,
199        network_keypair: NetworkKeyPair,
200        clock: Arc<Clock>,
201        transaction_verifier: Arc<dyn TransactionVerifier>,
202        transaction_pool: Option<Arc<dyn TransactionPool>>,
203        commit_consumer: CommitConsumerArgs,
204        registry: Registry,
205        boot_counter: u64,
206        randomness_signature_handler: Option<Arc<dyn RandomnessSignatureHandler>>,
207    ) -> Self {
208        let metrics = initialise_metrics(registry);
209
210        // If a protocol key pair is provided, then this is a validator node.
211        let own_index = if let Some(protocol_keypair) = &protocol_keypair {
212            let (own_index, _) = committee
213                .authorities()
214                .find(|(_, a)| a.protocol_key == protocol_keypair.public())
215                .expect("Own authority should be among the consensus authorities!");
216
217            let own_hostname = committee.authority(own_index).hostname.clone();
218            info!(
219                "Starting consensus validator authority {} {}, {:?}, epoch start timestamp {}, boot counter {}, replay mode {:?}",
220                own_index,
221                own_hostname,
222                protocol_config.protocol_version(),
223                epoch_start_timestamp_ms,
224                boot_counter,
225                commit_consumer.replay_mode
226            );
227
228            metrics
229                .node_metrics
230                .authority_index
231                .with_label_values(&[&own_hostname])
232                .set(own_index.value() as i64);
233            Some(own_index)
234        } else {
235            // Otherwise this is an observer node and no index exists for it.
236            info!(
237                "Starting consensus observer authority, {:?}, epoch start timestamp {}, boot counter {}, replay mode {:?}",
238                protocol_config.protocol_version(),
239                epoch_start_timestamp_ms,
240                boot_counter,
241                commit_consumer.replay_mode
242            );
243            None
244        };
245
246        info!(
247            "Consensus authorities: {}",
248            committee
249                .authorities()
250                .map(|(i, a)| format!("{}: {}", i, a.hostname))
251                .join(", ")
252        );
253        info!("Consensus parameters: {:?}", parameters);
254        info!("Consensus committee: {:?}", committee);
255        let context = Arc::new(Context::new(
256            epoch_start_timestamp_ms,
257            own_index,
258            committee,
259            parameters,
260            protocol_config,
261            metrics,
262            clock,
263        ));
264        let start_time = Instant::now();
265
266        context
267            .metrics
268            .node_metrics
269            .protocol_version
270            .set(context.protocol_config.protocol_version() as i64);
271
272        let (tx_client, tx_receiver, priority_tx_receiver) =
273            TransactionClient::new(context.clone());
274        let transaction_pool: Arc<dyn TransactionPool> = match transaction_pool {
275            // With an external pool, the TransactionClient path is unused. The channel
276            // receiver is dropped so accidental client submissions fail fast instead of
277            // hanging.
278            Some(pool) => {
279                drop(tx_receiver);
280                drop(priority_tx_receiver);
281                pool
282            }
283            None => Arc::new(TransactionConsumerPool::new(TransactionConsumer::new(
284                tx_receiver,
285                priority_tx_receiver,
286                context.clone(),
287            ))),
288        };
289
290        let (core_signals, signals_receivers) = CoreSignals::new(context.clone());
291
292        let mut network_manager = N::new(context.clone(), network_keypair);
293        let validator_client = network_manager.validator_client();
294        let observer_client = network_manager.observer_client();
295
296        let synchronizer_client = Arc::new(SynchronizerClient::<
297            N::ValidatorClient,
298            N::ObserverClient,
299        >::new(
300            context.clone(),
301            Some(validator_client.clone()),
302            Some(observer_client.clone()),
303        ));
304        let commit_syncer_client = Arc::new(CommitSyncerClient::<
305            N::ValidatorClient,
306            N::ObserverClient,
307        >::new(
308            context.clone(),
309            Some(validator_client.clone()),
310            Some(observer_client.clone()),
311        ));
312
313        let store_path = context.parameters.db_path.as_path().to_str().unwrap();
314        let store = Arc::new(RocksDBStore::new(store_path));
315        let dag_state = Arc::new(RwLock::new(DagState::new(context.clone(), store.clone())));
316
317        let block_verifier = Arc::new(SignedBlockVerifier::new(
318            context.clone(),
319            transaction_verifier,
320        ));
321
322        let transaction_vote_tracker =
323            TransactionVoteTracker::new(context.clone(), block_verifier.clone(), dag_state.clone());
324
325        // Only sync last known own block if we are a validator and it's the first boot.
326        let sync_last_known_own_block = boot_counter == 0
327            && !context
328                .parameters
329                .sync_last_known_own_block_timeout
330                .is_zero()
331            && context.is_validator();
332        info!(
333            "Sync last known own block: {}. Boot count: {}. Timeout: {:?}.",
334            sync_last_known_own_block,
335            boot_counter,
336            context.parameters.sync_last_known_own_block_timeout
337        );
338
339        let block_manager = BlockManager::new(context.clone(), dag_state.clone());
340
341        let leader_schedule = Arc::new(LeaderSchedule::from_store(
342            context.clone(),
343            dag_state.clone(),
344        ));
345
346        let consumer_monitor = commit_consumer.monitor();
347        let commit_observer = CommitObserver::new(
348            context.clone(),
349            commit_consumer,
350            dag_state.clone(),
351            transaction_vote_tracker.clone(),
352        )
353        .await;
354
355        let initial_received_rounds = dag_state
356            .read()
357            .get_last_cached_block_per_authority(Round::MAX)
358            .into_iter()
359            .map(|(block, _)| block.round())
360            .collect::<Vec<_>>();
361        let round_tracker = Arc::new(RwLock::new(RoundTracker::new(
362            context.clone(),
363            initial_received_rounds,
364        )));
365
366        // To avoid accidentally leaking the private key, the protocol key pair should only be
367        // kept in Core.
368        let core = if context.is_validator() {
369            Core::new_validator(
370                context.clone(),
371                leader_schedule,
372                transaction_pool,
373                transaction_vote_tracker.clone(),
374                block_manager,
375                commit_observer,
376                core_signals,
377                protocol_keypair.expect("protocol keypair is required when running as validator"),
378                dag_state.clone(),
379                sync_last_known_own_block,
380                round_tracker.clone(),
381            )
382        } else {
383            Core::new_observer(
384                context.clone(),
385                leader_schedule,
386                block_manager,
387                commit_observer,
388                core_signals,
389                dag_state.clone(),
390            )
391        };
392
393        let (core_dispatcher, core_thread_handle) =
394            ChannelCoreThreadDispatcher::start(context.clone(), &dag_state, core);
395        let core_dispatcher = Arc::new(core_dispatcher);
396        let leader_timeout_handle =
397            LeaderTimeoutTask::start(core_dispatcher.clone(), &signals_receivers, context.clone());
398
399        let commit_vote_monitor = Arc::new(CommitVoteMonitor::new(context.clone()));
400
401        // Create the PeersPool
402        let peers_pool = Arc::new(PeersPool::new(context.clone()));
403
404        let synchronizer = Synchronizer::start(
405            synchronizer_client.clone(),
406            context.clone(),
407            core_dispatcher.clone(),
408            commit_vote_monitor.clone(),
409            block_verifier.clone(),
410            transaction_vote_tracker.clone(),
411            round_tracker.clone(),
412            dag_state.clone(),
413            peers_pool.clone(),
414            sync_last_known_own_block,
415        );
416
417        let commit_syncer_handle = CommitSyncer::new(
418            context.clone(),
419            core_dispatcher.clone(),
420            commit_vote_monitor.clone(),
421            consumer_monitor.clone(),
422            block_verifier.clone(),
423            transaction_vote_tracker.clone(),
424            round_tracker.clone(),
425            commit_syncer_client.clone(),
426            dag_state.clone(),
427            peers_pool.clone(),
428        )
429        .start();
430
431        // Create BlockSyncService that will be shared by both AuthorityService and ObserverService
432        let block_sync_service = Arc::new(BlockSyncService::new(
433            context.clone(),
434            dag_state.clone(),
435            store.clone(),
436        ));
437
438        let (subscriber, round_prober_handle, observer_service) = if context.is_validator() {
439            let authority_service = Arc::new(AuthorityService::new(
440                context.clone(),
441                block_verifier.clone(),
442                commit_vote_monitor.clone(),
443                round_tracker.clone(),
444                synchronizer.clone(),
445                core_dispatcher.clone(),
446                signals_receivers.block_broadcast_receiver(),
447                transaction_vote_tracker.clone(),
448                dag_state.clone(),
449                block_sync_service.clone(),
450            ));
451
452            // Start the validator server if this is a validator node.
453            network_manager
454                .start_validator_server(authority_service.clone())
455                .await;
456
457            // Validator node: subscribe to all other validators
458            let s = Subscriber::new(
459                context.clone(),
460                validator_client.clone(),
461                authority_service.clone(),
462                dag_state.clone(),
463            );
464            for (peer, _) in context.committee.authorities() {
465                if peer != context.own_index {
466                    s.subscribe(peer);
467                }
468            }
469
470            // Start the round prober
471            let round_prober_handle = Some(
472                RoundProber::new(
473                    context.clone(),
474                    core_dispatcher.clone(),
475                    round_tracker.clone(),
476                    dag_state.clone(),
477                    validator_client,
478                    consumer_monitor.clone(),
479                )
480                .start(),
481            );
482
483            // Start the observer server if the observer server is enabled in the parameters.
484            let observer_service = if context.parameters.observer.is_server_enabled() {
485                let observer_service = Arc::new(ObserverService::new(
486                    context.clone(),
487                    core_dispatcher.clone(),
488                    dag_state.clone(),
489                    signals_receivers.accepted_block_broadcast_receiver(),
490                    block_verifier,
491                    commit_vote_monitor.clone(),
492                    transaction_vote_tracker.clone(),
493                    synchronizer.clone(),
494                    block_sync_service.clone(),
495                    randomness_signature_handler.clone(),
496                ));
497                network_manager
498                    .start_observer_server(observer_service.clone())
499                    .await;
500                Some(observer_service)
501            } else {
502                None
503            };
504
505            (
506                SubscriberType::Validator(s),
507                round_prober_handle,
508                observer_service,
509            )
510        } else {
511            // Observer node: subscribe to specified peer(s) using ObserverSubscriber
512            let observer_client = network_manager.observer_client();
513            let observer_service = Arc::new(ObserverService::new(
514                context.clone(),
515                core_dispatcher.clone(),
516                dag_state.clone(),
517                signals_receivers.accepted_block_broadcast_receiver(),
518                block_verifier,
519                commit_vote_monitor.clone(),
520                transaction_vote_tracker.clone(),
521                synchronizer.clone(),
522                block_sync_service.clone(),
523                randomness_signature_handler.clone(),
524            ));
525
526            let observer_subscriber = ObserverSubscriber::new(
527                context.clone(),
528                observer_client,
529                observer_service.clone(),
530                commit_vote_monitor.clone(),
531                dag_state.clone(),
532                randomness_signature_handler,
533            );
534
535            network_manager
536                .start_observer_server(observer_service.clone())
537                .await;
538
539            // Subscribe to peers specified in the configuration
540            // For now get the first peer from the list to connect to.
541            // TODO: support multiple peers - as in choose/detect which one to connect to.
542            for peer_record in context.parameters.observer.peers.iter().take(1) {
543                let peer_id = if let Some((index, _)) = context
544                    .committee
545                    .authorities()
546                    .find(|(_, authority)| authority.network_key == peer_record.public_key)
547                {
548                    PeerId::Validator(index)
549                } else {
550                    PeerId::Observer(Box::new(peer_record.public_key.clone()))
551                };
552
553                info!("Observer subscribing to peer: {:?}", peer_id);
554                observer_subscriber.subscribe(peer_id);
555            }
556
557            (
558                SubscriberType::Observer(observer_subscriber),
559                None,
560                Some(observer_service),
561            )
562        };
563
564        info!(
565            "Consensus authority started, took {:?}",
566            start_time.elapsed()
567        );
568
569        Self {
570            context,
571            start_time,
572            transaction_client: Arc::new(tx_client),
573            synchronizer,
574            store,
575            dag_state: Arc::downgrade(&dag_state),
576            commit_syncer_handle,
577            round_prober_handle,
578            leader_timeout_handle,
579            core_thread_handle,
580            subscriber,
581            observer_service,
582            network_manager,
583        }
584    }
585
586    pub(crate) async fn stop(self) {
587        let Self {
588            context,
589            start_time,
590            transaction_client,
591            synchronizer,
592            store,
593            dag_state,
594            commit_syncer_handle,
595            round_prober_handle,
596            leader_timeout_handle,
597            core_thread_handle,
598            subscriber,
599            observer_service,
600            mut network_manager,
601        } = self;
602
603        info!(
604            "Stopping authority. Total run time: {:?}",
605            start_time.elapsed()
606        );
607
608        // First shutdown components calling into Core.
609        synchronizer.stop().await;
610        commit_syncer_handle.stop().await;
611        if let Some(round_prober_handle) = round_prober_handle {
612            round_prober_handle.stop().await;
613        }
614        leader_timeout_handle.stop().await;
615        // Shutdown Core to stop block productions and broadcast.
616        core_thread_handle.stop().await;
617        // Stop block subscriptions before stopping network server.
618        subscriber.stop().await;
619        network_manager.stop().await;
620
621        context
622            .metrics
623            .node_metrics
624            .uptime
625            .observe(start_time.elapsed().as_secs_f64());
626
627        drop((
628            context,
629            transaction_client,
630            synchronizer,
631            store,
632            subscriber,
633            observer_service,
634            network_manager,
635        ));
636
637        // Canceled tasks should wait to report cancellation on next poll, but they report from
638        // their JoinHandles immediately under msim. Their futures and captured references are
639        // only dropped when the executor next processes the canceled tasks. Sleeping (instead
640        // of yielding) ensures this task resumes only after the pending drops have run.
641        // In production tokio, a canceled task's future is guaranteed to have been dropped when
642        // its JoinHandle resolves, so the loop exits on the first check.
643        let mut dag_state_owners = dag_state.strong_count();
644        for _ in 0..5 {
645            if dag_state_owners == 0 {
646                break;
647            }
648            tokio::time::sleep(Duration::from_millis(1)).await;
649            dag_state_owners = dag_state.strong_count();
650        }
651        if dag_state_owners != 0 {
652            debug_fatal!(
653                "DagState still has {} owner(s) after stopping ConsensusAuthority",
654                dag_state_owners
655            );
656        }
657    }
658
659    pub(crate) fn transaction_client(&self) -> Arc<TransactionClient> {
660        self.transaction_client.clone()
661    }
662
663    pub(crate) fn store(&self) -> Arc<RocksDBStore> {
664        self.store.clone()
665    }
666
667    pub(crate) fn update_peer_address(
668        &self,
669        network_pubkey: NetworkPublicKey,
670        address: Option<Multiaddr>,
671    ) {
672        // Find the peer index for this network key
673        let Some(peer) = self
674            .context
675            .committee
676            .authorities()
677            .find(|(_, authority)| authority.network_key == network_pubkey)
678            .map(|(index, _)| index)
679        else {
680            warn!(
681                "Network public key {:?} not found in committee, ignoring address update",
682                network_pubkey
683            );
684            return;
685        };
686
687        // Update the address in the network manager
688        self.network_manager.update_peer_address(peer, address);
689
690        // Re-subscribe to the peer to force reconnection with new address
691        if peer != self.context.own_index {
692            info!("Re-subscribing to peer {} after address update", peer);
693            match &self.subscriber {
694                SubscriberType::Validator(s) => s.subscribe(peer),
695                SubscriberType::Observer(s) => {
696                    // For observer, create a PeerId for the validator
697                    s.subscribe(PeerId::Validator(peer));
698                }
699            }
700        }
701    }
702}
703
704#[cfg(test)]
705mod tests {
706    #![allow(non_snake_case)]
707
708    use std::{
709        collections::{BTreeMap, BTreeSet},
710        sync::Arc,
711        time::Duration,
712    };
713
714    use consensus_config::{
715        AuthorityIndex, ObserverParameters, Parameters, PeerRecord, local_committee_and_keys,
716    };
717    use mysten_metrics::RegistryService;
718    use mysten_metrics::monitored_mpsc::UnboundedReceiver;
719    use prometheus::Registry;
720    use rand::{SeedableRng, rngs::StdRng};
721    use rstest::rstest;
722    use tempfile::TempDir;
723    use tokio::time::{sleep, timeout};
724    use typed_store::DBMetrics;
725
726    use super::*;
727    use crate::{
728        CommittedSubDag,
729        block::{BlockAPI as _, GENESIS_ROUND},
730        transaction::{NoopTransactionVerifier, Priority},
731    };
732
733    #[rstest]
734    #[tokio::test]
735    async fn test_authority_start_and_stop(
736        #[values(NetworkType::Tonic)] network_type: NetworkType,
737    ) {
738        let (committee, keypairs) = local_committee_and_keys(0, vec![1]);
739        let registry = Registry::new();
740
741        let temp_dir = TempDir::new().unwrap();
742        let parameters = Parameters {
743            db_path: temp_dir.keep(),
744            ..Default::default()
745        };
746        let txn_verifier = NoopTransactionVerifier {};
747
748        let own_index = committee.to_authority_index(0).unwrap();
749        let protocol_keypair = keypairs[own_index].1.clone();
750        let network_keypair = keypairs[own_index].0.clone();
751
752        let (commit_consumer, _) = CommitConsumerArgs::new(0, 0);
753
754        let authority = ConsensusAuthority::start(
755            network_type,
756            0,
757            committee,
758            parameters,
759            ConsensusProtocolConfig::for_testing(),
760            Some(protocol_keypair),
761            network_keypair,
762            Arc::new(Clock::default()),
763            Arc::new(txn_verifier),
764            None,
765            commit_consumer,
766            registry,
767            0,
768            None,
769        )
770        .await;
771
772        assert_eq!(authority.context().own_index, own_index);
773        assert_eq!(authority.context().committee.epoch(), 0);
774        assert_eq!(authority.context().committee.size(), 1);
775
776        authority.stop().await;
777    }
778
779    #[rstest]
780    #[tokio::test]
781    async fn test_observer_start_and_stop(#[values(NetworkType::Tonic)] network_type: NetworkType) {
782        let (committee, keypairs) = local_committee_and_keys(0, vec![1]);
783        let registry = Registry::new();
784
785        let temp_dir = TempDir::new().unwrap();
786        let parameters = Parameters {
787            db_path: temp_dir.keep(),
788            ..Default::default()
789        };
790        let txn_verifier = NoopTransactionVerifier {};
791
792        // Use any network keypair for the observer, it doesn't need to match a committee member
793        let network_keypair = keypairs[0].0.clone();
794
795        let (commit_consumer, _) = CommitConsumerArgs::new(0, 0);
796
797        let observer = ConsensusAuthority::start(
798            network_type,
799            0,
800            committee.clone(),
801            parameters,
802            ConsensusProtocolConfig::for_testing(),
803            None, // No protocol keypair for observer node
804            network_keypair,
805            Arc::new(Clock::default()),
806            Arc::new(txn_verifier),
807            None,
808            commit_consumer,
809            registry,
810            0,
811            None,
812        )
813        .await;
814
815        sleep(Duration::from_secs(2)).await;
816
817        // Observer nodes have own_index set to MAX as a special value
818        assert_eq!(observer.context().own_index, AuthorityIndex::MAX);
819        assert_eq!(observer.context().committee.epoch(), 0);
820        assert_eq!(observer.context().committee.size(), 1);
821        assert!(!observer.context().is_validator());
822
823        observer.stop().await;
824    }
825
826    // TODO: build AuthorityFixture.
827    // Spins up a committee of authorities and an observer node that connects to authority 0.
828    // Verifies that the network is progressing, advancing rounds and commits. It also verifies
829    // that the Observer node is receiving blocks from the network.
830    #[rstest]
831    #[tokio::test(flavor = "current_thread")]
832    async fn test_authority_committee(
833        #[values(NetworkType::Tonic)] network_type: NetworkType,
834        #[values(5, 10)] gc_depth: u32,
835    ) {
836        telemetry_subscribers::init_for_testing();
837        let db_registry = Registry::new();
838        DBMetrics::init(RegistryService::new(db_registry));
839
840        const NUM_OF_AUTHORITIES: usize = 4;
841        let (committee, keypairs) = local_committee_and_keys(0, [1; NUM_OF_AUTHORITIES].to_vec());
842        let mut protocol_config = ConsensusProtocolConfig::for_testing();
843        protocol_config.set_gc_depth_for_testing(gc_depth);
844
845        let temp_dirs = (0..NUM_OF_AUTHORITIES)
846            .map(|_| TempDir::new().unwrap())
847            .collect::<Vec<_>>();
848
849        let mut commit_receivers = Vec::with_capacity(committee.size());
850        let mut authorities = Vec::with_capacity(committee.size());
851        let mut boot_counters = [0; NUM_OF_AUTHORITIES];
852
853        // Use a unique port based on gc_depth to avoid conflicts between parallel tests
854        let observer_server_port = 8900 + gc_depth as u16;
855
856        // Create authorities with observer server enabled for authority 0
857        let mut authority_0_network_key = None;
858        for (index, authority_info) in committee.authorities() {
859            let (authority, commit_receiver) = if index.value() == 0 {
860                // Save authority 0's network key for Observer connection
861                authority_0_network_key = Some(authority_info.network_key.clone());
862                // Enable observer server for authority 0
863                make_authority_with_observer_server(
864                    index,
865                    &temp_dirs[index.value()],
866                    committee.clone(),
867                    keypairs.clone(),
868                    network_type,
869                    boot_counters[index],
870                    protocol_config.clone(),
871                    Some(observer_server_port),
872                )
873                .await
874            } else {
875                make_authority(
876                    index,
877                    &temp_dirs[index.value()],
878                    committee.clone(),
879                    keypairs.clone(),
880                    network_type,
881                    boot_counters[index],
882                    protocol_config.clone(),
883                )
884                .await
885            };
886            boot_counters[index] += 1;
887            commit_receivers.push(commit_receiver);
888            authorities.push(authority);
889        }
890
891        // Create an Observer node that connects to authority 0
892        let observer_temp_dir = TempDir::new().unwrap();
893        let mut rng = StdRng::from_seed([99; 32]);
894        let observer_network_keypair = consensus_config::NetworkKeyPair::generate(&mut rng);
895
896        let observer_parameters = Parameters {
897            db_path: observer_temp_dir.path().to_path_buf(),
898            observer: ObserverParameters {
899                // Configure Observer to connect to authority 0
900                peers: vec![PeerRecord {
901                    public_key: authority_0_network_key
902                        .clone()
903                        .expect("Authority 0 network key should be set"),
904                    address: format!("/ip4/127.0.0.1/udp/{}", observer_server_port)
905                        .parse()
906                        .unwrap(),
907                }],
908                ..Default::default()
909            },
910            ..Default::default()
911        };
912
913        let (observer_commit_consumer, observer_commit_receiver) = CommitConsumerArgs::new(0, 0);
914        let observer = ConsensusAuthority::start(
915            network_type,
916            0,
917            committee.clone(),
918            observer_parameters,
919            protocol_config.clone(),
920            None, // No protocol keypair for observer
921            observer_network_keypair,
922            Arc::new(Clock::default()),
923            Arc::new(NoopTransactionVerifier {}),
924            None,
925            observer_commit_consumer,
926            Registry::new(),
927            0,
928            None,
929        )
930        .await;
931        // The relevant endpoints are now implemented for the synchronizer and commit_syncer components, so the Observer node should be able to catch up and
932        // fetch blocks beyond the latest ones that are fetched from the stream.
933        commit_receivers.push(observer_commit_receiver);
934
935        // Give Observer more time to connect and sync
936        sleep(Duration::from_secs(5)).await;
937
938        const NUM_TRANSACTIONS: u8 = 15;
939        let mut submitted_transactions = BTreeSet::<Vec<u8>>::new();
940        for i in 0..NUM_TRANSACTIONS {
941            let txn = vec![i; 16];
942            submitted_transactions.insert(txn.clone());
943            authorities[i as usize % authorities.len()]
944                .transaction_client()
945                .submit(vec![txn], Priority::Normal)
946                .await
947                .unwrap();
948        }
949
950        for receiver in &mut commit_receivers {
951            let mut expected_transactions = submitted_transactions.clone();
952            loop {
953                let committed_subdag =
954                    tokio::time::timeout(Duration::from_secs(1), receiver.recv())
955                        .await
956                        .unwrap()
957                        .unwrap();
958                for b in committed_subdag.blocks {
959                    for txn in b.transactions().iter().map(|t| t.data().to_vec()) {
960                        assert!(
961                            expected_transactions.remove(&txn),
962                            "Transaction not submitted or already seen: {:?}",
963                            txn
964                        );
965                    }
966                }
967                if expected_transactions.is_empty() {
968                    break;
969                }
970            }
971        }
972
973        // Stop authority 1.
974        let index = committee.to_authority_index(1).unwrap();
975        authorities.remove(index.value()).stop().await;
976        sleep(Duration::from_secs(10)).await;
977
978        // Restart authority 1 and let it run.
979        let (authority, commit_receiver) = make_authority(
980            index,
981            &temp_dirs[index.value()],
982            committee.clone(),
983            keypairs.clone(),
984            network_type,
985            boot_counters[index],
986            protocol_config.clone(),
987        )
988        .await;
989        boot_counters[index] += 1;
990        commit_receivers[index] = commit_receiver;
991        authorities.insert(index.value(), authority);
992        sleep(Duration::from_secs(10)).await;
993
994        // Verify that the Observer node is running
995        // TODO: The actual block processing for observers is not fully implemented yet
996        // for now we just verify that blocks are received and the number of received blocks is not far from
997        // the number of blocks sent by authority 0.
998        let observer_context = observer.context();
999        assert!(
1000            observer_context.is_observer(),
1001            "It should be an observer node"
1002        );
1003
1004        // Get the total verified_blocks from authority 0 (sum across all sending authorities)
1005        let authority_0 = &authorities[0];
1006        let authority_0_context = authority_0.context();
1007        let mut authority_0_total_verified_blocks = 0;
1008
1009        // Sum verified_blocks from all authorities as seen by authority 0
1010        for (_, authority_info) in committee.authorities() {
1011            if let Ok(metric) = authority_0_context
1012                .metrics
1013                .node_metrics
1014                .verified_blocks
1015                .get_metric_with_label_values(&[&authority_info.hostname])
1016            {
1017                authority_0_total_verified_blocks += metric.get();
1018                println!(
1019                    "authority_info.hostname: {}, metric: {:?}",
1020                    authority_info.hostname, authority_0_total_verified_blocks
1021                );
1022            }
1023        }
1024
1025        let mut authority_0_total_proposed_blocks = 0;
1026        for force in [true, false] {
1027            if let Ok(metric) = authority_0_context
1028                .metrics
1029                .node_metrics
1030                .proposed_blocks
1031                .get_metric_with_label_values(&[&force.to_string()])
1032            {
1033                authority_0_total_proposed_blocks += metric.get();
1034            }
1035        }
1036
1037        authority_0_total_verified_blocks += authority_0_total_proposed_blocks;
1038
1039        // Sum verified_blocks from all authorities as seen by the observer
1040        let mut observer_received_blocks = 0;
1041        for (_, authority_info) in committee.authorities() {
1042            if let Ok(metric) = observer_context
1043                .metrics
1044                .node_metrics
1045                .verified_blocks
1046                .get_metric_with_label_values(&[&authority_info.hostname])
1047            {
1048                observer_received_blocks += metric.get();
1049            }
1050        }
1051
1052        // Compare the values - they should be related but might not be exactly equal
1053        // due to timing and the observer connecting mid-stream
1054        assert!(
1055            observer_received_blocks > 0,
1056            "Observer should have received at least some blocks, got: {}",
1057            observer_received_blocks
1058        );
1059
1060        println!(
1061            "authority_0_total_verified_blocks: {}, observer_received_blocks: {}",
1062            authority_0_total_verified_blocks, observer_received_blocks
1063        );
1064
1065        const TOLERANCE: u64 = 20;
1066        assert!(
1067            authority_0_total_verified_blocks - observer_received_blocks <= TOLERANCE,
1068            "The number of blocks received by the observer ({}) should be close to the number of blocks verified by authority 0 ({})",
1069            observer_received_blocks,
1070            authority_0_total_verified_blocks,
1071        );
1072
1073        // Stop observer first
1074        observer.stop().await;
1075
1076        // Stop all authorities and exit.
1077        for authority in authorities {
1078            authority.stop().await;
1079        }
1080    }
1081
1082    #[rstest]
1083    #[tokio::test(flavor = "current_thread")]
1084    async fn test_small_committee(
1085        #[values(NetworkType::Tonic)] network_type: NetworkType,
1086        #[values(1, 2, 3)] num_authorities: usize,
1087    ) {
1088        telemetry_subscribers::init_for_testing();
1089        let db_registry = Registry::new();
1090        DBMetrics::init(RegistryService::new(db_registry));
1091
1092        let (committee, keypairs) = local_committee_and_keys(0, vec![1; num_authorities]);
1093        let protocol_config = ConsensusProtocolConfig::for_testing();
1094
1095        let temp_dirs = (0..num_authorities)
1096            .map(|_| TempDir::new().unwrap())
1097            .collect::<Vec<_>>();
1098
1099        let mut output_receivers = Vec::with_capacity(committee.size());
1100        let mut authorities: Vec<ConsensusAuthority> = Vec::with_capacity(committee.size());
1101        let mut boot_counters = vec![0; num_authorities];
1102
1103        for (index, _authority_info) in committee.authorities() {
1104            let (authority, commit_receiver) = make_authority(
1105                index,
1106                &temp_dirs[index.value()],
1107                committee.clone(),
1108                keypairs.clone(),
1109                network_type,
1110                boot_counters[index],
1111                protocol_config.clone(),
1112            )
1113            .await;
1114            boot_counters[index] += 1;
1115            output_receivers.push(commit_receiver);
1116            authorities.push(authority);
1117        }
1118
1119        const NUM_TRANSACTIONS: u8 = 15;
1120        let mut submitted_transactions = BTreeSet::<Vec<u8>>::new();
1121        for i in 0..NUM_TRANSACTIONS {
1122            let txn = vec![i; 16];
1123            submitted_transactions.insert(txn.clone());
1124            authorities[i as usize % authorities.len()]
1125                .transaction_client()
1126                .submit(vec![txn], Priority::Normal)
1127                .await
1128                .unwrap();
1129        }
1130
1131        for receiver in &mut output_receivers {
1132            let mut expected_transactions = submitted_transactions.clone();
1133            loop {
1134                let committed_subdag =
1135                    tokio::time::timeout(Duration::from_secs(1), receiver.recv())
1136                        .await
1137                        .unwrap()
1138                        .unwrap();
1139                for b in committed_subdag.blocks {
1140                    for txn in b.transactions().iter().map(|t| t.data().to_vec()) {
1141                        assert!(
1142                            expected_transactions.remove(&txn),
1143                            "Transaction not submitted or already seen: {:?}",
1144                            txn
1145                        );
1146                    }
1147                }
1148                if expected_transactions.is_empty() {
1149                    break;
1150                }
1151            }
1152        }
1153
1154        // Stop authority 0.
1155        let index = committee.to_authority_index(0).unwrap();
1156        authorities.remove(index.value()).stop().await;
1157        sleep(Duration::from_secs(10)).await;
1158
1159        // Restart authority 0 and let it run.
1160        let (authority, commit_receiver) = make_authority(
1161            index,
1162            &temp_dirs[index.value()],
1163            committee.clone(),
1164            keypairs.clone(),
1165            network_type,
1166            boot_counters[index],
1167            protocol_config.clone(),
1168        )
1169        .await;
1170        boot_counters[index] += 1;
1171        output_receivers[index] = commit_receiver;
1172        authorities.insert(index.value(), authority);
1173        sleep(Duration::from_secs(10)).await;
1174
1175        // Stop all authorities and exit.
1176        for authority in authorities {
1177            authority.stop().await;
1178        }
1179    }
1180
1181    #[rstest]
1182    #[tokio::test(flavor = "current_thread")]
1183    async fn test_amnesia_recovery_success(#[values(5, 10)] gc_depth: u32) {
1184        telemetry_subscribers::init_for_testing();
1185        let db_registry = Registry::new();
1186        DBMetrics::init(RegistryService::new(db_registry));
1187
1188        const NUM_OF_AUTHORITIES: usize = 4;
1189        let (committee, keypairs) = local_committee_and_keys(0, [1; NUM_OF_AUTHORITIES].to_vec());
1190        let mut commit_receivers = vec![];
1191        let mut authorities = BTreeMap::new();
1192        let mut temp_dirs = BTreeMap::new();
1193        let mut boot_counters = [0; NUM_OF_AUTHORITIES];
1194
1195        let mut protocol_config = ConsensusProtocolConfig::for_testing();
1196        protocol_config.set_gc_depth_for_testing(gc_depth);
1197
1198        for (index, _authority_info) in committee.authorities() {
1199            let dir = TempDir::new().unwrap();
1200            let (authority, commit_receiver) = make_authority(
1201                index,
1202                &dir,
1203                committee.clone(),
1204                keypairs.clone(),
1205                NetworkType::Tonic,
1206                boot_counters[index],
1207                protocol_config.clone(),
1208            )
1209            .await;
1210            boot_counters[index] += 1;
1211            commit_receivers.push(commit_receiver);
1212            authorities.insert(index, authority);
1213            temp_dirs.insert(index, dir);
1214        }
1215
1216        // Now we take the receiver of authority 1 and we wait until we see at least one block committed from this authority
1217        // We wait until we see at least one committed block authored from this authority. That way we'll be 100% sure that
1218        // at least one block has been proposed and successfully received by a quorum of nodes.
1219        let index_1 = committee.to_authority_index(1).unwrap();
1220        'outer: while let Some(result) =
1221            timeout(Duration::from_secs(10), commit_receivers[index_1].recv())
1222                .await
1223                .expect("Timed out while waiting for at least one committed block from authority 1")
1224        {
1225            for block in result.blocks {
1226                if block.round() > GENESIS_ROUND && block.author() == index_1 {
1227                    break 'outer;
1228                }
1229            }
1230        }
1231
1232        // Stop authority 1 & 2.
1233        // * Authority 1 will be used to wipe out their DB and practically "force" the amnesia recovery.
1234        // * Authority 2 is stopped in order to simulate less than f+1 availability which will
1235        // make authority 1 retry during amnesia recovery until it has finally managed to successfully get back f+1 responses.
1236        // once authority 2 is up and running again.
1237        authorities.remove(&index_1).unwrap().stop().await;
1238        let index_2 = committee.to_authority_index(2).unwrap();
1239        authorities.remove(&index_2).unwrap().stop().await;
1240        sleep(Duration::from_secs(5)).await;
1241
1242        // Authority 1: create a new directory to simulate amnesia. The node will start having participated previously
1243        // to consensus but now will attempt to synchronize the last own block and recover from there. It won't be able
1244        // to do that successfully as authority 2 is still down.
1245        let dir = TempDir::new().unwrap();
1246        // We do reset the boot counter for this one to simulate a "binary" restart
1247        boot_counters[index_1] = 0;
1248        let (authority, mut commit_receiver) = make_authority(
1249            index_1,
1250            &dir,
1251            committee.clone(),
1252            keypairs.clone(),
1253            NetworkType::Tonic,
1254            boot_counters[index_1],
1255            protocol_config.clone(),
1256        )
1257        .await;
1258        boot_counters[index_1] += 1;
1259        authorities.insert(index_1, authority);
1260        temp_dirs.insert(index_1, dir);
1261        sleep(Duration::from_secs(5)).await;
1262
1263        // Now spin up authority 2 using its earlier directly - so no amnesia recovery should be forced here.
1264        // Authority 1 should be able to recover from amnesia successfully.
1265        let (authority, _commit_receiver) = make_authority(
1266            index_2,
1267            &temp_dirs[&index_2],
1268            committee.clone(),
1269            keypairs,
1270            NetworkType::Tonic,
1271            boot_counters[index_2],
1272            protocol_config.clone(),
1273        )
1274        .await;
1275        boot_counters[index_2] += 1;
1276        authorities.insert(index_2, authority);
1277        sleep(Duration::from_secs(5)).await;
1278
1279        // We wait until we see at least one committed block authored from this authority
1280        'outer: while let Some(result) = commit_receiver.recv().await {
1281            for block in result.blocks {
1282                if block.round() > GENESIS_ROUND && block.author() == index_1 {
1283                    break 'outer;
1284                }
1285            }
1286        }
1287
1288        // Stop all authorities and exit.
1289        for (_, authority) in authorities {
1290            authority.stop().await;
1291        }
1292    }
1293
1294    // TODO: create a fixture
1295    async fn make_authority(
1296        index: AuthorityIndex,
1297        db_dir: &TempDir,
1298        committee: Committee,
1299        keypairs: Vec<(NetworkKeyPair, ProtocolKeyPair)>,
1300        network_type: NetworkType,
1301        boot_counter: u64,
1302        protocol_config: ConsensusProtocolConfig,
1303    ) -> (ConsensusAuthority, UnboundedReceiver<CommittedSubDag>) {
1304        make_authority_with_observer_server(
1305            index,
1306            db_dir,
1307            committee,
1308            keypairs,
1309            network_type,
1310            boot_counter,
1311            protocol_config,
1312            None, // No observer server port
1313        )
1314        .await
1315    }
1316
1317    async fn make_authority_with_observer_server(
1318        index: AuthorityIndex,
1319        db_dir: &TempDir,
1320        committee: Committee,
1321        keypairs: Vec<(NetworkKeyPair, ProtocolKeyPair)>,
1322        network_type: NetworkType,
1323        boot_counter: u64,
1324        protocol_config: ConsensusProtocolConfig,
1325        observer_server_port: Option<u16>,
1326    ) -> (ConsensusAuthority, UnboundedReceiver<CommittedSubDag>) {
1327        let registry = Registry::new();
1328
1329        // Cache less blocks to exercise commit sync.
1330        let mut parameters = Parameters {
1331            db_path: db_dir.path().to_path_buf(),
1332            dag_state_cached_rounds: 5,
1333            commit_sync_parallel_fetches: 2,
1334            commit_sync_batch_size: 3,
1335            sync_last_known_own_block_timeout: Duration::from_millis(2_000),
1336            ..Default::default()
1337        };
1338
1339        // Enable observer server if port is provided
1340        if let Some(port) = observer_server_port {
1341            parameters.observer.server_port = Some(port);
1342        }
1343
1344        let txn_verifier = NoopTransactionVerifier {};
1345
1346        let protocol_keypair = keypairs[index].1.clone();
1347        let network_keypair = keypairs[index].0.clone();
1348
1349        let (commit_consumer, commit_receiver) = CommitConsumerArgs::new(0, 0);
1350
1351        let authority = ConsensusAuthority::start(
1352            network_type,
1353            0,
1354            committee,
1355            parameters,
1356            protocol_config,
1357            Some(protocol_keypair),
1358            network_keypair,
1359            Arc::new(Clock::default()),
1360            Arc::new(txn_verifier),
1361            None,
1362            commit_consumer,
1363            registry,
1364            boot_counter,
1365            None,
1366        )
1367        .await;
1368
1369        (authority, commit_receiver)
1370    }
1371}