reth-primitives-traits 0.3.1

Common types in reth.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Sealed block types

use crate::{
    block::{error::BlockRecoveryError, header::BlockHeader, RecoveredBlock},
    transaction::signed::{RecoveryError, SignedTransaction},
    Block, BlockBody, GotExpected, InMemorySize, SealedHeader,
};
use alloc::vec::Vec;
use alloy_consensus::BlockHeader as _;
use alloy_eips::{eip1898::BlockWithParent, BlockNumHash};
use alloy_primitives::{Address, BlockHash, Sealable, Sealed, B256};
use alloy_rlp::{Decodable, Encodable};
use bytes::BufMut;
use core::ops::Deref;

/// Sealed full block composed of the block's header and body.
///
/// This type uses lazy sealing to avoid hashing the header until it is needed, see also
/// [`SealedHeader`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SealedBlock<B: Block> {
    /// Sealed Header.
    header: SealedHeader<B::Header>,
    /// the block's body.
    body: B::Body,
}

impl<B: Block> SealedBlock<B> {
    /// Hashes the header and creates a sealed block.
    ///
    /// This calculates the header hash. To create a [`SealedBlock`] without calculating the hash
    /// upfront see [`SealedBlock::new_unhashed`]
    pub fn seal_slow(block: B) -> Self {
        let hash = block.header().hash_slow();
        Self::new_unchecked(block, hash)
    }

    /// Create a new sealed block instance using the block.
    ///
    /// Caution: This assumes the given hash is the block's hash.
    #[inline]
    pub fn new_unchecked(block: B, hash: BlockHash) -> Self {
        let (header, body) = block.split();
        Self { header: SealedHeader::new(header, hash), body }
    }

    /// Creates a `SealedBlock` from the block without the available hash
    pub fn new_unhashed(block: B) -> Self {
        let (header, body) = block.split();
        Self { header: SealedHeader::new_unhashed(header), body }
    }

    /// Creates the [`SealedBlock`] from the block's parts by hashing the header.
    ///
    ///
    /// This calculates the header hash. To create a [`SealedBlock`] from its parts without
    /// calculating the hash upfront see [`SealedBlock::from_parts_unhashed`]
    pub fn seal_parts(header: B::Header, body: B::Body) -> Self {
        Self::seal_slow(B::new(header, body))
    }

    /// Creates the [`SealedBlock`] from the block's parts without calculating the hash upfront.
    pub fn from_parts_unhashed(header: B::Header, body: B::Body) -> Self {
        Self::new_unhashed(B::new(header, body))
    }

    /// Creates the [`SealedBlock`] from the block's parts.
    pub fn from_parts_unchecked(header: B::Header, body: B::Body, hash: BlockHash) -> Self {
        Self::new_unchecked(B::new(header, body), hash)
    }

    /// Creates the [`SealedBlock`] from the [`SealedHeader`] and the body.
    pub fn from_sealed_parts(header: SealedHeader<B::Header>, body: B::Body) -> Self {
        let (header, hash) = header.split();
        Self::from_parts_unchecked(header, body, hash)
    }

    /// Returns a reference to the block hash.
    #[inline]
    pub fn hash_ref(&self) -> &BlockHash {
        self.header.hash_ref()
    }

    /// Returns the block hash.
    #[inline]
    pub fn hash(&self) -> B256 {
        self.header.hash()
    }

    /// Consumes the type and returns its components.
    #[doc(alias = "into_components")]
    pub fn split(self) -> (B, BlockHash) {
        let (header, hash) = self.header.split();
        (B::new(header, self.body), hash)
    }

    /// Consumes the type and returns the block.
    pub fn into_block(self) -> B {
        self.unseal()
    }

    /// Consumes the type and returns the block.
    pub fn unseal(self) -> B {
        let header = self.header.unseal();
        B::new(header, self.body)
    }

    /// Clones the wrapped block.
    pub fn clone_block(&self) -> B {
        B::new(self.header.clone_header(), self.body.clone())
    }

    /// Converts this block into a [`RecoveredBlock`] with the given senders
    ///
    /// Note: This method assumes the senders are correct and does not validate them.
    pub const fn with_senders(self, senders: Vec<Address>) -> RecoveredBlock<B> {
        RecoveredBlock::new_sealed(self, senders)
    }

    /// Converts this block into a [`RecoveredBlock`] with the given senders if the number of
    /// senders is equal to the number of transactions in the block and recovers the senders from
    /// the transactions, if
    /// not using [`SignedTransaction::recover_signer`](crate::transaction::signed::SignedTransaction)
    /// to recover the senders.
    ///
    /// Returns an error if any of the transactions fail to recover the sender.
    pub fn try_with_senders(
        self,
        senders: Vec<Address>,
    ) -> Result<RecoveredBlock<B>, BlockRecoveryError<Self>> {
        RecoveredBlock::try_recover_sealed_with_senders(self, senders)
    }

