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))]
133pub enum RequestsOrHash {
134 /// Stores a list of requests, allowing for dynamic requests hash calculation.
135 Requests(Requests),
136 /// Stores a precomputed requests hash, used primarily for testing or mocking because the
137 /// header only contains the hash.
138 Hash(B256),
139}
140
141impl RequestsOrHash {
142 /// Returns the requests hash for the enum instance.
143 ///
144 /// - If the instance contains a list of requests, this function calculates the hash using
145 /// `requests_hash` of the [`Requests`] struct.
146 /// - If it contains a precomputed hash, it returns that hash directly.
147 #[cfg(feature = "sha2")]
148 pub fn requests_hash(&self) -> B256 {
149 match self {
150 Self::Requests(requests) => requests.requests_hash(),
151 Self::Hash(precomputed_hash) => *precomputed_hash,
152 }
153 }
154
155 /// Returns an instance with the [`EMPTY_REQUESTS_HASH`].
156 pub const fn empty() -> Self {
157 Self::Hash(EMPTY_REQUESTS_HASH)
158 }
159
160 /// Returns the requests, if any.
161 pub const fn requests(&self) -> Option<&Requests> {
162 match self {
163 Self::Requests(requests) => Some(requests),
164 Self::Hash(_) => None,
165 }
166 }
167
168 /// Returns `true` if the variant is a list of requests.
169 pub const fn is_requests(&self) -> bool {
170 matches!(self, Self::Requests(_))
171 }
172
173 /// Returns `true` if the variant is a precomputed hash.
174 pub const fn is_hash(&self) -> bool {
175 matches!(self, Self::Hash(_))
176 }
177}
178
179impl Default for RequestsOrHash {
180 fn default() -> Self {
181 Self::Requests(Requests::default())
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
190 fn test_extend() {
191 // Test extending a Requests container with another Requests container
192 let mut reqs1 = Requests::new(vec![Bytes::from(vec![0x01, 0x02])]);
193 let reqs2 =
194 Requests::new(vec![Bytes::from(vec![0x03, 0x04]), Bytes::from(vec![0x05, 0x06])]);
195
196 // Extend reqs1 with reqs2
197 reqs1.extend(reqs2);
198
199 // Ensure the requests are correctly combined
200 assert_eq!(reqs1.0.len(), 3);
201 assert_eq!(
202 reqs1.0,
203 vec![
204 Bytes::from(vec![0x01, 0x02]),
205 Bytes::from(vec![0x03, 0x04]),
206 Bytes::from(vec![0x05, 0x06])
207 ]
208 );
209 }
210
211 #[test]
212 #[cfg(feature = "sha2")]
213 fn test_consistent_requests_hash() {
214 // We test that the empty requests hash is consistent with the EIP-7685 definition.
215 assert_eq!(Requests::default().requests_hash(), EMPTY_REQUESTS_HASH);
216
217 // Test to hash a non-empty vector of requests.
218 assert_eq!(
219 Requests(vec![
220 Bytes::from(vec![0x00, 0x0a, 0x0b, 0x0c]),
221 Bytes::from(vec![0x01, 0x0d, 0x0e, 0x0f])
222 ])
223 .requests_hash(),
224 b256!("be3a57667b9bb9e0275019c0faf0f415fdc8385a408fd03e13a5c50615e3530c"),
225 );
226 }
227}