Skip to main content

reth_rpc_eth_api/helpers/
state.rs

1//! Loads a pending block from database. Helper trait for `eth_` block, transaction, call and trace
2//! RPC methods.
3
4use super::{
5    pending_block::PendingStateSource, EthApiSpec, LoadBlock, LoadPendingBlock, SpawnBlocking,
6};
7use crate::{EthApiTypes, FromEthApiError, RpcNodeCore, RpcNodeCoreExt};
8use alloy_consensus::{constants::KECCAK_EMPTY, BlockHeader};
9use alloy_eips::BlockId;
10use alloy_primitives::{keccak256, Address, Bytes, B256, U256};
11use alloy_rpc_types_eth::{Account, AccountInfo, EIP1186AccountProofResponse};
12use alloy_serde::JsonStorageKey;
13use futures::Future;
14use reth_errors::RethError;
15use reth_evm::{ConfigureEvm, EvmEnvFor};
16use reth_primitives_traits::{BlockTy, RecoveredBlock, SealedHeaderFor};
17use reth_rpc_convert::{RpcConvert, RpcTxReq};
18use reth_rpc_eth_types::{
19    error::{FromEvmError, IntoEthApiError},
20    EthApiError, PendingBlockEnv, RpcInvalidTransactionError, SignError,
21};
22use reth_rpc_server_types::constants::{DEFAULT_MAX_PROOF_SLOTS, DEFAULT_MAX_STORAGE_VALUES_SLOTS};
23use reth_storage_api::{
24    BlockIdReader, BlockReaderIdExt, StateProvider, StateProviderBox, StateProviderFactory,
25};
26use reth_transaction_pool::TransactionPool;
27use reth_trie_common::{MultiProofTargetsV2, ProofV2Target};
28use std::{collections::HashMap, sync::Arc};
29
30/// Helper methods for `eth_` methods relating to state (accounts).
31pub trait EthState: LoadState + SpawnBlocking {
32    /// Returns the maximum number of blocks into the past for generating state proofs.
33    fn max_proof_window(&self) -> u64 {
34        self.eth_api_settings().eth_proof_window
35    }
36
37    /// Validates that the given block is within the configured proof window.
38    ///
39    /// Returns an error if the distance between the chain tip and the requested block exceeds
40    /// [`Self::max_proof_window`].
41    fn ensure_within_proof_window(&self, block_id: BlockId) -> Result<(), Self::Error>
42    where
43        Self: EthApiSpec,
44    {
45        let chain_info = self.chain_info().map_err(Self::Error::from_eth_err)?;
46        let block_number = self
47            .provider()
48            .block_number_for_id(block_id)
49            .map_err(Self::Error::from_eth_err)?
50            .ok_or(EthApiError::HeaderNotFound(block_id))?;
51        if chain_info.best_number.saturating_sub(block_number) > self.max_proof_window() {
52            return Err(EthApiError::ExceedsMaxProofWindow.into())
53        }
54        Ok(())
55    }
56
57    /// Returns the number of transactions sent from an address at the given block identifier.
58    ///
59    /// If this is [`BlockNumberOrTag::Pending`](alloy_eips::BlockNumberOrTag) then this will
60    /// look up the highest transaction in pool and return the next nonce (highest + 1).
61    fn transaction_count(
62        &self,
63        address: Address,
64        block_id: Option<BlockId>,
65    ) -> impl Future<Output = Result<U256, Self::Error>> + Send {
66        LoadState::transaction_count(self, address, block_id)
67    }
68
69    /// Returns code of given account, at given blocknumber.
70    fn get_code(
71        &self,
72        address: Address,
73        block_id: Option<BlockId>,
74    ) -> impl Future<Output = Result<Bytes, Self::Error>> + Send {
75        LoadState::get_code(self, address, block_id)
76    }
77
78    /// Returns balance of given account, at given blocknumber.
79    fn balance(
80        &self,
81        address: Address,
82        block_id: Option<BlockId>,
83    ) -> impl Future<Output = Result<U256, Self::Error>> + Send {
84        self.spawn_blocking_io_with_state(block_id.unwrap_or_default(), move |_, state| {
85            Ok(state
86                .account_balance(&address)
87                .map_err(Self::Error::from_eth_err)?
88                .unwrap_or_default())
89        })
90    }
91
92    /// Returns values stored of given account, at given blocknumber.
93    fn storage_at(
94        &self,
95        address: Address,
96        index: JsonStorageKey,
97        block_id: Option<BlockId>,
98    ) -> impl Future<Output = Result<B256, Self::Error>> + Send {
99        self.spawn_blocking_io_with_state(block_id.unwrap_or_default(), move |_, state| {
100            Ok(B256::from(
101                state
102                    .storage(address, index.as_b256())
103                    .map_err(Self::Error::from_eth_err)?
104                    .unwrap_or_default(),
105            ))
106        })
107    }
108
109    /// Returns values from multiple storage positions across multiple addresses.
110    ///
111    /// Enforces a cap on total slot count (sum of all slot arrays) and returns an error if
112    /// exceeded.
113    fn storage_values(
114        &self,
115        requests: HashMap<Address, Vec<JsonStorageKey>>,
116        block_id: Option<BlockId>,
117    ) -> impl Future<Output = Result<HashMap<Address, Vec<B256>>, Self::Error>> + Send {
118        async move {
119            if requests.is_empty() {
120                return Err(Self::Error::from_eth_err(EthApiError::InvalidParams(
121                    "empty request".to_string(),
122                )));
123            }
124            let total_slots: usize = requests.values().map(|slots| slots.len()).sum();
125            if total_slots > DEFAULT_MAX_STORAGE_VALUES_SLOTS {
126                return Err(Self::Error::from_eth_err(EthApiError::InvalidParams(
127                    format!(
128                        "total slot count {total_slots} exceeds limit {DEFAULT_MAX_STORAGE_VALUES_SLOTS}",
129                    ),
130                )));
131            }
132
133            self.spawn_blocking_io_with_state(block_id.unwrap_or_default(), move |_, state| {
134                let mut result = HashMap::with_capacity(requests.len());
135                for (address, slots) in requests {
136                    let mut values = Vec::with_capacity(slots.len());
137                    for slot in &slots {
138                        let value = state
139                            .storage(address, slot.as_b256())
140                            .map_err(Self::Error::from_eth_err)?
141                            .unwrap_or_default();
142                        values.push(B256::from(value));
143                    }
144                    result.insert(address, values);
145                }
146
147                Ok(result)
148            })
149            .await
150        }
151    }
152
153    /// Returns values stored of given account, with Merkle-proof, at given blocknumber.
154    ///
155    /// Enforces a cap of [`DEFAULT_MAX_PROOF_SLOTS`] on the number of requested keys, before a
156    /// proof permit is acquired.
157    fn get_proof(
158        &self,
159        address: Address,
160        keys: Vec<JsonStorageKey>,
161        block_id: Option<BlockId>,
162    ) -> Result<
163        impl Future<Output = Result<EIP1186AccountProofResponse, Self::Error>> + Send,
164        Self::Error,
165    >
166    where
167        Self: EthApiSpec,
168    {
169        if keys.len() > DEFAULT_MAX_PROOF_SLOTS {
170            return Err(Self::Error::from_eth_err(EthApiError::InvalidParams(format!(
171                "storage key count {} exceeds limit {DEFAULT_MAX_PROOF_SLOTS}",
172                keys.len(),
173            ))));
174        }
175
176        Ok(async move {
177            let permit = self
178                .acquire_owned_tracing()
179                .await
180                .map_err(RethError::other)
181                .map_err(EthApiError::Internal)?;
182
183            let block_id = block_id.unwrap_or_default();
184            self.ensure_within_proof_window(block_id)?;
185
186            self.spawn_blocking_io_with_state(block_id, move |_, state| {
187                let _permit = permit;
188                let storage_keys = keys.iter().map(|key| key.as_b256()).collect::<Vec<_>>();
189                let proof =
190                    state.proof(address, &storage_keys).map_err(Self::Error::from_eth_err)?;
191                Ok(proof.into_eip1186_response_with(keys, true))
192            })
193            .await
194        })
195    }
196
197    /// Returns account and storage proofs for multiple targets at the given block number.
198    ///
199    /// Enforces a cap of [`DEFAULT_MAX_PROOF_SLOTS`] on both the number of targets and the total
200    /// slot count across all targets, before a proof permit is acquired.
201    fn get_multi_proof(
202        &self,
203        targets: Vec<(Address, Vec<B256>)>,
204        block_id: Option<BlockId>,
205    ) -> Result<
206        impl Future<Output = Result<Vec<EIP1186AccountProofResponse>, Self::Error>> + Send,
207        Self::Error,
208    >
209    where
210        Self: EthApiSpec,
211    {
212        if targets.len() > DEFAULT_MAX_PROOF_SLOTS {
213            return Err(Self::Error::from_eth_err(EthApiError::InvalidParams(format!(
214                "target count {} exceeds limit {DEFAULT_MAX_PROOF_SLOTS}",
215                targets.len(),
216            ))));
217        }
218        let total_slots: usize = targets.iter().map(|(_, slots)| slots.len()).sum();
219        if total_slots > DEFAULT_MAX_PROOF_SLOTS {
220            return Err(Self::Error::from_eth_err(EthApiError::InvalidParams(format!(
221                "total slot count {total_slots} exceeds limit {DEFAULT_MAX_PROOF_SLOTS}",
222            ))));
223        }
224
225        Ok(async move {
226            let permit = self
227                .acquire_owned_tracing()
228                .await
229                .map_err(RethError::other)
230                .map_err(EthApiError::Internal)?;
231
232            let block_id = block_id.unwrap_or_default();
233            self.ensure_within_proof_window(block_id)?;
234
235            self.spawn_blocking_io_with_state(block_id, move |_, state| {
236                let _permit = permit;
237                let mut proof_targets = MultiProofTargetsV2::default();
238                proof_targets.account_targets.reserve(targets.len());
239                proof_targets.storage_targets.reserve(targets.len());
240                for (address, slots) in &targets {
241                    let hashed_address = keccak256(address);
242                    proof_targets.account_targets.push(ProofV2Target::new(hashed_address));
243                    if !slots.is_empty() {
244                        proof_targets
245                            .storage_targets
246                            .entry(hashed_address)
247                            .or_default()
248                            .extend(slots.iter().map(|slot| ProofV2Target::new(keccak256(slot))));
249                    }
250                }
251
252                let multiproof =
253                    state.multiproof_v2(proof_targets, false).map_err(Self::Error::from_eth_err)?;
254
255                targets
256                    .into_iter()
257                    .map(|(address, slots)| {
258                        let proof = multiproof
259                            .account_proof(address, &slots)
260                            .map_err(RethError::other)
261                            .map_err(Self::Error::from_eth_err)?;
262                        let storage_keys =
263                            slots.into_iter().map(JsonStorageKey::from).collect::<Vec<_>>();
264                        Ok(proof.into_eip1186_response_with(storage_keys, true))
265                    })
266                    .collect::<Result<Vec<_>, Self::Error>>()
267            })
268            .await
269        })
270    }
271
272    /// Returns the account at the given address for the provided block identifier.
273    fn get_account(
274        &self,
275        address: Address,
276        block_id: BlockId,
277    ) -> impl Future<Output = Result<Option<Account>, Self::Error>> + Send
278    where
279        Self: EthApiSpec,
280    {
281        async move {
282            self.ensure_within_proof_window(block_id)?;
283
284            self.spawn_blocking_io_with_state(block_id, move |_, state| {
285                let account = state.basic_account(&address).map_err(Self::Error::from_eth_err)?;
286                let Some(account) = account else { return Ok(None) };
287
288                // Provide a default `HashedStorage` value in order to
289                // get the storage root hash of the current state.
290                let storage_root = state
291                    .storage_root(address, Default::default())
292                    .map_err(Self::Error::from_eth_err)?;
293
294                Ok(Some(account.into_trie_account(storage_root)))
295            })
296            .await
297        }
298    }
299
300    /// Retrieves the account's balance, nonce, and code for a given address.
301    #[allow(clippy::needless_update)]
302    fn get_account_info(
303        &self,
304        address: Address,
305        block_id: BlockId,
306    ) -> impl Future<Output = Result<AccountInfo, Self::Error>> + Send {
307        self.spawn_blocking_io_with_state(block_id, move |_, state| {
308            let account = state
309                .basic_account(&address)
310                .map_err(Self::Error::from_eth_err)?
311                .unwrap_or_default();
312
313            let balance = account.balance;
314            let nonce = account.nonce;
315            let code = if account.get_bytecode_hash() == KECCAK_EMPTY {
316                Default::default()
317            } else {
318                state
319                    .account_code(&address)
320                    .map_err(Self::Error::from_eth_err)?
321                    .unwrap_or_default()
322                    .original_bytes()
323            };
324
325            Ok(AccountInfo {
326                balance,
327                nonce,
328                code,
329                #[cfg(feature = "account-ext")]
330                extension: account.extension,
331                ..Default::default()
332            })
333        })
334    }
335}
336
337/// Loads state from database.
338///
339/// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` state RPC methods.
340pub trait LoadState:
341    LoadPendingBlock
342    + EthApiTypes<
343        Error: FromEvmError<Self::Evm> + FromEthApiError,
344        RpcConvert: RpcConvert<Network = Self::NetworkTypes>,
345    > + RpcNodeCoreExt
346{
347    /// Returns the state at the given block number
348    fn state_at_hash(&self, block_hash: B256) -> Result<StateProviderBox, Self::Error> {
349        self.provider().history_by_block_hash(block_hash).map_err(Self::Error::from_eth_err)
350    }
351
352    /// Returns the state at the given [`BlockId`], preferring locally built state for `pending`.
353    ///
354    /// If local pending state is unavailable or fails to build, falls back to the provider's
355    /// pending state. Other block IDs resolve only canonical state. See
356    /// <https://github.com/paradigmxyz/reth/issues/4515>.
357    ///
358    /// Pending block construction may spawn blocking work, so await this outside a blocking task.
359    /// The fallback provider lookup is synchronous on the calling task; RPC handlers should use
360    /// [`Self::spawn_blocking_io_with_state`] to keep that read on the blocking pool.
361    fn state_at_block_id(
362        &self,
363        at: BlockId,
364    ) -> impl Future<Output = Result<StateProviderBox, Self::Error>> + Send
365    where
366        Self: SpawnBlocking,
367    {
368        async move {
369            if at.is_pending() &&
370                let Ok(Some(state)) = self.local_pending_state().await
371            {
372                return Ok(state)
373            }
374
375            self.provider().state_by_block_id(at).map_err(Self::Error::from_eth_err)
376        }
377    }
378
379    /// Returns the _latest_ state
380    fn latest_state(&self) -> Result<StateProviderBox, Self::Error> {
381        self.provider().latest().map_err(Self::Error::from_eth_err)
382    }
383
384    /// Returns the state at the given [`BlockId`] enum or the latest.
385    ///
386    /// Convenience function to interprets `None` as `BlockId::Number(BlockNumberOrTag::Latest)`
387    fn state_at_block_id_or_latest(
388        &self,
389        block_id: Option<BlockId>,
390    ) -> impl Future<Output = Result<StateProviderBox, Self::Error>> + Send
391    where
392        Self: SpawnBlocking,
393    {
394        async move {
395            if let Some(block_id) = block_id {
396                self.state_at_block_id(block_id).await
397            } else {
398                Ok(self.latest_state()?)
399            }
400        }
401    }
402
403    /// Executes `f` with the state at the given [`BlockId`] on a blocking IO task.
404    ///
405    /// Resolves the chain's pending-state source before occupying a blocking thread, since
406    /// building a pending block may need a blocking thread of its own.
407    fn spawn_blocking_io_with_state<F, R>(
408        &self,
409        at: BlockId,
410        f: F,
411    ) -> impl Future<Output = Result<R, Self::Error>> + Send
412    where
413        Self: SpawnBlocking,
414        F: FnOnce(Self, StateProviderBox) -> Result<R, Self::Error> + Send + 'static,
415        R: Send + 'static,
416    {
417        async move {
418            let pending = if at.is_pending() {
419                self.local_pending_block_or_state().await.ok().flatten()
420            } else {
421                None
422            };
423
424            self.spawn_blocking_io(move |this| {
425                let state = match pending {
426                    Some(PendingStateSource::Block(pending)) => this
427                        .provider()
428                        .state_with_block_appended(
429                            pending.block().parent_hash(),
430                            pending.executed_block,
431                        )
432                        .or_else(|_| this.provider().state_by_block_id(BlockId::pending()))
433                        .map_err(Self::Error::from_eth_err)?,
434                    Some(PendingStateSource::State(state)) => state,
435                    None if at.is_latest() => this.latest_state()?,
436                    None => {
437                        this.provider().state_by_block_id(at).map_err(Self::Error::from_eth_err)?
438                    }
439                };
440                f(this, state)
441            })
442            .await
443        }
444    }
445
446    /// Returns the EVM environment for the given sealed header.
447    fn evm_env_for_header(
448        &self,
449        header: &SealedHeaderFor<Self::Primitives>,
450    ) -> Result<EvmEnvFor<Self::Evm>, Self::Error> {
451        self.evm_config()
452            .evm_env(header)
453            .map_err(RethError::other)
454            .map_err(Self::Error::from_eth_err)
455    }
456
457    /// Returns the EVM environment for the requested [`BlockId`]
458    ///
459    /// If the [`BlockId`] this will return the [`BlockId`] of the block the env was configured
460    /// for.
461    /// If the [`BlockId`] is pending, this will return the "Pending" tag, otherwise this returns
462    /// the hash of the exact block.
463    fn evm_env_at(
464        &self,
465        at: BlockId,
466    ) -> impl Future<Output = Result<(EvmEnvFor<Self::Evm>, BlockId), Self::Error>> + Send
467    where
468        Self: SpawnBlocking,
469    {
470        async move {
471            if at.is_pending() {
472                let PendingBlockEnv { evm_env, origin } = self.pending_block_env_and_cfg()?;
473                Ok((evm_env, origin.state_block_id()))
474            } else {
475                // we can assume that the blockid will be predominantly `Latest` (e.g. for
476                // `eth_call`) and if requested by number or hash we can quickly fetch just the
477                // header
478                let header = RpcNodeCore::provider(self)
479                    .sealed_header_by_id(at)
480                    .map_err(Self::Error::from_eth_err)?
481                    .ok_or_else(|| EthApiError::HeaderNotFound(at))?;
482                let evm_env = self.evm_env_for_header(&header)?;
483
484                Ok((evm_env, header.hash().into()))
485            }
486        }
487    }
488
489    /// Returns the recovered block, EVM environment, and state block id for the requested
490    /// [`BlockId`].
491    ///
492    /// For pending blocks, this preserves the state id returned by [`Self::evm_env_at`], which can
493    /// be the pending tag for an actual pending block or the latest block hash when the pending env
494    /// is derived from latest.
495    #[expect(clippy::type_complexity)]
496    fn evm_env_and_recovered_block_at(
497        &self,
498        at: BlockId,
499    ) -> impl Future<
500        Output = Result<
501            (Arc<RecoveredBlock<BlockTy<Self::Primitives>>>, EvmEnvFor<Self::Evm>, BlockId),
502            Self::Error,
503        >,
504    > + Send
505    where
506        Self: LoadBlock,
507    {
508        async move {
509            if at.is_pending() {
510                let (evm_env, block_id) = self.evm_env_at(at).await?;
511                let block = self
512                    .recovered_block(block_id)
513                    .await?
514                    .ok_or_else(|| EthApiError::HeaderNotFound(at))?;
515
516                Ok((block, evm_env, block_id))
517            } else {
518                let block = self
519                    .recovered_block(at)
520                    .await?
521                    .ok_or_else(|| EthApiError::HeaderNotFound(at))?;
522                let evm_env = self.evm_env_for_header(block.sealed_block().sealed_header())?;
523                let block_id = block.hash().into();
524
525                Ok((block, evm_env, block_id))
526            }
527        }
528    }
529
530    /// Returns the next available nonce without gaps for the given address
531    /// Next available nonce is either the on chain nonce of the account or the highest consecutive
532    /// nonce in the pool + 1
533    ///
534    /// The provided request must have a from address set.
535    fn next_available_nonce_for(
536        &self,
537        request: &RpcTxReq<Self::NetworkTypes>,
538    ) -> impl Future<Output = Result<u64, Self::Error>> + Send
539    where
540        Self: SpawnBlocking,
541    {
542        let address = request.as_ref().from;
543        self.spawn_blocking_io(move |this| {
544            let address = match address {
545                Some(address) => address,
546                None => return Err(SignError::NoAccount.into_eth_err()),
547            };
548
549            // first fetch the on chain nonce of the account
550            let mut next_nonce = this
551                .latest_state()?
552                .account_nonce(&address)
553                .map_err(Self::Error::from_eth_err)?
554                .unwrap_or_default();
555
556            // Retrieve the highest consecutive transaction for the sender from the transaction pool
557            if let Some(highest_tx) =
558                this.pool().get_highest_consecutive_transaction_by_sender(address, next_nonce)
559            {
560                // Return the nonce of the highest consecutive transaction + 1
561                next_nonce = highest_tx.nonce().checked_add(1).ok_or_else(|| {
562                    Self::Error::from(EthApiError::InvalidTransaction(
563                        RpcInvalidTransactionError::NonceMaxValue,
564                    ))
565                })?;
566            }
567
568            Ok(next_nonce)
569        })
570    }
571
572    /// Returns the number of transactions sent from an address at the given block identifier.
573    ///
574    /// If this is [`BlockNumberOrTag::Pending`](alloy_eips::BlockNumberOrTag) then this will
575    /// look up the highest transaction in pool and return the next nonce (highest + 1).
576    fn transaction_count(
577        &self,
578        address: Address,
579        block_id: Option<BlockId>,
580    ) -> impl Future<Output = Result<U256, Self::Error>> + Send
581    where
582        Self: SpawnBlocking,
583    {
584        let at = block_id.unwrap_or_default();
585        self.spawn_blocking_io_with_state(at, move |this, state| {
586            this.transaction_count_with_state(address, at, &state)
587        })
588    }
589
590    /// Returns the number of transactions sent from an address, given the state at `at`.
591    ///
592    /// If `at` is the pending tag, this accounts for the sender's pool transactions that follow
593    /// the account's nonce in `state` without a gap. Called by [`Self::transaction_count`] once
594    /// the state is open, so implementations can choose the state the nonce is read from.
595    fn transaction_count_with_state(
596        &self,
597        address: Address,
598        at: BlockId,
599        state: &StateProviderBox,
600    ) -> Result<U256, Self::Error> {
601        // first fetch the on chain nonce of the account
602        let on_chain_account_nonce =
603            state.account_nonce(&address).map_err(Self::Error::from_eth_err)?.unwrap_or_default();
604
605        if at.is_pending() {
606            // for pending tag we need to find the highest nonce of txn in the pending state.
607            if let Some(highest_pool_tx) = self
608                .pool()
609                .get_highest_consecutive_transaction_by_sender(address, on_chain_account_nonce)
610            {
611                {
612                    // and the corresponding txcount is nonce + 1 of the highest tx in the pool
613                    // (on chain nonce is increased after tx)
614                    let next_tx_nonce =
615                        highest_pool_tx.nonce().checked_add(1).ok_or_else(|| {
616                            Self::Error::from(EthApiError::InvalidTransaction(
617                                RpcInvalidTransactionError::NonceMaxValue,
618                            ))
619                        })?;
620
621                    // guard against drifts in the pool
622                    let next_tx_nonce = on_chain_account_nonce.max(next_tx_nonce);
623
624                    let tx_count = on_chain_account_nonce.max(next_tx_nonce);
625                    return Ok(U256::from(tx_count));
626                }
627            }
628        }
629        Ok(U256::from(on_chain_account_nonce))
630    }
631
632    /// Returns code of given account, at the given identifier.
633    fn get_code(
634        &self,
635        address: Address,
636        block_id: Option<BlockId>,
637    ) -> impl Future<Output = Result<Bytes, Self::Error>> + Send
638    where
639        Self: SpawnBlocking,
640    {
641        self.spawn_blocking_io_with_state(block_id.unwrap_or_default(), move |_, state| {
642            Ok(state
643                .account_code(&address)
644                .map_err(Self::Error::from_eth_err)?
645                .unwrap_or_default()
646                .original_bytes())
647        })
648    }
649}