    /// Converts this block into a [`RecoveredBlock`] with the given senders if the number of
    /// senders is equal to the number of transactions in the block and recovers the senders from
    /// the transactions, if
    /// not using [`SignedTransaction::recover_signer_unchecked`](crate::transaction::signed::SignedTransaction)
    /// to recover the senders.
    ///
    /// Returns an error if any of the transactions fail to recover the sender.
    pub fn try_with_senders_unchecked(
        self,
        senders: Vec<Address>,
    ) -> Result<RecoveredBlock<B>, BlockRecoveryError<Self>> {
        RecoveredBlock::try_recover_sealed_with_senders_unchecked(self, senders)
    }

    /// Recovers the senders from the transactions in the block using
    /// [`SignedTransaction::recover_signer`](crate::transaction::signed::SignedTransaction).
    ///
    /// Returns an error if any of the transactions fail to recover the sender.
    pub fn try_recover(self) -> Result<RecoveredBlock<B>, BlockRecoveryError<Self>> {
        RecoveredBlock::try_recover_sealed(self)
    }

    /// Recovers the senders from the transactions in the block using
    /// [`SignedTransaction::recover_signer_unchecked`](crate::transaction::signed::SignedTransaction).
    ///
    /// Returns an error if any of the transactions fail to recover the sender.
    pub fn try_recover_unchecked(self) -> Result<RecoveredBlock<B>, BlockRecoveryError<Self>> {
        RecoveredBlock::try_recover_sealed_unchecked(self)
    }

    /// Returns reference to block header.
    pub const fn header(&self) -> &B::Header {
        self.header.header()
    }

    /// Returns reference to block body.
    pub const fn body(&self) -> &B::Body {
        &self.body
    }

    /// Returns the length of the block.
    pub fn rlp_length(&self) -> usize {
        B::rlp_length(self.header(), self.body())
    }

    /// Recovers all senders from the transactions in the block.
    ///
    /// Returns an error if any of the transactions fail to recover the sender.
    pub fn senders(&self) -> Result<Vec<Address>, RecoveryError> {
        self.body().recover_signers()
    }

    /// Return the number hash tuple.
    pub fn num_hash(&self) -> BlockNumHash {
        BlockNumHash::new(self.number(), self.hash())
    }

    /// Return a [`BlockWithParent`] for this header.
    pub fn block_with_parent(&self) -> BlockWithParent {
        BlockWithParent { parent: self.parent_hash(), block: self.num_hash() }
    }

    /// Returns the Sealed header.
    pub const fn sealed_header(&self) -> &SealedHeader<B::Header> {
        &self.header
    }

    /// Returns the wrapped `SealedHeader<B::Header>` as `SealedHeader<&B::Header>`.
    pub fn sealed_header_ref(&self) -> SealedHeader<&B::Header> {
        SealedHeader::new(self.header(), self.hash())
    }

    /// Clones the wrapped header and returns a [`SealedHeader`] sealed with the hash.
    pub fn clone_sealed_header(&self) -> SealedHeader<B::Header> {
        self.header.clone()
    }

    /// Consumes the block and returns the sealed header.
    pub fn into_sealed_header(self) -> SealedHeader<B::Header> {
        self.header
    }

    /// Consumes the block and returns the header.
    pub fn into_header(self) -> B::Header {
        self.header.unseal()
    }

    /// Consumes the block and returns the body.
    pub fn into_body(self) -> B::Body {
        self.body
    }

    /// Splits the block into body and header into separate components
    pub fn split_header_body(self) -> (B::Header, B::Body) {
        let header = self.header.unseal();
        (header, self.body)
    }

    /// Splits the block into body and header into separate components.
    pub fn split_sealed_header_body(self) -> (SealedHeader<B::Header>, B::Body) {
        (self.header, self.body)
    }

