Skip to main content

sui_core/
authority_server.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// SPDX-License-Identifier: Apache-2.0
4
5use anyhow::Result;
6use async_trait::async_trait;
7use fastcrypto::traits::KeyPair;
8use futures::{TryFutureExt, future};
9use itertools::Itertools as _;
10use moka::sync::Cache;
11use mysten_common::ZipDebugEqIteratorExt;
12use mysten_common::{assert_reachable, debug_fatal};
13use mysten_metrics::spawn_monitored_task;
14use parking_lot::Mutex;
15use prometheus::{
16    Gauge, Histogram, HistogramVec, IntCounter, IntCounterVec, IntGauge, Registry,
17    register_gauge_with_registry, register_histogram_vec_with_registry,
18    register_histogram_with_registry, register_int_counter_vec_with_registry,
19    register_int_counter_with_registry, register_int_gauge_with_registry,
20};
21use std::{
22    collections::{HashMap, HashSet},
23    io,
24    net::{IpAddr, SocketAddr},
25    sync::Arc,
26    time::{Duration, Instant, SystemTime},
27};
28use sui_network::{
29    api::{Validator, ValidatorServer},
30    tonic,
31    validator::server::SUI_TLS_SERVER_NAME,
32};
33use sui_types::effects::TransactionEffectsAPI;
34use sui_types::message_envelope::Message;
35use sui_types::messages_consensus::{ConsensusTransaction, ConsensusTransactionKey};
36use sui_types::messages_grpc::{
37    ObjectInfoRequest, ObjectInfoResponse, RawSubmitTxResponse, SystemStateRequest,
38    TransactionInfoRequest, TransactionInfoResponse,
39};
40use sui_types::multiaddr::Multiaddr;
41use sui_types::object::Object;
42use sui_types::sui_system_state::SuiSystemState;
43use sui_types::traffic_control::{ClientIdSource, Weight};
44use sui_types::{
45    base_types::ObjectID,
46    digests::{TransactionDigest, TransactionEffectsDigest},
47    error::{SuiErrorKind, UserInputError},
48};
49use sui_types::{
50    effects::TransactionEffects,
51    messages_grpc::{
52        ExecutedData, RawSubmitTxRequest, RawWaitForEffectsRequest, RawWaitForEffectsResponse,
53        SubmitTxResult, WaitForEffectsRequest, WaitForEffectsResponse,
54    },
55};
56use sui_types::{effects::TransactionEvents, messages_grpc::SubmitTxType};
57use sui_types::{error::*, transaction::*};
58use sui_types::{
59    fp_ensure,
60    messages_checkpoint::{
61        CheckpointRequest, CheckpointRequestV2, CheckpointResponse, CheckpointResponseV2,
62    },
63};
64use tokio::time::timeout;
65use tonic::metadata::{Ascii, MetadataValue};
66use tracing::{debug, error, info, instrument};
67
68use crate::admission_queue::{AdmissionQueueContext, AdmissionQueueManager};
69use crate::gasless_rate_limiter::GaslessRateLimiter;
70use crate::{
71    authority::{AuthorityState, consensus_tx_status_cache::ConsensusTxStatus},
72    consensus_adapter::{ConsensusAdapter, ConsensusAdapterMetrics, ConsensusOverloadChecker},
73    consensus_handler::SequencedConsensusTransactionKey,
74    traffic_controller::{TrafficController, parse_ip, policies::TrafficTally},
75};
76use crate::{
77    authority::{
78        authority_per_epoch_store::AuthorityPerEpochStore,
79        consensus_tx_status_cache::NotifyReadConsensusTxStatusResult,
80    },
81    checkpoints::CheckpointStore,
82    mysticeti_adapter::LazyMysticetiClient,
83};
84use sui_config::local_ip_utils::new_local_tcp_address_for_testing;
85
86#[cfg(test)]
87#[path = "unit_tests/server_tests.rs"]
88mod server_tests;
89
90#[cfg(test)]
91#[path = "unit_tests/wait_for_effects_tests.rs"]
92mod wait_for_effects_tests;
93
94#[cfg(test)]
95#[path = "unit_tests/submit_transaction_tests.rs"]
96mod submit_transaction_tests;
97
98pub struct AuthorityServerHandle {
99    server_handle: sui_network::validator::server::Server,
100}
101
102impl AuthorityServerHandle {
103    pub async fn join(self) -> Result<(), io::Error> {
104        self.server_handle.handle().wait_for_shutdown().await;
105        Ok(())
106    }
107
108    pub async fn kill(self) -> Result<(), io::Error> {
109        self.server_handle.handle().shutdown().await;
110        Ok(())
111    }
112
113    pub fn address(&self) -> &Multiaddr {
114        self.server_handle.local_addr()
115    }
116}
117
118pub struct AuthorityServer {
119    address: Multiaddr,
120    pub state: Arc<AuthorityState>,
121    consensus_adapter: Arc<ConsensusAdapter>,
122    pub metrics: Arc<ValidatorServiceMetrics>,
123}
124
125impl AuthorityServer {
126    pub fn new_for_test_with_consensus_adapter(
127        state: Arc<AuthorityState>,
128        consensus_adapter: Arc<ConsensusAdapter>,
129    ) -> Self {
130        let address = new_local_tcp_address_for_testing();
131        let metrics = Arc::new(ValidatorServiceMetrics::new_for_tests());
132
133        Self {
134            address,
135            state,
136            consensus_adapter,
137            metrics,
138        }
139    }
140
141    pub fn new_for_test(state: Arc<AuthorityState>) -> Self {
142        let slot_freed_notify = Arc::new(tokio::sync::Notify::new());
143        let consensus_adapter = Arc::new(ConsensusAdapter::new(
144            Arc::new(LazyMysticetiClient::new()),
145            CheckpointStore::new_for_tests(),
146            state.name,
147            100_000,
148            100_000,
149            ConsensusAdapterMetrics::new_test(),
150            slot_freed_notify,
151        ));
152        Self::new_for_test_with_consensus_adapter(state, consensus_adapter)
153    }
154
155    pub async fn spawn_for_test(self) -> Result<AuthorityServerHandle, io::Error> {
156        let address = self.address.clone();
157        self.spawn_with_bind_address_for_test(address).await
158    }
159
160    pub async fn spawn_with_bind_address_for_test(
161        self,
162        address: Multiaddr,
163    ) -> Result<AuthorityServerHandle, io::Error> {
164        let tls_config = sui_tls::create_rustls_server_config(
165            self.state.config.network_key_pair().copy().private(),
166            SUI_TLS_SERVER_NAME.to_string(),
167        );
168        let config = mysten_network::config::Config::new();
169        let server = sui_network::validator::server::ServerBuilder::from_config(
170            &config,
171            mysten_network::metrics::DefaultMetricsCallbackProvider::default(),
172        )
173        .add_service(ValidatorServer::new(ValidatorService::new_for_tests(
174            self.state,
175            self.consensus_adapter,
176            self.metrics,
177        )))
178        .bind(&address, Some(tls_config))
179        .await
180        .unwrap();
181        let local_addr = server.local_addr().to_owned();
182        info!("Listening to traffic on {local_addr}");
183        let handle = AuthorityServerHandle {
184            server_handle: server,
185        };
186        Ok(handle)
187    }
188}
189
190pub struct ValidatorServiceMetrics {
191    pub signature_errors: IntCounter,
192    pub tx_verification_latency: Histogram,
193    pub handle_transaction_latency: Histogram,
194    pub handle_transaction_consensus_latency: Histogram,
195    pub handle_submit_transaction_consensus_latency: HistogramVec,
196    pub handle_wait_for_effects_ping_latency: HistogramVec,
197
198    handle_submit_transaction_latency: HistogramVec,
199    handle_submit_transaction_bytes: HistogramVec,
200    handle_submit_transaction_batch_size: HistogramVec,
201
202    num_rejected_tx_during_overload: IntCounterVec,
203    submission_rejected_transactions: IntCounterVec,
204    submission_suppressed_already_processed: IntCounterVec,
205    submission_suppressed_recently_submitted: IntCounterVec,
206    recently_submitted_cache_size: IntGauge,
207    recently_submitted_resubmission_interval: Histogram,
208    submission_suppressed_inflight: IntCounterVec,
209    inflight_transactions: IntGauge,
210    connection_ip_not_found: IntCounter,
211    forwarded_header_parse_error: IntCounter,
212    forwarded_header_invalid: IntCounter,
213    forwarded_header_not_included: IntCounter,
214    client_id_source_config_mismatch: IntCounter,
215    x_forwarded_for_num_hops: Gauge,
216    pub gasless_rate_limited_count: IntCounter,
217    pub gasless_submission_outcomes: IntCounterVec,
218}
219
220impl ValidatorServiceMetrics {
221    pub fn new(registry: &Registry) -> Self {
222        Self {
223            signature_errors: register_int_counter_with_registry!(
224                "total_signature_errors",
225                "Number of transaction signature errors",
226                registry,
227            )
228            .unwrap(),
229            tx_verification_latency: register_histogram_with_registry!(
230                "validator_service_tx_verification_latency",
231                "Latency of verifying a transaction",
232                mysten_metrics::SUBSECOND_LATENCY_SEC_BUCKETS.to_vec(),
233                registry,
234            )
235            .unwrap(),
236            handle_transaction_latency: register_histogram_with_registry!(
237                "validator_service_handle_transaction_latency",
238                "Latency of handling a transaction",
239                mysten_metrics::SUBSECOND_LATENCY_SEC_BUCKETS.to_vec(),
240                registry,
241            )
242            .unwrap(),
243            handle_transaction_consensus_latency: register_histogram_with_registry!(
244                "validator_service_handle_transaction_consensus_latency",
245                "Latency of handling a user transaction sent through consensus",
246                mysten_metrics::COARSE_LATENCY_SEC_BUCKETS.to_vec(),
247                registry,
248            )
249            .unwrap(),
250            handle_submit_transaction_consensus_latency: register_histogram_vec_with_registry!(
251                "validator_service_submit_transaction_consensus_latency",
252                "Latency of submitting a user transaction sent through consensus",
253                &["req_type"],
254                mysten_metrics::COARSE_LATENCY_SEC_BUCKETS.to_vec(),
255                registry,
256            )
257            .unwrap(),
258            handle_submit_transaction_latency: register_histogram_vec_with_registry!(
259                "validator_service_submit_transaction_latency",
260                "Latency of submit transaction handler",
261                &["req_type"],
262                mysten_metrics::LATENCY_SEC_BUCKETS.to_vec(),
263                registry,
264            )
265            .unwrap(),
266            handle_wait_for_effects_ping_latency: register_histogram_vec_with_registry!(
267                "validator_service_handle_wait_for_effects_ping_latency",
268                "Latency of handling a ping request for wait_for_effects",
269                &["req_type"],
270                mysten_metrics::SUBSECOND_LATENCY_SEC_BUCKETS.to_vec(),
271                registry,
272            )
273            .unwrap(),
274            handle_submit_transaction_bytes: register_histogram_vec_with_registry!(
275                "validator_service_submit_transaction_bytes",
276                "The size of transactions in the submit transaction request",
277                &["req_type"],
278                mysten_metrics::BYTES_BUCKETS.to_vec(),
279                registry,
280            )
281            .unwrap(),
282            handle_submit_transaction_batch_size: register_histogram_vec_with_registry!(
283                "validator_service_submit_transaction_batch_size",
284                "The number of transactions in the submit transaction request",
285                &["req_type"],
286                mysten_metrics::COUNT_BUCKETS.to_vec(),
287                registry,
288            )
289            .unwrap(),
290            num_rejected_tx_during_overload: register_int_counter_vec_with_registry!(
291                "validator_service_num_rejected_tx_during_overload",
292                "Number of rejected transaction due to system overload",
293                &["error_type"],
294                registry,
295            )
296            .unwrap(),
297            submission_rejected_transactions: register_int_counter_vec_with_registry!(
298                "validator_service_submission_rejected_transactions",
299                "Number of transactions rejected during submission",
300                &["reason"],
301                registry,
302            )
303            .unwrap(),
304            submission_suppressed_already_processed: register_int_counter_vec_with_registry!(
305                "validator_service_submission_suppressed_already_processed",
306                "Number of submitted transactions suppressed because consensus had already \
307                 processed them this epoch (re-submission of already-processed transactions)",
308                &["req_type"],
309                registry,
310            )
311            .unwrap(),
312            submission_suppressed_recently_submitted: register_int_counter_vec_with_registry!(
313                "validator_service_submission_suppressed_recently_submitted",
314                "Number of submitted transactions suppressed because the same transaction was \
315                 submitted within the recent-submission window",
316                &["req_type"],
317                registry,
318            )
319            .unwrap(),
320            recently_submitted_cache_size: register_int_gauge_with_registry!(
321                "validator_service_recently_submitted_cache_size",
322                "Approximate number of transaction digests held in the recent-submission duplicate-suppression cache",
323                registry,
324            )
325            .unwrap(),
326            recently_submitted_resubmission_interval: register_histogram_with_registry!(
327                "validator_service_recently_submitted_resubmission_interval_seconds",
328                "Time between a transaction being recorded and a duplicate resubmission of it being suppressed",
329                mysten_metrics::SUBSECOND_LATENCY_SEC_BUCKETS.to_vec(),
330                registry,
331            )
332            .unwrap(),
333            submission_suppressed_inflight: register_int_counter_vec_with_registry!(
334                "validator_service_submission_suppressed_inflight",
335                "Number of submitted transactions suppressed because the same transaction was \
336                 already being handled by a concurrent in-flight submit request",
337                &["req_type"],
338                registry,
339            )
340            .unwrap(),
341            inflight_transactions: register_int_gauge_with_registry!(
342                "validator_service_inflight_transactions",
343                "Number of transactions from inflight submit requests",
344                registry,
345            )
346            .unwrap(),
347            connection_ip_not_found: register_int_counter_with_registry!(
348                "validator_service_connection_ip_not_found",
349                "Number of times connection IP was not extractable from request",
350                registry,
351            )
352            .unwrap(),
353            forwarded_header_parse_error: register_int_counter_with_registry!(
354                "validator_service_forwarded_header_parse_error",
355                "Number of times x-forwarded-for header could not be parsed",
356                registry,
357            )
358            .unwrap(),
359            forwarded_header_invalid: register_int_counter_with_registry!(
360                "validator_service_forwarded_header_invalid",
361                "Number of times x-forwarded-for header was invalid",
362                registry,
363            )
364            .unwrap(),
365            forwarded_header_not_included: register_int_counter_with_registry!(
366                "validator_service_forwarded_header_not_included",
367                "Number of times x-forwarded-for header was (unexpectedly) not included in request",
368                registry,
369            )
370            .unwrap(),
371            client_id_source_config_mismatch: register_int_counter_with_registry!(
372                "validator_service_client_id_source_config_mismatch",
373                "Number of times detected that client id source config doesn't agree with x-forwarded-for header",
374                registry,
375            )
376            .unwrap(),
377            x_forwarded_for_num_hops: register_gauge_with_registry!(
378                "validator_service_x_forwarded_for_num_hops",
379                "Number of hops in x-forwarded-for header",
380                registry,
381            )
382            .unwrap(),
383            gasless_rate_limited_count: register_int_counter_with_registry!(
384                "validator_service_gasless_rate_limited_count",
385                "Number of gasless transactions rejected by rate limiter",
386                registry,
387            )
388            .unwrap(),
389            gasless_submission_outcomes: register_int_counter_vec_with_registry!(
390                "validator_service_gasless_submission_outcomes",
391                "Number of valid gasless transaction submissions by outcome",
392                &["outcome"],
393                registry,
394            )
395            .unwrap(),
396        }
397    }
398
399    pub fn new_for_tests() -> Self {
400        let registry = Registry::new();
401        Self::new(&registry)
402    }
403}
404
405/// Where `handle_submit_transaction` routes a request.
406enum AdmissionQueueSubmitMode {
407    /// Admit via the gas-price priority queue.
408    Queue,
409    /// Submit directly to consensus, bypassing the queue — used when the queue
410    /// is turned off by config, temporarily disabled by failover, or for a ping
411    /// request. Individual txs are rejected when consensus is saturated
412    /// (pre-queue behavior).
413    Direct,
414}
415
416#[derive(Clone)]
417pub struct ValidatorService {
418    state: Arc<AuthorityState>,
419    consensus_adapter: Arc<ConsensusAdapter>,
420    metrics: Arc<ValidatorServiceMetrics>,
421    traffic_controller: Option<Arc<TrafficController>>,
422    client_id_source: Option<ClientIdSource>,
423    gasless_limiter: GaslessRateLimiter,
424    admission_queue: Option<AdmissionQueueContext>,
425    /// Digests submitted within the last `recent_submission_window` (value: when recorded), to
426    /// drop duplicate resubmissions before they reach consensus.
427    recently_submitted: Cache<TransactionDigest, Instant>,
428    /// How long a transaction is suppressed after submission (from node config).
429    recent_submission_window: Duration,
430    /// Digests currently being handled by an in-flight submit handler. Acquired atomically at
431    /// entry and removed (then demoted into `recently_submitted`) when the handler returns.
432    inflight_transactions: Arc<Mutex<HashSet<TransactionDigest>>>,
433}
434
435/// Assumed peak distinct-submission rate, used to size the dedup cache (per window).
436const RECENT_SUBMISSION_PEAK_TPS: u64 = 50_000;
437
438impl ValidatorService {
439    pub fn new(
440        state: Arc<AuthorityState>,
441        consensus_adapter: Arc<ConsensusAdapter>,
442        validator_metrics: Arc<ValidatorServiceMetrics>,
443        client_id_source: Option<ClientIdSource>,
444        admission_queue: Option<AdmissionQueueContext>,
445    ) -> Self {
446        let traffic_controller = state.traffic_controller.clone();
447        let gasless_limiter = GaslessRateLimiter::new(state.consensus_gasless_counter.clone());
448        let recent_submission_window = state.config.recent_submission_dedup_window();
449        Self {
450            state,
451            consensus_adapter,
452            metrics: validator_metrics,
453            traffic_controller,
454            client_id_source,
455            gasless_limiter,
456            admission_queue,
457            recently_submitted: Self::new_recently_submitted_cache(recent_submission_window),
458            recent_submission_window,
459            inflight_transactions: Arc::new(Mutex::new(HashSet::new())),
460        }
461    }
462
463    fn new_recently_submitted_cache(window: Duration) -> Cache<TransactionDigest, Instant> {
464        // Memory backstop only; the window bounds the cache, and amplified duplicates do not add
465        // entries (they share a digest). Sized for roughly one window at peak throughput.
466        let max_capacity = window.as_secs().max(1) * RECENT_SUBMISSION_PEAK_TPS;
467        Cache::builder()
468            .time_to_live(window)
469            .max_capacity(max_capacity)
470            .build()
471    }
472
473    pub fn new_for_tests(
474        state: Arc<AuthorityState>,
475        consensus_adapter: Arc<ConsensusAdapter>,
476        metrics: Arc<ValidatorServiceMetrics>,
477    ) -> Self {
478        let gasless_limiter = GaslessRateLimiter::new(state.consensus_gasless_counter.clone());
479        let epoch_store = state.epoch_store_for_testing().clone();
480        let slot_freed_notify = Arc::new(tokio::sync::Notify::new());
481        let manager = Arc::new(AdmissionQueueManager::new_for_tests(
482            consensus_adapter.clone(),
483            slot_freed_notify,
484        ));
485        let admission_queue = Some(AdmissionQueueContext::spawn(manager, epoch_store));
486        let recent_submission_window = state.config.recent_submission_dedup_window();
487        Self {
488            state,
489            consensus_adapter,
490            metrics,
491            traffic_controller: None,
492            client_id_source: None,
493            gasless_limiter,
494            admission_queue,
495            recently_submitted: Self::new_recently_submitted_cache(recent_submission_window),
496            recent_submission_window,
497            inflight_transactions: Arc::new(Mutex::new(HashSet::new())),
498        }
499    }
500
501    pub fn validator_state(&self) -> &Arc<AuthorityState> {
502        &self.state
503    }
504
505    /// Test method that performs transaction validation without going through gRPC.
506    pub fn handle_transaction_for_testing(&self, transaction: Transaction) -> SuiResult<()> {
507        let epoch_store = self.state.load_epoch_store_one_call_per_task();
508
509        // Validity check (basic structural validation)
510        transaction.validity_check(&epoch_store.tx_validity_check_context())?;
511
512        // Signature verification
513        let transaction = epoch_store
514            .verify_transaction_require_no_aliases(transaction)?
515            .into_tx();
516
517        // Validate the transaction
518        self.state
519            .handle_vote_transaction(&epoch_store, transaction)?;
520
521        Ok(())
522    }
523
524    /// Test method that performs transaction validation with overload checking.
525    /// Used for testing validator overload behavior.
526    pub fn handle_transaction_for_testing_with_overload_check(
527        &self,
528        transaction: Transaction,
529    ) -> SuiResult<()> {
530        let epoch_store = self.state.load_epoch_store_one_call_per_task();
531
532        // Validity check (basic structural validation)
533        transaction.validity_check(&epoch_store.tx_validity_check_context())?;
534
535        // Check system overload
536        self.state.check_system_overload(
537            transaction.data(),
538            self.state.check_system_overload_at_signing(),
539        )?;
540
541        // Signature verification
542        let transaction = epoch_store
543            .verify_transaction_require_no_aliases(transaction)?
544            .into_tx();
545
546        // Validate the transaction
547        self.state
548            .handle_vote_transaction(&epoch_store, transaction)?;
549
550        Ok(())
551    }
552
553    /// Collect the IDs of input objects that are immutable.
554    /// This is used to create the ImmutableInputObjects claim for consensus messages.
555    async fn collect_immutable_object_ids(
556        &self,
557        tx: &VerifiedTransaction,
558        state: &AuthorityState,
559    ) -> SuiResult<Vec<ObjectID>> {
560        let input_objects = tx.data().transaction_data().input_objects()?;
561
562        // Collect object IDs from ImmOrOwnedMoveObject inputs
563        let object_ids: Vec<ObjectID> = input_objects
564            .iter()
565            .filter_map(|obj| match obj {
566                InputObjectKind::ImmOrOwnedMoveObject((id, _, _)) => Some(*id),
567                _ => None,
568            })
569            .collect();
570        if object_ids.is_empty() {
571            return Ok(vec![]);
572        }
573
574        // Load objects from cache and filter to immutable ones
575        let objects = state.get_object_cache_reader().get_objects(&object_ids);
576
577        // All objects should be found, since owned input objects have been validated to exist.
578        objects
579            .into_iter()
580            .zip_debug_eq(object_ids.iter())
581            .filter_map(|(obj, id)| {
582                let Some(o) = obj else {
583                    return Some(Err::<ObjectID, SuiError>(
584                        SuiErrorKind::UserInputError {
585                            error: UserInputError::ObjectNotFound {
586                                object_id: *id,
587                                version: None,
588                            },
589                        }
590                        .into(),
591                    ));
592                };
593                if o.is_immutable() {
594                    Some(Ok(*id))
595                } else {
596                    None
597                }
598            })
599            .collect::<SuiResult<Vec<ObjectID>>>()
600    }
601
602    #[instrument(
603        name = "ValidatorService::handle_submit_transaction",
604        level = "error",
605        skip_all,
606        err(level = "debug")
607    )]
608    async fn handle_submit_transaction(
609        &self,
610        request: tonic::Request<RawSubmitTxRequest>,
611    ) -> WrappedServiceResponse<RawSubmitTxResponse> {
612        let Self {
613            state,
614            consensus_adapter: _,
615            metrics,
616            traffic_controller: _,
617            client_id_source,
618            gasless_limiter: _,
619            admission_queue: _,
620            recently_submitted: _,
621            recent_submission_window: _,
622            inflight_transactions: _,
623        } = self.clone();
624
625        let submitter_client_addr = if let Some(client_id_source) = &client_id_source {
626            self.get_client_ip_addr(&request, client_id_source)
627        } else {
628            self.get_client_ip_addr(&request, &ClientIdSource::SocketAddr)
629        };
630
631        let inner = request.into_inner();
632        let start_epoch = state.load_epoch_store_one_call_per_task().epoch();
633
634        let next_epoch = start_epoch + 1;
635        let mut max_retries = 1;
636
637        let mut inflight_guard = InflightTransactionsGuard::new(self);
638        loop {
639            let res = self
640                .handle_submit_transaction_inner(
641                    &state,
642                    &metrics,
643                    &inner,
644                    submitter_client_addr,
645                    &mut inflight_guard,
646                )
647                .await;
648            match res {
649                Ok((response, weight)) => return Ok((tonic::Response::new(response), weight)),
650                Err(err) => {
651                    if max_retries > 0
652                        && let SuiErrorKind::ValidatorHaltedAtEpochEnd = err.as_inner()
653                    {
654                        max_retries -= 1;
655
656                        debug!(
657                            "ValidatorHaltedAtEpochEnd. Will retry after validator reconfigures"
658                        );
659
660                        if let Ok(Ok(new_epoch)) =
661                            timeout(Duration::from_secs(15), state.wait_for_epoch(next_epoch)).await
662                        {
663                            assert_reachable!("retry submission at epoch end");
664                            if new_epoch >= next_epoch {
665                                continue;
666                            }
667                            // wait_for_epoch guarantees >= target; < would indicate a bug there.
668                            debug_fatal!(
669                                "wait_for_epoch returned early: expected >= {}, got {}",
670                                next_epoch,
671                                new_epoch
672                            );
673                        }
674                    }
675                    return Err(err.into());
676                }
677            }
678        }
679    }
680
681    async fn handle_submit_transaction_inner(
682        &self,
683        state: &AuthorityState,
684        metrics: &ValidatorServiceMetrics,
685        request: &RawSubmitTxRequest,
686        submitter_client_addr: Option<IpAddr>,
687        inflight_guard: &mut InflightTransactionsGuard,
688    ) -> SuiResult<(RawSubmitTxResponse, Weight)> {
689        let epoch_store = state.load_epoch_store_one_call_per_task();
690        let submit_type = SubmitTxType::try_from(request.submit_type).map_err(|e| {
691            SuiErrorKind::GrpcMessageDeserializeError {
692                type_info: "RawSubmitTxRequest.submit_type".to_string(),
693                error: e.to_string(),
694            }
695        })?;
696
697        let is_ping_request = submit_type == SubmitTxType::Ping;
698        if is_ping_request {
699            fp_ensure!(
700                request.transactions.is_empty(),
701                SuiErrorKind::InvalidRequest(format!(
702                    "Ping request cannot contain {} transactions",
703                    request.transactions.len()
704                ))
705                .into()
706            );
707        } else {
708            // Ensure default and soft bundle requests contain at least one transaction.
709            fp_ensure!(
710                !request.transactions.is_empty(),
711                SuiErrorKind::InvalidRequest(
712                    "At least one transaction needs to be submitted".to_string(),
713                )
714                .into()
715            );
716        }
717
718        // NOTE: for soft bundle requests, the system tries to sequence the transactions in the same order
719        // if they use the same gas price. But this is only done with best effort.
720        // Transactions in a soft bundle can be individually rejected or deferred, without affecting
721        // other transactions in the same bundle.
722        let is_soft_bundle_request = submit_type == SubmitTxType::SoftBundle;
723
724        let max_num_transactions = if is_soft_bundle_request {
725            // Soft bundle cannot contain too many transactions.
726            // Otherwise it is hard to include all of them in a single block.
727            epoch_store.protocol_config().max_soft_bundle_size()
728        } else {
729            // Still enforce a limit even when transactions do not need to be in the same block.
730            epoch_store
731                .protocol_config()
732                .max_num_transactions_in_block()
733        };
734        fp_ensure!(
735            request.transactions.len() <= max_num_transactions as usize,
736            SuiErrorKind::InvalidRequest(format!(
737                "Too many transactions in request: {} vs {}",
738                request.transactions.len(),
739                max_num_transactions
740            ))
741            .into()
742        );
743
744        // Transaction digests.
745        let mut tx_digests = Vec::with_capacity(request.transactions.len());
746        // Transactions to submit to consensus.
747        let mut consensus_transactions = Vec::with_capacity(request.transactions.len());
748        // Indexes of transactions above in the request transactions.
749        let mut transaction_indexes = Vec::with_capacity(request.transactions.len());
750        // Results corresponding to each transaction in the request.
751        let mut results: Vec<Option<SubmitTxResult>> = vec![None; request.transactions.len()];
752        // Total size of all transactions in the request.
753        let mut total_size_bytes = 0;
754        // Whether the request contains any gasless transaction.
755        let mut has_gasless = false;
756        // Set when a transaction duplicates an in-flight submission at admission. Tracked
757        // separately because it is detected after the per-tx results are finalized (those
758        // remain Submitted), so it cannot be derived from the results alone.
759        let mut duplicate_at_admission = false;
760        // First gas price seen in this soft bundle.
761        let mut expected_soft_bundle_gas_price = None;
762        // Transaction digests seen in this request attempt, used to reject repeated transactions.
763        let mut request_digests = HashSet::new();
764
765        let req_type = if is_ping_request {
766            "ping"
767        } else if request.transactions.len() == 1 {
768            "single_transaction"
769        } else if is_soft_bundle_request {
770            "soft_bundle"
771        } else {
772            "batch"
773        };
774
775        let _handle_tx_metrics_guard = metrics
776            .handle_submit_transaction_latency
777            .with_label_values(&[req_type])
778            .start_timer();
779
780        let submit_mode = self.classify_submit_mode(is_ping_request);
781
782        for (idx, tx_bytes) in request.transactions.iter().enumerate() {
783            let transaction = match bcs::from_bytes::<Transaction>(tx_bytes) {
784                Ok(txn) => txn,
785                Err(e) => {
786                    // Ok to fail the request when any transaction is invalid.
787                    return Err(SuiErrorKind::TransactionDeserializationError {
788                        error: format!("Failed to deserialize transaction at index {}: {}", idx, e),
789                    }
790                    .into());
791                }
792            };
793
794            // Ok to fail the request when any transaction is invalid.
795            let tx_size = transaction.validity_check(&epoch_store.tx_validity_check_context())?;
796            let tx_digest = *transaction.digest();
797
798            // A request must not repeat a transaction.
799            if !request_digests.insert(tx_digest) {
800                let error: SuiError = SuiErrorKind::UserInputError {
801                    error: UserInputError::RepeatedTransactions { digest: tx_digest },
802                }
803                .into();
804                // Reject individual repeated transactions in batch.
805                if is_soft_bundle_request {
806                    return Err(error);
807                }
808                results[idx] = Some(SubmitTxResult::Rejected { error });
809                continue;
810            }
811
812            // Soft bundles require all transactions to use the same gas price.
813            if is_soft_bundle_request {
814                let gas_price = transaction.data().transaction_data().gas_price();
815                if let Some(expected) = expected_soft_bundle_gas_price {
816                    fp_ensure!(
817                        gas_price == expected,
818                        SuiErrorKind::UserInputError {
819                            error: UserInputError::GasPriceMismatchError {
820                                digest: tx_digest,
821                                expected,
822                                actual: gas_price,
823                            }
824                        }
825                        .into()
826                    );
827                } else {
828                    expected_soft_bundle_gas_price = Some(gas_price);
829                }
830            }
831
832            let is_gasless = transaction
833                .data()
834                .transaction_data()
835                .is_gasless_transaction();
836
837            if is_gasless {
838                has_gasless = true;
839                metrics
840                    .gasless_submission_outcomes
841                    .with_label_values(&["attempted"])
842                    .inc();
843            }
844
845            let overload_check_res = state.check_system_overload(
846                transaction.data(),
847                state.check_system_overload_at_signing(),
848            );
849            if let Err(error) = overload_check_res {
850                metrics
851                    .num_rejected_tx_during_overload
852                    .with_label_values(&[error.as_ref()])
853                    .inc();
854                if is_gasless {
855                    metrics
856                        .gasless_submission_outcomes
857                        .with_label_values(&["rejected_overload"])
858                        .inc();
859                }
860                results[idx] = Some(SubmitTxResult::Rejected { error });
861                continue;
862            }
863
864            // Use the pre-queue per-tx consensus overload reject on the direct
865            // submission path (queue off, failover, or ping).
866            if matches!(submit_mode, AdmissionQueueSubmitMode::Direct)
867                && let Err(error) = self.consensus_adapter.check_consensus_overload()
868            {
869                state.update_overload_metrics("consensus");
870                metrics
871                    .num_rejected_tx_during_overload
872                    .with_label_values(&[error.as_ref()])
873                    .inc();
874                if is_gasless {
875                    metrics
876                        .gasless_submission_outcomes
877                        .with_label_values(&["rejected_overload"])
878                        .inc();
879                }
880                results[idx] = Some(SubmitTxResult::Rejected { error });
881                continue;
882            }
883
884            if is_gasless
885                && !self
886                    .gasless_limiter
887                    .try_acquire(epoch_store.protocol_config())
888            {
889                metrics.gasless_rate_limited_count.inc();
890                metrics
891                    .gasless_submission_outcomes
892                    .with_label_values(&["rejected_rate_limited"])
893                    .inc();
894                results[idx] = Some(SubmitTxResult::Rejected {
895                    error: SuiErrorKind::ValidatorOverloadedRetryAfter {
896                        retry_after_secs: 1,
897                    }
898                    .into(),
899                });
900                continue;
901            }
902
903            // Ok to fail the request when any signature is invalid.
904            let verified_transaction = {
905                let _metrics_guard = metrics.tx_verification_latency.start_timer();
906                if epoch_store.protocol_config().address_aliases() {
907                    match epoch_store.verify_transaction_with_current_aliases(transaction) {
908                        Ok(tx) => tx,
909                        Err(e) => {
910                            metrics.signature_errors.inc();
911                            return Err(e);
912                        }
913                    }
914                } else {
915                    match epoch_store.verify_transaction_require_no_aliases(transaction) {
916                        Ok(tx) => tx,
917                        Err(e) => {
918                            metrics.signature_errors.inc();
919                            return Err(e);
920                        }
921                    }
922                }
923            };
924
925            debug!(
926                ?tx_digest,
927                "handle_submit_transaction: verified transaction"
928            );
929
930            // Check if the transaction has executed, before checking input objects
931            // which could have been consumed.
932            if let Some(effects) = state
933                .get_transaction_cache_reader()
934                .get_executed_effects(&tx_digest)
935            {
936                let effects_digest = effects.digest();
937                if let Ok(executed_data) = self.complete_executed_data(effects).await {
938                    let executed_result = SubmitTxResult::Executed {
939                        effects_digest,
940                        details: Some(executed_data),
941                    };
942                    results[idx] = Some(executed_result);
943                    debug!(?tx_digest, "handle_submit_transaction: already executed");
944                    continue;
945                }
946            }
947
948            if self
949                .state
950                .get_transaction_cache_reader()
951                .transaction_executed_in_last_epoch(&tx_digest, epoch_store.epoch())
952            {
953                results[idx] = Some(SubmitTxResult::Rejected {
954                    error: UserInputError::TransactionAlreadyExecuted { digest: tx_digest }.into(),
955                });
956                debug!(
957                    ?tx_digest,
958                    "handle_submit_transaction: transaction already executed in previous epoch"
959                );
960                continue;
961            }
962
963            // Suppress resubmission of transactions consensus already processed this epoch:
964            // executed transactions whose effects details could not be reconstructed above (e.g.
965            // objects pruned), sequenced-but-deferred transactions, and dropped transactions.
966            let consensus_key = SequencedConsensusTransactionKey::External(
967                ConsensusTransactionKey::Certificate(tx_digest),
968            );
969            if epoch_store.is_consensus_message_processed(&consensus_key)? {
970                // Prefer a concrete, non-retriable error over the generic, retriable
971                // TransactionProcessing suppression. A processed-but-unexecuted digest is
972                // commonly a dropped owned-object conflict loser; surfacing the terminal
973                // error lets the client stop retrying instead of polling for effects that
974                // will never come.
975                //
976                // First check the epoch owned-object lock table with the same conflict
977                // logic the consensus handler uses post-consensus. Locks are never
978                // released within an epoch, so this reports the conflict even before the
979                // winner executes, while the loser's input versions still validate as
980                // live.
981                if let Ok(input_objects) = verified_transaction
982                    .tx()
983                    .data()
984                    .transaction_data()
985                    .input_objects()
986                {
987                    let immutable_object_ids = self
988                        .collect_immutable_object_ids(verified_transaction.tx(), state)
989                        .await?;
990                    let owned_object_refs: Vec<_> = input_objects
991                        .iter()
992                        .filter_map(|obj| match obj {
993                            InputObjectKind::ImmOrOwnedMoveObject(obj_ref)
994                                if !immutable_object_ids.contains(&obj_ref.0) =>
995                            {
996                                Some(*obj_ref)
997                            }
998                            _ => None,
999                        })
1000                        .collect();
1001                    let existing_locks =
1002                        epoch_store.get_owned_object_locks_map(&owned_object_refs)?;
1003                    if let Err(error) = epoch_store.try_acquire_owned_object_locks_post_consensus(
1004                        &owned_object_refs,
1005                        tx_digest,
1006                        &HashMap::new(),
1007                        &existing_locks,
1008                    ) {
1009                        debug!(
1010                            ?tx_digest,
1011                            "handle_submit_transaction: processed transaction rejected on lock conflict: {error}"
1012                        );
1013                        metrics
1014                            .submission_rejected_transactions
1015                            .with_label_values(&[error.to_variant_name()])
1016                            .inc();
1017                        results[idx] = Some(SubmitTxResult::Rejected { error });
1018                        continue;
1019                    }
1020                }
1021                // Then revalidate against live state, which surfaces the terminal
1022                // stale-version error once the conflict winner has executed.
1023                if let Err(error) =
1024                    state.handle_vote_transaction(&epoch_store, verified_transaction.tx().clone())
1025                {
1026                    // The transaction may have executed while being validated (e.g. it was
1027                    // deferred rather than dropped).
1028                    if let Some(effects) = state
1029                        .get_transaction_cache_reader()
1030                        .get_executed_effects(&tx_digest)
1031                    {
1032                        let effects_digest = effects.digest();
1033                        if let Ok(executed_data) = self.complete_executed_data(effects).await {
1034                            results[idx] = Some(SubmitTxResult::Executed {
1035                                effects_digest,
1036                                details: Some(executed_data),
1037                            });
1038                            continue;
1039                        }
1040                    }
1041                    debug!(
1042                        ?tx_digest,
1043                        "handle_submit_transaction: processed transaction rejected on revalidation: {error}"
1044                    );
1045                    metrics
1046                        .submission_rejected_transactions
1047                        .with_label_values(&[error.to_variant_name()])
1048                        .inc();
1049                    results[idx] = Some(SubmitTxResult::Rejected { error });
1050                    continue;
1051                }
1052                // Validation passed, so this processed digest may still be executable.
1053                // Return retriable TransactionProcessing rather than resubmitting it to consensus.
1054                // A later client retry can observe effects or a concrete terminal validation error.
1055                metrics
1056                    .submission_suppressed_already_processed
1057                    .with_label_values(&[req_type])
1058                    .inc();
1059                results[idx] = Some(SubmitTxResult::Rejected {
1060                    error: SuiErrorKind::TransactionProcessing {
1061                        digest: tx_digest,
1062                        status: "consensus message processed".to_string(),
1063                    }
1064                    .into(),
1065                });
1066                debug!(
1067                    ?tx_digest,
1068                    "handle_submit_transaction: consensus message already processed"
1069                );
1070                continue;
1071            }
1072
1073            // Atomically acquire the digest for the duration of this handler. Reject concurrent
1074            // and recent duplicates and record the result per result index.
1075            match inflight_guard.try_acquire(tx_digest) {
1076                AcquireOutcome::Acquired | AcquireOutcome::AlreadyAcquiredByThisRequest => {
1077                    // Continue to process the transaction and submit to consensus.
1078                }
1079                AcquireOutcome::AlreadyAcquiredByAnotherRequest => {
1080                    metrics
1081                        .submission_suppressed_inflight
1082                        .with_label_values(&[req_type])
1083                        .inc();
1084                    results[idx] = Some(SubmitTxResult::Rejected {
1085                        error: SuiErrorKind::TransactionSubmitted { digest: tx_digest }.into(),
1086                    });
1087                    debug!(
1088                        ?tx_digest,
1089                        "handle_submit_transaction: concurrent submission in progress"
1090                    );
1091                    continue;
1092                }
1093                AcquireOutcome::RecentlyProcessed { since } => {
1094                    metrics
1095                        .submission_suppressed_recently_submitted
1096                        .with_label_values(&[req_type])
1097                        .inc();
1098                    metrics
1099                        .recently_submitted_resubmission_interval
1100                        .observe(since.as_secs_f64());
1101                    results[idx] = Some(SubmitTxResult::Rejected {
1102                        error: SuiErrorKind::TransactionSubmitted { digest: tx_digest }.into(),
1103                    });
1104                    debug!(?tx_digest, "handle_submit_transaction: recently processed");
1105                    continue;
1106                }
1107            }
1108
1109            debug!(
1110                ?tx_digest,
1111                "handle_submit_transaction: waiting for fastpath dependency objects"
1112            );
1113            if !state
1114                .wait_for_fastpath_dependency_objects(
1115                    verified_transaction.tx(),
1116                    epoch_store.epoch(),
1117                )
1118                .await?
1119            {
1120                debug!(
1121                    ?tx_digest,
1122                    "fastpath input objects are still unavailable after waiting"
1123                );
1124            }
1125
1126            match state.handle_vote_transaction(&epoch_store, verified_transaction.tx().clone()) {
1127                Ok(_) => { /* continue processing */ }
1128                Err(e) => {
1129                    // Check if transaction has been executed while being validated.
1130                    // This is an edge case so checking executed effects twice is acceptable.
1131                    if let Some(effects) = state
1132                        .get_transaction_cache_reader()
1133                        .get_executed_effects(&tx_digest)
1134                    {
1135                        let effects_digest = effects.digest();
1136                        if let Ok(executed_data) = self.complete_executed_data(effects).await {
1137                            let executed_result = SubmitTxResult::Executed {
1138                                effects_digest,
1139                                details: Some(executed_data),
1140                            };
1141                            results[idx] = Some(executed_result);
1142                            continue;
1143                        }
1144                    }
1145
1146                    // When the transaction has not been executed, record the error for the transaction.
1147                    debug!(?tx_digest, "Transaction rejected during submission: {e}");
1148                    metrics
1149                        .submission_rejected_transactions
1150                        .with_label_values(&[e.to_variant_name()])
1151                        .inc();
1152                    results[idx] = Some(SubmitTxResult::Rejected { error: e });
1153                    continue;
1154                }
1155            }
1156
1157            // Create claims with aliases and / or immutable objects.
1158            let mut claims = vec![];
1159
1160            let immutable_object_ids = self
1161                .collect_immutable_object_ids(verified_transaction.tx(), state)
1162                .await?;
1163            if !immutable_object_ids.is_empty() {
1164                claims.push(TransactionClaim::ImmutableInputObjects(
1165                    immutable_object_ids,
1166                ));
1167            }
1168
1169            let (tx, aliases) = verified_transaction.into_inner();
1170            if epoch_store.protocol_config().address_aliases() {
1171                if epoch_store
1172                    .protocol_config()
1173                    .fix_checkpoint_signature_mapping()
1174                {
1175                    claims.push(TransactionClaim::AddressAliasesV2(aliases));
1176                } else {
1177                    let v1_aliases: Vec<_> = tx
1178                        .data()
1179                        .intent_message()
1180                        .value
1181                        .required_signers()
1182                        .into_iter()
1183                        .zip_eq(aliases.into_iter().map(|(_, seq)| seq))
1184                        .collect();
1185                    #[allow(deprecated)]
1186                    claims.push(TransactionClaim::AddressAliases(
1187                        nonempty::NonEmpty::from_vec(v1_aliases)
1188                            .expect("must have at least one required_signer"),
1189                    ));
1190                }
1191            }
1192
1193            let tx_with_claims = TransactionWithClaims::new(tx.into(), claims);
1194
1195            consensus_transactions.push(ConsensusTransaction::new_user_transaction_v2_message(
1196                &state.name,
1197                tx_with_claims,
1198            ));
1199            if is_gasless {
1200                metrics
1201                    .gasless_submission_outcomes
1202                    .with_label_values(&["submitted"])
1203                    .inc();
1204            }
1205
1206            transaction_indexes.push(idx);
1207            tx_digests.push(tx_digest);
1208            total_size_bytes += tx_size;
1209        }
1210
1211        if consensus_transactions.is_empty() && !is_ping_request {
1212            let spam_weight = Self::request_spam_weight(
1213                &results,
1214                has_gasless,
1215                duplicate_at_admission,
1216                is_ping_request,
1217            );
1218            let response = Self::try_from_submit_tx_response(results)?;
1219            return Ok((response, spam_weight));
1220        }
1221
1222        // Set the max bytes size of the soft bundle to be half of the consensus max transactions in block size.
1223        // We do this to account for serialization overheads and to ensure that the soft bundle is not too large
1224        // when is attempted to be posted via consensus.
1225        let max_transaction_bytes = if is_soft_bundle_request {
1226            epoch_store
1227                .protocol_config()
1228                .consensus_max_transactions_in_block_bytes()
1229                / 2
1230        } else {
1231            epoch_store
1232                .protocol_config()
1233                .consensus_max_transactions_in_block_bytes()
1234        };
1235        fp_ensure!(
1236            total_size_bytes <= max_transaction_bytes as usize,
1237            SuiErrorKind::UserInputError {
1238                error: UserInputError::TotalTransactionSizeTooLargeInBatch {
1239                    size: total_size_bytes,
1240                    limit: max_transaction_bytes,
1241                },
1242            }
1243            .into()
1244        );
1245
1246        metrics
1247            .handle_submit_transaction_bytes
1248            .with_label_values(&[req_type])
1249            .observe(total_size_bytes as f64);
1250        metrics
1251            .handle_submit_transaction_batch_size
1252            .with_label_values(&[req_type])
1253            .observe(consensus_transactions.len() as f64);
1254
1255        let _latency_metric_guard = metrics
1256            .handle_submit_transaction_consensus_latency
1257            .with_label_values(&[req_type])
1258            .start_timer();
1259
1260        if is_soft_bundle_request {
1261            // We only allow the `consensus_transactions` to be empty for ping requests. This is how it should and is be treated from the downstream components.
1262            // For any other case, having an empty `consensus_transactions` vector is an invalid state and we should have never reached at this point.
1263            assert!(
1264                !consensus_transactions.is_empty(),
1265                "A valid soft bundle must have at least one transaction"
1266            );
1267        }
1268
1269        // Soft bundles are inserted as a single queue entry.
1270        // Individual transactions are each inserted separately.
1271        let tx_groups: Vec<Vec<ConsensusTransaction>> = if is_soft_bundle_request || is_ping_request
1272        {
1273            vec![consensus_transactions]
1274        } else {
1275            consensus_transactions
1276                .into_iter()
1277                .map(|t| vec![t])
1278                .collect()
1279        };
1280
1281        // Map each submission group back to the (result index, digest) of the transactions it
1282        // contains, so a per-group outcome — consensus positions, or an "already processing"
1283        // error — can be recorded against each individual transaction. Soft bundles submit as a
1284        // single group; individual transactions submit one group each.
1285        let group_tx_meta = if is_soft_bundle_request {
1286            vec![
1287                transaction_indexes
1288                    .into_iter()
1289                    .zip_eq(tx_digests)
1290                    .collect::<Vec<_>>(),
1291            ]
1292        } else {
1293            transaction_indexes
1294                .into_iter()
1295                .zip_eq(tx_digests)
1296                .map(|pair| vec![pair])
1297                .collect::<Vec<_>>()
1298        };
1299
1300        // Collect one result per submission group WITHOUT short-circuiting. An
1301        // already-processing transaction is reported per-tx as a retriable below;
1302        // any other error fails the whole request, after all groups have settled.
1303        // Soft bundles submit as a single group; individual transactions submit one group each.
1304        let group_results = match submit_mode {
1305            AdmissionQueueSubmitMode::Direct => {
1306                let futures = tx_groups.into_iter().map(|txns| {
1307                    debug!(
1308                        "handle_submit_transaction: submitting consensus transactions ({}): {}",
1309                        req_type,
1310                        txns.iter().map(|t| t.local_display()).join(", ")
1311                    );
1312                    self.consensus_adapter.submit_and_get_positions(
1313                        txns,
1314                        &epoch_store,
1315                        submitter_client_addr,
1316                    )
1317                });
1318                future::join_all(futures).await
1319            }
1320            AdmissionQueueSubmitMode::Queue => {
1321                let aq = self
1322                    .admission_queue
1323                    .as_ref()
1324                    .expect("Queue mode implies admission_queue is Some")
1325                    .load();
1326                let mut receivers = Vec::with_capacity(tx_groups.len());
1327                for txns in tx_groups {
1328                    let gas_price = Self::extract_gas_price(&txns);
1329                    let (rx, newly_inserted) = aq
1330                        .try_insert(gas_price, txns, submitter_client_addr)
1331                        .await?;
1332                    if !newly_inserted {
1333                        // Duplicate of an in-flight submission; flag the request as spam. The
1334                        // per-tx result is still Submitted, so this is tracked separately.
1335                        duplicate_at_admission = true;
1336                    }
1337                    receivers.push(rx);
1338                }
1339                future::join_all(receivers.into_iter().map(|rx| async move {
1340                    match rx.await {
1341                        Ok(result) => result.map_err(SuiError::from),
1342                        Err(_) => Err(SuiError::from(
1343                            SuiErrorKind::TooManyTransactionsPendingConsensus,
1344                        )),
1345                    }
1346                }))
1347                .await
1348            }
1349        };
1350
1351        if is_ping_request {
1352            // For ping requests there is a single group returning the special consensus position.
1353            let consensus_positions = group_results
1354                .into_iter()
1355                .next()
1356                .expect("Ping request must have exactly one submission group")?;
1357            assert_eq!(consensus_positions.len(), 1);
1358            results.push(Some(SubmitTxResult::Submitted {
1359                consensus_position: consensus_positions[0],
1360            }));
1361        } else {
1362            for (group_result, txns_meta) in group_results.into_iter().zip_debug_eq(group_tx_meta) {
1363                match group_result {
1364                    Ok(consensus_positions) => {
1365                        for ((idx, tx_digest), consensus_position) in
1366                            txns_meta.into_iter().zip_debug_eq(consensus_positions)
1367                        {
1368                            debug!(
1369                                ?tx_digest,
1370                                "handle_submit_transaction: submitted consensus transaction at {}",
1371                                consensus_position,
1372                            );
1373                            results[idx] = Some(SubmitTxResult::Submitted { consensus_position });
1374                        }
1375                    }
1376                    // The transaction(s) in this group are already being processed by consensus.
1377                    // Report per-tx as a retriable rejection rather than failing the whole request.
1378                    Err(err) => {
1379                        let SuiErrorKind::TransactionProcessing { status, .. } =
1380                            err.as_inner().clone()
1381                        else {
1382                            return Err(err);
1383                        };
1384                        // For TransactionProcessing error, ensure the per txn result has the correct digest.
1385                        for (idx, tx_digest) in txns_meta {
1386                            debug!(
1387                                ?tx_digest,
1388                                "handle_submit_transaction: transaction already processing: {err}"
1389                            );
1390                            // Same suppression the upfront `is_consensus_message_processed` check
1391                            // records, just detected during submission instead of before it. The
1392                            // two paths are mutually exclusive, so this does not double-count.
1393                            metrics
1394                                .submission_suppressed_already_processed
1395                                .with_label_values(&[req_type])
1396                                .inc();
1397                            results[idx] = Some(SubmitTxResult::Rejected {
1398                                error: SuiErrorKind::TransactionProcessing {
1399                                    digest: tx_digest,
1400                                    status: status.clone(),
1401                                }
1402                                .into(),
1403                            });
1404                        }
1405                    }
1406                }
1407            }
1408        }
1409
1410        let spam_weight = Self::request_spam_weight(
1411            &results,
1412            has_gasless,
1413            duplicate_at_admission,
1414            is_ping_request,
1415        );
1416        let response = Self::try_from_submit_tx_response(results)?;
1417        Ok((response, spam_weight))
1418    }
1419
1420    /// Traffic-control spam weight for a whole submit request. The request is spam unless it is
1421    /// entirely accepted gas-chargable work.
1422    fn request_spam_weight(
1423        results: &[Option<SubmitTxResult>],
1424        has_gasless: bool,
1425        duplicate_at_admission: bool,
1426        is_ping: bool,
1427    ) -> Weight {
1428        if is_ping || has_gasless || duplicate_at_admission {
1429            return Weight::one();
1430        }
1431        for result in results {
1432            let Some(result) = result else {
1433                // `results` is expected to be fully populated (every entry `Some`) for the
1434                // request's transactions; a missing entry is a bug and is conservatively
1435                // treated as spam.
1436                debug_fatal!("transaction outcome unset when computing spam weight");
1437                return Weight::one();
1438            };
1439            if Self::submission_spam_weight(result) == Weight::one() {
1440                return Weight::one();
1441            }
1442        }
1443        Weight::zero()
1444    }
1445
1446    fn submission_spam_weight(result: &SubmitTxResult) -> Weight {
1447        match result {
1448            SubmitTxResult::Submitted { .. } => Weight::zero(),
1449            // Non-submitted results can't be charged.
1450            SubmitTxResult::Executed { .. } | SubmitTxResult::Rejected { .. } => Weight::one(),
1451        }
1452    }
1453
1454    fn try_from_submit_tx_response(
1455        results: Vec<Option<SubmitTxResult>>,
1456    ) -> Result<RawSubmitTxResponse, SuiError> {
1457        let mut raw_results = Vec::new();
1458        for (i, result) in results.into_iter().enumerate() {
1459            let result = result.ok_or_else(|| SuiErrorKind::GenericAuthorityError {
1460                error: format!("Missing transaction result at {}", i),
1461            })?;
1462            let raw_result = result.try_into()?;
1463            raw_results.push(raw_result);
1464        }
1465        Ok(RawSubmitTxResponse {
1466            results: raw_results,
1467        })
1468    }
1469
1470    /// Extract the gas price from a batch of consensus transactions.
1471    /// Returns the minimum gas price in the batch, or 0 if no user transactions.
1472    fn extract_gas_price(transactions: &[ConsensusTransaction]) -> u64 {
1473        use sui_types::messages_consensus::ConsensusTransactionKind;
1474        transactions
1475            .iter()
1476            .filter_map(|tx| match &tx.kind {
1477                ConsensusTransactionKind::CertifiedTransaction(cert) => Some(cert.gas_price()),
1478                ConsensusTransactionKind::UserTransaction(t) => {
1479                    Some(t.data().transaction_data().gas_price())
1480                }
1481                ConsensusTransactionKind::UserTransactionV2(t) => {
1482                    Some(t.tx().data().transaction_data().gas_price())
1483                }
1484                _ => None,
1485            })
1486            .min()
1487            .unwrap_or(0)
1488    }
1489
1490    fn classify_submit_mode(&self, is_ping_request: bool) -> AdmissionQueueSubmitMode {
1491        let Some(aq) = &self.admission_queue else {
1492            return AdmissionQueueSubmitMode::Direct;
1493        };
1494
1495        // Ping requests carry no transactions and must not wait behind queued
1496        // work; submit them directly to consensus.
1497        if is_ping_request {
1498            return AdmissionQueueSubmitMode::Direct;
1499        }
1500
1501        // If the queue actor is stuck, fall back to direct submission with the
1502        // pre-queue saturation reject until it resumes making progress.
1503        if aq.load().failover_tripped() {
1504            return AdmissionQueueSubmitMode::Direct;
1505        }
1506
1507        AdmissionQueueSubmitMode::Queue
1508    }
1509
1510    async fn collect_effects_data(
1511        &self,
1512        effects: &TransactionEffects,
1513        include_events: bool,
1514        include_input_objects: bool,
1515        include_output_objects: bool,
1516    ) -> SuiResult<(Option<TransactionEvents>, Vec<Object>, Vec<Object>)> {
1517        let events = if include_events && effects.events_digest().is_some() {
1518            Some(
1519                self.state
1520                    .get_transaction_events(effects.transaction_digest())?,
1521            )
1522        } else {
1523            None
1524        };
1525
1526        let input_objects = if include_input_objects {
1527            self.state.get_transaction_input_objects(effects)?
1528        } else {
1529            vec![]
1530        };
1531
1532        let output_objects = if include_output_objects {
1533            self.state.get_transaction_output_objects(effects)?
1534        } else {
1535            vec![]
1536        };
1537
1538        Ok((events, input_objects, output_objects))
1539    }
1540}
1541
1542type WrappedServiceResponse<T> = Result<(tonic::Response<T>, Weight), tonic::Status>;
1543
1544/// RAII guard tracking the transaction digests a single submit request is actively handling, so
1545/// concurrent duplicates can be rejected. On drop, each acquired digest is removed from
1546/// the in-flight set and demoted into `recently_submitted` cache, so resubmissions
1547/// arriving shortly after the handler returns are still suppressed.
1548struct InflightTransactionsGuard {
1549    // Handle to inflight map and recently submitted cache.
1550    inflight: Arc<Mutex<HashSet<TransactionDigest>>>,
1551    recently_submitted: Cache<TransactionDigest, Instant>,
1552    window: Duration,
1553    metrics: Arc<ValidatorServiceMetrics>,
1554    /// Digests this request successfully acquired.
1555    acquired: HashSet<TransactionDigest>,
1556}
1557
1558enum AcquireOutcome {
1559    /// Transaction digest newly acquired by this request.
1560    Acquired,
1561    /// Transaction digest already acquired by this request before this internal retry attempt.
1562    AlreadyAcquiredByThisRequest,
1563    /// Transaction digest being handled by another concurrent request — reject this index.
1564    AlreadyAcquiredByAnotherRequest,
1565    /// Transaction digest recently processed — reject this index.
1566    RecentlyProcessed { since: Duration },
1567}
1568
1569impl InflightTransactionsGuard {
1570    fn new(service: &ValidatorService) -> Self {
1571        Self {
1572            inflight: service.inflight_transactions.clone(),
1573            recently_submitted: service.recently_submitted.clone(),
1574            window: service.recent_submission_window,
1575            metrics: service.metrics.clone(),
1576            acquired: HashSet::new(),
1577        }
1578    }
1579
1580    fn try_acquire(&mut self, digest: TransactionDigest) -> AcquireOutcome {
1581        // A retry of this own request re-acquires the same digests.
1582        if self.acquired.contains(&digest) {
1583            return AcquireOutcome::AlreadyAcquiredByThisRequest;
1584        }
1585
1586        // Suppress resubmissions of recently processed transactions.
1587        if let Some(outcome) = self.recently_processed_outcome(digest) {
1588            return outcome;
1589        }
1590
1591        // Atomic check-and-acquire against concurrent in-flight transactions.
1592        {
1593            let mut set = self.inflight.lock();
1594            // Only continue processing the transaction if it is not already inflight.
1595            if !set.insert(digest) {
1596                return AcquireOutcome::AlreadyAcquiredByAnotherRequest;
1597            }
1598            self.metrics.inflight_transactions.set(set.len() as i64);
1599        }
1600
1601        // Without this re-check, a duplicated transaction arriving between the first check and
1602        // the digest acquisition could slip through.
1603        if let Some(outcome) = self.recently_processed_outcome(digest) {
1604            let mut set = self.inflight.lock();
1605            set.remove(&digest);
1606            self.metrics.inflight_transactions.set(set.len() as i64);
1607            return outcome;
1608        }
1609
1610        self.acquired.insert(digest);
1611        AcquireOutcome::Acquired
1612    }
1613
1614    fn recently_processed_outcome(&self, digest: TransactionDigest) -> Option<AcquireOutcome> {
1615        let recorded_at = self.recently_submitted.get(&digest)?;
1616        let since = recorded_at.elapsed();
1617        (since < self.window).then_some(AcquireOutcome::RecentlyProcessed { since })
1618    }
1619}
1620
1621impl Drop for InflightTransactionsGuard {
1622    fn drop(&mut self) {
1623        if self.acquired.is_empty() {
1624            return;
1625        }
1626        // Demote inflight transactions to recently submitted cache before taking the in-flight lock,
1627        // to avoid cleaning up the cache with the lock.
1628        let now = Instant::now();
1629        for digest in &self.acquired {
1630            self.recently_submitted.insert(*digest, now);
1631        }
1632        {
1633            let mut set = self.inflight.lock();
1634            for digest in &self.acquired {
1635                set.remove(digest);
1636            }
1637            self.metrics.inflight_transactions.set(set.len() as i64);
1638        }
1639        self.metrics
1640            .recently_submitted_cache_size
1641            .set(self.recently_submitted.entry_count() as i64);
1642    }
1643}
1644
1645impl ValidatorService {
1646    async fn handle_submit_transaction_impl(
1647        &self,
1648        request: tonic::Request<RawSubmitTxRequest>,
1649    ) -> WrappedServiceResponse<RawSubmitTxResponse> {
1650        self.handle_submit_transaction(request).await
1651    }
1652
1653    async fn wait_for_effects_impl(
1654        &self,
1655        request: tonic::Request<RawWaitForEffectsRequest>,
1656    ) -> WrappedServiceResponse<RawWaitForEffectsResponse> {
1657        let request: WaitForEffectsRequest = request.into_inner().try_into()?;
1658        let epoch_store = self.state.load_epoch_store_one_call_per_task();
1659        let response = timeout(
1660            // TODO(fastpath): Tune this once we have a good estimate of the typical delay.
1661            Duration::from_secs(20),
1662            epoch_store
1663                .within_alive_epoch(self.wait_for_effects_response(request, &epoch_store))
1664                .map_err(|_| SuiErrorKind::EpochEnded(epoch_store.epoch())),
1665        )
1666        .await
1667        .map_err(|_| tonic::Status::internal("Timeout waiting for effects"))???
1668        .try_into()?;
1669        Ok((tonic::Response::new(response), Weight::zero()))
1670    }
1671
1672    #[instrument(name= "ValidatorService::wait_for_effects_response", level = "debug", skip_all, fields(consensus_position = ?request.consensus_position))]
1673    async fn wait_for_effects_response(
1674        &self,
1675        request: WaitForEffectsRequest,
1676        epoch_store: &Arc<AuthorityPerEpochStore>,
1677    ) -> SuiResult<WaitForEffectsResponse> {
1678        if request.ping_type.is_some() {
1679            return timeout(
1680                Duration::from_secs(10),
1681                self.ping_response(request, epoch_store),
1682            )
1683            .await
1684            .map_err(|_| SuiErrorKind::TimeoutError)?;
1685        }
1686
1687        let Some(tx_digest) = request.transaction_digest else {
1688            return Err(SuiErrorKind::InvalidRequest(
1689                "Transaction digest is required for wait for effects requests".to_string(),
1690            )
1691            .into());
1692        };
1693        let tx_digests = [tx_digest];
1694
1695        // When consensus_position is provided, also watch the consensus status cache
1696        // so rejected/dropped transactions get a timely response instead of waiting
1697        // forever for effects that will never be produced.
1698        let consensus_status_future = async {
1699            let consensus_position = match request.consensus_position {
1700                Some(pos) => pos,
1701                None => return futures::future::pending().await,
1702            };
1703            let consensus_tx_status_cache = &epoch_store.consensus_tx_status_cache;
1704            consensus_tx_status_cache.check_position_too_ahead(&consensus_position)?;
1705            match consensus_tx_status_cache
1706                .notify_read_transaction_status(consensus_position)
1707                .await
1708            {
1709                NotifyReadConsensusTxStatusResult::Status(
1710                    ConsensusTxStatus::Rejected | ConsensusTxStatus::Dropped,
1711                ) => Ok(WaitForEffectsResponse::Rejected {
1712                    error: epoch_store.get_rejection_vote_reason(consensus_position),
1713                }),
1714                NotifyReadConsensusTxStatusResult::Status(ConsensusTxStatus::Finalized) => {
1715                    // Effects will be produced — yield to let the effects future win.
1716                    futures::future::pending().await
1717                }
1718                NotifyReadConsensusTxStatusResult::Expired(round) => {
1719                    Ok(WaitForEffectsResponse::Expired {
1720                        epoch: epoch_store.epoch(),
1721                        round: Some(round),
1722                    })
1723                }
1724            }
1725        };
1726
1727        tokio::select! {
1728            effects_result = self.state
1729                .get_transaction_cache_reader()
1730                .notify_read_executed_effects_may_fail(
1731                    "AuthorityServer::wait_for_effects::notify_read_executed_effects_finalized",
1732                    &tx_digests,
1733                ) => {
1734                let effects = effects_result?.pop().unwrap();
1735                let effects_digest = effects.digest();
1736                let details = if request.include_details {
1737                    Some(self.complete_executed_data(effects).await?)
1738                } else {
1739                    None
1740                };
1741                Ok(WaitForEffectsResponse::Executed {
1742                    effects_digest,
1743                    details,
1744                })
1745            }
1746            status_response = consensus_status_future => {
1747                status_response
1748            }
1749        }
1750    }
1751
1752    #[instrument(level = "error", skip_all, err(level = "debug"))]
1753    async fn ping_response(
1754        &self,
1755        request: WaitForEffectsRequest,
1756        epoch_store: &Arc<AuthorityPerEpochStore>,
1757    ) -> SuiResult<WaitForEffectsResponse> {
1758        let consensus_tx_status_cache = &epoch_store.consensus_tx_status_cache;
1759
1760        let Some(consensus_position) = request.consensus_position else {
1761            return Err(SuiErrorKind::InvalidRequest(
1762                "Consensus position is required for Ping requests".to_string(),
1763            )
1764            .into());
1765        };
1766
1767        // We assume that the caller has already checked for the existence of the `ping` field, but handling it gracefully here.
1768        let Some(ping) = request.ping_type else {
1769            return Err(SuiErrorKind::InvalidRequest(
1770                "Ping type is required for ping requests".to_string(),
1771            )
1772            .into());
1773        };
1774
1775        let _metrics_guard = self
1776            .metrics
1777            .handle_wait_for_effects_ping_latency
1778            .with_label_values(&[ping.as_str()])
1779            .start_timer();
1780
1781        consensus_tx_status_cache.check_position_too_ahead(&consensus_position)?;
1782
1783        let details = if request.include_details {
1784            Some(Box::new(ExecutedData::default()))
1785        } else {
1786            None
1787        };
1788
1789        let status = consensus_tx_status_cache
1790            .notify_read_transaction_status(consensus_position)
1791            .await;
1792        match status {
1793            NotifyReadConsensusTxStatusResult::Status(status) => match status {
1794                ConsensusTxStatus::Rejected | ConsensusTxStatus::Dropped => {
1795                    Ok(WaitForEffectsResponse::Rejected {
1796                        error: epoch_store.get_rejection_vote_reason(consensus_position),
1797                    })
1798                }
1799                ConsensusTxStatus::Finalized => Ok(WaitForEffectsResponse::Executed {
1800                    effects_digest: TransactionEffectsDigest::ZERO,
1801                    details,
1802                }),
1803            },
1804            NotifyReadConsensusTxStatusResult::Expired(round) => {
1805                Ok(WaitForEffectsResponse::Expired {
1806                    epoch: epoch_store.epoch(),
1807                    round: Some(round),
1808                })
1809            }
1810        }
1811    }
1812
1813    async fn complete_executed_data(
1814        &self,
1815        effects: TransactionEffects,
1816    ) -> SuiResult<Box<ExecutedData>> {
1817        let (events, input_objects, output_objects) = self
1818            .collect_effects_data(
1819                &effects, /* include_events */ true, /* include_input_objects */ true,
1820                /* include_output_objects */ true,
1821            )
1822            .await?;
1823        Ok(Box::new(ExecutedData {
1824            effects,
1825            events,
1826            input_objects,
1827            output_objects,
1828        }))
1829    }
1830
1831    async fn object_info_impl(
1832        &self,
1833        request: tonic::Request<ObjectInfoRequest>,
1834    ) -> WrappedServiceResponse<ObjectInfoResponse> {
1835        let request = request.into_inner();
1836        let response = self.state.handle_object_info_request(request).await?;
1837        Ok((tonic::Response::new(response), Weight::one()))
1838    }
1839
1840    async fn transaction_info_impl(
1841        &self,
1842        request: tonic::Request<TransactionInfoRequest>,
1843    ) -> WrappedServiceResponse<TransactionInfoResponse> {
1844        let request = request.into_inner();
1845        let response = self.state.handle_transaction_info_request(request).await?;
1846        Ok((tonic::Response::new(response), Weight::one()))
1847    }
1848
1849    async fn checkpoint_impl(
1850        &self,
1851        request: tonic::Request<CheckpointRequest>,
1852    ) -> WrappedServiceResponse<CheckpointResponse> {
1853        let request = request.into_inner();
1854        let response = self.state.handle_checkpoint_request(&request)?;
1855        Ok((tonic::Response::new(response), Weight::one()))
1856    }
1857
1858    async fn checkpoint_v2_impl(
1859        &self,
1860        request: tonic::Request<CheckpointRequestV2>,
1861    ) -> WrappedServiceResponse<CheckpointResponseV2> {
1862        let request = request.into_inner();
1863        let response = self.state.handle_checkpoint_request_v2(&request)?;
1864        Ok((tonic::Response::new(response), Weight::one()))
1865    }
1866
1867    async fn get_system_state_object_impl(
1868        &self,
1869        _request: tonic::Request<SystemStateRequest>,
1870    ) -> WrappedServiceResponse<SuiSystemState> {
1871        let response = self
1872            .state
1873            .get_object_cache_reader()
1874            .get_sui_system_state_object_unsafe()?;
1875        Ok((tonic::Response::new(response), Weight::one()))
1876    }
1877
1878    async fn validator_health_impl(
1879        &self,
1880        _request: tonic::Request<sui_types::messages_grpc::RawValidatorHealthRequest>,
1881    ) -> WrappedServiceResponse<sui_types::messages_grpc::RawValidatorHealthResponse> {
1882        let state = &self.state;
1883
1884        // Get epoch store once for both metrics
1885        let epoch_store = state.load_epoch_store_one_call_per_task();
1886
1887        // Get in-flight execution transactions from execution scheduler
1888        let num_inflight_execution_transactions =
1889            state.execution_scheduler().num_pending_certificates() as u64;
1890
1891        // Get in-flight consensus transactions from consensus adapter
1892        let num_inflight_consensus_transactions =
1893            self.consensus_adapter.num_inflight_transactions();
1894
1895        // Get last committed leader round from epoch store
1896        let last_committed_leader_round = epoch_store
1897            .consensus_tx_status_cache
1898            .get_last_committed_leader_round()
1899            .unwrap_or(0);
1900
1901        // Get last locally built checkpoint sequence
1902        let last_locally_built_checkpoint = epoch_store
1903            .last_built_checkpoint_summary()
1904            .ok()
1905            .flatten()
1906            .map(|(_, summary)| summary.sequence_number)
1907            .unwrap_or(0);
1908
1909        let typed_response = sui_types::messages_grpc::ValidatorHealthResponse {
1910            num_inflight_consensus_transactions,
1911            num_inflight_execution_transactions,
1912            last_locally_built_checkpoint,
1913            last_committed_leader_round,
1914        };
1915
1916        let raw_response = typed_response
1917            .try_into()
1918            .map_err(|e: sui_types::error::SuiError| {
1919                tonic::Status::internal(format!("Failed to serialize health response: {}", e))
1920            })?;
1921
1922        Ok((tonic::Response::new(raw_response), Weight::one()))
1923    }
1924
1925    fn get_client_ip_addr<T>(
1926        &self,
1927        request: &tonic::Request<T>,
1928        source: &ClientIdSource,
1929    ) -> Option<IpAddr> {
1930        let forwarded_header = request.metadata().get_all("x-forwarded-for").iter().next();
1931
1932        if let Some(header) = forwarded_header {
1933            let num_hops = header
1934                .to_str()
1935                .map(|h| h.split(',').count().saturating_sub(1))
1936                .unwrap_or(0);
1937
1938            self.metrics.x_forwarded_for_num_hops.set(num_hops as f64);
1939        }
1940
1941        match source {
1942            ClientIdSource::SocketAddr => {
1943                let socket_addr: Option<SocketAddr> = request.remote_addr();
1944
1945                // We will hit this case if the IO type used does not
1946                // implement Connected or when using a unix domain socket.
1947                // TODO: once we have confirmed that no legitimate traffic
1948                // is hitting this case, we should reject such requests that
1949                // hit this case.
1950                if let Some(socket_addr) = socket_addr {
1951                    Some(socket_addr.ip())
1952                } else {
1953                    if cfg!(msim) {
1954                        // Ignore the error from simtests.
1955                    } else if cfg!(test) {
1956                        panic!("Failed to get remote address from request");
1957                    } else {
1958                        self.metrics.connection_ip_not_found.inc();
1959                        error!("Failed to get remote address from request");
1960                    }
1961                    None
1962                }
1963            }
1964            ClientIdSource::XForwardedFor(num_hops) => {
1965                let do_header_parse = |op: &MetadataValue<Ascii>| {
1966                    match op.to_str() {
1967                        Ok(header_val) => {
1968                            let header_contents =
1969                                header_val.split(',').map(str::trim).collect::<Vec<_>>();
1970                            if *num_hops == 0 {
1971                                error!(
1972                                    "x-forwarded-for: 0 specified. x-forwarded-for contents: {:?}. Please assign nonzero value for \
1973                                    number of hops here, or use `socket-addr` client-id-source type if requests are not being proxied \
1974                                    to this node. Skipping traffic controller request handling.",
1975                                    header_contents,
1976                                );
1977                                return None;
1978                            }
1979                            let contents_len = header_contents.len();
1980                            if contents_len < *num_hops {
1981                                error!(
1982                                    "x-forwarded-for header value of {:?} contains {} values, but {} hops were specified. \
1983                                    Expected at least {} values. Please correctly set the `x-forwarded-for` value under \
1984                                    `client-id-source` in the node config.",
1985                                    header_contents, contents_len, num_hops, contents_len,
1986                                );
1987                                self.metrics.client_id_source_config_mismatch.inc();
1988                                return None;
1989                            }
1990                            let Some(client_ip) = header_contents.get(contents_len - num_hops)
1991                            else {
1992                                error!(
1993                                    "x-forwarded-for header value of {:?} contains {} values, but {} hops were specified. \
1994                                    Expected at least {} values. Skipping traffic controller request handling.",
1995                                    header_contents, contents_len, num_hops, contents_len,
1996                                );
1997                                return None;
1998                            };
1999                            parse_ip(client_ip).or_else(|| {
2000                                self.metrics.forwarded_header_parse_error.inc();
2001                                None
2002                            })
2003                        }
2004                        Err(e) => {
2005                            // TODO: once we have confirmed that no legitimate traffic
2006                            // is hitting this case, we should reject such requests that
2007                            // hit this case.
2008                            self.metrics.forwarded_header_invalid.inc();
2009                            error!("Invalid UTF-8 in x-forwarded-for header: {:?}", e);
2010                            None
2011                        }
2012                    }
2013                };
2014                if let Some(op) = request.metadata().get("x-forwarded-for") {
2015                    do_header_parse(op)
2016                } else if let Some(op) = request.metadata().get("X-Forwarded-For") {
2017                    do_header_parse(op)
2018                } else {
2019                    self.metrics.forwarded_header_not_included.inc();
2020                    error!(
2021                        "x-forwarded-for header not present for request despite node configuring x-forwarded-for tracking type"
2022                    );
2023                    None
2024                }
2025            }
2026        }
2027    }
2028
2029    async fn handle_traffic_req(&self, client: Option<IpAddr>) -> Result<(), tonic::Status> {
2030        if let Some(traffic_controller) = &self.traffic_controller {
2031            if !traffic_controller.check(&client, &None).await {
2032                // Entity in blocklist
2033                Err(tonic::Status::from_error(
2034                    SuiErrorKind::TooManyRequests.into(),
2035                ))
2036            } else {
2037                Ok(())
2038            }
2039        } else {
2040            Ok(())
2041        }
2042    }
2043
2044    fn handle_traffic_resp<T>(
2045        &self,
2046        client: Option<IpAddr>,
2047        wrapped_response: WrappedServiceResponse<T>,
2048        method_name: &str,
2049    ) -> Result<tonic::Response<T>, tonic::Status> {
2050        let (error, spam_weight, unwrapped_response) = match wrapped_response {
2051            Ok((result, spam_weight)) => (None, spam_weight.clone(), Ok(result)),
2052            Err(status) => (
2053                Some(SuiError::from(status.clone())),
2054                Weight::zero(),
2055                Err(status.clone()),
2056            ),
2057        };
2058
2059        if let Some(traffic_controller) = self.traffic_controller.clone() {
2060            traffic_controller.tally(TrafficTally {
2061                direct: client,
2062                through_fullnode: None,
2063                error_info: error.map(|e| {
2064                    let error_type = String::from(e.clone().as_ref());
2065                    let error_weight = normalize(e);
2066                    (error_weight, error_type)
2067                }),
2068                spam_weight,
2069                timestamp: SystemTime::now(),
2070                method: Some(method_name.to_string()),
2071            })
2072        }
2073        unwrapped_response
2074    }
2075}
2076
2077// TODO: refine error matching here
2078fn normalize(err: SuiError) -> Weight {
2079    match err.as_inner() {
2080        SuiErrorKind::UserInputError {
2081            error: UserInputError::IncorrectUserSignature { .. },
2082        } => Weight::one(),
2083        SuiErrorKind::InvalidSignature { .. }
2084        | SuiErrorKind::SignerSignatureAbsent { .. }
2085        | SuiErrorKind::SignerSignatureNumberMismatch { .. }
2086        | SuiErrorKind::IncorrectSigner { .. }
2087        | SuiErrorKind::UnknownSigner { .. }
2088        | SuiErrorKind::WrongEpoch { .. } => Weight::one(),
2089        _ => Weight::zero(),
2090    }
2091}
2092
2093/// Implements generic pre- and post-processing. Since this is on the critical
2094/// path, any heavy lifting should be done in a separate non-blocking task
2095/// unless it is necessary to override the return value.
2096#[macro_export]
2097macro_rules! handle_with_decoration {
2098    ($self:ident, $func_name:ident, $request:ident, $method_name:expr) => {{
2099        if $self.client_id_source.is_none() {
2100            return $self.$func_name($request).await.map(|(result, _)| result);
2101        }
2102
2103        let client = $self.get_client_ip_addr(&$request, $self.client_id_source.as_ref().unwrap());
2104
2105        // check if either IP is blocked, in which case return early
2106        $self.handle_traffic_req(client.clone()).await?;
2107
2108        // handle traffic tallying
2109        let wrapped_response = $self.$func_name($request).await;
2110        $self.handle_traffic_resp(client, wrapped_response, $method_name)
2111    }};
2112}
2113
2114#[async_trait]
2115impl Validator for ValidatorService {
2116    async fn submit_transaction(
2117        &self,
2118        request: tonic::Request<RawSubmitTxRequest>,
2119    ) -> Result<tonic::Response<RawSubmitTxResponse>, tonic::Status> {
2120        let validator_service = self.clone();
2121
2122        // Spawns a task which handles the transaction. The task will unconditionally continue
2123        // processing in the event that the client connection is dropped.
2124        spawn_monitored_task!(async move {
2125            // NB: traffic tally wrapping handled within the task rather than on task exit
2126            // to prevent an attacker from subverting traffic control by severing the connection
2127            handle_with_decoration!(
2128                validator_service,
2129                handle_submit_transaction_impl,
2130                request,
2131                "submit_transaction"
2132            )
2133        })
2134        .await
2135        .unwrap()
2136    }
2137
2138    async fn wait_for_effects(
2139        &self,
2140        request: tonic::Request<RawWaitForEffectsRequest>,
2141    ) -> Result<tonic::Response<RawWaitForEffectsResponse>, tonic::Status> {
2142        handle_with_decoration!(self, wait_for_effects_impl, request, "wait_for_effects")
2143    }
2144
2145    async fn object_info(
2146        &self,
2147        request: tonic::Request<ObjectInfoRequest>,
2148    ) -> Result<tonic::Response<ObjectInfoResponse>, tonic::Status> {
2149        handle_with_decoration!(self, object_info_impl, request, "object_info")
2150    }
2151
2152    async fn transaction_info(
2153        &self,
2154        request: tonic::Request<TransactionInfoRequest>,
2155    ) -> Result<tonic::Response<TransactionInfoResponse>, tonic::Status> {
2156        handle_with_decoration!(self, transaction_info_impl, request, "transaction_info")
2157    }
2158
2159    async fn checkpoint(
2160        &self,
2161        request: tonic::Request<CheckpointRequest>,
2162    ) -> Result<tonic::Response<CheckpointResponse>, tonic::Status> {
2163        handle_with_decoration!(self, checkpoint_impl, request, "checkpoint")
2164    }
2165
2166    async fn checkpoint_v2(
2167        &self,
2168        request: tonic::Request<CheckpointRequestV2>,
2169    ) -> Result<tonic::Response<CheckpointResponseV2>, tonic::Status> {
2170        handle_with_decoration!(self, checkpoint_v2_impl, request, "checkpoint_v2")
2171    }
2172
2173    async fn get_system_state_object(
2174        &self,
2175        request: tonic::Request<SystemStateRequest>,
2176    ) -> Result<tonic::Response<SuiSystemState>, tonic::Status> {
2177        handle_with_decoration!(
2178            self,
2179            get_system_state_object_impl,
2180            request,
2181            "get_system_state_object"
2182        )
2183    }
2184
2185    async fn validator_health(
2186        &self,
2187        request: tonic::Request<sui_types::messages_grpc::RawValidatorHealthRequest>,
2188    ) -> Result<tonic::Response<sui_types::messages_grpc::RawValidatorHealthResponse>, tonic::Status>
2189    {
2190        handle_with_decoration!(self, validator_health_impl, request, "validator_health")
2191    }
2192}
2193
2194#[cfg(test)]
2195mod inflight_guard_tests {
2196    use super::*;
2197    use prometheus::Registry;
2198
2199    fn make_guard(
2200        inflight: Arc<Mutex<HashSet<TransactionDigest>>>,
2201        cache: Cache<TransactionDigest, Instant>,
2202        metrics: Arc<ValidatorServiceMetrics>,
2203    ) -> InflightTransactionsGuard {
2204        InflightTransactionsGuard {
2205            inflight,
2206            recently_submitted: cache,
2207            window: Duration::from_secs(10),
2208            metrics,
2209            acquired: HashSet::new(),
2210        }
2211    }
2212
2213    #[test]
2214    fn concurrent_acquire_rejects_other_request_and_is_idempotent_for_owner() {
2215        let inflight = Arc::new(Mutex::new(HashSet::new()));
2216        let cache = ValidatorService::new_recently_submitted_cache(Duration::from_secs(10));
2217        let metrics = Arc::new(ValidatorServiceMetrics::new(&Registry::new()));
2218        let digest = TransactionDigest::random();
2219
2220        let mut g1 = make_guard(inflight.clone(), cache.clone(), metrics.clone());
2221        let mut g2 = make_guard(inflight.clone(), cache.clone(), metrics.clone());
2222
2223        // First handler acquires it.
2224        assert!(matches!(g1.try_acquire(digest), AcquireOutcome::Acquired));
2225        assert_eq!(metrics.inflight_transactions.get(), 1);
2226
2227        // A concurrent handler sees another in-flight owner and is rejected.
2228        assert!(matches!(
2229            g2.try_acquire(digest),
2230            AcquireOutcome::AlreadyAcquiredByAnotherRequest
2231        ));
2232
2233        // The owning handler re-acquiring (epoch-end retry) is NOT a duplicate.
2234        assert!(matches!(
2235            g1.try_acquire(digest),
2236            AcquireOutcome::AlreadyAcquiredByThisRequest
2237        ));
2238    }
2239
2240    #[test]
2241    fn drop_demotes_into_recently_processed_outcome() {
2242        let inflight = Arc::new(Mutex::new(HashSet::new()));
2243        let cache = ValidatorService::new_recently_submitted_cache(Duration::from_secs(10));
2244        let metrics = Arc::new(ValidatorServiceMetrics::new(&Registry::new()));
2245        let digest = TransactionDigest::random();
2246
2247        {
2248            let mut g = make_guard(inflight.clone(), cache.clone(), metrics.clone());
2249            assert!(matches!(g.try_acquire(digest), AcquireOutcome::Acquired));
2250            assert_eq!(inflight.lock().len(), 1);
2251        } // guard dropped here -> remove from set + demote to TTL cache
2252
2253        assert_eq!(
2254            inflight.lock().len(),
2255            0,
2256            "acquired digest must be removed from the in-flight set on drop"
2257        );
2258        assert_eq!(metrics.inflight_transactions.get(), 0);
2259
2260        // Make moka's read view deterministic before asserting the demoted entry.
2261        cache.run_pending_tasks();
2262
2263        // A fresh request now sees the digest as recently processed (tail window).
2264        let mut g_after = make_guard(inflight.clone(), cache.clone(), metrics.clone());
2265        assert!(matches!(
2266            g_after.try_acquire(digest),
2267            AcquireOutcome::RecentlyProcessed { .. }
2268        ));
2269    }
2270}