reth_primitives_traits/block/
body.rs

1//! Block body abstraction.
2
3use crate::{
4    transaction::signed::RecoveryError, BlockHeader, FullSignedTx, InMemorySize, MaybeSerde,
5    MaybeSerdeBincodeCompat, SignedTransaction,
6};
7use alloc::{fmt, vec::Vec};
8use alloy_consensus::{Transaction, Typed2718};
9use alloy_eips::{eip2718::Encodable2718, eip4895::Withdrawals};
10use alloy_primitives::{Address, Bytes, B256};
11
12/// Helper trait that unifies all behaviour required by transaction to support full node operations.
13pub trait FullBlockBody: BlockBody<Transaction: FullSignedTx> + MaybeSerdeBincodeCompat {}
14
15impl<T> FullBlockBody for T where T: BlockBody<Transaction: FullSignedTx> + MaybeSerdeBincodeCompat {}
16
17/// Abstraction for block's body.
18///
19/// This type is a container for everything that is included in a block except the header.
20/// For ethereum this includes transactions, ommers, and withdrawals.
21pub trait BlockBody:
22    Send
23    + Sync
24    + Unpin
25    + Clone
26    + Default
27    + fmt::Debug
28    + PartialEq
29    + Eq
30    + alloy_rlp::Encodable
31    + alloy_rlp::Decodable
32    + InMemorySize
33    + MaybeSerde
34    + 'static
35{
36    /// Ordered list of signed transactions as committed in the block.
37    type Transaction: SignedTransaction;
38
39    /// Ommer header type.
40    type OmmerHeader: BlockHeader;
41
42    /// Returns reference to transactions in the block.
43    fn transactions(&self) -> &[Self::Transaction];
44
45    /// A Convenience function to convert this type into the regular ethereum block body that
46    /// consists of:
47    ///
48    /// - Transactions
49    /// - Withdrawals
50    /// - Ommers
51    ///
52    /// Note: This conversion can be incomplete. It is not expected that this `Body` is the same as
53    /// [`alloy_consensus::BlockBody`] only that it can be converted into it which is useful for
54    /// the `eth_` RPC namespace (e.g. RPC block).
55    fn into_ethereum_body(self)
56        -> alloy_consensus::BlockBody<Self::Transaction, Self::OmmerHeader>;
57
58    /// Returns an iterator over the transactions in the block.
59    fn transactions_iter(&self) -> impl Iterator<Item = &Self::Transaction> + '_ {
60        self.transactions().iter()
61    }
62
63    /// Returns the transaction with the matching hash.
64    ///
65    /// This is a convenience function for `transactions_iter().find()`
66    fn transaction_by_hash(&self, hash: &B256) -> Option<&Self::Transaction> {
67        self.transactions_iter().find(|tx| tx.tx_hash() == hash)
68    }
69
70    /// Clones the transactions in the block.
71    ///
72    /// This is a convenience function for `transactions().to_vec()`
73    fn clone_transactions(&self) -> Vec<Self::Transaction> {
74        self.transactions().to_vec()
75    }
76
77    /// Returns an iterator over all transaction hashes in the block body.
78    fn transaction_hashes_iter(&self) -> impl Iterator<Item = &B256> + '_ {
79        self.transactions_iter().map(|tx| tx.tx_hash())
80    }
81
82    /// Returns the number of the transactions in the block.
83    fn transaction_count(&self) -> usize {
84        self.transactions().len()
85    }
86
87    /// Consume the block body and return a [`Vec`] of transactions.
88    fn into_transactions(self) -> Vec<Self::Transaction>;
89
90    /// Returns `true` if the block body contains a transaction of the given type.
91    fn contains_transaction_type(&self, tx_type: u8) -> bool {
92        self.transactions_iter().any(|tx| tx.is_type(tx_type))
93    }
94
95    /// Calculate the transaction root for the block body.
96    fn calculate_tx_root(&self) -> B256 {
97        alloy_consensus::proofs::calculate_transaction_root(self.transactions())
98    }
99
100    /// Returns block withdrawals if any.
101    fn withdrawals(&self) -> Option<&Withdrawals>;
102
103    /// Calculate the withdrawals root for the block body.
104    ///
105    /// Returns `None` if there are no withdrawals in the block.
106    fn calculate_withdrawals_root(&self) -> Option<B256> {
107        self.withdrawals().map(|withdrawals| {
108            alloy_consensus::proofs::calculate_withdrawals_root(withdrawals.as_slice())
109        })
110    }
111
112    /// Returns block ommers if any.
113    fn ommers(&self) -> Option<&[Self::OmmerHeader]>;
114
115    /// Calculate the ommers root for the block body.
116    ///
117    /// Returns `None` if there are no ommers in the block.
118    fn calculate_ommers_root(&self) -> Option<B256> {
119        self.ommers().map(alloy_consensus::proofs::calculate_ommers_root)
120    }
121
122    /// Calculates the total blob gas used by _all_ EIP-4844 transactions in the block.
123    fn blob_gas_used(&self) -> u64 {
124        self.transactions_iter().filter_map(|tx| tx.blob_gas_used()).sum()
125    }
126
127    /// Returns an iterator over all blob versioned hashes in the block body.
128    fn blob_versioned_hashes_iter(&self) -> impl Iterator<Item = &B256> + '_ {
129        self.transactions_iter().filter_map(|tx| tx.blob_versioned_hashes()).flatten()
130    }
131
132    /// Returns an iterator over the encoded 2718 transactions.
133    ///
134    /// This is also known as `raw transactions`.
135    ///
136    /// See also [`Encodable2718`].
137    #[doc(alias = "raw_transactions_iter")]
138    fn encoded_2718_transactions_iter(&self) -> impl Iterator<Item = Vec<u8>> + '_ {
139        self.transactions_iter().map(|tx| tx.encoded_2718())
140    }
141
142    /// Returns a vector of encoded 2718 transactions.
143    ///
144    /// This is also known as `raw transactions`.
145    ///
146    /// See also [`Encodable2718`].
147    #[doc(alias = "raw_transactions")]
148    fn encoded_2718_transactions(&self) -> Vec<Bytes> {
149        self.encoded_2718_transactions_iter().map(Into::into).collect()
150    }
151
152    /// Recover signer addresses for all transactions in the block body.
153    fn recover_signers(&self) -> Result<Vec<Address>, RecoveryError>
154    where
155        Self::Transaction: SignedTransaction,
156    {
157        crate::transaction::recover::recover_signers(self.transactions()).map_err(|_| RecoveryError)
158    }
159
160    /// Recover signer addresses for all transactions in the block body.
161    ///
162    /// Returns an error if some transaction's signature is invalid.
163    fn try_recover_signers(&self) -> Result<Vec<Address>, RecoveryError>
164    where
165        Self::Transaction: SignedTransaction,
166    {
167        self.recover_signers()
168    }
169
170    /// Recover signer addresses for all transactions in the block body _without ensuring that the
171    /// signature has a low `s` value_.
172    ///
173    /// Returns `None`, if some transaction's signature is invalid.
174    fn recover_signers_unchecked(&self) -> Result<Vec<Address>, RecoveryError>
175    where
176        Self::Transaction: SignedTransaction,
177    {
178        crate::transaction::recover::recover_signers_unchecked(self.transactions())
179    }
180
181    /// Recover signer addresses for all transactions in the block body _without ensuring that the
182    /// signature has a low `s` value_.
183    ///
184    /// Returns an error if some transaction's signature is invalid.
185    fn try_recover_signers_unchecked(&self) -> Result<Vec<Address>, RecoveryError>
186    where
187        Self::Transaction: SignedTransaction,
188    {
189        self.recover_signers_unchecked()
190    }
191}
192
193impl<T, H> BlockBody for alloy_consensus::BlockBody<T, H>
194where
195    T: SignedTransaction,
196    H: BlockHeader,
197{
198    type Transaction = T;
199    type OmmerHeader = H;
200
201    fn transactions(&self) -> &[Self::Transaction] {
202        &self.transactions
203    }
204
205    fn into_ethereum_body(self) -> Self {
206        self
207    }
208
209    fn into_transactions(self) -> Vec<Self::Transaction> {
210        self.transactions
211    }
212
213    fn withdrawals(&self) -> Option<&Withdrawals> {
214        self.withdrawals.as_ref()
215    }
216
217    fn ommers(&self) -> Option<&[Self::OmmerHeader]> {
218        Some(&self.ommers)
219    }
220}
221
222/// This is a helper alias to make it easy to refer to the inner `Transaction` associated type of a
223/// given type that implements [`BlockBody`].
224pub type BodyTx<N> = <N as BlockBody>::Transaction;
225
226/// This is a helper alias to make it easy to refer to the inner `OmmerHeader` associated type of a
227/// given type that implements [`BlockBody`].
228pub type BodyOmmer<N> = <N as BlockBody>::OmmerHeader;