Skip to main content

alloy_eips/
eip7685.rs

1//! [EIP-7685]: General purpose execution layer requests
2//!
3//! [EIP-7685]: https://eips.ethereum.org/EIPS/eip-7685
4
5use alloc::vec::Vec;
6use alloy_primitives::{b256, Bytes, B256};
7use derive_more::{Deref, DerefMut, From, IntoIterator};
8
9/// The empty requests hash.
10///
11/// This is equivalent to `sha256("")`
12pub const EMPTY_REQUESTS_HASH: B256 =
13    b256!("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
14
15/// A container of EIP-7685 requests.
16///
17/// The container only holds the `requests` as defined by their respective EIPs. The first byte of
18/// each element is the `request_type` and the remaining bytes are the `request_data`.
19/// Construction and mutable access accept short entries and duplicate type bytes. `requests_hash`
20/// filters entries shorter than type plus data and sorts by type, but does not deduplicate them.
21#[derive(Debug, Clone, PartialEq, Eq, Default, Hash, Deref, DerefMut, From, IntoIterator)]
22#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub struct Requests(Vec<Bytes>);
25
26#[cfg(feature = "ssz")]
27impl ssz::Encode for Requests {
28    fn is_ssz_fixed_len() -> bool {
29        <Vec<Bytes> as ssz::Encode>::is_ssz_fixed_len()
30    }
31
32    fn ssz_fixed_len() -> usize {
33        <Vec<Bytes> as ssz::Encode>::ssz_fixed_len()
34    }
35
36    fn ssz_bytes_len(&self) -> usize {
37        self.0.ssz_bytes_len()
38    }
39
40    fn ssz_append(&self, buf: &mut Vec<u8>) {
41        self.0.ssz_append(buf);
42    }
43}
44
45#[cfg(feature = "ssz")]
46impl ssz::Decode for Requests {
47    fn is_ssz_fixed_len() -> bool {
48        <Vec<Bytes> as ssz::Decode>::is_ssz_fixed_len()
49    }
50
51    fn ssz_fixed_len() -> usize {
52        <Vec<Bytes> as ssz::Decode>::ssz_fixed_len()
53    }
54
55    fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> {
56        <Vec<Bytes> as ssz::Decode>::from_ssz_bytes(bytes).map(Self)
57    }
58}
59
60impl Requests {
61    /// Creates a raw container without validating request shape or type uniqueness.
62    pub fn from_requests<T: Into<Bytes>>(requests: impl IntoIterator<Item = T>) -> Self {
63        Self(requests.into_iter().map(Into::into).collect())
64    }
65    /// Construct a new [`Requests`] container with the given capacity.
66    pub fn with_capacity(capacity: usize) -> Self {
67        Self(Vec::with_capacity(capacity))
68    }
69
70    /// Constructs a raw container without validating request shape or type uniqueness.
71    ///
72    /// This function assumes that the request type byte is already included as the
73    /// first byte in the provided `Bytes` blob.
74    pub const fn new(requests: Vec<Bytes>) -> Self {
75        Self(requests)
76    }
77
78    /// Add a new request into the container.
79    pub fn push_request(&mut self, request: Bytes) {
80        // Omit empty requests.
81        if request.len() == 1 {
82            return;
83        }
84        self.0.push(request);
85    }
86
87    /// Adds a new request with the given request type into the container.
88    pub fn push_request_with_type(
89        &mut self,
90        request_type: u8,
91        request: impl IntoIterator<Item = u8>,
92    ) {
93        let mut request = request.into_iter().peekable();
94        // Omit empty requests.
95        if request.peek().is_none() {
96            return;
97        }
98        self.0.push(core::iter::once(request_type).chain(request).collect());
99    }
100
101    /// Consumes [`Requests`] and returns the inner raw opaque requests.
102    ///
103    /// # Note
104    ///
105    /// These requests include the `request_type` as the first byte in each
106    /// `Bytes` element, followed by the `requests_data`.
107    pub fn take(self) -> Vec<Bytes> {
108        self.0
109    }
110
111    /// Get an iterator over the requests.
112    pub fn iter(&self) -> core::slice::Iter<'_, Bytes> {
113        self.0.iter()
114    }
115
116    /// Calculate the requests hash as defined in EIP-7685 for the requests.
117    ///
118    /// The requests hash is defined as
119    ///
120    /// ```text
121    /// sha256(sha256(requests_0) ++ sha256(requests_1) ++ ...)
122    /// ```
123    ///
124    /// Each request in the container is expected to already have the `request_type` prepended
125    /// to its corresponding `requests_data`. This function directly calculates the hash based
126    /// on the combined `request_type` and `requests_data`.
127    ///
128    /// Empty requests are omitted from the hash calculation.
129    /// Requests are sorted by their `request_type` before hashing, see also [Ordering](https://eips.ethereum.org/EIPS/eip-7685#ordering)
130    #[cfg(feature = "sha2")]
131    pub fn requests_hash(&self) -> B256 {
132        use sha2::{Digest, Sha256};
133        let mut hash = Sha256::new();
134
135        let mut requests: Vec<_> = self
136            .0
137            .iter()
138            .filter(|req| {
139                // filter out all requests that are empty or only have the type byte
140                // <type-id> <data>
141                req.len() > 1
142            })
143            .collect();
144
145        // requests should only contain unique types: `id [r1,r2,..]`
146        requests.sort_unstable_by_key(|req| {
147            // SAFETY: only includes non-empty requests
148            req[0]
149        });
150
151        for req in requests {
152            let mut req_hash = Sha256::new();
153            req_hash.update(req);
154            hash.update(req_hash.finalize());
155        }
156        B256::new(hash.finalize().into())
157    }
158
159    /// Extend this container with requests from another container.
160    pub fn extend(&mut self, other: Self) {
161        self.0.extend(other.take());
162    }
163}
164
165/// A list of requests or a precomputed requests hash.
166///
167/// For testing purposes, the `Hash` variant stores a precomputed requests hash. This can be useful
168/// when the exact contents of the requests are unnecessary, and only a consistent hash value is
169/// needed to simulate the presence of requests without holding actual data.
170#[derive(Debug, Clone, PartialEq, Eq, Hash, derive_more::From)]
171#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
172#[cfg_attr(feature = "serde", serde(untagged))]
173#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
174pub enum RequestsOrHash {
175    /// Stores a list of requests, allowing for dynamic requests hash calculation.
176    Requests(Requests),
177    /// Stores a precomputed requests hash, used primarily for testing or mocking because the
178    /// header only contains the hash.
179    Hash(B256),
180}
181
182impl RequestsOrHash {
183    /// Returns the requests hash for the enum instance.
184    ///
185    /// - If the instance contains a list of requests, this function calculates the hash using
186    ///   `requests_hash` of the [`Requests`] struct.
187    /// - If it contains a precomputed hash, it returns that hash directly.
188    #[cfg(feature = "sha2")]
189    pub fn requests_hash(&self) -> B256 {
190        match self {
191            Self::Requests(requests) => requests.requests_hash(),
192            Self::Hash(precomputed_hash) => *precomputed_hash,
193        }
194    }
195
196    /// Returns an instance with the [`EMPTY_REQUESTS_HASH`].
197    pub const fn empty() -> Self {
198        Self::Hash(EMPTY_REQUESTS_HASH)
199    }
200
201    /// Returns the requests, if any.
202    pub const fn requests(&self) -> Option<&Requests> {
203        match self {
204            Self::Requests(requests) => Some(requests),
205            Self::Hash(_) => None,
206        }
207    }
208
209    /// Returns `true` if the variant is a list of requests.
210    pub const fn is_requests(&self) -> bool {
211        matches!(self, Self::Requests(_))
212    }
213
214    /// Returns `true` if the variant is a precomputed hash.
215    pub const fn is_hash(&self) -> bool {
216        matches!(self, Self::Hash(_))
217    }
218}
219
220impl Default for RequestsOrHash {
221    fn default() -> Self {
222        Self::Requests(Requests::default())
223    }
224}
225
226impl From<Vec<Bytes>> for RequestsOrHash {
227    fn from(requests: Vec<Bytes>) -> Self {
228        Self::Requests(requests.into())
229    }
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235
236    #[test]
237    fn test_extend() {
238        // Test extending a Requests container with another Requests container
239        let mut reqs1 = Requests::new(vec![Bytes::from(vec![0x01, 0x02])]);
240        let reqs2 =
241            Requests::new(vec![Bytes::from(vec![0x03, 0x04]), Bytes::from(vec![0x05, 0x06])]);
242
243        // Extend reqs1 with reqs2
244        reqs1.extend(reqs2);
245
246        // Ensure the requests are correctly combined
247        assert_eq!(reqs1.0.len(), 3);
248        assert_eq!(
249            reqs1.0,
250            vec![
251                Bytes::from(vec![0x01, 0x02]),
252                Bytes::from(vec![0x03, 0x04]),
253                Bytes::from(vec![0x05, 0x06])
254            ]
255        );
256    }
257
258    #[test]
259    #[cfg(feature = "sha2")]
260    fn test_consistent_requests_hash() {
261        // We test that the empty requests hash is consistent with the EIP-7685 definition.
262        assert_eq!(Requests::default().requests_hash(), EMPTY_REQUESTS_HASH);
263
264        // Test to hash a non-empty vector of requests.
265        assert_eq!(
266            Requests(vec![
267                Bytes::from(vec![0x00, 0x0a, 0x0b, 0x0c]),
268                Bytes::from(vec![0x01, 0x0d, 0x0e, 0x0f])
269            ])
270            .requests_hash(),
271            b256!("be3a57667b9bb9e0275019c0faf0f415fdc8385a408fd03e13a5c50615e3530c"),
272        );
273    }
274}