alloy-consensus 2.0.4

Ethereum consensus interface
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Block-related consensus types.

mod header;
pub use header::{BlockHeader, Header};

mod traits;
pub use traits::EthBlock;

mod meta;
pub use meta::{HeaderInfo, HeaderRoots};

#[cfg(all(feature = "serde", feature = "serde-bincode-compat"))]
pub(crate) use header::serde_bincode_compat;

use crate::Transaction;
use alloc::vec::Vec;
use alloy_eips::{eip2718::WithEncoded, eip4895::Withdrawals, Encodable2718, Typed2718};
use alloy_primitives::{keccak256, Sealable, Sealed, B256};
use alloy_rlp::{Decodable, Encodable, RlpDecodable, RlpEncodable};

/// Ethereum full block.
///
/// Withdrawals can be optionally included at the end of the RLP encoded message.
///
/// Taken from [reth-primitives](https://github.com/paradigmxyz/reth)
///
/// See p2p block encoding reference: <https://github.com/ethereum/devp2p/blob/master/caps/eth.md#block-encoding-and-validity>
#[derive(Debug, Clone, PartialEq, Eq, derive_more::Deref)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
pub struct Block<T, H = Header> {
    /// Block header.
    #[deref]
    pub header: H,
    /// Block body.
    pub body: BlockBody<T, H>,
}

impl<T, H> Block<T, H> {
    /// Creates a new block with the given header and body.
    pub const fn new(header: H, body: BlockBody<T, H>) -> Self {
        Self { header, body }
    }

    /// Creates a new empty uncle block.
    pub fn uncle(header: H) -> Self {
        Self { header, body: Default::default() }
    }

    /// Consumes the block and returns the header.
    pub fn into_header(self) -> H {
        self.header
    }

    /// Consumes the block and returns the body.
    pub fn into_body(self) -> BlockBody<T, H> {
        self.body
    }

    /// Converts the block's header type by applying a function to it.
    pub fn map_header<U>(self, mut f: impl FnMut(H) -> U) -> Block<T, U> {
        Block { header: f(self.header), body: self.body.map_ommers(f) }
    }

    /// Converts the block's header type by applying a fallible function to it.
    pub fn try_map_header<U, E>(
        self,
        mut f: impl FnMut(H) -> Result<U, E>,
    ) -> Result<Block<T, U>, E> {
        Ok(Block { header: f(self.header)?, body: self.body.try_map_ommers(f)? })
    }

    /// Converts the block's transaction type to the given alternative that is `From<T>`
    pub fn convert_transactions<U>(self) -> Block<U, H>
    where
        U: From<T>,
    {
        self.map_transactions(U::from)
    }

    /// Converts the block's transaction to the given alternative that is `TryFrom<T>`
    ///
    /// Returns the block with the new transaction type if all conversions were successful.
    pub fn try_convert_transactions<U>(self) -> Result<Block<U, H>, U::Error>
    where
        U: TryFrom<T>,
    {
        self.try_map_transactions(U::try_from)
    }

    /// Converts the block's transaction type by applying a function to each transaction.
    ///
    /// Returns the block with the new transaction type.
    pub fn map_transactions<U>(self, f: impl FnMut(T) -> U) -> Block<U, H> {
        Block {
            header: self.header,
            body: BlockBody {
                transactions: self.body.transactions.into_iter().map(f).collect(),
                ommers: self.body.ommers,
                withdrawals: self.body.withdrawals,
            },
        }
    }

    /// Converts the block's transaction type by applying a fallible function to each transaction.
    ///
    /// Returns the block with the new transaction type if all transactions were successfully.
    pub fn try_map_transactions<U, E>(
        self,
        f: impl FnMut(T) -> Result<U, E>,
    ) -> Result<Block<U, H>, E> {
        Ok(Block {
            header: self.header,
            body: BlockBody {
                transactions: self
                    .body
                    .transactions
                    .into_iter()
                    .map(f)
                    .collect::<Result<_, _>>()?,
                ommers: self.body.ommers,
                withdrawals: self.body.withdrawals,
            },
        })
    }

    /// Converts the transactions in the block's body to `WithEncoded<T>` by encoding them via
    /// [`Encodable2718`]
    pub fn into_with_encoded2718(self) -> Block<WithEncoded<T>, H>
    where
        T: Encodable2718,
    {
        self.map_transactions(|tx| tx.into_encoded())
    }

    /// Replaces the header of the block.
    ///
    /// Note: This method only replaces the main block header. If you need to transform
    /// the ommer headers as well, use [`map_header`](Self::map_header) instead.
    pub fn with_header(mut self, header: H) -> Self {
        self.header = header;
        self
    }

