diff --git a/crates/consensus/src/block.rs b/crates/consensus/src/block.rs index f540cc52dae1..6c4b321a68d2 100644 --- a/crates/consensus/src/block.rs +++ b/crates/consensus/src/block.rs @@ -1,6 +1,6 @@ -//! Genesic Block Type +//! Block Type -use crate::{Header, Requests}; +use crate::Header; use alloc::vec::Vec; use alloy_eips::eip4895::Withdrawal; use alloy_rlp::{Decodable, Encodable, RlpDecodable, RlpEncodable}; @@ -32,8 +32,6 @@ pub struct BlockBody { pub ommers: Vec
, /// Block withdrawals. pub withdrawals: Option>, - /// Block requests - pub requests: Option, } /// We need to implement RLP traits manually because we currently don't have a way to flatten @@ -48,7 +46,6 @@ mod block_rlp { transactions: Vec, ommers: Vec
, withdrawals: Option>, - requests: Option, } #[derive(RlpEncodable)] @@ -58,20 +55,12 @@ mod block_rlp { transactions: &'a Vec, ommers: &'a Vec
, withdrawals: Option<&'a Vec>, - requests: Option<&'a Requests>, } impl<'a, T> From<&'a Block> for HelperRef<'a, T> { fn from(block: &'a Block) -> Self { - let Block { header, body: BlockBody { transactions, ommers, withdrawals, requests } } = - block; - Self { - header, - transactions, - ommers, - withdrawals: withdrawals.as_ref(), - requests: requests.as_ref(), - } + let Block { header, body: BlockBody { transactions, ommers, withdrawals } } = block; + Self { header, transactions, ommers, withdrawals: withdrawals.as_ref() } } } @@ -89,8 +78,8 @@ mod block_rlp { impl Decodable for Block { fn decode(b: &mut &[u8]) -> alloy_rlp::Result { - let Helper { header, transactions, ommers, withdrawals, requests } = Helper::decode(b)?; - Ok(Self { header, body: BlockBody { transactions, ommers, withdrawals, requests } }) + let Helper { header, transactions, ommers, withdrawals } = Helper::decode(b)?; + Ok(Self { header, body: BlockBody { transactions, ommers, withdrawals } }) } } } diff --git a/crates/consensus/src/lib.rs b/crates/consensus/src/lib.rs index b85cab92dfbe..491393c49acf 100644 --- a/crates/consensus/src/lib.rs +++ b/crates/consensus/src/lib.rs @@ -30,9 +30,6 @@ pub use receipt::{ TxReceipt, }; -mod request; -pub use request::{Request, Requests}; - pub mod transaction; #[cfg(feature = "kzg")] pub use transaction::BlobTransactionValidationError; diff --git a/crates/consensus/src/request.rs b/crates/consensus/src/request.rs deleted file mode 100644 index d234044ead84..000000000000 --- a/crates/consensus/src/request.rs +++ /dev/null @@ -1,155 +0,0 @@ -use alloc::vec::Vec; -use alloy_eips::{ - eip6110::DepositRequest, - eip7002::WithdrawalRequest, - eip7251::ConsolidationRequest, - eip7685::{Decodable7685, Eip7685Error, Encodable7685}, -}; -use alloy_primitives::{bytes, Bytes}; -use alloy_rlp::{Decodable, Encodable}; -use derive_more::{Deref, DerefMut, From, IntoIterator}; - -/// Ethereum execution layer requests. -/// -/// See also [EIP-7685](https://eips.ethereum.org/EIPS/eip-7685). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[non_exhaustive] -#[cfg_attr(any(test, feature = "arbitrary"), derive(arbitrary::Arbitrary))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "serde", serde(untagged))] -pub enum Request { - /// An [EIP-6110] deposit request. - /// - /// [EIP-6110]: https://eips.ethereum.org/EIPS/eip-6110 - DepositRequest(DepositRequest), - /// An [EIP-7002] withdrawal request. - /// - /// [EIP-7002]: https://eips.ethereum.org/EIPS/eip-7002 - WithdrawalRequest(WithdrawalRequest), - /// An [EIP-7251] consolidation request. - /// - /// [EIP-7251]: https://eips.ethereum.org/EIPS/eip-7251 - ConsolidationRequest(ConsolidationRequest), -} - -impl From for Request { - fn from(v: DepositRequest) -> Self { - Self::DepositRequest(v) - } -} - -impl From for Request { - fn from(v: WithdrawalRequest) -> Self { - Self::WithdrawalRequest(v) - } -} - -impl From for Request { - fn from(v: ConsolidationRequest) -> Self { - Self::ConsolidationRequest(v) - } -} - -impl Request { - /// Whether this is a [`DepositRequest`]. - pub const fn is_deposit_request(&self) -> bool { - matches!(self, Self::DepositRequest(_)) - } - - /// Whether this is a [`WithdrawalRequest`]. - pub const fn is_withdrawal_request(&self) -> bool { - matches!(self, Self::WithdrawalRequest(_)) - } - - /// Whether this is a [`ConsolidationRequest`]. - pub const fn is_consolidation_request(&self) -> bool { - matches!(self, Self::ConsolidationRequest(_)) - } - - /// Return the inner [`DepositRequest`], or `None` of this is not a deposit request. - pub const fn as_deposit_request(&self) -> Option<&DepositRequest> { - match self { - Self::DepositRequest(req) => Some(req), - _ => None, - } - } - - /// Return the inner [`WithdrawalRequest`], or `None` if this is not a withdrawal request. - pub const fn as_withdrawal_request(&self) -> Option<&WithdrawalRequest> { - match self { - Self::WithdrawalRequest(req) => Some(req), - _ => None, - } - } - - /// Return the inner [`ConsolidationRequest`], or `None` if this is not a consolidation request. - pub const fn as_consolidation_request(&self) -> Option<&ConsolidationRequest> { - match self { - Self::ConsolidationRequest(req) => Some(req), - _ => None, - } - } -} - -impl Encodable7685 for Request { - fn request_type(&self) -> u8 { - match self { - Self::DepositRequest(_) => 0, - Self::WithdrawalRequest(_) => 1, - Self::ConsolidationRequest(_) => 2, - } - } - - fn encode_payload_7685(&self, out: &mut dyn alloy_rlp::BufMut) { - match self { - Self::DepositRequest(deposit) => deposit.encode(out), - Self::WithdrawalRequest(withdrawal) => withdrawal.encode(out), - Self::ConsolidationRequest(consolidation) => consolidation.encode(out), - } - } -} - -impl Decodable7685 for Request { - fn typed_decode(ty: u8, buf: &mut &[u8]) -> Result { - Ok(match ty { - 0 => Self::DepositRequest(DepositRequest::decode(buf)?), - 1 => Self::WithdrawalRequest(WithdrawalRequest::decode(buf)?), - 2 => Self::ConsolidationRequest(ConsolidationRequest::decode(buf)?), - ty => return Err(Eip7685Error::UnexpectedType(ty)), - }) - } -} - -/// A list of EIP-7685 requests. -#[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(pub Vec); - -impl Encodable for Requests { - fn encode(&self, out: &mut dyn bytes::BufMut) { - let mut h = alloy_rlp::Header { list: true, payload_length: 0 }; - - let mut encoded = Vec::new(); - for req in &self.0 { - let encoded_req = req.encoded_7685(); - h.payload_length += encoded_req.len(); - encoded.push(Bytes::from(encoded_req)); - } - - h.encode(out); - for req in encoded { - req.encode(out); - } - } -} - -impl Decodable for Requests { - fn decode(buf: &mut &[u8]) -> alloy_rlp::Result { - Ok( as Decodable>::decode(buf)? - .into_iter() - .map(|bytes| Request::decode_7685(&mut bytes.as_ref())) - .collect::, alloy_eips::eip7685::Eip7685Error>>() - .map(Self)?) - } -} diff --git a/crates/eips/src/eip7685.rs b/crates/eips/src/eip7685.rs index 216ca9c66833..22424f7ca7ef 100644 --- a/crates/eips/src/eip7685.rs +++ b/crates/eips/src/eip7685.rs @@ -4,133 +4,59 @@ //! //! [EIP-7685]: https://eips.ethereum.org/EIPS/eip-7685 -#[cfg(not(feature = "std"))] -use crate::alloc::{vec, vec::Vec}; - -use alloy_rlp::BufMut; -use core::{ - fmt, - fmt::{Display, Formatter}, -}; - -/// [EIP-7685] decoding errors. -/// -/// [EIP-7685]: https://eips.ethereum.org/EIPS/eip-7685 -#[derive(Clone, Copy, Debug)] -#[non_exhaustive] -pub enum Eip7685Error { - /// Rlp error from [`alloy_rlp`]. - RlpError(alloy_rlp::Error), - /// Got an unexpected request type while decoding. - UnexpectedType(u8), - /// There was no request type in the buffer. - MissingType, -} - -impl Display for Eip7685Error { - fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { - match self { - Self::RlpError(err) => write!(f, "{err}"), - Self::UnexpectedType(t) => write!(f, "Unexpected request type. Got {t}."), - Self::MissingType => write!(f, "There was no type flag"), - } - } -} - -impl From for Eip7685Error { - fn from(err: alloy_rlp::Error) -> Self { - Self::RlpError(err) +use alloc::vec::Vec; +use alloy_primitives::Bytes; +use derive_more::{Deref, DerefMut, From, IntoIterator}; + +/// A list of opaque EIP-7685 requests. +#[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); + +impl Requests { + /// Construct a new [`Requests`] container. + pub const fn new(requests: Vec) -> Self { + Self(requests) } -} -impl From for alloy_rlp::Error { - fn from(err: Eip7685Error) -> Self { - match err { - Eip7685Error::RlpError(err) => err, - Eip7685Error::MissingType => Self::Custom("eip7685 decoding failed: missing type"), - Eip7685Error::UnexpectedType(_) => { - Self::Custom("eip7685 decoding failed: unexpected type") - } - } + /// Add a new request into the container. + pub fn push_request(&mut self, request: Bytes) { + self.0.push(request); } -} -/// Decoding trait for [EIP-7685] requests. The trait should be implemented for an envelope that -/// wraps each possible request type. -/// -/// [EIP-7685]: https://eips.ethereum.org/EIPS/eip-7685 -pub trait Decodable7685: Sized { - /// Extract the type byte from the buffer, if any. The type byte is the - /// first byte. - fn extract_type_byte(buf: &mut &[u8]) -> Option { - buf.first().copied() + /// Consumes [`Requests`] and returns the inner raw opaque requests. + pub fn take(self) -> Vec { + self.0 } - /// Decode the appropriate variant, based on the request type. - /// - /// This function is invoked by [`Self::decode_7685`] with the type byte, and the tail of the - /// buffer. - /// - /// ## Note - /// - /// This should be a simple match block that invokes an inner type's decoder. The decoder is - /// request type dependent. - fn typed_decode(ty: u8, buf: &mut &[u8]) -> Result; - - /// Decode an EIP-7685 request into a concrete instance - fn decode_7685(buf: &mut &[u8]) -> Result { - Self::extract_type_byte(buf) - .map(|ty| Self::typed_decode(ty, &mut &buf[1..])) - .unwrap_or(Err(Eip7685Error::MissingType)) + /// Get an iterator over the Requests. + pub fn iter(&self) -> core::slice::Iter<'_, Bytes> { + self.0.iter() } -} -/// Encoding trait for [EIP-7685] requests. The trait should be implemented for an envelope that -/// wraps each possible request type. -/// -/// [EIP-7685]: https://eips.ethereum.org/EIPS/eip-7685 -pub trait Encodable7685: Sized + Send + Sync + 'static { - /// Return the request type. - fn request_type(&self) -> u8; - - /// Encode the request according to [EIP-7685] rules. - /// - /// First a 1-byte flag specifying the request type, then the encoded payload. - /// - /// The encoding of the payload is request-type dependent. - /// - /// [EIP-7685]: https://eips.ethereum.org/EIPS/eip-7685 - fn encode_7685(&self, out: &mut dyn BufMut) { - out.put_u8(self.request_type()); - self.encode_payload_7685(out); + /// Calculate the requests hash as defined in EIP-7685 for the requests. + /// + /// The requests hash is defined as + /// + /// ```text + /// sha256(sha256(requests_0) ++ sha256(requests_1) ++ ...) + /// ``` + #[cfg(feature = "sha2")] + pub fn requests_hash(&self) -> alloy_primitives::B256 { + use sha2::{Digest, Sha256}; + let mut hash = sha2::Sha256::new(); + for (ty, req) in self.0.iter().enumerate() { + let mut req_hash = Sha256::new(); + req_hash.update([ty as u8]); + req_hash.update(req); + hash.update(req_hash.finalize()); + } + alloy_primitives::B256::from(hash.finalize().as_ref()) } - /// Encode the request payload. - /// - /// The encoding for the payload is request type dependent. - fn encode_payload_7685(&self, out: &mut dyn BufMut); - - /// Encode the request according to [EIP-7685] rules. - /// - /// First a 1-byte flag specifying the request type, then the encoded payload. - /// - /// The encoding of the payload is request-type dependent. - /// - /// This is a convenience method for encoding into a vec, and returning the - /// vec. - /// - /// [EIP-7685]: https://eips.ethereum.org/EIPS/eip-7685 - fn encoded_7685(&self) -> Vec { - let mut out = vec![]; - self.encode_7685(&mut out); - out + /// Extend this container with requests from another container. + pub fn extend(&mut self, other: Self) { + self.0.extend(other.take()); } } - -/// An [EIP-7685] request envelope, blanket implemented for types that impl -/// [`Encodable7685`] and [`Decodable7685`]. This envelope is a wrapper around -/// a request, differentiated by the request type. -/// -/// [EIP-7685]: https://eips.ethereum.org/EIPS/eip-7685 -pub trait Eip7685RequestEnvelope: Decodable7685 + Encodable7685 {} -impl Eip7685RequestEnvelope for T where T: Decodable7685 + Encodable7685 {}