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