    /// Encodes the [`Block`] given header and block body.
    ///
    /// Returns the rlp encoded block.
    ///
    /// This is equivalent to `block.encode`.
    pub fn rlp_encoded_from_parts(header: &H, body: &BlockBody<T, H>) -> Vec<u8>
    where
        H: Encodable,
        T: Encodable,
    {
        let helper = block_rlp::HelperRef::from_parts(header, body);
        let mut buf = Vec::with_capacity(helper.length());
        helper.encode(&mut buf);
        buf
    }

    /// Encodes the [`Block`] given header and block body
    ///
    /// This is equivalent to `block.encode`.
    pub fn rlp_encode_from_parts(
        header: &H,
        body: &BlockBody<T, H>,
        out: &mut dyn alloy_rlp::bytes::BufMut,
    ) where
        H: Encodable,
        T: Encodable,
    {
        block_rlp::HelperRef::from_parts(header, body).encode(out)
    }

    /// Returns the RLP encoded length of the block's header and body.
    pub fn rlp_length_for(header: &H, body: &BlockBody<T, H>) -> usize
    where
        H: Encodable,
        T: Encodable,
    {
        block_rlp::HelperRef::from_parts(header, body).length()
    }
}

impl<T: Encodable2718> Block<T, Header> {
    /// Creates a new block from a header and an iterator of transactions.
    ///
    /// Computes and sets the `transactions_root` on the header automatically.
    /// `ommers_hash` is set to [`EMPTY_OMMER_ROOT_HASH`](crate::EMPTY_OMMER_ROOT_HASH).
    pub fn from_transactions(
        mut header: Header,
        transactions: impl IntoIterator<Item = T>,
    ) -> Self {
        let transactions: Vec<T> = transactions.into_iter().collect();
        header.transactions_root = crate::proofs::calculate_transaction_root(&transactions);
        header.ommers_hash = crate::EMPTY_OMMER_ROOT_HASH;
        Self::new(header, BlockBody { transactions, ommers: Vec::new(), withdrawals: None })
    }
}

impl<T, H> Default for Block<T, H>
where
    H: Default,
{
    fn default() -> Self {
        Self { header: Default::default(), body: Default::default() }
    }
}

impl<T, H> From<Block<T, H>> for BlockBody<T, H> {
    fn from(block: Block<T, H>) -> Self {
        block.into_body()
    }
}

#[cfg(any(test, feature = "arbitrary"))]
impl<'a, T, H> arbitrary::Arbitrary<'a> for Block<T, H>
where
    T: arbitrary::Arbitrary<'a>,
    H: arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        Ok(Self { header: u.arbitrary()?, body: u.arbitrary()? })
    }
}

/// A response to `GetBlockBodies`, containing bodies if any bodies were found.
///
/// Withdrawals can be optionally included at the end of the RLP encoded message.
#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
#[rlp(trailing)]
pub struct BlockBody<T, H = Header> {
    /// Transactions in this block.
    pub transactions: Vec<T>,
    /// Ommers/uncles header.
    pub ommers: Vec<H>,
    /// Block withdrawals.
    pub withdrawals: Option<Withdrawals>,
}

impl<T, H> Default for BlockBody<T, H> {
    fn default() -> Self {
        Self { transactions: Vec::new(), ommers: Vec::new(), withdrawals: None }
    }
}

impl<T, H> BlockBody<T, H> {
    /// Returns an iterator over all transactions.
    #[inline]
    pub fn transactions(&self) -> impl Iterator<Item = &T> + '_ {
        self.transactions.iter()
    }

    /// Create a [`Block`] from the body and its header.
    pub const fn into_block(self, header: H) -> Block<T, H> {
        Block { header, body: self }
    }

    /// Calculate the ommers root for the block body.
    pub fn calculate_ommers_root(&self) -> B256
    where
        H: Encodable,
    {
        crate::proofs::calculate_ommers_root(&self.ommers)
    }

    /// Returns an iterator over the hashes of the ommers in the block body.
    pub fn ommers_hashes(&self) -> impl Iterator<Item = B256> + '_
    where
        H: Sealable,
    {
        self.ommers.iter().map(|h| h.hash_slow())
    }

    /// Calculate the withdrawals root for the block body, if withdrawals exist. If there are no
    /// withdrawals, this will return `None`.
    pub fn calculate_withdrawals_root(&self) -> Option<B256> {
        self.withdrawals.as_ref().map(|w| crate::proofs::calculate_withdrawals_root(w))
    }

    /// Converts the body's ommers type by applying a function to it.
    pub fn map_ommers<U>(self, f: impl FnMut(H) -> U) -> BlockBody<T, U> {
        BlockBody {
            transactions: self.transactions,
            ommers: self.ommers.into_iter().map(f).collect(),
            withdrawals: self.withdrawals,
        }
    }

    /// Converts the body's ommers type by applying a fallible function to it.
    pub fn try_map_ommers<U, E>(
        self,
        f: impl FnMut(H) -> Result<U, E>,
    ) -> Result<BlockBody<T, U>, E> {
        Ok(BlockBody {
            transactions: self.transactions,
            ommers: self.ommers.into_iter().map(f).collect::<Result<Vec<_>, _>>()?,
            withdrawals: self.withdrawals,
        })
    }
}

