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