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            throughput_calculator,
1582            backpressure_manager,
1583            config.congestion_log.clone(),
1584        );
1585
1586        info!("Starting consensus manager asynchronously");
1587
1588        // Spawn consensus startup asynchronously to avoid blocking other components
1589        tokio::spawn({
1590            let config = config.clone();
1591            let epoch_store = epoch_store.clone();
1592            let sui_tx_validator = SuiTxValidator::new(
1593                state.clone(),
1594                epoch_store.clone(),
1595                checkpoint_service.clone(),
1596                sui_tx_validator_metrics.clone(),
1597            );
1598            let consensus_manager = consensus_manager.clone();
1599            async move {
1600                consensus_manager
1601                    .start(
1602                        &config,
1603                        epoch_store,
1604                        consensus_handler_initializer,
1605                        sui_tx_validator,
1606                        Some(randomness_receiver_handle),
1607                    )
1608                    .await;
1609            }
1610        });
1611        let replay_waiter = consensus_manager.replay_waiter();
1612
1613        info!("Spawning checkpoint service");
1614        let replay_waiter = if std::env::var("DISABLE_REPLAY_WAITER").is_ok() {
1615            None
1616        } else {
1617            Some(replay_waiter)
1618        };
1619        checkpoint_service
1620            .spawn(epoch_store.clone(), replay_waiter)
1621            .await;
1622
1623        if node_role.is_validator() && epoch_store.authenticator_state_enabled() {
1624            Self::start_jwk_updater(
1625                config,
1626                sui_node_metrics,
1627                state.name,
1628                epoch_store.clone(),
1629                consensus_adapter.clone(),
1630            );
1631        }
1632
1633        if let Some(ctx) = &admission_queue {
1634            ctx.rotate_for_epoch(epoch_store);
1635        }
1636
1637        Ok(ValidatorComponents {
1638            validator_server_handle,
1639            validator_overload_monitor_handle,
1640            consensus_manager,
1641            consensus_store_pruner,
1642            consensus_adapter,
1643            checkpoint_metrics,
1644            sui_tx_validator_metrics,
1645            admission_queue,
1646        })
1647    }
1648
1649    fn build_checkpoint_service(
1650        config: &NodeConfig,
1651        consensus_adapter: Arc<ConsensusAdapter>,
1652        checkpoint_store: Arc<CheckpointStore>,
1653        epoch_store: Arc<AuthorityPerEpochStore>,
1654        state: Arc<AuthorityState>,
1655        state_sync_handle: state_sync::Handle,
1656        state_hasher: Weak<GlobalStateHasher>,
1657        checkpoint_metrics: Arc<CheckpointMetrics>,
1658        node_role: NodeRole,
1659    ) -> Arc<CheckpointService> {
1660        let checkpoint_output: Box<dyn CheckpointOutput> = if node_role.is_validator() {
1661            Box::new(SubmitCheckpointToConsensus::new(
1662                consensus_adapter,
1663                state.secret.clone(),
1664                config.protocol_public_key(),
1665                checkpoint_metrics.clone(),
1666            ))
1667        } else {
1668            Box::new(LogCheckpointOutput::new(checkpoint_metrics.clone()))
1669        };
1670
1671        let certified_checkpoint_output = SendCheckpointToStateSync::new(state_sync_handle);
1672
1673        CheckpointService::build(
1674            state.clone(),
1675            checkpoint_store,
1676            epoch_store,
1677            state.get_transaction_cache_reader().clone(),
1678            state_hasher,
1679            checkpoint_output,
1680            Box::new(certified_checkpoint_output),
1681            checkpoint_metrics,
1682        )
1683    }
1684
1685    fn construct_consensus_adapter(
1686        committee: &Committee,
1687        consensus_config: &ConsensusConfig,
1688        authority: AuthorityName,
1689        prometheus_registry: &Registry,
1690        consensus_client: Arc<dyn ConsensusClient>,
1691        checkpoint_store: Arc<CheckpointStore>,
1692        inflight_slot_freed_notify: Arc<tokio::sync::Notify>,
1693    ) -> ConsensusAdapter {
1694        let ca_metrics = ConsensusAdapterMetrics::new(prometheus_registry);
1695        // The consensus adapter allows the authority to send user certificates through consensus.
1696
1697        ConsensusAdapter::new(
1698            consensus_client,
1699            checkpoint_store,
1700            authority,
1701            consensus_config.max_pending_transactions(),
1702            consensus_config.max_pending_transactions() * 2 / committee.num_members(),
1703            ca_metrics,
1704            inflight_slot_freed_notify,
1705        )
1706    }
1707
1708    async fn start_grpc_validator_service(
1709        config: &NodeConfig,
1710        state: Arc<AuthorityState>,
1711        consensus_adapter: Arc<ConsensusAdapter>,
1712        epoch_store: Arc<AuthorityPerEpochStore>,
1713        prometheus_registry: &Registry,
1714        inflight_slot_freed_notify: Arc<tokio::sync::Notify>,
1715    ) -> Result<(SpawnOnce, Option<AdmissionQueueContext>)> {
1716        let overload_config = &config.authority_overload_config;
1717        let admission_queue = overload_config.admission_queue_enabled.then(|| {
1718            let manager = Arc::new(AdmissionQueueManager::new(
1719                consensus_adapter.clone(),
1720                Arc::new(AdmissionQueueMetrics::new(prometheus_registry)),
1721                overload_config.admission_queue_capacity_fraction,
1722                overload_config.admission_queue_failover_timeout,
1723                inflight_slot_freed_notify,
1724            ));
1725            AdmissionQueueContext::spawn(manager, epoch_store)
1726        });
1727        let validator_service = ValidatorService::new(
1728            state.clone(),
1729            consensus_adapter,
1730            Arc::new(ValidatorServiceMetrics::new(prometheus_registry)),
1731            config.policy_config.clone().map(|p| p.client_id_source),
1732            admission_queue.clone(),
1733        );
1734
1735        let mut server_conf = mysten_network::config::Config::new();
1736        server_conf.connect_timeout = Some(DEFAULT_GRPC_CONNECT_TIMEOUT);
1737        server_conf.http2_keepalive_interval = Some(DEFAULT_GRPC_CONNECT_TIMEOUT);
1738        server_conf.http2_keepalive_timeout = Some(DEFAULT_GRPC_CONNECT_TIMEOUT);
1739        server_conf.global_concurrency_limit = config.grpc_concurrency_limit;
1740        server_conf.load_shed = config.grpc_load_shed;
1741        let mut server_builder =
1742            ServerBuilder::from_config(&server_conf, GrpcMetrics::new(prometheus_registry));
1743
1744        server_builder = server_builder.add_service(ValidatorServer::new(validator_service));
1745
1746        let tls_config = sui_tls::create_rustls_server_config(
1747            config.network_key_pair().copy().private(),
1748            SUI_TLS_SERVER_NAME.to_string(),
1749        );
1750
1751        let network_address = config.network_address().clone();
1752
1753        let (ready_tx, ready_rx) = oneshot::channel();
1754
1755        let spawn_once = SpawnOnce::new(ready_rx, async move {
1756            let server = server_builder
1757                .bind(&network_address, Some(tls_config))
1758                .await
1759                .unwrap_or_else(|err| panic!("Failed to bind to {network_address}: {err}"));
1760            let local_addr = server.local_addr();
1761            info!("Listening to traffic on {local_addr}");
1762            ready_tx.send(()).unwrap();
1763            if let Err(err) = server.serve().await {
1764                info!("Server stopped: {err}");
1765            }
1766            info!("Server stopped");
1767        });
1768        Ok((spawn_once, admission_queue))
1769    }
1770
1771    pub fn state(&self) -> Arc<AuthorityState> {
1772        self.state.clone()
1773    }
1774
1775    /// The embedded `sui-rpc-store` index backend, when the node is a
1776    /// fullnode with indexing enabled. Exposes the startup bootstrap
1777    /// decision and per-cohort watermarks for introspection (used by
1778    /// tests to observe restore/resume behavior across restarts without
1779    /// going through the RPC surface).
1780    pub fn embedded_rpc_store(&self) -> Option<&EmbeddedRpcStore> {
1781        self.embedded_rpc_store.as_ref()
1782    }
1783
1784    #[cfg(any(test, msim))]
1785    pub fn connection_monitor_handle_for_testing(
1786        &self,
1787    ) -> &mysten_network::anemo_connection_monitor::ConnectionMonitorHandle {
1788        &self._connection_monitor_handle
1789    }
1790
1791    #[cfg(any(test, msim))]
1792    pub fn address_prober_metrics_for_testing(
1793        &self,
1794    ) -> std::sync::Arc<address_prober::AddressProberMetrics> {
1795        self.address_prober
1796            .as_ref()
1797            .expect("address prober should be running in tests")
1798            .metrics_for_testing()
1799    }
1800
1801    #[cfg(feature = "testing")]
1802    pub fn prometheus_metrics_for_testing(&self) -> Vec<prometheus::proto::MetricFamily> {
1803        self.registry_service.default_registry().gather()
1804    }
1805
1806    pub fn node_role(&self) -> NodeRole {
1807        self.state.load_epoch_store_one_call_per_task().node_role()
1808    }
1809
1810    // Only used for testing because of how epoch store is loaded.
1811    pub fn reference_gas_price_for_testing(&self) -> Result<u64, anyhow::Error> {
1812        self.state.reference_gas_price_for_testing()
1813    }
1814
1815    pub fn clone_committee_store(&self) -> Arc<CommitteeStore> {
1816        self.state.committee_store().clone()
1817    }
1818
1819    pub fn clone_checkpoint_store(&self) -> Arc<CheckpointStore> {
1820        self.checkpoint_store.clone()
1821    }
1822
1823    pub fn clone_authority_store(&self) -> Arc<AuthorityStore> {
1824        self.state.authority_store()
1825    }
1826
1827    pub fn clone_consensus_store(
1828        &self,
1829    ) -> Option<Arc<consensus_core::storage::rocksdb_store::RocksDBStore>> {
1830        self.validator_components
1831            .try_lock()
1832            .ok()?
1833            .as_ref()?
1834            .consensus_manager
1835            .consensus_store()
1836    }
1837
1838    /// Clone an AuthorityAggregator currently used in this node, if the node is a fullnode.
1839    /// After reconfig, Transaction Driver builds a new AuthorityAggregator. The caller
1840    /// of this function will mostly likely want to call this again
1841    /// to get a fresh one.
1842    pub fn clone_authority_aggregator(
1843        &self,
1844    ) -> Option<Arc<AuthorityAggregator<NetworkAuthorityClient>>> {
1845        self.transaction_orchestrator
1846            .as_ref()
1847            .map(|to| to.clone_authority_aggregator())
1848    }
1849
1850    pub fn transaction_orchestrator(
1851        &self,
1852    ) -> Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>> {
1853        self.transaction_orchestrator.clone()
1854    }
1855
1856    /// This function awaits the completion of checkpoint execution of the current epoch,
1857    /// after which it initiates reconfiguration of the entire system.
1858    pub async fn monitor_reconfiguration(
1859        self: Arc<Self>,
1860        mut epoch_store: Arc<AuthorityPerEpochStore>,
1861    ) -> Result<()> {
1862        let checkpoint_executor_metrics =
1863            CheckpointExecutorMetrics::new(&self.registry_service.default_registry());
1864
1865        loop {
1866            let mut hasher_guard = self.global_state_hasher.lock().await;
1867            let hasher = hasher_guard.take().unwrap();
1868            info!(
1869                "Creating checkpoint executor for epoch {}",
1870                epoch_store.epoch()
1871            );
1872            let checkpoint_executor = CheckpointExecutor::new(
1873                epoch_store.clone(),
1874                self.checkpoint_store.clone(),
1875                self.state.clone(),
1876                hasher.clone(),
1877                self.backpressure_manager.clone(),
1878                self.config.checkpoint_executor_config.clone(),
1879                checkpoint_executor_metrics.clone(),
1880                self.subscription_service_checkpoint_sender.clone(),
1881            );
1882
1883            let run_with_range = self.config.run_with_range;
1884
1885            let cur_epoch_store = self.state.load_epoch_store_one_call_per_task();
1886
1887            // Update the current protocol version metric.
1888            self.metrics
1889                .current_protocol_version
1890                .set(cur_epoch_store.protocol_config().version.as_u64() as i64);
1891
1892            // Advertise capabilities to committee, if we are a validator.
1893            // FullNodes that state sync via consensus will also have validator components, by they are not supposed to submit any capabilities.
1894            if let Some(components) = &*self.validator_components.lock().await
1895                && cur_epoch_store.is_validator()
1896            {
1897                // TODO: without this sleep, the consensus message is not delivered reliably.
1898                tokio::time::sleep(Duration::from_millis(1)).await;
1899
1900                let config = cur_epoch_store.protocol_config();
1901                let mut supported_protocol_versions = self
1902                    .config
1903                    .supported_protocol_versions
1904                    .expect("Supported versions should be populated")
1905                    // no need to send digests of versions less than the current version
1906                    .truncate_below(config.version);
1907
1908                while supported_protocol_versions.max > config.version {
1909                    let proposed_protocol_config = ProtocolConfig::get_for_version(
1910                        supported_protocol_versions.max,
1911                        cur_epoch_store.get_chain(),
1912                    );
1913
1914                    if proposed_protocol_config.enable_accumulators()
1915                        && !epoch_store.accumulator_root_exists()
1916                    {
1917                        error!(
1918                            "cannot upgrade to protocol version {:?} because accumulator root does not exist",
1919                            supported_protocol_versions.max
1920                        );
1921                        supported_protocol_versions.max = supported_protocol_versions.max.prev();
1922                    } else {
1923                        break;
1924                    }
1925                }
1926
1927                let binary_config = config.binary_config(None);
1928                let transaction = ConsensusTransaction::new_capability_notification_v2(
1929                    AuthorityCapabilitiesV2::new(
1930                        self.state.name,
1931                        cur_epoch_store.get_chain_identifier().chain(),
1932                        supported_protocol_versions,
1933                        self.state
1934                            .get_available_system_packages(&binary_config)
1935                            .await,
1936                    ),
1937                );
1938                info!(?transaction, "submitting capabilities to consensus");
1939                components.consensus_adapter.submit(
1940                    transaction,
1941                    None,
1942                    &cur_epoch_store,
1943                    None,
1944                    None,
1945                )?;
1946            }
1947
1948            let stop_condition = checkpoint_executor.run_epoch(run_with_range).await;
1949
1950            if stop_condition == StopReason::RunWithRangeCondition {
1951                SuiNode::shutdown(&self).await;
1952                self.shutdown_channel_tx
1953                    .send(run_with_range)
1954                    .expect("RunWithRangeCondition met but failed to send shutdown message");
1955                return Ok(());
1956            }
1957
1958            // Safe to call because we are in the middle of reconfiguration.
1959            let latest_system_state = self
1960                .state
1961                .get_object_cache_reader()
1962                .get_sui_system_state_object_unsafe()
1963                .expect("Read Sui System State object cannot fail");
1964
1965            #[cfg(msim)]
1966            if !self
1967                .sim_state
1968                .sim_safe_mode_expected
1969                .load(Ordering::Relaxed)
1970            {
1971                debug_assert!(!latest_system_state.safe_mode());
1972            }
1973
1974            #[cfg(not(msim))]
1975            debug_assert!(!latest_system_state.safe_mode());
1976
1977            if let Err(err) = self.end_of_epoch_channel.send(latest_system_state.clone())
1978                && self.state.is_fullnode(&cur_epoch_store)
1979            {
1980                warn!(
1981                    "Failed to send end of epoch notification to subscriber: {:?}",
1982                    err
1983                );
1984            }
1985
1986            cur_epoch_store.record_is_safe_mode_metric(latest_system_state.safe_mode());
1987            let new_epoch_start_state = latest_system_state.into_epoch_start_state();
1988
1989            self.auth_agg.store(Arc::new(
1990                self.auth_agg
1991                    .load()
1992                    .recreate_with_new_epoch_start_state(&new_epoch_start_state),
1993            ));
1994
1995            let next_epoch_committee = new_epoch_start_state.get_sui_committee();
1996            let next_epoch = next_epoch_committee.epoch();
1997            assert_eq!(cur_epoch_store.epoch() + 1, next_epoch);
1998
1999            info!(
2000                next_epoch,
2001                "Finished executing all checkpoints in epoch. About to reconfigure the system."
2002            );
2003
2004            fail_point_async!("reconfig_delay");
2005
2006            cur_epoch_store.record_epoch_reconfig_start_time_metric();
2007
2008            update_peer_addresses(
2009                &self.config,
2010                &self.endpoint_manager,
2011                &new_epoch_start_state,
2012                Some(cur_epoch_store.epoch_start_state()),
2013            );
2014
2015            let mut validator_components_lock_guard = self.validator_components.lock().await;
2016
2017            // The following code handles 4 different cases, depending on whether the node
2018            // was a validator in the previous epoch, and whether the node is a validator
2019            // in the new epoch.
2020            let new_epoch_store = self
2021                .reconfigure_state(
2022                    &self.state,
2023                    &cur_epoch_store,
2024                    next_epoch_committee.clone(),
2025                    new_epoch_start_state,
2026                    hasher.clone(),
2027                )
2028                .await;
2029
2030            let new_role = new_epoch_store.node_role();
2031
2032            let new_validator_components = if let Some(ValidatorComponents {
2033                validator_server_handle,
2034                validator_overload_monitor_handle,
2035                consensus_manager,
2036                consensus_store_pruner,
2037                consensus_adapter,
2038                checkpoint_metrics,
2039                sui_tx_validator_metrics,
2040                admission_queue,
2041            }) = validator_components_lock_guard.take()
2042            {
2043                info!("Reconfiguring node (was running consensus).");
2044
2045                consensus_manager.shutdown().await;
2046                info!("Consensus has shut down.");
2047
2048                if let Some(handle) = &self.address_prober {
2049                    handle.leave_committee();
2050                }
2051
2052                info!("Epoch store finished reconfiguration.");
2053
2054                // No other components should be holding a strong reference to state hasher
2055                // at this point. Confirm here before we swap in the new hasher.
2056                let global_state_hasher_metrics = Arc::into_inner(hasher)
2057                    .expect("Object state hasher should have no other references at this point")
2058                    .metrics();
2059                let new_hasher = Arc::new(GlobalStateHasher::new(
2060                    self.state.get_global_state_hash_store().clone(),
2061                    global_state_hasher_metrics,
2062                ));
2063                let weak_hasher = Arc::downgrade(&new_hasher);
2064                *hasher_guard = Some(new_hasher);
2065
2066                consensus_store_pruner.prune(next_epoch).await;
2067
2068                if new_role.runs_consensus() {
2069                    info!("Restarting consensus as {new_role}");
2070                    let components = Self::start_epoch_specific_validator_components(
2071                        &self.config,
2072                        self.state.clone(),
2073                        consensus_adapter,
2074                        self.checkpoint_store.clone(),
2075                        new_epoch_store.clone(),
2076                        self.state_sync_handle.clone(),
2077                        self.randomness_handle.clone(),
2078                        self.randomness_receiver_handle.clone(),
2079                        consensus_manager,
2080                        consensus_store_pruner,
2081                        weak_hasher,
2082                        self.backpressure_manager.clone(),
2083                        validator_server_handle,
2084                        validator_overload_monitor_handle,
2085                        checkpoint_metrics,
2086                        self.metrics.clone(),
2087                        sui_tx_validator_metrics,
2088                        admission_queue,
2089                        new_role,
2090                    )
2091                    .await?;
2092                    self.update_address_prober_epoch(
2093                        &new_epoch_store,
2094                        &components.consensus_manager,
2095                    );
2096                    Some(components)
2097                } else {
2098                    info!(
2099                        "This node has new role {new_role} and no longer runs consensus after reconfiguration"
2100                    );
2101                    None
2102                }
2103            } else {
2104                // No other components should be holding a strong reference to state hasher
2105                // at this point. Confirm here before we swap in the new hasher.
2106                let global_state_hasher_metrics = Arc::into_inner(hasher)
2107                    .expect("Object state hasher should have no other references at this point")
2108                    .metrics();
2109                let new_hasher = Arc::new(GlobalStateHasher::new(
2110                    self.state.get_global_state_hash_store().clone(),
2111                    global_state_hasher_metrics,
2112                ));
2113                let weak_hasher = Arc::downgrade(&new_hasher);
2114                *hasher_guard = Some(new_hasher);
2115
2116                if new_role.runs_consensus() {
2117                    info!("Promoting node to {new_role}, starting consensus components");
2118
2119                    let mut components = Self::construct_validator_components(
2120                        self.config.clone(),
2121                        self.state.clone(),
2122                        Arc::new(next_epoch_committee.clone()),
2123                        new_epoch_store.clone(),
2124                        self.checkpoint_store.clone(),
2125                        self.state_sync_handle.clone(),
2126                        self.randomness_handle.clone(),
2127                        weak_hasher,
2128                        self.backpressure_manager.clone(),
2129                        &self.registry_service,
2130                        self.metrics.clone(),
2131                        self.checkpoint_metrics.clone(),
2132                        new_role,
2133                        self.randomness_receiver_handle.clone(),
2134                    )
2135                    .await?;
2136
2137                    if new_role.is_validator() {
2138                        components.validator_server_handle = Some(
2139                            components
2140                                .validator_server_handle
2141                                .take()
2142                                .unwrap()
2143                                .start()
2144                                .await,
2145                        );
2146
2147                        self.endpoint_manager
2148                            .set_consensus_address_updater(components.consensus_manager.clone());
2149                    }
2150
2151                    self.update_address_prober_epoch(
2152                        &new_epoch_store,
2153                        &components.consensus_manager,
2154                    );
2155                    Some(components)
2156                } else {
2157                    None
2158                }
2159            };
2160            *validator_components_lock_guard = new_validator_components;
2161
2162            // Force releasing current epoch store DB handle, because the
2163            // Arc<AuthorityPerEpochStore> may linger.
2164            cur_epoch_store.release_db_handles();
2165
2166            if cfg!(msim)
2167                && !matches!(
2168                    self.config
2169                        .authority_store_pruning_config
2170                        .num_epochs_to_retain_for_checkpoints(),
2171                    None | Some(u64::MAX) | Some(0)
2172                )
2173            {
2174                self.state
2175                    .prune_checkpoints_for_eligible_epochs_for_testing(
2176                        self.config.clone(),
2177                        sui_core::authority::authority_store_pruner::AuthorityStorePruningMetrics::new_for_test(),
2178                    )
2179                    .await?;
2180            }
2181
2182            epoch_store = new_epoch_store;
2183            info!("Reconfiguration finished");
2184        }
2185    }
2186
2187    async fn shutdown(&self) {
2188        if let Some(validator_components) = &*self.validator_components.lock().await {
2189            validator_components.consensus_manager.shutdown().await;
2190        }
2191    }
2192
2193    async fn reconfigure_state(
2194        &self,
2195        state: &Arc<AuthorityState>,
2196        cur_epoch_store: &AuthorityPerEpochStore,
2197        next_epoch_committee: Committee,
2198        next_epoch_start_system_state: EpochStartSystemState,
2199        global_state_hasher: Arc<GlobalStateHasher>,
2200    ) -> Arc<AuthorityPerEpochStore> {
2201        let next_epoch = next_epoch_committee.epoch();
2202
2203        let last_checkpoint = self
2204            .checkpoint_store
2205            .get_epoch_last_checkpoint(cur_epoch_store.epoch())
2206            .expect("Error loading last checkpoint for current epoch")
2207            .expect("Could not load last checkpoint for current epoch");
2208
2209        let last_checkpoint_seq = *last_checkpoint.sequence_number();
2210
2211        assert_eq!(
2212            Some(last_checkpoint_seq),
2213            self.checkpoint_store
2214                .get_highest_executed_checkpoint_seq_number()
2215                .expect("Error loading highest executed checkpoint sequence number")
2216        );
2217
2218        let epoch_start_configuration = EpochStartConfiguration::new(
2219            next_epoch_start_system_state,
2220            *last_checkpoint.digest(),
2221            state.get_object_store().as_ref(),
2222            EpochFlag::default_flags_for_new_epoch(&state.config),
2223        )
2224        .expect("EpochStartConfiguration construction cannot fail");
2225
2226        let new_epoch_store = self
2227            .state
2228            .reconfigure(
2229                cur_epoch_store,
2230                self.config.supported_protocol_versions.unwrap(),
2231                next_epoch_committee,
2232                epoch_start_configuration,
2233                global_state_hasher,
2234                &self.config.expensive_safety_check_config,
2235                last_checkpoint_seq,
2236            )
2237            .await
2238            .expect("Reconfigure authority state cannot fail");
2239        info!(next_epoch, "Node State has been reconfigured");
2240        assert_eq!(next_epoch, new_epoch_store.epoch());
2241        self.state.get_reconfig_api().update_epoch_flags_metrics(
2242            cur_epoch_store.epoch_start_config().flags(),
2243            new_epoch_store.epoch_start_config().flags(),
2244        );
2245
2246        new_epoch_store
2247    }
2248
2249    pub fn get_config(&self) -> &NodeConfig {
2250        &self.config
2251    }
2252
2253    pub fn randomness_handle(&self) -> randomness::Handle {
2254        self.randomness_handle.clone()
2255    }
2256
2257    pub fn state_sync_handle(&self) -> state_sync::Handle {
2258        self.state_sync_handle.clone()
2259    }
2260
2261    pub fn endpoint_manager(&self) -> &EndpointManager {
2262        &self.endpoint_manager
2263    }
2264
2265    pub async fn address_prober_report(&self) -> Option<address_prober::ProbeReport> {
2266        match &self.address_prober {
2267            Some(handle) => handle.probe_report().await,
2268            None => None,
2269        }
2270    }
2271
2272    /// Get a short prefix of a digest for metric labels
2273    fn get_digest_prefix(digest: impl std::fmt::Display) -> String {
2274        let digest_str = digest.to_string();
2275        if digest_str.len() >= 8 {
2276            digest_str[0..8].to_string()
2277        } else {
2278            digest_str
2279        }
2280    }
2281
2282    /// Check for previously detected forks and handle them appropriately.
2283    /// For validators with fork recovery config, clear the fork if it matches the recovery config.
2284    /// For all other cases, block node startup if a fork is detected.
2285    async fn check_and_recover_forks(
2286        checkpoint_store: &CheckpointStore,
2287        checkpoint_metrics: &CheckpointMetrics,
2288        fork_recovery: Option<&ForkRecoveryConfig>,
2289        build_version: &str,
2290    ) -> Result<()> {
2291        // Manual recovery from operator-supplied overrides; runs regardless of fork_crash_behavior
2292        // and only acts on the checkpoints / transactions explicitly listed in the config.
2293        if let Some(recovery) = fork_recovery {
2294            Self::try_recover_checkpoint_fork(checkpoint_store, recovery)?;
2295            Self::try_recover_transaction_fork(checkpoint_store, recovery)?;
2296        }
2297
2298        let behavior = fork_recovery
2299            .map(|fr| fr.fork_crash_behavior)
2300            .unwrap_or_default();
2301
2302        match behavior {
2303            ForkCrashBehavior::RecoverOncePerVersion => {
2304                Self::try_recover_forks(checkpoint_store, checkpoint_metrics, build_version)?;
2305            }
2306            ForkCrashBehavior::AwaitForkRecovery | ForkCrashBehavior::ReturnError => {}
2307        }
2308
2309        if let Some(fork_info) = checkpoint_store
2310            .get_checkpoint_fork_detected()
2311            .map_err(|e| {
2312                error!("Failed to check for checkpoint fork: {:?}", e);
2313                e
2314            })?
2315        {
2316            Self::handle_checkpoint_fork(
2317                fork_info.checkpoint_seq,
2318                fork_info.checkpoint_digest,
2319                checkpoint_metrics,
2320                fork_recovery,
2321            )
2322            .await?;
2323        }
2324        if let Some(fork_info) = checkpoint_store
2325            .get_transaction_fork_detected()
2326            .map_err(|e| {
2327                error!("Failed to check for transaction fork: {:?}", e);
2328                e
2329            })?
2330        {
2331            Self::handle_transaction_fork(
2332                fork_info.tx_digest,
2333                fork_info.expected_effects_digest,
2334                fork_info.actual_effects_digest,
2335                checkpoint_metrics,
2336                fork_recovery,
2337            )
2338            .await?;
2339        }
2340
2341        Ok(())
2342    }
2343
2344    /// Manual recovery: for each `seq -> digest` override, if the locally computed checkpoint at
2345    /// `seq` differs, clear locally computed checkpoints from `seq` (and the checkpoint fork marker)
2346    /// so the node rebuilds toward the operator-specified digest.
2347    fn try_recover_checkpoint_fork(
2348        checkpoint_store: &CheckpointStore,
2349        recovery: &ForkRecoveryConfig,
2350    ) -> Result<()> {
2351        if recovery.checkpoint_overrides.is_empty() {
2352            return Ok(());
2353        }
2354
2355        for (seq, expected_digest_str) in &recovery.checkpoint_overrides {
2356            let Ok(expected_digest) = CheckpointDigest::from_str(expected_digest_str) else {
2357                anyhow::bail!(
2358                    "Invalid checkpoint digest override for seq {}: {}",
2359                    seq,
2360                    expected_digest_str
2361                );
2362            };
2363
2364            if let Some(local_summary) = checkpoint_store.get_locally_computed_checkpoint(*seq)? {
2365                let local_digest = sui_types::message_envelope::Message::digest(&local_summary);
2366                if local_digest != expected_digest {
2367                    info!(
2368                        seq,
2369                        local = %Self::get_digest_prefix(local_digest),
2370                        expected = %Self::get_digest_prefix(expected_digest),
2371                        "Fork recovery: clearing locally_computed_checkpoints from {} due to digest mismatch",
2372                        seq
2373                    );
2374                    checkpoint_store
2375                        .clear_locally_computed_checkpoints_from(*seq)
2376                        .context(
2377                            "Failed to clear locally computed checkpoints from override seq",
2378                        )?;
2379                }
2380            }
2381        }
2382
2383        if let Some(fork_info) = checkpoint_store.get_checkpoint_fork_detected()?
2384            && recovery
2385                .checkpoint_overrides
2386                .contains_key(&fork_info.checkpoint_seq)
2387        {
2388            info!(
2389                "Fork recovery enabled: clearing checkpoint fork at seq {} with digest {:?}",
2390                fork_info.checkpoint_seq, fork_info.checkpoint_digest
2391            );
2392            checkpoint_store
2393                .clear_checkpoint_fork_detected()
2394                .expect("Failed to clear checkpoint fork detected marker");
2395        }
2396        Ok(())
2397    }
2398
2399    /// Manual recovery: if the forked transaction is listed in transaction_overrides, clear its fork
2400    /// marker so the node proceeds on restart.
2401    fn try_recover_transaction_fork(
2402        checkpoint_store: &CheckpointStore,
2403        recovery: &ForkRecoveryConfig,
2404    ) -> Result<()> {
2405        if recovery.transaction_overrides.is_empty() {
2406            return Ok(());
2407        }
2408
2409        if let Some(fork_info) = checkpoint_store.get_transaction_fork_detected()?
2410            && recovery
2411                .transaction_overrides
2412                .contains_key(&fork_info.tx_digest.to_string())
2413        {
2414            info!(
2415                "Fork recovery enabled: clearing transaction fork for tx {:?}",
2416                fork_info.tx_digest
2417            );
2418            checkpoint_store
2419                .clear_transaction_fork_detected()
2420                .expect("Failed to clear transaction fork detected marker");
2421        }
2422        Ok(())
2423    }
2424
2425    /// Auto-recovery: clear fork markers (the affected seq/tx is read from the markers) so the
2426    /// node re-derives canonically. A marker is cleared only if both gates pass:
2427    ///
2428    /// - Version gate: the marker was recorded by a different binary version than the one now
2429    ///   running. The binary that forked would deterministically fork again, so clearing under
2430    ///   it would only add a second equivocation; the node hangs until a corrected binary is
2431    ///   deployed.
2432    /// - Certification gate: the marker records the certified checkpoint the node diverged
2433    ///   from. Markers carry it only when detection compared against a certificate already
2434    ///   durably persisted locally, so its presence proves the network certified the canonical
2435    ///   outcome. Recovery is deliberate equivocation — the node may have already signed the
2436    ///   forked result and will sign a different one after re-deriving — which is safe only
2437    ///   under that proof: a quorum certificate is irrevocable (a conflicting certificate would
2438    ///   require f+1 double-signers), so re-signing can no longer influence what finalizes.
2439    ///   Self-divergence markers (the node disagreeing with its own prior result rather than a
2440    ///   certificate) carry no certified reference and never pass; the node halts awaiting
2441    ///   operator intervention.
2442    fn try_recover_forks(
2443        checkpoint_store: &CheckpointStore,
2444        checkpoint_metrics: &CheckpointMetrics,
2445        build_version: &str,
2446    ) -> Result<()> {
2447        if let Some(fork_info) = checkpoint_store.get_checkpoint_fork_detected()? {
2448            if fork_info.binary_version == build_version {
2449                error!(
2450                    checkpoint_seq = fork_info.checkpoint_seq,
2451                    build_version,
2452                    "Fork recovery blocked: this binary version produced the checkpoint fork and \
2453                     would fork again. Halting; deploy a corrected binary to recover."
2454                );
2455                checkpoint_metrics
2456                    .fork_auto_recovery_awaiting_new_binary
2457                    .set(1);
2458            } else if fork_info.certified_checkpoint_digest.is_none() {
2459                // The builder re-derived a previously computed checkpoint differently: the fork
2460                // is against the node's own prior result, not a certified checkpoint, so there
2461                // is no canonical outcome to converge toward.
2462                error!(
2463                    checkpoint_seq = fork_info.checkpoint_seq,
2464                    checkpoint_digest = ?fork_info.checkpoint_digest,
2465                    "Fork recovery blocked: the builder re-derived its own previous checkpoint \
2466                     differently, so there is no certified checkpoint proving the canonical \
2467                     outcome to converge toward. Halting awaiting operator intervention."
2468                );
2469                checkpoint_metrics
2470                    .fork_auto_recovery_blocked_uncertified
2471                    .set(1);
2472            } else {
2473                info!(
2474                    checkpoint_seq = fork_info.checkpoint_seq,
2475                    checkpoint_digest = ?fork_info.checkpoint_digest,
2476                    forked_binary_version = ?fork_info.binary_version,
2477                    build_version,
2478                    "Fork recovery: clearing checkpoint fork and locally computed checkpoints \
2479                     from the forked sequence so the builder rebuilds toward the certified \
2480                     checkpoint"
2481                );
2482                checkpoint_store
2483                    .clear_locally_computed_checkpoints_from(fork_info.checkpoint_seq)
2484                    .context("Failed to clear locally computed checkpoints during fork recovery")?;
2485                checkpoint_store.clear_checkpoint_fork_detected()?;
2486                checkpoint_metrics.checkpoint_fork_auto_recovered.set(1);
2487            }
2488        }
2489
2490        if let Some(fork_info) = checkpoint_store.get_transaction_fork_detected()? {
2491            if fork_info.binary_version == build_version {
2492                error!(
2493                    tx_digest = ?fork_info.tx_digest,
2494                    build_version,
2495                    "Fork recovery blocked: this binary version produced the transaction fork and \
2496                     would fork again. Halting; deploy a corrected binary to recover."
2497                );
2498                checkpoint_metrics
2499                    .fork_auto_recovery_awaiting_new_binary
2500                    .set(1);
2501            } else if fork_info.certified_checkpoint_seq.is_none() {
2502                error!(
2503                    tx_digest = ?fork_info.tx_digest,
2504                    "Fork recovery blocked: the expected effects of the forked transaction did \
2505                     not come from a certified checkpoint (they came from this validator's own \
2506                     previously signed effects), so the network has not provably certified the \
2507                     canonical outcome. Halting awaiting operator intervention."
2508                );
2509                checkpoint_metrics
2510                    .fork_auto_recovery_blocked_uncertified
2511                    .set(1);
2512            } else {
2513                info!(
2514                    tx_digest = ?fork_info.tx_digest,
2515                    expected_effects = ?fork_info.expected_effects_digest,
2516                    actual_effects = ?fork_info.actual_effects_digest,
2517                    certified_checkpoint_seq = ?fork_info.certified_checkpoint_seq,
2518                    forked_binary_version = ?fork_info.binary_version,
2519                    build_version,
2520                    "Fork recovery: clearing transaction fork; re-execution will converge toward \
2521                     the canonical certified effects"
2522                );
2523                checkpoint_store.clear_transaction_fork_detected()?;
2524                checkpoint_metrics.transaction_fork_auto_recovered.set(1);
2525            }
2526        }
2527
2528        Ok(())
2529    }
2530
2531    fn get_current_timestamp() -> u64 {
2532        std::time::SystemTime::now()
2533            .duration_since(std::time::SystemTime::UNIX_EPOCH)
2534            .unwrap()
2535            .as_secs()
2536    }
2537
2538    async fn handle_checkpoint_fork(
2539        checkpoint_seq: u64,
2540        checkpoint_digest: CheckpointDigest,
2541        checkpoint_metrics: &CheckpointMetrics,
2542        fork_recovery: Option<&ForkRecoveryConfig>,
2543    ) -> Result<()> {
2544        checkpoint_metrics
2545            .checkpoint_fork_crash_mode
2546            .with_label_values(&[
2547                &checkpoint_seq.to_string(),
2548                &Self::get_digest_prefix(checkpoint_digest),
2549                &Self::get_current_timestamp().to_string(),
2550            ])
2551            .set(1);
2552
2553        let behavior = fork_recovery
2554            .map(|fr| fr.fork_crash_behavior)
2555            .unwrap_or_default();
2556
2557        match behavior {
2558            ForkCrashBehavior::AwaitForkRecovery | ForkCrashBehavior::RecoverOncePerVersion => {
2559                error!(
2560                    checkpoint_seq = checkpoint_seq,
2561                    checkpoint_digest = ?checkpoint_digest,
2562                    "Checkpoint fork detected! Node startup halted. Sleeping indefinitely."
2563                );
2564                futures::future::pending::<()>().await;
2565                unreachable!("pending() should never return");
2566            }
2567            ForkCrashBehavior::ReturnError => {
2568                error!(
2569                    checkpoint_seq = checkpoint_seq,
2570                    checkpoint_digest = ?checkpoint_digest,
2571                    "Checkpoint fork detected! Returning error."
2572                );
2573                Err(anyhow::anyhow!(
2574                    "Checkpoint fork detected! checkpoint_seq: {}, checkpoint_digest: {:?}",
2575                    checkpoint_seq,
2576                    checkpoint_digest
2577                ))
2578            }
2579        }
2580    }
2581
2582    async fn handle_transaction_fork(
2583        tx_digest: TransactionDigest,
2584        expected_effects_digest: TransactionEffectsDigest,
2585        actual_effects_digest: TransactionEffectsDigest,
2586        checkpoint_metrics: &CheckpointMetrics,
2587        fork_recovery: Option<&ForkRecoveryConfig>,
2588    ) -> Result<()> {
2589        checkpoint_metrics
2590            .transaction_fork_crash_mode
2591            .with_label_values(&[
2592                &Self::get_digest_prefix(tx_digest),
2593                &Self::get_digest_prefix(expected_effects_digest),
2594                &Self::get_digest_prefix(actual_effects_digest),
2595                &Self::get_current_timestamp().to_string(),
2596            ])
2597            .set(1);
2598
2599        let behavior = fork_recovery
2600            .map(|fr| fr.fork_crash_behavior)
2601            .unwrap_or_default();
2602
2603        match behavior {
2604            ForkCrashBehavior::AwaitForkRecovery | ForkCrashBehavior::RecoverOncePerVersion => {
2605                error!(
2606                    tx_digest = ?tx_digest,
2607                    expected_effects_digest = ?expected_effects_digest,
2608                    actual_effects_digest = ?actual_effects_digest,
2609                    "Transaction fork detected! Node startup halted. Sleeping indefinitely."
2610                );
2611                futures::future::pending::<()>().await;
2612                unreachable!("pending() should never return");
2613            }
2614            ForkCrashBehavior::ReturnError => {
2615                error!(
2616                    tx_digest = ?tx_digest,
2617                    expected_effects_digest = ?expected_effects_digest,
2618                    actual_effects_digest = ?actual_effects_digest,
2619                    "Transaction fork detected! Returning error."
2620                );
2621                Err(anyhow::anyhow!(
2622                    "Transaction fork detected! tx_digest: {:?}, expected_effects: {:?}, actual_effects: {:?}",
2623                    tx_digest,
2624                    expected_effects_digest,
2625                    actual_effects_digest
2626                ))
2627            }
2628        }
2629    }
2630}
2631
2632#[cfg(not(msim))]
2633impl SuiNode {
2634    async fn fetch_jwks(
2635        _authority: AuthorityName,
2636        provider: &OIDCProvider,
2637    ) -> SuiResult<Vec<(JwkId, JWK)>> {
2638        use fastcrypto_zkp::bn254::zk_login::fetch_jwks;
2639        use sui_types::error::SuiErrorKind;
2640        let client = reqwest::Client::new();
2641        fetch_jwks(provider, &client, true)
2642            .await
2643            .map_err(|_| SuiErrorKind::JWKRetrievalError.into())
2644    }
2645}
2646
2647#[cfg(msim)]
2648impl SuiNode {
2649    pub fn get_sim_node_id(&self) -> sui_simulator::task::NodeId {
2650        self.sim_state.sim_node.id()
2651    }
2652
2653    pub fn set_safe_mode_expected(&self, new_value: bool) {
2654        info!("Setting safe mode expected to {}", new_value);
2655        self.sim_state
2656            .sim_safe_mode_expected
2657            .store(new_value, Ordering::Relaxed);
2658    }
2659
2660    #[allow(unused_variables)]
2661    async fn fetch_jwks(
2662        authority: AuthorityName,
2663        provider: &OIDCProvider,
2664    ) -> SuiResult<Vec<(JwkId, JWK)>> {
2665        get_jwk_injector()(authority, provider)
2666    }
2667}
2668
2669enum SpawnOnce {
2670    // Mutex is only needed to make SpawnOnce Send
2671    Unstarted(oneshot::Receiver<()>, Mutex<BoxFuture<'static, ()>>),
2672    #[allow(unused)]
2673    Started(JoinHandle<()>),
2674}
2675
2676impl SpawnOnce {
2677    pub fn new(
2678        ready_rx: oneshot::Receiver<()>,
2679        future: impl Future<Output = ()> + Send + 'static,
2680    ) -> Self {
2681        Self::Unstarted(ready_rx, Mutex::new(Box::pin(future)))
2682    }
2683
2684    pub async fn start(self) -> Self {
2685        match self {
2686            Self::Unstarted(ready_rx, future) => {
2687                let future = future.into_inner();
2688                let handle = tokio::spawn(future);
2689                ready_rx.await.unwrap();
2690                Self::Started(handle)
2691            }
2692            Self::Started(_) => self,
2693        }
2694    }
2695}
2696
2697/// Updates trusted peer addresses in the p2p network (for nodes configured as validators).
2698/// When `prev_epoch_start_state` is provided, validators that are no longer in the committee
2699/// have their Chain addresses cleared.
2700fn update_peer_addresses(
2701    config: &NodeConfig,
2702    endpoint_manager: &EndpointManager,
2703    epoch_start_state: &EpochStartSystemState,
2704    prev_epoch_start_state: Option<&EpochStartSystemState>,
2705) {
2706    if config.consensus_config().is_none() {
2707        return;
2708    }
2709    let new_peers: HashSet<PeerId> = epoch_start_state
2710        .get_validator_as_p2p_peers(config.protocol_public_key())
2711        .into_iter()
2712        .map(|(peer_id, address)| {
2713            endpoint_manager
2714                .update_endpoint(
2715                    EndpointId::P2p(peer_id),
2716                    AddressSource::Chain,
2717                    vec![address],
2718                )
2719                .expect("Updating peer addresses should not fail");
2720            peer_id
2721        })
2722        .collect();
2723
2724    // Clear Chain addresses for validators that left the committee.
2725    if let Some(prev) = prev_epoch_start_state {
2726        for (peer_id, _) in prev.get_validator_as_p2p_peers(config.protocol_public_key()) {
2727            if !new_peers.contains(&peer_id) {
2728                endpoint_manager
2729                    .update_endpoint(EndpointId::P2p(peer_id), AddressSource::Chain, vec![])
2730                    .expect("Clearing peer addresses should not fail");
2731            }
2732        }
2733    }
2734}
2735
2736fn build_kv_store(
2737    state: &Arc<AuthorityState>,
2738    config: &NodeConfig,
2739    registry: &Registry,
2740) -> Result<Arc<TransactionKeyValueStore>> {
2741    let metrics = KeyValueStoreMetrics::new(registry);
2742    let db_store = TransactionKeyValueStore::new("rocksdb", metrics.clone(), state.clone());
2743
2744    let base_url = &config.transaction_kv_store_read_config.base_url;
2745
2746    if base_url.is_empty() {
2747        info!("no http kv store url provided, using local db only");
2748        return Ok(Arc::new(db_store));
2749    }
2750
2751    let base_url: url::Url = base_url.parse().tap_err(|e| {
2752        error!(
2753            "failed to parse config.transaction_kv_store_config.base_url ({:?}) as url: {}",
2754            base_url, e
2755        )
2756    })?;
2757
2758    let network_str = match state.get_chain_identifier().chain() {
2759        Chain::Mainnet => "/mainnet",
2760        _ => {
2761            info!("using local db only for kv store");
2762            return Ok(Arc::new(db_store));
2763        }
2764    };
2765
2766    let base_url = base_url.join(network_str)?.to_string();
2767    let http_store = HttpKVStore::new_kv(
2768        &base_url,
2769        config.transaction_kv_store_read_config.cache_size,
2770        metrics.clone(),
2771    )?;
2772    info!("using local key-value store with fallback to http key-value store");
2773    Ok(Arc::new(FallbackTransactionKVStore::new_kv(
2774        db_store,
2775        http_store,
2776        metrics,
2777        "json_rpc_fallback",
2778    )))
2779}
2780
2781async fn build_json_rpc_router(
2782    state: &Arc<AuthorityState>,
2783    transaction_orchestrator: &Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>>,
2784    config: &NodeConfig,
2785    prometheus_registry: &Registry,
2786) -> Result<axum::Router> {
2787    let traffic_controller = state.traffic_controller.clone();
2788    let mut server = JsonRpcServerBuilder::new(
2789        env!("CARGO_PKG_VERSION"),
2790        prometheus_registry,
2791        traffic_controller,
2792        config.policy_config.clone(),
2793    );
2794
2795    let kv_store = build_kv_store(state, config, prometheus_registry)?;
2796
2797    let metrics = Arc::new(JsonRpcMetrics::new(prometheus_registry));
2798    server.register_module(ReadApi::new(
2799        state.clone(),
2800        kv_store.clone(),
2801        metrics.clone(),
2802    ))?;
2803    server.register_module(CoinReadApi::new(
2804        state.clone(),
2805        kv_store.clone(),
2806        metrics.clone(),
2807    ))?;
2808
2809    // if run_with_range is enabled we want to prevent any transactions
2810    // run_with_range = None is normal operating conditions
2811    if config.run_with_range.is_none() {
2812        server.register_module(TransactionBuilderApi::new(state.clone()))?;
2813    }
2814    server.register_module(GovernanceReadApi::new(state.clone(), metrics.clone()))?;
2815    server.register_module(BridgeReadApi::new(state.clone(), metrics.clone()))?;
2816
2817    if let Some(transaction_orchestrator) = transaction_orchestrator {
2818        server.register_module(TransactionExecutionApi::new(
2819            state.clone(),
2820            transaction_orchestrator.clone(),
2821            metrics.clone(),
2822        ))?;
2823    }
2824
2825    let name_service_config = if let (
2826        Some(package_address),
2827        Some(registry_id),
2828        Some(reverse_registry_id),
2829    ) = (
2830        config.name_service_package_address,
2831        config.name_service_registry_id,
2832        config.name_service_reverse_registry_id,
2833    ) {
2834        sui_name_service::NameServiceConfig::new(package_address, registry_id, reverse_registry_id)
2835    } else {
2836        match state.get_chain_identifier().chain() {
2837            Chain::Mainnet => sui_name_service::NameServiceConfig::mainnet(),
2838            Chain::Testnet => sui_name_service::NameServiceConfig::testnet(),
2839            Chain::Unknown => sui_name_service::NameServiceConfig::default(),
2840        }
2841    };
2842
2843    server.register_module(IndexerApi::new(
2844        state.clone(),
2845        ReadApi::new(state.clone(), kv_store.clone(), metrics.clone()),
2846        kv_store,
2847        name_service_config,
2848        metrics,
2849        config.indexer_max_subscriptions,
2850    ))?;
2851    server.register_module(MoveUtils::new(state.clone()))?;
2852
2853    let server_type = config.jsonrpc_server_type();
2854
2855    Ok(server.to_router(server_type).await?)
2856}
2857
2858/// Remove the on-disk directory of the legacy `rpc-index` backend.
2859///
2860/// The embedded `sui-rpc-store` replaced the `RpcIndexStore` backend, which
2861/// wrote to `<db_path>/rpc-index`; that data is now dead. Remove it on startup
2862/// so a node upgraded from an older version does not leave it lingering and
2863/// wasting disk. Best-effort: a node that never ran the legacy backend has
2864/// nothing to remove, and a failure to remove stale data must not block
2865/// startup.
2866fn remove_legacy_rpc_index_store(db_path: &Path) {
2867    let legacy_dir = db_path.join("rpc-index");
2868    match std::fs::remove_dir_all(&legacy_dir) {
2869        Ok(()) => info!(
2870            "removed legacy rpc-index directory {}",
2871            legacy_dir.display()
2872        ),
2873        // The common case: the node never ran the legacy backend, or it was
2874        // already cleaned up on a prior startup.
2875        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2876        Err(e) => warn!(
2877            "failed to remove legacy rpc-index directory {}: {e:?}",
2878            legacy_dir.display()
2879        ),
2880    }
2881}
2882
2883async fn build_http_servers(
2884    state: Arc<AuthorityState>,
2885    store: RocksDbStore,
2886    transaction_orchestrator: &Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>>,
2887    config: &NodeConfig,
2888    prometheus_registry: &Registry,
2889    server_version: ServerVersion,
2890    node_role: NodeRole,
2891    embedded_rpc_store: Option<&EmbeddedRpcStore>,
2892) -> Result<(
2893    HttpServers,
2894    Option<tokio::sync::broadcast::Sender<Arc<Checkpoint>>>,
2895)> {
2896    // Validators do not expose these APIs
2897    if !node_role.is_fullnode() {
2898        return Ok((HttpServers::default(), None));
2899    }
2900
2901    info!("starting rpc service with config: {:?}", config.rpc);
2902
2903    let mut router = axum::Router::new();
2904
2905    // The JSON-RPC service can be disabled independently of the gRPC/REST
2906    // service and of JSON-RPC indexing, so that a node can keep indexing
2907    // without exposing the JSON-RPC endpoints.
2908    if config.json_rpc_enabled() {
2909        router = router.merge(
2910            build_json_rpc_router(
2911                &state,
2912                transaction_orchestrator,
2913                config,
2914                prometheus_registry,
2915            )
2916            .await?,
2917        );
2918    } else {
2919        info!("json-rpc service is disabled");
2920    }
2921
2922    // When the embedded rpc-store is active, gate checkpoint delivery on the
2923    // index so a client that waits for a checkpoint can immediately read its
2924    // indexed state (matching the legacy synchronously-committed index).
2925    let indexed_checkpoint = embedded_rpc_store.map(|embedded| embedded.indexed_checkpoint_fn());
2926    let subscription_watermark_interval = config
2927        .rpc
2928        .as_ref()
2929        .and_then(|rpc| rpc.subscription_watermark_interval);
2930    let subscription_max_subscribers = config
2931        .rpc
2932        .as_ref()
2933        .and_then(|rpc| rpc.subscription_max_subscribers);
2934    let subscription_shards = config.rpc.as_ref().and_then(|rpc| rpc.subscription_shards);
2935    let (subscription_service_checkpoint_sender, subscription_service_handle) =
2936        SubscriptionService::build(
2937            prometheus_registry,
2938            indexed_checkpoint,
2939            subscription_watermark_interval,
2940            subscription_max_subscribers,
2941            subscription_shards,
2942        );
2943    let rpc_router = {
2944        // Serve the index read paths from the embedded rpc-store when it
2945        // is enabled. Raw chain data comes from the perpetual / checkpoint
2946        // stores either way.
2947        let reader: Arc<dyn RpcStateReader> = match embedded_rpc_store {
2948            Some(embedded) => Arc::new(RpcStoreReadStore::new(
2949                state.clone(),
2950                store,
2951                embedded.reader(),
2952            )),
2953            None => Arc::new(RestReadStore::new(state.clone(), store)),
2954        };
2955        let mut rpc_service = sui_rpc_api::RpcService::new(reader);
2956        rpc_service.with_server_version(server_version);
2957
2958        if let Some(config) = config.rpc.clone() {
2959            config.validate()?;
2960            rpc_service.with_config(config);
2961        }
2962
2963        rpc_service.with_metrics(prometheus_registry);
2964        rpc_service.with_subscription_service(subscription_service_handle);
2965
2966        if let Some(transaction_orchestrator) = transaction_orchestrator {
2967            rpc_service.with_executor(transaction_orchestrator.clone())
2968        }
2969
2970        rpc_service.into_router().await
2971    };
2972
2973    let layers = ServiceBuilder::new()
2974        .map_request(|mut request: axum::http::Request<_>| {
2975            if let Some(connect_info) = request.extensions().get::<sui_http::ConnectInfo>() {
2976                let axum_connect_info = axum::extract::ConnectInfo(connect_info.remote_addr);
2977                request.extensions_mut().insert(axum_connect_info);
2978            }
2979            request
2980        })
2981        .layer(axum::middleware::from_fn(server_timing_middleware))
2982        // Setup a permissive CORS policy
2983        .layer(
2984            tower_http::cors::CorsLayer::new()
2985                .allow_methods([http::Method::GET, http::Method::POST])
2986                .allow_origin(tower_http::cors::Any)
2987                .allow_headers(tower_http::cors::Any)
2988                .expose_headers(tower_http::cors::Any),
2989        );
2990
2991    router = router.merge(rpc_router).layer(layers);
2992
2993    // On top of sui-http's hardened defaults (bounded concurrent streams;
2994    // transport keepalives stay disabled by default), bound connection
2995    // lifetime: GOAWAY at the configured age and force-close after the grace
2996    // period. The hard close is the only server-side mechanism that reclaims
2997    // streams wedged behind HTTP/2 flow-control windows that a stalled peer
2998    // never reopens, and connection age also bounds how long a vanished peer
2999    // can pin connection state, which keepalives would otherwise detect.
3000    let server_config = {
3001        let rpc_config = config.rpc().cloned().unwrap_or_default();
3002        let mut server_config = sui_http::Config::default()
3003            .max_connection_age_grace(rpc_config.max_connection_age_grace());
3004        if let Some(age) = rpc_config.max_connection_age() {
3005            server_config = server_config.max_connection_age(age);
3006        }
3007        server_config
3008    };
3009
3010    let https = if let Some((tls_config, https_address)) = config
3011        .rpc()
3012        .and_then(|config| config.tls_config().map(|tls| (tls, config.https_address())))
3013    {
3014        let tls_server_config = https_rustls_config(tls_config.cert(), tls_config.key())?;
3015        let https = sui_http::Builder::new()
3016            .config(server_config.clone())
3017            .tls_config(tls_server_config)
3018            .serve(https_address, router.clone())
3019            .map_err(|e| anyhow::anyhow!(e))?;
3020
3021        info!(
3022            https_address =? https.local_addr(),
3023            "HTTPS rpc server listening on {}",
3024            https.local_addr()
3025        );
3026
3027        Some(https)
3028    } else {
3029        None
3030    };
3031
3032    let http = sui_http::Builder::new()
3033        .config(server_config)
3034        .serve(&config.json_rpc_address, router)
3035        .map_err(|e| anyhow::anyhow!(e))?;
3036
3037    info!(
3038        http_address =? http.local_addr(),
3039        "HTTP rpc server listening on {}",
3040        http.local_addr()
3041    );
3042
3043    Ok((
3044        HttpServers {
3045            http: Some(http),
3046            https,
3047        },
3048        Some(subscription_service_checkpoint_sender),
3049    ))
3050}
3051
3052/// Builds the HTTPS RPC server's rustls config from PEM files, pinning the
3053/// ring crypto provider.
3054///
3055/// `sui_http::Builder::tls_single_cert` resolves the provider from rustls
3056/// crate features and panics at runtime when more than one provider feature is
3057/// enabled in the final binary (e.g. `aws-lc-rs` is pulled in through
3058/// `aws-config` in the `sui` CLI), so the provider is pinned explicitly here
3059/// instead.
3060fn https_rustls_config(cert: &str, key: &str) -> Result<sui_http::rustls::ServerConfig> {
3061    use sui_http::rustls;
3062    use sui_http::rustls::pki_types::pem::PemObject;
3063
3064    let certs = rustls::pki_types::CertificateDer::pem_file_iter(cert)
3065        .with_context(|| format!("failed to read TLS certificate chain from {cert}"))?
3066        .collect::<Result<Vec<_>, _>>()
3067        .with_context(|| format!("failed to parse TLS certificate chain from {cert}"))?;
3068    let private_key = rustls::pki_types::PrivateKeyDer::from_pem_file(key)
3069        .with_context(|| format!("failed to read TLS private key from {key}"))?;
3070    let config = rustls::ServerConfig::builder_with_provider(Arc::new(
3071        rustls::crypto::ring::default_provider(),
3072    ))
3073    .with_protocol_versions(rustls::DEFAULT_VERSIONS)?
3074    .with_no_client_auth()
3075    .with_single_cert(certs, private_key)?;
3076    Ok(config)
3077}
3078
3079#[derive(Default)]
3080struct HttpServers {
3081    #[allow(unused)]
3082    http: Option<sui_http::ServerHandle>,
3083    #[allow(unused)]
3084    https: Option<sui_http::ServerHandle>,
3085}
3086
3087#[cfg(test)]
3088mod tests {
3089    use super::*;
3090    use prometheus::Registry;
3091    use std::collections::BTreeMap;
3092    use sui_config::node::{ForkCrashBehavior, ForkRecoveryConfig};
3093    use sui_core::checkpoints::{CheckpointMetrics, CheckpointStore};
3094    use sui_types::digests::{CheckpointDigest, TransactionDigest, TransactionEffectsDigest};
3095
3096    // A present legacy `rpc-index` directory is removed, while its siblings
3097    // (notably the still-used jsonrpc `indexes` store) are left untouched, and a
3098    // missing directory is a no-op.
3099    #[test]
3100    fn removes_only_the_legacy_rpc_index_directory() {
3101        let db = tempfile::tempdir().unwrap();
3102        let legacy = db.path().join("rpc-index");
3103        let sibling = db.path().join("indexes");
3104        std::fs::create_dir(&legacy).unwrap();
3105        std::fs::create_dir(&sibling).unwrap();
3106        std::fs::write(legacy.join("CURRENT"), b"stale").unwrap();
3107
3108        remove_legacy_rpc_index_store(db.path());
3109        assert!(
3110            !legacy.exists(),
3111            "legacy rpc-index directory should be gone"
3112        );
3113        assert!(sibling.exists(), "sibling stores must be left untouched");
3114
3115        // Idempotent: a second run (nothing to remove) does not error or touch
3116        // the siblings.
3117        remove_legacy_rpc_index_store(db.path());
3118        assert!(!legacy.exists());
3119        assert!(sibling.exists());
3120    }
3121
3122    // Halt / ReturnError never clear markers; ReturnError surfaces the fork as a startup error.
3123    #[tokio::test]
3124    async fn test_return_error_does_not_recover() {
3125        let checkpoint_store = CheckpointStore::new_for_tests();
3126        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3127        let cfg = ForkRecoveryConfig {
3128            transaction_overrides: Default::default(),
3129            checkpoint_overrides: Default::default(),
3130            fork_crash_behavior: ForkCrashBehavior::ReturnError,
3131        };
3132
3133        // Checkpoint fork.
3134        checkpoint_store
3135            .record_checkpoint_fork_detected(
3136                42,
3137                CheckpointDigest::random(),
3138                Some(CheckpointDigest::random()),
3139            )
3140            .unwrap();
3141        let r = SuiNode::check_and_recover_forks(
3142            &checkpoint_store,
3143            &checkpoint_metrics,
3144            Some(&cfg),
3145            "v1",
3146        )
3147        .await;
3148        assert!(
3149            r.unwrap_err()
3150                .to_string()
3151                .contains("Checkpoint fork detected")
3152        );
3153        assert!(
3154            checkpoint_store
3155                .get_checkpoint_fork_detected()
3156                .unwrap()
3157                .is_some()
3158        );
3159        checkpoint_store.clear_checkpoint_fork_detected().unwrap();
3160
3161        // Transaction fork.
3162        checkpoint_store
3163            .record_transaction_fork_detected(
3164                TransactionDigest::random(),
3165                TransactionEffectsDigest::random(),
3166                TransactionEffectsDigest::random(),
3167                Some(1),
3168            )
3169            .unwrap();
3170        let r = SuiNode::check_and_recover_forks(
3171            &checkpoint_store,
3172            &checkpoint_metrics,
3173            Some(&cfg),
3174            "v1",
3175        )
3176        .await;
3177        assert!(
3178            r.unwrap_err()
3179                .to_string()
3180                .contains("Transaction fork detected")
3181        );
3182    }
3183
3184    // A fork marker carrying the currently running binary version is never cleared — the binary
3185    // that forked would deterministically fork again — so the node hangs until a corrected
3186    // binary (different version) runs recovery.
3187    #[tokio::test]
3188    async fn test_same_binary_version_does_not_recover() {
3189        let checkpoint_store = CheckpointStore::new_for_tests();
3190        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3191        let seq = 7;
3192        // The fork is recorded by binary "v1", against a certified checkpoint.
3193        checkpoint_store.set_binary_version("v1");
3194        checkpoint_store
3195            .record_checkpoint_fork_detected(
3196                seq,
3197                CheckpointDigest::random(),
3198                Some(CheckpointDigest::random()),
3199            )
3200            .unwrap();
3201
3202        // Restarting the same binary: recovery refused despite certification.
3203        SuiNode::try_recover_forks(&checkpoint_store, &checkpoint_metrics, "v1").unwrap();
3204        assert!(
3205            checkpoint_store
3206                .get_checkpoint_fork_detected()
3207                .unwrap()
3208                .is_some()
3209        );
3210        assert_eq!(
3211            checkpoint_metrics
3212                .fork_auto_recovery_awaiting_new_binary
3213                .get(),
3214            1
3215        );
3216        assert_eq!(checkpoint_metrics.checkpoint_fork_auto_recovered.get(), 0);
3217
3218        // Corrected binary (new version): recovers.
3219        SuiNode::try_recover_forks(&checkpoint_store, &checkpoint_metrics, "v2").unwrap();
3220        assert!(
3221            checkpoint_store
3222                .get_checkpoint_fork_detected()
3223                .unwrap()
3224                .is_none()
3225        );
3226        assert_eq!(checkpoint_metrics.checkpoint_fork_auto_recovered.get(), 1);
3227    }
3228
3229    // The default behavior (RecoverOncePerVersion) recovers with no fork-recovery config present.
3230    #[tokio::test]
3231    async fn test_default_recovers() {
3232        let checkpoint_store = CheckpointStore::new_for_tests();
3233        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3234
3235        let tx_digest = TransactionDigest::random();
3236        // The fork was recorded by binary "v1"; its expected effects came from certified
3237        // checkpoint 3, so recovery under "v2" is permitted.
3238        checkpoint_store.set_binary_version("v1");
3239        checkpoint_store
3240            .record_transaction_fork_detected(
3241                tx_digest,
3242                TransactionEffectsDigest::random(),
3243                TransactionEffectsDigest::random(),
3244                Some(3),
3245            )
3246            .unwrap();
3247
3248        let r =
3249            SuiNode::check_and_recover_forks(&checkpoint_store, &checkpoint_metrics, None, "v2")
3250                .await;
3251        assert!(r.is_ok());
3252        assert!(
3253            checkpoint_store
3254                .get_transaction_fork_detected()
3255                .unwrap()
3256                .is_none()
3257        );
3258        assert_eq!(checkpoint_metrics.transaction_fork_auto_recovered.get(), 1);
3259    }
3260
3261    // checkpoint_overrides clears only the checkpoint fork marker (when the forked seq is listed); it
3262    // is decoupled from the transaction fork marker, which is cleared by transaction_overrides.
3263    #[tokio::test]
3264    async fn test_checkpoint_overrides_clear_checkpoint_marker_only() {
3265        let checkpoint_store = CheckpointStore::new_for_tests();
3266        let seq = 9;
3267
3268        checkpoint_store
3269            .record_checkpoint_fork_detected(
3270                seq,
3271                CheckpointDigest::random(),
3272                Some(CheckpointDigest::random()),
3273            )
3274            .unwrap();
3275        checkpoint_store
3276            .record_transaction_fork_detected(
3277                TransactionDigest::random(),
3278                TransactionEffectsDigest::random(),
3279                TransactionEffectsDigest::random(),
3280                None,
3281            )
3282            .unwrap();
3283
3284        // No overrides: both markers are left intact.
3285        SuiNode::try_recover_checkpoint_fork(&checkpoint_store, &ForkRecoveryConfig::default())
3286            .unwrap();
3287        assert!(
3288            checkpoint_store
3289                .get_checkpoint_fork_detected()
3290                .unwrap()
3291                .is_some()
3292        );
3293        assert!(
3294            checkpoint_store
3295                .get_transaction_fork_detected()
3296                .unwrap()
3297                .is_some()
3298        );
3299
3300        // Override for the forked seq: clears the checkpoint marker but leaves the transaction marker.
3301        let mut checkpoint_overrides = BTreeMap::new();
3302        checkpoint_overrides.insert(seq, CheckpointDigest::random().to_string());
3303        let cfg = ForkRecoveryConfig {
3304            transaction_overrides: Default::default(),
3305            checkpoint_overrides,
3306            fork_crash_behavior: ForkCrashBehavior::AwaitForkRecovery,
3307        };
3308        SuiNode::try_recover_checkpoint_fork(&checkpoint_store, &cfg).unwrap();
3309        assert!(
3310            checkpoint_store
3311                .get_checkpoint_fork_detected()
3312                .unwrap()
3313                .is_none()
3314        );
3315        assert!(
3316            checkpoint_store
3317                .get_transaction_fork_detected()
3318                .unwrap()
3319                .is_some(),
3320            "checkpoint_overrides must not touch the transaction fork marker"
3321        );
3322    }
3323
3324    // transaction_overrides clears the transaction fork marker when the forked tx is listed.
3325    #[tokio::test]
3326    async fn test_transaction_overrides_clear_transaction_marker() {
3327        let checkpoint_store = CheckpointStore::new_for_tests();
3328        let tx_digest = TransactionDigest::random();
3329        checkpoint_store
3330            .record_transaction_fork_detected(
3331                tx_digest,
3332                TransactionEffectsDigest::random(),
3333                TransactionEffectsDigest::random(),
3334                None,
3335            )
3336            .unwrap();
3337
3338        // Unrelated override: marker stays.
3339        let mut transaction_overrides = BTreeMap::new();
3340        transaction_overrides.insert(TransactionDigest::random().to_string(), String::new());
3341        let cfg = ForkRecoveryConfig {
3342            transaction_overrides,
3343            checkpoint_overrides: Default::default(),
3344            fork_crash_behavior: ForkCrashBehavior::AwaitForkRecovery,
3345        };
3346        SuiNode::try_recover_transaction_fork(&checkpoint_store, &cfg).unwrap();
3347        assert!(
3348            checkpoint_store
3349                .get_transaction_fork_detected()
3350                .unwrap()
3351                .is_some()
3352        );
3353
3354        // Override for the forked tx: marker cleared.
3355        let mut transaction_overrides = BTreeMap::new();
3356        transaction_overrides.insert(tx_digest.to_string(), String::new());
3357        let cfg = ForkRecoveryConfig {
3358            transaction_overrides,
3359            checkpoint_overrides: Default::default(),
3360            fork_crash_behavior: ForkCrashBehavior::AwaitForkRecovery,
3361        };
3362        SuiNode::try_recover_transaction_fork(&checkpoint_store, &cfg).unwrap();
3363        assert!(
3364            checkpoint_store
3365                .get_transaction_fork_detected()
3366                .unwrap()
3367                .is_none()
3368        );
3369    }
3370
3371    // Under RecoverOncePerVersion, a checkpoint override clears the fork via the manual path
3372    // even when the auto path would refuse (here: the fork was recorded by the currently running
3373    // binary version and the sequence is not certified).
3374    #[tokio::test]
3375    async fn test_override_clears_fork_auto_recovery_refuses() {
3376        let checkpoint_store = CheckpointStore::new_for_tests();
3377        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3378        let seq = 5;
3379        checkpoint_store.set_binary_version("v1");
3380        checkpoint_store
3381            .record_checkpoint_fork_detected(
3382                seq,
3383                CheckpointDigest::random(),
3384                Some(CheckpointDigest::random()),
3385            )
3386            .unwrap();
3387
3388        let mut checkpoint_overrides = BTreeMap::new();
3389        checkpoint_overrides.insert(seq, CheckpointDigest::random().to_string());
3390        let cfg = ForkRecoveryConfig {
3391            transaction_overrides: Default::default(),
3392            checkpoint_overrides,
3393            fork_crash_behavior: ForkCrashBehavior::RecoverOncePerVersion,
3394        };
3395
3396        SuiNode::check_and_recover_forks(&checkpoint_store, &checkpoint_metrics, Some(&cfg), "v1")
3397            .await
3398            .unwrap();
3399
3400        assert!(
3401            checkpoint_store
3402                .get_checkpoint_fork_detected()
3403                .unwrap()
3404                .is_none()
3405        );
3406    }
3407
3408    // A self-divergence checkpoint fork (the builder re-derived its own previous checkpoint
3409    // differently; no certified digest in the marker) is never auto-recovered, even under a new
3410    // binary version, because neither result is proven canonical. It requires operator
3411    // overrides.
3412    #[tokio::test]
3413    async fn test_self_divergence_checkpoint_fork_blocks_recovery() {
3414        let checkpoint_store = CheckpointStore::new_for_tests();
3415        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3416        let seq = 17;
3417        checkpoint_store.set_binary_version("v1");
3418        checkpoint_store
3419            .record_checkpoint_fork_detected(seq, CheckpointDigest::random(), None)
3420            .unwrap();
3421
3422        SuiNode::try_recover_forks(&checkpoint_store, &checkpoint_metrics, "v2").unwrap();
3423
3424        assert!(
3425            checkpoint_store
3426                .get_checkpoint_fork_detected()
3427                .unwrap()
3428                .is_some()
3429        );
3430        assert_eq!(
3431            checkpoint_metrics
3432                .fork_auto_recovery_blocked_uncertified
3433                .get(),
3434            1
3435        );
3436        assert_eq!(checkpoint_metrics.checkpoint_fork_auto_recovered.get(), 0);
3437    }
3438
3439    // A transaction fork whose expected effects did not come from a certified checkpoint (i.e.
3440    // they came from this validator's own previously signed effects) is never auto-recovered,
3441    // even on a new binary version.
3442    #[tokio::test]
3443    async fn test_uncertified_transaction_fork_blocks_recovery() {
3444        let checkpoint_store = CheckpointStore::new_for_tests();
3445        let checkpoint_metrics = CheckpointMetrics::new(&Registry::new());
3446        checkpoint_store.set_binary_version("v1");
3447        checkpoint_store
3448            .record_transaction_fork_detected(
3449                TransactionDigest::random(),
3450                TransactionEffectsDigest::random(),
3451                TransactionEffectsDigest::random(),
3452                None,
3453            )
3454            .unwrap();
3455
3456        SuiNode::try_recover_forks(&checkpoint_store, &checkpoint_metrics, "v2").unwrap();
3457        SuiNode::try_recover_forks(&checkpoint_store, &checkpoint_metrics, "v3").unwrap();
3458
3459        assert!(
3460            checkpoint_store
3461                .get_transaction_fork_detected()
3462                .unwrap()
3463                .is_some()
3464        );
3465        assert_eq!(
3466            checkpoint_metrics
3467                .fork_auto_recovery_blocked_uncertified
3468                .get(),
3469            1
3470        );
3471    }
3472}