1mod header;
4pub use header::{BlockHeader, GasLimitMismatch, Header};
5
6mod traits;
7pub use traits::EthBlock;
8
9mod meta;
10pub use meta::{HeaderInfo, HeaderRoots};
11
12#[cfg(all(feature = "serde", feature = "serde-bincode-compat"))]
13pub(crate) use header::serde_bincode_compat;
14
15use crate::Transaction;
16use alloc::vec::Vec;
17use alloy_eips::{eip2718::WithEncoded, eip4895::Withdrawals, Encodable2718, Typed2718};
18use alloy_primitives::{keccak256, Sealable, Sealed, B256};
19use alloy_rlp::{Decodable, Encodable, RlpDecodable, RlpEncodable};
20
21#[derive(Debug, Clone, PartialEq, Eq, derive_more::Deref)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
30#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
31pub struct Block<T, H = Header> {
32 #[deref]
34 pub header: H,
35 pub body: BlockBody<T, H>,
37}
38
39impl<T, H> Block<T, H> {
40 pub const fn new(header: H, body: BlockBody<T, H>) -> Self {
42 Self { header, body }
43 }
44
45 pub fn uncle(header: H) -> Self {
47 Self { header, body: Default::default() }
48 }
49
50 pub fn into_header(self) -> H {
52 self.header
53 }
54
55 pub fn into_body(self) -> BlockBody<T, H> {
57 self.body
58 }
59
60 pub fn map_header<U>(self, mut f: impl FnMut(H) -> U) -> Block<T, U> {
62 Block { header: f(self.header), body: self.body.map_ommers(f) }
63 }
64
65 pub fn try_map_header<U, E>(
67 self,
68 mut f: impl FnMut(H) -> Result<U, E>,
69 ) -> Result<Block<T, U>, E> {
70 Ok(Block { header: f(self.header)?, body: self.body.try_map_ommers(f)? })
71 }
72
73 pub fn convert_transactions<U>(self) -> Block<U, H>
75 where
76 U: From<T>,
77 {
78 self.map_transactions(U::from)
79 }
80
81 pub fn try_convert_transactions<U>(self) -> Result<Block<U, H>, U::Error>
85 where
86 U: TryFrom<T>,
87 {
88 self.try_map_transactions(U::try_from)
89 }
90
91 pub fn map_transactions<U>(self, f: impl FnMut(T) -> U) -> Block<U, H> {
95 Block {
96 header: self.header,
97 body: BlockBody {
98 transactions: self.body.transactions.into_iter().map(f).collect(),
99 ommers: self.body.ommers,
100 withdrawals: self.body.withdrawals,
101 },
102 }
103 }
104
105 pub fn try_map_transactions<U, E>(
109 self,
110 f: impl FnMut(T) -> Result<U, E>,
111 ) -> Result<Block<U, H>, E> {
112 Ok(Block {
113 header: self.header,
114 body: BlockBody {
115 transactions: self
116 .body
117 .transactions
118 .into_iter()
119 .map(f)
120 .collect::<Result<_, _>>()?,
121 ommers: self.body.ommers,
122 withdrawals: self.body.withdrawals,
123 },
124 })
125 }
126
127 pub fn into_with_encoded2718(self) -> Block<WithEncoded<T>, H>
130 where
131 T: Encodable2718,
132 {
133 self.map_transactions(|tx| tx.into_encoded())
134 }
135
136 pub fn with_header(mut self, header: H) -> Self {
141 self.header = header;
142 self
143 }
144
145 pub fn rlp_encoded_from_parts(header: &H, body: &BlockBody<T, H>) -> Vec<u8>
151 where
152 H: Encodable,
153 T: Encodable,
154 {
155 let helper = block_rlp::HelperRef::from_parts(header, body);
156 let mut buf = Vec::with_capacity(helper.length());
157 helper.encode(&mut buf);
158 buf
159 }
160
161 pub fn rlp_encode_from_parts(
165 header: &H,
166 body: &BlockBody<T, H>,
167 out: &mut dyn alloy_rlp::bytes::BufMut,
168 ) where
169 H: Encodable,
170 T: Encodable,
171 {
172 block_rlp::HelperRef::from_parts(header, body).encode(out)
173 }
174
175 pub fn rlp_length_for(header: &H, body: &BlockBody<T, H>) -> usize
177 where
178 H: Encodable,
179 T: Encodable,
180 {
181 block_rlp::HelperRef::from_parts(header, body).length()
182 }
183}
184
185impl<T: Encodable2718> Block<T, Header> {
186 pub fn from_transactions(
194 mut header: Header,
195 transactions: impl IntoIterator<Item = T>,
196 ) -> Self {
197 let transactions: Vec<T> = transactions.into_iter().collect();
198 header.transactions_root = crate::proofs::calculate_transaction_root(&transactions);
199 header.ommers_hash = crate::EMPTY_OMMER_ROOT_HASH;
200 Self::new(header, BlockBody { transactions, ommers: Vec::new(), withdrawals: None })
201 }
202}
203
204impl<T, H> Default for Block<T, H>
205where
206 H: Default,
207{
208 fn default() -> Self {
209 Self { header: Default::default(), body: Default::default() }
210 }
211}
212
213impl<T, H> From<Block<T, H>> for BlockBody<T, H> {
214 fn from(block: Block<T, H>) -> Self {
215 block.into_body()
216 }
217}
218
219#[cfg(any(test, feature = "arbitrary"))]
220impl<'a, T, H> arbitrary::Arbitrary<'a> for Block<T, H>
221where
222 T: arbitrary::Arbitrary<'a>,
223 H: arbitrary::Arbitrary<'a>,
224{
225 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
226 Ok(Self { header: u.arbitrary()?, body: u.arbitrary()? })
227 }
228}
229
230#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
234#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
235#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
236#[rlp(trailing(no_gaps))]
237pub struct BlockBody<T, H = Header> {
238 pub transactions: Vec<T>,
240 pub ommers: Vec<H>,
242 pub withdrawals: Option<Withdrawals>,
244}
245
246impl<T, H> Default for BlockBody<T, H> {
247 fn default() -> Self {
248 Self { transactions: Vec::new(), ommers: Vec::new(), withdrawals: None }
249 }
250}
251
252impl<T, H> BlockBody<T, H> {
253 #[inline]
255 pub fn transactions(&self) -> impl Iterator<Item = &T> + '_ {
256 self.transactions.iter()
257 }
258
259 pub const fn into_block(self, header: H) -> Block<T, H> {
261 Block { header, body: self }
262 }
263
264 pub fn calculate_ommers_root(&self) -> B256
266 where
267 H: Encodable,
268 {
269 crate::proofs::calculate_ommers_root(&self.ommers)
270 }
271
272 pub fn ommers_hashes(&self) -> impl Iterator<Item = B256> + '_
274 where
275 H: Sealable,
276 {
277 self.ommers.iter().map(|h| h.hash_slow())
278 }
279
280 pub fn calculate_withdrawals_root(&self) -> Option<B256> {
283 self.withdrawals.as_ref().map(|w| crate::proofs::calculate_withdrawals_root(w))
284 }
285
286 pub fn map_ommers<U>(self, f: impl FnMut(H) -> U) -> BlockBody<T, U> {
288 BlockBody {
289 transactions: self.transactions,
290 ommers: self.ommers.into_iter().map(f).collect(),
291 withdrawals: self.withdrawals,
292 }
293 }
294
295 pub fn try_map_ommers<U, E>(
297 self,
298 f: impl FnMut(H) -> Result<U, E>,
299 ) -> Result<BlockBody<T, U>, E> {
300 Ok(BlockBody {
301 transactions: self.transactions,
302 ommers: self.ommers.into_iter().map(f).collect::<Result<Vec<_>, _>>()?,
303 withdrawals: self.withdrawals,
304 })
305 }
306}
307
308impl<T: Transaction, H> BlockBody<T, H> {
309 #[inline]
311 pub fn blob_versioned_hashes_iter(&self) -> impl Iterator<Item = &B256> + '_ {
312 self.eip4844_transactions_iter().filter_map(|tx| tx.blob_versioned_hashes()).flatten()
313 }
314}
315
316impl<T: Typed2718, H> BlockBody<T, H> {
317 #[inline]
319 pub fn has_eip4844_transactions(&self) -> bool {
320 self.transactions.iter().any(|tx| tx.is_eip4844())
321 }
322
323 #[inline]
325 pub fn has_eip7702_transactions(&self) -> bool {
326 self.transactions.iter().any(|tx| tx.is_eip7702())
327 }
328
329 #[inline]
331 pub fn eip4844_transactions_iter(&self) -> impl Iterator<Item = &T> + '_ {
332 self.transactions.iter().filter(|tx| tx.is_eip4844())
333 }
334}
335
336mod block_rlp {
339 use super::*;
340
341 #[derive(RlpDecodable)]
342 #[rlp(trailing(no_gaps))]
343 struct Helper<T, H> {
344 header: H,
345 transactions: Vec<T>,
346 ommers: Vec<H>,
347 withdrawals: Option<Withdrawals>,
348 }
349
350 #[derive(RlpEncodable)]
351 #[rlp(trailing(no_gaps))]
352 pub(crate) struct HelperRef<'a, T, H> {
353 pub(crate) header: &'a H,
354 pub(crate) transactions: &'a Vec<T>,
355 pub(crate) ommers: &'a Vec<H>,
356 pub(crate) withdrawals: Option<&'a Withdrawals>,
357 }
358
359 impl<'a, T, H> HelperRef<'a, T, H> {
360 pub(crate) const fn from_parts(header: &'a H, body: &'a BlockBody<T, H>) -> Self {
361 Self {
362 header,
363 transactions: &body.transactions,
364 ommers: &body.ommers,
365 withdrawals: body.withdrawals.as_ref(),
366 }
367 }
368 }
369
370 impl<'a, T, H> From<&'a Block<T, H>> for HelperRef<'a, T, H> {
371 fn from(block: &'a Block<T, H>) -> Self {
372 let Block { header, body: BlockBody { transactions, ommers, withdrawals } } = block;
373 Self { header, transactions, ommers, withdrawals: withdrawals.as_ref() }
374 }
375 }
376
377 impl<T: Encodable, H: Encodable> Encodable for Block<T, H> {
378 fn encode(&self, out: &mut dyn alloy_rlp::bytes::BufMut) {
379 let helper: HelperRef<'_, T, H> = self.into();
380 helper.encode(out)
381 }
382
383 fn length(&self) -> usize {
384 let helper: HelperRef<'_, T, H> = self.into();
385 helper.length()
386 }
387 }
388
389 impl<T: Decodable, H: Decodable> Decodable for Block<T, H> {
390 fn decode(b: &mut &[u8]) -> alloy_rlp::Result<Self> {
391 let Helper { header, transactions, ommers, withdrawals } = Helper::decode(b)?;
392 Ok(Self { header, body: BlockBody { transactions, ommers, withdrawals } })
393 }
394 }
395
396 impl<T: Decodable, H: Decodable> Block<T, H> {
397 pub fn decode_sealed(buf: &mut &[u8]) -> alloy_rlp::Result<Sealed<Self>> {
402 let block_rlp_head = alloy_rlp::Header::decode(buf)?;
404 if !block_rlp_head.list {
405 return Err(alloy_rlp::Error::UnexpectedString);
406 }
407
408 let header_start = *buf;
410 let header = H::decode(buf)?;
411 let header_hash = keccak256(&header_start[..header_start.len() - buf.len()]);
412
413 let transactions = Vec::<T>::decode(buf)?;
415 let ommers = Vec::<H>::decode(buf)?;
416 let withdrawals = if buf.is_empty() { None } else { Some(Decodable::decode(buf)?) };
417
418 let block = Self { header, body: BlockBody { transactions, ommers, withdrawals } };
419
420 Ok(Sealed::new_unchecked(block, header_hash))
421 }
422 }
423}
424
425#[cfg(any(test, feature = "arbitrary"))]
426impl<'a, T, H> arbitrary::Arbitrary<'a> for BlockBody<T, H>
427where
428 T: arbitrary::Arbitrary<'a>,
429 H: arbitrary::Arbitrary<'a>,
430{
431 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
432 let transactions = (0..u.int_in_range(0..=100)?)
434 .map(|_| T::arbitrary(u))
435 .collect::<arbitrary::Result<Vec<_>>>()?;
436
437 let ommers = (0..u.int_in_range(0..=1)?)
439 .map(|_| H::arbitrary(u))
440 .collect::<arbitrary::Result<Vec<_>>>()?;
441
442 Ok(Self { transactions, ommers, withdrawals: u.arbitrary()? })
443 }
444}
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449 use crate::{Signed, TxEnvelope, TxLegacy};
450 use alloy_rlp::{Decodable, Encodable};
451
452 #[test]
453 fn can_convert_block() {
454 let block: Block<Signed<TxLegacy>> = Block::default();
455 let _: Block<TxEnvelope> = block.convert_transactions();
456 }
457
458 #[test]
459 fn decode_sealed_produces_correct_hash() {
460 let block: Block<TxEnvelope> = Block::default();
461 let expected_hash = block.header.hash_slow();
462
463 let mut encoded = Vec::new();
464 block.encode(&mut encoded);
465
466 let mut buf = encoded.as_slice();
467 let sealed = Block::<TxEnvelope>::decode_sealed(&mut buf).unwrap();
468
469 assert_eq!(sealed.hash(), expected_hash);
470 assert_eq!(*sealed.inner(), block);
471 }
472
473 #[test]
474 fn header_decode_sealed_produces_correct_hash() {
475 let header = Header::default();
476 let expected_hash = header.hash_slow();
477
478 let mut encoded = Vec::new();
479 header.encode(&mut encoded);
480
481 let mut buf = encoded.as_slice();
482 let sealed = Header::decode_sealed(&mut buf).unwrap();
483
484 assert_eq!(sealed.hash(), expected_hash);
485 assert_eq!(*sealed.inner(), header);
486 assert!(buf.is_empty());
487 }
488
489 #[test]
490 fn decode_sealed_roundtrip_with_transactions() {
491 use crate::{SignableTransaction, TxLegacy};
492 use alloy_primitives::{Address, Signature, TxKind, U256};
493
494 let tx = TxLegacy {
495 nonce: 1,
496 gas_price: 100,
497 gas_limit: 21000,
498 to: TxKind::Call(Address::ZERO),
499 value: U256::from(1000),
500 input: Default::default(),
501 chain_id: Some(1),
502 };
503 let sig = Signature::new(U256::from(1), U256::from(2), false);
504 let signed = tx.into_signed(sig);
505 let envelope: TxEnvelope = signed.into();
506
507 let block = Block {
508 header: Header { number: 42, gas_limit: 30_000_000, ..Default::default() },
509 body: BlockBody { transactions: vec![envelope], ommers: vec![], withdrawals: None },
510 };
511
512 let expected_hash = block.header.hash_slow();
513
514 let mut encoded = Vec::new();
515 block.encode(&mut encoded);
516
517 let mut buf = encoded.as_slice();
518 let sealed = Block::<TxEnvelope>::decode_sealed(&mut buf).unwrap();
519
520 assert_eq!(sealed.hash(), expected_hash);
521 assert_eq!(sealed.header.number, 42);
522 assert_eq!(sealed.body.transactions.len(), 1);
523 assert!(buf.is_empty());
524 }
525
526 #[test]
527 fn block_body_rejects_present_string_withdrawals() {
528 let mut omitted: &[u8] = &[0xc2, 0xc0, 0xc0];
529 let body = BlockBody::<TxEnvelope>::decode(&mut omitted).unwrap();
530 assert!(body.withdrawals.is_none());
531 assert!(omitted.is_empty());
532
533 let mut present_empty: &[u8] = &[0xc3, 0xc0, 0xc0, 0xc0];
534 let body = BlockBody::<TxEnvelope>::decode(&mut present_empty).unwrap();
535 assert!(body.withdrawals.as_ref().is_some_and(|w| w.is_empty()));
536 assert!(present_empty.is_empty());
537
538 let mut present_string: &[u8] = &[0xc3, 0xc0, 0xc0, 0x80];
539 assert!(BlockBody::<TxEnvelope>::decode(&mut present_string).is_err());
540 }
541
542 #[test]
543 fn block_decoders_reject_present_string_withdrawals() {
544 fn block_rlp_with_body_fields(body_fields: &[u8]) -> Vec<u8> {
545 let mut header = Vec::new();
546 Header::default().encode(&mut header);
547
548 let block_header =
549 alloy_rlp::Header { list: true, payload_length: header.len() + body_fields.len() };
550 let mut out = Vec::with_capacity(block_header.length_with_payload());
551 block_header.encode(&mut out);
552 out.extend_from_slice(&header);
553 out.extend_from_slice(body_fields);
554 out
555 }
556
557 let omitted = block_rlp_with_body_fields(&[0xc0, 0xc0]);
558 assert!(Block::<TxEnvelope>::decode(&mut omitted.as_slice()).is_ok());
559 assert!(Block::<TxEnvelope>::decode_sealed(&mut omitted.as_slice()).is_ok());
560
561 let present_empty = block_rlp_with_body_fields(&[0xc0, 0xc0, 0xc0]);
562 assert!(Block::<TxEnvelope>::decode(&mut present_empty.as_slice()).is_ok());
563 assert!(Block::<TxEnvelope>::decode_sealed(&mut present_empty.as_slice()).is_ok());
564
565 let present_string = block_rlp_with_body_fields(&[0xc0, 0xc0, 0x80]);
566 assert!(Block::<TxEnvelope>::decode(&mut present_string.as_slice()).is_err());
567 assert!(Block::<TxEnvelope>::decode_sealed(&mut present_string.as_slice()).is_err());
568 }
569}
570
571#[cfg(all(test, feature = "arbitrary"))]
572mod fuzz_tests {
573 use super::*;
574 use crate::{EthereumTxEnvelope, TxEip4844};
575 use alloy_rlp::Encodable;
576 use arbitrary::{Arbitrary, Unstructured};
577 use rand::Rng;
578
579 #[test]
580 fn fuzz_decode_sealed_block_roundtrip() {
581 for _ in 0..10 {
582 let mut bytes = [0u8; 1024 * 1024];
583 rand::thread_rng().fill(bytes.as_mut_slice());
584 let mut u = Unstructured::new(&bytes);
585
586 let block = Block::<EthereumTxEnvelope<TxEip4844>>::arbitrary(&mut u).unwrap();
587 let expected_hash = block.header.hash_slow();
588
589 let mut encoded = Vec::new();
590 block.encode(&mut encoded);
591
592 let sealed =
593 Block::<EthereumTxEnvelope<TxEip4844>>::decode_sealed(&mut encoded.as_slice())
594 .unwrap();
595 assert_eq!(sealed.hash(), expected_hash);
596 assert_eq!(*sealed.inner(), block);
597 }
598 }
599
600 #[test]
601 fn fuzz_header_decode_sealed_roundtrip() {
602 for _ in 0..200 {
603 let mut bytes = [0u8; 1024];
604 rand::thread_rng().fill(bytes.as_mut_slice());
605 let mut u = Unstructured::new(&bytes);
606
607 let header = Header::arbitrary(&mut u).unwrap();
608 let expected_hash = header.hash_slow();
609
610 let mut encoded = Vec::new();
611 header.encode(&mut encoded);
612
613 let mut buf = encoded.as_slice();
614 let sealed = Header::decode_sealed(&mut buf).unwrap();
615
616 assert_eq!(sealed.hash(), expected_hash);
617 assert_eq!(*sealed.inner(), header);
618 }
619 }
620}