use alloc::vec::Vec;
use alloy_primitives::{b256, Bytes, B256};
use derive_more::{Deref, DerefMut, From, IntoIterator};
pub const EMPTY_REQUESTS_HASH: B256 =
b256!("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash, Deref, DerefMut, From, IntoIterator)]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Requests(Vec<Bytes>);
#[cfg(feature = "ssz")]
impl ssz::Encode for Requests {
fn is_ssz_fixed_len() -> bool {
<Vec<Bytes> as ssz::Encode>::is_ssz_fixed_len()
}
fn ssz_fixed_len() -> usize {
<Vec<Bytes> as ssz::Encode>::ssz_fixed_len()
}
fn ssz_bytes_len(&self) -> usize {
self.0.ssz_bytes_len()
}
fn ssz_append(&self, buf: &mut Vec<u8>) {
self.0.ssz_append(buf);
}
}
#[cfg(feature = "ssz")]
impl ssz::Decode for Requests {
fn is_ssz_fixed_len() -> bool {
<Vec<Bytes> as ssz::Decode>::is_ssz_fixed_len()
}
fn ssz_fixed_len() -> usize {
<Vec<Bytes> as ssz::Decode>::ssz_fixed_len()
}
fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> {
<Vec<Bytes> as ssz::Decode>::from_ssz_bytes(bytes).map(Self)
}
}
impl Requests {
pub fn from_requests<T: Into<Bytes>>(requests: impl IntoIterator<Item = T>) -> Self {
Self(requests.into_iter().map(Into::into).collect())
}
pub fn with_capacity(capacity: usize) -> Self {
Self(Vec::with_capacity(capacity))
}
pub const fn new(requests: Vec<Bytes>) -> Self {
Self(requests)
}
pub fn push_request(&mut self, request: Bytes) {
if request.len() == 1 {
return;
}
self.0.push(request);
}
pub fn push_request_with_type(
&mut self,
request_type: u8,
request: impl IntoIterator<Item = u8>,
) {
let mut request = request.into_iter().peekable();
if request.peek().is_none() {
return;
}
self.0.push(core::iter::once(request_type).chain(request).collect());
}
pub fn take(self) -> Vec<Bytes> {
self.0
}
pub fn iter(&self) -> core::slice::Iter<'_, Bytes> {
self.0.iter()
}
#[cfg(feature = "sha2")]
pub fn requests_hash(&self) -> B256 {
use sha2::{Digest, Sha256};
let mut hash = Sha256::new();
let mut requests: Vec<_> = self
.0
.iter()
.filter(|req| {
req.len() > 1
})
.collect();
requests.sort_unstable_by_key(|req| {
req[0]
});
for req in requests {
let mut req_hash = Sha256::new();
req_hash.update(req);
hash.update(req_hash.finalize());
}
B256::new(hash.finalize().into())
}
pub fn extend(&mut self, other: Self) {
self.0.extend(other.take());
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, derive_more::From)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))]
pub enum RequestsOrHash {
Requests(Requests),
Hash(B256),
}
impl RequestsOrHash {
#[cfg(feature = "sha2")]
pub fn requests_hash(&self) -> B256 {
match self {
Self::Requests(requests) => requests.requests_hash(),
Self::Hash(precomputed_hash) => *precomputed_hash,
}
}
pub const fn empty() -> Self {
Self::Hash(EMPTY_REQUESTS_HASH)
}
pub const fn requests(&self) -> Option<&Requests> {
match self {
Self::Requests(requests) => Some(requests),
Self::Hash(_) => None,
}
}
pub const fn is_requests(&self) -> bool {
matches!(self, Self::Requests(_))
}
pub const fn is_hash(&self) -> bool {
matches!(self, Self::Hash(_))
}
}
impl Default for RequestsOrHash {
fn default() -> Self {
Self::Requests(Requests::default())
}
}
impl From<Vec<Bytes>> for RequestsOrHash {
fn from(requests: Vec<Bytes>) -> Self {
Self::Requests(requests.into())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extend() {
let mut reqs1 = Requests::new(vec![Bytes::from(vec![0x01, 0x02])]);
let reqs2 =
Requests::new(vec![Bytes::from(vec![0x03, 0x04]), Bytes::from(vec![0x05, 0x06])]);
reqs1.extend(reqs2);
assert_eq!(reqs1.0.len(), 3);
assert_eq!(
reqs1.0,
vec![
Bytes::from(vec![0x01, 0x02]),
Bytes::from(vec![0x03, 0x04]),
Bytes::from(vec![0x05, 0x06])
]
);
}
#[test]
#[cfg(feature = "sha2")]
fn test_consistent_requests_hash() {
assert_eq!(Requests::default().requests_hash(), EMPTY_REQUESTS_HASH);
assert_eq!(
Requests(vec![
Bytes::from(vec![0x00, 0x0a, 0x0b, 0x0c]),
Bytes::from(vec![0x01, 0x0d, 0x0e, 0x0f])
])
.requests_hash(),
b256!("be3a57667b9bb9e0275019c0faf0f415fdc8385a408fd03e13a5c50615e3530c"),
);
}
}