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