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 /// A convenience function that encodes the value in the 2718 format and wraps it in a
236 /// [`WithEncoded`] wrapper.
237 ///
238 /// See also [`WithEncoded::from_2718_encodable`].
239 #[auto_impl(keep_default_for(&))]
240 fn into_encoded(self) -> WithEncoded<Self> {
241 WithEncoded::from_2718_encodable(self)
242 }
243
244 /// The length of the 2718 encoded envelope in network format. This is the
245 /// length of the header + the length of the type flag and inner encoding.
246 fn network_len(&self) -> usize {
247 let mut payload_length = self.encode_2718_len();
248 if !self.is_legacy() {
249 payload_length += Header { list: false, payload_length }.length();
250 }
251
252 payload_length
253 }
254
255 /// Encode in the network format. The network format is used ONLY by the
256 /// Ethereum p2p protocol. Do not call this method unless you are building
257 /// a p2p protocol client.
258 ///
259 /// The network encoding is the RLP encoding of the eip2718-encoded
260 /// envelope.
261 fn network_encode(&self, out: &mut dyn BufMut) {
262 if !self.is_legacy() {
263 Header { list: false, payload_length: self.encode_2718_len() }.encode(out);
264 }
265
266 self.encode_2718(out);
267 }
268}
269
270/// An [EIP-2718] envelope, blanket implemented for types that impl [`Encodable2718`] and
271/// [`Decodable2718`].
272///
273/// This envelope is a wrapper around a transaction, or a receipt, or any other type that is
274/// differentiated by an EIP-2718 transaction type.
275///
276/// [EIP-2718]: https://eips.ethereum.org/EIPS/eip-2718
277pub trait Eip2718Envelope: Decodable2718 + Encodable2718 {}
278impl<T> Eip2718Envelope for T where T: Decodable2718 + Encodable2718 {}
279
280/// A trait that helps to determine the type of the transaction.
281#[auto_impl::auto_impl(&)]
282pub trait Typed2718 {
283 /// Returns the EIP-2718 type flag.
284 fn ty(&self) -> u8;
285
286 /// Returns true if the type matches the given type.
287 fn is_type(&self, ty: u8) -> bool {
288 self.ty() == ty
289 }
290
291 /// Returns true if the type is a legacy transaction.
292 fn is_legacy(&self) -> bool {
293 self.ty() == LEGACY_TX_TYPE_ID
294 }
295
296 /// Returns true if the type is an EIP-2930 transaction.
297 fn is_eip2930(&self) -> bool {
298 self.ty() == EIP2930_TX_TYPE_ID
299 }
300
301 /// Returns true if the type is an EIP-1559 transaction.
302 fn is_eip1559(&self) -> bool {
303 self.ty() == EIP1559_TX_TYPE_ID
304 }
305
306 /// Returns true if the type is an EIP-4844 transaction.
307 fn is_eip4844(&self) -> bool {
308 self.ty() == EIP4844_TX_TYPE_ID
309 }
310
311 /// Returns true if the type is an EIP-7702 transaction.
312 fn is_eip7702(&self) -> bool {
313 self.ty() == EIP7702_TX_TYPE_ID
314 }
315}
316
317#[cfg(feature = "serde")]
318impl<T: Typed2718> Typed2718 for alloy_serde::WithOtherFields<T> {
319 #[inline]
320 fn ty(&self) -> u8 {
321 self.inner.ty()
322 }
323}
324
325/// Generic wrapper with encoded Bytes, such as transaction data.
326#[derive(Debug, Clone, PartialEq, Eq)]
327pub struct WithEncoded<T>(Bytes, pub T);
328
329impl<T> From<(Bytes, T)> for WithEncoded<T> {
330 fn from(value: (Bytes, T)) -> Self {
331 Self(value.0, value.1)
332 }
333}
334
335impl<T> WithEncoded<T> {
336 /// Wraps the value with the bytes.
337 pub const fn new(bytes: Bytes, value: T) -> Self {
338 Self(bytes, value)
339 }
340
341 /// Get the encoded bytes
342 pub const fn encoded_bytes(&self) -> &Bytes {
343 &self.0
344 }
345
346 /// Returns ownership of the encoded bytes.
347 pub fn into_encoded_bytes(self) -> Bytes {
348 self.0
349 }
350
351 /// Get the underlying value
352 pub const fn value(&self) -> &T {
353 &self.1
354 }
355
356 /// Returns ownership of the underlying value.
357 pub fn into_value(self) -> T {
358 self.1
359 }
360
361 /// Transform the value
362 pub fn transform<F: From<T>>(self) -> WithEncoded<F> {
363 WithEncoded(self.0, self.1.into())
364 }
365
366 /// Split the wrapper into [`Bytes`] and value tuple
367 pub fn split(self) -> (Bytes, T) {
368 (self.0, self.1)
369 }
370
371 /// Maps the inner value to a new value using the given function.
372 pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> WithEncoded<U> {
373 WithEncoded(self.0, op(self.1))
374 }
375}
376
377impl<T: Encodable2718> WithEncoded<T> {
378 /// Wraps the value with the [`Encodable2718::encoded_2718`] bytes.
379 pub fn from_2718_encodable(value: T) -> Self {
380 Self(value.encoded_2718().into(), value)
381 }
382}
383
384impl<T> WithEncoded<Option<T>> {
385 /// returns `None` if the inner value is `None`, otherwise returns `Some(WithEncoded<T>)`.
386 pub fn transpose(self) -> Option<WithEncoded<T>> {
387 self.1.map(|v| WithEncoded(self.0, v))
388 }
389}
390
391impl<L: Encodable2718, R: Encodable2718> Encodable2718 for either::Either<L, R> {
392 fn encode_2718_len(&self) -> usize {
393 match self {
394 Self::Left(l) => l.encode_2718_len(),
395 Self::Right(r) => r.encode_2718_len(),
396 }
397 }
398
399 fn encode_2718(&self, out: &mut dyn BufMut) {
400 match self {
401 Self::Left(l) => l.encode_2718(out),
402 Self::Right(r) => r.encode_2718(out),
403 }
404 }
405}
406
407impl<L: Typed2718, R: Typed2718> Typed2718 for either::Either<L, R> {
408 fn ty(&self) -> u8 {
409 match self {
410 Self::Left(l) => l.ty(),
411 Self::Right(r) => r.ty(),
412 }
413 }
414}
415
416/// Trait for checking if a transaction envelope supports a given EIP-2718 type ID.
417pub trait IsTyped2718 {
418 /// Returns true if the given type ID corresponds to a supported typed transaction.
419 fn is_type(type_id: u8) -> bool;
420}
421
422impl<L, R> IsTyped2718 for either::Either<L, R>
423where
424 L: IsTyped2718,
425 R: IsTyped2718,
426{
427 fn is_type(type_id: u8) -> bool {
428 L::is_type(type_id) || R::is_type(type_id)
429 }
430}
431
432impl<L, R> Decodable2718 for either::Either<L, R>
433where
434 L: Decodable2718 + IsTyped2718,
435 R: Decodable2718,
436{
437 fn typed_decode(ty: u8, buf: &mut &[u8]) -> Eip2718Result<Self> {
438 if L::is_type(ty) {
439 let envelope = L::typed_decode(ty, buf)?;
440 Ok(Self::Left(envelope))
441 } else {
442 let other = R::typed_decode(ty, buf)?;
443 Ok(Self::Right(other))
444 }
445 }
446 fn fallback_decode(buf: &mut &[u8]) -> Eip2718Result<Self> {
447 if buf.is_empty() {
448 return Err(Eip2718Error::RlpError(alloy_rlp::Error::InputTooShort));
449 }
450 L::fallback_decode(buf).map(Self::Left)
451 }
452}