Skip to main content

reth_rpc_eth_api/helpers/
block.rs

1//! Database access for `eth_` block RPC methods. Loads block and receipt data w.r.t. network.
2
3use super::{LoadPendingBlock, SpawnBlocking};
4use crate::{
5    node::RpcNodeCoreExt, EthApiTypes, FromEthApiError, FullEthApiTypes, RpcBlock, RpcNodeCore,
6    RpcReceipt,
7};
8use alloy_consensus::{transaction::TxHashRef, TxReceipt};
9use alloy_eip7928::bal::DecodedBal;
10use alloy_eips::BlockId;
11use alloy_rlp::Encodable;
12use alloy_rpc_types_eth::{Block, BlockTransactions, Index};
13use evm2::evm::Bal as EvmBal;
14use futures::Future;
15use reth_primitives_traits::{
16    AlloyBlockHeader, BlockBody, RecoveredBlock, SealedHeader, TransactionMeta,
17};
18use reth_rpc_convert::{transaction::ConvertReceiptInput, RpcConvert, RpcHeader};
19use reth_rpc_eth_types::block::SharedReceipts;
20use reth_storage_api::{
21    BlockIdReader, BlockReader, ProviderBlock, ProviderHeader, ProviderReceipt, ProviderTx,
22};
23use reth_transaction_pool::{PoolTransaction, TransactionPool};
24use std::sync::Arc;
25
26/// Result type of the fetched block receipts.
27pub type BlockReceiptsResult<N, E> = Result<Option<Vec<RpcReceipt<N>>>, E>;
28/// Result type of the fetched block and its receipts.
29pub type BlockAndReceiptsResult<Eth> = Result<
30    Option<(
31        Arc<RecoveredBlock<<<Eth as RpcNodeCore>::Provider as BlockReader>::Block>>,
32        SharedReceipts<ProviderReceipt<<Eth as RpcNodeCore>::Provider>>,
33    )>,
34    <Eth as EthApiTypes>::Error,
35>;
36
37/// Block related functions for the [`EthApiServer`](crate::EthApiServer) trait in the
38/// `eth_` namespace.
39pub trait EthBlocks: LoadBlock<RpcConvert: RpcConvert<Primitives = Self::Primitives>> {
40    /// Returns the block header for the given block id.
41    fn rpc_block_header(
42        &self,
43        block_id: BlockId,
44    ) -> impl Future<Output = Result<Option<RpcHeader<Self::NetworkTypes>>, Self::Error>> + Send
45    where
46        Self: FullEthApiTypes,
47    {
48        async move {
49            let Some(block) = self.recovered_block(block_id).await? else { return Ok(None) };
50            // Header responses omit the block size: https://github.com/ethereum/execution-apis/pull/877
51            let header = self.converter().convert_header(block.clone_sealed_header(), None)?;
52            Ok(Some(header))
53        }
54    }
55
56    /// Returns the populated rpc block object for the given block id.
57    ///
58    /// If `full` is true, the block object will contain all transaction objects, otherwise it will
59    /// only contain the transaction hashes.
60    fn rpc_block(
61        &self,
62        block_id: BlockId,
63        full: bool,
64    ) -> impl Future<Output = Result<Option<RpcBlock<Self::NetworkTypes>>, Self::Error>> + Send
65    where
66        Self: FullEthApiTypes,
67    {
68        async move {
69            let Some(block) = self.recovered_block(block_id).await? else { return Ok(None) };
70
71            self.convert_block(&block, full).map(Some)
72        }
73    }
74
75    /// Builds an RPC block with full transactions or only their hashes, propagating conversion
76    /// errors from the network's header and transaction converters.
77    fn convert_block(
78        &self,
79        block: &RecoveredBlock<ProviderBlock<Self::Provider>>,
80        full: bool,
81    ) -> Result<RpcBlock<Self::NetworkTypes>, Self::Error> {
82        Ok(block.clone_into_rpc_block(
83            full.into(),
84            |tx, tx_info| self.converter().fill(tx, tx_info),
85            |header, block_size| self.converter().convert_header(header, Some(block_size)),
86        )?)
87    }
88
89    /// Returns the number transactions in the given block.
90    ///
91    /// Returns `None` if the block does not exist
92    fn block_transaction_count(
93        &self,
94        block_id: BlockId,
95    ) -> impl Future<Output = Result<Option<usize>, Self::Error>> + Send {
96        async move { Ok(self.recovered_block(block_id).await?.map(|b| b.body().transaction_count())) }
97    }
98
99    /// Helper function for `eth_getBlockReceipts`.
100    ///
101    /// Returns all transaction receipts in block, or `None` if block wasn't found.
102    fn block_receipts(
103        &self,
104        block_id: BlockId,
105    ) -> impl Future<Output = BlockReceiptsResult<Self::NetworkTypes, Self::Error>> + Send {
106        async move {
107            self.load_block_and_receipts(block_id)
108                .await?
109                .map(|(block, receipts)| self.convert_block_receipts(&block, receipts))
110                .transpose()
111        }
112    }
113
114    /// Converts receipts in transaction order using their recovered block's execution metadata.
115    /// Returns the network converter's error if it cannot build the RPC receipts.
116    fn convert_block_receipts(
117        &self,
118        block: &RecoveredBlock<ProviderBlock<Self::Provider>>,
119        receipts: SharedReceipts<ProviderReceipt<Self::Provider>>,
120    ) -> Result<Vec<RpcReceipt<Self::NetworkTypes>>, Self::Error> {
121        let block_number = block.number();
122        let base_fee = block.base_fee_per_gas();
123        let block_hash = block.hash();
124        let excess_blob_gas = block.excess_blob_gas();
125        let timestamp = block.timestamp();
126        let mut gas_used = 0;
127        let mut next_log_index = 0;
128
129        let inputs = block
130            .transactions_recovered()
131            .zip(receipts.into_vec())
132            .enumerate()
133            .map(|(idx, (tx, receipt))| {
134                let meta = TransactionMeta {
135                    tx_hash: *tx.tx_hash(),
136                    index: idx as u64,
137                    block_hash,
138                    block_number,
139                    base_fee,
140                    excess_blob_gas,
141                    timestamp,
142                };
143
144                let cumulative_gas_used = receipt.cumulative_gas_used();
145                let logs_len = receipt.logs().len();
146
147                let input = ConvertReceiptInput {
148                    tx,
149                    gas_used: cumulative_gas_used - gas_used,
150                    next_log_index,
151                    meta,
152                    receipt,
153                };
154
155                gas_used = cumulative_gas_used;
156                next_log_index += logs_len;
157
158                input
159            })
160            .collect::<Vec<_>>();
161
162        Ok(self.converter().convert_receipts_with_block(inputs, block)?)
163    }
164
165    /// Helper method that loads a block and all its receipts.
166    fn load_block_and_receipts(
167        &self,
168        block_id: BlockId,
169    ) -> impl Future<Output = BlockAndReceiptsResult<Self>> + Send
170    where
171        Self::Pool:
172            TransactionPool<Transaction: PoolTransaction<Consensus = ProviderTx<Self::Provider>>>,
173    {
174        async move {
175            if block_id.is_pending() {
176                if self.pending_block_kind().is_none() {
177                    return Ok(None);
178                }
179
180                // First, try to get the pending block from the provider, in case we already
181                // received the actual pending block from the CL.
182                if let Some(pending) = self
183                    .provider()
184                    .pending_block_and_receipts()
185                    .map_err(Self::Error::from_eth_err)?
186                {
187                    let (block, output) = pending.into_parts();
188                    return Ok(Some((block, output.into())));
189                }
190
191                // If no pending block from provider, build the pending block locally.
192                if let Some(pending) = self.local_pending_block().await? {
193                    return Ok(Some((pending.block, pending.receipts)));
194                }
195            }
196
197            if let Some(block_hash) =
198                self.provider().block_hash_for_id(block_id).map_err(Self::Error::from_eth_err)? &&
199                let Some((block, receipts)) = self
200                    .cache()
201                    .get_block_and_receipts(block_hash)
202                    .await
203                    .map_err(Self::Error::from_eth_err)?
204            {
205                return Ok(Some((block, receipts.into())));
206            }
207
208            Ok(None)
209        }
210    }
211
212    /// Returns uncle headers of given block.
213    ///
214    /// Returns an empty vec if there are none.
215    #[expect(clippy::type_complexity)]
216    fn ommers(
217        &self,
218        block_id: BlockId,
219    ) -> impl Future<Output = Result<Option<Vec<ProviderHeader<Self::Provider>>>, Self::Error>> + Send
220    {
221        async move {
222            if let Some(block) = self.recovered_block(block_id).await? {
223                Ok(block.body().ommers().map(|o| o.to_vec()))
224            } else {
225                Ok(None)
226            }
227        }
228    }
229
230    /// Returns uncle block at given index in given block.
231    ///
232    /// Returns `None` if index out of range.
233    fn ommer_by_block_and_index(
234        &self,
235        block_id: BlockId,
236        index: Index,
237    ) -> impl Future<Output = Result<Option<RpcBlock<Self::NetworkTypes>>, Self::Error>> + Send
238    {
239        async move {
240            let uncles = self
241                .recovered_block(block_id)
242                .await?
243                .map(|block| block.body().ommers().map(|o| o.to_vec()).unwrap_or_default())
244                .unwrap_or_default();
245
246            uncles
247                .into_iter()
248                .nth(index.into())
249                .map(|header| {
250                    let block =
251                        alloy_consensus::Block::<alloy_consensus::TxEnvelope, _>::uncle(header);
252                    let size = block.length();
253                    let header = self
254                        .converter()
255                        .convert_header(SealedHeader::new_unhashed(block.header), Some(size))?;
256                    Ok(Block {
257                        uncles: vec![],
258                        header,
259                        transactions: BlockTransactions::Uncle,
260                        withdrawals: None,
261                    })
262                })
263                .transpose()
264        }
265    }
266}
267
268/// Loads a block from database.
269///
270/// Behaviour shared by several `eth_` RPC methods, not exclusive to `eth_` blocks RPC methods.
271pub trait LoadBlock: LoadPendingBlock + SpawnBlocking + RpcNodeCoreExt {
272    /// Returns the block object for the given block id.
273    #[expect(clippy::type_complexity)]
274    fn recovered_block(
275        &self,
276        block_id: BlockId,
277    ) -> impl Future<
278        Output = Result<
279            Option<Arc<RecoveredBlock<<Self::Provider as BlockReader>::Block>>>,
280            Self::Error,
281        >,
282    > + Send {
283        async move {
284            if block_id.is_pending() {
285                if self.pending_block_kind().is_none() {
286                    return Ok(None);
287                }
288
289                // Pending block can be fetched directly without need for caching
290                if let Some(pending_block) =
291                    self.provider().pending_block().map_err(Self::Error::from_eth_err)?
292                {
293                    return Ok(Some(pending_block));
294                }
295
296                // If no pending block from provider, try to get local pending block
297                return match self.local_pending_block().await? {
298                    Some(pending) => Ok(Some(pending.block)),
299                    None => Ok(None),
300                };
301            }
302
303            let block_hash = match self
304                .provider()
305                .block_hash_for_id(block_id)
306                .map_err(Self::Error::from_eth_err)?
307            {
308                Some(block_hash) => block_hash,
309                None => return Ok(None),
310            };
311
312            self.cache().get_recovered_block(block_hash).await.map_err(Self::Error::from_eth_err)
313        }
314    }
315
316    /// Returns the block for the given block id, together with the block's cached block access
317    /// list, if any.
318    ///
319    /// The BAL is only returned if it is already cached, it is never fetched from the BAL store.
320    /// Pending blocks never have a BAL.
321    #[expect(clippy::type_complexity)]
322    fn recovered_block_and_maybe_bal(
323        &self,
324        block_id: BlockId,
325    ) -> impl Future<
326        Output = Result<
327            Option<(
328                Arc<RecoveredBlock<<Self::Provider as BlockReader>::Block>>,
329                Option<Arc<DecodedBal<Arc<EvmBal>>>>,
330            )>,
331            Self::Error,
332        >,
333    > + Send {
334        async move {
335            if block_id.is_pending() {
336                return Ok(self.recovered_block(block_id).await?.map(|block| (block, None)));
337            }
338
339            let block_hash = match self
340                .provider()
341                .block_hash_for_id(block_id)
342                .map_err(Self::Error::from_eth_err)?
343            {
344                Some(block_hash) => block_hash,
345                None => return Ok(None),
346            };
347
348            self.cache()
349                .get_recovered_block_and_maybe_bal(block_hash)
350                .await
351                .map_err(Self::Error::from_eth_err)
352        }
353    }
354}