    /// Returns an iterator over all blob versioned hashes from the block body.
    #[inline]
    pub fn blob_versioned_hashes_iter(&self) -> impl Iterator<Item = &B256> + '_ {
        self.body().blob_versioned_hashes_iter()
    }

    /// Returns the number of transactions in the block.
    #[inline]
    pub fn transaction_count(&self) -> usize {
        self.body().transaction_count()
    }

    /// Ensures that the transaction root in the block header is valid.
    ///
    /// The transaction root is the Keccak 256-bit hash of the root node of the trie structure
    /// populated with each transaction in the transactions list portion of the block.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the calculated transaction root matches the one stored in the header,
    /// indicating that the transactions in the block are correctly represented in the trie.
    ///
    /// Returns `Err(error)` if the transaction root validation fails, providing a `GotExpected`
    /// error containing the calculated and expected roots.
    pub fn ensure_transaction_root_valid(&self) -> Result<(), GotExpected<B256>> {
        let calculated_root = self.body().calculate_tx_root();

        if self.header().transactions_root() != calculated_root {
            return Err(GotExpected {
                got: calculated_root,
                expected: self.header().transactions_root(),
            })
        }

        Ok(())
    }
}

impl<B> From<B> for SealedBlock<B>
where
    B: Block,
{
    fn from(block: B) -> Self {
        Self::seal_slow(block)
    }
}

impl<B> Default for SealedBlock<B>
where
    B: Block + Default,
{
    fn default() -> Self {
        Self::seal_slow(Default::default())
    }
}

impl<B: Block> InMemorySize for SealedBlock<B> {
    #[inline]
    fn size(&self) -> usize {
        self.body.size() + self.header.size()
    }
}

impl<B: Block> Deref for SealedBlock<B> {
    type Target = B::Header;

    fn deref(&self) -> &Self::Target {
        self.header()
    }
}

impl<B: Block> Encodable for SealedBlock<B> {
    fn encode(&self, out: &mut dyn BufMut) {
        // TODO: https://github.com/paradigmxyz/reth/issues/18002
        self.clone().into_block().encode(out);
    }
}

impl<B: Block> Decodable for SealedBlock<B> {
    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        let block = B::decode(buf)?;
        Ok(Self::seal_slow(block))
    }
}

impl<B: Block> From<SealedBlock<B>> for Sealed<B> {
    fn from(value: SealedBlock<B>) -> Self {
        let (block, hash) = value.split();
        Self::new_unchecked(block, hash)
    }
}

impl<B: Block> From<Sealed<B>> for SealedBlock<B> {
    fn from(value: Sealed<B>) -> Self {
        let (block, hash) = value.into_parts();
        Self::new_unchecked(block, hash)
    }
}

impl<T, H> SealedBlock<alloy_consensus::Block<T, H>>
where
    T: Decodable + SignedTransaction,
    H: BlockHeader,
{
    /// Decodes the block from RLP, computing the header hash directly from the RLP bytes.
    ///
    /// This is more efficient than decoding and then sealing, as the header hash is computed
    /// from the raw RLP bytes without re-encoding.
    ///
    /// This leverages [`alloy_consensus::Block::decode_sealed`].
    pub fn decode_sealed(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        let sealed = alloy_consensus::Block::<T, H>::decode_sealed(buf)?;
        let (block, hash) = sealed.into_parts();
        Ok(Self::new_unchecked(block, hash))
    }
}

#[cfg(any(test, feature = "arbitrary"))]
impl<'a, B> arbitrary::Arbitrary<'a> for SealedBlock<B>
where
    B: Block + arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let block = B::arbitrary(u)?;
        Ok(Self::seal_slow(block))
    }
}

#[cfg(any(test, feature = "test-utils"))]
impl<B: crate::test_utils::TestBlock> SealedBlock<B> {
    /// Returns a mutable reference to the header.
    pub const fn header_mut(&mut self) -> &mut B::Header {
        self.header.header_mut()
    }

    /// Updates the block hash.
    pub fn set_hash(&mut self, hash: BlockHash) {
        self.header.set_hash(hash)
    }

    /// Returns a mutable reference to the body.
    pub const fn body_mut(&mut self) -> &mut B::Body {
        &mut self.body
    }

    /// Updates the parent block hash.
    pub fn set_parent_hash(&mut self, hash: BlockHash) {
        self.header.set_parent_hash(hash)
    }

    /// Updates the block number.
    pub fn set_block_number(&mut self, number: alloy_primitives::BlockNumber) {
        self.header.set_block_number(number)
    }

    /// Updates the block timestamp.
    pub fn set_timestamp(&mut self, timestamp: u64) {
        self.header.set_timestamp(timestamp)
    }

    /// Updates the block state root.
    pub fn set_state_root(&mut self, state_root: alloy_primitives::B256) {
        self.header.set_state_root(state_root)
    }

