reth_primitives_traits/block/
sealed.rs

1//! Sealed block types
2
3use crate::{
4    block::{error::BlockRecoveryError, RecoveredBlock},
5    transaction::signed::RecoveryError,
6    Block, BlockBody, GotExpected, InMemorySize, SealedHeader,
7};
8use alloc::vec::Vec;
9use alloy_consensus::BlockHeader;
10use alloy_eips::{eip1898::BlockWithParent, BlockNumHash};
11use alloy_primitives::{Address, BlockHash, Sealable, Sealed, B256};
12use alloy_rlp::{Decodable, Encodable};
13use bytes::BufMut;
14use core::ops::Deref;
15
16/// Sealed full block composed of the block's header and body.
17///
18/// This type uses lazy sealing to avoid hashing the header until it is needed, see also
19/// [`SealedHeader`].
20#[derive(Debug, Clone, PartialEq, Eq)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22pub struct SealedBlock<B: Block> {
23    /// Sealed Header.
24    header: SealedHeader<B::Header>,
25    /// the block's body.
26    body: B::Body,
27}
28
29impl<B: Block> SealedBlock<B> {
30    /// Hashes the header and creates a sealed block.
31    ///
32    /// This calculates the header hash. To create a [`SealedBlock`] without calculating the hash
33    /// upfront see [`SealedBlock::new_unhashed`]
34    pub fn seal_slow(block: B) -> Self {
35        let hash = block.header().hash_slow();
36        Self::new_unchecked(block, hash)
37    }
38
39    /// Create a new sealed block instance using the block.
40    ///
41    /// Caution: This assumes the given hash is the block's hash.
42    #[inline]
43    pub fn new_unchecked(block: B, hash: BlockHash) -> Self {
44        let (header, body) = block.split();
45        Self { header: SealedHeader::new(header, hash), body }
46    }
47
48    /// Creates a `SealedBlock` from the block without the available hash
49    pub fn new_unhashed(block: B) -> Self {
50        let (header, body) = block.split();
51        Self { header: SealedHeader::new_unhashed(header), body }
52    }
53
54    /// Creates the [`SealedBlock`] from the block's parts by hashing the header.
55    ///
56    ///
57    /// This calculates the header hash. To create a [`SealedBlock`] from its parts without
58    /// calculating the hash upfront see [`SealedBlock::from_parts_unhashed`]
59    pub fn seal_parts(header: B::Header, body: B::Body) -> Self {
60        Self::seal_slow(B::new(header, body))
61    }
62
63    /// Creates the [`SealedBlock`] from the block's parts without calculating the hash upfront.
64    pub fn from_parts_unhashed(header: B::Header, body: B::Body) -> Self {
65        Self::new_unhashed(B::new(header, body))
66    }
67
68    /// Creates the [`SealedBlock`] from the block's parts.
69    pub fn from_parts_unchecked(header: B::Header, body: B::Body, hash: BlockHash) -> Self {
70        Self::new_unchecked(B::new(header, body), hash)
71    }
72
73    /// Creates the [`SealedBlock`] from the [`SealedHeader`] and the body.
74    pub fn from_sealed_parts(header: SealedHeader<B::Header>, body: B::Body) -> Self {
75        let (header, hash) = header.split();
76        Self::from_parts_unchecked(header, body, hash)
77    }
78
79    /// Returns a reference to the block hash.
80    #[inline]
81    pub fn hash_ref(&self) -> &BlockHash {
82        self.header.hash_ref()
83    }
84
85    /// Returns the block hash.
86    #[inline]
87    pub fn hash(&self) -> B256 {
88        self.header.hash()
89    }
90
91    /// Consumes the type and returns its components.
92    #[doc(alias = "into_components")]
93    pub fn split(self) -> (B, BlockHash) {
94        let (header, hash) = self.header.split();
95        (B::new(header, self.body), hash)
96    }
97
98    /// Consumes the type and returns the block.
99    pub fn into_block(self) -> B {
100        self.unseal()
101    }
102
103    /// Consumes the type and returns the block.
104    pub fn unseal(self) -> B {
105        let header = self.header.unseal();
106        B::new(header, self.body)
107    }
108
109    /// Clones the wrapped block.
110    pub fn clone_block(&self) -> B {
111        B::new(self.header.clone_header(), self.body.clone())
112    }
113
114    /// Converts this block into a [`RecoveredBlock`] with the given senders
115    ///
116    /// Note: This method assumes the senders are correct and does not validate them.
117    pub const fn with_senders(self, senders: Vec<Address>) -> RecoveredBlock<B> {
118        RecoveredBlock::new_sealed(self, senders)
119    }
120
121    /// Converts this block into a [`RecoveredBlock`] with the given senders if the number of
122    /// senders is equal to the number of transactions in the block and recovers the senders from
123    /// the transactions, if
124    /// not using [`SignedTransaction::recover_signer`](crate::transaction::signed::SignedTransaction)
125    /// to recover the senders.
126    ///
127    /// Returns an error if any of the transactions fail to recover the sender.
128    pub fn try_with_senders(
129        self,
130        senders: Vec<Address>,
131    ) -> Result<RecoveredBlock<B>, BlockRecoveryError<Self>> {
132        RecoveredBlock::try_recover_sealed_with_senders(self, senders)
133    }
134
135    /// Converts this block into a [`RecoveredBlock`] with the given senders if the number of
136    /// senders is equal to the number of transactions in the block and recovers the senders from
137    /// the transactions, if
138    /// not using [`SignedTransaction::recover_signer_unchecked`](crate::transaction::signed::SignedTransaction)
139    /// to recover the senders.
140    ///
141    /// Returns an error if any of the transactions fail to recover the sender.
142    pub fn try_with_senders_unchecked(
143        self,
144        senders: Vec<Address>,
145    ) -> Result<RecoveredBlock<B>, BlockRecoveryError<Self>> {
146        RecoveredBlock::try_recover_sealed_with_senders_unchecked(self, senders)
147    }
148
149    /// Recovers the senders from the transactions in the block using
150    /// [`SignedTransaction::recover_signer`](crate::transaction::signed::SignedTransaction).
151    ///
152    /// Returns an error if any of the transactions fail to recover the sender.
153    pub fn try_recover(self) -> Result<RecoveredBlock<B>, BlockRecoveryError<Self>> {
154        RecoveredBlock::try_recover_sealed(self)
155    }
156
157    /// Recovers the senders from the transactions in the block using
158    /// [`SignedTransaction::recover_signer_unchecked`](crate::transaction::signed::SignedTransaction).
159    ///
160    /// Returns an error if any of the transactions fail to recover the sender.
161    pub fn try_recover_unchecked(self) -> Result<RecoveredBlock<B>, BlockRecoveryError<Self>> {
162        RecoveredBlock::try_recover_sealed_unchecked(self)
163    }
164
165    /// Returns reference to block header.
166    pub const fn header(&self) -> &B::Header {
167        self.header.header()
168    }
169
170    /// Returns reference to block body.
171    pub const fn body(&self) -> &B::Body {
172        &self.body
173    }
174
175    /// Returns the length of the block.
176    pub fn rlp_length(&self) -> usize {
177        B::rlp_length(self.header(), self.body())
178    }
179
180    /// Recovers all senders from the transactions in the block.
181    ///
182    /// Returns `None` if any of the transactions fail to recover the sender.
183    pub fn senders(&self) -> Result<Vec<Address>, RecoveryError> {
184        self.body().recover_signers()
185    }
186
187    /// Return the number hash tuple.
188    pub fn num_hash(&self) -> BlockNumHash {
189        BlockNumHash::new(self.number(), self.hash())
190    }
191
192    /// Return a [`BlockWithParent`] for this header.
193    pub fn block_with_parent(&self) -> BlockWithParent {
194        BlockWithParent { parent: self.parent_hash(), block: self.num_hash() }
195    }
196
197    /// Returns the Sealed header.
198    pub const fn sealed_header(&self) -> &SealedHeader<B::Header> {
199        &self.header
200    }
201
202    /// Returns the wrapped `SealedHeader<B::Header>` as `SealedHeader<&B::Header>`.
203    pub fn sealed_header_ref(&self) -> SealedHeader<&B::Header> {
204        SealedHeader::new(self.header(), self.hash())
205    }
206
207    /// Clones the wrapped header and returns a [`SealedHeader`] sealed with the hash.
208    pub fn clone_sealed_header(&self) -> SealedHeader<B::Header> {
209        self.header.clone()
210    }
211
212    /// Consumes the block and returns the sealed header.
213    pub fn into_sealed_header(self) -> SealedHeader<B::Header> {
214        self.header
215    }
216
217    /// Consumes the block and returns the header.
218    pub fn into_header(self) -> B::Header {
219        self.header.unseal()
220    }
221
222    /// Consumes the block and returns the body.
223    pub fn into_body(self) -> B::Body {
224        self.body
225    }
226
227    /// Splits the block into body and header into separate components
228    pub fn split_header_body(self) -> (B::Header, B::Body) {
229        let header = self.header.unseal();
230        (header, self.body)
231    }
232
233    /// Splits the block into body and header into separate components.
234    pub fn split_sealed_header_body(self) -> (SealedHeader<B::Header>, B::Body) {
235        (self.header, self.body)
236    }
237
238    /// Returns an iterator over all blob versioned hashes from the block body.
239    #[inline]
240    pub fn blob_versioned_hashes_iter(&self) -> impl Iterator<Item = &B256> + '_ {
241        self.body().blob_versioned_hashes_iter()
242    }
243
244    /// Returns the number of transactions in the block.
245    #[inline]
246    pub fn transaction_count(&self) -> usize {
247        self.body().transaction_count()
248    }
249
250    /// Ensures that the transaction root in the block header is valid.
251    ///
252    /// The transaction root is the Keccak 256-bit hash of the root node of the trie structure
253    /// populated with each transaction in the transactions list portion of the block.
254    ///
255    /// # Returns
256    ///
257    /// Returns `Ok(())` if the calculated transaction root matches the one stored in the header,
258    /// indicating that the transactions in the block are correctly represented in the trie.
259    ///
260    /// Returns `Err(error)` if the transaction root validation fails, providing a `GotExpected`
261    /// error containing the calculated and expected roots.
262    pub fn ensure_transaction_root_valid(&self) -> Result<(), GotExpected<B256>> {
263        let calculated_root = self.body().calculate_tx_root();
264
265        if self.header().transactions_root() != calculated_root {
266            return Err(GotExpected {
267                got: calculated_root,
268                expected: self.header().transactions_root(),
269            })
270        }
271
272        Ok(())
273    }
274}
275
276impl<B> From<B> for SealedBlock<B>
277where
278    B: Block,
279{
280    fn from(block: B) -> Self {
281        Self::seal_slow(block)
282    }
283}
284
285impl<B> Default for SealedBlock<B>
286where
287    B: Block + Default,
288{
289    fn default() -> Self {
290        Self::seal_slow(Default::default())
291    }
292}
293
294impl<B: Block> InMemorySize for SealedBlock<B> {
295    #[inline]
296    fn size(&self) -> usize {
297        self.body.size() + self.header.size()
298    }
299}
300
301impl<B: Block> Deref for SealedBlock<B> {
302    type Target = B::Header;
303
304    fn deref(&self) -> &Self::Target {
305        self.header()
306    }
307}
308
309impl<B: Block> Encodable for SealedBlock<B> {
310    fn encode(&self, out: &mut dyn BufMut) {
311        self.body.encode(out);
312    }
313}
314
315impl<B: Block> Decodable for SealedBlock<B> {
316    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
317        let block = B::decode(buf)?;
318        Ok(Self::seal_slow(block))
319    }
320}
321
322impl<B: Block> From<SealedBlock<B>> for Sealed<B> {
323    fn from(value: SealedBlock<B>) -> Self {
324        let (block, hash) = value.split();
325        Self::new_unchecked(block, hash)
326    }
327}
328
329#[cfg(any(test, feature = "arbitrary"))]
330impl<'a, B> arbitrary::Arbitrary<'a> for SealedBlock<B>
331where
332    B: Block + arbitrary::Arbitrary<'a>,
333{
334    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
335        let block = B::arbitrary(u)?;
336        Ok(Self::seal_slow(block))
337    }
338}
339
340#[cfg(any(test, feature = "test-utils"))]
341impl<B: crate::test_utils::TestBlock> SealedBlock<B> {
342    /// Returns a mutable reference to the header.
343    pub const fn header_mut(&mut self) -> &mut B::Header {
344        self.header.header_mut()
345    }
346
347    /// Updates the block hash.
348    pub fn set_hash(&mut self, hash: BlockHash) {
349        self.header.set_hash(hash)
350    }
351
352    /// Returns a mutable reference to the header.
353    pub const fn body_mut(&mut self) -> &mut B::Body {
354        &mut self.body
355    }
356
357    /// Updates the parent block hash.
358    pub fn set_parent_hash(&mut self, hash: BlockHash) {
359        self.header.set_parent_hash(hash)
360    }
361
362    /// Updates the block number.
363    pub fn set_block_number(&mut self, number: alloy_primitives::BlockNumber) {
364        self.header.set_block_number(number)
365    }
366
367    /// Updates the block state root.
368    pub fn set_state_root(&mut self, state_root: alloy_primitives::B256) {
369        self.header.set_state_root(state_root)
370    }
371
372    /// Updates the block difficulty.
373    pub fn set_difficulty(&mut self, difficulty: alloy_primitives::U256) {
374        self.header.set_difficulty(difficulty)
375    }
376}
377
378/// Bincode-compatible [`SealedBlock`] serde implementation.
379#[cfg(feature = "serde-bincode-compat")]
380pub(super) mod serde_bincode_compat {
381    use crate::{
382        serde_bincode_compat::{self, BincodeReprFor, SerdeBincodeCompat},
383        Block,
384    };
385    use serde::{Deserialize, Deserializer, Serialize, Serializer};
386    use serde_with::{serde_as, DeserializeAs, SerializeAs};
387
388    /// Bincode-compatible [`super::SealedBlock`] serde implementation.
389    ///
390    /// Intended to use with the [`serde_with::serde_as`] macro in the following way:
391    /// ```rust
392    /// use reth_primitives_traits::{
393    ///     block::SealedBlock,
394    ///     serde_bincode_compat::{self, SerdeBincodeCompat},
395    ///     Block,
396    /// };
397    /// use serde::{Deserialize, Serialize};
398    /// use serde_with::serde_as;
399    ///
400    /// #[serde_as]
401    /// #[derive(Serialize, Deserialize)]
402    /// struct Data<T: Block<Header: SerdeBincodeCompat, Body: SerdeBincodeCompat> + 'static> {
403    ///     #[serde_as(as = "serde_bincode_compat::SealedBlock<'_, T>")]
404    ///     block: SealedBlock<T>,
405    /// }
406    /// ```
407    #[serde_as]
408    #[derive(derive_more::Debug, Serialize, Deserialize)]
409    pub struct SealedBlock<
410        'a,
411        T: Block<Header: SerdeBincodeCompat, Body: SerdeBincodeCompat> + 'static,
412    > {
413        #[serde(
414            bound = "serde_bincode_compat::SealedHeader<'a, T::Header>: Serialize + serde::de::DeserializeOwned"
415        )]
416        header: serde_bincode_compat::SealedHeader<'a, T::Header>,
417        body: BincodeReprFor<'a, T::Body>,
418    }
419
420    impl<'a, T: Block<Header: SerdeBincodeCompat, Body: SerdeBincodeCompat> + 'static>
421        From<&'a super::SealedBlock<T>> for SealedBlock<'a, T>
422    {
423        fn from(value: &'a super::SealedBlock<T>) -> Self {
424            Self { header: value.header.as_repr(), body: value.body.as_repr() }
425        }
426    }
427
428    impl<'a, T: Block<Header: SerdeBincodeCompat, Body: SerdeBincodeCompat> + 'static>
429        From<SealedBlock<'a, T>> for super::SealedBlock<T>
430    {
431        fn from(value: SealedBlock<'a, T>) -> Self {
432            Self::from_sealed_parts(value.header.into(), SerdeBincodeCompat::from_repr(value.body))
433        }
434    }
435
436    impl<T: Block<Header: SerdeBincodeCompat, Body: SerdeBincodeCompat> + 'static>
437        SerializeAs<super::SealedBlock<T>> for SealedBlock<'_, T>
438    {
439        fn serialize_as<S>(source: &super::SealedBlock<T>, serializer: S) -> Result<S::Ok, S::Error>
440        where
441            S: Serializer,
442        {
443            SealedBlock::from(source).serialize(serializer)
444        }
445    }
446
447    impl<'de, T: Block<Header: SerdeBincodeCompat, Body: SerdeBincodeCompat> + 'static>
448        DeserializeAs<'de, super::SealedBlock<T>> for SealedBlock<'de, T>
449    {
450        fn deserialize_as<D>(deserializer: D) -> Result<super::SealedBlock<T>, D::Error>
451        where
452            D: Deserializer<'de>,
453        {
454            SealedBlock::deserialize(deserializer).map(Into::into)
455        }
456    }
457
458    impl<T: Block<Header: SerdeBincodeCompat, Body: SerdeBincodeCompat> + 'static>
459        SerdeBincodeCompat for super::SealedBlock<T>
460    {
461        type BincodeRepr<'a> = SealedBlock<'a, T>;
462
463        fn as_repr(&self) -> Self::BincodeRepr<'_> {
464            self.into()
465        }
466
467        fn from_repr(repr: Self::BincodeRepr<'_>) -> Self {
468            repr.into()
469        }
470    }
471}