alloy_eips/
eip2718.rs

1//! [EIP-2718] traits.
2//!
3//! [EIP-2718]: https://eips.ethereum.org/EIPS/eip-2718
4
5use crate::alloc::vec::Vec;
6use alloy_primitives::{keccak256, Bytes, Sealed, B256};
7use alloy_rlp::{Buf, BufMut, Header, EMPTY_STRING_CODE};
8use auto_impl::auto_impl;
9use core::fmt;
10
11// https://eips.ethereum.org/EIPS/eip-2718#transactiontype-only-goes-up-to-0x7f
12const TX_TYPE_BYTE_MAX: u8 = 0x7f;
13
14/// Identifier for legacy transaction, however a legacy tx is technically not
15/// typed.
16pub const LEGACY_TX_TYPE_ID: u8 = 0;
17
18/// Identifier for an EIP2930 transaction.
19pub const EIP2930_TX_TYPE_ID: u8 = 1;
20
21/// Identifier for an EIP1559 transaction.
22pub const EIP1559_TX_TYPE_ID: u8 = 2;
23
24/// Identifier for an EIP4844 transaction.
25pub const EIP4844_TX_TYPE_ID: u8 = 3;
26
27/// Identifier for an EIP7702 transaction.
28pub const EIP7702_TX_TYPE_ID: u8 = 4;
29
30/// [EIP-2718] decoding errors.
31///
32/// [EIP-2718]: https://eips.ethereum.org/EIPS/eip-2718
33#[derive(Clone, Copy, Debug)]
34#[non_exhaustive] // NB: non-exhaustive allows us to add a Custom variant later
35pub enum Eip2718Error {
36    /// Rlp error from [`alloy_rlp`].
37    RlpError(alloy_rlp::Error),
38    /// Got an unexpected type flag while decoding.
39    UnexpectedType(u8),
40}
41
42/// Result type for [EIP-2718] decoding.
43pub type Eip2718Result<T, E = Eip2718Error> = core::result::Result<T, E>;
44
45impl fmt::Display for Eip2718Error {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        match self {
48            Self::RlpError(err) => write!(f, "{err}"),
49            Self::UnexpectedType(t) => write!(f, "Unexpected type flag. Got {t}."),
50        }
51    }
52}
53
54impl From<alloy_rlp::Error> for Eip2718Error {
55    fn from(err: alloy_rlp::Error) -> Self {
56        Self::RlpError(err)
57    }
58}
59
60impl From<Eip2718Error> for alloy_rlp::Error {
61    fn from(err: Eip2718Error) -> Self {
62        match err {
63            Eip2718Error::RlpError(err) => err,
64            Eip2718Error::UnexpectedType(_) => Self::Custom("Unexpected type flag"),
65        }
66    }
67}
68
69impl core::error::Error for Eip2718Error {}
70
71/// Decoding trait for [EIP-2718] envelopes. These envelopes wrap a transaction
72/// or a receipt with a type flag.
73///
74/// Users should rarely import this trait, and should instead prefer letting the
75/// alloy `Provider` methods handle encoding
76///
77/// ## Implementing
78///
79/// Implement this trait when you need to make custom TransactionEnvelope
80/// and ReceiptEnvelope types for your network. These types should be enums
81/// over the accepted transaction types.
82///
83/// [EIP-2718]: https://eips.ethereum.org/EIPS/eip-2718
84pub trait Decodable2718: Sized {
85    /// Extract the type byte from the buffer, if any. The type byte is the
86    /// first byte, provided that first byte is 0x7f or lower.
87    fn extract_type_byte(buf: &mut &[u8]) -> Option<u8> {
88        buf.first().copied().filter(|b| *b <= TX_TYPE_BYTE_MAX)
89    }
90
91    /// Decode the appropriate variant, based on the type flag.
92    ///
93    /// This function is invoked by [`Self::decode_2718`] with the type byte,
94    /// and the tail of the buffer.
95    ///
96    /// ## Implementing
97    ///
98    /// This should be a simple match block that invokes an inner type's
99    /// specific decoder.
100    fn typed_decode(ty: u8, buf: &mut &[u8]) -> Eip2718Result<Self>;
101
102    /// Decode the default variant.
103    ///
104    /// ## Implementing
105    ///
106    /// This function is invoked by [`Self::decode_2718`] when no type byte can
107    /// be extracted. It should be a simple wrapper around the default type's
108    /// decoder.
109    fn fallback_decode(buf: &mut &[u8]) -> Eip2718Result<Self>;
110
111    /// Decode the transaction according to [EIP-2718] rules. First a 1-byte
112    /// type flag in the range 0x0-0x7f, then the body of the transaction.
113    ///
114    /// [EIP-2718] inner encodings are unspecified, and produce an opaque
115    /// bytestring.
116    ///
117    /// [EIP-2718]: https://eips.ethereum.org/EIPS/eip-2718
118    fn decode_2718(buf: &mut &[u8]) -> Eip2718Result<Self> {
119        Self::extract_type_byte(buf)
120            .map(|ty| {
121                buf.advance(1);
122                Self::typed_decode(ty, buf)
123            })
124            .unwrap_or_else(|| Self::fallback_decode(buf))
125    }
126
127    /// Decode an [EIP-2718] transaction in the network format. The network
128    /// format is used ONLY by the Ethereum p2p protocol. Do not call this
129    /// method unless you are building a p2p protocol client.
130    ///
131    /// The network encoding is the RLP encoding of the eip2718-encoded
132    /// envelope.
133    ///
134    /// [EIP-2718]: https://eips.ethereum.org/EIPS/eip-2718
135    fn network_decode(buf: &mut &[u8]) -> Eip2718Result<Self> {
136        // Keep the original buffer around by copying it.
137        let mut h_decode = *buf;
138        let h = Header::decode(&mut h_decode)?;
139
140        // If it's a list, we need to fallback to the legacy decoding.
141        if h.list {
142            return Self::fallback_decode(buf);
143        }
144        *buf = h_decode;
145
146        let remaining_len = buf.len();
147        if remaining_len == 0 || remaining_len < h.payload_length {
148            return Err(alloy_rlp::Error::InputTooShort.into());
149        }
150
151        let ty = buf.get_u8();
152        let tx = Self::typed_decode(ty, buf)?;
153
154        let bytes_consumed = remaining_len - buf.len();
155        // because Header::decode works for single bytes (including the tx type), returning a
156        // string Header with payload_length of 1, we need to make sure this check is only
157        // performed for transactions with a string header
158        if bytes_consumed != h.payload_length && h_decode[0] > EMPTY_STRING_CODE {
159            return Err(alloy_rlp::Error::UnexpectedLength.into());
160        }
161
162        Ok(tx)
163    }
164}
165
166/// Encoding trait for [EIP-2718] envelopes.
167///
168/// These envelopes wrap a transaction or a receipt with a type flag. [EIP-2718] encodings are used
169/// by the `eth_sendRawTransaction` RPC call, the Ethereum block header's tries, and the
170/// peer-to-peer protocol.
171///
172/// Users should rarely import this trait, and should instead prefer letting the
173/// alloy `Provider` methods handle encoding
174///
175/// ## Implementing
176///
177/// Implement this trait when you need to make custom TransactionEnvelope
178/// and ReceiptEnvelope types for your network. These types should be enums
179/// over the accepted transaction types.
180///
181/// [EIP-2718]: https://eips.ethereum.org/EIPS/eip-2718
182#[auto_impl(&)]
183pub trait Encodable2718: Typed2718 + Sized + Send + Sync {
184    /// Return the type flag (if any).
185    ///
186    /// This should return `None` for the default (legacy) variant of the
187    /// envelope.
188    fn type_flag(&self) -> Option<u8> {
189        match self.ty() {
190            LEGACY_TX_TYPE_ID => None,
191            ty => Some(ty),
192        }
193    }
194
195    /// The length of the 2718 encoded envelope. This is the length of the type
196    /// flag + the length of the inner encoding.
197    fn encode_2718_len(&self) -> usize;
198
199    /// Encode the transaction according to [EIP-2718] rules. First a 1-byte
200    /// type flag in the range 0x0-0x7f, then the body of the transaction.
201    ///
202    /// [EIP-2718] inner encodings are unspecified, and produce an opaque
203    /// bytestring.
204    ///
205    /// [EIP-2718]: https://eips.ethereum.org/EIPS/eip-2718
206    fn encode_2718(&self, out: &mut dyn BufMut);
207
208    /// Encode the transaction according to [EIP-2718] rules. First a 1-byte
209    /// type flag in the range 0x0-0x7f, then the body of the transaction.
210    ///
211    /// This is a convenience method for encoding into a vec, and returning the
212    /// vec.
213    fn encoded_2718(&self) -> Vec<u8> {
214        let mut out = Vec::with_capacity(self.encode_2718_len());
215        self.encode_2718(&mut out);
216        out
217    }
218
219    /// Compute the hash as committed to in the MPT trie. This hash is used
220    /// ONLY by the Ethereum merkle-patricia trie and associated proofs. Do not
221    /// call this method unless you are building a full or light client.
222    ///
223    /// The trie hash is the keccak256 hash of the 2718-encoded envelope.
224    fn trie_hash(&self) -> B256 {
225        keccak256(self.encoded_2718())
226    }
227
228    /// Seal the encodable, by encoding and hashing it.
229    #[auto_impl(keep_default_for(&))]
230    fn seal(self) -> Sealed<Self> {
231        let hash = self.trie_hash();
232        Sealed::new_unchecked(self, hash)
233    }
234
235    /// The length of the 2718 encoded envelope in network format. This is the
236    /// length of the header + the length of the type flag and inner encoding.
237    fn network_len(&self) -> usize {
238        let mut payload_length = self.encode_2718_len();
239        if !self.is_legacy() {
240            payload_length += Header { list: false, payload_length }.length();
241        }
242
243        payload_length
244    }
245
246    /// Encode in the network format. The network format is used ONLY by the
247    /// Ethereum p2p protocol. Do not call this method unless you are building
248    /// a p2p protocol client.
249    ///
250    /// The network encoding is the RLP encoding of the eip2718-encoded
251    /// envelope.
252    fn network_encode(&self, out: &mut dyn BufMut) {
253        if !self.is_legacy() {
254            Header { list: false, payload_length: self.encode_2718_len() }.encode(out);
255        }
256
257        self.encode_2718(out);
258    }
259}
260
261/// An [EIP-2718] envelope, blanket implemented for types that impl [`Encodable2718`] and
262/// [`Decodable2718`].
263///
264/// This envelope is a wrapper around a transaction, or a receipt, or any other type that is
265/// differentiated by an EIP-2718 transaction type.
266///
267/// [EIP-2718]: https://eips.ethereum.org/EIPS/eip-2718
268pub trait Eip2718Envelope: Decodable2718 + Encodable2718 {}
269impl<T> Eip2718Envelope for T where T: Decodable2718 + Encodable2718 {}
270
271/// A trait that helps to determine the type of the transaction.
272#[auto_impl::auto_impl(&)]
273pub trait Typed2718 {
274    /// Returns the EIP-2718 type flag.
275    fn ty(&self) -> u8;
276
277    /// Returns true if the type matches the given type.
278    fn is_type(&self, ty: u8) -> bool {
279        self.ty() == ty
280    }
281
282    /// Returns true if the type is a legacy transaction.
283    fn is_legacy(&self) -> bool {
284        self.ty() == LEGACY_TX_TYPE_ID
285    }
286
287    /// Returns true if the type is an EIP-2930 transaction.
288    fn is_eip2930(&self) -> bool {
289        self.ty() == EIP2930_TX_TYPE_ID
290    }
291
292    /// Returns true if the type is an EIP-1559 transaction.
293    fn is_eip1559(&self) -> bool {
294        self.ty() == EIP1559_TX_TYPE_ID
295    }
296
297    /// Returns true if the type is an EIP-4844 transaction.
298    fn is_eip4844(&self) -> bool {
299        self.ty() == EIP4844_TX_TYPE_ID
300    }
301
302    /// Returns true if the type is an EIP-7702 transaction.
303    fn is_eip7702(&self) -> bool {
304        self.ty() == EIP7702_TX_TYPE_ID
305    }
306}
307
308#[cfg(feature = "serde")]
309impl<T: Typed2718> Typed2718 for alloy_serde::WithOtherFields<T> {
310    #[inline]
311    fn ty(&self) -> u8 {
312        self.inner.ty()
313    }
314}
315
316/// Generic wrapper with encoded Bytes, such as transaction data.
317#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct WithEncoded<T>(Bytes, pub T);
319
320impl<T> From<(Bytes, T)> for WithEncoded<T> {
321    fn from(value: (Bytes, T)) -> Self {
322        Self(value.0, value.1)
323    }
324}
325
326impl<T> WithEncoded<T> {
327    /// Wraps the value with the bytes.
328    pub const fn new(bytes: Bytes, value: T) -> Self {
329        Self(bytes, value)
330    }
331
332    /// Get the encoded bytes
333    pub const fn encoded_bytes(&self) -> &Bytes {
334        &self.0
335    }
336
337    /// Returns ownership of the encoded bytes.
338    pub fn into_encoded_bytes(self) -> Bytes {
339        self.0
340    }
341
342    /// Get the underlying value
343    pub const fn value(&self) -> &T {
344        &self.1
345    }
346
347    /// Returns ownership of the underlying value.
348    pub fn into_value(self) -> T {
349        self.1
350    }
351
352    /// Transform the value
353    pub fn transform<F: From<T>>(self) -> WithEncoded<F> {
354        WithEncoded(self.0, self.1.into())
355    }
356
357    /// Split the wrapper into [`Bytes`] and value tuple
358    pub fn split(self) -> (Bytes, T) {
359        (self.0, self.1)
360    }
361
362    /// Maps the inner value to a new value using the given function.
363    pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> WithEncoded<U> {
364        WithEncoded(self.0, op(self.1))
365    }
366}
367
368impl<T: Encodable2718> WithEncoded<T> {
369    /// Wraps the value with the [`Encodable2718::encoded_2718`] bytes.
370    pub fn from_2718_encodable(value: T) -> Self {
371        Self(value.encoded_2718().into(), value)
372    }
373}
374
375impl<T> WithEncoded<Option<T>> {
376    /// returns `None` if the inner value is `None`, otherwise returns `Some(WithEncoded<T>)`.
377    pub fn transpose(self) -> Option<WithEncoded<T>> {
378        self.1.map(|v| WithEncoded(self.0, v))
379    }
380}
381
382impl<L: Encodable2718, R: Encodable2718> Encodable2718 for either::Either<L, R> {
383    fn encode_2718_len(&self) -> usize {
384        match self {
385            Self::Left(l) => l.encode_2718_len(),
386            Self::Right(r) => r.encode_2718_len(),
387        }
388    }
389
390    fn encode_2718(&self, out: &mut dyn BufMut) {
391        match self {
392            Self::Left(l) => l.encode_2718(out),
393            Self::Right(r) => r.encode_2718(out),
394        }
395    }
396}
397
398impl<L: Typed2718, R: Typed2718> Typed2718 for either::Either<L, R> {
399    fn ty(&self) -> u8 {
400        match self {
401            Self::Left(l) => l.ty(),
402            Self::Right(r) => r.ty(),
403        }
404    }
405}
406
407/// Trait for checking if a transaction envelope supports a given EIP-2718 type ID.
408pub trait IsTyped2718 {
409    /// Returns true if the given type ID corresponds to a supported typed transaction.
410    fn is_type(type_id: u8) -> bool;
411}
412
413impl<L, R> IsTyped2718 for either::Either<L, R>
414where
415    L: IsTyped2718,
416    R: IsTyped2718,
417{
418    fn is_type(type_id: u8) -> bool {
419        L::is_type(type_id) || R::is_type(type_id)
420    }
421}
422
423impl<L, R> Decodable2718 for either::Either<L, R>
424where
425    L: Decodable2718 + IsTyped2718,
426    R: Decodable2718,
427{
428    fn typed_decode(ty: u8, buf: &mut &[u8]) -> Eip2718Result<Self> {
429        if L::is_type(ty) {
430            let envelope = L::typed_decode(ty, buf)?;
431            Ok(Self::Left(envelope))
432        } else {
433            let other = R::typed_decode(ty, buf)?;
434            Ok(Self::Right(other))
435        }
436    }
437    fn fallback_decode(buf: &mut &[u8]) -> Eip2718Result<Self> {
438        if buf.is_empty() {
439            return Err(Eip2718Error::RlpError(alloy_rlp::Error::InputTooShort));
440        }
441        L::fallback_decode(buf).map(Self::Left)
442    }
443}