iota_node/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5#[cfg(msim)]
6use std::sync::atomic::Ordering;
7use std::{
8    collections::{BTreeSet, HashMap, HashSet},
9    fmt,
10    future::Future,
11    path::PathBuf,
12    str::FromStr,
13    sync::{Arc, Weak},
14    time::Duration,
15};
16
17use anemo::Network;
18use anemo_tower::{
19    callback::CallbackLayer,
20    trace::{DefaultMakeSpan, DefaultOnFailure, TraceLayer},
21};
22use anyhow::{Result, anyhow};
23use arc_swap::ArcSwap;
24use fastcrypto_zkp::bn254::zk_login::{JWK, JwkId, OIDCProvider};
25use futures::future::BoxFuture;
26pub use handle::IotaNodeHandle;
27use iota_archival::{reader::ArchiveReaderBalancer, writer::ArchiveWriter};
28use iota_common::debug_fatal;
29use iota_config::{
30    ConsensusConfig, NodeConfig,
31    node::{DBCheckpointConfig, RunWithRange},
32    node_config_metrics::NodeConfigMetrics,
33    object_storage_config::{ObjectStoreConfig, ObjectStoreType},
34};
35use iota_core::{
36    authority::{
37        AuthorityState, AuthorityStore, RandomnessRoundReceiver,
38        authority_per_epoch_store::AuthorityPerEpochStore,
39        authority_store_pruner::ObjectsCompactionFilter,
40        authority_store_tables::{
41            AuthorityPerpetualTables, AuthorityPerpetualTablesOptions, AuthorityPrunerTables,
42        },
43        backpressure::BackpressureManager,
44        epoch_start_configuration::{EpochFlag, EpochStartConfigTrait, EpochStartConfiguration},
45    },
46    authority_aggregator::{
47        AggregatorSendCapabilityNotificationError, AuthAggMetrics, AuthorityAggregator,
48    },
49    authority_client::NetworkAuthorityClient,
50    authority_server::{ValidatorService, ValidatorServiceMetrics},
51    checkpoints::{
52        CheckpointMetrics, CheckpointService, CheckpointStore, SendCheckpointToStateSync,
53        SubmitCheckpointToConsensus,
54        checkpoint_executor::{CheckpointExecutor, StopReason, metrics::CheckpointExecutorMetrics},
55    },
56    connection_monitor::ConnectionMonitor,
57    consensus_adapter::{
58        CheckConnection, ConnectionMonitorStatus, ConsensusAdapter, ConsensusAdapterMetrics,
59        ConsensusClient,
60    },
61    consensus_handler::ConsensusHandlerInitializer,
62    consensus_manager::{ConsensusManager, ConsensusManagerTrait, UpdatableConsensusClient},
63    consensus_validator::{IotaTxValidator, IotaTxValidatorMetrics},
64    db_checkpoint_handler::DBCheckpointHandler,
65    epoch::{
66        committee_store::CommitteeStore, consensus_store_pruner::ConsensusStorePruner,
67        epoch_metrics::EpochMetrics, randomness::RandomnessManager,
68        reconfiguration::ReconfigurationInitiator,
69    },
70    execution_cache::build_execution_cache,
71    jsonrpc_index::IndexStore,
72    module_cache_metrics::ResolverMetrics,
73    overload_monitor::overload_monitor,
74    rest_index::RestIndexStore,
75    safe_client::SafeClientMetricsBase,
76    signature_verifier::SignatureVerifierMetrics,
77    state_accumulator::{StateAccumulator, StateAccumulatorMetrics},
78    storage::{RestReadStore, RocksDbStore},
79    traffic_controller::metrics::TrafficControllerMetrics,
80    transaction_orchestrator::TransactionOrchestrator,
81    validator_tx_finalizer::ValidatorTxFinalizer,
82};
83use iota_grpc_server::{GrpcReader, GrpcServerHandle, start_grpc_server};
84use iota_json_rpc::{
85    JsonRpcServerBuilder, coin_api::CoinReadApi, governance_api::GovernanceReadApi,
86    indexer_api::IndexerApi, move_utils::MoveUtils, read_api::ReadApi,
87    transaction_builder_api::TransactionBuilderApi,
88    transaction_execution_api::TransactionExecutionApi,
89};
90use iota_json_rpc_api::JsonRpcMetrics;
91use iota_macros::{fail_point, fail_point_async, replay_log};
92use iota_metrics::{
93    RegistryID, RegistryService,
94    hardware_metrics::register_hardware_metrics,
95    metrics_network::{MetricsMakeCallbackHandler, NetworkConnectionMetrics, NetworkMetrics},
96    server_timing_middleware, spawn_monitored_task,
97};
98use iota_names::config::IotaNamesConfig;
99use iota_network::{
100    api::ValidatorServer, discovery, discovery::TrustedPeerChangeEvent, randomness, state_sync,
101};
102use iota_network_stack::server::{IOTA_TLS_SERVER_NAME, ServerBuilder};
103use iota_protocol_config::ProtocolConfig;
104use iota_rest_api::RestMetrics;
105use iota_sdk_types::crypto::{Intent, IntentMessage, IntentScope};
106use iota_snapshot::uploader::StateSnapshotUploader;
107use iota_storage::{
108    FileCompression, StorageFormat,
109    http_key_value_store::HttpKVStore,
110    key_value_store::{FallbackTransactionKVStore, TransactionKeyValueStore},
111    key_value_store_metrics::KeyValueStoreMetrics,
112};
113use iota_types::{
114    base_types::{AuthorityName, ConciseableName, EpochId},
115    committee::Committee,
116    crypto::{AuthoritySignature, IotaAuthoritySignature, KeypairTraits, RandomnessRound},
117    digests::ChainIdentifier,
118    error::{IotaError, IotaResult},
119    executable_transaction::VerifiedExecutableTransaction,
120    execution_config_utils::to_binary_config,
121    full_checkpoint_content::CheckpointData,
122    iota_system_state::{
123        IotaSystemState, IotaSystemStateTrait,
124        epoch_start_iota_system_state::{EpochStartSystemState, EpochStartSystemStateTrait},
125    },
126    messages_consensus::{
127        AuthorityCapabilitiesV1, ConsensusTransaction, ConsensusTransactionKind,
128        SignedAuthorityCapabilitiesV1, check_total_jwk_size,
129    },
130    messages_grpc::HandleCapabilityNotificationRequestV1,
131    quorum_driver_types::QuorumDriverEffectsQueueResult,
132    supported_protocol_versions::SupportedProtocolVersions,
133    transaction::{Transaction, VerifiedCertificate},
134};
135use prometheus::Registry;
136#[cfg(msim)]
137pub use simulator::set_jwk_injector;
138#[cfg(msim)]
139use simulator::*;
140use tap::tap::TapFallible;
141use tokio::{
142    runtime::Handle,
143    sync::{Mutex, broadcast, mpsc, watch},
144    task::{JoinHandle, JoinSet},
145};
146use tokio_util::sync::CancellationToken;
147use tower::ServiceBuilder;
148use tracing::{Instrument, debug, error, error_span, info, warn};
149use typed_store::{
150    DBMetrics,
151    rocks::{check_and_mark_db_corruption, default_db_options, unmark_db_corruption},
152};
153
154use crate::metrics::{GrpcMetrics, IotaNodeMetrics};
155
156pub mod admin;
157mod handle;
158pub mod metrics;
159
160pub struct ValidatorComponents {
161    validator_server_handle: SpawnOnce,
162    validator_overload_monitor_handle: Option<JoinHandle<()>>,
163    consensus_manager: ConsensusManager,
164    consensus_store_pruner: ConsensusStorePruner,
165    consensus_adapter: Arc<ConsensusAdapter>,
166    // Keeping the handle to the checkpoint service tasks to shut them down during reconfiguration.
167    checkpoint_service_tasks: JoinSet<()>,
168    checkpoint_metrics: Arc<CheckpointMetrics>,
169    iota_tx_validator_metrics: Arc<IotaTxValidatorMetrics>,
170    validator_registry_id: RegistryID,
171}
172
173#[cfg(msim)]
174mod simulator {
175    use std::sync::atomic::AtomicBool;
176
177    use super::*;
178
179    pub(super) struct SimState {
180        pub sim_node: iota_simulator::runtime::NodeHandle,
181        pub sim_safe_mode_expected: AtomicBool,
182        _leak_detector: iota_simulator::NodeLeakDetector,
183    }
184
185    impl Default for SimState {
186        fn default() -> Self {
187            Self {
188                sim_node: iota_simulator::runtime::NodeHandle::current(),
189                sim_safe_mode_expected: AtomicBool::new(false),
190                _leak_detector: iota_simulator::NodeLeakDetector::new(),
191            }
192        }
193    }
194
195    type JwkInjector = dyn Fn(AuthorityName, &OIDCProvider) -> IotaResult<Vec<(JwkId, JWK)>>
196        + Send
197        + Sync
198        + 'static;
199
200    fn default_fetch_jwks(
201        _authority: AuthorityName,
202        _provider: &OIDCProvider,
203    ) -> IotaResult<Vec<(JwkId, JWK)>> {
204        use fastcrypto_zkp::bn254::zk_login::parse_jwks;
205        // Just load a default Twitch jwk for testing.
206        parse_jwks(
207            iota_types::zk_login_util::DEFAULT_JWK_BYTES,
208            &OIDCProvider::Twitch,
209        )
210        .map_err(|_| IotaError::JWKRetrieval)
211    }
212
213    thread_local! {
214        static JWK_INJECTOR: std::cell::RefCell<Arc<JwkInjector>> = std::cell::RefCell::new(Arc::new(default_fetch_jwks));
215    }
216
217    pub(super) fn get_jwk_injector() -> Arc<JwkInjector> {
218        JWK_INJECTOR.with(|injector| injector.borrow().clone())
219    }
220
221    pub fn set_jwk_injector(injector: Arc<JwkInjector>) {
222        JWK_INJECTOR.with(|cell| *cell.borrow_mut() = injector);
223    }
224}
225
226pub struct IotaNode {
227    config: NodeConfig,
228    validator_components: Mutex<Option<ValidatorComponents>>,
229    /// The http server responsible for serving JSON-RPC as well as the
230    /// experimental rest service
231    _http_server: Option<iota_http::ServerHandle>,
232    state: Arc<AuthorityState>,
233    transaction_orchestrator: Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>>,
234    registry_service: RegistryService,
235    metrics: Arc<IotaNodeMetrics>,
236
237    _discovery: discovery::Handle,
238    state_sync_handle: state_sync::Handle,
239    randomness_handle: randomness::Handle,
240    checkpoint_store: Arc<CheckpointStore>,
241    accumulator: Mutex<Option<Arc<StateAccumulator>>>,
242    connection_monitor_status: Arc<ConnectionMonitorStatus>,
243
244    /// Broadcast channel to send the starting system state for the next epoch.
245    end_of_epoch_channel: broadcast::Sender<IotaSystemState>,
246
247    /// Broadcast channel to notify [`DiscoveryEventLoop`] for new validator
248    /// peers.
249    trusted_peer_change_tx: watch::Sender<TrustedPeerChangeEvent>,
250
251    backpressure_manager: Arc<BackpressureManager>,
252
253    _db_checkpoint_handle: Option<tokio::sync::broadcast::Sender<()>>,
254
255    #[cfg(msim)]
256    sim_state: SimState,
257
258    _state_archive_handle: Option<broadcast::Sender<()>>,
259
260    _state_snapshot_uploader_handle: Option<broadcast::Sender<()>>,
261    // Channel to allow signaling upstream to shutdown iota-node
262    shutdown_channel_tx: broadcast::Sender<Option<RunWithRange>>,
263
264    /// Handle to the gRPC server for gRPC streaming and graceful shutdown
265    grpc_server_handle: Mutex<Option<GrpcServerHandle>>,
266
267    /// AuthorityAggregator of the network, created at start and beginning of
268    /// each epoch. Use ArcSwap so that we could mutate it without taking
269    /// mut reference.
270    // TODO: Eventually we can make this auth aggregator a shared reference so that this
271    // update will automatically propagate to other uses.
272    auth_agg: Arc<ArcSwap<AuthorityAggregator<NetworkAuthorityClient>>>,
273}
274
275impl fmt::Debug for IotaNode {
276    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
277        f.debug_struct("IotaNode")
278            .field("name", &self.state.name.concise())
279            .finish()
280    }
281}
282
283static MAX_JWK_KEYS_PER_FETCH: usize = 100;
284
285impl IotaNode {
286    pub async fn start(
287        config: NodeConfig,
288        registry_service: RegistryService,
289        custom_rpc_runtime: Option<Handle>,
290    ) -> Result<Arc<IotaNode>> {
291        Self::start_async(config, registry_service, custom_rpc_runtime, "unknown").await
292    }
293
294    /// Starts the JWK (JSON Web Key) updater tasks for the specified node
295    /// configuration.
296    /// This function ensures continuous fetching, validation, and submission of
297    /// JWKs, maintaining up-to-date keys for the specified providers.
298    fn start_jwk_updater(
299        config: &NodeConfig,
300        metrics: Arc<IotaNodeMetrics>,
301        authority: AuthorityName,
302        epoch_store: Arc<AuthorityPerEpochStore>,
303        consensus_adapter: Arc<ConsensusAdapter>,
304    ) {
305        let epoch = epoch_store.epoch();
306
307        let supported_providers = config
308            .zklogin_oauth_providers
309            .get(&epoch_store.get_chain_identifier().chain())
310            .unwrap_or(&BTreeSet::new())
311            .iter()
312            .map(|s| OIDCProvider::from_str(s).expect("Invalid provider string"))
313            .collect::<Vec<_>>();
314
315        let fetch_interval = Duration::from_secs(config.jwk_fetch_interval_seconds);
316
317        info!(
318            ?fetch_interval,
319            "Starting JWK updater tasks with supported providers: {:?}", supported_providers
320        );
321
322        fn validate_jwk(
323            metrics: &Arc<IotaNodeMetrics>,
324            provider: &OIDCProvider,
325            id: &JwkId,
326            jwk: &JWK,
327        ) -> bool {
328            let Ok(iss_provider) = OIDCProvider::from_iss(&id.iss) else {
329                warn!(
330                    "JWK iss {:?} (retrieved from {:?}) is not a valid provider",
331                    id.iss, provider
332                );
333                metrics
334                    .invalid_jwks
335                    .with_label_values(&[&provider.to_string()])
336                    .inc();
337                return false;
338            };
339
340            if iss_provider != *provider {
341                warn!(
342                    "JWK iss {:?} (retrieved from {:?}) does not match provider {:?}",
343                    id.iss, provider, iss_provider
344                );
345                metrics
346                    .invalid_jwks
347                    .with_label_values(&[&provider.to_string()])
348                    .inc();
349                return false;
350            }
351
352            if !check_total_jwk_size(id, jwk) {
353                warn!("JWK {:?} (retrieved from {:?}) is too large", id, provider);
354                metrics
355                    .invalid_jwks
356                    .with_label_values(&[&provider.to_string()])
357                    .inc();
358                return false;
359            }
360
361            true
362        }
363
364        // metrics is:
365        //  pub struct IotaNodeMetrics {
366        //      pub jwk_requests: IntCounterVec,
367        //      pub jwk_request_errors: IntCounterVec,
368        //      pub total_jwks: IntCounterVec,
369        //      pub unique_jwks: IntCounterVec,
370        //  }
371
372        for p in supported_providers.into_iter() {
373            let provider_str = p.to_string();
374            let epoch_store = epoch_store.clone();
375            let consensus_adapter = consensus_adapter.clone();
376            let metrics = metrics.clone();
377            spawn_monitored_task!(epoch_store.clone().within_alive_epoch(
378                async move {
379                    // note: restart-safe de-duplication happens after consensus, this is
380                    // just best-effort to reduce unneeded submissions.
381                    let mut seen = HashSet::new();
382                    loop {
383                        info!("fetching JWK for provider {:?}", p);
384                        metrics.jwk_requests.with_label_values(&[&provider_str]).inc();
385                        match Self::fetch_jwks(authority, &p).await {
386                            Err(e) => {
387                                metrics.jwk_request_errors.with_label_values(&[&provider_str]).inc();
388                                warn!("Error when fetching JWK for provider {:?} {:?}", p, e);
389                                // Retry in 30 seconds
390                                tokio::time::sleep(Duration::from_secs(30)).await;
391                                continue;
392                            }
393                            Ok(mut keys) => {
394                                metrics.total_jwks
395                                    .with_label_values(&[&provider_str])
396                                    .inc_by(keys.len() as u64);
397
398                                keys.retain(|(id, jwk)| {
399                                    validate_jwk(&metrics, &p, id, jwk) &&
400                                    !epoch_store.jwk_active_in_current_epoch(id, jwk) &&
401                                    seen.insert((id.clone(), jwk.clone()))
402                                });
403
404                                metrics.unique_jwks
405                                    .with_label_values(&[&provider_str])
406                                    .inc_by(keys.len() as u64);
407
408                                // prevent oauth providers from sending too many keys,
409                                // inadvertently or otherwise
410                                if keys.len() > MAX_JWK_KEYS_PER_FETCH {
411                                    warn!("Provider {:?} sent too many JWKs, only the first {} will be used", p, MAX_JWK_KEYS_PER_FETCH);
412                                    keys.truncate(MAX_JWK_KEYS_PER_FETCH);
413                                }
414
415                                for (id, jwk) in keys.into_iter() {
416                                    info!("Submitting JWK to consensus: {:?}", id);
417
418                                    let txn = ConsensusTransaction::new_jwk_fetched(authority, id, jwk);
419                                    consensus_adapter.submit(txn, None, &epoch_store)
420                                        .tap_err(|e| warn!("Error when submitting JWKs to consensus {:?}", e))
421                                        .ok();
422                                }
423                            }
424                        }
425                        tokio::time::sleep(fetch_interval).await;
426                    }
427                }
428                .instrument(error_span!("jwk_updater_task", epoch)),
429            ));
430        }
431    }
432
433    pub async fn start_async(
434        config: NodeConfig,
435        registry_service: RegistryService,
436        custom_rpc_runtime: Option<Handle>,
437        software_version: &'static str,
438    ) -> Result<Arc<IotaNode>> {
439        NodeConfigMetrics::new(&registry_service.default_registry()).record_metrics(&config);
440        let mut config = config.clone();
441        if config.supported_protocol_versions.is_none() {
442            info!(
443                "populating config.supported_protocol_versions with default {:?}",
444                SupportedProtocolVersions::SYSTEM_DEFAULT
445            );
446            config.supported_protocol_versions = Some(SupportedProtocolVersions::SYSTEM_DEFAULT);
447        }
448
449        let run_with_range = config.run_with_range;
450        let is_validator = config.consensus_config().is_some();
451        let is_full_node = !is_validator;
452        let prometheus_registry = registry_service.default_registry();
453
454        info!(node =? config.authority_public_key(),
455            "Initializing iota-node listening on {}", config.network_address
456        );
457
458        let genesis = config.genesis()?.clone();
459
460        let chain_identifier = ChainIdentifier::from(*genesis.checkpoint().digest());
461        info!("IOTA chain identifier: {chain_identifier}");
462
463        // Check and set the db_corrupted flag
464        let db_corrupted_path = &config.db_path().join("status");
465        if let Err(err) = check_and_mark_db_corruption(db_corrupted_path) {
466            panic!("Failed to check database corruption: {err}");
467        }
468
469        // Initialize metrics to track db usage before creating any stores
470        DBMetrics::init(&prometheus_registry);
471
472        // Initialize IOTA metrics.
473        iota_metrics::init_metrics(&prometheus_registry);
474        // Unsupported (because of the use of static variable) and unnecessary in
475        // simtests.
476        #[cfg(not(msim))]
477        iota_metrics::thread_stall_monitor::start_thread_stall_monitor();
478
479        // Register hardware metrics.
480        register_hardware_metrics(&registry_service, &config.db_path)
481            .expect("Failed registering hardware metrics");
482        // Register uptime metric
483        prometheus_registry
484            .register(iota_metrics::uptime_metric(
485                if is_validator {
486                    "validator"
487                } else {
488                    "fullnode"
489                },
490                software_version,
491                &chain_identifier.to_string(),
492            ))
493            .expect("Failed registering uptime metric");
494
495        // If genesis come with some migration data then load them into memory from the
496        // file path specified in config.
497        let migration_tx_data = if genesis.contains_migrations() {
498            // Here the load already verifies that the content of the migration blob is
499            // valid in respect to the content found in genesis
500            Some(config.load_migration_tx_data()?)
501        } else {
502            None
503        };
504
505        let secret = Arc::pin(config.authority_key_pair().copy());
506        let genesis_committee = genesis.committee()?;
507        let committee_store = Arc::new(CommitteeStore::new(
508            config.db_path().join("epochs"),
509            &genesis_committee,
510            None,
511        ));
512
513        let mut pruner_db = None;
514        if config
515            .authority_store_pruning_config
516            .enable_compaction_filter
517        {
518            pruner_db = Some(Arc::new(AuthorityPrunerTables::open(
519                &config.db_path().join("store"),
520            )));
521        }
522        let compaction_filter = pruner_db
523            .clone()
524            .map(|db| ObjectsCompactionFilter::new(db, &prometheus_registry));
525
526        // By default, only enable write stall on validators for perpetual db.
527        let enable_write_stall = config.enable_db_write_stall.unwrap_or(is_validator);
528        let perpetual_tables_options = AuthorityPerpetualTablesOptions {
529            enable_write_stall,
530            compaction_filter,
531        };
532        let perpetual_tables = Arc::new(AuthorityPerpetualTables::open(
533            &config.db_path().join("store"),
534            Some(perpetual_tables_options),
535        ));
536        let is_genesis = perpetual_tables
537            .database_is_empty()
538            .expect("Database read should not fail at init.");
539        let checkpoint_store = CheckpointStore::new(&config.db_path().join("checkpoints"));
540        let backpressure_manager =
541            BackpressureManager::new_from_checkpoint_store(&checkpoint_store);
542
543        let store = AuthorityStore::open(
544            perpetual_tables,
545            &genesis,
546            &config,
547            &prometheus_registry,
548            migration_tx_data.as_ref(),
549        )
550        .await?;
551
552        let cur_epoch = store.get_recovery_epoch_at_restart()?;
553        let committee = committee_store
554            .get_committee(&cur_epoch)?
555            .expect("Committee of the current epoch must exist");
556        let epoch_start_configuration = store
557            .get_epoch_start_configuration()?
558            .expect("EpochStartConfiguration of the current epoch must exist");
559        let cache_metrics = Arc::new(ResolverMetrics::new(&prometheus_registry));
560        let signature_verifier_metrics = SignatureVerifierMetrics::new(&prometheus_registry);
561
562        let cache_traits = build_execution_cache(
563            &config.execution_cache_config,
564            &epoch_start_configuration,
565            &prometheus_registry,
566            &store,
567            backpressure_manager.clone(),
568        );
569
570        let auth_agg = {
571            let safe_client_metrics_base = SafeClientMetricsBase::new(&prometheus_registry);
572            let auth_agg_metrics = Arc::new(AuthAggMetrics::new(&prometheus_registry));
573            Arc::new(ArcSwap::new(Arc::new(
574                AuthorityAggregator::new_from_epoch_start_state(
575                    epoch_start_configuration.epoch_start_state(),
576                    &committee_store,
577                    safe_client_metrics_base,
578                    auth_agg_metrics,
579                ),
580            )))
581        };
582
583        let chain_id = ChainIdentifier::from(*genesis.checkpoint().digest());
584        let chain = match config.chain_override_for_testing {
585            Some(chain) => chain,
586            None => ChainIdentifier::from(*genesis.checkpoint().digest()).chain(),
587        };
588
589        let epoch_options = default_db_options().optimize_db_for_write_throughput(4);
590        let epoch_store = AuthorityPerEpochStore::new(
591            config.authority_public_key(),
592            committee.clone(),
593            &config.db_path().join("store"),
594            Some(epoch_options.options),
595            EpochMetrics::new(&registry_service.default_registry()),
596            epoch_start_configuration,
597            cache_traits.backing_package_store.clone(),
598            cache_traits.object_store.clone(),
599            cache_metrics,
600            signature_verifier_metrics,
601            &config.expensive_safety_check_config,
602            (chain_id, chain),
603            checkpoint_store
604                .get_highest_executed_checkpoint_seq_number()
605                .expect("checkpoint store read cannot fail")
606                .unwrap_or(0),
607        )?;
608
609        info!("created epoch store");
610
611        replay_log!(
612            "Beginning replay run. Epoch: {:?}, Protocol config: {:?}",
613            epoch_store.epoch(),
614            epoch_store.protocol_config()
615        );
616
617        // the database is empty at genesis time
618        if is_genesis {
619            info!("checking IOTA conservation at genesis");
620            // When we are opening the db table, the only time when it's safe to
621            // check IOTA conservation is at genesis. Otherwise we may be in the middle of
622            // an epoch and the IOTA conservation check will fail. This also initialize
623            // the expected_network_iota_amount table.
624            cache_traits
625                .reconfig_api
626                .try_expensive_check_iota_conservation(&epoch_store, None)
627                .expect("IOTA conservation check cannot fail at genesis");
628        }
629
630        let effective_buffer_stake = epoch_store.get_effective_buffer_stake_bps();
631        let default_buffer_stake = epoch_store
632            .protocol_config()
633            .buffer_stake_for_protocol_upgrade_bps();
634        if effective_buffer_stake != default_buffer_stake {
635            warn!(
636                ?effective_buffer_stake,
637                ?default_buffer_stake,
638                "buffer_stake_for_protocol_upgrade_bps is currently overridden"
639            );
640        }
641
642        checkpoint_store.insert_genesis_checkpoint(
643            genesis.checkpoint(),
644            genesis.checkpoint_contents().clone(),
645            &epoch_store,
646        );
647
648        // Database has everything from genesis, set corrupted key to 0
649        unmark_db_corruption(db_corrupted_path)?;
650
651        info!("creating state sync store");
652        let state_sync_store = RocksDbStore::new(
653            cache_traits.clone(),
654            committee_store.clone(),
655            checkpoint_store.clone(),
656        );
657
658        let index_store = if is_full_node && config.enable_index_processing {
659            info!("creating index store");
660            Some(Arc::new(IndexStore::new(
661                config.db_path().join("indexes"),
662                &prometheus_registry,
663                epoch_store
664                    .protocol_config()
665                    .max_move_identifier_len_as_option(),
666                config.remove_deprecated_tables,
667            )))
668        } else {
669            None
670        };
671
672        let rest_index = if is_full_node && config.enable_rest_api && config.enable_index_processing
673        {
674            Some(Arc::new(
675                RestIndexStore::new(
676                    config.db_path().join("rest_index"),
677                    &store,
678                    &checkpoint_store,
679                    &epoch_store,
680                    &cache_traits.backing_package_store,
681                )
682                .await,
683            ))
684        } else {
685            None
686        };
687
688        info!("creating archive reader");
689        // Create network
690        // TODO only configure validators as seed/preferred peers for validators and not
691        // for fullnodes once we've had a chance to re-work fullnode
692        // configuration generation.
693        let archive_readers =
694            ArchiveReaderBalancer::new(config.archive_reader_config(), &prometheus_registry)?;
695        let (trusted_peer_change_tx, trusted_peer_change_rx) = watch::channel(Default::default());
696        let (randomness_tx, randomness_rx) = mpsc::channel(
697            config
698                .p2p_config
699                .randomness
700                .clone()
701                .unwrap_or_default()
702                .mailbox_capacity(),
703        );
704        let (p2p_network, discovery_handle, state_sync_handle, randomness_handle) =
705            Self::create_p2p_network(
706                &config,
707                state_sync_store.clone(),
708                chain_identifier,
709                trusted_peer_change_rx,
710                archive_readers.clone(),
711                randomness_tx,
712                &prometheus_registry,
713            )?;
714
715        // We must explicitly send this instead of relying on the initial value to
716        // trigger watch value change, so that state-sync is able to process it.
717        send_trusted_peer_change(
718            &config,
719            &trusted_peer_change_tx,
720            epoch_store.epoch_start_state(),
721        );
722
723        info!("start state archival");
724        // Start archiving local state to remote store
725        let state_archive_handle =
726            Self::start_state_archival(&config, &prometheus_registry, state_sync_store.clone())
727                .await?;
728
729        info!("start snapshot upload");
730        // Start uploading state snapshot to remote store
731        let state_snapshot_handle =
732            Self::start_state_snapshot(&config, &prometheus_registry, checkpoint_store.clone())?;
733
734        // Start uploading db checkpoints to remote store
735        info!("start db checkpoint");
736        let (db_checkpoint_config, db_checkpoint_handle) = Self::start_db_checkpoint(
737            &config,
738            &prometheus_registry,
739            state_snapshot_handle.is_some(),
740        )?;
741
742        let mut genesis_objects = genesis.objects().to_vec();
743        if let Some(migration_tx_data) = migration_tx_data.as_ref() {
744            genesis_objects.extend(migration_tx_data.get_objects());
745        }
746
747        let authority_name = config.authority_public_key();
748        let validator_tx_finalizer =
749            config
750                .enable_validator_tx_finalizer
751                .then_some(Arc::new(ValidatorTxFinalizer::new(
752                    auth_agg.clone(),
753                    authority_name,
754                    &prometheus_registry,
755                )));
756
757        info!("create authority state");
758        let state = AuthorityState::new(
759            authority_name,
760            secret,
761            config.supported_protocol_versions.unwrap(),
762            store.clone(),
763            cache_traits.clone(),
764            epoch_store.clone(),
765            committee_store.clone(),
766            index_store.clone(),
767            rest_index,
768            checkpoint_store.clone(),
769            &prometheus_registry,
770            &genesis_objects,
771            &db_checkpoint_config,
772            config.clone(),
773            archive_readers,
774            validator_tx_finalizer,
775            chain_identifier,
776            pruner_db,
777        )
778        .await;
779
780        // ensure genesis and migration txs were executed
781        if epoch_store.epoch() == 0 {
782            let genesis_tx = &genesis.transaction();
783            let span = error_span!("genesis_txn", tx_digest = ?genesis_tx.digest());
784            // Execute genesis transaction
785            Self::execute_transaction_immediately_at_zero_epoch(
786                &state,
787                &epoch_store,
788                genesis_tx,
789                span,
790            )
791            .await;
792
793            // Execute migration transactions if present
794            if let Some(migration_tx_data) = migration_tx_data {
795                for (tx_digest, (tx, _, _)) in migration_tx_data.txs_data() {
796                    let span = error_span!("migration_txn", tx_digest = ?tx_digest);
797                    Self::execute_transaction_immediately_at_zero_epoch(
798                        &state,
799                        &epoch_store,
800                        tx,
801                        span,
802                    )
803                    .await;
804                }
805            }
806        }
807
808        // Start the loop that receives new randomness and generates transactions for
809        // it.
810        RandomnessRoundReceiver::spawn(state.clone(), randomness_rx);
811
812        if config
813            .expensive_safety_check_config
814            .enable_secondary_index_checks()
815        {
816            if let Some(indexes) = state.indexes.clone() {
817                iota_core::verify_indexes::verify_indexes(
818                    state.get_accumulator_store().as_ref(),
819                    indexes,
820                )
821                .expect("secondary indexes are inconsistent");
822            }
823        }
824
825        let (end_of_epoch_channel, end_of_epoch_receiver) =
826            broadcast::channel(config.end_of_epoch_broadcast_channel_capacity);
827
828        let transaction_orchestrator = if is_full_node && run_with_range.is_none() {
829            Some(Arc::new(TransactionOrchestrator::new_with_auth_aggregator(
830                auth_agg.load_full(),
831                state.clone(),
832                end_of_epoch_receiver,
833                &config.db_path(),
834                &prometheus_registry,
835            )))
836        } else {
837            None
838        };
839
840        let http_server = build_http_server(
841            state.clone(),
842            state_sync_store.clone(),
843            &transaction_orchestrator.clone(),
844            &config,
845            &prometheus_registry,
846            custom_rpc_runtime,
847            software_version,
848        )
849        .await?;
850
851        let accumulator = Arc::new(StateAccumulator::new(
852            cache_traits.accumulator_store.clone(),
853            StateAccumulatorMetrics::new(&prometheus_registry),
854        ));
855
856        let authority_names_to_peer_ids = epoch_store
857            .epoch_start_state()
858            .get_authority_names_to_peer_ids();
859
860        let network_connection_metrics =
861            NetworkConnectionMetrics::new("iota", &registry_service.default_registry());
862
863        let authority_names_to_peer_ids = ArcSwap::from_pointee(authority_names_to_peer_ids);
864
865        let (_connection_monitor_handle, connection_statuses) = ConnectionMonitor::spawn(
866            p2p_network.downgrade(),
867            network_connection_metrics,
868            HashMap::new(),
869            None,
870        );
871
872        let connection_monitor_status = ConnectionMonitorStatus {
873            connection_statuses,
874            authority_names_to_peer_ids,
875        };
876
877        let connection_monitor_status = Arc::new(connection_monitor_status);
878        let iota_node_metrics =
879            Arc::new(IotaNodeMetrics::new(&registry_service.default_registry()));
880
881        // Convert transaction orchestrator to executor trait object for gRPC server
882        // Note that the transaction_orchestrator (so as executor) will be None if it is
883        // a validator node or run_with_range is set
884        let executor: Option<Arc<dyn iota_types::transaction_executor::TransactionExecutor>> =
885            transaction_orchestrator
886                .clone()
887                .map(|o| o as Arc<dyn iota_types::transaction_executor::TransactionExecutor>);
888
889        let grpc_server_handle =
890            build_grpc_server(&config, state.clone(), state_sync_store.clone(), executor).await?;
891
892        let validator_components = if state.is_committee_validator(&epoch_store) {
893            let (components, _) = futures::join!(
894                Self::construct_validator_components(
895                    config.clone(),
896                    state.clone(),
897                    committee,
898                    epoch_store.clone(),
899                    checkpoint_store.clone(),
900                    state_sync_handle.clone(),
901                    randomness_handle.clone(),
902                    Arc::downgrade(&accumulator),
903                    backpressure_manager.clone(),
904                    connection_monitor_status.clone(),
905                    &registry_service,
906                    iota_node_metrics.clone(),
907                ),
908                Self::reexecute_pending_consensus_certs(&epoch_store, &state,)
909            );
910            let mut components = components?;
911
912            components.consensus_adapter.submit_recovered(&epoch_store);
913
914            // Start the gRPC server
915            components.validator_server_handle = components.validator_server_handle.start().await;
916
917            Some(components)
918        } else {
919            None
920        };
921
922        // setup shutdown channel
923        let (shutdown_channel, _) = broadcast::channel::<Option<RunWithRange>>(1);
924
925        let node = Self {
926            config,
927            validator_components: Mutex::new(validator_components),
928            _http_server: http_server,
929            state,
930            transaction_orchestrator,
931            registry_service,
932            metrics: iota_node_metrics,
933
934            _discovery: discovery_handle,
935            state_sync_handle,
936            randomness_handle,
937            checkpoint_store,
938            accumulator: Mutex::new(Some(accumulator)),
939            end_of_epoch_channel,
940            connection_monitor_status,
941            trusted_peer_change_tx,
942            backpressure_manager,
943
944            _db_checkpoint_handle: db_checkpoint_handle,
945
946            #[cfg(msim)]
947            sim_state: Default::default(),
948
949            _state_archive_handle: state_archive_handle,
950            _state_snapshot_uploader_handle: state_snapshot_handle,
951            shutdown_channel_tx: shutdown_channel,
952
953            grpc_server_handle: Mutex::new(grpc_server_handle),
954
955            auth_agg,
956        };
957
958        info!("IotaNode started!");
959        let node = Arc::new(node);
960        let node_copy = node.clone();
961        spawn_monitored_task!(async move {
962            let result = Self::monitor_reconfiguration(node_copy, epoch_store).await;
963            if let Err(error) = result {
964                warn!("Reconfiguration finished with error {:?}", error);
965            }
966        });
967
968        Ok(node)
969    }
970
971    pub fn subscribe_to_epoch_change(&self) -> broadcast::Receiver<IotaSystemState> {
972        self.end_of_epoch_channel.subscribe()
973    }
974
975    pub fn subscribe_to_shutdown_channel(&self) -> broadcast::Receiver<Option<RunWithRange>> {
976        self.shutdown_channel_tx.subscribe()
977    }
978
979    pub fn current_epoch_for_testing(&self) -> EpochId {
980        self.state.current_epoch_for_testing()
981    }
982
983    pub fn db_checkpoint_path(&self) -> PathBuf {
984        self.config.db_checkpoint_path()
985    }
986
987    // Init reconfig process by starting to reject user certs
988    pub async fn close_epoch(&self, epoch_store: &Arc<AuthorityPerEpochStore>) -> IotaResult {
989        info!("close_epoch (current epoch = {})", epoch_store.epoch());
990        self.validator_components
991            .lock()
992            .await
993            .as_ref()
994            .ok_or_else(|| IotaError::from("Node is not a validator"))?
995            .consensus_adapter
996            .close_epoch(epoch_store);
997        Ok(())
998    }
999
1000    pub fn clear_override_protocol_upgrade_buffer_stake(&self, epoch: EpochId) -> IotaResult {
1001        self.state
1002            .clear_override_protocol_upgrade_buffer_stake(epoch)
1003    }
1004
1005    pub fn set_override_protocol_upgrade_buffer_stake(
1006        &self,
1007        epoch: EpochId,
1008        buffer_stake_bps: u64,
1009    ) -> IotaResult {
1010        self.state
1011            .set_override_protocol_upgrade_buffer_stake(epoch, buffer_stake_bps)
1012    }
1013
1014    // Testing-only API to start epoch close process.
1015    // For production code, please use the non-testing version.
1016    pub async fn close_epoch_for_testing(&self) -> IotaResult {
1017        let epoch_store = self.state.epoch_store_for_testing();
1018        self.close_epoch(&epoch_store).await
1019    }
1020
1021    async fn start_state_archival(
1022        config: &NodeConfig,
1023        prometheus_registry: &Registry,
1024        state_sync_store: RocksDbStore,
1025    ) -> Result<Option<tokio::sync::broadcast::Sender<()>>> {
1026        if let Some(remote_store_config) = &config.state_archive_write_config.object_store_config {
1027            let local_store_config = ObjectStoreConfig {
1028                object_store: Some(ObjectStoreType::File),
1029                directory: Some(config.archive_path()),
1030                ..Default::default()
1031            };
1032            let archive_writer = ArchiveWriter::new(
1033                local_store_config,
1034                remote_store_config.clone(),
1035                FileCompression::Zstd,
1036                StorageFormat::Blob,
1037                Duration::from_secs(600),
1038                256 * 1024 * 1024,
1039                prometheus_registry,
1040            )
1041            .await?;
1042            Ok(Some(archive_writer.start(state_sync_store).await?))
1043        } else {
1044            Ok(None)
1045        }
1046    }
1047
1048    /// Creates an StateSnapshotUploader and start it if the StateSnapshotConfig
1049    /// is set.
1050    fn start_state_snapshot(
1051        config: &NodeConfig,
1052        prometheus_registry: &Registry,
1053        checkpoint_store: Arc<CheckpointStore>,
1054    ) -> Result<Option<tokio::sync::broadcast::Sender<()>>> {
1055        if let Some(remote_store_config) = &config.state_snapshot_write_config.object_store_config {
1056            let snapshot_uploader = StateSnapshotUploader::new(
1057                &config.db_checkpoint_path(),
1058                &config.snapshot_path(),
1059                remote_store_config.clone(),
1060                60,
1061                prometheus_registry,
1062                checkpoint_store,
1063            )?;
1064            Ok(Some(snapshot_uploader.start()))
1065        } else {
1066            Ok(None)
1067        }
1068    }
1069
1070    fn start_db_checkpoint(
1071        config: &NodeConfig,
1072        prometheus_registry: &Registry,
1073        state_snapshot_enabled: bool,
1074    ) -> Result<(
1075        DBCheckpointConfig,
1076        Option<tokio::sync::broadcast::Sender<()>>,
1077    )> {
1078        let checkpoint_path = Some(
1079            config
1080                .db_checkpoint_config
1081                .checkpoint_path
1082                .clone()
1083                .unwrap_or_else(|| config.db_checkpoint_path()),
1084        );
1085        let db_checkpoint_config = if config.db_checkpoint_config.checkpoint_path.is_none() {
1086            DBCheckpointConfig {
1087                checkpoint_path,
1088                perform_db_checkpoints_at_epoch_end: if state_snapshot_enabled {
1089                    true
1090                } else {
1091                    config
1092                        .db_checkpoint_config
1093                        .perform_db_checkpoints_at_epoch_end
1094                },
1095                ..config.db_checkpoint_config.clone()
1096            }
1097        } else {
1098            config.db_checkpoint_config.clone()
1099        };
1100
1101        match (
1102            db_checkpoint_config.object_store_config.as_ref(),
1103            state_snapshot_enabled,
1104        ) {
1105            // If db checkpoint config object store not specified but
1106            // state snapshot object store is specified, create handler
1107            // anyway for marking db checkpoints as completed so that they
1108            // can be uploaded as state snapshots.
1109            (None, false) => Ok((db_checkpoint_config, None)),
1110            (_, _) => {
1111                let handler = DBCheckpointHandler::new(
1112                    &db_checkpoint_config.checkpoint_path.clone().unwrap(),
1113                    db_checkpoint_config.object_store_config.as_ref(),
1114                    60,
1115                    db_checkpoint_config
1116                        .prune_and_compact_before_upload
1117                        .unwrap_or(true),
1118                    config.authority_store_pruning_config.clone(),
1119                    prometheus_registry,
1120                    state_snapshot_enabled,
1121                )?;
1122                Ok((
1123                    db_checkpoint_config,
1124                    Some(DBCheckpointHandler::start(handler)),
1125                ))
1126            }
1127        }
1128    }
1129
1130    fn create_p2p_network(
1131        config: &NodeConfig,
1132        state_sync_store: RocksDbStore,
1133        chain_identifier: ChainIdentifier,
1134        trusted_peer_change_rx: watch::Receiver<TrustedPeerChangeEvent>,
1135        archive_readers: ArchiveReaderBalancer,
1136        randomness_tx: mpsc::Sender<(EpochId, RandomnessRound, Vec<u8>)>,
1137        prometheus_registry: &Registry,
1138    ) -> Result<(
1139        Network,
1140        discovery::Handle,
1141        state_sync::Handle,
1142        randomness::Handle,
1143    )> {
1144        let (state_sync, state_sync_server) = state_sync::Builder::new()
1145            .config(config.p2p_config.state_sync.clone().unwrap_or_default())
1146            .store(state_sync_store)
1147            .archive_readers(archive_readers)
1148            .with_metrics(prometheus_registry)
1149            .build();
1150
1151        let (discovery, discovery_server) = discovery::Builder::new(trusted_peer_change_rx)
1152            .config(config.p2p_config.clone())
1153            .build();
1154
1155        let (randomness, randomness_router) =
1156            randomness::Builder::new(config.authority_public_key(), randomness_tx)
1157                .config(config.p2p_config.randomness.clone().unwrap_or_default())
1158                .with_metrics(prometheus_registry)
1159                .build();
1160
1161        let p2p_network = {
1162            let routes = anemo::Router::new()
1163                .add_rpc_service(discovery_server)
1164                .add_rpc_service(state_sync_server);
1165            let routes = routes.merge(randomness_router);
1166
1167            let inbound_network_metrics =
1168                NetworkMetrics::new("iota", "inbound", prometheus_registry);
1169            let outbound_network_metrics =
1170                NetworkMetrics::new("iota", "outbound", prometheus_registry);
1171
1172            let service = ServiceBuilder::new()
1173                .layer(
1174                    TraceLayer::new_for_server_errors()
1175                        .make_span_with(DefaultMakeSpan::new().level(tracing::Level::INFO))
1176                        .on_failure(DefaultOnFailure::new().level(tracing::Level::WARN)),
1177                )
1178                .layer(CallbackLayer::new(MetricsMakeCallbackHandler::new(
1179                    Arc::new(inbound_network_metrics),
1180                    config.p2p_config.excessive_message_size(),
1181                )))
1182                .service(routes);
1183
1184            let outbound_layer = ServiceBuilder::new()
1185                .layer(
1186                    TraceLayer::new_for_client_and_server_errors()
1187                        .make_span_with(DefaultMakeSpan::new().level(tracing::Level::INFO))
1188                        .on_failure(DefaultOnFailure::new().level(tracing::Level::WARN)),
1189                )
1190                .layer(CallbackLayer::new(MetricsMakeCallbackHandler::new(
1191                    Arc::new(outbound_network_metrics),
1192                    config.p2p_config.excessive_message_size(),
1193                )))
1194                .into_inner();
1195
1196            let mut anemo_config = config.p2p_config.anemo_config.clone().unwrap_or_default();
1197            // Set the max_frame_size to be 1 GB to work around the issue of there being too
1198            // many staking events in the epoch change txn.
1199            anemo_config.max_frame_size = Some(1 << 30);
1200
1201            // Set a higher default value for socket send/receive buffers if not already
1202            // configured.
1203            let mut quic_config = anemo_config.quic.unwrap_or_default();
1204            if quic_config.socket_send_buffer_size.is_none() {
1205                quic_config.socket_send_buffer_size = Some(20 << 20);
1206            }
1207            if quic_config.socket_receive_buffer_size.is_none() {
1208                quic_config.socket_receive_buffer_size = Some(20 << 20);
1209            }
1210            quic_config.allow_failed_socket_buffer_size_setting = true;
1211
1212            // Set high-performance defaults for quinn transport.
1213            // With 200MiB buffer size and ~500ms RTT, max throughput ~400MiB/s.
1214            if quic_config.max_concurrent_bidi_streams.is_none() {
1215                quic_config.max_concurrent_bidi_streams = Some(500);
1216            }
1217            if quic_config.max_concurrent_uni_streams.is_none() {
1218                quic_config.max_concurrent_uni_streams = Some(500);
1219            }
1220            if quic_config.stream_receive_window.is_none() {
1221                quic_config.stream_receive_window = Some(100 << 20);
1222            }
1223            if quic_config.receive_window.is_none() {
1224                quic_config.receive_window = Some(200 << 20);
1225            }
1226            if quic_config.send_window.is_none() {
1227                quic_config.send_window = Some(200 << 20);
1228            }
1229            if quic_config.crypto_buffer_size.is_none() {
1230                quic_config.crypto_buffer_size = Some(1 << 20);
1231            }
1232            if quic_config.max_idle_timeout_ms.is_none() {
1233                quic_config.max_idle_timeout_ms = Some(30_000);
1234            }
1235            if quic_config.keep_alive_interval_ms.is_none() {
1236                quic_config.keep_alive_interval_ms = Some(5_000);
1237            }
1238            anemo_config.quic = Some(quic_config);
1239
1240            let server_name = format!("iota-{chain_identifier}");
1241            let network = Network::bind(config.p2p_config.listen_address)
1242                .server_name(&server_name)
1243                .private_key(config.network_key_pair().copy().private().0.to_bytes())
1244                .config(anemo_config)
1245                .outbound_request_layer(outbound_layer)
1246                .start(service)?;
1247            info!(
1248                server_name = server_name,
1249                "P2p network started on {}",
1250                network.local_addr()
1251            );
1252
1253            network
1254        };
1255
1256        let discovery_handle =
1257            discovery.start(p2p_network.clone(), config.network_key_pair().copy());
1258        let state_sync_handle = state_sync.start(p2p_network.clone());
1259        let randomness_handle = randomness.start(p2p_network.clone());
1260
1261        Ok((
1262            p2p_network,
1263            discovery_handle,
1264            state_sync_handle,
1265            randomness_handle,
1266        ))
1267    }
1268
1269    /// Asynchronously constructs and initializes the components necessary for
1270    /// the validator node.
1271    async fn construct_validator_components(
1272        config: NodeConfig,
1273        state: Arc<AuthorityState>,
1274        committee: Arc<Committee>,
1275        epoch_store: Arc<AuthorityPerEpochStore>,
1276        checkpoint_store: Arc<CheckpointStore>,
1277        state_sync_handle: state_sync::Handle,
1278        randomness_handle: randomness::Handle,
1279        accumulator: Weak<StateAccumulator>,
1280        backpressure_manager: Arc<BackpressureManager>,
1281        connection_monitor_status: Arc<ConnectionMonitorStatus>,
1282        registry_service: &RegistryService,
1283        iota_node_metrics: Arc<IotaNodeMetrics>,
1284    ) -> Result<ValidatorComponents> {
1285        let mut config_clone = config.clone();
1286        let consensus_config = config_clone
1287            .consensus_config
1288            .as_mut()
1289            .ok_or_else(|| anyhow!("Validator is missing consensus config"))?;
1290        let validator_registry = Registry::new();
1291        let validator_registry_id = registry_service.add(validator_registry.clone());
1292
1293        let client = Arc::new(UpdatableConsensusClient::new());
1294        let consensus_adapter = Arc::new(Self::construct_consensus_adapter(
1295            &committee,
1296            consensus_config,
1297            state.name,
1298            connection_monitor_status.clone(),
1299            &validator_registry,
1300            client.clone(),
1301            checkpoint_store.clone(),
1302        ));
1303        let consensus_manager = ConsensusManager::new(
1304            &config,
1305            consensus_config,
1306            registry_service,
1307            &validator_registry,
1308            client,
1309        );
1310
1311        // This only gets started up once, not on every epoch. (Make call to remove
1312        // every epoch.)
1313        let consensus_store_pruner = ConsensusStorePruner::new(
1314            consensus_manager.get_storage_base_path(),
1315            consensus_config.db_retention_epochs(),
1316            consensus_config.db_pruner_period(),
1317            &validator_registry,
1318        );
1319
1320        let checkpoint_metrics = CheckpointMetrics::new(&validator_registry);
1321        let iota_tx_validator_metrics = IotaTxValidatorMetrics::new(&validator_registry);
1322
1323        let validator_server_handle = Self::start_grpc_validator_service(
1324            &config,
1325            state.clone(),
1326            consensus_adapter.clone(),
1327            &validator_registry,
1328        )
1329        .await?;
1330
1331        // Starts an overload monitor that monitors the execution of the authority.
1332        // Don't start the overload monitor when max_load_shedding_percentage is 0.
1333        let validator_overload_monitor_handle = if config
1334            .authority_overload_config
1335            .max_load_shedding_percentage
1336            > 0
1337        {
1338            let authority_state = Arc::downgrade(&state);
1339            let overload_config = config.authority_overload_config.clone();
1340            fail_point!("starting_overload_monitor");
1341            Some(spawn_monitored_task!(overload_monitor(
1342                authority_state,
1343                overload_config,
1344            )))
1345        } else {
1346            None
1347        };
1348
1349        Self::start_epoch_specific_validator_components(
1350            &config,
1351            state.clone(),
1352            consensus_adapter,
1353            checkpoint_store,
1354            epoch_store,
1355            state_sync_handle,
1356            randomness_handle,
1357            consensus_manager,
1358            consensus_store_pruner,
1359            accumulator,
1360            backpressure_manager,
1361            validator_server_handle,
1362            validator_overload_monitor_handle,
1363            checkpoint_metrics,
1364            iota_node_metrics,
1365            iota_tx_validator_metrics,
1366            validator_registry_id,
1367        )
1368        .await
1369    }
1370
1371    /// Initializes and starts components specific to the current
1372    /// epoch for the validator node.
1373    async fn start_epoch_specific_validator_components(
1374        config: &NodeConfig,
1375        state: Arc<AuthorityState>,
1376        consensus_adapter: Arc<ConsensusAdapter>,
1377        checkpoint_store: Arc<CheckpointStore>,
1378        epoch_store: Arc<AuthorityPerEpochStore>,
1379        state_sync_handle: state_sync::Handle,
1380        randomness_handle: randomness::Handle,
1381        consensus_manager: ConsensusManager,
1382        consensus_store_pruner: ConsensusStorePruner,
1383        accumulator: Weak<StateAccumulator>,
1384        backpressure_manager: Arc<BackpressureManager>,
1385        validator_server_handle: SpawnOnce,
1386        validator_overload_monitor_handle: Option<JoinHandle<()>>,
1387        checkpoint_metrics: Arc<CheckpointMetrics>,
1388        iota_node_metrics: Arc<IotaNodeMetrics>,
1389        iota_tx_validator_metrics: Arc<IotaTxValidatorMetrics>,
1390        validator_registry_id: RegistryID,
1391    ) -> Result<ValidatorComponents> {
1392        let checkpoint_service = Self::build_checkpoint_service(
1393            config,
1394            consensus_adapter.clone(),
1395            checkpoint_store.clone(),
1396            epoch_store.clone(),
1397            state.clone(),
1398            state_sync_handle,
1399            accumulator,
1400            checkpoint_metrics.clone(),
1401        );
1402
1403        // create a new map that gets injected into both the consensus handler and the
1404        // consensus adapter the consensus handler will write values forwarded
1405        // from consensus, and the consensus adapter will read the values to
1406        // make decisions about which validator submits a transaction to consensus
1407        let low_scoring_authorities = Arc::new(ArcSwap::new(Arc::new(HashMap::new())));
1408
1409        consensus_adapter.swap_low_scoring_authorities(low_scoring_authorities.clone());
1410
1411        let randomness_manager = RandomnessManager::try_new(
1412            Arc::downgrade(&epoch_store),
1413            Box::new(consensus_adapter.clone()),
1414            randomness_handle,
1415            config.authority_key_pair(),
1416        )
1417        .await;
1418        if let Some(randomness_manager) = randomness_manager {
1419            epoch_store
1420                .set_randomness_manager(randomness_manager)
1421                .await?;
1422        }
1423
1424        let consensus_handler_initializer = ConsensusHandlerInitializer::new(
1425            state.clone(),
1426            checkpoint_service.clone(),
1427            epoch_store.clone(),
1428            low_scoring_authorities,
1429            backpressure_manager,
1430        );
1431
1432        info!("Starting consensus manager");
1433
1434        consensus_manager
1435            .start(
1436                config,
1437                epoch_store.clone(),
1438                consensus_handler_initializer,
1439                IotaTxValidator::new(
1440                    epoch_store.clone(),
1441                    checkpoint_service.clone(),
1442                    state.transaction_manager().clone(),
1443                    iota_tx_validator_metrics.clone(),
1444                ),
1445            )
1446            .await;
1447
1448        info!("Spawning checkpoint service");
1449        let checkpoint_service_tasks = checkpoint_service.spawn().await;
1450
1451        if epoch_store.authenticator_state_enabled() {
1452            Self::start_jwk_updater(
1453                config,
1454                iota_node_metrics,
1455                state.name,
1456                epoch_store.clone(),
1457                consensus_adapter.clone(),
1458            );
1459        }
1460
1461        Ok(ValidatorComponents {
1462            validator_server_handle,
1463            validator_overload_monitor_handle,
1464            consensus_manager,
1465            consensus_store_pruner,
1466            consensus_adapter,
1467            checkpoint_service_tasks,
1468            checkpoint_metrics,
1469            iota_tx_validator_metrics,
1470            validator_registry_id,
1471        })
1472    }
1473
1474    /// Starts the checkpoint service for the validator node, initializing
1475    /// necessary components and settings.
1476    /// The function ensures proper initialization of the checkpoint service,
1477    /// preparing it to handle checkpoint creation and submission to consensus,
1478    /// while also setting up the necessary monitoring and synchronization
1479    /// mechanisms.
1480    fn build_checkpoint_service(
1481        config: &NodeConfig,
1482        consensus_adapter: Arc<ConsensusAdapter>,
1483        checkpoint_store: Arc<CheckpointStore>,
1484        epoch_store: Arc<AuthorityPerEpochStore>,
1485        state: Arc<AuthorityState>,
1486        state_sync_handle: state_sync::Handle,
1487        accumulator: Weak<StateAccumulator>,
1488        checkpoint_metrics: Arc<CheckpointMetrics>,
1489    ) -> Arc<CheckpointService> {
1490        let epoch_start_timestamp_ms = epoch_store.epoch_start_state().epoch_start_timestamp_ms();
1491        let epoch_duration_ms = epoch_store.epoch_start_state().epoch_duration_ms();
1492
1493        debug!(
1494            "Starting checkpoint service with epoch start timestamp {}
1495            and epoch duration {}",
1496            epoch_start_timestamp_ms, epoch_duration_ms
1497        );
1498
1499        let checkpoint_output = Box::new(SubmitCheckpointToConsensus {
1500            sender: consensus_adapter,
1501            signer: state.secret.clone(),
1502            authority: config.authority_public_key(),
1503            next_reconfiguration_timestamp_ms: epoch_start_timestamp_ms
1504                .checked_add(epoch_duration_ms)
1505                .expect("Overflow calculating next_reconfiguration_timestamp_ms"),
1506            metrics: checkpoint_metrics.clone(),
1507        });
1508
1509        let certified_checkpoint_output = SendCheckpointToStateSync::new(state_sync_handle);
1510        let max_tx_per_checkpoint = max_tx_per_checkpoint(epoch_store.protocol_config());
1511        let max_checkpoint_size_bytes =
1512            epoch_store.protocol_config().max_checkpoint_size_bytes() as usize;
1513
1514        CheckpointService::build(
1515            state.clone(),
1516            checkpoint_store,
1517            epoch_store,
1518            state.get_transaction_cache_reader().clone(),
1519            accumulator,
1520            checkpoint_output,
1521            Box::new(certified_checkpoint_output),
1522            checkpoint_metrics,
1523            max_tx_per_checkpoint,
1524            max_checkpoint_size_bytes,
1525        )
1526    }
1527
1528    fn construct_consensus_adapter(
1529        committee: &Committee,
1530        consensus_config: &ConsensusConfig,
1531        authority: AuthorityName,
1532        connection_monitor_status: Arc<ConnectionMonitorStatus>,
1533        prometheus_registry: &Registry,
1534        consensus_client: Arc<dyn ConsensusClient>,
1535        checkpoint_store: Arc<CheckpointStore>,
1536    ) -> ConsensusAdapter {
1537        let ca_metrics = ConsensusAdapterMetrics::new(prometheus_registry);
1538        // The consensus adapter allows the authority to send user certificates through
1539        // consensus.
1540
1541        ConsensusAdapter::new(
1542            consensus_client,
1543            checkpoint_store,
1544            authority,
1545            connection_monitor_status,
1546            consensus_config.max_pending_transactions(),
1547            consensus_config.max_pending_transactions() * 2 / committee.num_members(),
1548            consensus_config.max_submit_position,
1549            consensus_config.submit_delay_step_override(),
1550            ca_metrics,
1551        )
1552    }
1553
1554    async fn start_grpc_validator_service(
1555        config: &NodeConfig,
1556        state: Arc<AuthorityState>,
1557        consensus_adapter: Arc<ConsensusAdapter>,
1558        prometheus_registry: &Registry,
1559    ) -> Result<SpawnOnce> {
1560        let validator_service = ValidatorService::new(
1561            state.clone(),
1562            consensus_adapter,
1563            Arc::new(ValidatorServiceMetrics::new(prometheus_registry)),
1564            TrafficControllerMetrics::new(prometheus_registry),
1565            config.policy_config.clone(),
1566            config.firewall_config.clone(),
1567        );
1568
1569        let mut server_conf = iota_network_stack::config::Config::new();
1570        server_conf.global_concurrency_limit = config.grpc_concurrency_limit;
1571        server_conf.load_shed = config.grpc_load_shed;
1572        let server_builder =
1573            ServerBuilder::from_config(&server_conf, GrpcMetrics::new(prometheus_registry))
1574                .add_service(ValidatorServer::new(validator_service));
1575
1576        let tls_config = iota_tls::create_rustls_server_config(
1577            config.network_key_pair().copy().private(),
1578            IOTA_TLS_SERVER_NAME.to_string(),
1579        );
1580
1581        let network_address = config.network_address().clone();
1582
1583        let bind_future = async move {
1584            let server = server_builder
1585                .bind(&network_address, Some(tls_config))
1586                .await
1587                .map_err(|err| anyhow!("Failed to bind to {network_address}: {err}"))?;
1588
1589            let local_addr = server.local_addr();
1590            info!("Listening to traffic on {local_addr}");
1591
1592            Ok(server)
1593        };
1594
1595        Ok(SpawnOnce::new(bind_future))
1596    }
1597
1598    /// Re-executes pending consensus certificates, which may not have been
1599    /// committed to disk before the node restarted. This is necessary for
1600    /// the following reasons:
1601    ///
1602    /// 1. For any transaction for which we returned signed effects to a client,
1603    ///    we must ensure that we have re-executed the transaction before we
1604    ///    begin accepting grpc requests. Otherwise we would appear to have
1605    ///    forgotten about the transaction.
1606    /// 2. While this is running, we are concurrently waiting for all previously
1607    ///    built checkpoints to be rebuilt. Since there may be dependencies in
1608    ///    either direction (from checkpointed consensus transactions to pending
1609    ///    consensus transactions, or vice versa), we must re-execute pending
1610    ///    consensus transactions to ensure that both processes can complete.
1611    /// 3. Also note that for any pending consensus transactions for which we
1612    ///    wrote a signed effects digest to disk, we must re-execute using that
1613    ///    digest as the expected effects digest, to ensure that we cannot
1614    ///    arrive at different effects than what we previously signed.
1615    async fn reexecute_pending_consensus_certs(
1616        epoch_store: &Arc<AuthorityPerEpochStore>,
1617        state: &Arc<AuthorityState>,
1618    ) {
1619        let mut pending_consensus_certificates = Vec::new();
1620        let mut additional_certs = Vec::new();
1621
1622        for tx in epoch_store.get_all_pending_consensus_transactions() {
1623            match tx.kind {
1624                // Shared object txns cannot be re-executed at this point, because we must wait for
1625                // consensus replay to assign shared object versions.
1626                ConsensusTransactionKind::CertifiedTransaction(tx)
1627                    if !tx.contains_shared_object() =>
1628                {
1629                    let tx = *tx;
1630                    // new_unchecked is safe because we never submit a transaction to consensus
1631                    // without verifying it
1632                    let tx = VerifiedExecutableTransaction::new_from_certificate(
1633                        VerifiedCertificate::new_unchecked(tx),
1634                    );
1635                    // we only need to re-execute if we previously signed the effects (which
1636                    // indicates we returned the effects to a client).
1637                    if let Some(fx_digest) = epoch_store
1638                        .get_signed_effects_digest(tx.digest())
1639                        .expect("db error")
1640                    {
1641                        pending_consensus_certificates.push((tx, fx_digest));
1642                    } else {
1643                        additional_certs.push(tx);
1644                    }
1645                }
1646                _ => (),
1647            }
1648        }
1649
1650        let digests = pending_consensus_certificates
1651            .iter()
1652            .map(|(tx, _)| *tx.digest())
1653            .collect::<Vec<_>>();
1654
1655        info!(
1656            "reexecuting {} pending consensus certificates: {:?}",
1657            digests.len(),
1658            digests
1659        );
1660
1661        state.enqueue_with_expected_effects_digest(pending_consensus_certificates, epoch_store);
1662        state.enqueue_transactions_for_execution(additional_certs, epoch_store);
1663
1664        // If this times out, the validator will still almost certainly start up fine.
1665        // But, it is possible that it may temporarily "forget" about
1666        // transactions that it had previously executed. This could confuse
1667        // clients in some circumstances. However, the transactions are still in
1668        // pending_consensus_certificates, so we cannot lose any finality guarantees.
1669        let timeout = if cfg!(msim) { 120 } else { 60 };
1670        if tokio::time::timeout(
1671            std::time::Duration::from_secs(timeout),
1672            state
1673                .get_transaction_cache_reader()
1674                .try_notify_read_executed_effects_digests(&digests),
1675        )
1676        .await
1677        .is_err()
1678        {
1679            // Log all the digests that were not executed to help debugging.
1680            if let Ok(executed_effects_digests) = state
1681                .get_transaction_cache_reader()
1682                .try_multi_get_executed_effects_digests(&digests)
1683            {
1684                let pending_digests = digests
1685                    .iter()
1686                    .zip(executed_effects_digests.iter())
1687                    .filter_map(|(digest, executed_effects_digest)| {
1688                        if executed_effects_digest.is_none() {
1689                            Some(digest)
1690                        } else {
1691                            None
1692                        }
1693                    })
1694                    .collect::<Vec<_>>();
1695                debug_fatal!(
1696                    "Timed out waiting for effects digests to be executed: {:?}",
1697                    pending_digests
1698                );
1699            } else {
1700                debug_fatal!(
1701                    "Timed out waiting for effects digests to be executed, digests not found"
1702                );
1703            }
1704        }
1705    }
1706
1707    pub fn state(&self) -> Arc<AuthorityState> {
1708        self.state.clone()
1709    }
1710
1711    // Only used for testing because of how epoch store is loaded.
1712    pub fn reference_gas_price_for_testing(&self) -> Result<u64, anyhow::Error> {
1713        self.state.reference_gas_price_for_testing()
1714    }
1715
1716    pub fn clone_committee_store(&self) -> Arc<CommitteeStore> {
1717        self.state.committee_store().clone()
1718    }
1719
1720    // pub fn clone_authority_store(&self) -> Arc<AuthorityStore> {
1721    // self.state.db()
1722    // }
1723
1724    /// Clone an AuthorityAggregator currently used in this node's
1725    /// QuorumDriver, if the node is a fullnode. After reconfig,
1726    /// QuorumDriver builds a new AuthorityAggregator. The caller
1727    /// of this function will mostly likely want to call this again
1728    /// to get a fresh one.
1729    pub fn clone_authority_aggregator(
1730        &self,
1731    ) -> Option<Arc<AuthorityAggregator<NetworkAuthorityClient>>> {
1732        self.transaction_orchestrator
1733            .as_ref()
1734            .map(|to| to.clone_authority_aggregator())
1735    }
1736
1737    pub fn transaction_orchestrator(
1738        &self,
1739    ) -> Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>> {
1740        self.transaction_orchestrator.clone()
1741    }
1742
1743    pub fn subscribe_to_transaction_orchestrator_effects(
1744        &self,
1745    ) -> Result<tokio::sync::broadcast::Receiver<QuorumDriverEffectsQueueResult>> {
1746        self.transaction_orchestrator
1747            .as_ref()
1748            .map(|to| to.subscribe_to_effects_queue())
1749            .ok_or_else(|| anyhow::anyhow!("Transaction Orchestrator is not enabled in this node."))
1750    }
1751
1752    /// This function awaits the completion of checkpoint execution of the
1753    /// current epoch, after which it initiates reconfiguration of the
1754    /// entire system. This function also handles role changes for the node when
1755    /// epoch changes and advertises capabilities to the committee if the node
1756    /// is a validator.
1757    pub async fn monitor_reconfiguration(
1758        self: Arc<Self>,
1759        mut epoch_store: Arc<AuthorityPerEpochStore>,
1760    ) -> Result<()> {
1761        let checkpoint_executor_metrics =
1762            CheckpointExecutorMetrics::new(&self.registry_service.default_registry());
1763
1764        loop {
1765            let mut accumulator_guard = self.accumulator.lock().await;
1766            let accumulator = accumulator_guard.take().unwrap();
1767            info!(
1768                "Creating checkpoint executor for epoch {}",
1769                epoch_store.epoch()
1770            );
1771
1772            // Create closures that handle gRPC type conversion
1773            let data_sender = if let Ok(guard) = self.grpc_server_handle.try_lock() {
1774                guard.as_ref().map(|handle| {
1775                    let tx = handle.checkpoint_data_broadcaster().clone();
1776                    Box::new(move |data: &CheckpointData| {
1777                        tx.send_traced(data);
1778                    }) as Box<dyn Fn(&CheckpointData) + Send + Sync>
1779                })
1780            } else {
1781                None
1782            };
1783
1784            let checkpoint_executor = CheckpointExecutor::new(
1785                epoch_store.clone(),
1786                self.checkpoint_store.clone(),
1787                self.state.clone(),
1788                accumulator.clone(),
1789                self.backpressure_manager.clone(),
1790                self.config.checkpoint_executor_config.clone(),
1791                checkpoint_executor_metrics.clone(),
1792                data_sender,
1793            );
1794
1795            let run_with_range = self.config.run_with_range;
1796
1797            let cur_epoch_store = self.state.load_epoch_store_one_call_per_task();
1798
1799            // Advertise capabilities to committee, if we are a validator.
1800            if let Some(components) = &*self.validator_components.lock().await {
1801                // TODO: without this sleep, the consensus message is not delivered reliably.
1802                tokio::time::sleep(Duration::from_millis(1)).await;
1803
1804                let config = cur_epoch_store.protocol_config();
1805                let binary_config = to_binary_config(config);
1806                let transaction = ConsensusTransaction::new_capability_notification_v1(
1807                    AuthorityCapabilitiesV1::new(
1808                        self.state.name,
1809                        cur_epoch_store.get_chain_identifier().chain(),
1810                        self.config
1811                            .supported_protocol_versions
1812                            .expect("Supported versions should be populated")
1813                            // no need to send digests of versions less than the current version
1814                            .truncate_below(config.version),
1815                        self.state
1816                            .get_available_system_packages(&binary_config)
1817                            .await,
1818                    ),
1819                );
1820                info!(?transaction, "submitting capabilities to consensus");
1821                components
1822                    .consensus_adapter
1823                    .submit(transaction, None, &cur_epoch_store)?;
1824            } else if self.state.is_active_validator(&cur_epoch_store)
1825                && cur_epoch_store
1826                    .protocol_config()
1827                    .track_non_committee_eligible_validators()
1828            {
1829                // Send signed capabilities to committee validators if we are a non-committee
1830                // validator in a separate task to not block the caller. Sending is done only if
1831                // the feature flag supporting it is enabled.
1832                let epoch_store = cur_epoch_store.clone();
1833                let node_clone = self.clone();
1834                spawn_monitored_task!(epoch_store.clone().within_alive_epoch(async move {
1835                    node_clone
1836                        .send_signed_capability_notification_to_committee_with_retry(&epoch_store)
1837                        .await;
1838                }));
1839            }
1840
1841            let stop_condition = checkpoint_executor.run_epoch(run_with_range).await;
1842
1843            if stop_condition == StopReason::RunWithRangeCondition {
1844                IotaNode::shutdown(&self).await;
1845                self.shutdown_channel_tx
1846                    .send(run_with_range)
1847                    .expect("RunWithRangeCondition met but failed to send shutdown message");
1848                return Ok(());
1849            }
1850
1851            // Safe to call because we are in the middle of reconfiguration.
1852            let latest_system_state = self
1853                .state
1854                .get_object_cache_reader()
1855                .try_get_iota_system_state_object_unsafe()
1856                .expect("Read IOTA System State object cannot fail");
1857
1858            #[cfg(msim)]
1859            if !self
1860                .sim_state
1861                .sim_safe_mode_expected
1862                .load(Ordering::Relaxed)
1863            {
1864                debug_assert!(!latest_system_state.safe_mode());
1865            }
1866
1867            #[cfg(not(msim))]
1868            debug_assert!(!latest_system_state.safe_mode());
1869
1870            if let Err(err) = self.end_of_epoch_channel.send(latest_system_state.clone()) {
1871                if self.state.is_fullnode(&cur_epoch_store) {
1872                    warn!(
1873                        "Failed to send end of epoch notification to subscriber: {:?}",
1874                        err
1875                    );
1876                }
1877            }
1878
1879            cur_epoch_store.record_is_safe_mode_metric(latest_system_state.safe_mode());
1880            let new_epoch_start_state = latest_system_state.into_epoch_start_state();
1881
1882            self.auth_agg.store(Arc::new(
1883                self.auth_agg
1884                    .load()
1885                    .recreate_with_new_epoch_start_state(&new_epoch_start_state),
1886            ));
1887
1888            let next_epoch_committee = new_epoch_start_state.get_iota_committee();
1889            let next_epoch = next_epoch_committee.epoch();
1890            assert_eq!(cur_epoch_store.epoch() + 1, next_epoch);
1891
1892            info!(
1893                next_epoch,
1894                "Finished executing all checkpoints in epoch. About to reconfigure the system."
1895            );
1896
1897            fail_point_async!("reconfig_delay");
1898
1899            // We save the connection monitor status map regardless of validator / fullnode
1900            // status so that we don't need to restart the connection monitor
1901            // every epoch. Update the mappings that will be used by the
1902            // consensus adapter if it exists or is about to be created.
1903            let authority_names_to_peer_ids =
1904                new_epoch_start_state.get_authority_names_to_peer_ids();
1905            self.connection_monitor_status
1906                .update_mapping_for_epoch(authority_names_to_peer_ids);
1907
1908            cur_epoch_store.record_epoch_reconfig_start_time_metric();
1909
1910            send_trusted_peer_change(
1911                &self.config,
1912                &self.trusted_peer_change_tx,
1913                &new_epoch_start_state,
1914            );
1915
1916            let mut validator_components_lock_guard = self.validator_components.lock().await;
1917
1918            // The following code handles 4 different cases, depending on whether the node
1919            // was a validator in the previous epoch, and whether the node is a validator
1920            // in the new epoch.
1921            let new_epoch_store = self
1922                .reconfigure_state(
1923                    &self.state,
1924                    &cur_epoch_store,
1925                    next_epoch_committee.clone(),
1926                    new_epoch_start_state,
1927                    accumulator.clone(),
1928                )
1929                .await?;
1930
1931            let new_validator_components = if let Some(ValidatorComponents {
1932                validator_server_handle,
1933                validator_overload_monitor_handle,
1934                consensus_manager,
1935                consensus_store_pruner,
1936                consensus_adapter,
1937                mut checkpoint_service_tasks,
1938                checkpoint_metrics,
1939                iota_tx_validator_metrics,
1940                validator_registry_id,
1941            }) = validator_components_lock_guard.take()
1942            {
1943                info!("Reconfiguring the validator.");
1944                // Cancel the old checkpoint service tasks.
1945                // Waiting for checkpoint builder to finish gracefully is not possible, because
1946                // it may wait on transactions while consensus on peers have
1947                // already shut down.
1948                checkpoint_service_tasks.abort_all();
1949                while let Some(result) = checkpoint_service_tasks.join_next().await {
1950                    if let Err(err) = result {
1951                        if err.is_panic() {
1952                            std::panic::resume_unwind(err.into_panic());
1953                        }
1954                        warn!("Error in checkpoint service task: {:?}", err);
1955                    }
1956                }
1957                info!("Checkpoint service has shut down.");
1958
1959                consensus_manager.shutdown().await;
1960                info!("Consensus has shut down.");
1961
1962                info!("Epoch store finished reconfiguration.");
1963
1964                // No other components should be holding a strong reference to state accumulator
1965                // at this point. Confirm here before we swap in the new accumulator.
1966                let accumulator_metrics = Arc::into_inner(accumulator)
1967                    .expect("Accumulator should have no other references at this point")
1968                    .metrics();
1969                let new_accumulator = Arc::new(StateAccumulator::new(
1970                    self.state.get_accumulator_store().clone(),
1971                    accumulator_metrics,
1972                ));
1973                let weak_accumulator = Arc::downgrade(&new_accumulator);
1974                *accumulator_guard = Some(new_accumulator);
1975
1976                consensus_store_pruner.prune(next_epoch).await;
1977
1978                if self.state.is_committee_validator(&new_epoch_store) {
1979                    // Only restart consensus if this node is still a validator in the new epoch.
1980                    Some(
1981                        Self::start_epoch_specific_validator_components(
1982                            &self.config,
1983                            self.state.clone(),
1984                            consensus_adapter,
1985                            self.checkpoint_store.clone(),
1986                            new_epoch_store.clone(),
1987                            self.state_sync_handle.clone(),
1988                            self.randomness_handle.clone(),
1989                            consensus_manager,
1990                            consensus_store_pruner,
1991                            weak_accumulator,
1992                            self.backpressure_manager.clone(),
1993                            validator_server_handle,
1994                            validator_overload_monitor_handle,
1995                            checkpoint_metrics,
1996                            self.metrics.clone(),
1997                            iota_tx_validator_metrics,
1998                            validator_registry_id,
1999                        )
2000                        .await?,
2001                    )
2002                } else {
2003                    info!("This node is no longer a validator after reconfiguration");
2004                    if self.registry_service.remove(validator_registry_id) {
2005                        debug!("Removed validator metrics registry");
2006                    } else {
2007                        warn!("Failed to remove validator metrics registry");
2008                    }
2009                    validator_server_handle.shutdown();
2010                    debug!("Validator grpc server shutdown triggered");
2011
2012                    None
2013                }
2014            } else {
2015                // No other components should be holding a strong reference to state accumulator
2016                // at this point. Confirm here before we swap in the new accumulator.
2017                let accumulator_metrics = Arc::into_inner(accumulator)
2018                    .expect("Accumulator should have no other references at this point")
2019                    .metrics();
2020                let new_accumulator = Arc::new(StateAccumulator::new(
2021                    self.state.get_accumulator_store().clone(),
2022                    accumulator_metrics,
2023                ));
2024                let weak_accumulator = Arc::downgrade(&new_accumulator);
2025                *accumulator_guard = Some(new_accumulator);
2026
2027                if self.state.is_committee_validator(&new_epoch_store) {
2028                    info!("Promoting the node from fullnode to validator, starting grpc server");
2029
2030                    let mut components = Self::construct_validator_components(
2031                        self.config.clone(),
2032                        self.state.clone(),
2033                        Arc::new(next_epoch_committee.clone()),
2034                        new_epoch_store.clone(),
2035                        self.checkpoint_store.clone(),
2036                        self.state_sync_handle.clone(),
2037                        self.randomness_handle.clone(),
2038                        weak_accumulator,
2039                        self.backpressure_manager.clone(),
2040                        self.connection_monitor_status.clone(),
2041                        &self.registry_service,
2042                        self.metrics.clone(),
2043                    )
2044                    .await?;
2045
2046                    components.validator_server_handle =
2047                        components.validator_server_handle.start().await;
2048
2049                    Some(components)
2050                } else {
2051                    None
2052                }
2053            };
2054            *validator_components_lock_guard = new_validator_components;
2055
2056            // Force releasing current epoch store DB handle, because the
2057            // Arc<AuthorityPerEpochStore> may linger.
2058            cur_epoch_store.release_db_handles();
2059
2060            if cfg!(msim)
2061                && !matches!(
2062                    self.config
2063                        .authority_store_pruning_config
2064                        .num_epochs_to_retain_for_checkpoints(),
2065                    None | Some(u64::MAX) | Some(0)
2066                )
2067            {
2068                self.state
2069                .prune_checkpoints_for_eligible_epochs_for_testing(
2070                    self.config.clone(),
2071                    iota_core::authority::authority_store_pruner::AuthorityStorePruningMetrics::new_for_test(),
2072                )
2073                .await?;
2074            }
2075
2076            epoch_store = new_epoch_store;
2077            info!("Reconfiguration finished");
2078        }
2079    }
2080
2081    async fn shutdown(&self) {
2082        if let Some(validator_components) = &*self.validator_components.lock().await {
2083            validator_components.consensus_manager.shutdown().await;
2084        }
2085
2086        // Shutdown the gRPC server if it's running
2087        if let Some(grpc_handle) = self.grpc_server_handle.lock().await.take() {
2088            info!("Shutting down gRPC server");
2089            if let Err(e) = grpc_handle.shutdown().await {
2090                warn!("Failed to gracefully shutdown gRPC server: {e}");
2091            }
2092        }
2093    }
2094
2095    /// Asynchronously reconfigures the state of the authority node for the next
2096    /// epoch.
2097    async fn reconfigure_state(
2098        &self,
2099        state: &Arc<AuthorityState>,
2100        cur_epoch_store: &AuthorityPerEpochStore,
2101        next_epoch_committee: Committee,
2102        next_epoch_start_system_state: EpochStartSystemState,
2103        accumulator: Arc<StateAccumulator>,
2104    ) -> IotaResult<Arc<AuthorityPerEpochStore>> {
2105        let next_epoch = next_epoch_committee.epoch();
2106
2107        let last_checkpoint = self
2108            .checkpoint_store
2109            .get_epoch_last_checkpoint(cur_epoch_store.epoch())
2110            .expect("Error loading last checkpoint for current epoch")
2111            .expect("Could not load last checkpoint for current epoch");
2112        let epoch_supply_change = last_checkpoint
2113            .end_of_epoch_data
2114            .as_ref()
2115            .ok_or_else(|| {
2116                IotaError::from("last checkpoint in epoch should contain end of epoch data")
2117            })?
2118            .epoch_supply_change;
2119
2120        let last_checkpoint_seq = *last_checkpoint.sequence_number();
2121
2122        assert_eq!(
2123            Some(last_checkpoint_seq),
2124            self.checkpoint_store
2125                .get_highest_executed_checkpoint_seq_number()
2126                .expect("Error loading highest executed checkpoint sequence number")
2127        );
2128
2129        let epoch_start_configuration = EpochStartConfiguration::new(
2130            next_epoch_start_system_state,
2131            *last_checkpoint.digest(),
2132            state.get_object_store().as_ref(),
2133            EpochFlag::default_flags_for_new_epoch(&state.config),
2134        )
2135        .expect("EpochStartConfiguration construction cannot fail");
2136
2137        let new_epoch_store = self
2138            .state
2139            .reconfigure(
2140                cur_epoch_store,
2141                self.config.supported_protocol_versions.unwrap(),
2142                next_epoch_committee,
2143                epoch_start_configuration,
2144                accumulator,
2145                &self.config.expensive_safety_check_config,
2146                epoch_supply_change,
2147                last_checkpoint_seq,
2148            )
2149            .await
2150            .expect("Reconfigure authority state cannot fail");
2151        info!(next_epoch, "Node State has been reconfigured");
2152        assert_eq!(next_epoch, new_epoch_store.epoch());
2153        self.state.get_reconfig_api().update_epoch_flags_metrics(
2154            cur_epoch_store.epoch_start_config().flags(),
2155            new_epoch_store.epoch_start_config().flags(),
2156        );
2157
2158        Ok(new_epoch_store)
2159    }
2160
2161    pub fn get_config(&self) -> &NodeConfig {
2162        &self.config
2163    }
2164
2165    async fn execute_transaction_immediately_at_zero_epoch(
2166        state: &Arc<AuthorityState>,
2167        epoch_store: &Arc<AuthorityPerEpochStore>,
2168        tx: &Transaction,
2169        span: tracing::Span,
2170    ) {
2171        let _guard = span.enter();
2172        let transaction =
2173            iota_types::executable_transaction::VerifiedExecutableTransaction::new_unchecked(
2174                iota_types::executable_transaction::ExecutableTransaction::new_from_data_and_sig(
2175                    tx.data().clone(),
2176                    iota_types::executable_transaction::CertificateProof::Checkpoint(0, 0),
2177                ),
2178            );
2179        state
2180            .try_execute_immediately(&transaction, None, epoch_store)
2181            .unwrap();
2182    }
2183
2184    pub fn randomness_handle(&self) -> randomness::Handle {
2185        self.randomness_handle.clone()
2186    }
2187
2188    /// Sends signed capability notification to committee validators for
2189    /// non-committee validators. This method implements retry logic to handle
2190    /// failed attempts to send the notification. It will retry sending the
2191    /// notification with an increasing interval until it receives a successful
2192    /// response from a f+1 committee members or 2f+1 non-retryable errors.
2193    async fn send_signed_capability_notification_to_committee_with_retry(
2194        &self,
2195        epoch_store: &Arc<AuthorityPerEpochStore>,
2196    ) {
2197        const INITIAL_RETRY_INTERVAL_SECS: u64 = 5;
2198        const RETRY_INTERVAL_INCREMENT_SECS: u64 = 5;
2199        const MAX_RETRY_INTERVAL_SECS: u64 = 300; // 5 minutes
2200
2201        // Create the capability notification once
2202        let config = epoch_store.protocol_config();
2203        let binary_config = to_binary_config(config);
2204
2205        // Create the capability notification
2206        let capabilities = AuthorityCapabilitiesV1::new(
2207            self.state.name,
2208            epoch_store.get_chain_identifier().chain(),
2209            self.config
2210                .supported_protocol_versions
2211                .expect("Supported versions should be populated")
2212                .truncate_below(config.version),
2213            self.state
2214                .get_available_system_packages(&binary_config)
2215                .await,
2216        );
2217
2218        // Sign the capabilities using the authority key pair from config
2219        let signature = AuthoritySignature::new_secure(
2220            &IntentMessage::new(
2221                Intent::iota_app(IntentScope::AuthorityCapabilities),
2222                &capabilities,
2223            ),
2224            &epoch_store.epoch(),
2225            self.config.authority_key_pair(),
2226        );
2227
2228        let request = HandleCapabilityNotificationRequestV1 {
2229            message: SignedAuthorityCapabilitiesV1::new_from_data_and_sig(capabilities, signature),
2230        };
2231
2232        let mut retry_interval = Duration::from_secs(INITIAL_RETRY_INTERVAL_SECS);
2233
2234        loop {
2235            let auth_agg = self.auth_agg.load();
2236            match auth_agg
2237                .send_capability_notification_to_quorum(request.clone())
2238                .await
2239            {
2240                Ok(_) => {
2241                    info!("Successfully sent capability notification to committee");
2242                    break;
2243                }
2244                Err(err) => {
2245                    match &err {
2246                        AggregatorSendCapabilityNotificationError::RetryableNotification {
2247                            errors,
2248                        } => {
2249                            warn!(
2250                                "Failed to send capability notification to committee (retryable error), will retry in {:?}: {:?}",
2251                                retry_interval, errors
2252                            );
2253                        }
2254                        AggregatorSendCapabilityNotificationError::NonRetryableNotification {
2255                            errors,
2256                        } => {
2257                            error!(
2258                                "Failed to send capability notification to committee (non-retryable error): {:?}",
2259                                errors
2260                            );
2261                            break;
2262                        }
2263                    };
2264
2265                    // Wait before retrying
2266                    tokio::time::sleep(retry_interval).await;
2267
2268                    // Increase retry interval for the next attempt, capped at max
2269                    retry_interval = std::cmp::min(
2270                        retry_interval + Duration::from_secs(RETRY_INTERVAL_INCREMENT_SECS),
2271                        Duration::from_secs(MAX_RETRY_INTERVAL_SECS),
2272                    );
2273                }
2274            }
2275        }
2276    }
2277}
2278
2279#[cfg(not(msim))]
2280impl IotaNode {
2281    async fn fetch_jwks(
2282        _authority: AuthorityName,
2283        provider: &OIDCProvider,
2284    ) -> IotaResult<Vec<(JwkId, JWK)>> {
2285        use fastcrypto_zkp::bn254::zk_login::fetch_jwks;
2286        let client = reqwest::Client::new();
2287        fetch_jwks(provider, &client)
2288            .await
2289            .map_err(|_| IotaError::JWKRetrieval)
2290    }
2291}
2292
2293#[cfg(msim)]
2294impl IotaNode {
2295    pub fn get_sim_node_id(&self) -> iota_simulator::task::NodeId {
2296        self.sim_state.sim_node.id()
2297    }
2298
2299    pub fn set_safe_mode_expected(&self, new_value: bool) {
2300        info!("Setting safe mode expected to {}", new_value);
2301        self.sim_state
2302            .sim_safe_mode_expected
2303            .store(new_value, Ordering::Relaxed);
2304    }
2305
2306    async fn fetch_jwks(
2307        authority: AuthorityName,
2308        provider: &OIDCProvider,
2309    ) -> IotaResult<Vec<(JwkId, JWK)>> {
2310        get_jwk_injector()(authority, provider)
2311    }
2312}
2313
2314enum SpawnOnce {
2315    // Mutex is only needed to make SpawnOnce Sync
2316    Unstarted(Mutex<BoxFuture<'static, Result<iota_network_stack::server::Server>>>),
2317    #[allow(unused)]
2318    Started(iota_http::ServerHandle),
2319}
2320
2321impl SpawnOnce {
2322    pub fn new(
2323        future: impl Future<Output = Result<iota_network_stack::server::Server>> + Send + 'static,
2324    ) -> Self {
2325        Self::Unstarted(Mutex::new(Box::pin(future)))
2326    }
2327
2328    pub async fn start(self) -> Self {
2329        match self {
2330            Self::Unstarted(future) => {
2331                let server = future
2332                    .into_inner()
2333                    .await
2334                    .unwrap_or_else(|err| panic!("Failed to start validator gRPC server: {err}"));
2335                let handle = server.handle().clone();
2336                tokio::spawn(async move {
2337                    if let Err(err) = server.serve().await {
2338                        info!("Server stopped: {err}");
2339                    }
2340                    info!("Server stopped");
2341                });
2342                Self::Started(handle)
2343            }
2344            Self::Started(_) => self,
2345        }
2346    }
2347
2348    pub fn shutdown(self) {
2349        if let SpawnOnce::Started(handle) = self {
2350            handle.trigger_shutdown();
2351        }
2352    }
2353}
2354
2355/// Notify [`DiscoveryEventLoop`] that a new list of trusted peers are now
2356/// available.
2357fn send_trusted_peer_change(
2358    config: &NodeConfig,
2359    sender: &watch::Sender<TrustedPeerChangeEvent>,
2360    new_epoch_start_state: &EpochStartSystemState,
2361) {
2362    let new_committee =
2363        new_epoch_start_state.get_validator_as_p2p_peers(config.authority_public_key());
2364
2365    sender.send_modify(|event| {
2366        core::mem::swap(&mut event.new_committee, &mut event.old_committee);
2367        event.new_committee = new_committee;
2368    })
2369}
2370
2371fn build_kv_store(
2372    state: &Arc<AuthorityState>,
2373    config: &NodeConfig,
2374    registry: &Registry,
2375) -> Result<Arc<TransactionKeyValueStore>> {
2376    let metrics = KeyValueStoreMetrics::new(registry);
2377    let db_store = TransactionKeyValueStore::new("rocksdb", metrics.clone(), state.clone());
2378
2379    let base_url = &config.transaction_kv_store_read_config.base_url;
2380
2381    if base_url.is_empty() {
2382        info!("no http kv store url provided, using local db only");
2383        return Ok(Arc::new(db_store));
2384    }
2385
2386    base_url.parse::<url::Url>().tap_err(|e| {
2387        error!(
2388            "failed to parse config.transaction_kv_store_config.base_url ({:?}) as url: {}",
2389            base_url, e
2390        )
2391    })?;
2392
2393    let http_store = HttpKVStore::new_kv(
2394        base_url,
2395        config.transaction_kv_store_read_config.cache_size,
2396        metrics.clone(),
2397    )?;
2398    info!("using local key-value store with fallback to http key-value store");
2399    Ok(Arc::new(FallbackTransactionKVStore::new_kv(
2400        db_store,
2401        http_store,
2402        metrics,
2403        "json_rpc_fallback",
2404    )))
2405}
2406
2407/// Builds and starts the gRPC server for the IOTA node based on the node's
2408/// configuration.
2409///
2410/// This function performs the following tasks:
2411/// 1. Checks if the node is a validator by inspecting the consensus
2412///    configuration; if so, it returns early as validators do not expose gRPC
2413///    APIs.
2414/// 2. Checks if gRPC is enabled in the configuration.
2415/// 3. Creates broadcast channels for checkpoint streaming.
2416/// 4. Initializes the gRPC checkpoint service.
2417/// 5. Spawns the gRPC server to listen for incoming connections.
2418///
2419/// Returns a tuple of optional broadcast channels for checkpoint summary and
2420/// data.
2421async fn build_grpc_server(
2422    config: &NodeConfig,
2423    state: Arc<AuthorityState>,
2424    state_sync_store: RocksDbStore,
2425    executor: Option<Arc<dyn iota_types::transaction_executor::TransactionExecutor>>,
2426) -> Result<Option<GrpcServerHandle>> {
2427    // Validators do not expose gRPC APIs
2428    if config.consensus_config().is_some() || !config.enable_grpc_api {
2429        return Ok(None);
2430    }
2431
2432    let Some(grpc_config) = &config.grpc_api_config else {
2433        return Err(anyhow!("gRPC API is enabled but no configuration provided"));
2434    };
2435
2436    // Get chain identifier from state directly
2437    let chain_id = state.get_chain_identifier();
2438
2439    let rest_read_store = Arc::new(RestReadStore::new(state.clone(), state_sync_store));
2440
2441    // Create cancellation token for proper shutdown hierarchy
2442    let shutdown_token = CancellationToken::new();
2443
2444    // Create GrpcReader
2445    let grpc_reader = Arc::new(GrpcReader::from_rest_state_reader(
2446        rest_read_store,
2447        Some(env!("CARGO_PKG_VERSION").to_string()),
2448    ));
2449
2450    // Pass the same token to both GrpcReader (already done above) and
2451    // start_grpc_server
2452    let handle = start_grpc_server(
2453        grpc_reader,
2454        executor,
2455        grpc_config.clone(),
2456        shutdown_token,
2457        chain_id,
2458    )
2459    .await?;
2460
2461    Ok(Some(handle))
2462}
2463
2464/// Builds and starts the HTTP server for the IOTA node, exposing JSON-RPC and
2465/// REST APIs based on the node's configuration.
2466///
2467/// This function performs the following tasks:
2468/// 1. Checks if the node is a validator by inspecting the consensus
2469///    configuration; if so, it returns early as validators do not expose these
2470///    APIs.
2471/// 2. Creates an Axum router to handle HTTP requests.
2472/// 3. Initializes the JSON-RPC server and registers various RPC modules based
2473///    on the node's state and configuration, including CoinApi,
2474///    TransactionBuilderApi, GovernanceApi, TransactionExecutionApi, and
2475///    IndexerApi.
2476/// 4. Optionally, if the REST API is enabled, nests the REST API router under
2477///    the `/api/v1` path.
2478/// 5. Binds the server to the specified JSON-RPC address and starts listening
2479///    for incoming connections.
2480pub async fn build_http_server(
2481    state: Arc<AuthorityState>,
2482    store: RocksDbStore,
2483    transaction_orchestrator: &Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>>,
2484    config: &NodeConfig,
2485    prometheus_registry: &Registry,
2486    _custom_runtime: Option<Handle>,
2487    software_version: &'static str,
2488) -> Result<Option<iota_http::ServerHandle>> {
2489    // Validators do not expose these APIs
2490    if config.consensus_config().is_some() {
2491        return Ok(None);
2492    }
2493
2494    let mut router = axum::Router::new();
2495
2496    let json_rpc_router = {
2497        let mut server = JsonRpcServerBuilder::new(
2498            env!("CARGO_PKG_VERSION"),
2499            prometheus_registry,
2500            config.policy_config.clone(),
2501            config.firewall_config.clone(),
2502        );
2503
2504        let kv_store = build_kv_store(&state, config, prometheus_registry)?;
2505
2506        let metrics = Arc::new(JsonRpcMetrics::new(prometheus_registry));
2507        server.register_module(ReadApi::new(
2508            state.clone(),
2509            kv_store.clone(),
2510            metrics.clone(),
2511        ))?;
2512        server.register_module(CoinReadApi::new(
2513            state.clone(),
2514            kv_store.clone(),
2515            metrics.clone(),
2516        )?)?;
2517
2518        // if run_with_range is enabled we want to prevent any transactions
2519        // run_with_range = None is normal operating conditions
2520        if config.run_with_range.is_none() {
2521            server.register_module(TransactionBuilderApi::new(state.clone()))?;
2522        }
2523        server.register_module(GovernanceReadApi::new(state.clone(), metrics.clone()))?;
2524
2525        if let Some(transaction_orchestrator) = transaction_orchestrator {
2526            server.register_module(TransactionExecutionApi::new(
2527                state.clone(),
2528                transaction_orchestrator.clone(),
2529                metrics.clone(),
2530            ))?;
2531        }
2532
2533        let iota_names_config = config
2534            .iota_names_config
2535            .clone()
2536            .unwrap_or_else(|| IotaNamesConfig::from_chain(&state.get_chain_identifier().chain()));
2537
2538        server.register_module(IndexerApi::new(
2539            state.clone(),
2540            ReadApi::new(state.clone(), kv_store.clone(), metrics.clone()),
2541            kv_store,
2542            metrics,
2543            iota_names_config,
2544            config.indexer_max_subscriptions,
2545        ))?;
2546        server.register_module(MoveUtils::new(state.clone()))?;
2547
2548        let server_type = config.jsonrpc_server_type();
2549
2550        server.to_router(server_type).await?
2551    };
2552
2553    router = router.merge(json_rpc_router);
2554
2555    if config.enable_rest_api {
2556        let mut rest_service = iota_rest_api::RestService::new(
2557            Arc::new(RestReadStore::new(state.clone(), store)),
2558            software_version,
2559        );
2560
2561        if let Some(config) = config.rest.clone() {
2562            rest_service.with_config(config);
2563        }
2564
2565        rest_service.with_metrics(RestMetrics::new(prometheus_registry));
2566
2567        if let Some(transaction_orchestrator) = transaction_orchestrator {
2568            rest_service.with_executor(transaction_orchestrator.clone())
2569        }
2570
2571        router = router.merge(rest_service.into_router());
2572    }
2573
2574    // TODO: Remove this health check when experimental REST API becomes default
2575    // This is a copy of the health check in crates/iota-rest-api/src/health.rs
2576    router = router
2577        .route("/health", axum::routing::get(health_check_handler))
2578        .route_layer(axum::Extension(state));
2579
2580    let layers = ServiceBuilder::new()
2581        .map_request(|mut request: axum::http::Request<_>| {
2582            if let Some(connect_info) = request.extensions().get::<iota_http::ConnectInfo>() {
2583                let axum_connect_info = axum::extract::ConnectInfo(connect_info.remote_addr);
2584                request.extensions_mut().insert(axum_connect_info);
2585            }
2586            request
2587        })
2588        .layer(axum::middleware::from_fn(server_timing_middleware));
2589
2590    router = router.layer(layers);
2591
2592    let handle = iota_http::Builder::new()
2593        .serve(&config.json_rpc_address, router)
2594        .map_err(|e| anyhow::anyhow!("{e}"))?;
2595    info!(local_addr =? handle.local_addr(), "IOTA JSON-RPC server listening on {}", handle.local_addr());
2596
2597    Ok(Some(handle))
2598}
2599
2600#[derive(Debug, serde::Serialize, serde::Deserialize)]
2601pub struct Threshold {
2602    pub threshold_seconds: Option<u32>,
2603}
2604
2605async fn health_check_handler(
2606    axum::extract::Query(Threshold { threshold_seconds }): axum::extract::Query<Threshold>,
2607    axum::Extension(state): axum::Extension<Arc<AuthorityState>>,
2608) -> impl axum::response::IntoResponse {
2609    if let Some(threshold_seconds) = threshold_seconds {
2610        // Attempt to get the latest checkpoint
2611        let summary = match state
2612            .get_checkpoint_store()
2613            .get_highest_executed_checkpoint()
2614        {
2615            Ok(Some(summary)) => summary,
2616            Ok(None) => {
2617                warn!("Highest executed checkpoint not found");
2618                return (axum::http::StatusCode::SERVICE_UNAVAILABLE, "down");
2619            }
2620            Err(err) => {
2621                warn!("Failed to retrieve highest executed checkpoint: {:?}", err);
2622                return (axum::http::StatusCode::SERVICE_UNAVAILABLE, "down");
2623            }
2624        };
2625
2626        // Calculate the threshold time based on the provided threshold_seconds
2627        let latest_chain_time = summary.timestamp();
2628        let threshold =
2629            std::time::SystemTime::now() - Duration::from_secs(threshold_seconds as u64);
2630
2631        // Check if the latest checkpoint is within the threshold
2632        if latest_chain_time < threshold {
2633            warn!(
2634                ?latest_chain_time,
2635                ?threshold,
2636                "failing health check due to checkpoint lag"
2637            );
2638            return (axum::http::StatusCode::SERVICE_UNAVAILABLE, "down");
2639        }
2640    }
2641    // if health endpoint is responding and no threshold is given, respond success
2642    (axum::http::StatusCode::OK, "up")
2643}
2644
2645#[cfg(not(test))]
2646fn max_tx_per_checkpoint(protocol_config: &ProtocolConfig) -> usize {
2647    protocol_config.max_transactions_per_checkpoint() as usize
2648}
2649
2650#[cfg(test)]
2651fn max_tx_per_checkpoint(_: &ProtocolConfig) -> usize {
2652    2
2653}