impl<T: Transaction, H> BlockBody<T, H> {
    /// 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.eip4844_transactions_iter().filter_map(|tx| tx.blob_versioned_hashes()).flatten()
    }
}

impl<T: Typed2718, H> BlockBody<T, H> {
    /// Returns whether or not the block body contains any blob transactions.
    #[inline]
    pub fn has_eip4844_transactions(&self) -> bool {
        self.transactions.iter().any(|tx| tx.is_eip4844())
    }

    /// Returns whether or not the block body contains any EIP-7702 transactions.
    #[inline]
    pub fn has_eip7702_transactions(&self) -> bool {
        self.transactions.iter().any(|tx| tx.is_eip7702())
    }

    /// Returns an iterator over all blob transactions of the block.
    #[inline]
    pub fn eip4844_transactions_iter(&self) -> impl Iterator<Item = &T> + '_ {
        self.transactions.iter().filter(|tx| tx.is_eip4844())
    }
}

/// We need to implement RLP traits manually because we currently don't have a way to flatten
/// [`BlockBody`] into [`Block`].
mod block_rlp {
    use super::*;

    #[derive(RlpDecodable)]
    #[rlp(trailing)]
    struct Helper<T, H> {
        header: H,
        transactions: Vec<T>,
        ommers: Vec<H>,
        withdrawals: Option<Withdrawals>,
    }

    #[derive(RlpEncodable)]
    #[rlp(trailing)]
    pub(crate) struct HelperRef<'a, T, H> {
        pub(crate) header: &'a H,
        pub(crate) transactions: &'a Vec<T>,
        pub(crate) ommers: &'a Vec<H>,
        pub(crate) withdrawals: Option<&'a Withdrawals>,
    }

    impl<'a, T, H> HelperRef<'a, T, H> {
        pub(crate) const fn from_parts(header: &'a H, body: &'a BlockBody<T, H>) -> Self {
            Self {
                header,
                transactions: &body.transactions,
                ommers: &body.ommers,
                withdrawals: body.withdrawals.as_ref(),
            }
        }
    }

    impl<'a, T, H> From<&'a Block<T, H>> for HelperRef<'a, T, H> {
        fn from(block: &'a Block<T, H>) -> Self {
            let Block { header, body: BlockBody { transactions, ommers, withdrawals } } = block;
            Self { header, transactions, ommers, withdrawals: withdrawals.as_ref() }
        }
    }

    impl<T: Encodable, H: Encodable> Encodable for Block<T, H> {
        fn encode(&self, out: &mut dyn alloy_rlp::bytes::BufMut) {
            let helper: HelperRef<'_, T, H> = self.into();
            helper.encode(out)
        }

        fn length(&self) -> usize {
            let helper: HelperRef<'_, T, H> = self.into();
            helper.length()
        }
    }

    impl<T: Decodable, H: Decodable> Decodable for Block<T, H> {
        fn decode(b: &mut &[u8]) -> alloy_rlp::Result<Self> {
            let Helper { header, transactions, ommers, withdrawals } = Helper::decode(b)?;
            Ok(Self { header, body: BlockBody { transactions, ommers, withdrawals } })
        }
    }

    impl<T: Decodable, H: Decodable> Block<T, H> {
        /// Decodes the block from RLP, computing the header hash directly from the RLP bytes.
        ///
        /// This is more efficient than decoding the block and then sealing it, as the header
        /// hash is computed from the raw RLP bytes without re-encoding.
        pub fn decode_sealed(buf: &mut &[u8]) -> alloy_rlp::Result<Sealed<Self>> {
            // Decode the outer block list header
            let block_rlp_head = alloy_rlp::Header::decode(buf)?;
            if !block_rlp_head.list {
                return Err(alloy_rlp::Error::UnexpectedString);
            }

            // Decode header and compute hash from raw RLP bytes
            let header_start = *buf;
            let header = H::decode(buf)?;
            let header_hash = keccak256(&header_start[..header_start.len() - buf.len()]);

            // Decode remaining body fields
            let transactions = Vec::<T>::decode(buf)?;
            let ommers = Vec::<H>::decode(buf)?;
            let withdrawals = if buf.is_empty() { None } else { Some(Decodable::decode(buf)?) };

            let block = Self { header, body: BlockBody { transactions, ommers, withdrawals } };

            Ok(Sealed::new_unchecked(block, header_hash))
        }
    }
}

