Skip to main content

iota_node/
lib.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6    collections::{BTreeSet, HashMap},
7    fmt,
8    future::Future,
9    num::{NonZeroU32, NonZeroUsize},
10    sync::{
11        Arc, Weak,
12        atomic::{AtomicBool, Ordering},
13    },
14    time::Duration,
15};
16
17use anemo::Network;
18use anemo_tower::{
19    callback::CallbackLayer,
20    trace::{DefaultMakeSpan, DefaultOnFailure, TraceLayer},
21};
22use anyhow::{Result, anyhow};
23use arc_swap::ArcSwap;
24use futures::future::BoxFuture;
25pub use handle::IotaNodeHandle;
26use iota_common::{debug_fatal, fatal};
27use iota_config::{
28    ConsensusConfig, NodeConfig, node::RunWithRange, node_config_metrics::NodeConfigMetrics,
29};
30use iota_core::{
31    authority::{
32        AuthorityState, AuthorityStore, ExecutionEnv, RandomnessRoundReceiver,
33        authority_per_epoch_store::AuthorityPerEpochStore,
34        authority_store_tables::{AuthorityPerpetualTables, AuthorityPerpetualTablesOptions},
35        backpressure::BackpressureManager,
36        epoch_start_configuration::{EpochFlag, EpochStartConfigTrait, EpochStartConfiguration},
37        shared_object_version_manager::Schedulable,
38    },
39    authority_aggregator::{
40        AggregatorSendCapabilityNotificationError, AuthAggMetrics, AuthorityAggregator,
41    },
42    authority_client::NetworkAuthorityClient,
43    authority_server::{
44        ValidatorService, ValidatorServiceMetrics, soft_lock::PreConsensusSoftLocks,
45    },
46    checkpoint_progress_tracker::CheckpointProgressTracker,
47    checkpoints::{
48        CheckpointMetrics, CheckpointService, CheckpointStore, FullCheckpointContentsCache,
49        FullCheckpointContentsCacheMetrics, SendCheckpointToStateSync, SubmitCheckpointToConsensus,
50        checkpoint_executor::{CheckpointExecutor, StopReason, metrics::CheckpointExecutorMetrics},
51    },
52    connection_monitor::ConnectionMonitor,
53    consensus_adapter::{
54        CheckConnection, ConnectionMonitorStatus, ConsensusAdapter, ConsensusAdapterMetrics,
55        ConsensusClient,
56    },
57    consensus_handler::ConsensusHandlerInitializer,
58    consensus_manager::{ConsensusManager, ConsensusManagerTrait, UpdatableConsensusClient},
59    consensus_validator::{IotaTxValidator, IotaTxValidatorMetrics},
60    epoch::{
61        committee_store::CommitteeStore, consensus_store_pruner::ConsensusStorePruner,
62        epoch_metrics::EpochMetrics, randomness::RandomnessManager,
63        reconfiguration::ReconfigurationInitiator,
64    },
65    epoch_buckets::HISTORIC_DB_DIR,
66    epoch_end_db_snapshot::{EpochEndDbSnapshotHandle, EpochEndDbSnapshotRequest},
67    execution_cache::build_execution_cache,
68    execution_scheduler::ExecutionSchedulerAPI,
69    global_state_hasher::{GlobalStateHashMetrics, GlobalStateHasher},
70    module_cache_metrics::ResolverMetrics,
71    overload_monitor::{consensus_queue_overload_monitor, overload_monitor},
72    rpc_indexes::{
73        RpcIndexesStore,
74        schema::{IndexGroup, RPC_INDEXES_DIR},
75    },
76    safe_client::SafeClientMetricsBase,
77    signature_verifier::SignatureVerifierMetrics,
78    storage::{GrpcReadStore, RocksDbStore},
79    transaction_orchestrator::TransactionOrchestrator,
80    validator_tx_finalizer::ValidatorTxFinalizer,
81};
82use iota_grpc_server::{GrpcReader, GrpcServerHandle, start_grpc_server};
83use iota_http::metrics::ListenerMetrics;
84use iota_json_rpc::{
85    JsonRpcServerBuilder, coin_api::CoinReadApi, governance_api::GovernanceReadApi,
86    indexer_api::IndexerApi, move_utils::MoveUtils, read_api::ReadApi,
87    transaction_builder_api::TransactionBuilderApi,
88    transaction_execution_api::TransactionExecutionApi,
89};
90use iota_json_rpc_api::JsonRpcMetrics;
91use iota_macros::{fail_point, fail_point_async, replay_log};
92use iota_metrics::{
93    RegistryID, RegistryService,
94    metrics_network::{MetricsMakeCallbackHandler, NetworkConnectionMetrics, NetworkMetrics},
95    server_timing_middleware, spawn_monitored_task,
96};
97use iota_names::config::IotaNamesConfig;
98use iota_network::{
99    api::{ValidatorPeerServer, ValidatorServer, ValidatorV2Server},
100    discovery,
101    discovery::TrustedPeerChangeEvent,
102    randomness, state_sync,
103};
104use iota_network_stack::server::{IOTA_TLS_SERVER_NAME, ServerBuilder};
105use iota_node_transaction_builder::NodeTransactionBuilderLedgerClient;
106use iota_protocol_config::{ProtocolConfig, ProtocolVersion};
107use iota_sdk_crypto::ToFromBytes as _;
108use iota_sdk_types::{
109    RandomnessRound,
110    crypto::{Intent, IntentMessage, IntentScope},
111};
112use iota_snapshot::uploader::StateSnapshotUploader;
113use iota_storage::{
114    http_key_value_store::HttpKVStore,
115    key_value_store::{
116        FallbackTransactionKVStore, TransactionKeyValueStore, TransactionKeyValueStoreTrait,
117    },
118    key_value_store_metrics::KeyValueStoreMetrics,
119};
120use iota_types::{
121    base_types::{AuthorityName, ConciseableName, EpochId},
122    committee::Committee,
123    crypto::{AuthoritySignature, IotaAuthoritySignature, KeypairTraits},
124    digests::ChainIdentifier,
125    error::{IotaError, IotaResult, UserInputError},
126    executable_transaction::VerifiedExecutableTransaction,
127    full_checkpoint_content::CheckpointData,
128    iota_system_state::{
129        IotaSystemState, IotaSystemStateTrait,
130        epoch_start_iota_system_state::{EpochStartSystemState, EpochStartSystemStateTrait},
131    },
132    messages_checkpoint::CheckpointSummaryExt,
133    messages_consensus::{
134        AuthorityCapabilitiesV1, ConsensusTransaction, ConsensusTransactionKind,
135        SignedAuthorityCapabilitiesV1, TransactionDenyRuleProposal,
136    },
137    messages_grpc::HandleCapabilityNotificationRequestV1,
138    quorum_driver_types::QuorumDriverEffectsQueueResult,
139    supported_protocol_versions::SupportedProtocolVersions,
140    transaction::{SenderSignedTransactionAPI, TransactionEnvelope, VerifiedCertificate},
141};
142use prometheus_filtered::{MetricLevel, Registry};
143#[cfg(msim)]
144use simulator::*;
145use tap::tap::TapFallible;
146use tokio::{
147    sync::{Mutex, broadcast, mpsc, watch},
148    task::{JoinHandle, JoinSet},
149};
150use tokio_util::sync::CancellationToken;
151use tower::ServiceBuilder;
152use tracing::{Instrument, debug, error, error_span, info, trace_span, warn};
153use typed_store::{
154    DBMetrics,
155    rocks::{check_and_mark_db_corruption, default_db_options, unmark_db_corruption},
156};
157
158use crate::metrics::{GrpcMetrics, IotaNodeMetrics};
159
160pub mod admin;
161mod handle;
162pub mod metrics;
163
164pub struct ValidatorComponents {
165    validator_server_handle: SpawnOnce,
166    validator_overload_monitor_handle: Option<JoinHandle<()>>,
167    /// Handle for the consensus queue overload monitor task, present only
168    /// when the certificate-less (P-COOL) flow is enabled. The
169    /// task self-terminates via `Weak` references; this handle exists purely
170    /// for ownership clarity.
171    consensus_queue_overload_monitor_handle: Option<JoinHandle<()>>,
172    /// Handle for the soft-lock expiry sweep task. The task self-terminates
173    /// via a `Weak` reference; this handle exists purely for ownership clarity.
174    soft_lock_sweep_handle: JoinHandle<()>,
175    overload_notifier_handle: Option<JoinHandle<()>>,
176    consensus_manager: Arc<ConsensusManager>,
177    consensus_store_pruner: ConsensusStorePruner,
178    consensus_adapter: Arc<ConsensusAdapter>,
179    soft_locks: Arc<PreConsensusSoftLocks>,
180    // Keeping the handle to the checkpoint service tasks to shut them down during reconfiguration.
181    checkpoint_service_tasks: JoinSet<()>,
182    checkpoint_metrics: Arc<CheckpointMetrics>,
183    iota_tx_validator_metrics: Arc<IotaTxValidatorMetrics>,
184    validator_registry_id: RegistryID,
185}
186
187#[cfg(msim)]
188mod simulator {
189    use std::sync::atomic::AtomicBool;
190
191    pub(super) struct SimState {
192        pub sim_node: iota_simulator::runtime::NodeHandle,
193        pub sim_safe_mode_expected: AtomicBool,
194        _leak_detector: iota_simulator::NodeLeakDetector,
195    }
196
197    impl Default for SimState {
198        fn default() -> Self {
199            Self {
200                sim_node: iota_simulator::runtime::NodeHandle::current(),
201                sim_safe_mode_expected: AtomicBool::new(false),
202                _leak_detector: iota_simulator::NodeLeakDetector::new(),
203            }
204        }
205    }
206}
207
208#[derive(Clone)]
209pub struct ServerVersion {
210    pub bin: &'static str,
211    pub version: &'static str,
212}
213
214impl ServerVersion {
215    pub fn new(bin: &'static str, version: &'static str) -> Self {
216        Self { bin, version }
217    }
218}
219
220impl std::fmt::Display for ServerVersion {
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        f.write_str(self.bin)?;
223        f.write_str("/")?;
224        f.write_str(self.version)
225    }
226}
227
228pub struct IotaNode {
229    config: NodeConfig,
230    validator_components: Mutex<Option<ValidatorComponents>>,
231    /// The http server responsible for serving JSON-RPC
232    _http_server: Option<iota_http::ServerHandle>,
233    state: Arc<AuthorityState>,
234    transaction_orchestrator: Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>>,
235    registry_service: RegistryService,
236    metrics: Arc<IotaNodeMetrics>,
237
238    _discovery: discovery::Handle,
239    state_sync_handle: state_sync::Handle,
240    randomness_handle: randomness::Handle,
241    /// Lets state sync fetch summaries to the end of the epoch being
242    /// executed; set for each epoch from `sync_summaries_to_epoch_end`.
243    sync_summaries_to_epoch_end: Arc<AtomicBool>,
244    checkpoint_store: Arc<CheckpointStore>,
245    state_sync_store: RocksDbStore,
246    global_state_hasher: Mutex<Option<Arc<GlobalStateHasher>>>,
247    connection_monitor_status: Arc<ConnectionMonitorStatus>,
248
249    /// Broadcast channel to send the starting system state for the next epoch.
250    end_of_epoch_channel: broadcast::Sender<IotaSystemState>,
251
252    /// Broadcast channel to notify [`DiscoveryEventLoop`] for new validator
253    /// peers.
254    trusted_peer_change_tx: watch::Sender<TrustedPeerChangeEvent>,
255
256    backpressure_manager: Arc<BackpressureManager>,
257
258    checkpoint_progress_tracker: Arc<CheckpointProgressTracker>,
259
260    #[cfg(msim)]
261    sim_state: SimState,
262
263    _state_snapshot_uploader_handle: Option<broadcast::Sender<()>>,
264    // Channel to allow signaling upstream to shutdown iota-node
265    shutdown_channel_tx: broadcast::Sender<Option<RunWithRange>>,
266
267    /// Handle to the gRPC server for gRPC streaming and graceful shutdown
268    grpc_server_handle: Mutex<Option<GrpcServerHandle>>,
269
270    /// AuthorityAggregator of the network, created at start and beginning of
271    /// each epoch. Use ArcSwap so that we could mutate it without taking
272    /// mut reference.
273    // TODO: Eventually we can make this auth aggregator a shared reference so that this
274    // update will automatically propagate to other uses.
275    auth_agg: Arc<ArcSwap<AuthorityAggregator<NetworkAuthorityClient>>>,
276
277    /// Runtime that hosts the client-facing servers and their per-request
278    /// handlers, isolating external request load from the node core.
279    serving_rt_handle: tokio::runtime::Handle,
280}
281
282impl fmt::Debug for IotaNode {
283    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
284        f.debug_struct("IotaNode")
285            .field("name", &self.state.name.concise())
286            .finish()
287    }
288}
289
290impl IotaNode {
291    /// Starts a node that hosts the client-facing servers on the caller's
292    /// runtime, alongside everything else.
293    ///
294    /// This is intentional: this entry point serves the in-process nodes of
295    /// iota-swarm, where a separate serving runtime is either impossible
296    /// (simtests must keep every task on the simulator's deterministic
297    /// scheduler) or not worth the threads (thread-mode swarm runs many nodes
298    /// per process). Only the `iota-node` binary isolates client-facing
299    /// request handling on the dedicated serving runtime of `IotaRuntimes`,
300    /// via [`IotaNode::start_async`].
301    pub async fn start(
302        config: NodeConfig,
303        registry_service: RegistryService,
304    ) -> Result<Arc<IotaNode>> {
305        Self::start_async(
306            config,
307            registry_service,
308            ServerVersion::new("iota-node", "unknown"),
309            tokio::runtime::Handle::current(),
310            Arc::default(),
311        )
312        .await
313    }
314
315    /// Starts a background task that polls the authority's load shedding
316    /// percentage and broadcasts changes to other validators via consensus.
317    /// Returns the task handle if the feature flag is enabled, or `None`
318    /// otherwise.
319    fn start_overload_notifier(
320        config: &NodeConfig,
321        state: Arc<AuthorityState>,
322        epoch_store: Arc<AuthorityPerEpochStore>,
323        consensus_adapter: Arc<ConsensusAdapter>,
324    ) -> Option<JoinHandle<()>> {
325        if !epoch_store.protocol_config().enable_pcool_flow() {
326            return None;
327        }
328
329        let poll_interval = config.authority_overload_config.overload_monitor_interval;
330        let authority_name = state.name;
331
332        Some(spawn_monitored_task!(async move {
333            // The percentage of the latest notification submitted, and the
334            // task that ends once this authority has processed it.
335            let mut latest_notification: Option<(u32, JoinHandle<()>)> = None;
336            loop {
337                tokio::time::sleep(poll_interval).await;
338                let current = state
339                    .overload_info
340                    .local_load_shedding_percentage
341                    .load(std::sync::atomic::Ordering::Relaxed);
342                let last_notified_percentage = match &latest_notification {
343                    // The recorded percentage is about to become this one.
344                    // Waiting for it would delay a change of the local
345                    // percentage by as long as this authority takes to
346                    // process its own notification.
347                    Some((percentage, task)) if !task.is_finished() => *percentage,
348                    _ => epoch_store
349                        .load_overload_notification(&authority_name)
350                        .unwrap_or(0) as u32,
351                };
352                // A notification processed once the epoch has stopped
353                // accepting certificates is not recorded, so the recorded
354                // percentage would never match and every poll would submit.
355                if current != last_notified_percentage
356                    && epoch_store
357                        .get_reconfig_state_read_lock_guard()
358                        .should_accept_consensus_certs()
359                {
360                    let transaction = ConsensusTransaction::new_overload_notification_v1(
361                        authority_name,
362                        current as u8,
363                    );
364                    match consensus_adapter.submit(transaction, None, &epoch_store) {
365                        Ok(task) => latest_notification = Some((current, task)),
366                        Err(e) => tracing::warn!(
367                            "Failed to submit overload notification to consensus: {:?}",
368                            e
369                        ),
370                    }
371                }
372            }
373        }))
374    }
375
376    /// Setting `index_rebuild_cancelled` stops an RPC index rebuild running
377    /// during startup, which no other shutdown path can reach.
378    pub async fn start_async(
379        mut config: NodeConfig,
380        registry_service: RegistryService,
381        server_version: ServerVersion,
382        serving_rt_handle: tokio::runtime::Handle,
383        index_rebuild_cancelled: Arc<AtomicBool>,
384    ) -> Result<Arc<IotaNode>> {
385        config.validate()?;
386        if config.maintains_rpc_indexes() {
387            config
388                .authority_store_pruning_config
389                .check_index_retention_within_ledger()?;
390        }
391        NodeConfigMetrics::new(&registry_service.default_registry()).record_metrics(&config);
392        if config.supported_protocol_versions.is_none() {
393            info!(
394                "populating config.supported_protocol_versions with default {:?}",
395                SupportedProtocolVersions::SYSTEM_DEFAULT
396            );
397            config.supported_protocol_versions = Some(SupportedProtocolVersions::SYSTEM_DEFAULT);
398        }
399
400        let run_with_range = config.run_with_range;
401        let is_validator = config.is_validator();
402        let is_full_node = !is_validator;
403        let prometheus_registry = registry_service.default_registry();
404
405        info!(node =? config.authority_public_key(),
406            "Initializing iota-node listening on {}", config.network_address
407        );
408
409        let genesis = config.genesis()?.clone();
410
411        let chain_identifier = ChainIdentifier::from(*genesis.checkpoint().digest());
412        info!("IOTA chain identifier: {chain_identifier}");
413
414        // Check and set the db_corrupted flag
415        let db_corrupted_path = &config.db_path().join("status");
416        if let Err(err) = check_and_mark_db_corruption(db_corrupted_path) {
417            panic!("Failed to check database corruption: {err}");
418        }
419
420        // Initialize metrics to track db usage before creating any stores
421        DBMetrics::init(&prometheus_registry);
422
423        // Initialize IOTA metrics.
424        iota_metrics::init_metrics(&prometheus_registry);
425        // Unsupported (because of the use of static variable) and unnecessary in
426        // simtests.
427        #[cfg(not(msim))]
428        iota_metrics::thread_stall_monitor::start_thread_stall_monitor();
429
430        // Monitor the node-core and serving runtimes so that worker-thread
431        // starvation between them is observable. Gated out of simtests, where
432        // tokio runs under the deterministic simulator.
433        #[cfg(not(msim))]
434        {
435            let runtime_monitor_metrics =
436                iota_metrics::runtime_metrics::RuntimeMonitorMetrics::new(&prometheus_registry);
437            iota_metrics::runtime_metrics::start_runtime_monitor(
438                "iota_node",
439                &tokio::runtime::Handle::current(),
440                runtime_monitor_metrics.clone(),
441            );
442            iota_metrics::runtime_metrics::start_runtime_monitor(
443                "serving",
444                &serving_rt_handle,
445                runtime_monitor_metrics,
446            );
447        }
448
449        // Register uptime metric
450        prometheus_registry
451            .register(iota_metrics::uptime_metric(
452                if is_validator {
453                    "validator"
454                } else {
455                    "fullnode"
456                },
457                server_version.version,
458                &chain_identifier.to_string(),
459            ))
460            .expect("Failed registering uptime metric");
461
462        let secret = Arc::pin(config.authority_key_pair().copy());
463        let genesis_committee = genesis.committee()?;
464        let committee_store = Arc::new(CommitteeStore::new(
465            config.db_path().join("epochs"),
466            &genesis_committee,
467            None,
468        ));
469
470        AuthorityPerpetualTables::ensure_per_epoch_layout(&config.db_path().join("store"))
471            .map_err(|e| anyhow!("refusing to start: {e}"))?;
472
473        let historic_db_path = config.db_path().join(HISTORIC_DB_DIR);
474
475        // By default, only enable write stall on validators for perpetual db.
476        let enable_write_stall = config.enable_db_write_stall.unwrap_or(is_validator);
477        let perpetual_tables_options = AuthorityPerpetualTablesOptions {
478            enable_write_stall,
479            historic_db_path: Some(historic_db_path.clone()),
480        };
481        let (perpetual_tables, historic_objects, historic_ledger, epoch_markers) =
482            AuthorityPerpetualTables::open_with_historic_objects(
483                &config.db_path().join("store"),
484                Some(perpetual_tables_options),
485            )?;
486        let perpetual_tables = Arc::new(perpetual_tables);
487        let historic_objects = Arc::new(historic_objects);
488        let historic_ledger = Arc::new(historic_ledger);
489        let is_genesis = perpetual_tables
490            .database_is_empty()
491            .expect("Database read should not fail at init.");
492
493        let checkpoint_store = CheckpointStore::new_with_contents_cache(
494            &config.db_path().join("checkpoints"),
495            Some(&historic_db_path),
496            FullCheckpointContentsCache::new(
497                config
498                    .full_checkpoint_contents_cache_size_mb
499                    .saturating_mul(1024 * 1024),
500                FullCheckpointContentsCacheMetrics::new(&prometheus_registry),
501            ),
502        );
503
504        // The migration data is only needed to initialize an empty database and to
505        // execute the migration transactions, which are part of the genesis
506        // checkpoint. Loading it also leads to re-executing every migration
507        // transaction, so skip it once the genesis checkpoint has been executed.
508        let genesis_checkpoint_executed = checkpoint_store
509            .get_highest_executed_checkpoint_seq_number()?
510            .is_some();
511        let migration_tx_data =
512            if genesis.contains_migrations() && (is_genesis || !genesis_checkpoint_executed) {
513                // Here the load already verifies that the content of the migration blob is
514                // valid in respect to the content found in genesis
515                Some(config.load_migration_tx_data()?)
516            } else {
517                None
518            };
519
520        let chain = match config.chain_override_for_testing {
521            Some(chain) => chain,
522            None => chain_identifier.chain(),
523        };
524        let backpressure_manager =
525            BackpressureManager::new_from_checkpoint_store(&checkpoint_store);
526
527        let historic_objects_for_progress = historic_objects.clone();
528        let perpetual_tables_for_snapshots = perpetual_tables.clone();
529        let store = AuthorityStore::open(
530            perpetual_tables,
531            historic_objects,
532            historic_ledger,
533            Arc::new(epoch_markers),
534            &genesis,
535            &config,
536            &prometheus_registry,
537            migration_tx_data.as_ref(),
538        )
539        .await?;
540
541        let cur_epoch = store.get_recovery_epoch_at_restart()?;
542        let committee = committee_store
543            .get_committee(&cur_epoch)?
544            .expect("Committee of the current epoch must exist");
545        let epoch_start_configuration = store
546            .get_epoch_start_configuration()?
547            .expect("EpochStartConfiguration of the current epoch must exist");
548        let cache_metrics = Arc::new(ResolverMetrics::new(&prometheus_registry));
549        let signature_verifier_metrics = SignatureVerifierMetrics::new(&prometheus_registry);
550
551        let cache_traits = build_execution_cache(
552            &config.execution_cache_config,
553            &prometheus_registry,
554            &store,
555            backpressure_manager.clone(),
556        );
557
558        let auth_agg = {
559            let safe_client_metrics_base = SafeClientMetricsBase::new(&prometheus_registry);
560            let auth_agg_metrics = Arc::new(AuthAggMetrics::new(&prometheus_registry));
561            Arc::new(ArcSwap::new(Arc::new(
562                AuthorityAggregator::new_from_epoch_start_state(
563                    epoch_start_configuration.epoch_start_state(),
564                    &committee_store,
565                    safe_client_metrics_base,
566                    auth_agg_metrics,
567                ),
568            )))
569        };
570
571        let epoch_options = default_db_options().optimize_db_for_write_throughput(4);
572        let epoch_store = AuthorityPerEpochStore::new(
573            config.authority_public_key(),
574            committee.clone(),
575            &config.db_path().join("store"),
576            Some(epoch_options.options),
577            EpochMetrics::new(&registry_service.default_registry()),
578            epoch_start_configuration,
579            cache_traits.backing_package_store.clone(),
580            cache_metrics,
581            signature_verifier_metrics,
582            &config.expensive_safety_check_config,
583            (chain_identifier, chain),
584            checkpoint_store
585                .get_highest_executed_checkpoint_seq_number()
586                .expect("checkpoint store read cannot fail")
587                .unwrap_or(0),
588        )?;
589
590        info!("created epoch store");
591
592        replay_log!(
593            "Beginning replay run. Epoch: {:?}, Protocol config: {:?}",
594            epoch_store.epoch(),
595            epoch_store.protocol_config()
596        );
597
598        // the database is empty at genesis time
599        if is_genesis {
600            info!("checking IOTA conservation at genesis");
601            // When we are opening the db table, the only time when it's safe to
602            // check IOTA conservation is at genesis. Otherwise we may be in the middle of
603            // an epoch and the IOTA conservation check will fail. This also initialize
604            // the expected_network_iota_amount table.
605            cache_traits
606                .reconfig_api
607                .try_expensive_check_iota_conservation(&epoch_store, None)
608                .expect("IOTA conservation check cannot fail at genesis");
609        }
610
611        let effective_buffer_stake = epoch_store.get_effective_buffer_stake_bps();
612        let default_buffer_stake = epoch_store
613            .protocol_config()
614            .buffer_stake_for_protocol_upgrade_bps();
615        if effective_buffer_stake != default_buffer_stake {
616            warn!(
617                ?effective_buffer_stake,
618                ?default_buffer_stake,
619                "buffer_stake_for_protocol_upgrade_bps is currently overridden"
620            );
621        }
622
623        checkpoint_store.insert_genesis_checkpoint(
624            genesis.checkpoint(),
625            genesis.checkpoint_contents().clone(),
626            &epoch_store,
627        );
628
629        // Database has everything from genesis, set corrupted key to 0
630        unmark_db_corruption(db_corrupted_path)?;
631
632        // As at an epoch change, before state sync marks anything synced.
633        if epoch_store.protocol_config().enable_pcool_flow()
634            && epoch_store
635                .committee()
636                .authority_exists(&config.authority_public_key())
637        {
638            checkpoint_store
639                .hold_synced_watermark_in_memory(store.get_historic_ledger().clone())?;
640        }
641
642        info!("creating state sync store");
643        let state_sync_store = RocksDbStore::new(
644            cache_traits.clone(),
645            committee_store.clone(),
646            checkpoint_store.clone(),
647        );
648
649        let mut index_groups = BTreeSet::new();
650        if is_full_node && config.enable_jsonrpc_api {
651            index_groups.insert(IndexGroup::JsonRpc);
652        }
653        if is_full_node && config.enable_grpc_api {
654            index_groups.insert(IndexGroup::Grpc);
655        }
656        let rpc_indexes_store = if index_groups.is_empty() {
657            None
658        } else {
659            info!("creating index store");
660            let epochs_to_retain = config
661                .authority_store_pruning_config
662                .num_epochs_to_retain_for_indexes();
663            if epochs_to_retain.is_none() {
664                warn!(
665                    "index pruning is off: the history index backing iotax_queryTransactionBlocks() and iotax_queryEvents() adds a column family per epoch and grows without bound. Set num-epochs-to-retain-for-checkpoints, which num-epochs-to-retain-for-indexes follows, or num-epochs-to-retain-for-indexes itself"
666                );
667            }
668            Some(
669                RpcIndexesStore::new(
670                    config.db_path().join(RPC_INDEXES_DIR),
671                    Some(&historic_db_path),
672                    &prometheus_registry,
673                    index_groups,
674                    epoch_store
675                        .protocol_config()
676                        .max_move_identifier_len_as_option(),
677                    epochs_to_retain,
678                    &store,
679                    &checkpoint_store,
680                    index_rebuild_cancelled,
681                )
682                .await?,
683            )
684        };
685
686        // Seed the open epoch's `epoch_info` row before services start.
687        checkpoint_store
688            .seed_epoch_info(&store, chain_identifier)
689            .expect("failed to seed the epoch_info chain");
690
691        info!("creating archive reader");
692        // Create network
693        // TODO only configure validators as seed/preferred peers for validators and not
694        // for fullnodes once we've had a chance to re-work fullnode
695        // configuration generation.
696        let (trusted_peer_change_tx, trusted_peer_change_rx) = watch::channel(Default::default());
697        let (randomness_tx, randomness_rx) = mpsc::channel(
698            config
699                .p2p_config
700                .randomness
701                .clone()
702                .unwrap_or_default()
703                .mailbox_capacity(),
704        );
705        let sync_summaries_to_epoch_end = Arc::new(AtomicBool::new(
706            Self::sync_summaries_to_epoch_end(&config, &epoch_store),
707        ));
708        let (p2p_network, discovery_handle, state_sync_handle, randomness_handle) =
709            Self::create_p2p_network(
710                &config,
711                state_sync_store.clone(),
712                chain_identifier,
713                trusted_peer_change_rx,
714                randomness_tx,
715                sync_summaries_to_epoch_end.clone(),
716                &prometheus_registry,
717            )?;
718
719        // We must explicitly send this instead of relying on the initial value to
720        // trigger watch value change, so that state-sync is able to process it.
721        send_trusted_peer_change(
722            &config,
723            &trusted_peer_change_tx,
724            epoch_store.epoch_start_state(),
725        );
726
727        info!("start snapshot upload");
728        // The state snapshot writer is the consumer of the epoch end database
729        // snapshot: the boundary hands each epoch to it on this channel. A
730        // depth of one is enough, because an epoch arriving while the writer
731        // is still busy is skipped rather than queued.
732        let (state_snapshot_requests, state_snapshot_receiver) = mpsc::channel(1);
733        let state_snapshot_handle = Self::start_state_snapshot(
734            &config,
735            &prometheus_registry,
736            checkpoint_store.clone(),
737            perpetual_tables_for_snapshots,
738            state_snapshot_receiver,
739        )?;
740        let epoch_end_db_snapshots = state_snapshot_handle
741            .is_some()
742            .then(|| EpochEndDbSnapshotHandle::new(state_snapshot_requests));
743
744        let checkpoint_progress_tracker = Arc::new(CheckpointProgressTracker::new());
745
746        let authority_name = config.authority_public_key();
747        let validator_tx_finalizer =
748            config
749                .enable_validator_tx_finalizer
750                .then_some(Arc::new(ValidatorTxFinalizer::new(
751                    auth_agg.clone(),
752                    authority_name,
753                    &prometheus_registry,
754                )));
755
756        info!("create authority state");
757        let state = AuthorityState::new(
758            authority_name,
759            secret,
760            config.supported_protocol_versions.unwrap(),
761            store.clone(),
762            cache_traits.clone(),
763            epoch_store.clone(),
764            committee_store.clone(),
765            rpc_indexes_store,
766            checkpoint_store.clone(),
767            &prometheus_registry,
768            config.clone(),
769            validator_tx_finalizer,
770            chain_identifier,
771            config.policy_config.clone(),
772            epoch_end_db_snapshots,
773        )
774        .await;
775
776        // ensure genesis and migration txs were executed
777        if epoch_store.epoch() == 0 {
778            let genesis_tx = &genesis.transaction();
779            let span = error_span!("genesis_txn", tx_digest = ?genesis_tx.digest());
780            // Execute genesis transaction
781            Self::execute_transaction_immediately_at_zero_epoch(
782                &state,
783                &epoch_store,
784                genesis_tx,
785                span,
786            )
787            .await;
788
789            // Execute migration transactions if present
790            if let Some(migration_tx_data) = migration_tx_data {
791                for (tx_digest, (tx, _, _)) in migration_tx_data.txs_data() {
792                    let span = error_span!("migration_txn", tx_digest = ?tx_digest);
793                    Self::execute_transaction_immediately_at_zero_epoch(
794                        &state,
795                        &epoch_store,
796                        tx,
797                        span,
798                    )
799                    .await;
800                }
801            }
802        }
803
804        // Start the loop that receives new randomness and generates transactions for
805        // it.
806        RandomnessRoundReceiver::spawn(state.clone(), randomness_rx);
807
808        let (end_of_epoch_channel, end_of_epoch_receiver) =
809            broadcast::channel(config.end_of_epoch_broadcast_channel_capacity);
810
811        let transaction_orchestrator = if is_full_node && run_with_range.is_none() {
812            Some(Arc::new(TransactionOrchestrator::new_with_auth_aggregator(
813                auth_agg.load_full(),
814                state.clone(),
815                end_of_epoch_receiver,
816                &config.db_path(),
817                &prometheus_registry,
818                Some(&config),
819            )))
820        } else {
821            None
822        };
823
824        // Only the JSON-RPC and gRPC APIs read the store, and validators expose neither.
825        let kv_store =
826            if config.is_validator() || !(config.enable_jsonrpc_api || config.enable_grpc_api) {
827                None
828            } else {
829                Some(SharedKeyValueStore::new(&config, &prometheus_registry)?)
830            };
831
832        // Run the JSON-RPC server (and its per-request handlers) on the serving
833        // runtime. `iota_http::Builder::serve` spawns the accept loop via
834        // `Handle::current()`, so the builder must execute on the serving runtime.
835        let http_server = if config.is_validator() {
836            None
837        } else {
838            let json_rpc_store = kv_store
839                .as_ref()
840                .filter(|_| config.enable_jsonrpc_api)
841                .map(|kv_store| kv_store.json_rpc_store(&state));
842            Some(
843                serving_rt_handle
844                    .spawn({
845                        let state = state.clone();
846                        let transaction_orchestrator = transaction_orchestrator.clone();
847                        let config = config.clone();
848                        let prometheus_registry = prometheus_registry.clone();
849                        async move {
850                            build_http_server(
851                                state,
852                                &transaction_orchestrator,
853                                &config,
854                                &prometheus_registry,
855                                json_rpc_store,
856                            )
857                            .await
858                        }
859                    })
860                    .await
861                    .expect("Failed to join JSON-RPC server startup task")?,
862            )
863        };
864
865        let global_state_hasher = Arc::new(GlobalStateHasher::new(
866            cache_traits.global_state_hash_store.clone(),
867            GlobalStateHashMetrics::new(&prometheus_registry),
868        ));
869
870        let authority_names_to_peer_ids = epoch_store
871            .epoch_start_state()
872            .get_authority_names_to_peer_ids();
873
874        let network_connection_metrics =
875            NetworkConnectionMetrics::new("iota", &registry_service.default_registry());
876
877        let authority_names_to_peer_ids = ArcSwap::from_pointee(authority_names_to_peer_ids);
878
879        let (_connection_monitor_handle, connection_statuses) = ConnectionMonitor::spawn(
880            p2p_network.downgrade(),
881            network_connection_metrics,
882            HashMap::new(),
883            None,
884        );
885
886        let connection_monitor_status = ConnectionMonitorStatus {
887            connection_statuses,
888            authority_names_to_peer_ids,
889        };
890
891        let connection_monitor_status = Arc::new(connection_monitor_status);
892        let iota_node_metrics =
893            Arc::new(IotaNodeMetrics::new(&registry_service.default_registry()));
894
895        iota_node_metrics
896            .binary_max_protocol_version
897            .set(ProtocolVersion::MAX.as_u64() as i64);
898        iota_node_metrics
899            .configured_max_protocol_version
900            .set(config.supported_protocol_versions.unwrap().max.as_u64() as i64);
901
902        // Convert transaction orchestrator to executor trait object for gRPC server
903        // Note that the transaction_orchestrator (so as executor) will be None if it is
904        // a validator node or run_with_range is set
905        let executor: Option<Arc<dyn iota_types::transaction_executor::TransactionExecutor>> =
906            transaction_orchestrator
907                .clone()
908                .map(|o| o as Arc<dyn iota_types::transaction_executor::TransactionExecutor>);
909
910        // Run the gRPC read API server (and its per-request handlers) on the
911        // serving runtime, for the same reason as the JSON-RPC server above.
912        let grpc_server_handle = serving_rt_handle
913            .spawn({
914                let config = config.clone();
915                let state = state.clone();
916                let state_sync_store = state_sync_store.clone();
917                let prometheus_registry = prometheus_registry.clone();
918                let transaction_fallback = kv_store.and_then(|kv_store| kv_store.grpc_store());
919                async move {
920                    build_grpc_server(
921                        &config,
922                        state,
923                        state_sync_store,
924                        executor,
925                        &prometheus_registry,
926                        server_version,
927                        transaction_fallback,
928                    )
929                    .await
930                }
931            })
932            .await
933            .expect("Failed to join gRPC server startup task")?;
934
935        let validator_components = if state.is_committee_validator(&epoch_store) {
936            let (components, _) = futures::join!(
937                Self::construct_validator_components(
938                    config.clone(),
939                    state.clone(),
940                    committee,
941                    epoch_store.clone(),
942                    checkpoint_store.clone(),
943                    state_sync_handle.clone(),
944                    randomness_handle.clone(),
945                    Arc::downgrade(&global_state_hasher),
946                    backpressure_manager.clone(),
947                    connection_monitor_status.clone(),
948                    &registry_service,
949                    serving_rt_handle.clone(),
950                ),
951                Self::reexecute_pending_consensus_certs(&epoch_store, &state,)
952            );
953            let mut components = components?;
954
955            components.consensus_adapter.submit_recovered(&epoch_store);
956
957            // Start the gRPC server
958            components.validator_server_handle = components.validator_server_handle.start().await;
959
960            Some(components)
961        } else {
962            None
963        };
964
965        // setup shutdown channel
966        let (shutdown_channel, _) = broadcast::channel::<Option<RunWithRange>>(1);
967
968        let node = Self {
969            config,
970            validator_components: Mutex::new(validator_components),
971            _http_server: http_server,
972            state,
973            transaction_orchestrator,
974            registry_service,
975            metrics: iota_node_metrics,
976
977            _discovery: discovery_handle,
978            state_sync_handle,
979            randomness_handle,
980            sync_summaries_to_epoch_end,
981            checkpoint_store,
982            state_sync_store,
983            global_state_hasher: Mutex::new(Some(global_state_hasher)),
984            end_of_epoch_channel,
985            connection_monitor_status,
986            trusted_peer_change_tx,
987            backpressure_manager,
988            checkpoint_progress_tracker: checkpoint_progress_tracker.clone(),
989
990            #[cfg(msim)]
991            sim_state: Default::default(),
992
993            _state_snapshot_uploader_handle: state_snapshot_handle,
994            shutdown_channel_tx: shutdown_channel,
995
996            grpc_server_handle: Mutex::new(grpc_server_handle),
997
998            auth_agg,
999
1000            serving_rt_handle,
1001        };
1002
1003        info!("IotaNode started!");
1004        let node = Arc::new(node);
1005        let node_copy = node.clone();
1006        spawn_monitored_task!(async move {
1007            let result = Self::monitor_reconfiguration(node_copy, epoch_store).await;
1008            if let Err(error) = result {
1009                warn!("Reconfiguration finished with error {:?}", error);
1010            }
1011        });
1012
1013        node.checkpoint_progress_tracker
1014            .spawn_logging_task(node.checkpoint_store.clone(), historic_objects_for_progress);
1015
1016        Ok(node)
1017    }
1018
1019    pub fn subscribe_to_epoch_change(&self) -> broadcast::Receiver<IotaSystemState> {
1020        self.end_of_epoch_channel.subscribe()
1021    }
1022
1023    pub fn subscribe_to_shutdown_channel(&self) -> broadcast::Receiver<Option<RunWithRange>> {
1024        self.shutdown_channel_tx.subscribe()
1025    }
1026
1027    pub fn current_epoch_for_testing(&self) -> EpochId {
1028        self.state.current_epoch_for_testing()
1029    }
1030
1031    // Init reconfig process by starting to reject user certs
1032    pub async fn close_epoch(&self, epoch_store: &Arc<AuthorityPerEpochStore>) -> IotaResult {
1033        info!("close_epoch (current epoch = {})", epoch_store.epoch());
1034        self.validator_components
1035            .lock()
1036            .await
1037            .as_ref()
1038            .ok_or_else(|| IotaError::from("Node is not a validator"))?
1039            .consensus_adapter
1040            .close_epoch(epoch_store);
1041        Ok(())
1042    }
1043
1044    pub fn clear_override_protocol_upgrade_buffer_stake(&self, epoch: EpochId) -> IotaResult {
1045        self.state
1046            .clear_override_protocol_upgrade_buffer_stake(epoch)
1047    }
1048
1049    pub fn set_override_protocol_upgrade_buffer_stake(
1050        &self,
1051        epoch: EpochId,
1052        buffer_stake_bps: u64,
1053    ) -> IotaResult {
1054        self.state
1055            .set_override_protocol_upgrade_buffer_stake(epoch, buffer_stake_bps)
1056    }
1057
1058    // Testing-only API to start epoch close process.
1059    // For production code, please use the non-testing version.
1060    pub async fn close_epoch_for_testing(&self) -> IotaResult {
1061        let epoch_store = self.state.epoch_store_for_testing();
1062        self.close_epoch(&epoch_store).await
1063    }
1064
1065    /// Creates a StateSnapshotUploader and starts it if
1066    /// `state-snapshot-write-config.object-store-config` is set. Snapshot
1067    /// publication is a fullnode-only role.
1068    fn start_state_snapshot(
1069        config: &NodeConfig,
1070        prometheus_registry: &Registry,
1071        checkpoint_store: Arc<CheckpointStore>,
1072        perpetual_tables: Arc<AuthorityPerpetualTables>,
1073        requests: mpsc::Receiver<EpochEndDbSnapshotRequest>,
1074    ) -> Result<Option<tokio::sync::broadcast::Sender<()>>> {
1075        if let Some(remote_store_config) = &config.state_snapshot_write_config.object_store_config {
1076            debug_assert!(
1077                !config.is_validator(),
1078                "`NodeConfig::validate` rejects snapshot upload on a validator"
1079            );
1080            let snapshot_uploader = StateSnapshotUploader::new(
1081                &config.snapshot_path(),
1082                remote_store_config.clone(),
1083                config.state_snapshot_write_config.concurrency,
1084                60,
1085                prometheus_registry,
1086                checkpoint_store,
1087                perpetual_tables,
1088            )?;
1089            Ok(Some(snapshot_uploader.start(requests)))
1090        } else {
1091            Ok(None)
1092        }
1093    }
1094
1095    /// Whether state sync should fetch summaries to the end of the epoch of
1096    /// `epoch_store`: this node is in its committee and waits for its own
1097    /// checkpoints there.
1098    fn sync_summaries_to_epoch_end(
1099        config: &NodeConfig,
1100        epoch_store: &AuthorityPerEpochStore,
1101    ) -> bool {
1102        config.is_validator() && epoch_store.pcool_bookkeeping_enabled()
1103    }
1104
1105    fn create_p2p_network(
1106        config: &NodeConfig,
1107        state_sync_store: RocksDbStore,
1108        chain_identifier: ChainIdentifier,
1109        trusted_peer_change_rx: watch::Receiver<TrustedPeerChangeEvent>,
1110        randomness_tx: mpsc::Sender<(EpochId, RandomnessRound, Vec<u8>)>,
1111        sync_summaries_to_epoch_end: Arc<AtomicBool>,
1112        prometheus_registry: &Registry,
1113    ) -> Result<(
1114        Network,
1115        discovery::Handle,
1116        state_sync::Handle,
1117        randomness::Handle,
1118    )> {
1119        let (state_sync, state_sync_router) = state_sync::Builder::new()
1120            .config(config.p2p_config.state_sync.clone().unwrap_or_default())
1121            .store(state_sync_store)
1122            .checkpoint_archive_config(config.checkpoint_archive_config().cloned())
1123            .sync_summaries_to_epoch_end(sync_summaries_to_epoch_end)
1124            .with_metrics(prometheus_registry)
1125            .build();
1126
1127        let (discovery, discovery_server) = discovery::Builder::new(trusted_peer_change_rx)
1128            .config(config.p2p_config.clone())
1129            .build();
1130
1131        let (randomness, randomness_router) =
1132            randomness::Builder::new(config.authority_public_key(), randomness_tx)
1133                .config(config.p2p_config.randomness.clone().unwrap_or_default())
1134                .with_metrics(prometheus_registry)
1135                .build();
1136
1137        let p2p_network = {
1138            let routes = anemo::Router::new()
1139                .add_rpc_service(discovery_server)
1140                .merge(state_sync_router);
1141            let routes = routes.merge(randomness_router);
1142
1143            let inbound_network_metrics =
1144                NetworkMetrics::new("iota", "inbound", prometheus_registry);
1145            let outbound_network_metrics =
1146                NetworkMetrics::new("iota", "outbound", prometheus_registry);
1147
1148            let service = ServiceBuilder::new()
1149                .layer(
1150                    TraceLayer::new_for_server_errors()
1151                        .make_span_with(DefaultMakeSpan::new().level(tracing::Level::INFO))
1152                        .on_failure(DefaultOnFailure::new().level(tracing::Level::WARN)),
1153                )
1154                .layer(CallbackLayer::new(MetricsMakeCallbackHandler::new(
1155                    Arc::new(inbound_network_metrics),
1156                    config.p2p_config.excessive_message_size(),
1157                )))
1158                .service(routes);
1159
1160            let outbound_layer = ServiceBuilder::new()
1161                .layer(
1162                    TraceLayer::new_for_client_and_server_errors()
1163                        .make_span_with(DefaultMakeSpan::new().level(tracing::Level::INFO))
1164                        .on_failure(DefaultOnFailure::new().level(tracing::Level::DEBUG)),
1165                )
1166                .layer(CallbackLayer::new(MetricsMakeCallbackHandler::new(
1167                    Arc::new(outbound_network_metrics),
1168                    config.p2p_config.excessive_message_size(),
1169                )))
1170                .into_inner();
1171
1172            let mut anemo_config = config.p2p_config.anemo_config.clone().unwrap_or_default();
1173            // Inbound requests on this network are small (signatures, queries, summaries).
1174            // Cap request frames at 1 MiB.
1175            anemo_config.max_request_frame_size = Some(1 << 20);
1176            // Responses can be larger (checkpoint contents).
1177            // Cap response frames at 128 MiB.
1178            anemo_config.max_response_frame_size = Some(128 << 20);
1179
1180            // Set a higher default value for socket send/receive buffers if not already
1181            // configured.
1182            let mut quic_config = anemo_config.quic.unwrap_or_default();
1183            if quic_config.socket_send_buffer_size.is_none() {
1184                quic_config.socket_send_buffer_size = Some(20 << 20);
1185            }
1186            if quic_config.socket_receive_buffer_size.is_none() {
1187                quic_config.socket_receive_buffer_size = Some(20 << 20);
1188            }
1189            quic_config.allow_failed_socket_buffer_size_setting = true;
1190
1191            // Set high-performance defaults for quinn transport.
1192            // With 200MiB buffer size and ~500ms RTT, max throughput ~400MiB/s.
1193            if quic_config.max_concurrent_bidi_streams.is_none() {
1194                quic_config.max_concurrent_bidi_streams = Some(500);
1195            }
1196            if quic_config.max_concurrent_uni_streams.is_none() {
1197                quic_config.max_concurrent_uni_streams = Some(500);
1198            }
1199            if quic_config.stream_receive_window.is_none() {
1200                quic_config.stream_receive_window = Some(100 << 20);
1201            }
1202            if quic_config.receive_window.is_none() {
1203                quic_config.receive_window = Some(200 << 20);
1204            }
1205            if quic_config.send_window.is_none() {
1206                quic_config.send_window = Some(200 << 20);
1207            }
1208            if quic_config.crypto_buffer_size.is_none() {
1209                quic_config.crypto_buffer_size = Some(1 << 20);
1210            }
1211            if quic_config.max_idle_timeout_ms.is_none() {
1212                quic_config.max_idle_timeout_ms = Some(10_000);
1213            }
1214            if quic_config.keep_alive_interval_ms.is_none() {
1215                quic_config.keep_alive_interval_ms = Some(5_000);
1216            }
1217            anemo_config.quic = Some(quic_config);
1218
1219            let server_name = format!("iota-{chain_identifier}");
1220            let network = Network::bind(config.p2p_config.listen_address)
1221                .server_name(&server_name)
1222                .private_key(config.network_private_key().to_bytes())
1223                .config(anemo_config)
1224                .outbound_request_layer(outbound_layer)
1225                .start(service)?;
1226            info!(
1227                server_name = server_name,
1228                "P2p network started on {}",
1229                network.local_addr()
1230            );
1231
1232            network
1233        };
1234
1235        let discovery_handle = discovery.start(p2p_network.clone(), config.network_private_key());
1236        let state_sync_handle = state_sync.start(p2p_network.clone());
1237        let randomness_handle = randomness.start(p2p_network.clone());
1238
1239        Ok((
1240            p2p_network,
1241            discovery_handle,
1242            state_sync_handle,
1243            randomness_handle,
1244        ))
1245    }
1246
1247    /// Asynchronously constructs and initializes the components necessary for
1248    /// the validator node.
1249    async fn construct_validator_components(
1250        config: NodeConfig,
1251        state: Arc<AuthorityState>,
1252        committee: Arc<Committee>,
1253        epoch_store: Arc<AuthorityPerEpochStore>,
1254        checkpoint_store: Arc<CheckpointStore>,
1255        state_sync_handle: state_sync::Handle,
1256        randomness_handle: randomness::Handle,
1257        global_state_hasher: Weak<GlobalStateHasher>,
1258        backpressure_manager: Arc<BackpressureManager>,
1259        connection_monitor_status: Arc<ConnectionMonitorStatus>,
1260        registry_service: &RegistryService,
1261        serving_rt_handle: tokio::runtime::Handle,
1262    ) -> Result<ValidatorComponents> {
1263        let mut config_clone = config.clone();
1264        let consensus_config = config_clone
1265            .consensus_config
1266            .as_mut()
1267            .ok_or_else(|| anyhow!("Validator is missing consensus config"))?;
1268        let validator_registry = registry_service.new_registry_custom(None, None)?;
1269        let validator_registry_id = registry_service.add(validator_registry.clone());
1270
1271        let client = Arc::new(UpdatableConsensusClient::new());
1272        let consensus_adapter = Arc::new(Self::construct_consensus_adapter(
1273            &committee,
1274            consensus_config,
1275            state.name,
1276            connection_monitor_status.clone(),
1277            &validator_registry,
1278            client.clone(),
1279            checkpoint_store.clone(),
1280        ));
1281        let consensus_manager = Arc::new(ConsensusManager::new(
1282            &config,
1283            consensus_config,
1284            registry_service,
1285            &validator_registry,
1286            client,
1287        ));
1288
1289        // This only gets started up once, not on every epoch. (Make call to remove
1290        // every epoch.)
1291        let consensus_store_pruner = ConsensusStorePruner::new(
1292            consensus_manager.get_storage_base_path(),
1293            consensus_config.db_retention_epochs(),
1294            consensus_config.db_pruner_period(),
1295            &validator_registry,
1296        );
1297
1298        let soft_locks = Arc::new(if config.enable_soft_locking {
1299            PreConsensusSoftLocks::new()
1300        } else {
1301            info!("pre-consensus soft-locking disabled via node config");
1302            PreConsensusSoftLocks::disabled()
1303        });
1304
1305        let checkpoint_metrics = CheckpointMetrics::new(&validator_registry);
1306        let iota_tx_validator_metrics = IotaTxValidatorMetrics::new(&validator_registry);
1307        let validator_service_metrics = Arc::new(ValidatorServiceMetrics::new(&validator_registry));
1308
1309        // Spawn the soft-lock sweep once for the lifetime of this validator
1310        // instance. The task holds only a `Weak<PreConsensusSoftLocks>` so it
1311        // stops itself automatically: each iteration it tries to upgrade the
1312        // weak reference, and when all strong `Arc` owners have been dropped
1313        // (i.e. `ValidatorComponents` is destructured and the old epoch store
1314        // is released after an epoch transition that removes us from the
1315        // committee) the upgrade returns `None` and the loop exits. No explicit
1316        // `abort()` is needed. The same `Arc<PreConsensusSoftLocks>` is reused
1317        // across epoch transitions (see `start_epoch_specific_validator_components`),
1318        // so the task keeps running uninterrupted while the node remains a validator.
1319        let soft_lock_sweep_handle = PreConsensusSoftLocks::spawn_sweep(
1320            Arc::downgrade(&soft_locks),
1321            validator_service_metrics.clone(),
1322        );
1323
1324        let validator_server_handle = Self::start_grpc_validator_service(
1325            &config,
1326            state.clone(),
1327            consensus_adapter.clone(),
1328            &validator_registry,
1329            soft_locks.clone(),
1330            validator_service_metrics.clone(),
1331            serving_rt_handle,
1332        )
1333        .await?;
1334
1335        // Starts an overload monitor that monitors the execution of the authority.
1336        // Don't start the overload monitor when max_load_shedding_percentage is 0.
1337        let validator_overload_monitor_handle = if config
1338            .authority_overload_config
1339            .max_load_shedding_percentage
1340            > 0
1341        {
1342            let authority_state = Arc::downgrade(&state);
1343            let overload_config = config.authority_overload_config.clone();
1344            fail_point!("starting_overload_monitor");
1345            Some(spawn_monitored_task!(overload_monitor(
1346                authority_state,
1347                overload_config,
1348            )))
1349        } else {
1350            None
1351        };
1352
1353        // Starts a monitor that periodically refreshes the
1354        // `consensus_queue_load_shedding_percentage` metric. Without this, the
1355        // metric goes stale once gRPC traffic stops (the only other update
1356        // path is `AuthorityState::check_consensus_queue_graduated_limits`, called on
1357        // each inbound tx). Used in the certificate-less (P-COOL)
1358        // mode.
1359        let consensus_queue_overload_monitor_handle =
1360            if epoch_store.protocol_config().enable_pcool_flow() {
1361                let consensus_queue_monitor_authority_state = Arc::downgrade(&state);
1362                let consensus_queue_monitor_consensus_adapter = Arc::downgrade(&consensus_adapter);
1363                let consensus_queue_monitor_interval =
1364                    config.authority_overload_config.overload_monitor_interval;
1365                Some(spawn_monitored_task!(consensus_queue_overload_monitor(
1366                    consensus_queue_monitor_authority_state,
1367                    consensus_queue_monitor_consensus_adapter,
1368                    consensus_queue_monitor_interval,
1369                )))
1370            } else {
1371                None
1372            };
1373
1374        Self::start_epoch_specific_validator_components(
1375            &config,
1376            state.clone(),
1377            consensus_adapter,
1378            checkpoint_store,
1379            epoch_store,
1380            state_sync_handle,
1381            randomness_handle,
1382            consensus_manager,
1383            consensus_store_pruner,
1384            global_state_hasher,
1385            backpressure_manager,
1386            soft_locks,
1387            validator_server_handle,
1388            validator_overload_monitor_handle,
1389            consensus_queue_overload_monitor_handle,
1390            soft_lock_sweep_handle,
1391            checkpoint_metrics,
1392            iota_tx_validator_metrics,
1393            validator_registry_id,
1394        )
1395        .await
1396    }
1397
1398    /// Initializes and starts components specific to the current
1399    /// epoch for the validator node.
1400    async fn start_epoch_specific_validator_components(
1401        config: &NodeConfig,
1402        state: Arc<AuthorityState>,
1403        consensus_adapter: Arc<ConsensusAdapter>,
1404        checkpoint_store: Arc<CheckpointStore>,
1405        epoch_store: Arc<AuthorityPerEpochStore>,
1406        state_sync_handle: state_sync::Handle,
1407        randomness_handle: randomness::Handle,
1408        consensus_manager: Arc<ConsensusManager>,
1409        consensus_store_pruner: ConsensusStorePruner,
1410        global_state_hasher: Weak<GlobalStateHasher>,
1411        backpressure_manager: Arc<BackpressureManager>,
1412        soft_locks: Arc<PreConsensusSoftLocks>,
1413        validator_server_handle: SpawnOnce,
1414        validator_overload_monitor_handle: Option<JoinHandle<()>>,
1415        consensus_queue_overload_monitor_handle: Option<JoinHandle<()>>,
1416        soft_lock_sweep_handle: JoinHandle<()>,
1417        checkpoint_metrics: Arc<CheckpointMetrics>,
1418        iota_tx_validator_metrics: Arc<IotaTxValidatorMetrics>,
1419        validator_registry_id: RegistryID,
1420    ) -> Result<ValidatorComponents> {
1421        let checkpoint_service = Self::build_checkpoint_service(
1422            config,
1423            consensus_adapter.clone(),
1424            checkpoint_store.clone(),
1425            epoch_store.clone(),
1426            state.clone(),
1427            state_sync_handle,
1428            global_state_hasher,
1429            checkpoint_metrics.clone(),
1430        );
1431
1432        // create a new map that gets injected into both the consensus handler and the
1433        // consensus adapter the consensus handler will write values forwarded
1434        // from consensus, and the consensus adapter will read the values to
1435        // make decisions about which validator submits a transaction to consensus
1436        let low_scoring_authorities = Arc::new(ArcSwap::new(Arc::new(HashMap::new())));
1437
1438        consensus_adapter.swap_low_scoring_authorities(low_scoring_authorities.clone());
1439
1440        // Wire pre-consensus soft locks to the epoch store so that
1441        // post-consensus processing can release locks once permanent locks are
1442        // quarantined. Clear stale locks from the previous epoch and spawn a
1443        // background sweep task.
1444        soft_locks.clear();
1445        epoch_store.set_soft_locks(soft_locks.clone());
1446
1447        // A validator cannot participate without a randomness manager. Aborting here
1448        // fails loudly at the real cause (startup or reconfiguration) instead
1449        // of leaving the node to panic later on the first consensus commit that
1450        // unconditionally expects one.
1451        let randomness_manager = match RandomnessManager::try_new(
1452            Arc::downgrade(&epoch_store),
1453            Box::new(consensus_adapter.clone()),
1454            randomness_handle,
1455            config.authority_key_pair(),
1456        )
1457        .await
1458        {
1459            Ok(randomness_manager) => randomness_manager,
1460            Err(err) => {
1461                fatal!(
1462                    "validator cannot start epoch {} without a randomness manager: {err}",
1463                    epoch_store.epoch()
1464                );
1465            }
1466        };
1467        epoch_store
1468            .set_randomness_manager(randomness_manager)
1469            .await?;
1470        epoch_store
1471            .epoch_metrics()
1472            .record_epoch_change_stage_now(epoch_store.epoch(), "randomness_ready");
1473
1474        let consensus_handler_initializer = ConsensusHandlerInitializer::new(
1475            state.clone(),
1476            checkpoint_service.clone(),
1477            epoch_store.clone(),
1478            low_scoring_authorities,
1479            backpressure_manager,
1480        );
1481
1482        info!("Starting consensus manager asynchronously");
1483
1484        // Subscribe before starting consensus so that the replay waiter cannot miss the
1485        // one-shot consumer monitor broadcast if consensus starts immediately.
1486        let replay_waiter = consensus_manager.replay_waiter();
1487
1488        // Spawn consensus startup asynchronously to avoid blocking other components
1489        tokio::spawn({
1490            let config = config.clone();
1491            let epoch_store = epoch_store.clone();
1492            let iota_tx_validator = IotaTxValidator::new(
1493                epoch_store.clone(),
1494                checkpoint_service.clone(),
1495                iota_tx_validator_metrics.clone(),
1496            );
1497            let consensus_manager = consensus_manager.clone();
1498            async move {
1499                consensus_manager
1500                    .start(
1501                        &config,
1502                        epoch_store,
1503                        consensus_handler_initializer,
1504                        iota_tx_validator,
1505                    )
1506                    .await;
1507            }
1508        });
1509        info!("Spawning checkpoint service");
1510        // With the P-COOL flow, a checkpoint built before a restart has to be
1511        // rebuilt from the replayed commits before it is executed.
1512        let replay_waiter = if std::env::var("DISABLE_REPLAY_WAITER").is_err() {
1513            Some(replay_waiter)
1514        } else if epoch_store.protocol_config().enable_pcool_flow() {
1515            warn!("DISABLE_REPLAY_WAITER is ignored with the P-COOL flow");
1516            Some(replay_waiter)
1517        } else {
1518            None
1519        };
1520        let checkpoint_service_tasks = checkpoint_service.spawn(replay_waiter).await;
1521
1522        let overload_notifier_handle = Self::start_overload_notifier(
1523            config,
1524            state.clone(),
1525            epoch_store.clone(),
1526            consensus_adapter.clone(),
1527        );
1528
1529        Ok(ValidatorComponents {
1530            validator_server_handle,
1531            validator_overload_monitor_handle,
1532            consensus_queue_overload_monitor_handle,
1533            soft_lock_sweep_handle,
1534            overload_notifier_handle,
1535            consensus_manager,
1536            consensus_store_pruner,
1537            consensus_adapter,
1538            soft_locks,
1539            checkpoint_service_tasks,
1540            checkpoint_metrics,
1541            iota_tx_validator_metrics,
1542            validator_registry_id,
1543        })
1544    }
1545
1546    /// Starts the checkpoint service for the validator node, initializing
1547    /// necessary components and settings.
1548    /// The function ensures proper initialization of the checkpoint service,
1549    /// preparing it to handle checkpoint creation and submission to consensus,
1550    /// while also setting up the necessary monitoring and synchronization
1551    /// mechanisms.
1552    fn build_checkpoint_service(
1553        config: &NodeConfig,
1554        consensus_adapter: Arc<ConsensusAdapter>,
1555        checkpoint_store: Arc<CheckpointStore>,
1556        epoch_store: Arc<AuthorityPerEpochStore>,
1557        state: Arc<AuthorityState>,
1558        state_sync_handle: state_sync::Handle,
1559        global_state_hasher: Weak<GlobalStateHasher>,
1560        checkpoint_metrics: Arc<CheckpointMetrics>,
1561    ) -> Arc<CheckpointService> {
1562        let epoch_start_timestamp_ms = epoch_store.epoch_start_state().epoch_start_timestamp_ms();
1563        let epoch_duration_ms = epoch_store.epoch_start_state().epoch_duration_ms();
1564
1565        debug!(
1566            "Starting checkpoint service with epoch start timestamp {}
1567            and epoch duration {}",
1568            epoch_start_timestamp_ms, epoch_duration_ms
1569        );
1570
1571        let checkpoint_output = Box::new(SubmitCheckpointToConsensus {
1572            sender: consensus_adapter,
1573            signer: state.secret.clone(),
1574            authority: config.authority_public_key(),
1575            next_reconfiguration_timestamp_ms: epoch_start_timestamp_ms
1576                .checked_add(epoch_duration_ms)
1577                .expect("Overflow calculating next_reconfiguration_timestamp_ms"),
1578            metrics: checkpoint_metrics.clone(),
1579        });
1580
1581        let certified_checkpoint_output = SendCheckpointToStateSync::new(state_sync_handle);
1582        let max_tx_per_checkpoint = max_tx_per_checkpoint(epoch_store.protocol_config());
1583        let max_checkpoint_size_bytes =
1584            epoch_store.protocol_config().max_checkpoint_size_bytes() as usize;
1585
1586        CheckpointService::build(
1587            state.clone(),
1588            checkpoint_store,
1589            epoch_store,
1590            state.get_transaction_cache_reader().clone(),
1591            global_state_hasher,
1592            checkpoint_output,
1593            Box::new(certified_checkpoint_output),
1594            checkpoint_metrics,
1595            max_tx_per_checkpoint,
1596            max_checkpoint_size_bytes,
1597        )
1598    }
1599
1600    fn construct_consensus_adapter(
1601        committee: &Committee,
1602        consensus_config: &ConsensusConfig,
1603        authority: AuthorityName,
1604        connection_monitor_status: Arc<ConnectionMonitorStatus>,
1605        prometheus_registry: &Registry,
1606        consensus_client: Arc<dyn ConsensusClient>,
1607        checkpoint_store: Arc<CheckpointStore>,
1608    ) -> ConsensusAdapter {
1609        let ca_metrics = ConsensusAdapterMetrics::new(prometheus_registry);
1610        // The consensus adapter allows the authority to send user certificates through
1611        // consensus.
1612
1613        ConsensusAdapter::new(
1614            consensus_client,
1615            checkpoint_store,
1616            authority,
1617            connection_monitor_status,
1618            consensus_config.max_pending_transactions(),
1619            consensus_config.max_pending_transactions() * 2 / committee.num_members(),
1620            consensus_config.max_submit_position,
1621            consensus_config.submit_delay_step_override(),
1622            ca_metrics,
1623            consensus_config.graduated_load_shedding_soft_limit_pct(),
1624        )
1625    }
1626
1627    async fn start_grpc_validator_service(
1628        config: &NodeConfig,
1629        state: Arc<AuthorityState>,
1630        consensus_adapter: Arc<ConsensusAdapter>,
1631        prometheus_registry: &Registry,
1632        soft_locks: Arc<PreConsensusSoftLocks>,
1633        validator_service_metrics: Arc<ValidatorServiceMetrics>,
1634        serving_rt_handle: tokio::runtime::Handle,
1635    ) -> Result<SpawnOnce> {
1636        let validator_service = ValidatorService::new(
1637            state,
1638            consensus_adapter,
1639            validator_service_metrics,
1640            config.policy_config.clone().map(|p| p.client_id_source),
1641            soft_locks,
1642        );
1643
1644        // Each service gets its own concurrency limit so that a flood of client
1645        // transaction submissions (Validator / ValidatorV2) cannot crowd the
1646        // validator-peer RPCs sharing this listener out of admission slots.
1647        // The config value is per core, so the same config scales with the
1648        // hardware; the effective limit is computed on the machine the server
1649        // actually runs on.
1650        let concurrency_limit = config.grpc_concurrency_limit_per_core.saturating_mul(
1651            NonZeroUsize::new(iota_core::runtime::available_cpu_cores())
1652                .unwrap_or(NonZeroUsize::MIN),
1653        );
1654        let load_shed = config.grpc_load_shed.unwrap_or_default();
1655
1656        // HTTP/2 keepalive is the only mechanism that closes a connection whose
1657        // peer has gone away without closing it: the server pings after this
1658        // long without inbound frames and drops the connection when the ping
1659        // goes unanswered for as long again.
1660        const VALIDATOR_GRPC_KEEPALIVE: Duration = Duration::from_secs(60);
1661        // Bounds the streams one connection may hold open, so a single peer
1662        // cannot fill a service's admission slots on its own. A fullnode sends
1663        // every request to this validator over one connection, so the cap must
1664        // stay well above a busy fullnode's peak concurrency.
1665        const VALIDATOR_GRPC_MAX_CONCURRENT_STREAMS: NonZeroU32 = NonZeroU32::new(1000).unwrap();
1666        // Leaves room for every fullnode and validator holding a connection,
1667        // while keeping a connection flood well inside the process fd limit,
1668        // which this listener shares with RocksDB and the other listeners.
1669        const VALIDATOR_GRPC_MAX_CONNECTIONS: NonZeroUsize = NonZeroUsize::new(4096).unwrap();
1670        // Each fullnode and validator holds about one connection, so this
1671        // leaves room for many nodes behind one address, while one address
1672        // can take no more than a sixteenth of the listener.
1673        const VALIDATOR_GRPC_MAX_CONNECTIONS_PER_CLIENT_IP: NonZeroUsize =
1674            NonZeroUsize::new(256).unwrap();
1675        // Frees the connections of peers that stopped sending requests. A peer
1676        // that comes back reconnects, paying one TLS handshake, which is cheap
1677        // next to five minutes without a request.
1678        const VALIDATOR_GRPC_MAX_CONNECTION_IDLE: Duration = Duration::from_secs(300);
1679        // A response holds its admission slot until it has been sent, and a
1680        // client that stops reading would otherwise hold it for good. The
1681        // timeout counts from the headers, so it also ends a response that is
1682        // being read. A `GetTxStatus` stream waits at most 30 s for its
1683        // transactions; a `SubmitTx` stream has no bound of its own and ends
1684        // within this timeout unless the validator is badly overloaded.
1685        const VALIDATOR_GRPC_RESPONSE_SEND_TIMEOUT: Duration = Duration::from_secs(60);
1686
1687        let limits = &config.validator_grpc_listener_limits;
1688        let http_config = iota_http::Config::default()
1689            .handshake_timeout(
1690                limits
1691                    .handshake_timeout
1692                    .resolve(iota_http::DEFAULT_HANDSHAKE_TIMEOUT),
1693            )
1694            .max_pending_connections(
1695                limits
1696                    .max_pending_connections
1697                    .resolve(iota_http::DEFAULT_MAX_PENDING_CONNECTIONS),
1698            )
1699            .max_connections(
1700                limits
1701                    .max_connections
1702                    .resolve(VALIDATOR_GRPC_MAX_CONNECTIONS),
1703            )
1704            .max_connections_per_client_ip(
1705                limits
1706                    .max_connections_per_client_ip
1707                    .resolve(VALIDATOR_GRPC_MAX_CONNECTIONS_PER_CLIENT_IP),
1708            )
1709            .ipv6_prefix_len(
1710                limits
1711                    .ipv6_prefix_len
1712                    .unwrap_or(iota_http::DEFAULT_IPV6_PREFIX_LEN),
1713            )
1714            .max_connection_idle(
1715                limits
1716                    .max_connection_idle
1717                    .resolve(VALIDATOR_GRPC_MAX_CONNECTION_IDLE),
1718            )
1719            .max_concurrent_streams(
1720                limits
1721                    .max_concurrent_streams
1722                    .resolve(VALIDATOR_GRPC_MAX_CONCURRENT_STREAMS),
1723            )
1724            .http2_keepalive_interval(
1725                limits
1726                    .http2_keepalive_interval
1727                    .resolve(VALIDATOR_GRPC_KEEPALIVE),
1728            )
1729            .http2_keepalive_timeout(VALIDATOR_GRPC_KEEPALIVE)
1730            .http1_header_read_timeout(
1731                limits
1732                    .http1_header_read_timeout
1733                    .resolve(iota_http::DEFAULT_HTTP1_HEADER_READ_TIMEOUT),
1734            );
1735        let server_builder = ServerBuilder::from_config(
1736            &iota_network_stack::config::Config::new(),
1737            GrpcMetrics::new(prometheus_registry),
1738        )
1739        .http_config(http_config)
1740        .listener_metrics(validator_server_listener_metrics(prometheus_registry))
1741        .add_service_with_concurrency_limit(
1742            ValidatorServer::new(validator_service.clone()),
1743            concurrency_limit,
1744            load_shed,
1745            VALIDATOR_GRPC_RESPONSE_SEND_TIMEOUT,
1746        )
1747        .add_service_with_concurrency_limit(
1748            ValidatorV2Server::new(validator_service.clone()),
1749            concurrency_limit,
1750            load_shed,
1751            VALIDATOR_GRPC_RESPONSE_SEND_TIMEOUT,
1752        )
1753        .add_service_with_concurrency_limit(
1754            ValidatorPeerServer::new(validator_service),
1755            concurrency_limit,
1756            load_shed,
1757            VALIDATOR_GRPC_RESPONSE_SEND_TIMEOUT,
1758        );
1759
1760        let tls_config = iota_tls::create_rustls_server_config(
1761            config.network_private_key(),
1762            IOTA_TLS_SERVER_NAME.to_string(),
1763        );
1764
1765        let network_address = config.network_address().clone();
1766
1767        let bind_future = async move {
1768            let server = server_builder
1769                .bind(&network_address, Some(tls_config))
1770                .await
1771                .map_err(|err| anyhow!("Failed to bind to {network_address}: {err}"))?;
1772
1773            let local_addr = server.local_addr();
1774            info!("Listening to traffic on {local_addr}");
1775
1776            Ok(server)
1777        };
1778
1779        Ok(SpawnOnce::new(bind_future, serving_rt_handle))
1780    }
1781
1782    /// Re-executes pending consensus certificates, which may not have been
1783    /// committed to disk before the node restarted. This is necessary for
1784    /// the following reasons:
1785    ///
1786    /// 1. For any transaction for which we returned signed effects to a client, we must ensure that
1787    ///    we have re-executed the transaction before we begin accepting grpc requests. Otherwise we
1788    ///    would appear to have forgotten about the transaction.
1789    /// 2. While this is running, we are concurrently waiting for all previously built checkpoints
1790    ///    to be rebuilt. Since there may be dependencies in either direction (from checkpointed
1791    ///    consensus transactions to pending consensus transactions, or vice versa), we must
1792    ///    re-execute pending consensus transactions to ensure that both processes can complete.
1793    /// 3. Also note that for any pending consensus transactions for which we wrote a signed effects
1794    ///    digest to disk, we must re-execute using that digest as the expected effects digest, to
1795    ///    ensure that we cannot arrive at different effects than what we previously signed.
1796    async fn reexecute_pending_consensus_certs(
1797        epoch_store: &Arc<AuthorityPerEpochStore>,
1798        state: &Arc<AuthorityState>,
1799    ) {
1800        let mut pending_consensus_certificates = Vec::new();
1801        let mut additional_certs = Vec::new();
1802
1803        for tx in epoch_store.get_all_pending_consensus_transactions() {
1804            match tx.kind {
1805                // TODO: what to do with UserTransactionV1 here? It seems like this only applies to
1806                //  optimistically executed owned-object transactions that possibly didn't go
1807                //  through  consensus before the node restarted. UserTransactionsV1
1808                //  always needs to go  through consensus, so it will be replayed
1809                //  there, just like shared object  transactions.
1810                //
1811                // Shared object txns
1812                // cannot be re-executed at this  point, because we must wait for
1813                // consensus replay to assign shared  object versions.
1814                ConsensusTransactionKind::CertifiedTransaction(tx)
1815                    if !tx.contains_shared_object() =>
1816                {
1817                    let tx = *tx;
1818                    // new_unchecked is safe because we never submit a transaction to consensus
1819                    // without verifying it
1820                    let tx = VerifiedExecutableTransaction::new_from_certificate(
1821                        VerifiedCertificate::new_unchecked(tx),
1822                    );
1823                    // we only need to re-execute if we previously signed the effects (which
1824                    // indicates we returned the effects to a client).
1825                    if let Some(fx_digest) = epoch_store
1826                        .get_signed_effects_digest(tx.digest())
1827                        .expect("db error")
1828                    {
1829                        pending_consensus_certificates.push((
1830                            Schedulable::Transaction(tx),
1831                            ExecutionEnv::new().with_expected_effects_digest(fx_digest),
1832                        ));
1833                    } else {
1834                        additional_certs.push((Schedulable::Transaction(tx), ExecutionEnv::new()));
1835                    }
1836                }
1837                _ => (),
1838            }
1839        }
1840
1841        let digests = pending_consensus_certificates
1842            .iter()
1843            // unwrap_digest okay because only user certs are in
1844            // pending_consensus_certificates
1845            .map(|(tx, _)| *tx.key().unwrap_digest())
1846            .collect::<Vec<_>>();
1847
1848        info!(
1849            "reexecuting {} pending consensus certificates: {:?}",
1850            digests.len(),
1851            digests
1852        );
1853
1854        state
1855            .execution_scheduler()
1856            .enqueue(pending_consensus_certificates, epoch_store);
1857        state
1858            .execution_scheduler()
1859            .enqueue(additional_certs, epoch_store);
1860
1861        // If this times out, the validator will still almost certainly start up fine.
1862        // But, it is possible that it may temporarily "forget" about
1863        // transactions that it had previously executed. This could confuse
1864        // clients in some circumstances. However, the transactions are still in
1865        // pending_consensus_certificates, so we cannot lose any finality guarantees.
1866        let timeout = if cfg!(msim) { 120 } else { 60 };
1867        if tokio::time::timeout(
1868            std::time::Duration::from_secs(timeout),
1869            state
1870                .get_transaction_cache_reader()
1871                .try_notify_read_executed_effects_digests(
1872                    "IotaNode::notify_read_executed_effects_digests",
1873                    &digests,
1874                ),
1875        )
1876        .await
1877        .is_err()
1878        {
1879            // Log all the digests that were not executed to help debugging.
1880            if let Ok(executed_effects_digests) = state
1881                .get_transaction_cache_reader()
1882                .try_multi_get_executed_effects_digests(&digests)
1883            {
1884                let pending_digests = digests
1885                    .iter()
1886                    .zip(executed_effects_digests.iter())
1887                    .filter_map(|(digest, executed_effects_digest)| {
1888                        if executed_effects_digest.is_none() {
1889                            Some(digest)
1890                        } else {
1891                            None
1892                        }
1893                    })
1894                    .collect::<Vec<_>>();
1895                debug_fatal!(
1896                    "Timed out waiting for effects digests to be executed: {:?}",
1897                    pending_digests
1898                );
1899            } else {
1900                debug_fatal!(
1901                    "Timed out waiting for effects digests to be executed, digests not found"
1902                );
1903            }
1904        }
1905    }
1906
1907    pub fn state(&self) -> Arc<AuthorityState> {
1908        self.state.clone()
1909    }
1910
1911    // Only used for testing because of how epoch store is loaded.
1912    pub fn reference_gas_price_for_testing(&self) -> Result<u64, anyhow::Error> {
1913        self.state.reference_gas_price_for_testing()
1914    }
1915
1916    pub fn clone_committee_store(&self) -> Arc<CommitteeStore> {
1917        self.state.committee_store().clone()
1918    }
1919
1920    // pub fn clone_authority_store(&self) -> Arc<AuthorityStore> {
1921    // self.state.db()
1922    // }
1923
1924    /// Clone an AuthorityAggregator from the transaction orchestrator, if
1925    /// this is a fullnode. The snapshot goes stale after an epoch change;
1926    /// call again for a fresh one.
1927    pub fn clone_authority_aggregator(
1928        &self,
1929    ) -> Option<Arc<AuthorityAggregator<NetworkAuthorityClient>>> {
1930        self.transaction_orchestrator
1931            .as_ref()
1932            .map(|to| to.clone_authority_aggregator())
1933    }
1934
1935    pub fn transaction_orchestrator(
1936        &self,
1937    ) -> Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>> {
1938        self.transaction_orchestrator.clone()
1939    }
1940
1941    /// Read-only client for the SDK's `TransactionBuilder` backed by this
1942    /// node's local state instead of a remote endpoint.
1943    pub fn transaction_builder_ledger_client(&self) -> NodeTransactionBuilderLedgerClient {
1944        let reader = Arc::new(GrpcReadStore::new(
1945            self.state.clone(),
1946            self.state_sync_store.clone(),
1947        ));
1948        NodeTransactionBuilderLedgerClient::new(reader)
1949    }
1950
1951    /// Subscribe to the quorum driver's effects stream; errors while the
1952    /// quorum driver is not the currently served flow on this node.
1953    pub fn subscribe_to_transaction_orchestrator_effects(
1954        &self,
1955    ) -> Result<tokio::sync::broadcast::Receiver<QuorumDriverEffectsQueueResult>> {
1956        self.transaction_orchestrator
1957            .as_ref()
1958            .ok_or_else(|| {
1959                anyhow::anyhow!("Transaction Orchestrator is not enabled in this node.")
1960            })?
1961            .subscribe_to_effects_queue()
1962            .ok_or_else(|| {
1963                anyhow::anyhow!(
1964                    "Effects queue is not available: the quorum driver is not the currently \
1965                     served flow on this node."
1966                )
1967            })
1968    }
1969
1970    /// This function awaits the completion of checkpoint execution of the
1971    /// current epoch, after which it initiates reconfiguration of the
1972    /// entire system. This function also handles role changes for the node when
1973    /// epoch changes and, if the node is a validator, advertises capabilities
1974    /// and submits the local deny rule proposal to consensus.
1975    pub async fn monitor_reconfiguration(
1976        self: Arc<Self>,
1977        mut epoch_store: Arc<AuthorityPerEpochStore>,
1978    ) -> Result<()> {
1979        let checkpoint_executor_metrics =
1980            CheckpointExecutorMetrics::new(&self.registry_service.default_registry());
1981
1982        loop {
1983            let mut hasher_guard = self.global_state_hasher.lock().await;
1984            let hasher = hasher_guard.take().unwrap();
1985            info!(
1986                "Creating checkpoint executor for epoch {}",
1987                epoch_store.epoch()
1988            );
1989
1990            // Create closures that handle gRPC type conversion
1991            let data_sender = if let Ok(guard) = self.grpc_server_handle.try_lock() {
1992                guard.as_ref().map(|handle| {
1993                    let tx = handle.checkpoint_data_broadcaster().clone();
1994                    Box::new(move |data: &CheckpointData| {
1995                        tx.send_traced(data);
1996                    }) as Box<dyn Fn(&CheckpointData) + Send + Sync>
1997                })
1998            } else {
1999                None
2000            };
2001
2002            let checkpoint_executor = CheckpointExecutor::new(
2003                epoch_store.clone(),
2004                self.checkpoint_store.clone(),
2005                self.state.clone(),
2006                hasher.clone(),
2007                self.backpressure_manager.clone(),
2008                self.config.checkpoint_executor_config.clone(),
2009                checkpoint_executor_metrics.clone(),
2010                data_sender,
2011                Some(self.checkpoint_progress_tracker.clone()),
2012            );
2013
2014            let run_with_range = self.config.run_with_range;
2015
2016            let cur_epoch_store = self.state.load_epoch_store_one_call_per_task();
2017
2018            // Update the current protocol version metric.
2019            self.metrics
2020                .current_protocol_version
2021                .set(cur_epoch_store.protocol_config().version.as_u64() as i64);
2022
2023            // Advertise capabilities to committee, if we are a validator.
2024            if let Some(components) = &*self.validator_components.lock().await {
2025                // TODO: without this sleep, the consensus message is not delivered reliably.
2026                tokio::time::sleep(Duration::from_millis(1)).await;
2027
2028                let config = cur_epoch_store.protocol_config();
2029                let transaction = ConsensusTransaction::new_capability_notification_v1(
2030                    AuthorityCapabilitiesV1::new(
2031                        self.state.name,
2032                        cur_epoch_store.get_chain(),
2033                        self.config
2034                            .supported_protocol_versions
2035                            .expect("Supported versions should be populated")
2036                            // no need to send digests of versions less than the current version
2037                            .truncate_below(config.version),
2038                        self.state.get_available_system_packages(config).await,
2039                    ),
2040                );
2041                info!(?transaction, "submitting capabilities to consensus");
2042                components
2043                    .consensus_adapter
2044                    .submit(transaction, None, &cur_epoch_store)?;
2045
2046                // Announce the local deny rules. Recorded proposals are
2047                // epoch-scoped, so this re-announces on every epoch change.
2048                // The empty set is announced too: every committee member
2049                // attests its configuration each epoch, so silence means
2050                // offline rather than "no rules".
2051                if config.enable_pcool_flow() {
2052                    let proposed_rules = self.config.transaction_deny_config.to_deny_rule_set();
2053                    let recorded = cur_epoch_store.recorded_deny_rule_proposal(&self.state.name);
2054                    let transaction = ConsensusTransaction::new_transaction_deny_rule_proposal(
2055                        TransactionDenyRuleProposal::new(
2056                            self.state.name,
2057                            proposed_rules,
2058                            recorded.map(|p| p.generation),
2059                        ),
2060                    );
2061                    info!(
2062                        tracking_id = ?transaction.get_tracking_id(),
2063                        "submitting deny rule proposal to consensus"
2064                    );
2065                    match components
2066                        .consensus_adapter
2067                        .submit(transaction, None, &cur_epoch_store)
2068                    {
2069                        // Consensus does not take a proposal that large, so
2070                        // the node goes on without announcing its deny rules.
2071                        Err(
2072                            error @ IotaError::UserInput {
2073                                error: UserInputError::SizeLimitExceeded { .. },
2074                            },
2075                        ) => error!(
2076                            ?error,
2077                            "the deny rule proposal is refused as larger than consensus accepts, \
2078                                so the local deny rules are not announced"
2079                        ),
2080                        result => {
2081                            result?;
2082                        }
2083                    }
2084                }
2085            } else if self.state.is_active_validator(&cur_epoch_store)
2086                && cur_epoch_store
2087                    .protocol_config()
2088                    .track_non_committee_eligible_validators()
2089            {
2090                // Send signed capabilities to committee validators if we are a non-committee
2091                // validator in a separate task to not block the caller. Sending is done only if
2092                // the feature flag supporting it is enabled.
2093                let epoch_store = cur_epoch_store.clone();
2094                let node_clone = self.clone();
2095                spawn_monitored_task!(epoch_store.clone().within_alive_epoch(async move {
2096                    node_clone
2097                        .send_signed_capability_notification_to_committee_with_retry(&epoch_store)
2098                        .instrument(trace_span!(
2099                            "send_signed_capability_notification_to_committee_with_retry"
2100                        ))
2101                        .await;
2102                }));
2103            }
2104
2105            let stop_condition = checkpoint_executor.run_epoch(run_with_range).await;
2106
2107            if stop_condition == StopReason::RuntimeShutdown {
2108                return Ok(());
2109            }
2110
2111            if stop_condition == StopReason::RunWithRangeCondition {
2112                IotaNode::shutdown(&self).await;
2113                self.shutdown_channel_tx
2114                    .send(run_with_range)
2115                    .expect("RunWithRangeCondition met but failed to send shutdown message");
2116                return Ok(());
2117            }
2118
2119            // Every checkpoint of the epoch has been executed: the epoch change
2120            // starts here.
2121            let epoch_metrics = cur_epoch_store.epoch_metrics().clone();
2122            let next_epoch = cur_epoch_store.epoch() + 1;
2123            epoch_metrics.begin_epoch_change(next_epoch);
2124
2125            // Safe to call because we are in the middle of reconfiguration.
2126            let latest_system_state = self
2127                .state
2128                .get_object_cache_reader()
2129                .try_get_iota_system_state_object_unsafe()
2130                .expect("Read IOTA System State object cannot fail");
2131
2132            #[cfg(msim)]
2133            if !self
2134                .sim_state
2135                .sim_safe_mode_expected
2136                .load(Ordering::Relaxed)
2137            {
2138                debug_assert!(!latest_system_state.safe_mode());
2139            }
2140
2141            #[cfg(not(msim))]
2142            debug_assert!(!latest_system_state.safe_mode());
2143
2144            if let Err(err) = self.end_of_epoch_channel.send(latest_system_state.clone()) {
2145                if self.state.is_fullnode(&cur_epoch_store) {
2146                    warn!(
2147                        "Failed to send end of epoch notification to subscriber: {:?}",
2148                        err
2149                    );
2150                }
2151            }
2152
2153            cur_epoch_store.record_is_safe_mode_metric(latest_system_state.safe_mode());
2154            let new_epoch_start_state = latest_system_state.into_epoch_start_state();
2155
2156            self.auth_agg.store(Arc::new(
2157                self.auth_agg
2158                    .load()
2159                    .recreate_with_new_epoch_start_state(&new_epoch_start_state),
2160            ));
2161
2162            let next_epoch_committee = new_epoch_start_state.get_iota_committee();
2163            let next_epoch = next_epoch_committee.epoch();
2164            assert_eq!(cur_epoch_store.epoch() + 1, next_epoch);
2165
2166            info!(
2167                next_epoch,
2168                "Finished executing all checkpoints in epoch. About to reconfigure the system."
2169            );
2170
2171            fail_point_async!("reconfig_delay");
2172
2173            // We save the connection monitor status map regardless of validator / fullnode
2174            // status so that we don't need to restart the connection monitor
2175            // every epoch. Update the mappings that will be used by the
2176            // consensus adapter if it exists or is about to be created.
2177            let authority_names_to_peer_ids =
2178                new_epoch_start_state.get_authority_names_to_peer_ids();
2179            self.connection_monitor_status
2180                .update_mapping_for_epoch(authority_names_to_peer_ids);
2181
2182            cur_epoch_store.record_epoch_reconfig_start_time_metric();
2183
2184            send_trusted_peer_change(
2185                &self.config,
2186                &self.trusted_peer_change_tx,
2187                &new_epoch_start_state,
2188            );
2189
2190            let mut validator_components_lock_guard = self.validator_components.lock().await;
2191
2192            // The following code handles 4 different cases, depending on whether the node
2193            // was a validator in the previous epoch, and whether the node is a validator
2194            // in the new epoch.
2195            let new_epoch_store = self
2196                .reconfigure_state(
2197                    &self.state,
2198                    &cur_epoch_store,
2199                    next_epoch_committee.clone(),
2200                    new_epoch_start_state,
2201                    hasher.clone(),
2202                )
2203                .await?;
2204            epoch_metrics.record_epoch_change_stage_now(next_epoch, "new_epoch_store_live");
2205            self.sync_summaries_to_epoch_end.store(
2206                Self::sync_summaries_to_epoch_end(&self.config, &new_epoch_store),
2207                Ordering::Relaxed,
2208            );
2209
2210            let new_validator_components = if let Some(ValidatorComponents {
2211                validator_server_handle,
2212                validator_overload_monitor_handle,
2213                consensus_queue_overload_monitor_handle,
2214                soft_lock_sweep_handle,
2215                overload_notifier_handle,
2216                consensus_manager,
2217                consensus_store_pruner,
2218                consensus_adapter,
2219                soft_locks,
2220                mut checkpoint_service_tasks,
2221                checkpoint_metrics,
2222                iota_tx_validator_metrics,
2223                validator_registry_id,
2224            }) = validator_components_lock_guard.take()
2225            {
2226                info!("Reconfiguring the validator.");
2227                // Cancel the old overload notifier task so a new one can be
2228                // started for the next epoch.
2229                if let Some(handle) = overload_notifier_handle {
2230                    handle.abort();
2231                }
2232                // Cancel the old checkpoint service tasks.
2233                // Waiting for checkpoint builder to finish gracefully is not possible, because
2234                // it may wait on transactions while consensus on peers have
2235                // already shut down.
2236                checkpoint_service_tasks.abort_all();
2237                while let Some(result) = checkpoint_service_tasks.join_next().await {
2238                    if let Err(err) = result {
2239                        if err.is_panic() {
2240                            std::panic::resume_unwind(err.into_panic());
2241                        }
2242                        warn!("Error in checkpoint service task: {:?}", err);
2243                    }
2244                }
2245                info!("Checkpoint service has shut down.");
2246                epoch_metrics
2247                    .record_epoch_change_stage_now(next_epoch, "checkpoint_service_stopped");
2248
2249                fail_point_async!("reconfig_before_consensus_shutdown");
2250
2251                consensus_manager.shutdown().await;
2252                info!("Consensus has shut down.");
2253
2254                info!("Epoch store finished reconfiguration.");
2255
2256                // No other components should be holding a strong reference to state hasher
2257                // at this point. Confirm here before we swap in the new hasher.
2258                let global_state_hasher_metrics = Arc::into_inner(hasher)
2259                    .expect("Object state hasher should have no other references at this point")
2260                    .metrics();
2261                let new_hasher = Arc::new(GlobalStateHasher::new(
2262                    self.state.get_global_state_hash_store().clone(),
2263                    global_state_hasher_metrics,
2264                ));
2265                let weak_hasher = Arc::downgrade(&new_hasher);
2266                *hasher_guard = Some(new_hasher);
2267
2268                consensus_store_pruner.prune(next_epoch).await;
2269
2270                if self.state.is_committee_validator(&new_epoch_store) {
2271                    // Only restart consensus if this node is still a validator in the new epoch.
2272                    Some(
2273                        Self::start_epoch_specific_validator_components(
2274                            &self.config,
2275                            self.state.clone(),
2276                            consensus_adapter,
2277                            self.checkpoint_store.clone(),
2278                            new_epoch_store.clone(),
2279                            self.state_sync_handle.clone(),
2280                            self.randomness_handle.clone(),
2281                            consensus_manager,
2282                            consensus_store_pruner,
2283                            weak_hasher,
2284                            self.backpressure_manager.clone(),
2285                            soft_locks,
2286                            validator_server_handle,
2287                            validator_overload_monitor_handle,
2288                            consensus_queue_overload_monitor_handle,
2289                            soft_lock_sweep_handle,
2290                            checkpoint_metrics,
2291                            iota_tx_validator_metrics,
2292                            validator_registry_id,
2293                        )
2294                        .await?,
2295                    )
2296                } else {
2297                    info!("This node is no longer a validator after reconfiguration");
2298                    if self.registry_service.remove(validator_registry_id) {
2299                        debug!("Removed validator metrics registry");
2300                    } else {
2301                        warn!("Failed to remove validator metrics registry");
2302                    }
2303                    validator_server_handle.shutdown();
2304                    debug!("Validator grpc server shutdown triggered");
2305
2306                    None
2307                }
2308            } else {
2309                // No other components should be holding a strong reference to state hasher
2310                // at this point. Confirm here before we swap in the new hasher.
2311                let global_state_hasher_metrics = Arc::into_inner(hasher)
2312                    .expect("Object state hasher should have no other references at this point")
2313                    .metrics();
2314                let new_hasher = Arc::new(GlobalStateHasher::new(
2315                    self.state.get_global_state_hash_store().clone(),
2316                    global_state_hasher_metrics,
2317                ));
2318                let weak_hasher = Arc::downgrade(&new_hasher);
2319                *hasher_guard = Some(new_hasher);
2320
2321                if self.state.is_committee_validator(&new_epoch_store) {
2322                    info!("Promoting the node from fullnode to validator, starting grpc server");
2323
2324                    let mut components = Self::construct_validator_components(
2325                        self.config.clone(),
2326                        self.state.clone(),
2327                        Arc::new(next_epoch_committee.clone()),
2328                        new_epoch_store.clone(),
2329                        self.checkpoint_store.clone(),
2330                        self.state_sync_handle.clone(),
2331                        self.randomness_handle.clone(),
2332                        weak_hasher,
2333                        self.backpressure_manager.clone(),
2334                        self.connection_monitor_status.clone(),
2335                        &self.registry_service,
2336                        self.serving_rt_handle.clone(),
2337                    )
2338                    .await?;
2339
2340                    components.validator_server_handle =
2341                        components.validator_server_handle.start().await;
2342
2343                    Some(components)
2344                } else {
2345                    None
2346                }
2347            };
2348            *validator_components_lock_guard = new_validator_components;
2349
2350            // Force releasing current epoch store DB handle, because the
2351            // Arc<AuthorityPerEpochStore> may linger.
2352            cur_epoch_store.release_db_handles();
2353
2354            // Drop the old epoch store to free its in-memory structures
2355            // (ConsensusOutputCache, ConsensusQuarantine, DashMaps, etc.).
2356            // The DB tables were already released above.
2357            drop(cur_epoch_store);
2358
2359            // Prune old epoch databases after each epoch transition to prevent
2360            // accumulation of RocksDB instances during fast catch-up sync
2361            // (e.g. syncing from genesis).
2362            self.state.epoch_db_pruner().prune_old_epoch_dbs().await;
2363
2364            epoch_store = new_epoch_store;
2365            epoch_metrics.record_epoch_change_stage_now(next_epoch, "reconfiguration_finished");
2366            info!("Reconfiguration finished");
2367        }
2368    }
2369
2370    /// Stops consensus, the JSON-RPC index backfill and the gRPC server.
2371    /// Does nothing the second time it is called.
2372    pub async fn shutdown(&self) {
2373        // First, so that a running expiry or compaction, which the runtime's
2374        // shutdown waits for, ends soon.
2375        self.state.stop_historic_bucket_work();
2376
2377        if let Some(validator_components) = &*self.validator_components.lock().await {
2378            validator_components.consensus_manager.shutdown().await;
2379        }
2380
2381        // Stop the background index backfill so shutdown does not block on
2382        // a full history replay.
2383        if let Some(indexes) = &self.state.rpc_indexes_store {
2384            indexes.shutdown().await;
2385        }
2386
2387        // Shutdown the gRPC server if it's running
2388        if let Some(grpc_handle) = self.grpc_server_handle.lock().await.take() {
2389            info!("Shutting down gRPC server");
2390            if let Err(e) = grpc_handle.shutdown().await {
2391                warn!("Failed to gracefully shutdown gRPC server: {e}");
2392            }
2393        }
2394    }
2395
2396    /// Asynchronously reconfigures the state of the authority node for the next
2397    /// epoch.
2398    async fn reconfigure_state(
2399        &self,
2400        state: &Arc<AuthorityState>,
2401        cur_epoch_store: &AuthorityPerEpochStore,
2402        next_epoch_committee: Committee,
2403        next_epoch_start_system_state: EpochStartSystemState,
2404        global_state_hasher: Arc<GlobalStateHasher>,
2405    ) -> IotaResult<Arc<AuthorityPerEpochStore>> {
2406        let next_epoch = next_epoch_committee.epoch();
2407
2408        let last_checkpoint = self
2409            .checkpoint_store
2410            .get_epoch_last_checkpoint(cur_epoch_store.epoch())
2411            .expect("Error loading last checkpoint for current epoch")
2412            .expect("Could not load last checkpoint for current epoch");
2413        let epoch_supply_change = last_checkpoint
2414            .end_of_epoch_data
2415            .as_ref()
2416            .ok_or_else(|| {
2417                IotaError::from("last checkpoint in epoch should contain end of epoch data")
2418            })?
2419            .epoch_supply_change;
2420
2421        let last_checkpoint_seq = last_checkpoint.sequence_number();
2422
2423        assert_eq!(
2424            Some(last_checkpoint_seq),
2425            self.checkpoint_store
2426                .get_highest_executed_checkpoint_seq_number()
2427                .expect("Error loading highest executed checkpoint sequence number")
2428        );
2429
2430        let epoch_start_configuration = EpochStartConfiguration::new(
2431            next_epoch_start_system_state,
2432            *last_checkpoint.digest(),
2433            state.get_object_store().as_ref(),
2434            EpochFlag::default_flags_for_new_epoch(&state.config),
2435        )
2436        .expect("EpochStartConfiguration construction cannot fail");
2437
2438        let new_epoch_store = self
2439            .state
2440            .reconfigure(
2441                cur_epoch_store,
2442                self.config.supported_protocol_versions.unwrap(),
2443                next_epoch_committee,
2444                epoch_start_configuration,
2445                global_state_hasher,
2446                &self.config.expensive_safety_check_config,
2447                epoch_supply_change,
2448                last_checkpoint_seq,
2449            )
2450            .await
2451            .expect("Reconfigure authority state cannot fail");
2452        info!(next_epoch, "Node State has been reconfigured");
2453        assert_eq!(next_epoch, new_epoch_store.epoch());
2454        // Every checkpoint of the ending epoch has executed, so the saved
2455        // synced watermark is safe to go on from while readers' value is held
2456        // in memory. Nodes outside the committee build no checkpoints, so
2457        // their saved watermark never falls behind and the hold is not turned
2458        // on for them. A hold turned on in an earlier epoch stays on, which is
2459        // harmless (see `CheckpointStore::hold_synced_watermark_in_memory`).
2460        if new_epoch_store.protocol_config().enable_pcool_flow()
2461            && self.state.is_committee_validator(&new_epoch_store)
2462        {
2463            self.checkpoint_store
2464                .hold_synced_watermark_in_memory(self.state.get_historic_ledger().clone())?;
2465        }
2466        self.state.get_reconfig_api().update_epoch_flags_metrics(
2467            cur_epoch_store.epoch_start_config().flags(),
2468            new_epoch_store.epoch_start_config().flags(),
2469        );
2470
2471        Ok(new_epoch_store)
2472    }
2473
2474    pub fn get_config(&self) -> &NodeConfig {
2475        &self.config
2476    }
2477
2478    async fn execute_transaction_immediately_at_zero_epoch(
2479        state: &Arc<AuthorityState>,
2480        epoch_store: &Arc<AuthorityPerEpochStore>,
2481        tx: &TransactionEnvelope,
2482        span: tracing::Span,
2483    ) {
2484        let _guard = span.enter();
2485        let transaction =
2486            iota_types::executable_transaction::VerifiedExecutableTransaction::new_unchecked(
2487                iota_types::executable_transaction::ExecutableTransaction::new_from_data_and_sig(
2488                    tx.data().clone(),
2489                    iota_types::executable_transaction::CertificateProof::Checkpoint(0, 0),
2490                ),
2491            );
2492        state
2493            .try_execute_immediately(&transaction, ExecutionEnv::new(), epoch_store)
2494            .unwrap();
2495    }
2496
2497    pub fn randomness_handle(&self) -> randomness::Handle {
2498        self.randomness_handle.clone()
2499    }
2500
2501    /// Returns the registry service holding the node's Prometheus registries
2502    /// and their shared exposure filter.
2503    pub(crate) fn registry_service(&self) -> &RegistryService {
2504        &self.registry_service
2505    }
2506
2507    /// Sends signed capability notification to committee validators for
2508    /// non-committee validators. This method implements retry logic to handle
2509    /// failed attempts to send the notification. It will retry sending the
2510    /// notification with an increasing interval until it receives a successful
2511    /// response from a f+1 committee members or 2f+1 non-retryable errors.
2512    async fn send_signed_capability_notification_to_committee_with_retry(
2513        &self,
2514        epoch_store: &Arc<AuthorityPerEpochStore>,
2515    ) {
2516        const INITIAL_RETRY_INTERVAL_SECS: u64 = 5;
2517        const RETRY_INTERVAL_INCREMENT_SECS: u64 = 5;
2518        const MAX_RETRY_INTERVAL_SECS: u64 = 300; // 5 minutes
2519
2520        // Create the capability notification once
2521        let config = epoch_store.protocol_config();
2522
2523        // Create the capability notification
2524        let capabilities = AuthorityCapabilitiesV1::new(
2525            self.state.name,
2526            epoch_store.get_chain(),
2527            self.config
2528                .supported_protocol_versions
2529                .expect("Supported versions should be populated")
2530                .truncate_below(config.version),
2531            self.state.get_available_system_packages(config).await,
2532        );
2533
2534        // Sign the capabilities using the authority key pair from config
2535        let signature = AuthoritySignature::new_secure(
2536            &IntentMessage::new(
2537                Intent::iota_app(IntentScope::AuthorityCapabilities),
2538                &capabilities,
2539            ),
2540            &epoch_store.epoch(),
2541            self.config.authority_key_pair(),
2542        );
2543
2544        let request = HandleCapabilityNotificationRequestV1 {
2545            message: SignedAuthorityCapabilitiesV1::new_from_data_and_sig(capabilities, signature),
2546        };
2547
2548        let mut retry_interval = Duration::from_secs(INITIAL_RETRY_INTERVAL_SECS);
2549
2550        loop {
2551            let auth_agg = self.auth_agg.load();
2552            match auth_agg
2553                .send_capability_notification_to_quorum(request.clone())
2554                .await
2555            {
2556                Ok(_) => {
2557                    info!("Successfully sent capability notification to committee");
2558                    break;
2559                }
2560                Err(err) => {
2561                    match &err {
2562                        AggregatorSendCapabilityNotificationError::RetryableNotification {
2563                            errors,
2564                        } => {
2565                            warn!(
2566                                "Failed to send capability notification to committee (retryable error), will retry in {:?}: {:?}",
2567                                retry_interval, errors
2568                            );
2569                        }
2570                        AggregatorSendCapabilityNotificationError::NonRetryableNotification {
2571                            errors,
2572                        } => {
2573                            error!(
2574                                "Failed to send capability notification to committee (non-retryable error): {:?}",
2575                                errors
2576                            );
2577                            break;
2578                        }
2579                    };
2580
2581                    // Wait before retrying
2582                    tokio::time::sleep(retry_interval).await;
2583
2584                    // Increase retry interval for the next attempt, capped at max
2585                    retry_interval = std::cmp::min(
2586                        retry_interval + Duration::from_secs(RETRY_INTERVAL_INCREMENT_SECS),
2587                        Duration::from_secs(MAX_RETRY_INTERVAL_SECS),
2588                    );
2589                }
2590            }
2591        }
2592    }
2593}
2594
2595#[cfg(msim)]
2596impl IotaNode {
2597    pub fn get_sim_node_id(&self) -> iota_simulator::task::NodeId {
2598        self.sim_state.sim_node.id()
2599    }
2600
2601    /// Gathers the metric families the node exposes under the current filter.
2602    pub fn gather_metrics(&self) -> Vec<prometheus_filtered::proto::MetricFamily> {
2603        self.registry_service.gather_all()
2604    }
2605
2606    pub fn set_safe_mode_expected(&self, new_value: bool) {
2607        info!("Setting safe mode expected to {}", new_value);
2608        self.sim_state
2609            .sim_safe_mode_expected
2610            .store(new_value, Ordering::Relaxed);
2611    }
2612}
2613
2614enum SpawnOnce {
2615    // Mutex is only needed to make SpawnOnce Sync
2616    Unstarted(
2617        Mutex<BoxFuture<'static, Result<iota_network_stack::server::Server>>>,
2618        tokio::runtime::Handle,
2619    ),
2620    #[allow(unused)]
2621    Started(iota_http::ServerHandle),
2622}
2623
2624impl SpawnOnce {
2625    pub fn new(
2626        future: impl Future<Output = Result<iota_network_stack::server::Server>> + Send + 'static,
2627        serving_rt_handle: tokio::runtime::Handle,
2628    ) -> Self {
2629        Self::Unstarted(Mutex::new(Box::pin(future)), serving_rt_handle)
2630    }
2631
2632    pub async fn start(self) -> Self {
2633        match self {
2634            Self::Unstarted(future, serving_rt_handle) => {
2635                // bind() and serve() must execute on the serving runtime:
2636                // iota_http::Builder::serve captures Handle::current() there for
2637                // the accept loop and every request handler.
2638                let (handle_tx, handle_rx) = tokio::sync::oneshot::channel();
2639                serving_rt_handle.spawn(async move {
2640                    let server = future.into_inner().await.unwrap_or_else(|err| {
2641                        panic!("Failed to start validator gRPC server: {err}")
2642                    });
2643                    if handle_tx.send(server.handle().clone()).is_err() {
2644                        return;
2645                    }
2646                    match server.serve().await {
2647                        Ok(()) => info!("Server stopped"),
2648                        Err(err) => info!("Server stopped: {err}"),
2649                    }
2650                });
2651                let handle = handle_rx
2652                    .await
2653                    .expect("validator gRPC server exited before returning its handle");
2654                Self::Started(handle)
2655            }
2656            Self::Started(_) => self,
2657        }
2658    }
2659
2660    pub fn shutdown(self) {
2661        if let SpawnOnce::Started(handle) = self {
2662            handle.trigger_shutdown();
2663        }
2664    }
2665}
2666
2667/// Notify [`DiscoveryEventLoop`] that a new list of trusted peers are now
2668/// available.
2669fn send_trusted_peer_change(
2670    config: &NodeConfig,
2671    sender: &watch::Sender<TrustedPeerChangeEvent>,
2672    new_epoch_start_state: &EpochStartSystemState,
2673) {
2674    let new_committee =
2675        new_epoch_start_state.get_validator_as_p2p_peers(config.authority_public_key());
2676
2677    sender.send_modify(|event| {
2678        core::mem::swap(&mut event.new_committee, &mut event.old_committee);
2679        event.new_committee = new_committee;
2680    })
2681}
2682
2683/// What the JSON-RPC and gRPC servers share to read the key-value store: the store metrics, which
2684/// register once, and the HTTP store, so that both use its client and cache.
2685struct SharedKeyValueStore {
2686    metrics: Arc<KeyValueStoreMetrics>,
2687    /// `None` without a base URL.
2688    http_store: Option<Arc<HttpKVStore>>,
2689}
2690
2691impl SharedKeyValueStore {
2692    fn new(config: &NodeConfig, registry: &Registry) -> Result<Self> {
2693        let metrics = KeyValueStoreMetrics::new(registry);
2694        let base_url = &config.transaction_kv_store_read_config.base_url;
2695        if base_url.is_empty() {
2696            info!("no http kv store url provided, using local db only");
2697            return Ok(Self {
2698                metrics,
2699                http_store: None,
2700            });
2701        }
2702
2703        base_url.parse::<url::Url>().tap_err(|e| {
2704            error!(
2705                "failed to parse config.transaction_kv_store_read_config.base_url ({:?}) as url: {}",
2706                base_url, e
2707            )
2708        })?;
2709        info!("using local key-value store with fallback to http key-value store");
2710        Ok(Self {
2711            http_store: Some(Arc::new(HttpKVStore::new(
2712                base_url,
2713                config.transaction_kv_store_read_config.cache_size,
2714                metrics.clone(),
2715            )?)),
2716            metrics,
2717        })
2718    }
2719
2720    /// The store JSON-RPC reads: the node's own, falling back to the HTTP store.
2721    fn json_rpc_store(&self, state: &Arc<AuthorityState>) -> Arc<TransactionKeyValueStore> {
2722        let db_store =
2723            TransactionKeyValueStore::new("rocksdb", self.metrics.clone(), state.clone());
2724        match &self.http_store {
2725            Some(http_store) => Arc::new(FallbackTransactionKVStore::new_kv(
2726                db_store,
2727                TransactionKeyValueStore::new("http", self.metrics.clone(), http_store.clone()),
2728                self.metrics.clone(),
2729                "json_rpc_fallback",
2730            )),
2731            None => Arc::new(db_store),
2732        }
2733    }
2734
2735    /// The store gRPC reads pruned data from.
2736    fn grpc_store(&self) -> Option<Arc<dyn TransactionKeyValueStoreTrait + Send + Sync>> {
2737        let http_store = self.http_store.clone()?;
2738        Some(Arc::new(TransactionKeyValueStore::new(
2739            "grpc_http",
2740            self.metrics.clone(),
2741            http_store,
2742        )))
2743    }
2744}
2745
2746/// Builds and starts the gRPC server for the IOTA node based on the node's
2747/// configuration.
2748///
2749/// Returns `None` on a validator and when the gRPC API is disabled.
2750///
2751/// # Panics
2752///
2753/// Panics if the gRPC API is enabled without a `grpc-api-config`.
2754/// [`NodeConfig::validate`] rejects such a config at startup.
2755async fn build_grpc_server(
2756    config: &NodeConfig,
2757    state: Arc<AuthorityState>,
2758    state_sync_store: RocksDbStore,
2759    executor: Option<Arc<dyn iota_types::transaction_executor::TransactionExecutor>>,
2760    prometheus_registry: &Registry,
2761    server_version: ServerVersion,
2762    transaction_fallback: Option<Arc<dyn TransactionKeyValueStoreTrait + Send + Sync>>,
2763) -> Result<Option<GrpcServerHandle>> {
2764    // Validators do not expose gRPC APIs. This return must agree with the
2765    // gRPC rule in `NodeConfig::validate`, which is what makes the `expect`
2766    // below unreachable.
2767    if config.is_validator() || !config.enable_grpc_api {
2768        return Ok(None);
2769    }
2770
2771    let grpc_config = config
2772        .grpc_api_config
2773        .as_ref()
2774        .expect("`NodeConfig::validate` rejects an enabled gRPC API without a config");
2775
2776    // Get chain identifier from state directly
2777    let chain_id = state.get_chain_identifier();
2778
2779    let grpc_read_store = Arc::new(GrpcReadStore::new(state.clone(), state_sync_store));
2780
2781    // Create cancellation token for proper shutdown hierarchy
2782    let shutdown_token = CancellationToken::new();
2783
2784    // Create GrpcReader
2785    let grpc_reader = Arc::new(
2786        GrpcReader::new(grpc_read_store, Some(server_version.to_string()))
2787            .with_transaction_fallback(transaction_fallback),
2788    );
2789
2790    // Create gRPC server metrics
2791    let grpc_server_metrics = iota_grpc_server::GrpcServerMetrics::new(prometheus_registry);
2792    let client_id_source = config
2793        .policy_config
2794        .as_ref()
2795        .map(|p| p.client_id_source.clone());
2796
2797    let handle = start_grpc_server(
2798        grpc_reader,
2799        executor,
2800        grpc_config.clone(),
2801        &config.grpc_api_listener_limits,
2802        shutdown_token,
2803        chain_id,
2804        Some(grpc_server_metrics),
2805        state.traffic_controller.clone(),
2806        client_id_source,
2807    )
2808    .await?;
2809
2810    Ok(Some(handle))
2811}
2812
2813/// Builds and starts the HTTP server for the IOTA node, exposing the JSON-RPC
2814/// API with `json_rpc_store`, or no JSON-RPC API when it is `None`. The
2815/// `/health` endpoint is served whether or not the JSON-RPC API is enabled.
2816///
2817/// Must not be called for a validator, which exposes no JSON-RPC API.
2818pub async fn build_http_server(
2819    state: Arc<AuthorityState>,
2820    transaction_orchestrator: &Option<Arc<TransactionOrchestrator<NetworkAuthorityClient>>>,
2821    config: &NodeConfig,
2822    prometheus_registry: &Registry,
2823    json_rpc_store: Option<Arc<TransactionKeyValueStore>>,
2824) -> Result<iota_http::ServerHandle> {
2825    let mut router = axum::Router::new();
2826
2827    // A full node with JSON-RPC off still serves `/health`, which liveness
2828    // probes rely on.
2829    if let Some(kv_store) = json_rpc_store {
2830        let json_rpc_router = {
2831            let traffic_controller = state.traffic_controller.clone();
2832            let mut server = JsonRpcServerBuilder::new(
2833                env!("CARGO_PKG_VERSION"),
2834                prometheus_registry,
2835                traffic_controller,
2836                config.policy_config.clone(),
2837            );
2838
2839            let metrics = Arc::new(JsonRpcMetrics::new(prometheus_registry));
2840            server.register_module(ReadApi::new(
2841                state.clone(),
2842                kv_store.clone(),
2843                metrics.clone(),
2844            ))?;
2845            server.register_module(CoinReadApi::new(
2846                state.clone(),
2847                kv_store.clone(),
2848                metrics.clone(),
2849            )?)?;
2850
2851            // if run_with_range is enabled we want to prevent any transactions
2852            // run_with_range = None is normal operating conditions
2853            if config.run_with_range.is_none() {
2854                server.register_module(TransactionBuilderApi::new(state.clone()))?;
2855            }
2856            server.register_module(GovernanceReadApi::new(state.clone(), metrics.clone()))?;
2857
2858            if let Some(transaction_orchestrator) = transaction_orchestrator {
2859                server.register_module(TransactionExecutionApi::new(
2860                    state.clone(),
2861                    transaction_orchestrator.clone(),
2862                    metrics.clone(),
2863                ))?;
2864            }
2865
2866            let iota_names_config = config.iota_names_config.clone().unwrap_or_else(|| {
2867                IotaNamesConfig::from_chain(&state.get_chain_identifier().chain())
2868            });
2869
2870            server.register_module(IndexerApi::new(
2871                state.clone(),
2872                ReadApi::new(state.clone(), kv_store.clone(), metrics.clone()),
2873                kv_store,
2874                metrics,
2875                iota_names_config,
2876            ))?;
2877            server.register_module(MoveUtils::new(state.clone()))?;
2878
2879            server.to_router().await?
2880        };
2881
2882        router = router.merge(json_rpc_router);
2883    }
2884
2885    router = router
2886        .route("/health", axum::routing::get(health_check_handler))
2887        .route_layer(axum::Extension(state));
2888
2889    let layers = ServiceBuilder::new()
2890        .map_request(|mut request: axum::http::Request<_>| {
2891            if let Some(connect_info) = request.extensions().get::<iota_http::ConnectInfo>() {
2892                let axum_connect_info = axum::extract::ConnectInfo(connect_info.remote_addr);
2893                request.extensions_mut().insert(axum_connect_info);
2894            }
2895            request
2896        })
2897        .layer(axum::middleware::from_fn(server_timing_middleware));
2898
2899    router = router.layer(layers);
2900
2901    // The listener is public and plaintext, so its connection count is bounded
2902    // only by this, well inside the process fd limit it shares with RocksDB and
2903    // the other listeners.
2904    const JSON_RPC_MAX_CONNECTIONS: NonZeroUsize = NonZeroUsize::new(4096).unwrap();
2905    // A reverse proxy in front of the node shows as one address, and HTTP/1
2906    // clients open a connection per request in flight, so one address may
2907    // hold a quarter of the listener; it then takes four to fill it.
2908    const JSON_RPC_MAX_CONNECTIONS_PER_CLIENT_IP: NonZeroUsize = NonZeroUsize::new(1024).unwrap();
2909    // Longer than HTTP clients keep an unused pooled connection (90 s in Go and
2910    // hyper), so they close first and a request is not sent on a
2911    // connection this server is closing at the same moment.
2912    const JSON_RPC_MAX_CONNECTION_IDLE: Duration = Duration::from_secs(300);
2913    // The smallest value RFC 9113 recommends; a JSON-RPC client needs few
2914    // requests in flight on one connection.
2915    const JSON_RPC_MAX_CONCURRENT_STREAMS: NonZeroU32 = NonZeroU32::new(100).unwrap();
2916    // Closes an HTTP/2 connection whose peer has gone while it still has a
2917    // request in flight, which the idle deadline does not.
2918    const JSON_RPC_HTTP2_KEEPALIVE: Duration = Duration::from_secs(60);
2919
2920    let limits = &config.json_rpc_listener_limits;
2921    let http_config = iota_http::Config::default()
2922        .handshake_timeout(
2923            limits
2924                .handshake_timeout
2925                .resolve(iota_http::DEFAULT_HANDSHAKE_TIMEOUT),
2926        )
2927        .max_pending_connections(
2928            limits
2929                .max_pending_connections
2930                .resolve(iota_http::DEFAULT_MAX_PENDING_CONNECTIONS),
2931        )
2932        .max_connections(limits.max_connections.resolve(JSON_RPC_MAX_CONNECTIONS))
2933        .max_connections_per_client_ip(
2934            limits
2935                .max_connections_per_client_ip
2936                .resolve(JSON_RPC_MAX_CONNECTIONS_PER_CLIENT_IP),
2937        )
2938        .ipv6_prefix_len(
2939            limits
2940                .ipv6_prefix_len
2941                .unwrap_or(iota_http::DEFAULT_IPV6_PREFIX_LEN),
2942        )
2943        .max_connection_idle(
2944            limits
2945                .max_connection_idle
2946                .resolve(JSON_RPC_MAX_CONNECTION_IDLE),
2947        )
2948        .max_concurrent_streams(
2949            limits
2950                .max_concurrent_streams
2951                .resolve(JSON_RPC_MAX_CONCURRENT_STREAMS),
2952        )
2953        .http2_keepalive_interval(
2954            limits
2955                .http2_keepalive_interval
2956                .resolve(JSON_RPC_HTTP2_KEEPALIVE),
2957        )
2958        .http1_header_read_timeout(
2959            limits
2960                .http1_header_read_timeout
2961                .resolve(iota_http::DEFAULT_HTTP1_HEADER_READ_TIMEOUT),
2962        )
2963        .metrics(json_rpc_listener_metrics(prometheus_registry));
2964    let handle = iota_http::Builder::new()
2965        .config(http_config)
2966        .serve(&config.json_rpc_address, router)
2967        .map_err(|e| anyhow::anyhow!("{e}"))?;
2968    info!(
2969        local_addr =? handle.local_addr(),
2970        json_rpc = config.enable_jsonrpc_api,
2971        "IOTA HTTP server listening on {}",
2972        handle.local_addr()
2973    );
2974
2975    Ok(handle)
2976}
2977
2978fn json_rpc_listener_metrics(prometheus_registry: &Registry) -> ListenerMetrics {
2979    ListenerMetrics::new("json_rpc", prometheus_registry, MetricLevel::Warn)
2980}
2981
2982fn validator_server_listener_metrics(prometheus_registry: &Registry) -> ListenerMetrics {
2983    ListenerMetrics::new("authority_grpc", prometheus_registry, MetricLevel::Warn)
2984}
2985
2986#[derive(Debug, serde::Serialize, serde::Deserialize)]
2987pub struct Threshold {
2988    pub threshold_seconds: Option<u32>,
2989}
2990
2991async fn health_check_handler(
2992    axum::extract::Query(Threshold { threshold_seconds }): axum::extract::Query<Threshold>,
2993    axum::Extension(state): axum::Extension<Arc<AuthorityState>>,
2994) -> impl axum::response::IntoResponse {
2995    if let Some(threshold_seconds) = threshold_seconds {
2996        // Attempt to get the latest checkpoint
2997        let summary = match state
2998            .get_checkpoint_store()
2999            .get_highest_executed_checkpoint()
3000        {
3001            Ok(Some(summary)) => summary,
3002            Ok(None) => {
3003                warn!("Highest executed checkpoint not found");
3004                return (axum::http::StatusCode::SERVICE_UNAVAILABLE, "down");
3005            }
3006            Err(err) => {
3007                warn!("Failed to retrieve highest executed checkpoint: {:?}", err);
3008                return (axum::http::StatusCode::SERVICE_UNAVAILABLE, "down");
3009            }
3010        };
3011
3012        // Calculate the threshold time based on the provided threshold_seconds
3013        let latest_chain_time = summary.timestamp();
3014        let threshold =
3015            std::time::SystemTime::now() - Duration::from_secs(threshold_seconds as u64);
3016
3017        // Check if the latest checkpoint is within the threshold
3018        if latest_chain_time < threshold {
3019            warn!(
3020                ?latest_chain_time,
3021                ?threshold,
3022                "failing health check due to checkpoint lag"
3023            );
3024            return (axum::http::StatusCode::SERVICE_UNAVAILABLE, "down");
3025        }
3026    }
3027    // if health endpoint is responding and no threshold is given, respond success
3028    (axum::http::StatusCode::OK, "up")
3029}
3030
3031#[cfg(not(test))]
3032fn max_tx_per_checkpoint(protocol_config: &ProtocolConfig) -> usize {
3033    protocol_config.max_transactions_per_checkpoint() as usize
3034}
3035
3036#[cfg(test)]
3037fn max_tx_per_checkpoint(_: &ProtocolConfig) -> usize {
3038    2
3039}
3040
3041// Not msim: this test asserts routing across real OS worker-thread pools by
3042// name, which the deterministic simulator collapses onto a single thread.
3043#[cfg(all(test, not(msim)))]
3044mod runtime_split_tests {
3045    use std::{
3046        sync::mpsc,
3047        time::{Duration, Instant},
3048    };
3049
3050    use anyhow::anyhow;
3051
3052    use super::SpawnOnce;
3053
3054    /// A single-worker-thread runtime whose worker thread carries `name`, so a
3055    /// task can tell which runtime it is running on via `current_pool()`.
3056    fn runtime(name: &'static str) -> tokio::runtime::Runtime {
3057        tokio::runtime::Builder::new_multi_thread()
3058            .worker_threads(1)
3059            .thread_name(name)
3060            .enable_all()
3061            .build()
3062            .unwrap()
3063    }
3064
3065    /// Name of the runtime whose worker thread is executing this code.
3066    fn current_pool() -> String {
3067        std::thread::current()
3068            .name()
3069            .unwrap_or("<unnamed>")
3070            .to_string()
3071    }
3072
3073    /// Regression guard for the runtime split. `SpawnOnce::start()` is invoked
3074    /// on the node-core runtime (as `IotaNode::start_async` does), but it
3075    /// must run the server *bind* on the serving runtime:
3076    /// `iota_http::Builder::serve` captures `Handle::current()` there for
3077    /// the accept loop and every request handler.
3078    ///
3079    /// The test records the runtime `start()` runs on and the runtime the bind
3080    /// runs on, and asserts the former is node-core and the latter is
3081    /// serving (so they differ). With the pre-fix inline bind the bind ran
3082    /// on the caller (node-core) runtime, and this test fails.
3083    #[test]
3084    fn spawn_once_binds_on_serving_not_the_core_runtime() {
3085        let node = runtime("node-core");
3086        let serving = runtime("serving");
3087        let (tx, rx) = mpsc::channel::<(&'static str, String)>();
3088
3089        // The "bind" future records where it runs, then binds a minimal real
3090        // server (health service only) on an ephemeral port.
3091        let bind_tx = tx.clone();
3092        let bind_future = async move {
3093            let _ = bind_tx.send(("bind", current_pool()));
3094            let addr = "/ip4/127.0.0.1/tcp/0/http".parse().unwrap();
3095            let server = iota_network_stack::config::Config::new()
3096                .server_builder()
3097                .bind(&addr, None)
3098                .await
3099                .map_err(|e| anyhow!("bind failed: {e}"))?;
3100            Ok(server)
3101        };
3102        let once = SpawnOnce::new(bind_future, serving.handle().clone());
3103
3104        // Drive start() ON the node-core runtime and record the runtime it runs on.
3105        let caller_tx = tx.clone();
3106        node.spawn(async move {
3107            let _ = caller_tx.send(("caller", current_pool()));
3108            let _ = once.start().await;
3109        });
3110
3111        // Collect both readings.
3112        let (mut caller_pool, mut bind_pool) = (None, None);
3113        let deadline = Instant::now() + Duration::from_secs(10);
3114        while (caller_pool.is_none() || bind_pool.is_none()) && Instant::now() < deadline {
3115            if let Ok((which, pool)) = rx.recv_timeout(Duration::from_millis(200)) {
3116                match which {
3117                    "caller" => caller_pool = Some(pool),
3118                    "bind" => bind_pool = Some(pool),
3119                    _ => {}
3120                }
3121            }
3122        }
3123        let caller_pool = caller_pool.expect("start() never ran");
3124        let bind_pool = bind_pool.expect("bind future never ran");
3125
3126        assert!(
3127            caller_pool.starts_with("node-core"),
3128            "start() should run on the node-core runtime, ran on: {caller_pool}"
3129        );
3130        assert!(
3131            bind_pool.starts_with("serving"),
3132            "server bind must run on the serving runtime, ran on: {bind_pool}"
3133        );
3134        assert_ne!(
3135            caller_pool, bind_pool,
3136            "the fix must move the bind off the caller (node-core) runtime onto serving"
3137        );
3138    }
3139}
3140
3141#[cfg(test)]
3142mod config_tests {
3143    use std::sync::{Arc, atomic::AtomicBool};
3144
3145    use iota_config::NodeConfig;
3146    use iota_metrics::RegistryService;
3147    use prometheus_filtered::Registry;
3148
3149    use super::{IotaNode, ServerVersion};
3150
3151    /// A config whose `db-path` is `db_path`, with nothing else a node would
3152    /// need to start.
3153    fn config_with_db_path(db_path: &std::path::Path) -> NodeConfig {
3154        serde_yaml::from_str(&format!(
3155            r#"
3156db-path: {}
3157network-address: /dns/localhost/tcp/8080/http
3158metrics-address: "0.0.0.0:9184"
3159json-rpc-address: "0.0.0.0:9000"
3160genesis:
3161  genesis-file-location: /nonexistent/genesis.blob
3162"#,
3163            db_path.display()
3164        ))
3165        .unwrap()
3166    }
3167
3168    /// `start_async` validates the config before it does anything else. That
3169    /// keeps the `expect` in `build_grpc_server` and the `debug_assert` in
3170    /// `start_state_snapshot` unreachable.
3171    #[tokio::test]
3172    async fn start_rejects_a_config_no_node_could_start_with() {
3173        let mut config = config_with_db_path(std::path::Path::new("/nonexistent/db"));
3174        config.enable_grpc_api = true;
3175        config.grpc_api_config = None;
3176
3177        let err = IotaNode::start(config, RegistryService::new(Registry::new()))
3178            .await
3179            .unwrap_err();
3180
3181        let err = format!("{err:#}");
3182        assert!(err.contains("`grpc-api-config` is `null`"), "{err}");
3183    }
3184
3185    /// `start_async` refuses a config whose index retention outlives its
3186    /// ledger retention before it opens a database.
3187    #[tokio::test]
3188    async fn index_retention_beyond_ledger_retention_refuses_to_start() {
3189        const TEMPLATE: &str = include_str!("../../iota-config/data/fullnode-template.yaml");
3190        let mut config: NodeConfig = serde_yaml::from_str(TEMPLATE).unwrap();
3191        config
3192            .authority_store_pruning_config
3193            .num_epochs_to_retain_for_checkpoints = Some(2);
3194        config
3195            .authority_store_pruning_config
3196            .num_epochs_to_retain_for_indexes = Some(3);
3197
3198        let err = IotaNode::start_async(
3199            config,
3200            RegistryService::new(Registry::new()),
3201            ServerVersion::new("test", "0.0.0"),
3202            tokio::runtime::Handle::current(),
3203            Arc::new(AtomicBool::new(false)),
3204        )
3205        .await
3206        .unwrap_err()
3207        .to_string();
3208
3209        assert!(err.contains("num-epochs-to-retain-for-indexes"), "{err}");
3210        assert!(
3211            err.contains("num-epochs-to-retain-for-checkpoints"),
3212            "{err}"
3213        );
3214    }
3215}
3216
3217#[cfg(test)]
3218mod listener_metrics_tests {
3219    use std::{collections::BTreeSet, sync::Arc, time::Duration};
3220
3221    use iota_metrics::{MetricGroups, MetricLevel, test_utils::MetricsReader};
3222    use iota_network_stack::config::Config;
3223    use iota_types::crypto::{NetworkPrivateKey, get_key_pair};
3224    use prometheus_filtered::Registry;
3225    use tokio::io::{AsyncReadExt, AsyncWriteExt};
3226    use tonic_health::pb::{HealthCheckRequest, health_client::HealthClient};
3227
3228    use super::{
3229        GrpcMetrics, ServerBuilder, json_rpc_listener_metrics, validator_server_listener_metrics,
3230    };
3231
3232    async fn get_health(handle: &iota_http::ServerHandle<std::net::SocketAddr>) {
3233        let mut stream = tokio::net::TcpStream::connect(handle.local_addr())
3234            .await
3235            .unwrap();
3236        stream
3237            .write_all(b"GET /health HTTP/1.1\r\nhost: localhost\r\nconnection: close\r\n\r\n")
3238            .await
3239            .unwrap();
3240        let mut response = String::new();
3241        tokio::time::timeout(
3242            Duration::from_secs(10),
3243            stream.read_to_string(&mut response),
3244        )
3245        .await
3246        .unwrap()
3247        .unwrap();
3248        assert!(response.starts_with("HTTP/1.1 200"), "{response}");
3249    }
3250
3251    /// Starts an HTTP listener with `metrics` and sends it one request.
3252    async fn serve_health(
3253        metrics: iota_http::metrics::ListenerMetrics,
3254    ) -> iota_http::ServerHandle<std::net::SocketAddr> {
3255        let handle = iota_http::Builder::new()
3256            .config(iota_http::Config::default().metrics(Some(metrics)))
3257            .serve(
3258                "127.0.0.1:0",
3259                axum::Router::new().route("/health", axum::routing::get(|| async { "up" })),
3260            )
3261            .unwrap();
3262        get_health(&handle).await;
3263        handle
3264    }
3265
3266    fn registry_with_groups(groups: &MetricGroups) -> Registry {
3267        let (filter, errors) = groups.startup_filter(None);
3268        assert!(errors.is_empty());
3269        Registry::new_custom(None, None, Some(Arc::new(filter))).unwrap()
3270    }
3271
3272    /// The registry of a node with the listener metrics registered the way the
3273    /// node registers them, after one TLS connection to the validator listener
3274    /// and one request to each of the JSON-RPC and gRPC API listeners.
3275    async fn node_registry(groups: &MetricGroups) -> Registry {
3276        let registry = registry_with_groups(groups);
3277
3278        let private_key = get_key_pair::<NetworkPrivateKey>().1;
3279        let tls_config =
3280            iota_tls::create_rustls_server_config(private_key.clone(), "test".to_string());
3281        let client_config = iota_tls::create_rustls_client_config(
3282            private_key.public_key(),
3283            "test".to_string(),
3284            None,
3285        );
3286        let config = Config::new();
3287        let validator = ServerBuilder::from_config(&config, GrpcMetrics::new(&registry))
3288            .listener_metrics(validator_server_listener_metrics(&registry))
3289            .bind(
3290                &"/ip4/127.0.0.1/tcp/0/http".parse().unwrap(),
3291                Some(tls_config),
3292            )
3293            .await
3294            .unwrap();
3295        let channel = config
3296            .connect(validator.local_addr(), client_config)
3297            .await
3298            .unwrap();
3299        HealthClient::new(channel)
3300            .check(HealthCheckRequest {
3301                service: String::new(),
3302            })
3303            .await
3304            .unwrap();
3305
3306        let json_rpc = serve_health(json_rpc_listener_metrics(&registry)).await;
3307        let grpc_api = iota_grpc_server::GrpcServerMetrics::new(&registry);
3308        let grpc_api_listener = serve_health(grpc_api.listener_metrics()).await;
3309
3310        validator.trigger_shutdown();
3311        json_rpc.trigger_shutdown();
3312        grpc_api_listener.trigger_shutdown();
3313        registry
3314    }
3315
3316    fn prefix_names<'a>(prefix: &'a str, names: &'a [&str]) -> impl Iterator<Item = String> + 'a {
3317        names.iter().map(move |name| format!("{prefix}_{name}"))
3318    }
3319
3320    const CONNECTION_FAMILIES: &[&str] = &[
3321        "inbound_connections_accepted",
3322        "inbound_connections",
3323        "inbound_connections_peak",
3324        "connection_lifetime_seconds",
3325    ];
3326    const TLS_FAMILIES: &[&str] = &["handshake_latency", "pending_handshakes_peak"];
3327    const CLIENT_FAMILIES: &[&str] = &["clients", "client_connections", "client_connections_peak"];
3328    const REQUEST_FAMILIES: &[&str] = &[
3329        "connection_idle_seconds",
3330        "connection_inflight_requests",
3331        "connection_inflight_requests_peak",
3332        "request_completion_latency",
3333        "response_delivery_latency",
3334    ];
3335
3336    /// `node_grpc_response_message_bytes` is not listed: it has a series per
3337    /// method, so it shows only once the gRPC API has sent a response.
3338    const GRPC_API_FAMILIES: &[&str] = &["response_item_bytes_peak", "requested_max_message_bytes"];
3339
3340    /// The families of the gRPC API that show by default. The request
3341    /// metrics per method are `warn` too, but have no series before the first
3342    /// request.
3343    const GRPC_API_DEFAULT_FAMILIES: &[&str] = &["inflight_checkpoint_stream_subscribers"];
3344
3345    /// Every family the listener of `prefix` registers, but not its TLS
3346    /// families.
3347    fn listener_families(prefix: &str) -> BTreeSet<String> {
3348        prefix_names(prefix, CONNECTION_FAMILIES)
3349            .chain(prefix_names(prefix, REQUEST_FAMILIES))
3350            .chain(prefix_names(prefix, CLIENT_FAMILIES))
3351            .collect()
3352    }
3353
3354    /// Every family the three listeners register. Only the validator listener
3355    /// uses TLS here.
3356    fn all_listener_families() -> BTreeSet<String> {
3357        listener_families("authority_grpc")
3358            .into_iter()
3359            .chain(prefix_names("authority_grpc", TLS_FAMILIES))
3360            .chain(listener_families("json_rpc"))
3361            .chain(listener_families("node_grpc"))
3362            .collect()
3363    }
3364
3365    /// The families of the response sizes of the gRPC API.
3366    fn grpc_api_families() -> BTreeSet<String> {
3367        prefix_names("node_grpc", GRPC_API_FAMILIES).collect()
3368    }
3369
3370    /// Every family that shows by default.
3371    fn default_families() -> BTreeSet<String> {
3372        all_listener_families()
3373            .into_iter()
3374            .chain(prefix_names("node_grpc", GRPC_API_DEFAULT_FAMILIES))
3375            .collect()
3376    }
3377
3378    async fn shown(groups: &MetricGroups) -> BTreeSet<String> {
3379        MetricsReader::new(&node_registry(groups).await).family_names()
3380    }
3381
3382    #[tokio::test]
3383    async fn the_listeners_and_the_grpc_api_requests_show_by_default() {
3384        assert_eq!(shown(&MetricGroups::default()).await, default_families());
3385    }
3386
3387    #[tokio::test]
3388    async fn the_iota_grpc_server_override_shows_the_response_sizes_of_the_grpc_api() {
3389        let groups = MetricGroups {
3390            overrides: [("iota_grpc_server".to_owned(), MetricLevel::Info)].into(),
3391            ..MetricGroups::default()
3392        };
3393        let expected: BTreeSet<String> = default_families()
3394            .into_iter()
3395            .chain(grpc_api_families())
3396            .collect();
3397        assert_eq!(shown(&groups).await, expected);
3398    }
3399}