alloy_consensus/block/
mod.rs

1//! Block-related consensus types.
2
3mod header;
4pub use header::{BlockHeader, Header};
5
6mod traits;
7pub use traits::EthBlock;
8
9#[cfg(all(feature = "serde", feature = "serde-bincode-compat"))]
10pub(crate) use header::serde_bincode_compat;
11
12use crate::Transaction;
13use alloc::vec::Vec;
14use alloy_eips::{eip4895::Withdrawals, Typed2718};
15use alloy_primitives::B256;
16use alloy_rlp::{Decodable, Encodable, RlpDecodable, RlpEncodable};
17
18/// Ethereum full block.
19///
20/// Withdrawals can be optionally included at the end of the RLP encoded message.
21///
22/// Taken from [reth-primitives](https://github.com/paradigmxyz/reth)
23///
24/// See p2p block encoding reference: <https://github.com/ethereum/devp2p/blob/master/caps/eth.md#block-encoding-and-validity>
25#[derive(Debug, Clone, PartialEq, Eq, derive_more::Deref)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub struct Block<T, H = Header> {
28    /// Block header.
29    #[deref]
30    pub header: H,
31    /// Block body.
32    pub body: BlockBody<T, H>,
33}
34
35impl<T, H> Block<T, H> {
36    /// Creates a new block with the given header and body.
37    pub const fn new(header: H, body: BlockBody<T, H>) -> Self {
38        Self { header, body }
39    }
40
41    /// Creates a new empty uncle block.
42    pub fn uncle(header: H) -> Self {
43        Self { header, body: Default::default() }
44    }
45
46    /// Consumes the block and returns the header.
47    pub fn into_header(self) -> H {
48        self.header
49    }
50
51    /// Consumes the block and returns the body.
52    pub fn into_body(self) -> BlockBody<T, H> {
53        self.body
54    }
55
56    /// Converts the block's header type by applying a function to it.
57    pub fn map_header<U>(self, mut f: impl FnMut(H) -> U) -> Block<T, U> {
58        Block { header: f(self.header), body: self.body.map_ommers(f) }
59    }
60
61    /// Converts the block's header type by applying a fallible function to it.
62    pub fn try_map_header<U, E>(
63        self,
64        mut f: impl FnMut(H) -> Result<U, E>,
65    ) -> Result<Block<T, U>, E> {
66        Ok(Block { header: f(self.header)?, body: self.body.try_map_ommers(f)? })
67    }
68
69    /// Converts the block's transaction type to the given alternative that is `From<T>`
70    pub fn convert_transactions<U>(self) -> Block<U, H>
71    where
72        U: From<T>,
73    {
74        self.map_transactions(U::from)
75    }
76
77    /// Converts the block's transaction to the given alternative that is `TryFrom<T>`
78    ///
79    /// Returns the block with the new transaction type if all conversions were successful.
80    pub fn try_convert_transactions<U>(self) -> Result<Block<U, H>, U::Error>
81    where
82        U: TryFrom<T>,
83    {
84        self.try_map_transactions(U::try_from)
85    }
86
87    /// Converts the block's transaction type by applying a function to each transaction.
88    ///
89    /// Returns the block with the new transaction type.
90    pub fn map_transactions<U>(self, f: impl FnMut(T) -> U) -> Block<U, H> {
91        Block {
92            header: self.header,
93            body: BlockBody {
94                transactions: self.body.transactions.into_iter().map(f).collect(),
95                ommers: self.body.ommers,
96                withdrawals: self.body.withdrawals,
97            },
98        }
99    }
100
101    /// Converts the block's transaction type by applying a fallible function to each transaction.
102    ///
103    /// Returns the block with the new transaction type if all transactions were successfully.
104    pub fn try_map_transactions<U, E>(
105        self,
106        f: impl FnMut(T) -> Result<U, E>,
107    ) -> Result<Block<U, H>, E> {
108        Ok(Block {
109            header: self.header,
110            body: BlockBody {
111                transactions: self
112                    .body
113                    .transactions
114                    .into_iter()
115                    .map(f)
116                    .collect::<Result<_, _>>()?,
117                ommers: self.body.ommers,
118                withdrawals: self.body.withdrawals,
119            },
120        })
121    }
122
123    /// Returns the RLP encoded length of the block's header and body.
124    pub fn rlp_length_for(header: &H, body: &BlockBody<T, H>) -> usize
125    where
126        H: Encodable,
127        T: Encodable,
128    {
129        block_rlp::HelperRef {
130            header,
131            transactions: &body.transactions,
132            ommers: &body.ommers,
133            withdrawals: body.withdrawals.as_ref(),
134        }
135        .length()
136    }
137}
138
139impl<T, H> Default for Block<T, H>
140where
141    H: Default,
142{
143    fn default() -> Self {
144        Self { header: Default::default(), body: Default::default() }
145    }
146}
147
148impl<T, H> From<Block<T, H>> for BlockBody<T, H> {
149    fn from(block: Block<T, H>) -> Self {
150        block.into_body()
151    }
152}
153
154#[cfg(any(test, feature = "arbitrary"))]
155impl<'a, T, H> arbitrary::Arbitrary<'a> for Block<T, H>
156where
157    T: arbitrary::Arbitrary<'a>,
158    H: arbitrary::Arbitrary<'a>,
159{
160    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
161        Ok(Self { header: u.arbitrary()?, body: u.arbitrary()? })
162    }
163}
164
165/// A response to `GetBlockBodies`, containing bodies if any bodies were found.
166///
167/// Withdrawals can be optionally included at the end of the RLP encoded message.
168#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
169#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
170#[rlp(trailing)]
171pub struct BlockBody<T, H = Header> {
172    /// Transactions in this block.
173    pub transactions: Vec<T>,
174    /// Ommers/uncles header.
175    pub ommers: Vec<H>,
176    /// Block withdrawals.
177    pub withdrawals: Option<Withdrawals>,
178}
179
180impl<T, H> Default for BlockBody<T, H> {
181    fn default() -> Self {
182        Self { transactions: Vec::new(), ommers: Vec::new(), withdrawals: None }
183    }
184}
185
186impl<T, H> BlockBody<T, H> {
187    /// Returns an iterator over all transactions.
188    #[inline]
189    pub fn transactions(&self) -> impl Iterator<Item = &T> + '_ {
190        self.transactions.iter()
191    }
192
193    /// Create a [`Block`] from the body and its header.
194    pub const fn into_block(self, header: H) -> Block<T, H> {
195        Block { header, body: self }
196    }
197
198    /// Calculate the ommers root for the block body.
199    pub fn calculate_ommers_root(&self) -> B256
200    where
201        H: Encodable,
202    {
203        crate::proofs::calculate_ommers_root(&self.ommers)
204    }
205
206    /// Calculate the withdrawals root for the block body, if withdrawals exist. If there are no
207    /// withdrawals, this will return `None`.
208    pub fn calculate_withdrawals_root(&self) -> Option<B256> {
209        self.withdrawals.as_ref().map(|w| crate::proofs::calculate_withdrawals_root(w))
210    }
211
212    /// Converts the body's ommers type by applying a function to it.
213    pub fn map_ommers<U>(self, f: impl FnMut(H) -> U) -> BlockBody<T, U> {
214        BlockBody {
215            transactions: self.transactions,
216            ommers: self.ommers.into_iter().map(f).collect(),
217            withdrawals: self.withdrawals,
218        }
219    }
220
221    /// Converts the body's ommers type by applying a fallible function to it.
222    pub fn try_map_ommers<U, E>(
223        self,
224        f: impl FnMut(H) -> Result<U, E>,
225    ) -> Result<BlockBody<T, U>, E> {
226        Ok(BlockBody {
227            transactions: self.transactions,
228            ommers: self.ommers.into_iter().map(f).collect::<Result<Vec<_>, _>>()?,
229            withdrawals: self.withdrawals,
230        })
231    }
232}
233
234impl<T: Transaction, H> BlockBody<T, H> {
235    /// Returns an iterator over all blob versioned hashes from the block body.
236    #[inline]
237    pub fn blob_versioned_hashes_iter(&self) -> impl Iterator<Item = &B256> + '_ {
238        self.eip4844_transactions_iter().filter_map(|tx| tx.blob_versioned_hashes()).flatten()
239    }
240}
241
242impl<T: Typed2718, H> BlockBody<T, H> {
243    /// Returns whether or not the block body contains any blob transactions.
244    #[inline]
245    pub fn has_eip4844_transactions(&self) -> bool {
246        self.transactions.iter().any(|tx| tx.is_eip4844())
247    }
248
249    /// Returns whether or not the block body contains any EIP-7702 transactions.
250    #[inline]
251    pub fn has_eip7702_transactions(&self) -> bool {
252        self.transactions.iter().any(|tx| tx.is_eip7702())
253    }
254
255    /// Returns an iterator over all blob transactions of the block.
256    #[inline]
257    pub fn eip4844_transactions_iter(&self) -> impl Iterator<Item = &T> + '_ {
258        self.transactions.iter().filter(|tx| tx.is_eip4844())
259    }
260}
261
262/// We need to implement RLP traits manually because we currently don't have a way to flatten
263/// [`BlockBody`] into [`Block`].
264mod block_rlp {
265    use super::*;
266
267    #[derive(RlpDecodable)]
268    #[rlp(trailing)]
269    struct Helper<T, H> {
270        header: H,
271        transactions: Vec<T>,
272        ommers: Vec<H>,
273        withdrawals: Option<Withdrawals>,
274    }
275
276    #[derive(RlpEncodable)]
277    #[rlp(trailing)]
278    pub(crate) struct HelperRef<'a, T, H> {
279        pub(crate) header: &'a H,
280        pub(crate) transactions: &'a Vec<T>,
281        pub(crate) ommers: &'a Vec<H>,
282        pub(crate) withdrawals: Option<&'a Withdrawals>,
283    }
284
285    impl<'a, T, H> From<&'a Block<T, H>> for HelperRef<'a, T, H> {
286        fn from(block: &'a Block<T, H>) -> Self {
287            let Block { header, body: BlockBody { transactions, ommers, withdrawals } } = block;
288            Self { header, transactions, ommers, withdrawals: withdrawals.as_ref() }
289        }
290    }
291
292    impl<T: Encodable, H: Encodable> Encodable for Block<T, H> {
293        fn encode(&self, out: &mut dyn alloy_rlp::bytes::BufMut) {
294            let helper: HelperRef<'_, T, H> = self.into();
295            helper.encode(out)
296        }
297
298        fn length(&self) -> usize {
299            let helper: HelperRef<'_, T, H> = self.into();
300            helper.length()
301        }
302    }
303
304    impl<T: Decodable, H: Decodable> Decodable for Block<T, H> {
305        fn decode(b: &mut &[u8]) -> alloy_rlp::Result<Self> {
306            let Helper { header, transactions, ommers, withdrawals } = Helper::decode(b)?;
307            Ok(Self { header, body: BlockBody { transactions, ommers, withdrawals } })
308        }
309    }
310}
311
312#[cfg(any(test, feature = "arbitrary"))]
313impl<'a, T, H> arbitrary::Arbitrary<'a> for BlockBody<T, H>
314where
315    T: arbitrary::Arbitrary<'a>,
316    H: arbitrary::Arbitrary<'a>,
317{
318    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
319        // first generate up to 100 txs
320        // first generate a reasonable amount of txs
321        let transactions = (0..u.int_in_range(0..=100)?)
322            .map(|_| T::arbitrary(u))
323            .collect::<arbitrary::Result<Vec<_>>>()?;
324
325        // then generate up to 2 ommers
326        let ommers = (0..u.int_in_range(0..=1)?)
327            .map(|_| H::arbitrary(u))
328            .collect::<arbitrary::Result<Vec<_>>>()?;
329
330        Ok(Self { transactions, ommers, withdrawals: u.arbitrary()? })
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337    use crate::{Signed, TxEnvelope, TxLegacy};
338
339    #[test]
340    fn can_convert_block() {
341        let block: Block<Signed<TxLegacy>> = Block::default();
342        let _: Block<TxEnvelope> = block.convert_transactions();
343    }
344}