#[cfg(any(test, feature = "arbitrary"))]
impl<'a, T, H> arbitrary::Arbitrary<'a> for BlockBody<T, H>
where
    T: arbitrary::Arbitrary<'a>,
    H: arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        // first generate up to 100 txs
        let transactions = (0..u.int_in_range(0..=100)?)
            .map(|_| T::arbitrary(u))
            .collect::<arbitrary::Result<Vec<_>>>()?;

        // then generate up to 2 ommers
        let ommers = (0..u.int_in_range(0..=1)?)
            .map(|_| H::arbitrary(u))
            .collect::<arbitrary::Result<Vec<_>>>()?;

        Ok(Self { transactions, ommers, withdrawals: u.arbitrary()? })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Signed, TxEnvelope, TxLegacy};
    use alloy_rlp::Encodable;

    #[test]
    fn can_convert_block() {
        let block: Block<Signed<TxLegacy>> = Block::default();
        let _: Block<TxEnvelope> = block.convert_transactions();
    }

    #[test]
    fn decode_sealed_produces_correct_hash() {
        let block: Block<TxEnvelope> = Block::default();
        let expected_hash = block.header.hash_slow();

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

        let mut buf = encoded.as_slice();
        let sealed = Block::<TxEnvelope>::decode_sealed(&mut buf).unwrap();

        assert_eq!(sealed.hash(), expected_hash);
        assert_eq!(*sealed.inner(), block);
    }

    #[test]
    fn header_decode_sealed_produces_correct_hash() {
        let header = Header::default();
        let expected_hash = header.hash_slow();

        let mut encoded = Vec::new();
        header.encode(&mut encoded);

        let mut buf = encoded.as_slice();
        let sealed = Header::decode_sealed(&mut buf).unwrap();

        assert_eq!(sealed.hash(), expected_hash);
        assert_eq!(*sealed.inner(), header);
        assert!(buf.is_empty());
    }

    #[test]
    fn decode_sealed_roundtrip_with_transactions() {
        use crate::{SignableTransaction, TxLegacy};
        use alloy_primitives::{Address, Signature, TxKind, U256};

        let tx = TxLegacy {
            nonce: 1,
            gas_price: 100,
            gas_limit: 21000,
            to: TxKind::Call(Address::ZERO),
            value: U256::from(1000),
            input: Default::default(),
            chain_id: Some(1),
        };
        let sig = Signature::new(U256::from(1), U256::from(2), false);
        let signed = tx.into_signed(sig);
        let envelope: TxEnvelope = signed.into();

        let block = Block {
            header: Header { number: 42, gas_limit: 30_000_000, ..Default::default() },
            body: BlockBody { transactions: vec![envelope], ommers: vec![], withdrawals: None },
        };

        let expected_hash = block.header.hash_slow();

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

        let mut buf = encoded.as_slice();
        let sealed = Block::<TxEnvelope>::decode_sealed(&mut buf).unwrap();

        assert_eq!(sealed.hash(), expected_hash);
        assert_eq!(sealed.header.number, 42);
        assert_eq!(sealed.body.transactions.len(), 1);
        assert!(buf.is_empty());
    }
}

#[cfg(all(test, feature = "arbitrary"))]
mod fuzz_tests {
    use super::*;
    use crate::{EthereumTxEnvelope, TxEip4844};
    use alloy_rlp::Encodable;
    use arbitrary::{Arbitrary, Unstructured};
    use rand::Rng;

    #[test]
    fn fuzz_decode_sealed_block_roundtrip() {
        for _ in 0..10 {
            let mut bytes = [0u8; 1024 * 1024];
            rand::thread_rng().fill(bytes.as_mut_slice());
            let mut u = Unstructured::new(&bytes);

            let block = Block::<EthereumTxEnvelope<TxEip4844>>::arbitrary(&mut u).unwrap();
            let expected_hash = block.header.hash_slow();

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

            let sealed =
                Block::<EthereumTxEnvelope<TxEip4844>>::decode_sealed(&mut encoded.as_slice())
                    .unwrap();
            assert_eq!(sealed.hash(), expected_hash);
            assert_eq!(*sealed.inner(), block);
        }
    }

    #[test]
    fn fuzz_header_decode_sealed_roundtrip() {
        for _ in 0..200 {
            let mut bytes = [0u8; 1024];
            rand::thread_rng().fill(bytes.as_mut_slice());
            let mut u = Unstructured::new(&bytes);

            let header = Header::arbitrary(&mut u).unwrap();
            let expected_hash = header.hash_slow();

            let mut encoded = Vec::new();
            header.encode(&mut encoded);

            let mut buf = encoded.as_slice();
            let sealed = Header::decode_sealed(&mut buf).unwrap();

            assert_eq!(sealed.hash(), expected_hash);
            assert_eq!(*sealed.inner(), header);
        }
    }
}