reth_codecs/alloy/
header.rs

1//! Compact implementation for [`AlloyHeader`]
2
3use crate::Compact;
4use alloy_consensus::Header as AlloyHeader;
5use alloy_primitives::{Address, BlockNumber, Bloom, Bytes, B256, U256};
6
7/// Block header
8///
9/// This is a helper type to use derive on it instead of manually managing `bitfield`.
10///
11/// By deriving `Compact` here, any future changes or enhancements to the `Compact` derive
12/// will automatically apply to this type.
13///
14/// Notice: Make sure this struct is 1:1 with [`alloy_consensus::Header`]
15#[cfg_attr(
16    any(test, feature = "test-utils"),
17    derive(serde::Serialize, serde::Deserialize, arbitrary::Arbitrary)
18)]
19#[cfg_attr(feature = "test-utils", allow(unreachable_pub), visibility::make(pub))]
20#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Compact)]
21#[reth_codecs(crate = "crate")]
22pub(crate) struct Header {
23    parent_hash: B256,
24    ommers_hash: B256,
25    beneficiary: Address,
26    state_root: B256,
27    transactions_root: B256,
28    receipts_root: B256,
29    withdrawals_root: Option<B256>,
30    logs_bloom: Bloom,
31    difficulty: U256,
32    number: BlockNumber,
33    gas_limit: u64,
34    gas_used: u64,
35    timestamp: u64,
36    mix_hash: B256,
37    nonce: u64,
38    base_fee_per_gas: Option<u64>,
39    blob_gas_used: Option<u64>,
40    excess_blob_gas: Option<u64>,
41    parent_beacon_block_root: Option<B256>,
42    extra_fields: Option<HeaderExt>,
43    extra_data: Bytes,
44}
45
46/// [`Header`] extension struct.
47///
48/// All new fields should be added here in the form of a `Option<T>`, since `Option<HeaderExt>` is
49/// used as a field of [`Header`] for backwards compatibility.
50///
51/// More information: <https://github.com/paradigmxyz/reth/issues/7820> & [`reth_codecs_derive::Compact`].
52#[cfg_attr(
53    any(test, feature = "test-utils"),
54    derive(serde::Serialize, serde::Deserialize, arbitrary::Arbitrary)
55)]
56#[cfg_attr(feature = "test-utils", allow(unreachable_pub), visibility::make(pub))]
57#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Compact)]
58#[reth_codecs(crate = "crate")]
59pub(crate) struct HeaderExt {
60    requests_hash: Option<B256>,
61}
62
63impl HeaderExt {
64    /// Converts into [`Some`] if any of the field exists. Otherwise, returns [`None`].
65    ///
66    /// Required since [`Header`] uses `Option<HeaderExt>` as a field.
67    const fn into_option(self) -> Option<Self> {
68        if self.requests_hash.is_some() {
69            Some(self)
70        } else {
71            None
72        }
73    }
74}
75
76impl Compact for AlloyHeader {
77    fn to_compact<B>(&self, buf: &mut B) -> usize
78    where
79        B: bytes::BufMut + AsMut<[u8]>,
80    {
81        let extra_fields = HeaderExt { requests_hash: self.requests_hash };
82
83        let header = Header {
84            parent_hash: self.parent_hash,
85            ommers_hash: self.ommers_hash,
86            beneficiary: self.beneficiary,
87            state_root: self.state_root,
88            transactions_root: self.transactions_root,
89            receipts_root: self.receipts_root,
90            withdrawals_root: self.withdrawals_root,
91            logs_bloom: self.logs_bloom,
92            difficulty: self.difficulty,
93            number: self.number,
94            gas_limit: self.gas_limit,
95            gas_used: self.gas_used,
96            timestamp: self.timestamp,
97            mix_hash: self.mix_hash,
98            nonce: self.nonce.into(),
99            base_fee_per_gas: self.base_fee_per_gas,
100            blob_gas_used: self.blob_gas_used,
101            excess_blob_gas: self.excess_blob_gas,
102            parent_beacon_block_root: self.parent_beacon_block_root,
103            extra_fields: extra_fields.into_option(),
104            extra_data: self.extra_data.clone(),
105        };
106        header.to_compact(buf)
107    }
108
109    fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {
110        let (header, _) = Header::from_compact(buf, len);
111        let alloy_header = Self {
112            parent_hash: header.parent_hash,
113            ommers_hash: header.ommers_hash,
114            beneficiary: header.beneficiary,
115            state_root: header.state_root,
116            transactions_root: header.transactions_root,
117            receipts_root: header.receipts_root,
118            withdrawals_root: header.withdrawals_root,
119            logs_bloom: header.logs_bloom,
120            difficulty: header.difficulty,
121            number: header.number,
122            gas_limit: header.gas_limit,
123            gas_used: header.gas_used,
124            timestamp: header.timestamp,
125            mix_hash: header.mix_hash,
126            nonce: header.nonce.into(),
127            base_fee_per_gas: header.base_fee_per_gas,
128            blob_gas_used: header.blob_gas_used,
129            excess_blob_gas: header.excess_blob_gas,
130            parent_beacon_block_root: header.parent_beacon_block_root,
131            requests_hash: header.extra_fields.as_ref().and_then(|h| h.requests_hash),
132            extra_data: header.extra_data,
133        };
134        (alloy_header, buf)
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141    use alloy_consensus::EMPTY_OMMER_ROOT_HASH;
142    use alloy_primitives::{address, b256, bloom, bytes, hex};
143
144    /// Holesky block #1947953
145    const HOLESKY_BLOCK: Header = Header {
146        parent_hash: b256!("0x8605e0c46689f66b3deed82598e43d5002b71a929023b665228728f0c6e62a95"),
147        ommers_hash: EMPTY_OMMER_ROOT_HASH,
148        beneficiary: address!("0xc6e2459991bfe27cca6d86722f35da23a1e4cb97"),
149        state_root: b256!("0xedad188ca5647d62f4cca417c11a1afbadebce30d23260767f6f587e9b3b9993"),
150        transactions_root: b256!("0x4daf25dc08a841aa22aa0d3cb3e1f159d4dcaf6a6063d4d36bfac11d3fdb63ee"),
151        receipts_root: b256!("0x1a1500328e8ade2592bbea1e04f9a9fd8c0142d3175d6e8420984ee159abd0ed"),
152        withdrawals_root: Some(b256!("0xd0f7f22d6d915be5a3b9c0fee353f14de5ac5c8ac1850b76ce9be70b69dfe37d")),
153        logs_bloom: bloom!("36410880400480e1090a001c408880800019808000125124002100400048442220020000408040423088300004d0000050803000862485a02020011600a5010404143021800881e8e08c402940404002105004820c440051640000809c000011080002300208510808150101000038002500400040000230000000110442800000800204420100008110080200088c1610c0b80000c6008900000340400200200210010111020000200041a2010804801100030a0284a8463820120a0601480244521002a10201100400801101006002001000008000000ce011011041086418609002000128800008180141002003004c00800040940c00c1180ca002890040"),
154        difficulty: U256::ZERO,
155        number: 0x1db931,
156        gas_limit: 0x1c9c380,
157        gas_used: 0x440949,
158        timestamp: 0x66982980,
159        mix_hash: b256!("0x574db0ff0a2243b434ba2a35da8f2f72df08bca44f8733f4908d10dcaebc89f1"),
160        nonce: 0,
161        base_fee_per_gas: Some(0x8),
162        blob_gas_used: Some(0x60000),
163        excess_blob_gas: Some(0x0),
164        parent_beacon_block_root: Some(b256!("0xaa1d9606b7932f2280a19b3498b9ae9eebc6a83f1afde8e45944f79d353db4c1")),
165        extra_data: bytes!("726574682f76312e302e302f6c696e7578"),
166        extra_fields: None,
167    };
168
169    #[test]
170    fn test_ensure_backwards_compatibility() {
171        assert_eq!(Header::bitflag_encoded_bytes(), 4);
172        assert_eq!(HeaderExt::bitflag_encoded_bytes(), 1);
173    }
174
175    #[test]
176    fn test_backwards_compatibility() {
177        let holesky_header_bytes = hex!("81a121788605e0c46689f66b3deed82598e43d5002b71a929023b665228728f0c6e62a951dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347c6e2459991bfe27cca6d86722f35da23a1e4cb97edad188ca5647d62f4cca417c11a1afbadebce30d23260767f6f587e9b3b99934daf25dc08a841aa22aa0d3cb3e1f159d4dcaf6a6063d4d36bfac11d3fdb63ee1a1500328e8ade2592bbea1e04f9a9fd8c0142d3175d6e8420984ee159abd0edd0f7f22d6d915be5a3b9c0fee353f14de5ac5c8ac1850b76ce9be70b69dfe37d36410880400480e1090a001c408880800019808000125124002100400048442220020000408040423088300004d0000050803000862485a02020011600a5010404143021800881e8e08c402940404002105004820c440051640000809c000011080002300208510808150101000038002500400040000230000000110442800000800204420100008110080200088c1610c0b80000c6008900000340400200200210010111020000200041a2010804801100030a0284a8463820120a0601480244521002a10201100400801101006002001000008000000ce011011041086418609002000128800008180141002003004c00800040940c00c1180ca0028900401db93101c9c38044094966982980574db0ff0a2243b434ba2a35da8f2f72df08bca44f8733f4908d10dcaebc89f101080306000000aa1d9606b7932f2280a19b3498b9ae9eebc6a83f1afde8e45944f79d353db4c1726574682f76312e302e302f6c696e7578");
178        let (decoded_header, _) =
179            Header::from_compact(&holesky_header_bytes, holesky_header_bytes.len());
180
181        assert_eq!(decoded_header, HOLESKY_BLOCK);
182
183        let mut encoded_header = Vec::with_capacity(holesky_header_bytes.len());
184        assert_eq!(holesky_header_bytes.len(), decoded_header.to_compact(&mut encoded_header));
185        assert_eq!(encoded_header, holesky_header_bytes);
186    }
187
188    #[test]
189    fn test_extra_fields() {
190        let mut header = HOLESKY_BLOCK;
191        header.extra_fields = Some(HeaderExt { requests_hash: Some(B256::random()) });
192
193        let mut encoded_header = vec![];
194        let len = header.to_compact(&mut encoded_header);
195        assert_eq!(header, Header::from_compact(&encoded_header, len).0);
196    }
197
198    #[test]
199    fn test_extra_fields_missing() {
200        let mut header = HOLESKY_BLOCK;
201        header.extra_fields = None;
202
203        let mut encoded_header = vec![];
204        let len = header.to_compact(&mut encoded_header);
205        assert_eq!(header, Header::from_compact(&encoded_header, len).0);
206    }
207}