    /// Updates the block difficulty.
    pub fn set_difficulty(&mut self, difficulty: alloy_primitives::U256) {
        self.header.set_difficulty(difficulty)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy_rlp::{Decodable, Encodable};

    #[test]
    fn test_sealed_block_rlp_roundtrip() {
        // Create a sample block using alloy_consensus::Block
        let header = alloy_consensus::Header {
            number: 42,
            gas_limit: 30_000_000,
            gas_used: 21_000,
            timestamp: 1_000_000,
            base_fee_per_gas: Some(1_000_000_000),
            ..Default::default()
        };

        // Create a simple transaction
        let tx = alloy_consensus::TxLegacy {
            chain_id: Some(1),
            nonce: 0,
            gas_price: 21_000_000_000,
            gas_limit: 21_000,
            to: alloy_primitives::TxKind::Call(Address::ZERO),
            value: alloy_primitives::U256::from(100),
            input: alloy_primitives::Bytes::default(),
        };

        let tx_signed =
            alloy_consensus::TxEnvelope::Legacy(alloy_consensus::Signed::new_unchecked(
                tx,
                alloy_primitives::Signature::test_signature(),
                B256::ZERO,
            ));

        // Create block body with the transaction
        let body = alloy_consensus::BlockBody {
            transactions: vec![tx_signed],
            ommers: vec![],
            withdrawals: Some(Default::default()),
        };

        // Create the block
        let block = alloy_consensus::Block::new(header, body);

        // Create a sealed block
        let sealed_block = SealedBlock::seal_slow(block);

        // Encode the sealed block
        let mut encoded = Vec::new();
        sealed_block.encode(&mut encoded);

        // Decode the sealed block
        let decoded = SealedBlock::<
            alloy_consensus::Block<alloy_consensus::TxEnvelope, alloy_consensus::Header>,
        >::decode(&mut encoded.as_slice())
        .expect("Failed to decode sealed block");

        // Verify the roundtrip
        assert_eq!(sealed_block.hash(), decoded.hash());
        assert_eq!(sealed_block.header().number, decoded.header().number);
        assert_eq!(sealed_block.header().state_root, decoded.header().state_root);
        assert_eq!(sealed_block.body().transactions.len(), decoded.body().transactions.len());
    }

    #[test]
    fn test_decode_sealed_produces_correct_hash() {
        // Create a sample block using alloy_consensus::Block
        let header = alloy_consensus::Header {
            number: 42,
            gas_limit: 30_000_000,
            gas_used: 21_000,
            timestamp: 1_000_000,
            base_fee_per_gas: Some(1_000_000_000),
            ..Default::default()
        };

        // Create a simple transaction
        let tx = alloy_consensus::TxLegacy {
            chain_id: Some(1),
            nonce: 0,
            gas_price: 21_000_000_000,
            gas_limit: 21_000,
            to: alloy_primitives::TxKind::Call(Address::ZERO),
            value: alloy_primitives::U256::from(100),
            input: alloy_primitives::Bytes::default(),
        };

        let tx_signed =
            alloy_consensus::TxEnvelope::Legacy(alloy_consensus::Signed::new_unchecked(
                tx,
                alloy_primitives::Signature::test_signature(),
                B256::ZERO,
            ));

        // Create block body with the transaction
        let body = alloy_consensus::BlockBody {
            transactions: vec![tx_signed],
            ommers: vec![],
            withdrawals: Some(Default::default()),
        };

        // Create the block
        let block = alloy_consensus::Block::new(header, body);
        let expected_hash = block.header.hash_slow();

        // Encode the block
        let mut encoded = Vec::new();
        block.encode(&mut encoded);

        // Decode using decode_sealed - this should compute hash from raw RLP
        let decoded =
            SealedBlock::<alloy_consensus::Block<alloy_consensus::TxEnvelope>>::decode_sealed(
                &mut encoded.as_slice(),
            )
            .expect("Failed to decode sealed block");

        // Verify the hash matches
        assert_eq!(decoded.hash(), expected_hash);
        assert_eq!(decoded.header().number, 42);
        assert_eq!(decoded.body().transactions.len(), 1);
    }

    #[test]
    fn test_sealed_block_from_sealed() {
        let header = alloy_consensus::Header::default();
        let body = alloy_consensus::BlockBody::<alloy_consensus::TxEnvelope>::default();
        let block = alloy_consensus::Block::new(header, body);
        let hash = block.header.hash_slow();

        // Create Sealed<Block>
        let sealed: Sealed<alloy_consensus::Block<alloy_consensus::TxEnvelope>> =
            Sealed::new_unchecked(block.clone(), hash);

        // Convert to SealedBlock
        let sealed_block: SealedBlock<alloy_consensus::Block<alloy_consensus::TxEnvelope>> =
            SealedBlock::from(sealed);

        assert_eq!(sealed_block.hash(), hash);
        assert_eq!(sealed_block.header().number, block.header.number);
    }
}