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