Skip to main content

sui_node/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use anemo::Network;
5use anemo::PeerId;
6use anemo_tower::callback::CallbackLayer;
7use anemo_tower::trace::DefaultMakeSpan;
8use anemo_tower::trace::DefaultOnFailure;
9use anemo_tower::trace::TraceLayer;
10use anyhow::Context;
11use anyhow::Result;
12use anyhow::anyhow;
13use arc_swap::ArcSwap;
14use fastcrypto_zkp::bn254::zk_login::JwkId;
15use fastcrypto_zkp::bn254::zk_login::OIDCProvider;
16use futures::future::BoxFuture;
17use mysten_common::in_test_configuration;
18use prometheus::Registry;
19use std::collections::{BTreeSet, HashMap, HashSet};
20use std::fmt;
21use std::future::Future;
22use std::path::Path;
23use std::path::PathBuf;
24use std::str::FromStr;
25#[cfg(msim)]
26use std::sync::atomic::Ordering;
27use std::sync::{Arc, Weak};
28use std::time::Duration;
29use sui_core::admission_queue::{
30    AdmissionQueueContext, AdmissionQueueManager, AdmissionQueueMetrics,
31};
32use sui_core::authority::ExecutionEnv;
33use sui_core::authority::authority_store_tables::AuthorityPerpetualTablesOptions;
34use sui_core::authority::backpressure::BackpressureManager;
35use sui_core::authority::epoch_start_configuration::EpochFlag;
36use sui_core::authority::execution_time_estimator::ExecutionTimeObserver;
37use sui_core::consensus_adapter::ConsensusClient;
38use sui_core::consensus_manager::UpdatableConsensusClient;
39use sui_core::epoch::randomness::RandomnessManager;
40use sui_core::execution_cache::build_execution_cache;
41use sui_core::randomness_round_receiver::{RandomnessRoundReceiver, RandomnessRoundReceiverHandle};
42use sui_network::endpoint_manager::{AddressSource, EndpointId};
43use sui_network::validator::server::SUI_TLS_SERVER_NAME;
44use sui_types::full_checkpoint_content::Checkpoint;
45use sui_types::node_role::NodeRole;
46
47use sui_core::global_state_hasher::GlobalStateHashMetrics;
48use sui_core::storage::RestReadStore;
49use sui_json_rpc::bridge_api::BridgeReadApi;
50use sui_json_rpc_api::JsonRpcMetrics;
51use sui_network::randomness;
52use sui_rpc_api::RpcMetrics;
53use sui_rpc_api::ServerVersion;
54use sui_rpc_api::subscription::SubscriptionService;
55use sui_types::base_types::ConciseableName;
56use sui_types::crypto::RandomnessRound;
57use sui_types::digests::{
58    ChainIdentifier, CheckpointDigest, TransactionDigest, TransactionEffectsDigest,
59};
60use sui_types::messages_consensus::AuthorityCapabilitiesV2;
61use sui_types::sui_system_state::SuiSystemState;
62use tap::tap::TapFallible;
63use tokio::sync::oneshot;
64use tokio::sync::{Mutex, broadcast, mpsc};
65use tokio::task::JoinHandle;
66use tower::ServiceBuilder;
67use tracing::{Instrument, error_span, info};
68use tracing::{debug, error, warn};
69
70// Logs at debug level in test configuration, info level otherwise.
71// JWK logs cause significant volume in tests, but are insignificant in prod,
72// so we keep them at info
73macro_rules! jwk_log {
74    ($($arg:tt)+) => {
75        if in_test_configuration() {
76            debug!($($arg)+);
77        } else {
78            info!($($arg)+);
79        }
80    };
81}
82
83use fastcrypto_zkp::bn254::zk_login::JWK;
84pub use handle::SuiNodeHandle;
85use mysten_metrics::{RegistryService, spawn_monitored_task};
86use mysten_service::server_timing::server_timing_middleware;
87use sui_config::node::{DBCheckpointConfig, RunWithRange};
88use sui_config::node::{ForkCrashBehavior, ForkRecoveryConfig};
89use sui_config::node_config_metrics::NodeConfigMetrics;
90use sui_config::{ConsensusConfig, NodeConfig};
91use sui_core::authority::authority_per_epoch_store::AuthorityPerEpochStore;
92use sui_core::authority::authority_store_tables::AuthorityPerpetualTables;
93use sui_core::authority::epoch_start_configuration::EpochStartConfigTrait;
94use sui_core::authority::epoch_start_configuration::EpochStartConfiguration;
95use sui_core::authority::submitted_transaction_cache::SubmittedTransactionCacheMetrics;
96use sui_core::authority_aggregator::AuthorityAggregator;
97use sui_core::authority_server::{ValidatorService, ValidatorServiceMetrics};
98use sui_core::checkpoints::checkpoint_executor::metrics::CheckpointExecutorMetrics;
99use sui_core::checkpoints::checkpoint_executor::{CheckpointExecutor, StopReason};
100use sui_core::checkpoints::{
101    CheckpointMetrics, CheckpointOutput, CheckpointService, CheckpointStore, LogCheckpointOutput,
102    SendCheckpointToStateSync, SubmitCheckpointToConsensus,
103};
104use sui_core::consensus_adapter::{ConsensusAdapter, ConsensusAdapterMetrics};
105use sui_core::consensus_manager::ConsensusManager;
106use sui_core::consensus_throughput_calculator::ConsensusThroughputCalculator;
107use sui_core::consensus_validator::{SuiTxValidator, SuiTxValidatorMetrics};
108use sui_core::db_checkpoint_handler::DBCheckpointHandler;
109use sui_core::epoch::committee_store::CommitteeStore;
110use sui_core::epoch::consensus_store_pruner::ConsensusStorePruner;
111use sui_core::epoch::epoch_metrics::EpochMetrics;
112use sui_core::epoch::reconfiguration::ReconfigurationInitiator;
113use sui_core::global_state_hasher::GlobalStateHasher;
114use sui_core::jsonrpc_index::IndexStore;
115use sui_core::module_cache_metrics::ResolverMetrics;
116use sui_core::overload_monitor::overload_monitor;
117use sui_core::rpc_store_embed::EmbeddedRpcStore;
118use sui_core::signature_verifier::SignatureVerifierMetrics;
119use sui_core::storage::RocksDbStore;
120use sui_core::storage::RpcStoreReadStore;
121use sui_core::transaction_orchestrator::TransactionOrchestrator;
122use sui_core::{
123    authority::{AuthorityState, AuthorityStore},
124    authority_client::NetworkAuthorityClient,
125};
126use sui_json_rpc::JsonRpcServerBuilder;
127use sui_json_rpc::coin_api::CoinReadApi;
128use sui_json_rpc::governance_api::GovernanceReadApi;
129use sui_json_rpc::indexer_api::IndexerApi;
130use sui_json_rpc::move_utils::MoveUtils;
131use sui_json_rpc::read_api::ReadApi;
132use sui_json_rpc::transaction_builder_api::TransactionBuilderApi;
133use sui_json_rpc::transaction_execution_api::TransactionExecutionApi;
134use sui_macros::fail_point;
135use sui_macros::{fail_point_arg, fail_point_async, replay_log};
136use sui_network::api::ValidatorServer;
137use sui_network::discovery;
138use sui_network::endpoint_manager::EndpointManager;
139use sui_network::state_sync;
140use sui_network::validator::server::ServerBuilder;
141use sui_protocol_config::{Chain, ProtocolConfig, ProtocolVersion};
142use sui_snapshot::uploader::StateSnapshotUploader;
143use sui_storage::{
144    http_key_value_store::HttpKVStore,
145    key_value_store::{FallbackTransactionKVStore, TransactionKeyValueStore},
146    key_value_store_metrics::KeyValueStoreMetrics,
147};
148use sui_types::base_types::{AuthorityName, EpochId};
149use sui_types::committee::Committee;
150use sui_types::crypto::KeypairTraits;
151use sui_types::error::{SuiError, SuiResult};
152use sui_types::messages_consensus::{ConsensusTransaction, check_total_jwk_size};
153use sui_types::storage::RpcStateReader;
154use sui_types::sui_system_state::SuiSystemStateTrait;
155use sui_types::sui_system_state::epoch_start_sui_system_state::EpochStartSystemState;
156use sui_types::sui_system_state::epoch_start_sui_system_state::EpochStartSystemStateTrait;
157use sui_types::supported_protocol_versions::SupportedProtocolVersions;
158use typed_store::DBMetrics;
159use typed_store::rocks::default_db_options;
160
161use crate::metrics::{GrpcMetrics, SuiNodeMetrics};
162
163pub mod address_prober;
164pub mod admin;
165pub mod db_shell;
166mod handle;
167pub mod metrics;
168
169pub struct ValidatorComponents {
170    validator_server_handle: Option<SpawnOnce>,
171    validator_overload_monitor_handle: Option<JoinHandle<()>>,
172    consensus_manager: Arc<ConsensusManager>,
173    consensus_store_pruner: ConsensusStorePruner,
174    consensus_adapter: Arc<ConsensusAdapter>,
175    checkpoint_metrics: Arc<CheckpointMetrics>,
176    sui_tx_validator_metrics: Arc<SuiTxValidatorMetrics>,
177    admission_queue: Option<AdmissionQueueContext>,
178}
179
180pub struct P2pComponents {
181    p2p_network: Network,
182    known_peers: HashMap<PeerId, String>,
183    discovery_handle: discovery::Handle,
184    state_sync_handle: state_sync::Handle,
185    randomness_handle: randomness::Handle,
186    endpoint_manager: EndpointManager,
187}
188
189#[cfg(msim)]
190mod simulator {
191    use std::sync::atomic::AtomicBool;
192    use sui_types::error::SuiErrorKind;
193
194    use super::*;
195    pub(super) struct SimState {
196        pub sim_node: sui_simulator::runtime::NodeHandle,
197        pub sim_safe_mode_expected: AtomicBool,
198        _leak_detector: sui_simulator::NodeLeakDetector,
199    }
200
201    impl Default for SimState {
202        fn default() -> Self {
203            Self {
204                sim_node: sui_simulator::runtime::NodeHandle::current(),
205                sim_safe_mode_expected: AtomicBool::new(false),
206                _leak_detector: sui_simulator::NodeLeakDetector::new(),
207            }
208        }
209    }
210
211    type JwkInjector = dyn Fn(AuthorityName, &OIDCProvider) -> SuiResult<Vec<(JwkId, JWK)>>
212        + Send
213        + Sync
214        + 'static;
215
216    fn default_fetch_jwks(
217        _authority: AuthorityName,
218        _provider: &OIDCProvider,
219    ) -> SuiResult<Vec<(JwkId, JWK)>> {
220        use fastcrypto_zkp::bn254::zk_login::parse_jwks;
221        // Just load a default Twitch jwk for testing.
222        parse_jwks(
223            sui_types::zk_login_util::DEFAULT_JWK_BYTES,
224            &OIDCProvider::Twitch,
225            true,
226        )
227        .map_err(|_| SuiErrorKind::JWKRetrievalError.into())
228    }
229
230    thread_local! {
231        static JWK_INJECTOR: std::cell::RefCell<Arc<JwkInjector>> = std::cell::RefCell::new(Arc::new(default_fetch_jwks));
232    }
233
234    pub(super) fn get_jwk_injector() -> Arc<JwkInjector> {
235        JWK_INJECTOR.with(|injector| injector.borrow().clone())
236    }
237
238    pub fn set_jwk_injector(injector: Arc<JwkInjector>) {
239        JWK_INJECTOR.with(|cell| *cell.borrow_mut() = injector);
240    }
241}
242
243#[cfg(msim)]
244pub use simulator::set_jwk_injector;
245#[cfg(msim)]
246use simulator::*;
247use sui_core::authority::authority_store_pruner::PrunerWatermarks;
248use sui_core::{
249    consensus_handler::ConsensusHandlerInitializer, safe_client::SafeClientMetricsBase,
250};
251
252const DEFAULT_GRPC_CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
253
254pub struct SuiNode {
255    config: NodeConfig,
256    validator_components: Mutex<Option<ValidatorComponents>>,
257
258    /// The http servers responsible for serving RPC traffic (gRPC and JSON-RPC)
259    #[allow(unused)]
260    http_servers: HttpServers,
261
262    state: Arc<AuthorityState>,
263    transaction_orchestrator: Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>>,
264    registry_service: RegistryService,
265    metrics: Arc<SuiNodeMetrics>,
266    checkpoint_metrics: Arc<CheckpointMetrics>,
267
268    _discovery: discovery::Handle,
269    _connection_monitor_handle: mysten_network::anemo_connection_monitor::ConnectionMonitorHandle,
270    state_sync_handle: state_sync::Handle,
271    randomness_handle: randomness::Handle,
272    checkpoint_store: Arc<CheckpointStore>,
273    global_state_hasher: Mutex<Option<Arc<GlobalStateHasher>>>,
274
275    /// Broadcast channel to send the starting system state for the next epoch.
276    end_of_epoch_channel: broadcast::Sender<SuiSystemState>,
277
278    /// EndpointManager for updating peer network addresses.
279    endpoint_manager: EndpointManager,
280
281    /// Handle to the discovery-shared address prober (`None` when disabled).
282    address_prober: Option<address_prober::Handle>,
283
284    backpressure_manager: Arc<BackpressureManager>,
285
286    _db_checkpoint_handle: Option<tokio::sync::broadcast::Sender<()>>,
287
288    #[cfg(msim)]
289    sim_state: SimState,
290
291    _state_snapshot_uploader_handle: Option<broadcast::Sender<()>>,
292    // Channel to allow signaling upstream to shutdown sui-node
293    shutdown_channel_tx: broadcast::Sender<Option<RunWithRange>>,
294
295    /// Handle shared with RandomnessManager and the consensus layer.
296    randomness_receiver_handle: Arc<RandomnessRoundReceiverHandle>,
297
298    /// AuthorityAggregator of the network, created at start and beginning of each epoch.
299    /// Use ArcSwap so that we could mutate it without taking mut reference.
300    // TODO: Eventually we can make this auth aggregator a shared reference so that this
301    // update will automatically propagate to other uses.
302    auth_agg: Arc<ArcSwap<AuthorityAggregator<NetworkAuthorityClient>>>,
303
304    subscription_service_checkpoint_sender: Option<tokio::sync::broadcast::Sender<Arc<Checkpoint>>>,
305
306    /// The embedded `sui-rpc-store`, present when the node is a fullnode
307    /// with indexing enabled. Held for the node's lifetime so its tip
308    /// indexer keeps running (dropping it aborts the indexer). Exposed
309    /// through [`SuiNode::embedded_rpc_store`] for introspection.
310    embedded_rpc_store: Option<EmbeddedRpcStore>,
311}
312
313impl fmt::Debug for SuiNode {
314    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
315        f.debug_struct("SuiNode")
316            .field("name", &self.state.name.concise())
317            .finish()
318    }
319}
320
321static MAX_JWK_KEYS_PER_FETCH: usize = 100;
322
323impl SuiNode {
324    pub async fn start(
325        config: NodeConfig,
326        registry_service: RegistryService,
327    ) -> Result<Arc<SuiNode>> {
328        Self::start_async(
329            config,
330            registry_service,
331            ServerVersion::new("sui-node", "unknown"),
332        )
333        .await
334    }
335
336    fn start_jwk_updater(
337        config: &NodeConfig,
338        metrics: Arc<SuiNodeMetrics>,
339        authority: AuthorityName,
340        epoch_store: Arc<AuthorityPerEpochStore>,
341        consensus_adapter: Arc<ConsensusAdapter>,
342    ) {
343        let epoch = epoch_store.epoch();
344
345        let supported_providers = config
346            .zklogin_oauth_providers
347            .get(&epoch_store.get_chain_identifier().chain())
348            .unwrap_or(&BTreeSet::new())
349            .iter()
350            .map(|s| OIDCProvider::from_str(s).expect("Invalid provider string"))
351            .collect::<Vec<_>>();
352
353        let fetch_interval = Duration::from_secs(config.jwk_fetch_interval_seconds);
354
355        info!(
356            ?fetch_interval,
357            "Starting JWK updater tasks with supported providers: {:?}", supported_providers
358        );
359
360        fn validate_jwk(
361            metrics: &Arc<SuiNodeMetrics>,
362            provider: &OIDCProvider,
363            id: &JwkId,
364            jwk: &JWK,
365        ) -> bool {
366            let Ok(iss_provider) = OIDCProvider::from_iss(&id.iss) else {
367                warn!(
368                    "JWK iss {:?} (retrieved from {:?}) is not a valid provider",
369                    id.iss, provider
370                );
371                metrics
372                    .invalid_jwks
373                    .with_label_values(&[&provider.to_string()])
374                    .inc();
375                return false;
376            };
377
378            if iss_provider != *provider {
379                warn!(
380                    "JWK iss {:?} (retrieved from {:?}) does not match provider {:?}",
381                    id.iss, provider, iss_provider
382                );
383                metrics
384                    .invalid_jwks
385                    .with_label_values(&[&provider.to_string()])
386                    .inc();
387                return false;
388            }
389
390            if !check_total_jwk_size(id, jwk) {
391                warn!("JWK {:?} (retrieved from {:?}) is too large", id, provider);
392                metrics
393                    .invalid_jwks
394                    .with_label_values(&[&provider.to_string()])
395                    .inc();
396                return false;
397            }
398
399            true
400        }
401
402        // metrics is:
403        //  pub struct SuiNodeMetrics {
404        //      pub jwk_requests: IntCounterVec,
405        //      pub jwk_request_errors: IntCounterVec,
406        //      pub total_jwks: IntCounterVec,
407        //      pub unique_jwks: IntCounterVec,
408        //  }
409
410        for p in supported_providers.into_iter() {
411            let provider_str = p.to_string();
412            let epoch_store = epoch_store.clone();
413            let consensus_adapter = consensus_adapter.clone();
414            let metrics = metrics.clone();
415            spawn_monitored_task!(epoch_store.clone().within_alive_epoch(
416                async move {
417                    // note: restart-safe de-duplication happens after consensus, this is
418                    // just best-effort to reduce unneeded submissions.
419                    let mut seen = HashSet::new();
420                    loop {
421                        jwk_log!("fetching JWK for provider {:?}", p);
422                        metrics.jwk_requests.with_label_values(&[&provider_str]).inc();
423                        match Self::fetch_jwks(authority, &p).await {
424                            Err(e) => {
425                                metrics.jwk_request_errors.with_label_values(&[&provider_str]).inc();
426                                warn!("Error when fetching JWK for provider {:?} {:?}", p, e);
427                                // Retry in 30 seconds
428                                tokio::time::sleep(Duration::from_secs(30)).await;
429                                continue;
430                            }
431                            Ok(mut keys) => {
432                                metrics.total_jwks
433                                    .with_label_values(&[&provider_str])
434                                    .inc_by(keys.len() as u64);
435
436                                keys.retain(|(id, jwk)| {
437                                    validate_jwk(&metrics, &p, id, jwk) &&
438                                    !epoch_store.jwk_active_in_current_epoch(id, jwk) &&
439                                    seen.insert((id.clone(), jwk.clone()))
440                                });
441
442                                metrics.unique_jwks
443                                    .with_label_values(&[&provider_str])
444                                    .inc_by(keys.len() as u64);
445
446                                // prevent oauth providers from sending too many keys,
447                                // inadvertently or otherwise
448                                if keys.len() > MAX_JWK_KEYS_PER_FETCH {
449                                    warn!("Provider {:?} sent too many JWKs, only the first {} will be used", p, MAX_JWK_KEYS_PER_FETCH);
450                                    keys.truncate(MAX_JWK_KEYS_PER_FETCH);
451                                }
452
453                                for (id, jwk) in keys.into_iter() {
454                                    jwk_log!("Submitting JWK to consensus: {:?}", id);
455
456                                    let txn = ConsensusTransaction::new_jwk_fetched(authority, id, jwk);
457                                    consensus_adapter.submit(txn, None, &epoch_store, None, None)
458                                        .tap_err(|e| warn!("Error when submitting JWKs to consensus {:?}", e))
459                                        .ok();
460                                }
461                            }
462                        }
463                        tokio::time::sleep(fetch_interval).await;
464                    }
465                }
466                .instrument(error_span!("jwk_updater_task", epoch)),
467            ));
468        }
469    }
470
471    pub async fn start_async(
472        config: NodeConfig,
473        registry_service: RegistryService,
474        server_version: ServerVersion,
475    ) -> Result<Arc<SuiNode>> {
476        // Fail fast on config errors before starting any node components.
477        if let Some(prober_config) = &config.address_prober {
478            prober_config.validate()?;
479        }
480
481        NodeConfigMetrics::new(&registry_service.default_registry()).record_metrics(&config);
482        let mut config = config.clone();
483        if config.supported_protocol_versions.is_none() {
484            info!(
485                "populating config.supported_protocol_versions with default {:?}",
486                SupportedProtocolVersions::SYSTEM_DEFAULT
487            );
488            config.supported_protocol_versions = Some(SupportedProtocolVersions::SYSTEM_DEFAULT);
489        }
490
491        let run_with_range = config.run_with_range;
492        let prometheus_registry = registry_service.default_registry();
493        let node_role = config.intended_node_role();
494
495        info!(node =? config.protocol_public_key(),
496            "Initializing sui-node listening on {} with role {:?}", config.network_address, node_role
497        );
498
499        // Initialize metrics to track db usage before creating any stores
500        DBMetrics::init(registry_service.clone());
501
502        // Initialize db sync-to-disk setting from config (falls back to env var if not set)
503        typed_store::init_write_sync(config.enable_db_sync_to_disk);
504
505        // Initialize Mysten metrics.
506        mysten_metrics::init_metrics(&prometheus_registry);
507        // Unsupported (because of the use of static variable) and unnecessary in simtests.
508        #[cfg(not(msim))]
509        mysten_metrics::thread_stall_monitor::start_thread_stall_monitor();
510
511        let genesis = config.genesis()?.clone();
512
513        let secret = Arc::pin(config.protocol_key_pair().copy());
514        let genesis_committee = genesis.committee();
515        let committee_store = Arc::new(CommitteeStore::new(
516            config.db_path().join("epochs"),
517            &genesis_committee,
518            None,
519        ));
520
521        let pruner_watermarks = Arc::new(PrunerWatermarks::default());
522        let checkpoint_store = CheckpointStore::new(
523            &config.db_path().join("checkpoints"),
524            pruner_watermarks.clone(),
525        );
526        let checkpoint_metrics = CheckpointMetrics::new(&registry_service.default_registry());
527
528        #[allow(unused_mut)]
529        let mut build_version = server_version.version.to_string();
530        fail_point_arg!("override_binary_version", |version: std::sync::Arc<
531            std::sync::Mutex<String>,
532        >| {
533            #[cfg(msim)]
534            {
535                build_version = version.lock().unwrap().clone();
536            }
537        });
538        // Embedded in any fork marker this run records, so recovery can refuse to clear a fork
539        // under the same binary version that produced it.
540        checkpoint_store.set_binary_version(&build_version);
541
542        if node_role.runs_consensus() {
543            Self::check_and_recover_forks(
544                &checkpoint_store,
545                &checkpoint_metrics,
546                config.fork_recovery.as_ref(),
547                &build_version,
548            )
549            .await?;
550        }
551
552        // By default, only enable write stall on nodes that run consensus.
553        let enable_write_stall = config
554            .enable_db_write_stall
555            .unwrap_or(node_role.runs_consensus());
556        // The tidehunter objects compactor retains only the latest version per
557        // ObjectID and is mutually exclusive with the object pruner. Enable it
558        // for validators (which always disable the pruner), and also for any
559        // node configured with `num_epochs_to_retain = 0` — that aggressive
560        // setting is what the compactor replaces. The pruner is force-disabled
561        // in `AuthorityStorePruner::new` whenever this is true.
562        let enable_objects_compactor = node_role.is_validator()
563            || config.authority_store_pruning_config.num_epochs_to_retain == 0;
564        let perpetual_tables_options = AuthorityPerpetualTablesOptions {
565            enable_write_stall,
566            enable_objects_compactor,
567        };
568        let perpetual_tables = Arc::new(AuthorityPerpetualTables::open(
569            &config.db_store_path(),
570            Some(perpetual_tables_options),
571            Some(pruner_watermarks.epoch_id.clone()),
572        ));
573        let is_genesis = perpetual_tables
574            .database_is_empty()
575            .expect("Database read should not fail at init.");
576
577        let backpressure_manager =
578            BackpressureManager::new_from_checkpoint_store(&checkpoint_store);
579
580        let store =
581            AuthorityStore::open(perpetual_tables, &genesis, &config, &prometheus_registry).await?;
582
583        let cur_epoch = store.get_recovery_epoch_at_restart()?;
584        let committee = committee_store
585            .get_committee(&cur_epoch)?
586            .expect("Committee of the current epoch must exist");
587        let epoch_start_configuration = store
588            .get_epoch_start_configuration()?
589            .expect("EpochStartConfiguration of the current epoch must exist");
590        let cache_metrics = Arc::new(ResolverMetrics::new(&prometheus_registry));
591        let signature_verifier_metrics = SignatureVerifierMetrics::new(&prometheus_registry);
592
593        let cache_traits = build_execution_cache(
594            &config.execution_cache,
595            &prometheus_registry,
596            &store,
597            backpressure_manager.clone(),
598        );
599
600        let auth_agg = {
601            let safe_client_metrics_base = SafeClientMetricsBase::new(&prometheus_registry);
602            Arc::new(ArcSwap::new(Arc::new(
603                AuthorityAggregator::new_from_epoch_start_state(
604                    epoch_start_configuration.epoch_start_state(),
605                    &committee_store,
606                    safe_client_metrics_base,
607                ),
608            )))
609        };
610
611        let chain_id = ChainIdentifier::from(*genesis.checkpoint().digest());
612        let chain = match config.chain_override_for_testing {
613            Some(chain) => chain,
614            None => ChainIdentifier::from(*genesis.checkpoint().digest()).chain(),
615        };
616
617        let highest_executed_checkpoint = checkpoint_store
618            .get_highest_executed_checkpoint_seq_number()
619            .expect("checkpoint store read cannot fail")
620            .unwrap_or(0);
621
622        let previous_epoch_last_checkpoint = if cur_epoch == 0 {
623            0
624        } else {
625            checkpoint_store
626                .get_epoch_last_checkpoint_seq_number(cur_epoch - 1)
627                .expect("checkpoint store read cannot fail")
628                .unwrap_or(highest_executed_checkpoint)
629        };
630
631        let epoch_options = default_db_options().optimize_db_for_write_throughput(4, false);
632        let epoch_store = AuthorityPerEpochStore::new(
633            config.protocol_public_key(),
634            committee.clone(),
635            &config.db_store_path(),
636            Some(epoch_options.options),
637            EpochMetrics::new(&registry_service.default_registry()),
638            epoch_start_configuration,
639            cache_traits.backing_package_store.clone(),
640            cache_traits.object_store.clone(),
641            cache_metrics,
642            signature_verifier_metrics,
643            &config.expensive_safety_check_config,
644            (chain_id, chain),
645            highest_executed_checkpoint,
646            previous_epoch_last_checkpoint,
647            Arc::new(SubmittedTransactionCacheMetrics::new(
648                &registry_service.default_registry(),
649            )),
650            config.fullnode_sync_mode,
651        )?;
652
653        info!("created epoch store");
654
655        replay_log!(
656            "Beginning replay run. Epoch: {:?}, Protocol config: {:?}",
657            epoch_store.epoch(),
658            epoch_store.protocol_config()
659        );
660
661        // the database is empty at genesis time
662        if is_genesis {
663            info!("checking SUI conservation at genesis");
664            // When we are opening the db table, the only time when it's safe to
665            // check SUI conservation is at genesis. Otherwise we may be in the middle of
666            // an epoch and the SUI conservation check will fail. This also initialize
667            // the expected_network_sui_amount table.
668            cache_traits
669                .reconfig_api
670                .expensive_check_sui_conservation(&epoch_store)
671                .expect("SUI conservation check cannot fail at genesis");
672        }
673
674        let effective_buffer_stake = epoch_store.get_effective_buffer_stake_bps();
675        let default_buffer_stake = epoch_store
676            .protocol_config()
677            .buffer_stake_for_protocol_upgrade_bps();
678        if effective_buffer_stake != default_buffer_stake {
679            warn!(
680                ?effective_buffer_stake,
681                ?default_buffer_stake,
682                "buffer_stake_for_protocol_upgrade_bps is currently overridden"
683            );
684        }
685
686        checkpoint_store.insert_genesis_checkpoint(
687            genesis.checkpoint(),
688            genesis.checkpoint_contents().clone(),
689            &epoch_store,
690        );
691
692        info!("creating state sync store");
693        let state_sync_store = RocksDbStore::new(
694            cache_traits.clone(),
695            committee_store.clone(),
696            checkpoint_store.clone(),
697        );
698
699        let index_store = if node_role.is_fullnode() && config.enable_index_processing {
700            info!("creating jsonrpc index store");
701            Some(Arc::new(IndexStore::new(
702                config.db_path().join("indexes"),
703                &prometheus_registry,
704                epoch_store
705                    .protocol_config()
706                    .max_move_identifier_len_as_option(),
707                config.remove_deprecated_tables,
708            )))
709        } else {
710            None
711        };
712
713        let chain_identifier = epoch_store.get_chain_identifier();
714
715        // The embedded `sui-rpc-store` is the node's index backend: when
716        // indexing is enabled it builds the derived-index and ledger-history
717        // column families (indexed independently of the authority store) and
718        // serves the index read paths from the embedded store. Raw chain data
719        // is still served from the perpetual store.
720        let mut embedded_rpc_store =
721            if node_role.is_fullnode() && config.rpc().is_some_and(|rpc| rpc.enable_indexing()) {
722                info!("creating embedded rpc-store");
723                // The embedded `sui-rpc-store` replaced the legacy `rpc-index`
724                // backend; remove its now-dead on-disk directory if a prior
725                // version left one behind.
726                remove_legacy_rpc_index_store(&config.db_path());
727                // The tip indexer pulls checkpoints from the node's local
728                // checkpoint / perpetual stores via a dedicated read handle.
729                let ingestion_source = RocksDbStore::new(
730                    cache_traits.clone(),
731                    committee_store.clone(),
732                    checkpoint_store.clone(),
733                );
734                let embedded_rpc_store = EmbeddedRpcStore::bootstrap(
735                    &config,
736                    &store,
737                    &checkpoint_store,
738                    ingestion_source,
739                    chain_identifier,
740                    &prometheus_registry,
741                )
742                .await?;
743                Some(embedded_rpc_store)
744            } else {
745                None
746            };
747
748        info!("creating archive reader");
749        // Create network
750        let (randomness_tx, randomness_rx) = mpsc::channel(
751            config
752                .p2p_config
753                .randomness
754                .clone()
755                .unwrap_or_default()
756                .mailbox_capacity(),
757        );
758        let P2pComponents {
759            p2p_network,
760            known_peers,
761            discovery_handle,
762            state_sync_handle,
763            randomness_handle,
764            endpoint_manager,
765        } = Self::create_p2p_network(
766            &config,
767            state_sync_store.clone(),
768            chain_identifier,
769            randomness_tx,
770            &prometheus_registry,
771        )?;
772
773        // Inject configured peer address overrides.
774        for peer in &config.p2p_config.peer_address_overrides {
775            endpoint_manager
776                .update_endpoint(
777                    EndpointId::P2p(peer.peer_id),
778                    AddressSource::Config,
779                    peer.addresses.clone(),
780                )
781                .expect("Updating peer address overrides should not fail");
782        }
783
784        // Send initial peer addresses to the p2p network.
785        update_peer_addresses(
786            &config,
787            &endpoint_manager,
788            epoch_store.epoch_start_state(),
789            None,
790        );
791
792        info!("start snapshot upload");
793        // Start uploading state snapshot to remote store
794        let state_snapshot_handle = Self::start_state_snapshot(
795            &config,
796            &prometheus_registry,
797            checkpoint_store.clone(),
798            chain_identifier,
799        )?;
800
801        // Start uploading db checkpoints to remote store
802        info!("start db checkpoint");
803        let (db_checkpoint_config, db_checkpoint_handle) = Self::start_db_checkpoint(
804            &config,
805            &prometheus_registry,
806            state_snapshot_handle.is_some(),
807        )?;
808
809        if !epoch_store
810            .protocol_config()
811            .simplified_unwrap_then_delete()
812        {
813            // We cannot prune tombstones if simplified_unwrap_then_delete is not enabled.
814            config
815                .authority_store_pruning_config
816                .set_killswitch_tombstone_pruning(true);
817        }
818
819        let authority_name = config.protocol_public_key();
820
821        info!("create authority state");
822        let state = AuthorityState::new(
823            authority_name,
824            secret,
825            config.supported_protocol_versions.unwrap(),
826            store.clone(),
827            cache_traits.clone(),
828            epoch_store.clone(),
829            committee_store.clone(),
830            index_store.clone(),
831            embedded_rpc_store.as_ref().map(|embedded| embedded.store()),
832            checkpoint_store.clone(),
833            &prometheus_registry,
834            genesis.objects(),
835            &db_checkpoint_config,
836            config.clone(),
837            chain_identifier,
838            config.policy_config.clone(),
839            config.firewall_config.clone(),
840            pruner_watermarks,
841        )
842        .await;
843        // ensure genesis txn was executed
844        if epoch_store.epoch() == 0 {
845            let txn = &genesis.transaction();
846            let span = error_span!("genesis_txn", tx_digest = ?txn.digest());
847            let transaction =
848                sui_types::executable_transaction::VerifiedExecutableTransaction::new_unchecked(
849                    sui_types::executable_transaction::ExecutableTransaction::new_from_data_and_sig(
850                        genesis.transaction().data().clone(),
851                        sui_types::executable_transaction::CertificateProof::Checkpoint(0, 0),
852                    ),
853                );
854            let _enter = span.enter();
855            state
856                .try_execute_immediately(&transaction, ExecutionEnv::new(), &epoch_store)
857                .unwrap();
858        }
859
860        // Start the loop that receives new randomness and generates transactions for it.
861        // The returned is long-lived (node lifetime).
862        let randomness_receiver_handle =
863            RandomnessRoundReceiver::spawn(state.clone(), randomness_rx);
864
865        let (end_of_epoch_channel, end_of_epoch_receiver) =
866            broadcast::channel(config.end_of_epoch_broadcast_channel_capacity);
867
868        let transaction_orchestrator = if node_role.is_fullnode() && run_with_range.is_none() {
869            Some(Arc::new(TransactionOrchestrator::new_with_auth_aggregator(
870                auth_agg.load_full(),
871                state.clone(),
872                end_of_epoch_receiver,
873                &config.db_path(),
874                &prometheus_registry,
875                &config,
876            )))
877        } else {
878            None
879        };
880
881        let (http_servers, subscription_service_checkpoint_sender) = build_http_servers(
882            state.clone(),
883            state_sync_store,
884            &transaction_orchestrator.clone(),
885            &config,
886            &prometheus_registry,
887            server_version,
888            node_role,
889            embedded_rpc_store.as_ref(),
890        )
891        .await?;
892
893        // Start the embedded rpc-store's tip indexer. It follows the tip
894        // via the checkpoint executor's broadcast stream and backfills
895        // any gap from the perpetual store. Spawned on a background task
896        // (see `spawn_indexer`) so node startup does not block on the
897        // first checkpoint, which the executor only produces after this
898        // function returns.
899        if let Some(embedded) = embedded_rpc_store.as_mut() {
900            embedded.spawn_indexer(
901                subscription_service_checkpoint_sender.clone(),
902                prometheus_registry.clone(),
903            );
904        }
905
906        let global_state_hasher = Arc::new(GlobalStateHasher::new(
907            cache_traits.global_state_hash_store.clone(),
908            GlobalStateHashMetrics::new(&prometheus_registry),
909        ));
910
911        let network_connection_metrics = mysten_network::quinn_metrics::QuinnConnectionMetrics::new(
912            "sui",
913            &registry_service.default_registry(),
914        );
915
916        let connection_monitor_handle =
917            mysten_network::anemo_connection_monitor::AnemoConnectionMonitor::spawn(
918                p2p_network.downgrade(),
919                Arc::new(network_connection_metrics),
920                known_peers,
921            );
922
923        let sui_node_metrics = Arc::new(SuiNodeMetrics::new(&registry_service.default_registry()));
924
925        sui_node_metrics
926            .binary_max_protocol_version
927            .set(ProtocolVersion::MAX.as_u64() as i64);
928        sui_node_metrics
929            .configured_max_protocol_version
930            .set(config.supported_protocol_versions.unwrap().max.as_u64() as i64);
931
932        let node_role = epoch_store.node_role();
933        let validator_components = if node_role.runs_consensus() {
934            let mut components = Self::construct_validator_components(
935                config.clone(),
936                state.clone(),
937                committee,
938                epoch_store.clone(),
939                checkpoint_store.clone(),
940                state_sync_handle.clone(),
941                randomness_handle.clone(),
942                Arc::downgrade(&global_state_hasher),
943                backpressure_manager.clone(),
944                &registry_service,
945                sui_node_metrics.clone(),
946                checkpoint_metrics.clone(),
947                node_role,
948                randomness_receiver_handle.clone(),
949            )
950            .await?;
951
952            if node_role.is_validator() {
953                components
954                    .consensus_adapter
955                    .recover_end_of_publish(&epoch_store);
956
957                // Start the gRPC server
958                components.validator_server_handle = Some(
959                    components
960                        .validator_server_handle
961                        .take()
962                        .unwrap()
963                        .start()
964                        .await,
965                );
966
967                // Set the consensus address updater so that we can update the consensus peer addresses when requested.
968                endpoint_manager
969                    .set_consensus_address_updater(components.consensus_manager.clone());
970            } else {
971                info!("Starting node as Observer — connecting to configured peers");
972            }
973
974            Some(components)
975        } else {
976            None
977        };
978
979        let address_prober = if Self::address_prober_enabled(&config) {
980            let handle = address_prober::Builder::new()
981                .config(config.address_prober.clone().unwrap_or_default())
982                .with_metrics(&prometheus_registry)
983                .build()
984                .start(
985                    p2p_network.clone(),
986                    discovery_handle.sender(),
987                    consensus_config::NetworkKeyPair::new(config.network_key_pair().copy()),
988                );
989            // Seed the current epoch if we are starting as a validator.
990            if node_role.is_validator()
991                && let Some(components) = &validator_components
992            {
993                handle.update_epoch(
994                    epoch_store.epoch(),
995                    epoch_store.epoch_start_state().get_consensus_committee(),
996                    components.consensus_manager.clone(),
997                );
998            }
999            Some(handle)
1000        } else {
1001            None
1002        };
1003
1004        // setup shutdown channel
1005        let (shutdown_channel, _) = broadcast::channel::<Option<RunWithRange>>(1);
1006
1007        let node = Self {
1008            config,
1009            validator_components: Mutex::new(validator_components),
1010            http_servers,
1011            state,
1012            transaction_orchestrator,
1013            registry_service,
1014            metrics: sui_node_metrics,
1015            checkpoint_metrics,
1016
1017            _discovery: discovery_handle,
1018            _connection_monitor_handle: connection_monitor_handle,
1019            state_sync_handle,
1020            randomness_handle,
1021            checkpoint_store,
1022            global_state_hasher: Mutex::new(Some(global_state_hasher)),
1023            end_of_epoch_channel,
1024            endpoint_manager,
1025            backpressure_manager,
1026            address_prober,
1027
1028            _db_checkpoint_handle: db_checkpoint_handle,
1029
1030            #[cfg(msim)]
1031            sim_state: Default::default(),
1032
1033            _state_snapshot_uploader_handle: state_snapshot_handle,
1034            shutdown_channel_tx: shutdown_channel,
1035            randomness_receiver_handle,
1036
1037            auth_agg,
1038            subscription_service_checkpoint_sender,
1039            embedded_rpc_store,
1040        };
1041
1042        info!("SuiNode started!");
1043        let node = Arc::new(node);
1044        let node_copy = node.clone();
1045        spawn_monitored_task!(async move {
1046            let result = Self::monitor_reconfiguration(node_copy, epoch_store).await;
1047            if let Err(error) = result {
1048                warn!("Reconfiguration finished with error {:?}", error);
1049            }
1050        });
1051
1052        Ok(node)
1053    }
1054
1055    pub fn subscribe_to_epoch_change(&self) -> broadcast::Receiver<SuiSystemState> {
1056        self.end_of_epoch_channel.subscribe()
1057    }
1058
1059    pub fn subscribe_to_shutdown_channel(&self) -> broadcast::Receiver<Option<RunWithRange>> {
1060        self.shutdown_channel_tx.subscribe()
1061    }
1062
1063    pub fn current_epoch_for_testing(&self) -> EpochId {
1064        self.state.current_epoch_for_testing()
1065    }
1066
1067    pub fn db_checkpoint_path(&self) -> PathBuf {
1068        self.config.db_checkpoint_path()
1069    }
1070
1071    // Init reconfig process by starting to reject user certs
1072    pub async fn close_epoch(&self, epoch_store: &Arc<AuthorityPerEpochStore>) -> SuiResult {
1073        info!("close_epoch (current epoch = {})", epoch_store.epoch());
1074        self.validator_components
1075            .lock()
1076            .await
1077            .as_ref()
1078            .ok_or_else(|| SuiError::from("Node is not a validator"))?
1079            .consensus_adapter
1080            .close_epoch(epoch_store);
1081        Ok(())
1082    }
1083
1084    pub fn clear_override_protocol_upgrade_buffer_stake(&self, epoch: EpochId) -> SuiResult {
1085        self.state
1086            .clear_override_protocol_upgrade_buffer_stake(epoch)
1087    }
1088
1089    pub fn set_override_protocol_upgrade_buffer_stake(
1090        &self,
1091        epoch: EpochId,
1092        buffer_stake_bps: u64,
1093    ) -> SuiResult {
1094        self.state
1095            .set_override_protocol_upgrade_buffer_stake(epoch, buffer_stake_bps)
1096    }
1097
1098    // Testing-only API to start epoch close process.
1099    // For production code, please use the non-testing version.
1100    pub async fn close_epoch_for_testing(&self) -> SuiResult {
1101        let epoch_store = self.state.epoch_store_for_testing();
1102        self.close_epoch(&epoch_store).await
1103    }
1104
1105    fn start_state_snapshot(
1106        config: &NodeConfig,
1107        prometheus_registry: &Registry,
1108        checkpoint_store: Arc<CheckpointStore>,
1109        chain_identifier: ChainIdentifier,
1110    ) -> Result<Option<tokio::sync::broadcast::Sender<()>>> {
1111        if let Some(remote_store_config) = &config.state_snapshot_write_config.object_store_config {
1112            let snapshot_uploader = StateSnapshotUploader::new(
1113                &config.db_checkpoint_path(),
1114                &config.snapshot_path(),
1115                remote_store_config.clone(),
1116                60,
1117                prometheus_registry,
1118                checkpoint_store,
1119                chain_identifier,
1120                config.state_snapshot_write_config.archive_interval_epochs,
1121            )?;
1122            Ok(Some(snapshot_uploader.start()))
1123        } else {
1124            Ok(None)
1125        }
1126    }
1127
1128    fn start_db_checkpoint(
1129        config: &NodeConfig,
1130        prometheus_registry: &Registry,
1131        state_snapshot_enabled: bool,
1132    ) -> Result<(
1133        DBCheckpointConfig,
1134        Option<tokio::sync::broadcast::Sender<()>>,
1135    )> {
1136        let checkpoint_path = Some(
1137            config
1138                .db_checkpoint_config
1139                .checkpoint_path
1140                .clone()
1141                .unwrap_or_else(|| config.db_checkpoint_path()),
1142        );
1143        let db_checkpoint_config = if config.db_checkpoint_config.checkpoint_path.is_none() {
1144            DBCheckpointConfig {
1145                checkpoint_path,
1146                perform_db_checkpoints_at_epoch_end: if state_snapshot_enabled {
1147                    true
1148                } else {
1149                    config
1150                        .db_checkpoint_config
1151                        .perform_db_checkpoints_at_epoch_end
1152                },
1153                ..config.db_checkpoint_config.clone()
1154            }
1155        } else {
1156            config.db_checkpoint_config.clone()
1157        };
1158
1159        match (
1160            db_checkpoint_config.object_store_config.as_ref(),
1161            state_snapshot_enabled,
1162        ) {
1163            // If db checkpoint config object store not specified but
1164            // state snapshot object store is specified, create handler
1165            // anyway for marking db checkpoints as completed so that they
1166            // can be uploaded as state snapshots.
1167            (None, false) => Ok((db_checkpoint_config, None)),
1168            (_, _) => {
1169                let handler = DBCheckpointHandler::new(
1170                    &db_checkpoint_config.checkpoint_path.clone().unwrap(),
1171                    db_checkpoint_config.object_store_config.as_ref(),
1172                    60,
1173                    db_checkpoint_config
1174                        .prune_and_compact_before_upload
1175                        .unwrap_or(true),
1176                    config.authority_store_pruning_config.clone(),
1177                    prometheus_registry,
1178                    state_snapshot_enabled,
1179                )?;
1180                Ok((
1181                    db_checkpoint_config,
1182                    Some(DBCheckpointHandler::start(handler)),
1183                ))
1184            }
1185        }
1186    }
1187
1188    fn create_p2p_network(
1189        config: &NodeConfig,
1190        state_sync_store: RocksDbStore,
1191        chain_identifier: ChainIdentifier,
1192        randomness_tx: mpsc::Sender<(EpochId, RandomnessRound, Vec<u8>)>,
1193        prometheus_registry: &Registry,
1194    ) -> Result<P2pComponents> {
1195        let mut p2p_config = config.p2p_config.clone();
1196        {
1197            let disc = p2p_config.discovery.get_or_insert_with(Default::default);
1198            if disc.peer_addr_store_path.is_none() {
1199                disc.peer_addr_store_path =
1200                    Some(config.db_path().join("discovery_peer_cache.yaml"));
1201            }
1202        }
1203        let mut discovery_builder = discovery::Builder::new().config(p2p_config.clone());
1204        if let Some(consensus_config) = &config.consensus_config {
1205            let effective_addr = consensus_config
1206                .external_address
1207                .as_ref()
1208                .or(consensus_config.listen_address.as_ref());
1209            if let Some(addr) = effective_addr {
1210                discovery_builder = discovery_builder.consensus_external_address(addr.clone());
1211            }
1212        }
1213        let (discovery, discovery_server, endpoint_manager) = discovery_builder.build();
1214        let discovery_sender = discovery.sender();
1215
1216        let (state_sync, state_sync_router) = state_sync::Builder::new()
1217            .config(config.p2p_config.state_sync.clone().unwrap_or_default())
1218            .store(state_sync_store)
1219            .archive_config(config.archive_reader_config())
1220            .discovery_sender(discovery_sender)
1221            .with_metrics(prometheus_registry)
1222            .build();
1223
1224        let discovery_config = config.p2p_config.discovery.clone().unwrap_or_default();
1225        let known_peers: HashMap<PeerId, String> = discovery_config
1226            .allowlisted_peers
1227            .clone()
1228            .into_iter()
1229            .map(|ap| (ap.peer_id, "allowlisted_peer".to_string()))
1230            .chain(config.p2p_config.seed_peers.iter().filter_map(|peer| {
1231                peer.peer_id
1232                    .map(|peer_id| (peer_id, "seed_peer".to_string()))
1233            }))
1234            .collect();
1235
1236        let (randomness, randomness_router) =
1237            randomness::Builder::new(config.protocol_public_key(), randomness_tx)
1238                .config(config.p2p_config.randomness.clone().unwrap_or_default())
1239                .with_metrics(prometheus_registry)
1240                .build();
1241
1242        let p2p_network = {
1243            let routes = anemo::Router::new()
1244                .add_rpc_service(discovery_server)
1245                .merge(state_sync_router);
1246            let routes = routes.merge(randomness_router);
1247
1248            let inbound_network_metrics =
1249                mysten_network::metrics::NetworkMetrics::new("sui", "inbound", prometheus_registry);
1250            let outbound_network_metrics = mysten_network::metrics::NetworkMetrics::new(
1251                "sui",
1252                "outbound",
1253                prometheus_registry,
1254            );
1255
1256            let service = ServiceBuilder::new()
1257                .layer(
1258                    TraceLayer::new_for_server_errors()
1259                        .make_span_with(DefaultMakeSpan::new().level(tracing::Level::INFO))
1260                        .on_failure(DefaultOnFailure::new().level(tracing::Level::WARN)),
1261                )
1262                .layer(CallbackLayer::new(
1263                    mysten_network::metrics::MetricsMakeCallbackHandler::new(
1264                        Arc::new(inbound_network_metrics),
1265                        config.p2p_config.excessive_message_size(),
1266                    ),
1267                ))
1268                .service(routes);
1269
1270            let outbound_layer = ServiceBuilder::new()
1271                .layer(
1272                    TraceLayer::new_for_client_and_server_errors()
1273                        .make_span_with(DefaultMakeSpan::new().level(tracing::Level::INFO))
1274                        .on_failure(DefaultOnFailure::new().level(tracing::Level::WARN)),
1275                )
1276                .layer(CallbackLayer::new(
1277                    mysten_network::metrics::MetricsMakeCallbackHandler::new(
1278                        Arc::new(outbound_network_metrics),
1279                        config.p2p_config.excessive_message_size(),
1280                    ),
1281                ))
1282                .into_inner();
1283
1284            let mut anemo_config = config.p2p_config.anemo_config.clone().unwrap_or_default();
1285            // Inbound requests on this network are small (signatures, queries, summaries).
1286            // Cap request frames at 1 MiB.
1287            anemo_config.max_request_frame_size = Some(1 << 20);
1288            // Responses can be larger (checkpoint contents).
1289            // Cap response frames at 128 MiB.
1290            anemo_config.max_response_frame_size = Some(128 << 20);
1291
1292            // Set a higher default value for socket send/receive buffers if not already
1293            // configured.
1294            let mut quic_config = anemo_config.quic.unwrap_or_default();
1295            if quic_config.socket_send_buffer_size.is_none() {
1296                quic_config.socket_send_buffer_size = Some(20 << 20);
1297            }
1298            if quic_config.socket_receive_buffer_size.is_none() {
1299                quic_config.socket_receive_buffer_size = Some(20 << 20);
1300            }
1301            quic_config.allow_failed_socket_buffer_size_setting = true;
1302
1303            // Set high-performance defaults for quinn transport.
1304            // With 200MiB buffer size and ~500ms RTT, max throughput ~400MiB/s.
1305            if quic_config.max_concurrent_bidi_streams.is_none() {
1306                quic_config.max_concurrent_bidi_streams = Some(500);
1307            }
1308            if quic_config.max_concurrent_uni_streams.is_none() {
1309                quic_config.max_concurrent_uni_streams = Some(500);
1310            }
1311            if quic_config.stream_receive_window.is_none() {
1312                quic_config.stream_receive_window = Some(100 << 20);
1313            }
1314            if quic_config.receive_window.is_none() {
1315                quic_config.receive_window = Some(200 << 20);
1316            }
1317            if quic_config.send_window.is_none() {
1318                quic_config.send_window = Some(200 << 20);
1319            }
1320            if quic_config.crypto_buffer_size.is_none() {
1321                quic_config.crypto_buffer_size = Some(1 << 20);
1322            }
1323            if quic_config.max_idle_timeout_ms.is_none() {
1324                quic_config.max_idle_timeout_ms = Some(10_000);
1325            }
1326            if quic_config.keep_alive_interval_ms.is_none() {
1327                quic_config.keep_alive_interval_ms = Some(5_000);
1328            }
1329            anemo_config.quic = Some(quic_config);
1330
1331            let server_name = format!("sui-{}", chain_identifier);
1332            let network = Network::bind(config.p2p_config.listen_address)
1333                .server_name(&server_name)
1334                .private_key(config.network_key_pair().copy().private().0.to_bytes())
1335                .config(anemo_config)
1336                .outbound_request_layer(outbound_layer)
1337                .start(service)?;
1338            info!(
1339                server_name = server_name,
1340                "P2p network started on {}",
1341                network.local_addr()
1342            );
1343
1344            network
1345        };
1346
1347        let discovery_handle =
1348            discovery.start(p2p_network.clone(), config.network_key_pair().copy());
1349        let state_sync_handle = state_sync.start(p2p_network.clone());
1350        let randomness_handle = randomness.start(p2p_network.clone());
1351
1352        Ok(P2pComponents {
1353            p2p_network,
1354            known_peers,
1355            discovery_handle,
1356            state_sync_handle,
1357            randomness_handle,
1358            endpoint_manager,
1359        })
1360    }
1361
1362    async fn construct_validator_components(
1363        config: NodeConfig,
1364        state: Arc<AuthorityState>,
1365        committee: Arc<Committee>,
1366        epoch_store: Arc<AuthorityPerEpochStore>,
1367        checkpoint_store: Arc<CheckpointStore>,
1368        state_sync_handle: state_sync::Handle,
1369        randomness_handle: randomness::Handle,
1370        global_state_hasher: Weak<GlobalStateHasher>,
1371        backpressure_manager: Arc<BackpressureManager>,
1372        registry_service: &RegistryService,
1373        sui_node_metrics: Arc<SuiNodeMetrics>,
1374        checkpoint_metrics: Arc<CheckpointMetrics>,
1375        node_role: NodeRole,
1376        randomness_receiver_handle: Arc<RandomnessRoundReceiverHandle>,
1377    ) -> Result<ValidatorComponents> {
1378        let mut config_clone = config.clone();
1379        let consensus_config = config_clone
1380            .consensus_config
1381            .as_mut()
1382            .ok_or_else(|| anyhow!("Node is missing consensus config"))?;
1383
1384        let client = Arc::new(UpdatableConsensusClient::new());
1385        let inflight_slot_freed_notify = Arc::new(tokio::sync::Notify::new());
1386        let consensus_adapter = Arc::new(Self::construct_consensus_adapter(
1387            &committee,
1388            consensus_config,
1389            state.name,
1390            &registry_service.default_registry(),
1391            client.clone(),
1392            checkpoint_store.clone(),
1393            inflight_slot_freed_notify.clone(),
1394        ));
1395
1396        let consensus_manager = Arc::new(ConsensusManager::new(
1397            &config,
1398            consensus_config,
1399            registry_service,
1400            client,
1401            node_role,
1402        ));
1403
1404        // This only gets started up once, not on every epoch. (Make call to remove every epoch.)
1405        let consensus_store_pruner = ConsensusStorePruner::new(
1406            consensus_manager.get_storage_base_path(),
1407            consensus_config.db_retention_epochs(),
1408            consensus_config.db_pruner_period(),
1409            &registry_service.default_registry(),
1410        );
1411
1412        let sui_tx_validator_metrics =
1413            SuiTxValidatorMetrics::new(&registry_service.default_registry());
1414
1415        let (validator_server_handle, admission_queue) = if node_role.is_validator() {
1416            let (handle, queue) = Self::start_grpc_validator_service(
1417                &config,
1418                state.clone(),
1419                consensus_adapter.clone(),
1420                epoch_store.clone(),
1421                &registry_service.default_registry(),
1422                inflight_slot_freed_notify,
1423            )
1424            .await?;
1425            (Some(handle), queue)
1426        } else {
1427            (None, None)
1428        };
1429
1430        // Starts an overload monitor that monitors the execution of the authority.
1431        // Don't start the overload monitor when max_load_shedding_percentage is 0.
1432        let validator_overload_monitor_handle = if node_role.is_validator()
1433            && config
1434                .authority_overload_config
1435                .max_load_shedding_percentage
1436                > 0
1437        {
1438            let authority_state = Arc::downgrade(&state);
1439            let overload_config = config.authority_overload_config.clone();
1440            fail_point!("starting_overload_monitor");
1441            Some(spawn_monitored_task!(overload_monitor(
1442                authority_state,
1443                overload_config,
1444            )))
1445        } else {
1446            None
1447        };
1448
1449        Self::start_epoch_specific_validator_components(
1450            &config,
1451            state.clone(),
1452            consensus_adapter,
1453            checkpoint_store,
1454            epoch_store,
1455            state_sync_handle,
1456            randomness_handle,
1457            randomness_receiver_handle,
1458            consensus_manager,
1459            consensus_store_pruner,
1460            global_state_hasher,
1461            backpressure_manager,
1462            validator_server_handle,
1463            validator_overload_monitor_handle,
1464            checkpoint_metrics,
1465            sui_node_metrics,
1466            sui_tx_validator_metrics,
1467            admission_queue,
1468            node_role,
1469        )
1470        .await
1471    }
1472
1473    fn address_prober_enabled(config: &NodeConfig) -> bool {
1474        let prober_enabled = config
1475            .address_prober
1476            .as_ref()
1477            .map(|c| c.enabled())
1478            .unwrap_or(true);
1479        let v3_enabled = config
1480            .p2p_config
1481            .discovery
1482            .as_ref()
1483            .is_some_and(|d| d.use_get_known_peers_v3());
1484        prober_enabled && v3_enabled
1485    }
1486
1487    fn update_address_prober_epoch(
1488        &self,
1489        epoch_store: &AuthorityPerEpochStore,
1490        consensus_manager: &Arc<ConsensusManager>,
1491    ) {
1492        if !epoch_store.is_validator() {
1493            return;
1494        }
1495        if let Some(handle) = &self.address_prober {
1496            handle.update_epoch(
1497                epoch_store.epoch(),
1498                epoch_store.epoch_start_state().get_consensus_committee(),
1499                consensus_manager.clone(),
1500            );
1501        }
1502    }
1503
1504    async fn start_epoch_specific_validator_components(
1505        config: &NodeConfig,
1506        state: Arc<AuthorityState>,
1507        consensus_adapter: Arc<ConsensusAdapter>,
1508        checkpoint_store: Arc<CheckpointStore>,
1509        epoch_store: Arc<AuthorityPerEpochStore>,
1510        state_sync_handle: state_sync::Handle,
1511        randomness_handle: randomness::Handle,
1512        randomness_receiver_handle: Arc<RandomnessRoundReceiverHandle>,
1513        consensus_manager: Arc<ConsensusManager>,
1514        consensus_store_pruner: ConsensusStorePruner,
1515        state_hasher: Weak<GlobalStateHasher>,
1516        backpressure_manager: Arc<BackpressureManager>,
1517        validator_server_handle: Option<SpawnOnce>,
1518        validator_overload_monitor_handle: Option<JoinHandle<()>>,
1519        checkpoint_metrics: Arc<CheckpointMetrics>,
1520        sui_node_metrics: Arc<SuiNodeMetrics>,
1521        sui_tx_validator_metrics: Arc<SuiTxValidatorMetrics>,
1522        admission_queue: Option<AdmissionQueueContext>,
1523        node_role: NodeRole,
1524    ) -> Result<ValidatorComponents> {
1525        let checkpoint_service = Self::build_checkpoint_service(
1526            config,
1527            consensus_adapter.clone(),
1528            checkpoint_store.clone(),
1529            epoch_store.clone(),
1530            state.clone(),
1531            state_sync_handle,
1532            state_hasher,
1533            checkpoint_metrics.clone(),
1534            node_role,
1535        );
1536
1537        // Clear the VSS public key from the previous epoch so any randomness round
1538        // signatures buffer in the channel until the new DKG completes.
1539        randomness_receiver_handle.clear_public_key();
1540
1541        if node_role.runs_consensus() && epoch_store.randomness_state_enabled() {
1542            let authority_key_pair = if node_role.is_validator() {
1543                Some(config.protocol_key_pair())
1544            } else {
1545                None
1546            };
1547            let randomness_manager = RandomnessManager::try_new(
1548                Arc::downgrade(&epoch_store),
1549                Box::new(consensus_adapter.clone()),
1550                randomness_handle,
1551                authority_key_pair,
1552                randomness_receiver_handle.clone(),
1553            )
1554            .await;
1555            if let Some(randomness_manager) = randomness_manager {
1556                epoch_store
1557                    .set_randomness_manager(randomness_manager)
1558                    .await?;
1559            }
1560        }
1561
1562        if node_role.is_validator() {
1563            ExecutionTimeObserver::spawn(
1564                epoch_store.clone(),
1565                Box::new(consensus_adapter.clone()),
1566                config
1567                    .execution_time_observer_config
1568                    .clone()
1569                    .unwrap_or_default(),
1570            );
1571        }
1572
1573        let throughput_calculator = Arc::new(ConsensusThroughputCalculator::new(
1574            None,
1575            state.metrics.clone(),
1576        ));
1577
1578        let consensus_handler_initializer = ConsensusHandlerInitializer::new(
1579            state.clone(),
1580            checkpoint_service.clone(),
1581            epoch_store.clone(),
1582            consensus_adapter.clone(),
1583            throughput_calculator,
1584            backpressure_manager,
1585            config.congestion_log.clone(),
1586        );
1587
1588        info!("Starting consensus manager asynchronously");
1589
1590        // Spawn consensus startup asynchronously to avoid blocking other components
1591        tokio::spawn({
1592            let config = config.clone();
1593            let epoch_store = epoch_store.clone();
1594            let sui_tx_validator = SuiTxValidator::new(
1595                state.clone(),
1596                epoch_store.clone(),
1597                checkpoint_service.clone(),
1598                sui_tx_validator_metrics.clone(),
1599            );
1600            let consensus_manager = consensus_manager.clone();
1601            async move {
1602                consensus_manager
1603                    .start(
1604                        &config,
1605                        epoch_store,
1606                        consensus_handler_initializer,
1607                        sui_tx_validator,
1608                        Some(randomness_receiver_handle),
1609                    )
1610                    .await;
1611            }
1612        });
1613        let replay_waiter = consensus_manager.replay_waiter();
1614
1615        info!("Spawning checkpoint service");
1616        let replay_waiter = if std::env::var("DISABLE_REPLAY_WAITER").is_ok() {
1617            None
1618        } else {
1619            Some(replay_waiter)
1620        };
1621        checkpoint_service
1622            .spawn(epoch_store.clone(), replay_waiter)
1623            .await;
1624
1625        if node_role.is_validator() && epoch_store.authenticator_state_enabled() {
1626            Self::start_jwk_updater(
1627                config,
1628                sui_node_metrics,
1629                state.name,
1630                epoch_store.clone(),
1631                consensus_adapter.clone(),
1632            );
1633        }
1634
1635        if let Some(ctx) = &admission_queue {
1636            ctx.rotate_for_epoch(epoch_store);
1637        }
1638
1639        Ok(ValidatorComponents {
1640            validator_server_handle,
1641            validator_overload_monitor_handle,
1642            consensus_manager,
1643            consensus_store_pruner,
1644            consensus_adapter,
1645            checkpoint_metrics,
1646            sui_tx_validator_metrics,
1647            admission_queue,
1648        })
1649    }
1650
1651    fn build_checkpoint_service(
1652        config: &NodeConfig,
1653        consensus_adapter: Arc<ConsensusAdapter>,
1654        checkpoint_store: Arc<CheckpointStore>,
1655        epoch_store: Arc<AuthorityPerEpochStore>,
1656        state: Arc<AuthorityState>,
1657        state_sync_handle: state_sync::Handle,
1658        state_hasher: Weak<GlobalStateHasher>,
1659        checkpoint_metrics: Arc<CheckpointMetrics>,
1660        node_role: NodeRole,
1661    ) -> Arc<CheckpointService> {
1662        let epoch_start_timestamp_ms = epoch_store.epoch_start_state().epoch_start_timestamp_ms();
1663        let epoch_duration_ms = epoch_store.epoch_start_state().epoch_duration_ms();
1664
1665        debug!(
1666            "Starting checkpoint service with epoch start timestamp {}
1667            and epoch duration {}",
1668            epoch_start_timestamp_ms, epoch_duration_ms
1669        );
1670
1671        let checkpoint_output: Box<dyn CheckpointOutput> = if node_role.is_validator() {
1672            Box::new(SubmitCheckpointToConsensus::new(
1673                consensus_adapter,
1674                state.secret.clone(),
1675                config.protocol_public_key(),
1676                epoch_start_timestamp_ms
1677                    .checked_add(epoch_duration_ms)
1678                    .expect("Overflow calculating next_reconfiguration_timestamp_ms"),
1679                checkpoint_metrics.clone(),
1680            ))
1681        } else {
1682            Box::new(LogCheckpointOutput::new(checkpoint_metrics.clone()))
1683        };
1684
1685        let certified_checkpoint_output = SendCheckpointToStateSync::new(state_sync_handle);
1686
1687        CheckpointService::build(
1688            state.clone(),
1689            checkpoint_store,
1690            epoch_store,
1691            state.get_transaction_cache_reader().clone(),
1692            state_hasher,
1693            checkpoint_output,
1694            Box::new(certified_checkpoint_output),
1695            checkpoint_metrics,
1696        )
1697    }
1698
1699    fn construct_consensus_adapter(
1700        committee: &Committee,
1701        consensus_config: &ConsensusConfig,
1702        authority: AuthorityName,
1703        prometheus_registry: &Registry,
1704        consensus_client: Arc<dyn ConsensusClient>,
1705        checkpoint_store: Arc<CheckpointStore>,
1706        inflight_slot_freed_notify: Arc<tokio::sync::Notify>,
1707    ) -> ConsensusAdapter {
1708        let ca_metrics = ConsensusAdapterMetrics::new(prometheus_registry);
1709        // The consensus adapter allows the authority to send user certificates through consensus.
1710
1711        ConsensusAdapter::new(
1712            consensus_client,
1713            checkpoint_store,
1714            authority,
1715            consensus_config.max_pending_transactions(),
1716            consensus_config.max_pending_transactions() * 2 / committee.num_members(),
1717            ca_metrics,
1718            inflight_slot_freed_notify,
1719        )
1720    }
1721
1722    async fn start_grpc_validator_service(
1723        config: &NodeConfig,
1724        state: Arc<AuthorityState>,
1725        consensus_adapter: Arc<ConsensusAdapter>,
1726        epoch_store: Arc<AuthorityPerEpochStore>,
1727        prometheus_registry: &Registry,
1728        inflight_slot_freed_notify: Arc<tokio::sync::Notify>,
1729    ) -> Result<(SpawnOnce, Option<AdmissionQueueContext>)> {
1730        let overload_config = &config.authority_overload_config;
1731        let admission_queue = overload_config.admission_queue_enabled.then(|| {
1732            let manager = Arc::new(AdmissionQueueManager::new(
1733                consensus_adapter.clone(),
1734                Arc::new(AdmissionQueueMetrics::new(prometheus_registry)),
1735                overload_config.admission_queue_capacity_fraction,
1736                overload_config.admission_queue_failover_timeout,
1737                inflight_slot_freed_notify,
1738            ));
1739            AdmissionQueueContext::spawn(manager, epoch_store)
1740        });
1741        let validator_service = ValidatorService::new(
1742            state.clone(),
1743            consensus_adapter,
1744            Arc::new(ValidatorServiceMetrics::new(prometheus_registry)),
1745            config.policy_config.clone().map(|p| p.client_id_source),
1746            admission_queue.clone(),
1747        );
1748
1749        let mut server_conf = mysten_network::config::Config::new();
1750        server_conf.connect_timeout = Some(DEFAULT_GRPC_CONNECT_TIMEOUT);
1751        server_conf.http2_keepalive_interval = Some(DEFAULT_GRPC_CONNECT_TIMEOUT);
1752        server_conf.http2_keepalive_timeout = Some(DEFAULT_GRPC_CONNECT_TIMEOUT);
1753        server_conf.global_concurrency_limit = config.grpc_concurrency_limit;
1754        server_conf.load_shed = config.grpc_load_shed;
1755        let mut server_builder =
1756            ServerBuilder::from_config(&server_conf, GrpcMetrics::new(prometheus_registry));
1757
1758        server_builder = server_builder.add_service(ValidatorServer::new(validator_service));
1759
1760        let tls_config = sui_tls::create_rustls_server_config(
1761            config.network_key_pair().copy().private(),
1762            SUI_TLS_SERVER_NAME.to_string(),
1763        );
1764
1765        let network_address = config.network_address().clone();
1766
1767        let (ready_tx, ready_rx) = oneshot::channel();
1768
1769        let spawn_once = SpawnOnce::new(ready_rx, async move {
1770            let server = server_builder
1771                .bind(&network_address, Some(tls_config))
1772                .await
1773                .unwrap_or_else(|err| panic!("Failed to bind to {network_address}: {err}"));
1774            let local_addr = server.local_addr();
1775            info!("Listening to traffic on {local_addr}");
1776            ready_tx.send(()).unwrap();
1777            if let Err(err) = server.serve().await {
1778                info!("Server stopped: {err}");
1779            }
1780            info!("Server stopped");
1781        });
1782        Ok((spawn_once, admission_queue))
1783    }
1784
1785    pub fn state(&self) -> Arc<AuthorityState> {
1786        self.state.clone()
1787    }
1788
1789    /// The embedded `sui-rpc-store` index backend, when the node is a
1790    /// fullnode with indexing enabled. Exposes the startup bootstrap
1791    /// decision and per-cohort watermarks for introspection (used by
1792    /// tests to observe restore/resume behavior across restarts without
1793    /// going through the RPC surface).
1794    pub fn embedded_rpc_store(&self) -> Option<&EmbeddedRpcStore> {
1795        self.embedded_rpc_store.as_ref()
1796    }
1797
1798    #[cfg(any(test, msim))]
1799    pub fn connection_monitor_handle_for_testing(
1800        &self,
1801    ) -> &mysten_network::anemo_connection_monitor::ConnectionMonitorHandle {
1802        &self._connection_monitor_handle
1803    }
1804
1805    #[cfg(any(test, msim))]
1806    pub fn address_prober_metrics_for_testing(
1807        &self,
1808    ) -> std::sync::Arc<address_prober::AddressProberMetrics> {
1809        self.address_prober
1810            .as_ref()
1811            .expect("address prober should be running in tests")
1812            .metrics_for_testing()
1813    }
1814
1815    #[cfg(feature = "testing")]
1816    pub fn prometheus_metrics_for_testing(&self) -> Vec<prometheus::proto::MetricFamily> {
1817        self.registry_service.default_registry().gather()
1818    }
1819
1820    pub fn node_role(&self) -> NodeRole {
1821        self.state.load_epoch_store_one_call_per_task().node_role()
1822    }
1823
1824    // Only used for testing because of how epoch store is loaded.
1825    pub fn reference_gas_price_for_testing(&self) -> Result<u64, anyhow::Error> {
1826        self.state.reference_gas_price_for_testing()
1827    }
1828
1829    pub fn clone_committee_store(&self) -> Arc<CommitteeStore> {
1830        self.state.committee_store().clone()
1831    }
1832
1833    pub fn clone_checkpoint_store(&self) -> Arc<CheckpointStore> {
1834        self.checkpoint_store.clone()
1835    }
1836
1837    pub fn clone_authority_store(&self) -> Arc<AuthorityStore> {
1838        self.state.authority_store()
1839    }
1840
1841    pub fn clone_consensus_store(
1842        &self,
1843    ) -> Option<Arc<consensus_core::storage::rocksdb_store::RocksDBStore>> {
1844        self.validator_components
1845            .try_lock()
1846            .ok()?
1847            .as_ref()?
1848            .consensus_manager
1849            .consensus_store()
1850    }
1851
1852    /// Clone an AuthorityAggregator currently used in this node, if the node is a fullnode.
1853    /// After reconfig, Transaction Driver builds a new AuthorityAggregator. The caller
1854    /// of this function will mostly likely want to call this again
1855    /// to get a fresh one.
1856    pub fn clone_authority_aggregator(
1857        &self,
1858    ) -> Option<Arc<AuthorityAggregator<NetworkAuthorityClient>>> {
1859        self.transaction_orchestrator
1860            .as_ref()
1861            .map(|to| to.clone_authority_aggregator())
1862    }
1863
1864    pub fn transaction_orchestrator(
1865        &self,
1866    ) -> Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>> {
1867        self.transaction_orchestrator.clone()
1868    }
1869
1870    /// This function awaits the completion of checkpoint execution of the current epoch,
1871    /// after which it initiates reconfiguration of the entire system.
1872    pub async fn monitor_reconfiguration(
1873        self: Arc<Self>,
1874        mut epoch_store: Arc<AuthorityPerEpochStore>,
1875    ) -> Result<()> {
1876        let checkpoint_executor_metrics =
1877            CheckpointExecutorMetrics::new(&self.registry_service.default_registry());
1878
1879        loop {
1880            let mut hasher_guard = self.global_state_hasher.lock().await;
1881            let hasher = hasher_guard.take().unwrap();
1882            info!(
1883                "Creating checkpoint executor for epoch {}",
1884                epoch_store.epoch()
1885            );
1886            let checkpoint_executor = CheckpointExecutor::new(
1887                epoch_store.clone(),
1888                self.checkpoint_store.clone(),
1889                self.state.clone(),
1890                hasher.clone(),
1891                self.backpressure_manager.clone(),
1892                self.config.checkpoint_executor_config.clone(),
1893                checkpoint_executor_metrics.clone(),
1894                self.subscription_service_checkpoint_sender.clone(),
1895            );
1896
1897            let run_with_range = self.config.run_with_range;
1898
1899            let cur_epoch_store = self.state.load_epoch_store_one_call_per_task();
1900
1901            // Update the current protocol version metric.
1902            self.metrics
1903                .current_protocol_version
1904                .set(cur_epoch_store.protocol_config().version.as_u64() as i64);
1905
1906            // Advertise capabilities to committee, if we are a validator.
1907            // FullNodes that state sync via consensus will also have validator components, by they are not supposed to submit any capabilities.
1908            if let Some(components) = &*self.validator_components.lock().await
1909                && cur_epoch_store.is_validator()
1910            {
1911                // TODO: without this sleep, the consensus message is not delivered reliably.
1912                tokio::time::sleep(Duration::from_millis(1)).await;
1913
1914                let config = cur_epoch_store.protocol_config();
1915                let mut supported_protocol_versions = self
1916                    .config
1917                    .supported_protocol_versions
1918                    .expect("Supported versions should be populated")
1919                    // no need to send digests of versions less than the current version
1920                    .truncate_below(config.version);
1921
1922                while supported_protocol_versions.max > config.version {
1923                    let proposed_protocol_config = ProtocolConfig::get_for_version(
1924                        supported_protocol_versions.max,
1925                        cur_epoch_store.get_chain(),
1926                    );
1927
1928                    if proposed_protocol_config.enable_accumulators()
1929                        && !epoch_store.accumulator_root_exists()
1930                    {
1931                        error!(
1932                            "cannot upgrade to protocol version {:?} because accumulator root does not exist",
1933                            supported_protocol_versions.max
1934                        );
1935                        supported_protocol_versions.max = supported_protocol_versions.max.prev();
1936                    } else {
1937                        break;
1938                    }
1939                }
1940
1941                let binary_config = config.binary_config(None);
1942                let transaction = ConsensusTransaction::new_capability_notification_v2(
1943                    AuthorityCapabilitiesV2::new(
1944                        self.state.name,
1945                        cur_epoch_store.get_chain_identifier().chain(),
1946                        supported_protocol_versions,
1947                        self.state
1948                            .get_available_system_packages(&binary_config)
1949                            .await,
1950                    ),
1951                );
1952                info!(?transaction, "submitting capabilities to consensus");
1953                components.consensus_adapter.submit(
1954                    transaction,
1955                    None,
1956                    &cur_epoch_store,
1957                    None,
1958                    None,
1959                )?;
1960            }
1961
1962            let stop_condition = checkpoint_executor.run_epoch(run_with_range).await;
1963
1964            if stop_condition == StopReason::RunWithRangeCondition {
1965                SuiNode::shutdown(&self).await;
1966                self.shutdown_channel_tx
1967                    .send(run_with_range)
1968                    .expect("RunWithRangeCondition met but failed to send shutdown message");
1969                return Ok(());
1970            }
1971
1972            // Safe to call because we are in the middle of reconfiguration.
1973            let latest_system_state = self
1974                .state
1975                .get_object_cache_reader()
1976                .get_sui_system_state_object_unsafe()
1977                .expect("Read Sui System State object cannot fail");
1978
1979            #[cfg(msim)]
1980            if !self
1981                .sim_state
1982                .sim_safe_mode_expected
1983                .load(Ordering::Relaxed)
1984            {
1985                debug_assert!(!latest_system_state.safe_mode());
1986            }
1987
1988            #[cfg(not(msim))]
1989            debug_assert!(!latest_system_state.safe_mode());
1990
1991            if let Err(err) = self.end_of_epoch_channel.send(latest_system_state.clone())
1992                && self.state.is_fullnode(&cur_epoch_store)
1993            {
1994                warn!(
1995                    "Failed to send end of epoch notification to subscriber: {:?}",
1996                    err
1997                );
1998            }
1999
2000            cur_epoch_store.record_is_safe_mode_metric(latest_system_state.safe_mode());
2001            let new_epoch_start_state = latest_system_state.into_epoch_start_state();
2002
2003            self.auth_agg.store(Arc::new(
2004                self.auth_agg
2005                    .load()
2006                    .recreate_with_new_epoch_start_state(&new_epoch_start_state),
2007            ));
2008
2009            let next_epoch_committee = new_epoch_start_state.get_sui_committee();
2010            let next_epoch = next_epoch_committee.epoch();
2011            assert_eq!(cur_epoch_store.epoch() + 1, next_epoch);
2012
2013            info!(
2014                next_epoch,
2015                "Finished executing all checkpoints in epoch. About to reconfigure the system."
2016            );
2017
2018            fail_point_async!("reconfig_delay");
2019
2020            cur_epoch_store.record_epoch_reconfig_start_time_metric();
2021
2022            update_peer_addresses(
2023                &self.config,
2024                &self.endpoint_manager,
2025                &new_epoch_start_state,
2026                Some(cur_epoch_store.epoch_start_state()),
2027            );
2028
2029            let mut validator_components_lock_guard = self.validator_components.lock().await;
2030
2031            // The following code handles 4 different cases, depending on whether the node
2032            // was a validator in the previous epoch, and whether the node is a validator
2033            // in the new epoch.
2034            let new_epoch_store = self
2035                .reconfigure_state(
2036                    &self.state,
2037                    &cur_epoch_store,
2038                    next_epoch_committee.clone(),
2039                    new_epoch_start_state,
2040                    hasher.clone(),
2041                )
2042                .await;
2043
2044            let new_role = new_epoch_store.node_role();
2045
2046            let new_validator_components = if let Some(ValidatorComponents {
2047                validator_server_handle,
2048                validator_overload_monitor_handle,
2049                consensus_manager,
2050                consensus_store_pruner,
2051                consensus_adapter,
2052                checkpoint_metrics,
2053                sui_tx_validator_metrics,
2054                admission_queue,
2055            }) = validator_components_lock_guard.take()
2056            {
2057                info!("Reconfiguring node (was running consensus).");
2058
2059                consensus_manager.shutdown().await;
2060                info!("Consensus has shut down.");
2061
2062                if let Some(handle) = &self.address_prober {
2063                    handle.leave_committee();
2064                }
2065
2066                info!("Epoch store finished reconfiguration.");
2067
2068                // No other components should be holding a strong reference to state hasher
2069                // at this point. Confirm here before we swap in the new hasher.
2070                let global_state_hasher_metrics = Arc::into_inner(hasher)
2071                    .expect("Object state hasher should have no other references at this point")
2072                    .metrics();
2073                let new_hasher = Arc::new(GlobalStateHasher::new(
2074                    self.state.get_global_state_hash_store().clone(),
2075                    global_state_hasher_metrics,
2076                ));
2077                let weak_hasher = Arc::downgrade(&new_hasher);
2078                *hasher_guard = Some(new_hasher);
2079
2080                consensus_store_pruner.prune(next_epoch).await;
2081
2082                if new_role.runs_consensus() {
2083                    info!("Restarting consensus as {new_role}");
2084                    let components = Self::start_epoch_specific_validator_components(
2085                        &self.config,
2086                        self.state.clone(),
2087                        consensus_adapter,
2088                        self.checkpoint_store.clone(),
2089                        new_epoch_store.clone(),
2090                        self.state_sync_handle.clone(),
2091                        self.randomness_handle.clone(),
2092                        self.randomness_receiver_handle.clone(),
2093                        consensus_manager,
2094                        consensus_store_pruner,
2095                        weak_hasher,
2096                        self.backpressure_manager.clone(),
2097                        validator_server_handle,
2098                        validator_overload_monitor_handle,
2099                        checkpoint_metrics,
2100                        self.metrics.clone(),
2101                        sui_tx_validator_metrics,
2102                        admission_queue,
2103                        new_role,
2104                    )
2105                    .await?;
2106                    self.update_address_prober_epoch(
2107                        &new_epoch_store,
2108                        &components.consensus_manager,
2109                    );
2110                    Some(components)
2111                } else {
2112                    info!(
2113                        "This node has new role {new_role} and no longer runs consensus after reconfiguration"
2114                    );
2115                    None
2116                }
2117            } else {
2118                // No other components should be holding a strong reference to state hasher
2119                // at this point. Confirm here before we swap in the new hasher.
2120                let global_state_hasher_metrics = Arc::into_inner(hasher)
2121                    .expect("Object state hasher should have no other references at this point")
2122                    .metrics();
2123                let new_hasher = Arc::new(GlobalStateHasher::new(
2124                    self.state.get_global_state_hash_store().clone(),
2125                    global_state_hasher_metrics,
2126                ));
2127                let weak_hasher = Arc::downgrade(&new_hasher);
2128                *hasher_guard = Some(new_hasher);
2129
2130                if new_role.runs_consensus() {
2131                    info!("Promoting node to {new_role}, starting consensus components");
2132
2133                    let mut components = Self::construct_validator_components(
2134                        self.config.clone(),
2135                        self.state.clone(),
2136                        Arc::new(next_epoch_committee.clone()),
2137                        new_epoch_store.clone(),
2138                        self.checkpoint_store.clone(),
2139                        self.state_sync_handle.clone(),
2140                        self.randomness_handle.clone(),
2141                        weak_hasher,
2142                        self.backpressure_manager.clone(),
2143                        &self.registry_service,
2144                        self.metrics.clone(),
2145                        self.checkpoint_metrics.clone(),
2146                        new_role,
2147                        self.randomness_receiver_handle.clone(),
2148                    )
2149                    .await?;
2150
2151                    if new_role.is_validator() {
2152                        components.validator_server_handle = Some(
2153                            components
2154                                .validator_server_handle
2155                                .take()
2156                                .unwrap()
2157                                .start()
2158                                .await,
2159                        );
2160
2161                        self.endpoint_manager
2162                            .set_consensus_address_updater(components.consensus_manager.clone());
2163                    }
2164
2165                    self.update_address_prober_epoch(
2166                        &new_epoch_store,
2167                        &components.consensus_manager,
2168                    );
2169                    Some(components)
2170                } else {
2171                    None
2172                }
2173            };
2174            *validator_components_lock_guard = new_validator_components;
2175
2176            // Force releasing current epoch store DB handle, because the
2177            // Arc<AuthorityPerEpochStore> may linger.
2178            cur_epoch_store.release_db_handles();
2179
2180            if cfg!(msim)
2181                && !matches!(
2182                    self.config
2183                        .authority_store_pruning_config
2184                        .num_epochs_to_retain_for_checkpoints(),
2185                    None | Some(u64::MAX) | Some(0)
2186                )
2187            {
2188                self.state
2189                    .prune_checkpoints_for_eligible_epochs_for_testing(
2190                        self.config.clone(),
2191                        sui_core::authority::authority_store_pruner::AuthorityStorePruningMetrics::new_for_test(),
2192                    )
2193                    .await?;
2194            }
2195
2196            epoch_store = new_epoch_store;
2197            info!("Reconfiguration finished");
2198        }
2199    }
2200
2201    async fn shutdown(&self) {
2202        if let Some(validator_components) = &*self.validator_components.lock().await {
2203            validator_components.consensus_manager.shutdown().await;
2204        }
2205    }
2206
2207    async fn reconfigure_state(
2208        &self,
2209        state: &Arc<AuthorityState>,
2210        cur_epoch_store: &AuthorityPerEpochStore,
2211        next_epoch_committee: Committee,
2212        next_epoch_start_system_state: EpochStartSystemState,
2213        global_state_hasher: Arc<GlobalStateHasher>,
2214    ) -> Arc<AuthorityPerEpochStore> {
2215        let next_epoch = next_epoch_committee.epoch();
2216
2217        let last_checkpoint = self
2218            .checkpoint_store
2219            .get_epoch_last_checkpoint(cur_epoch_store.epoch())
2220            .expect("Error loading last checkpoint for current epoch")
2221            .expect("Could not load last checkpoint for current epoch");
2222
2223        let last_checkpoint_seq = *last_checkpoint.sequence_number();
2224
2225        assert_eq!(
2226            Some(last_checkpoint_seq),
2227            self.checkpoint_store
2228                .get_highest_executed_checkpoint_seq_number()
2229                .expect("Error loading highest executed checkpoint sequence number")
2230        );
2231
2232        let epoch_start_configuration = EpochStartConfiguration::new(
2233            next_epoch_start_system_state,
2234            *last_checkpoint.digest(),
2235            state.get_object_store().as_ref(),
2236            EpochFlag::default_flags_for_new_epoch(&state.config),
2237        )
2238        .expect("EpochStartConfiguration construction cannot fail");
2239
2240        let new_epoch_store = self
2241            .state
2242            .reconfigure(
2243                cur_epoch_store,
2244                self.config.supported_protocol_versions.unwrap(),
2245                next_epoch_committee,
2246                epoch_start_configuration,
2247                global_state_hasher,
2248                &self.config.expensive_safety_check_config,
2249                last_checkpoint_seq,
2250            )
2251            .await
2252            .expect("Reconfigure authority state cannot fail");
2253        info!(next_epoch, "Node State has been reconfigured");
2254        assert_eq!(next_epoch, new_epoch_store.epoch());
2255        self.state.get_reconfig_api().update_epoch_flags_metrics(
2256            cur_epoch_store.epoch_start_config().flags(),
2257            new_epoch_store.epoch_start_config().flags(),
2258        );
2259
2260        new_epoch_store
2261    }
2262
2263    pub fn get_config(&self) -> &NodeConfig {
2264        &self.config
2265    }
2266
2267    pub fn randomness_handle(&self) -> randomness::Handle {
2268        self.randomness_handle.clone()
2269    }
2270
2271    pub fn state_sync_handle(&self) -> state_sync::Handle {
2272        self.state_sync_handle.clone()
2273    }
2274
2275    pub fn endpoint_manager(&self) -> &EndpointManager {
2276        &self.endpoint_manager
2277    }
2278
2279    pub async fn address_prober_report(&self) -> Option<address_prober::ProbeReport> {
2280        match &self.address_prober {
2281            Some(handle) => handle.probe_report().await,
2282            None => None,
2283        }
2284    }
2285
2286    /// Get a short prefix of a digest for metric labels
2287    fn get_digest_prefix(digest: impl std::fmt::Display) -> String {
2288        let digest_str = digest.to_string();
2289        if digest_str.len() >= 8 {
2290            digest_str[0..8].to_string()
2291        } else {
2292            digest_str
2293        }
2294    }
2295
2296    /// Check for previously detected forks and handle them appropriately.
2297    /// For validators with fork recovery config, clear the fork if it matches the recovery config.
2298    /// For all other cases, block node startup if a fork is detected.
2299    async fn check_and_recover_forks(
2300        checkpoint_store: &CheckpointStore,
2301        checkpoint_metrics: &CheckpointMetrics,
2302        fork_recovery: Option<&ForkRecoveryConfig>,
2303        build_version: &str,
2304    ) -> Result<()> {
2305        // Manual recovery from operator-supplied overrides; runs regardless of fork_crash_behavior
2306        // and only acts on the checkpoints / transactions explicitly listed in the config.
2307        if let Some(recovery) = fork_recovery {
2308            Self::try_recover_checkpoint_fork(checkpoint_store, recovery)?;
2309            Self::try_recover_transaction_fork(checkpoint_store, recovery)?;
2310        }
2311
2312        let behavior = fork_recovery
2313            .map(|fr| fr.fork_crash_behavior)
2314            .unwrap_or_default();
2315
2316        match behavior {
2317            ForkCrashBehavior::RecoverOncePerVersion => {
2318                Self::try_recover_forks(checkpoint_store, checkpoint_metrics, build_version)?;
2319            }
2320            ForkCrashBehavior::AwaitForkRecovery | ForkCrashBehavior::ReturnError => {}
2321        }
2322
2323        if let Some(fork_info) = checkpoint_store
2324            .get_checkpoint_fork_detected()
2325            .map_err(|e| {
2326                error!("Failed to check for checkpoint fork: {:?}", e);
2327                e
2328            })?
2329        {
2330            Self::handle_checkpoint_fork(
2331                fork_info.checkpoint_seq,
2332                fork_info.checkpoint_digest,
2333                checkpoint_metrics,
2334                fork_recovery,
2335            )
2336            .await?;
2337        }
2338        if let Some(fork_info) = checkpoint_store
2339            .get_transaction_fork_detected()
2340            .map_err(|e| {
2341                error!("Failed to check for transaction fork: {:?}", e);
2342                e
2343            })?
2344        {
2345            Self::handle_transaction_fork(
2346                fork_info.tx_digest,
2347                fork_info.expected_effects_digest,
2348                fork_info.actual_effects_digest,
2349                checkpoint_metrics,
2350                fork_recovery,
2351            )
2352            .await?;
2353        }
2354
2355        Ok(())
2356    }
2357
2358    /// Manual recovery: for each `seq -> digest` override, if the locally computed checkpoint at
2359    /// `seq` differs, clear locally computed checkpoints from `seq` (and the checkpoint fork marker)
2360    /// so the node rebuilds toward the operator-specified digest.
2361    fn try_recover_checkpoint_fork(
2362        checkpoint_store: &CheckpointStore,
2363        recovery: &ForkRecoveryConfig,
2364    ) -> Result<()> {
2365        if recovery.checkpoint_overrides.is_empty() {
2366            return Ok(());
2367        }
2368
2369        for (seq, expected_digest_str) in &recovery.checkpoint_overrides {
2370            let Ok(expected_digest) = CheckpointDigest::from_str(expected_digest_str) else {
2371                anyhow::bail!(
2372                    "Invalid checkpoint digest override for seq {}: {}",
2373                    seq,
2374                    expected_digest_str
2375                );
2376            };
2377
2378            if let Some(local_summary) = checkpoint_store.get_locally_computed_checkpoint(*seq)? {
2379                let local_digest = sui_types::message_envelope::Message::digest(&local_summary);
2380                if local_digest != expected_digest {
2381                    info!(
2382                        seq,
2383                        local = %Self::get_digest_prefix(local_digest),
2384                        expected = %Self::get_digest_prefix(expected_digest),
2385                        "Fork recovery: clearing locally_computed_checkpoints from {} due to digest mismatch",
2386                        seq
2387                    );
2388                    checkpoint_store
2389                        .clear_locally_computed_checkpoints_from(*seq)
2390                        .context(
2391                            "Failed to clear locally computed checkpoints from override seq",
2392                        )?;
2393                }
2394            }
2395        }
2396
2397        if let Some(fork_info) = checkpoint_store.get_checkpoint_fork_detected()?
2398            && recovery
2399                .checkpoint_overrides
2400                .contains_key(&fork_info.checkpoint_seq)
2401        {
2402            info!(
2403                "Fork recovery enabled: clearing checkpoint fork at seq {} with digest {:?}",
2404                fork_info.checkpoint_seq, fork_info.checkpoint_digest
2405            );
2406            checkpoint_store
2407                .clear_checkpoint_fork_detected()
2408                .expect("Failed to clear checkpoint fork detected marker");
2409        }
2410        Ok(())
2411    }
2412
2413    /// Manual recovery: if the forked transaction is listed in transaction_overrides, clear its fork
2414    /// marker so the node proceeds on restart.
2415    fn try_recover_transaction_fork(
2416        checkpoint_store: &CheckpointStore,
2417        recovery: &ForkRecoveryConfig,
2418    ) -> Result<()> {
2419        if recovery.transaction_overrides.is_empty() {
2420            return Ok(());
2421        }
2422
2423        if let Some(fork_info) = checkpoint_store.get_transaction_fork_detected()?
2424            && recovery
2425                .transaction_overrides
2426                .contains_key(&fork_info.tx_digest.to_string())
2427        {
2428            info!(
2429                "Fork recovery enabled: clearing transaction fork for tx {:?}",
2430                fork_info.tx_digest
2431            );
2432            checkpoint_store
2433                .clear_transaction_fork_detected()
2434                .expect("Failed to clear transaction fork detected marker");
2435        }
2436        Ok(())
2437    }
2438
2439    /// Auto-recovery: clear fork markers (the affected seq/tx is read from the markers) so the
2440    /// node re-derives canonically. A marker is cleared only if both gates pass:
2441    ///
2442    /// - Version gate: the marker was recorded by a different binary version than the one now
2443    ///   running. The binary that forked would deterministically fork again, so clearing under
2444    ///   it would only add a second equivocation; the node hangs until a corrected binary is
2445    ///   deployed.
2446    /// - Certification gate: the marker records the certified checkpoint the node diverged
2447    ///   from. Markers carry it only when detection compared against a certificate already
2448    ///   durably persisted locally, so its presence proves the network certified the canonical
2449    ///   outcome. Recovery is deliberate equivocation — the node may have already signed the
2450    ///   forked result and will sign a different one after re-deriving — which is safe only
2451    ///   under that proof: a quorum certificate is irrevocable (a conflicting certificate would
2452    ///   require f+1 double-signers), so re-signing can no longer influence what finalizes.
2453    ///   Self-divergence markers (the node disagreeing with its own prior result rather than a
2454    ///   certificate) carry no certified reference and never pass; the node halts awaiting
2455    ///   operator intervention.
2456    fn try_recover_forks(
2457        checkpoint_store: &CheckpointStore,
2458        checkpoint_metrics: &CheckpointMetrics,
2459        build_version: &str,
2460    ) -> Result<()> {
2461        if let Some(fork_info) = checkpoint_store.get_checkpoint_fork_detected()? {
2462            if fork_info.binary_version == build_version {
2463                error!(
2464                    checkpoint_seq = fork_info.checkpoint_seq,
2465                    build_version,
2466                    "Fork recovery blocked: this binary version produced the checkpoint fork and \
2467                     would fork again. Halting; deploy a corrected binary to recover."
2468                );
2469                checkpoint_metrics
2470                    .fork_auto_recovery_awaiting_new_binary
2471                    .set(1);
2472            } else if fork_info.certified_checkpoint_digest.is_none() {
2473                // The builder re-derived a previously computed checkpoint differently: the fork
2474                // is against the node's own prior result, not a certified checkpoint, so there
2475                // is no canonical outcome to converge toward.
2476                error!(
2477                    checkpoint_seq = fork_info.checkpoint_seq,
2478                    checkpoint_digest = ?fork_info.checkpoint_digest,
2479                    "Fork recovery blocked: the builder re-derived its own previous checkpoint \
2480                     differently, so there is no certified checkpoint proving the canonical \
2481                     outcome to converge toward. Halting awaiting operator intervention."
2482                );
2483                checkpoint_metrics
2484                    .fork_auto_recovery_blocked_uncertified
2485                    .set(1);
2486            } else {
2487                info!(
2488                    checkpoint_seq = fork_info.checkpoint_seq,
2489                    checkpoint_digest = ?fork_info.checkpoint_digest,
2490                    forked_binary_version = ?fork_info.binary_version,
2491                    build_version,
2492                    "Fork recovery: clearing checkpoint fork and locally computed checkpoints \
2493                     from the forked sequence so the builder rebuilds toward the certified \
2494                     checkpoint"
2495                );
2496                checkpoint_store
2497                    .clear_locally_computed_checkpoints_from(fork_info.checkpoint_seq)
2498                    .context("Failed to clear locally computed checkpoints during fork recovery")?;
2499                checkpoint_store.clear_checkpoint_fork_detected()?;
2500                checkpoint_metrics.checkpoint_fork_auto_recovered.set(1);
2501            }
2502        }
2503
2504        if let Some(fork_info) = checkpoint_store.get_transaction_fork_detected()? {
2505            if fork_info.binary_version == build_version {
2506                error!(
2507                    tx_digest = ?fork_info.tx_digest,
2508                    build_version,
2509                    "Fork recovery blocked: this binary version produced the transaction fork and \
2510                     would fork again. Halting; deploy a corrected binary to recover."
2511                );
2512                checkpoint_metrics
2513                    .fork_auto_recovery_awaiting_new_binary
2514                    .set(1);
2515            } else if fork_info.certified_checkpoint_seq.is_none() {
2516                error!(
2517                    tx_digest = ?fork_info.tx_digest,
2518                    "Fork recovery blocked: the expected effects of the forked transaction did \
2519                     not come from a certified checkpoint (they came from this validator's own \
2520                     previously signed effects), so the network has not provably certified the \
2521                     canonical outcome. Halting awaiting operator intervention."
2522                );
2523                checkpoint_metrics
2524                    .fork_auto_recovery_blocked_uncertified
2525                    .set(1);
2526            } else {
2527                info!(
2528                    tx_digest = ?fork_info.tx_digest,
2529                    expected_effects = ?fork_info.expected_effects_digest,
2530                    actual_effects = ?fork_info.actual_effects_digest,
2531                    certified_checkpoint_seq = ?fork_info.certified_checkpoint_seq,
2532                    forked_binary_version = ?fork_info.binary_version,
2533                    build_version,
2534                    "Fork recovery: clearing transaction fork; re-execution will converge toward \
2535                     the canonical certified effects"
2536                );
2537                checkpoint_store.clear_transaction_fork_detected()?;
2538                checkpoint_metrics.transaction_fork_auto_recovered.set(1);
2539            }
2540        }
2541
2542        Ok(())
2543    }
2544
2545    fn get_current_timestamp() -> u64 {
2546        std::time::SystemTime::now()
2547            .duration_since(std::time::SystemTime::UNIX_EPOCH)
2548            .unwrap()
2549            .as_secs()
2550    }
2551
2552    async fn handle_checkpoint_fork(
2553        checkpoint_seq: u64,
2554        checkpoint_digest: CheckpointDigest,
2555        checkpoint_metrics: &CheckpointMetrics,
2556        fork_recovery: Option<&ForkRecoveryConfig>,
2557    ) -> Result<()> {
2558        checkpoint_metrics
2559            .checkpoint_fork_crash_mode
2560            .with_label_values(&[
2561                &checkpoint_seq.to_string(),
2562                &Self::get_digest_prefix(checkpoint_digest),
2563                &Self::get_current_timestamp().to_string(),
2564            ])
2565            .set(1);
2566
2567        let behavior = fork_recovery
2568            .map(|fr| fr.fork_crash_behavior)
2569            .unwrap_or_default();
2570
2571        match behavior {
2572            ForkCrashBehavior::AwaitForkRecovery | ForkCrashBehavior::RecoverOncePerVersion => {
2573                error!(
2574                    checkpoint_seq = checkpoint_seq,
2575                    checkpoint_digest = ?checkpoint_digest,
2576                    "Checkpoint fork detected! Node startup halted. Sleeping indefinitely."
2577                );
2578                futures::future::pending::<()>().await;
2579                unreachable!("pending() should never return");
2580            }
2581            ForkCrashBehavior::ReturnError => {
2582                error!(
2583                    checkpoint_seq = checkpoint_seq,
2584                    checkpoint_digest = ?checkpoint_digest,
2585                    "Checkpoint fork detected! Returning error."
2586                );
2587                Err(anyhow::anyhow!(
2588                    "Checkpoint fork detected! checkpoint_seq: {}, checkpoint_digest: {:?}",
2589                    checkpoint_seq,
2590                    checkpoint_digest
2591                ))
2592            }
2593        }
2594    }
2595
2596    async fn handle_transaction_fork(
2597        tx_digest: TransactionDigest,
2598        expected_effects_digest: TransactionEffectsDigest,
2599        actual_effects_digest: TransactionEffectsDigest,
2600        checkpoint_metrics: &CheckpointMetrics,
2601        fork_recovery: Option<&ForkRecoveryConfig>,
2602    ) -> Result<()> {
2603        checkpoint_metrics
2604            .transaction_fork_crash_mode
2605            .with_label_values(&[
2606                &Self::get_digest_prefix(tx_digest),
2607                &Self::get_digest_prefix(expected_effects_digest),
2608                &Self::get_digest_prefix(actual_effects_digest),
2609                &Self::get_current_timestamp().to_string(),
2610            ])
2611            .set(1);
2612
2613        let behavior = fork_recovery
2614            .map(|fr| fr.fork_crash_behavior)
2615            .unwrap_or_default();
2616
2617        match behavior {
2618            ForkCrashBehavior::AwaitForkRecovery | ForkCrashBehavior::RecoverOncePerVersion => {
2619                error!(
2620                    tx_digest = ?tx_digest,
2621                    expected_effects_digest = ?expected_effects_digest,
2622                    actual_effects_digest = ?actual_effects_digest,
2623                    "Transaction fork detected! Node startup halted. Sleeping indefinitely."
2624                );
2625                futures::future::pending::<()>().await;
2626                unreachable!("pending() should never return");
2627            }
2628            ForkCrashBehavior::ReturnError => {
2629                error!(
2630                    tx_digest = ?tx_digest,
2631                    expected_effects_digest = ?expected_effects_digest,
2632                    actual_effects_digest = ?actual_effects_digest,
2633                    "Transaction fork detected! Returning error."
2634                );
2635                Err(anyhow::anyhow!(
2636                    "Transaction fork detected! tx_digest: {:?}, expected_effects: {:?}, actual_effects: {:?}",
2637                    tx_digest,
2638                    expected_effects_digest,
2639                    actual_effects_digest
2640                ))
2641            }
2642        }
2643    }
2644}
2645
2646#[cfg(not(msim))]
2647impl SuiNode {
2648    async fn fetch_jwks(
2649        _authority: AuthorityName,
2650        provider: &OIDCProvider,
2651    ) -> SuiResult<Vec<(JwkId, JWK)>> {
2652        use fastcrypto_zkp::bn254::zk_login::fetch_jwks;
2653        use sui_types::error::SuiErrorKind;
2654        let client = reqwest::Client::new();
2655        fetch_jwks(provider, &client, true)
2656            .await
2657            .map_err(|_| SuiErrorKind::JWKRetrievalError.into())
2658    }
2659}
2660
2661#[cfg(msim)]
2662impl SuiNode {
2663    pub fn get_sim_node_id(&self) -> sui_simulator::task::NodeId {
2664        self.sim_state.sim_node.id()
2665    }
2666
2667    pub fn set_safe_mode_expected(&self, new_value: bool) {
2668        info!("Setting safe mode expected to {}", new_value);
2669        self.sim_state
2670            .sim_safe_mode_expected
2671            .store(new_value, Ordering::Relaxed);
2672    }
2673
2674    #[allow(unused_variables)]
2675    async fn fetch_jwks(
2676        authority: AuthorityName,
2677        provider: &OIDCProvider,
2678    ) -> SuiResult<Vec<(JwkId, JWK)>> {
2679        get_jwk_injector()(authority, provider)
2680    }
2681}
2682
2683enum SpawnOnce {
2684    // Mutex is only needed to make SpawnOnce Send
2685    Unstarted(oneshot::Receiver<()>, Mutex<BoxFuture<'static, ()>>),
2686    #[allow(unused)]
2687    Started(JoinHandle<()>),
2688}
2689
2690impl SpawnOnce {
2691    pub fn new(
2692        ready_rx: oneshot::Receiver<()>,
2693        future: impl Future<Output = ()> + Send + 'static,
2694    ) -> Self {
2695        Self::Unstarted(ready_rx, Mutex::new(Box::pin(future)))
2696    }
2697
2698    pub async fn start(self) -> Self {
2699        match self {
2700            Self::Unstarted(ready_rx, future) => {
2701                let future = future.into_inner();
2702                let handle = tokio::spawn(future);
2703                ready_rx.await.unwrap();
2704                Self::Started(handle)
2705            }
2706            Self::Started(_) => self,
2707        }
2708    }
2709}
2710
2711/// Updates trusted peer addresses in the p2p network (for nodes configured as validators).
2712/// When `prev_epoch_start_state` is provided, validators that are no longer in the committee
2713/// have their Chain addresses cleared.
2714fn update_peer_addresses(
2715    config: &NodeConfig,
2716    endpoint_manager: &EndpointManager,
2717    epoch_start_state: &EpochStartSystemState,
2718    prev_epoch_start_state: Option<&EpochStartSystemState>,
2719) {
2720    if config.consensus_config().is_none() {
2721        return;
2722    }
2723    let new_peers: HashSet<PeerId> = epoch_start_state
2724        .get_validator_as_p2p_peers(config.protocol_public_key())
2725        .into_iter()
2726        .map(|(peer_id, address)| {
2727            endpoint_manager
2728                .update_endpoint(
2729                    EndpointId::P2p(peer_id),
2730                    AddressSource::Chain,
2731                    vec![address],
2732                )
2733                .expect("Updating peer addresses should not fail");
2734            peer_id
2735        })
2736        .collect();
2737
2738    // Clear Chain addresses for validators that left the committee.
2739    if let Some(prev) = prev_epoch_start_state {
2740        for (peer_id, _) in prev.get_validator_as_p2p_peers(config.protocol_public_key()) {
2741            if !new_peers.contains(&peer_id) {
2742                endpoint_manager
2743                    .update_endpoint(EndpointId::P2p(peer_id), AddressSource::Chain, vec![])
2744                    .expect("Clearing peer addresses should not fail");
2745            }
2746        }
2747    }
2748}
2749
2750fn build_kv_store(
2751    state: &Arc<AuthorityState>,
2752    config: &NodeConfig,
2753    registry: &Registry,
2754) -> Result<Arc<TransactionKeyValueStore>> {
2755    let metrics = KeyValueStoreMetrics::new(registry);
2756    let db_store = TransactionKeyValueStore::new("rocksdb", metrics.clone(), state.clone());
2757
2758    let base_url = &config.transaction_kv_store_read_config.base_url;
2759
2760    if base_url.is_empty() {
2761        info!("no http kv store url provided, using local db only");
2762        return Ok(Arc::new(db_store));
2763    }
2764
2765    let base_url: url::Url = base_url.parse().tap_err(|e| {
2766        error!(
2767            "failed to parse config.transaction_kv_store_config.base_url ({:?}) as url: {}",
2768            base_url, e
2769        )
2770    })?;
2771
2772    let network_str = match state.get_chain_identifier().chain() {
2773        Chain::Mainnet => "/mainnet",
2774        _ => {
2775            info!("using local db only for kv store");
2776            return Ok(Arc::new(db_store));
2777        }
2778    };
2779
2780    let base_url = base_url.join(network_str)?.to_string();
2781    let http_store = HttpKVStore::new_kv(
2782        &base_url,
2783        config.transaction_kv_store_read_config.cache_size,
2784        metrics.clone(),
2785    )?;
2786    info!("using local key-value store with fallback to http key-value store");
2787    Ok(Arc::new(FallbackTransactionKVStore::new_kv(
2788        db_store,
2789        http_store,
2790        metrics,
2791        "json_rpc_fallback",
2792    )))
2793}
2794
2795async fn build_json_rpc_router(
2796    state: &Arc<AuthorityState>,
2797    transaction_orchestrator: &Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>>,
2798    config: &NodeConfig,
2799    prometheus_registry: &Registry,
2800) -> Result<axum::Router> {
2801    let traffic_controller = state.traffic_controller.clone();
2802    let mut server = JsonRpcServerBuilder::new(
2803        env!("CARGO_PKG_VERSION"),
2804        prometheus_registry,
2805        traffic_controller,
2806        config.policy_config.clone(),
2807    );
2808
2809    let kv_store = build_kv_store(state, config, prometheus_registry)?;
2810
2811    let metrics = Arc::new(JsonRpcMetrics::new(prometheus_registry));
2812    server.register_module(ReadApi::new(
2813        state.clone(),
2814        kv_store.clone(),
2815        metrics.clone(),
2816    ))?;
2817    server.register_module(CoinReadApi::new(
2818        state.clone(),
2819        kv_store.clone(),
2820        metrics.clone(),
2821    ))?;
2822
2823    // if run_with_range is enabled we want to prevent any transactions
2824    // run_with_range = None is normal operating conditions
2825    if config.run_with_range.is_none() {
2826        server.register_module(TransactionBuilderApi::new(state.clone()))?;
2827    }
2828    server.register_module(GovernanceReadApi::new(state.clone(), metrics.clone()))?;
2829    server.register_module(BridgeReadApi::new(state.clone(), metrics.clone()))?;
2830
2831    if let Some(transaction_orchestrator) = transaction_orchestrator {
2832        server.register_module(TransactionExecutionApi::new(
2833            state.clone(),
2834            transaction_orchestrator.clone(),
2835            metrics.clone(),
2836        ))?;
2837    }
2838
2839    let name_service_config = if let (
2840        Some(package_address),
2841        Some(registry_id),
2842        Some(reverse_registry_id),
2843    ) = (
2844        config.name_service_package_address,
2845        config.name_service_registry_id,
2846        config.name_service_reverse_registry_id,
2847    ) {
2848        sui_name_service::NameServiceConfig::new(package_address, registry_id, reverse_registry_id)
2849    } else {
2850        match state.get_chain_identifier().chain() {
2851            Chain::Mainnet => sui_name_service::NameServiceConfig::mainnet(),
2852            Chain::Testnet => sui_name_service::NameServiceConfig::testnet(),
2853            Chain::Unknown => sui_name_service::NameServiceConfig::default(),
2854        }
2855    };
2856
2857    server.register_module(IndexerApi::new(
2858        state.clone(),
2859        ReadApi::new(state.clone(), kv_store.clone(), metrics.clone()),
2860        kv_store,
2861        name_service_config,
2862        metrics,
2863        config.indexer_max_subscriptions,
2864    ))?;
2865    server.register_module(MoveUtils::new(state.clone()))?;
2866
2867    let server_type = config.jsonrpc_server_type();
2868
2869    Ok(server.to_router(server_type).await?)
2870}
2871
2872/// Remove the on-disk directory of the legacy `rpc-index` backend.
2873///
2874/// The embedded `sui-rpc-store` replaced the `RpcIndexStore` backend, which
2875/// wrote to `<db_path>/rpc-index`; that data is now dead. Remove it on startup
2876/// so a node upgraded from an older version does not leave it lingering and
2877/// wasting disk. Best-effort: a node that never ran the legacy backend has
2878/// nothing to remove, and a failure to remove stale data must not block
2879/// startup.
2880fn remove_legacy_rpc_index_store(db_path: &Path) {
2881    let legacy_dir = db_path.join("rpc-index");
2882    match std::fs::remove_dir_all(&legacy_dir) {
2883        Ok(()) => info!(
2884            "removed legacy rpc-index directory {}",
2885            legacy_dir.display()
2886        ),
2887        // The common case: the node never ran the legacy backend, or it was
2888        // already cleaned up on a prior startup.
2889        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2890        Err(e) => warn!(
2891            "failed to remove legacy rpc-index directory {}: {e:?}",
2892            legacy_dir.display()
2893        ),
2894    }
2895}
2896
2897async fn build_http_servers(
2898    state: Arc<AuthorityState>,
2899    store: RocksDbStore,
2900    transaction_orchestrator: &Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>>,
2901    config: &NodeConfig,
2902    prometheus_registry: &Registry,
2903    server_version: ServerVersion,
2904    node_role: NodeRole,
2905    embedded_rpc_store: Option<&EmbeddedRpcStore>,
2906) -> Result<(
2907    HttpServers,
2908    Option<tokio::sync::broadcast::Sender<Arc<Checkpoint>>>,
2909)> {
2910    // Validators do not expose these APIs
2911    if !node_role.is_fullnode() {
2912        return Ok((HttpServers::default(), None));
2913    }
2914
2915    info!("starting rpc service with config: {:?}", config.rpc);
2916
2917    let mut router = axum::Router::new();
2918
2919    // The JSON-RPC service can be disabled independently of the gRPC/REST
2920    // service and of JSON-RPC indexing, so that a node can keep indexing
2921    // without exposing the JSON-RPC endpoints.
2922    if config.json_rpc_enabled() {
2923        router = router.merge(
2924            build_json_rpc_router(
2925                &state,
2926                transaction_orchestrator,
2927                config,
2928                prometheus_registry,
2929            )
2930            .await?,
2931        );
2932    } else {
2933        info!("json-rpc service is disabled");
2934    }
2935
2936    // When the embedded rpc-store is active, gate checkpoint delivery on the
2937    // index so a client that waits for a checkpoint can immediately read its
2938    // indexed state (matching the legacy synchronously-committed index).
2939    let indexed_checkpoint = embedded_rpc_store.map(|embedded| embedded.indexed_checkpoint_fn());
2940    let subscription_watermark_interval = config
2941        .rpc
2942        .as_ref()
2943        .and_then(|rpc| rpc.subscription_watermark_interval);
2944    let subscription_max_subscribers = config
2945        .rpc
2946        .as_ref()
2947        .and_then(|rpc| rpc.subscription_max_subscribers);
2948    let subscription_shards = config.rpc.as_ref().and_then(|rpc| rpc.subscription_shards);
2949    let (subscription_service_checkpoint_sender, subscription_service_handle) =
2950        SubscriptionService::build(
2951            prometheus_registry,
2952            indexed_checkpoint,
2953            subscription_watermark_interval,
2954            subscription_max_subscribers,
2955            subscription_shards,
2956        );
2957    let rpc_router = {
2958        // Serve the index read paths from the embedded rpc-store when it
2959        // is enabled. Raw chain data comes from the perpetual / checkpoint
2960        // stores either way.
2961        let reader: Arc<dyn RpcStateReader> = match embedded_rpc_store {
2962            Some(embedded) => Arc::new(RpcStoreReadStore::new(
2963                state.clone(),
2964                store,
2965                embedded.reader(),
2966            )),
2967            None => Arc::new(RestReadStore::new(state.clone(), store)),
2968        };
2969        let mut rpc_service = sui_rpc_api::RpcService::new(reader);
2970        rpc_service.with_server_version(server_version);
2971
2972        if let Some(config) = config.rpc.clone() {
2973            config.validate()?;
2974            rpc_service.with_config(config);
2975        }
2976
2977        rpc_service.with_metrics(RpcMetrics::new(prometheus_registry));
2978        rpc_service.with_subscription_service(subscription_service_handle);
2979
2980        if let Some(transaction_orchestrator) = transaction_orchestrator {
2981            rpc_service.with_executor(transaction_orchestrator.clone())
2982        }
2983
2984        rpc_service.into_router().await
2985    };
2986
2987    let layers = ServiceBuilder::new()
2988        .map_request(|mut request: axum::http::Request<_>| {
2989            if let Some(connect_info) = request.extensions().get::<sui_http::ConnectInfo>() {
2990                let axum_connect_info = axum::extract::ConnectInfo(connect_info.remote_addr);
2991                request.extensions_mut().insert(axum_connect_info);
2992            }
2993            request
2994        })
2995        .layer(axum::middleware::from_fn(server_timing_middleware))
2996        // Setup a permissive CORS policy
2997        .layer(
2998            tower_http::cors::CorsLayer::new()
2999                .allow_methods([http::Method::GET, http::Method::POST])
3000                .allow_origin(tower_http::cors::Any)
3001                .allow_headers(tower_http::cors::Any)
3002                .expose_headers(tower_http::cors::Any),
3003        );
3004
3005    router = router.merge(rpc_router).layer(layers);
3006
3007    // On top of sui-http's hardened defaults (bounded concurrent streams;
3008    // transport keepalives stay disabled by default), bound connection
3009    // lifetime: GOAWAY at the configured age and force-close after the grace
3010    // period. The hard close is the only server-side mechanism that reclaims
3011    // streams wedged behind HTTP/2 flow-control windows that a stalled peer
3012    // never reopens, and connection age also bounds how long a vanished peer
3013    // can pin connection state, which keepalives would otherwise detect.
3014    let server_config = {
3015        let rpc_config = config.rpc().cloned().unwrap_or_default();
3016        let mut server_config = sui_http::Config::default()
3017            .max_connection_age_grace(rpc_config.max_connection_age_grace());
3018        if let Some(age) = rpc_config.max_connection_age() {
3019            server_config = server_config.max_connection_age(age);
3020        }
3021        server_config
3022    };
3023
3024    let https = if let Some((tls_config, https_address)) = config
3025        .rpc()
3026        .and_then(|config| config.tls_config().map(|tls| (tls, config.https_address())))
3027    {
3028        let tls_server_config = https_rustls_config(tls_config.cert(), tls_config.key())?;
3029        let https = sui_http::Builder::new()
3030            .config(server_config.clone())
3031            .tls_config(tls_server_config)
3032            .serve(https_address, router.clone())
3033            .map_err(|e| anyhow::anyhow!(e))?;
3034
3035        info!(
3036            https_address =? https.local_addr(),
3037            "HTTPS rpc server listening on {}",
3038            https.local_addr()
3039        );
3040
3041        Some(https)
3042    } else {
3043        None
3044    };
3045
3046    let http = sui_http::Builder::new()
3047        .config(server_config)
3048        .serve(&config.json_rpc_address, router)
3049        .map_err(|e| anyhow::anyhow!(e))?;
3050
3051    info!(
3052        http_address =? http.local_addr(),
3053        "HTTP rpc server listening on {}",
3054        http.local_addr()
3055    );
3056
3057    Ok((
3058        HttpServers {
3059            http: Some(http),
3060            https,
3061        },
3062        Some(subscription_service_checkpoint_sender),
3063    ))
3064}
3065
3066/// Builds the HTTPS RPC server's rustls config from PEM files, pinning the
3067/// ring crypto provider.
3068///
3069/// `sui_http::Builder::tls_single_cert` resolves the provider from rustls
3070/// crate features and panics at runtime when more than one provider feature is
3071/// enabled in the final binary (e.g. `aws-lc-rs` is pulled in through
3072/// `aws-config` in the `sui` CLI), so the provider is pinned explicitly here
3073/// instead.
3074fn https_rustls_config(cert: &str, key: &str) -> Result<sui_http::rustls::ServerConfig> {
3075    use sui_http::rustls;
3076    use sui_http::rustls::pki_types::pem::PemObject;
3077
3078    let certs = rustls::pki_types::CertificateDer::pem_file_iter(cert)
3079        .with_context(|| format!("failed to read TLS certificate chain from {cert}"))?
3080        .collect::<Result<Vec<_>, _>>()
3081        .with_context(|| format!("failed to parse TLS certificate chain from {cert}"))?;
3082    let private_key = rustls::pki_types::PrivateKeyDer::from_pem_file(key)
3083        .with_context(|| format!("failed to read TLS private key from {key}"))?;
3084    let config = rustls::ServerConfig::builder_with_provider(Arc::new(
3085        rustls::crypto::ring::default_provider(),
3086    ))
3087    .with_protocol_versions(rustls::DEFAULT_VERSIONS)?
3088    .with_no_client_auth()
3089    .with_single_cert(certs, private_key)?;
3090    Ok(config)
3091}
3092
3093#[derive(Default)]
3094struct HttpServers {
3095    #[allow(unused)]
3096    http: Option<sui_http::ServerHandle>,
3097    #[allow(unused)]
3098    https: Option<sui_http::ServerHandle>,
3099}
3100
3101#[cfg(test)]
3102mod tests {
3103    use super::*;
3104    use prometheus::Registry;
3105    use std::collections::BTreeMap;
3106    use sui_config::node::{ForkCrashBehavior, ForkRecoveryConfig};
3107    use sui_core::checkpoints::{CheckpointMetrics, CheckpointStore};
3108    use sui_types::digests::{CheckpointDigest, TransactionDigest, TransactionEffectsDigest};
3109
3110    // A present legacy `rpc-index` directory is removed, while its siblings
3111    // (notably the still-used jsonrpc `indexes` store) are left untouched, and a
3112    // missing directory is a no-op.
3113    #[test]
3114    fn removes_only_the_legacy_rpc_index_directory() {
3115        let db = tempfile::tempdir().unwrap();
3116        let legacy = db.path().join("rpc-index");
3117        let sibling = db.path().join("indexes");
3118        std::fs::create_dir(&legacy).unwrap();
3119        std::fs::create_dir(&sibling).unwrap();
3120        std::fs::write(legacy.join("CURRENT"), b"stale").unwrap();
3121
3122        remove_legacy_rpc_index_store(db.path());
3123        assert!(
3124            !legacy.exists(),
3125            "legacy rpc-index directory should be gone"
3126        );
3127        assert!(sibling.exists(), "sibling stores must be left untouched");
3128
3129        // Idempotent: a second run (nothing to remove) does not error or touch
3130        // the siblings.
3131        remove_legacy_rpc_index_store(db.path());
3132        assert!(!legacy.exists());
3133        assert!(sibling.exists());
3134    }
3135
3136    // Halt / ReturnError never clear markers; ReturnError surfaces the fork as a startup error.
3137    #[tokio::test]
3138    async fn test_return_error_does_not_recover() {
3139        let checkpoint_store = CheckpointStore::new_for_tests();
3140        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3141        let cfg = ForkRecoveryConfig {
3142            transaction_overrides: Default::default(),
3143            checkpoint_overrides: Default::default(),
3144            fork_crash_behavior: ForkCrashBehavior::ReturnError,
3145        };
3146
3147        // Checkpoint fork.
3148        checkpoint_store
3149            .record_checkpoint_fork_detected(
3150                42,
3151                CheckpointDigest::random(),
3152                Some(CheckpointDigest::random()),
3153            )
3154            .unwrap();
3155        let r = SuiNode::check_and_recover_forks(
3156            &checkpoint_store,
3157            &checkpoint_metrics,
3158            Some(&cfg),
3159            "v1",
3160        )
3161        .await;
3162        assert!(
3163            r.unwrap_err()
3164                .to_string()
3165                .contains("Checkpoint fork detected")
3166        );
3167        assert!(
3168            checkpoint_store
3169                .get_checkpoint_fork_detected()
3170                .unwrap()
3171                .is_some()
3172        );
3173        checkpoint_store.clear_checkpoint_fork_detected().unwrap();
3174
3175        // Transaction fork.
3176        checkpoint_store
3177            .record_transaction_fork_detected(
3178                TransactionDigest::random(),
3179                TransactionEffectsDigest::random(),
3180                TransactionEffectsDigest::random(),
3181                Some(1),
3182            )
3183            .unwrap();
3184        let r = SuiNode::check_and_recover_forks(
3185            &checkpoint_store,
3186            &checkpoint_metrics,
3187            Some(&cfg),
3188            "v1",
3189        )
3190        .await;
3191        assert!(
3192            r.unwrap_err()
3193                .to_string()
3194                .contains("Transaction fork detected")
3195        );
3196    }
3197
3198    // A fork marker carrying the currently running binary version is never cleared — the binary
3199    // that forked would deterministically fork again — so the node hangs until a corrected
3200    // binary (different version) runs recovery.
3201    #[tokio::test]
3202    async fn test_same_binary_version_does_not_recover() {
3203        let checkpoint_store = CheckpointStore::new_for_tests();
3204        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3205        let seq = 7;
3206        // The fork is recorded by binary "v1", against a certified checkpoint.
3207        checkpoint_store.set_binary_version("v1");
3208        checkpoint_store
3209            .record_checkpoint_fork_detected(
3210                seq,
3211                CheckpointDigest::random(),
3212                Some(CheckpointDigest::random()),
3213            )
3214            .unwrap();
3215
3216        // Restarting the same binary: recovery refused despite certification.
3217        SuiNode::try_recover_forks(&checkpoint_store, &checkpoint_metrics, "v1").unwrap();
3218        assert!(
3219            checkpoint_store
3220                .get_checkpoint_fork_detected()
3221                .unwrap()
3222                .is_some()
3223        );
3224        assert_eq!(
3225            checkpoint_metrics
3226                .fork_auto_recovery_awaiting_new_binary
3227                .get(),
3228            1
3229        );
3230        assert_eq!(checkpoint_metrics.checkpoint_fork_auto_recovered.get(), 0);
3231
3232        // Corrected binary (new version): recovers.
3233        SuiNode::try_recover_forks(&checkpoint_store, &checkpoint_metrics, "v2").unwrap();
3234        assert!(
3235            checkpoint_store
3236                .get_checkpoint_fork_detected()
3237                .unwrap()
3238                .is_none()
3239        );
3240        assert_eq!(checkpoint_metrics.checkpoint_fork_auto_recovered.get(), 1);
3241    }
3242
3243    // The default behavior (RecoverOncePerVersion) recovers with no fork-recovery config present.
3244    #[tokio::test]
3245    async fn test_default_recovers() {
3246        let checkpoint_store = CheckpointStore::new_for_tests();
3247        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3248
3249        let tx_digest = TransactionDigest::random();
3250        // The fork was recorded by binary "v1"; its expected effects came from certified
3251        // checkpoint 3, so recovery under "v2" is permitted.
3252        checkpoint_store.set_binary_version("v1");
3253        checkpoint_store
3254            .record_transaction_fork_detected(
3255                tx_digest,
3256                TransactionEffectsDigest::random(),
3257                TransactionEffectsDigest::random(),
3258                Some(3),
3259            )
3260            .unwrap();
3261
3262        let r =
3263            SuiNode::check_and_recover_forks(&checkpoint_store, &checkpoint_metrics, None, "v2")
3264                .await;
3265        assert!(r.is_ok());
3266        assert!(
3267            checkpoint_store
3268                .get_transaction_fork_detected()
3269                .unwrap()
3270                .is_none()
3271        );
3272        assert_eq!(checkpoint_metrics.transaction_fork_auto_recovered.get(), 1);
3273    }
3274
3275    // checkpoint_overrides clears only the checkpoint fork marker (when the forked seq is listed); it
3276    // is decoupled from the transaction fork marker, which is cleared by transaction_overrides.
3277    #[tokio::test]
3278    async fn test_checkpoint_overrides_clear_checkpoint_marker_only() {
3279        let checkpoint_store = CheckpointStore::new_for_tests();
3280        let seq = 9;
3281
3282        checkpoint_store
3283            .record_checkpoint_fork_detected(
3284                seq,
3285                CheckpointDigest::random(),
3286                Some(CheckpointDigest::random()),
3287            )
3288            .unwrap();
3289        checkpoint_store
3290            .record_transaction_fork_detected(
3291                TransactionDigest::random(),
3292                TransactionEffectsDigest::random(),
3293                TransactionEffectsDigest::random(),
3294                None,
3295            )
3296            .unwrap();
3297
3298        // No overrides: both markers are left intact.
3299        SuiNode::try_recover_checkpoint_fork(&checkpoint_store, &ForkRecoveryConfig::default())
3300            .unwrap();
3301        assert!(
3302            checkpoint_store
3303                .get_checkpoint_fork_detected()
3304                .unwrap()
3305                .is_some()
3306        );
3307        assert!(
3308            checkpoint_store
3309                .get_transaction_fork_detected()
3310                .unwrap()
3311                .is_some()
3312        );
3313
3314        // Override for the forked seq: clears the checkpoint marker but leaves the transaction marker.
3315        let mut checkpoint_overrides = BTreeMap::new();
3316        checkpoint_overrides.insert(seq, CheckpointDigest::random().to_string());
3317        let cfg = ForkRecoveryConfig {
3318            transaction_overrides: Default::default(),
3319            checkpoint_overrides,
3320            fork_crash_behavior: ForkCrashBehavior::AwaitForkRecovery,
3321        };
3322        SuiNode::try_recover_checkpoint_fork(&checkpoint_store, &cfg).unwrap();
3323        assert!(
3324            checkpoint_store
3325                .get_checkpoint_fork_detected()
3326                .unwrap()
3327                .is_none()
3328        );
3329        assert!(
3330            checkpoint_store
3331                .get_transaction_fork_detected()
3332                .unwrap()
3333                .is_some(),
3334            "checkpoint_overrides must not touch the transaction fork marker"
3335        );
3336    }
3337
3338    // transaction_overrides clears the transaction fork marker when the forked tx is listed.
3339    #[tokio::test]
3340    async fn test_transaction_overrides_clear_transaction_marker() {
3341        let checkpoint_store = CheckpointStore::new_for_tests();
3342        let tx_digest = TransactionDigest::random();
3343        checkpoint_store
3344            .record_transaction_fork_detected(
3345                tx_digest,
3346                TransactionEffectsDigest::random(),
3347                TransactionEffectsDigest::random(),
3348                None,
3349            )
3350            .unwrap();
3351
3352        // Unrelated override: marker stays.
3353        let mut transaction_overrides = BTreeMap::new();
3354        transaction_overrides.insert(TransactionDigest::random().to_string(), String::new());
3355        let cfg = ForkRecoveryConfig {
3356            transaction_overrides,
3357            checkpoint_overrides: Default::default(),
3358            fork_crash_behavior: ForkCrashBehavior::AwaitForkRecovery,
3359        };
3360        SuiNode::try_recover_transaction_fork(&checkpoint_store, &cfg).unwrap();
3361        assert!(
3362            checkpoint_store
3363                .get_transaction_fork_detected()
3364                .unwrap()
3365                .is_some()
3366        );
3367
3368        // Override for the forked tx: marker cleared.
3369        let mut transaction_overrides = BTreeMap::new();
3370        transaction_overrides.insert(tx_digest.to_string(), String::new());
3371        let cfg = ForkRecoveryConfig {
3372            transaction_overrides,
3373            checkpoint_overrides: Default::default(),
3374            fork_crash_behavior: ForkCrashBehavior::AwaitForkRecovery,
3375        };
3376        SuiNode::try_recover_transaction_fork(&checkpoint_store, &cfg).unwrap();
3377        assert!(
3378            checkpoint_store
3379                .get_transaction_fork_detected()
3380                .unwrap()
3381                .is_none()
3382        );
3383    }
3384
3385    // Under RecoverOncePerVersion, a checkpoint override clears the fork via the manual path
3386    // even when the auto path would refuse (here: the fork was recorded by the currently running
3387    // binary version and the sequence is not certified).
3388    #[tokio::test]
3389    async fn test_override_clears_fork_auto_recovery_refuses() {
3390        let checkpoint_store = CheckpointStore::new_for_tests();
3391        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3392        let seq = 5;
3393        checkpoint_store.set_binary_version("v1");
3394        checkpoint_store
3395            .record_checkpoint_fork_detected(
3396                seq,
3397                CheckpointDigest::random(),
3398                Some(CheckpointDigest::random()),
3399            )
3400            .unwrap();
3401
3402        let mut checkpoint_overrides = BTreeMap::new();
3403        checkpoint_overrides.insert(seq, CheckpointDigest::random().to_string());
3404        let cfg = ForkRecoveryConfig {
3405            transaction_overrides: Default::default(),
3406            checkpoint_overrides,
3407            fork_crash_behavior: ForkCrashBehavior::RecoverOncePerVersion,
3408        };
3409
3410        SuiNode::check_and_recover_forks(&checkpoint_store, &checkpoint_metrics, Some(&cfg), "v1")
3411            .await
3412            .unwrap();
3413
3414        assert!(
3415            checkpoint_store
3416                .get_checkpoint_fork_detected()
3417                .unwrap()
3418                .is_none()
3419        );
3420    }
3421
3422    // A self-divergence checkpoint fork (the builder re-derived its own previous checkpoint
3423    // differently; no certified digest in the marker) is never auto-recovered, even under a new
3424    // binary version, because neither result is proven canonical. It requires operator
3425    // overrides.
3426    #[tokio::test]
3427    async fn test_self_divergence_checkpoint_fork_blocks_recovery() {
3428        let checkpoint_store = CheckpointStore::new_for_tests();
3429        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3430        let seq = 17;
3431        checkpoint_store.set_binary_version("v1");
3432        checkpoint_store
3433            .record_checkpoint_fork_detected(seq, CheckpointDigest::random(), None)
3434            .unwrap();
3435
3436        SuiNode::try_recover_forks(&checkpoint_store, &checkpoint_metrics, "v2").unwrap();
3437
3438        assert!(
3439            checkpoint_store
3440                .get_checkpoint_fork_detected()
3441                .unwrap()
3442                .is_some()
3443        );
3444        assert_eq!(
3445            checkpoint_metrics
3446                .fork_auto_recovery_blocked_uncertified
3447                .get(),
3448            1
3449        );
3450        assert_eq!(checkpoint_metrics.checkpoint_fork_auto_recovered.get(), 0);
3451    }
3452
3453    // A transaction fork whose expected effects did not come from a certified checkpoint (i.e.
3454    // they came from this validator's own previously signed effects) is never auto-recovered,
3455    // even on a new binary version.
3456    #[tokio::test]
3457    async fn test_uncertified_transaction_fork_blocks_recovery() {
3458        let checkpoint_store = CheckpointStore::new_for_tests();
3459        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3460        checkpoint_store.set_binary_version("v1");
3461        checkpoint_store
3462            .record_transaction_fork_detected(
3463                TransactionDigest::random(),
3464                TransactionEffectsDigest::random(),
3465                TransactionEffectsDigest::random(),
3466                None,
3467            )
3468            .unwrap();
3469
3470        SuiNode::try_recover_forks(&checkpoint_store, &checkpoint_metrics, "v2").unwrap();
3471        SuiNode::try_recover_forks(&checkpoint_store, &checkpoint_metrics, "v3").unwrap();
3472
3473        assert!(
3474            checkpoint_store
3475                .get_transaction_fork_detected()
3476                .unwrap()
3477                .is_some()
3478        );
3479        assert_eq!(
3480            checkpoint_metrics
3481                .fork_auto_recovery_blocked_uncertified
3482                .get(),
3483            1
3484        );
3485    }
3486}