1use std::{
2 cmp::min,
3 fmt::Display,
4 num::NonZeroUsize,
5 sync::{LazyLock, Mutex},
6};
7
8use crate::utils::keccak;
9use bytes::Bytes;
10use ethereum_types::{Address, H256, U256};
11use ethrex_crypto::{Crypto, CryptoError, NativeCrypto};
12use lru::LruCache;
13pub use mempool::MempoolTransaction;
14
15const MAX_SIGNER_CACHE_ENTRIES: usize = 100_000;
16
17pub static GLOBAL_SIGNER_CACHE: LazyLock<Mutex<LruCache<H256, Address>>> = LazyLock::new(|| {
28 Mutex::new(LruCache::new(
29 NonZeroUsize::new(MAX_SIGNER_CACHE_ENTRIES).expect("MAX_SIGNER_CACHE_ENTRIES is non-zero"),
30 ))
31});
32use rkyv::{Archive, Deserialize as RDeserialize, Serialize as RSerialize};
33use serde::{Serialize, ser::SerializeStruct};
34pub use serde_impl::{
35 AccessListEntry, AuthorizationTupleEntry, FrameEntry, GenericTransaction,
36 GenericTransactionError,
37};
38
39pub const EIP1559_DEFAULT_SERIALIZED_LENGTH: usize = 15;
41
42use ethrex_rlp::{
43 constants::RLP_NULL,
44 decode::{RLPDecode, decode_bytes, decode_rlp_item},
45 encode::{PayloadRLPEncode, RLPEncode},
46 error::RLPDecodeError,
47 structs::{Decoder, Encoder},
48};
49
50#[cfg(all(feature = "zisk", target_arch = "riscv64"))]
51use super::unsync_cell::OnceCell;
52use crate::types::{
53 AccessList, AuthorizationList, BlobsBundle, constants::VERSIONED_HASH_VERSION_KZG,
54};
55#[cfg(not(all(feature = "zisk", target_arch = "riscv64")))]
56use once_cell::sync::OnceCell;
57
58#[derive(Clone, Debug, PartialEq, Eq, Serialize, RSerialize, RDeserialize, Archive)]
67#[serde(untagged)]
68pub enum Transaction {
69 LegacyTransaction(LegacyTransaction),
70 EIP2930Transaction(EIP2930Transaction),
71 EIP1559Transaction(EIP1559Transaction),
72 EIP4844Transaction(EIP4844Transaction),
73 EIP7702Transaction(EIP7702Transaction),
74 PrivilegedL2Transaction(PrivilegedL2Transaction),
75 FeeTokenTransaction(FeeTokenTransaction),
76 FrameTransaction(FrameTransaction),
77}
78
79#[derive(Clone, Debug, PartialEq, Eq)]
83pub enum P2PTransaction {
84 LegacyTransaction(LegacyTransaction),
85 EIP2930Transaction(EIP2930Transaction),
86 EIP1559Transaction(EIP1559Transaction),
87 EIP4844TransactionWithBlobs(WrappedEIP4844Transaction),
88 EIP7702Transaction(EIP7702Transaction),
89 FeeTokenTransaction(FeeTokenTransaction),
90 FrameTransaction(FrameTransaction),
91}
92
93impl TryInto<Transaction> for P2PTransaction {
94 type Error = String;
95
96 fn try_into(self) -> Result<Transaction, Self::Error> {
97 match self {
98 P2PTransaction::LegacyTransaction(itx) => Ok(Transaction::LegacyTransaction(itx)),
99 P2PTransaction::EIP2930Transaction(itx) => Ok(Transaction::EIP2930Transaction(itx)),
100 P2PTransaction::EIP1559Transaction(itx) => Ok(Transaction::EIP1559Transaction(itx)),
101 P2PTransaction::EIP7702Transaction(itx) => Ok(Transaction::EIP7702Transaction(itx)),
102 P2PTransaction::FrameTransaction(itx) => Ok(Transaction::FrameTransaction(itx)),
103 _ => Err("Can't convert blob p2p transaction into regular transaction. Blob bundle would be lost.".to_string()),
104 }
105 }
106}
107
108impl RLPEncode for P2PTransaction {
109 fn encode(&self, buf: &mut dyn bytes::BufMut) {
110 match self {
111 P2PTransaction::LegacyTransaction(t) => t.encode(buf),
112 tx => <[u8] as RLPEncode>::encode(&tx.encode_canonical_to_vec(), buf),
113 };
114 }
115}
116
117impl RLPDecode for P2PTransaction {
118 fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
119 let (is_list, payload, remainder) = decode_rlp_item(rlp)?;
120 if !is_list {
121 let tx_type = *payload.first().ok_or(RLPDecodeError::InvalidLength)?;
122 let tx_encoding = payload.get(1..).ok_or(RLPDecodeError::InvalidLength)?;
123 let tx = match EnvelopeTxType::from_type_byte(tx_type)? {
126 EnvelopeTxType::EIP2930 => {
127 P2PTransaction::EIP2930Transaction(EIP2930Transaction::decode(tx_encoding)?)
128 }
129 EnvelopeTxType::EIP1559 => {
130 P2PTransaction::EIP1559Transaction(EIP1559Transaction::decode(tx_encoding)?)
131 }
132 EnvelopeTxType::EIP4844 => P2PTransaction::EIP4844TransactionWithBlobs(
133 WrappedEIP4844Transaction::decode(tx_encoding)?,
134 ),
135 EnvelopeTxType::EIP7702 => {
136 P2PTransaction::EIP7702Transaction(EIP7702Transaction::decode(tx_encoding)?)
137 }
138 EnvelopeTxType::Frame => {
139 P2PTransaction::FrameTransaction(FrameTransaction::decode(tx_encoding)?)
140 }
141 EnvelopeTxType::FeeToken => {
142 P2PTransaction::FeeTokenTransaction(FeeTokenTransaction::decode(tx_encoding)?)
143 }
144 EnvelopeTxType::Privileged => {
146 return Err(RLPDecodeError::Custom(
147 "privileged transactions are not sent over p2p".to_string(),
148 ));
149 }
150 };
151 Ok((tx, remainder))
152 } else {
153 LegacyTransaction::decode_unfinished(rlp)
155 .map(|(tx, rem)| (P2PTransaction::LegacyTransaction(tx), rem))
156 }
157 }
158}
159
160#[derive(Clone, Debug, PartialEq, Eq)]
161pub struct WrappedEIP4844Transaction {
162 pub tx: EIP4844Transaction,
163 pub wrapper_version: Option<u8>,
164 pub blobs_bundle: BlobsBundle,
165}
166
167impl RLPEncode for WrappedEIP4844Transaction {
168 fn encode(&self, buf: &mut dyn bytes::BufMut) {
169 let encoder = Encoder::new(buf);
170 encoder
171 .encode_field(&self.tx)
172 .encode_optional_field(&self.wrapper_version)
173 .encode_field(&self.blobs_bundle.blobs)
174 .encode_field(&self.blobs_bundle.commitments)
175 .encode_field(&self.blobs_bundle.proofs)
176 .finish();
177 }
178}
179
180impl RLPDecode for WrappedEIP4844Transaction {
181 fn decode_unfinished(rlp: &[u8]) -> Result<(WrappedEIP4844Transaction, &[u8]), RLPDecodeError> {
182 let decoder = Decoder::new(rlp)?;
183 let Ok((tx, decoder)) = decoder.decode_field("tx") else {
184 let (tx, rest) = EIP4844Transaction::decode_unfinished(rlp)?;
186 return Ok((
187 WrappedEIP4844Transaction {
188 tx,
189 wrapper_version: None,
190 blobs_bundle: BlobsBundle::empty(),
192 },
193 rest,
194 ));
195 };
196
197 let (wrapper_version, decoder) = decoder.decode_optional_field();
198 let (blobs, decoder) = decoder.decode_field("blobs")?;
199 let (commitments, decoder) = decoder.decode_field("commitments")?;
200 let (proofs, decoder) = decoder.decode_field("proofs")?;
201
202 let wrapped = WrappedEIP4844Transaction {
203 tx,
204 wrapper_version,
205 blobs_bundle: BlobsBundle {
206 blobs,
207 commitments,
208 proofs,
209 version: wrapper_version.unwrap_or_default(),
210 },
211 };
212 Ok((wrapped, decoder.finish()?))
213 }
214}
215
216#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
217pub struct LegacyTransaction {
218 pub nonce: u64,
219 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
220 pub gas_price: U256,
221 pub gas: u64,
222 pub to: TxKind,
225 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
226 pub value: U256,
227 #[rkyv(with=crate::rkyv_utils::BytesWrapper)]
228 pub data: Bytes,
229 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
230 pub v: U256,
231 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
232 pub r: U256,
233 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
234 pub s: U256,
235 #[rkyv(with=rkyv::with::Skip)]
236 pub inner_hash: OnceCell<H256>,
237 #[rkyv(with=rkyv::with::Skip)]
238 pub sender_cache: OnceCell<Address>,
239}
240
241#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
242pub struct EIP2930Transaction {
243 pub chain_id: u64,
244 pub nonce: u64,
245 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
246 pub gas_price: U256,
247 pub gas_limit: u64,
248 pub to: TxKind,
249 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
250 pub value: U256,
251 #[rkyv(with=crate::rkyv_utils::BytesWrapper)]
252 pub data: Bytes,
253 #[rkyv(with=rkyv::with::Map<crate::rkyv_utils::AccessListItemWrapper>)]
254 pub access_list: AccessList,
255 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
256 pub signature_y_parity: U256,
257 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
258 pub signature_r: U256,
259 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
260 pub signature_s: U256,
261 #[rkyv(with=rkyv::with::Skip)]
262 pub inner_hash: OnceCell<H256>,
263 #[rkyv(with=rkyv::with::Skip)]
264 pub sender_cache: OnceCell<Address>,
265 #[rkyv(with=rkyv::with::Skip)]
266 pub cached_canonical: OnceCell<Vec<u8>>,
267}
268
269#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
270pub struct EIP1559Transaction {
271 pub chain_id: u64,
272 pub nonce: u64,
273 pub max_priority_fee_per_gas: u64,
274 pub max_fee_per_gas: u64,
275 pub gas_limit: u64,
276 pub to: TxKind,
277 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
278 pub value: U256,
279 #[rkyv(with=crate::rkyv_utils::BytesWrapper)]
280 pub data: Bytes,
281 #[rkyv(with=rkyv::with::Map<crate::rkyv_utils::AccessListItemWrapper>)]
282 pub access_list: AccessList,
283 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
284 pub signature_y_parity: U256,
285 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
286 pub signature_r: U256,
287 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
288 pub signature_s: U256,
289 #[rkyv(with=rkyv::with::Skip)]
290 pub inner_hash: OnceCell<H256>,
291 #[rkyv(with=rkyv::with::Skip)]
292 pub sender_cache: OnceCell<Address>,
293 #[rkyv(with=rkyv::with::Skip)]
294 pub cached_canonical: OnceCell<Vec<u8>>,
295}
296
297#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
298pub struct EIP4844Transaction {
299 pub chain_id: u64,
300 pub nonce: u64,
301 pub max_priority_fee_per_gas: u64,
302 pub max_fee_per_gas: u64,
303 pub gas: u64,
304 #[rkyv(with=crate::rkyv_utils::H160Wrapper)]
305 pub to: Address,
306 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
307 pub value: U256,
308 #[rkyv(with=crate::rkyv_utils::BytesWrapper)]
309 pub data: Bytes,
310 #[rkyv(with=rkyv::with::Map<crate::rkyv_utils::AccessListItemWrapper>)]
311 pub access_list: AccessList,
312 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
313 pub max_fee_per_blob_gas: U256,
314 #[rkyv(with=rkyv::with::Map<crate::rkyv_utils::H256Wrapper>)]
315 pub blob_versioned_hashes: Vec<H256>,
316 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
317 pub signature_y_parity: U256,
318 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
319 pub signature_r: U256,
320 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
321 pub signature_s: U256,
322 #[rkyv(with=rkyv::with::Skip)]
323 pub inner_hash: OnceCell<H256>,
324 #[rkyv(with=rkyv::with::Skip)]
325 pub sender_cache: OnceCell<Address>,
326 #[rkyv(with=rkyv::with::Skip)]
327 pub cached_canonical: OnceCell<Vec<u8>>,
328}
329
330#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
331pub struct EIP7702Transaction {
332 pub chain_id: u64,
333 pub nonce: u64,
334 pub max_priority_fee_per_gas: u64,
335 pub max_fee_per_gas: u64,
336 pub gas_limit: u64,
337 #[rkyv(with=crate::rkyv_utils::H160Wrapper)]
338 pub to: Address,
339 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
340 pub value: U256,
341 #[rkyv(with=crate::rkyv_utils::BytesWrapper)]
342 pub data: Bytes,
343 #[rkyv(with=rkyv::with::Map<crate::rkyv_utils::AccessListItemWrapper>)]
344 pub access_list: AccessList,
345 pub authorization_list: AuthorizationList,
346 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
347 pub signature_y_parity: U256,
348 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
349 pub signature_r: U256,
350 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
351 pub signature_s: U256,
352 #[rkyv(with=rkyv::with::Skip)]
353 pub inner_hash: OnceCell<H256>,
354 #[rkyv(with=rkyv::with::Skip)]
355 pub sender_cache: OnceCell<Address>,
356 #[rkyv(with=rkyv::with::Skip)]
357 pub cached_canonical: OnceCell<Vec<u8>>,
358}
359#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
360pub struct PrivilegedL2Transaction {
361 pub chain_id: u64,
362 pub nonce: u64,
363 pub max_priority_fee_per_gas: u64,
364 pub max_fee_per_gas: u64,
365 pub gas_limit: u64,
366 pub to: TxKind,
367 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
368 pub value: U256,
369 #[rkyv(with=crate::rkyv_utils::BytesWrapper)]
370 pub data: Bytes,
371 #[rkyv(with=rkyv::with::Map<crate::rkyv_utils::AccessListItemWrapper>)]
372 pub access_list: AccessList,
373 #[rkyv(with=crate::rkyv_utils::H160Wrapper)]
374 pub from: Address,
375 #[rkyv(with=rkyv::with::Skip)]
376 pub inner_hash: OnceCell<H256>,
377 #[rkyv(with=rkyv::with::Skip)]
378 pub sender_cache: OnceCell<Address>,
379 #[rkyv(with=rkyv::with::Skip)]
380 pub cached_canonical: OnceCell<Vec<u8>>,
381}
382
383#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
384pub enum TxType {
385 #[default]
386 Legacy = 0x00,
387 EIP2930 = 0x01,
388 EIP1559 = 0x02,
389 EIP4844 = 0x03,
390 EIP7702 = 0x04,
391 Frame = 0x06,
392 FeeToken = 0x7d,
393 Privileged = 0x7e,
396}
397
398#[derive(Clone, Copy, Debug, PartialEq, Eq)]
404pub enum EnvelopeTxType {
405 EIP2930,
406 EIP1559,
407 EIP4844,
408 EIP7702,
409 Frame,
410 FeeToken,
411 Privileged,
412}
413
414impl EnvelopeTxType {
415 pub fn from_type_byte(byte: u8) -> Result<Self, RLPDecodeError> {
423 TxType::from_u8(byte)
424 .and_then(TxType::as_envelope)
425 .ok_or_else(|| RLPDecodeError::Custom(format!("Invalid transaction type: {byte}")))
426 }
427}
428
429impl From<TxType> for u8 {
430 fn from(val: TxType) -> Self {
431 match val {
432 TxType::Legacy => 0x00,
433 TxType::EIP2930 => 0x01,
434 TxType::EIP1559 => 0x02,
435 TxType::EIP4844 => 0x03,
436 TxType::EIP7702 => 0x04,
437 TxType::Frame => 0x06,
438 TxType::FeeToken => 0x7d,
439 TxType::Privileged => 0x7e,
440 }
441 }
442}
443
444impl Display for TxType {
445 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
446 match self {
447 TxType::Legacy => write!(f, "Legacy"),
448 TxType::EIP2930 => write!(f, "EIP2930"),
449 TxType::EIP1559 => write!(f, "EIP1559"),
450 TxType::EIP4844 => write!(f, "EIP4844"),
451 TxType::EIP7702 => write!(f, "EIP7702"),
452 TxType::Frame => write!(f, "Frame"),
453 TxType::Privileged => write!(f, "Privileged"),
454 TxType::FeeToken => write!(f, "FeeToken"),
455 }
456 }
457}
458
459impl Transaction {
460 pub fn tx_type(&self) -> TxType {
461 match self {
462 Transaction::LegacyTransaction(_) => TxType::Legacy,
463 Transaction::EIP2930Transaction(_) => TxType::EIP2930,
464 Transaction::EIP1559Transaction(_) => TxType::EIP1559,
465 Transaction::EIP4844Transaction(_) => TxType::EIP4844,
466 Transaction::EIP7702Transaction(_) => TxType::EIP7702,
467 Transaction::FeeTokenTransaction(_) => TxType::FeeToken,
468 Transaction::PrivilegedL2Transaction(_) => TxType::Privileged,
469 Transaction::FrameTransaction(_) => TxType::Frame,
470 }
471 }
472
473 fn calc_effective_gas_price(&self, base_fee_per_gas: Option<u64>) -> Option<U256> {
474 let base_fee = base_fee_per_gas?;
475 let max_fee = self.max_fee_per_gas()?;
476 if max_fee < base_fee {
477 return None;
479 }
480
481 let priority_fee_per_gas = min(self.max_priority_fee()?, max_fee.saturating_sub(base_fee));
482 Some(U256::from(priority_fee_per_gas) + U256::from(base_fee))
483 }
484
485 pub fn effective_gas_price(&self, base_fee_per_gas: Option<u64>) -> Option<U256> {
486 match self.tx_type() {
487 TxType::Legacy => Some(self.gas_price()),
488 TxType::EIP2930 => Some(self.gas_price()),
489 TxType::EIP1559 => self.calc_effective_gas_price(base_fee_per_gas),
490 TxType::EIP4844 => self.calc_effective_gas_price(base_fee_per_gas),
491 TxType::EIP7702 => self.calc_effective_gas_price(base_fee_per_gas),
492 TxType::Frame => self.calc_effective_gas_price(base_fee_per_gas),
493 TxType::FeeToken => self.calc_effective_gas_price(base_fee_per_gas),
494 TxType::Privileged => Some(self.gas_price()),
495 }
496 }
497
498 pub fn cost_without_base_fee(&self) -> Option<U256> {
499 let price = match self.tx_type() {
500 TxType::Legacy => self.gas_price(),
501 TxType::EIP2930 => self.gas_price(),
502 TxType::EIP1559 => U256::from(self.max_fee_per_gas()?),
503 TxType::EIP4844 => U256::from(self.max_fee_per_gas()?),
504 TxType::EIP7702 => U256::from(self.max_fee_per_gas()?),
505 TxType::Frame => U256::from(self.max_fee_per_gas()?),
506 TxType::FeeToken => U256::from(self.max_fee_per_gas()?),
507 TxType::Privileged => self.gas_price(),
508 };
509
510 let base = U256::saturating_add(
511 U256::saturating_mul(price, self.gas_limit().into()),
512 self.value(),
513 );
514
515 if let Transaction::EIP4844Transaction(tx) = self {
519 let blob_gas = U256::from(crate::constants::GAS_PER_BLOB)
520 .saturating_mul(U256::from(tx.blob_versioned_hashes.len() as u64));
521 let blob_cost = blob_gas.saturating_mul(tx.max_fee_per_blob_gas);
522 return Some(base.saturating_add(blob_cost));
523 }
524
525 Some(base)
526 }
527
528 pub fn fee_token(&self) -> Option<Address> {
529 if let Transaction::FeeTokenTransaction(tx) = self {
530 Some(tx.fee_token)
531 } else {
532 None
533 }
534 }
535
536 fn cached_canonical_cell(&self) -> Option<&OnceCell<Vec<u8>>> {
539 match self {
540 Transaction::LegacyTransaction(_) => None,
541 Transaction::EIP2930Transaction(t) => Some(&t.cached_canonical),
542 Transaction::EIP1559Transaction(t) => Some(&t.cached_canonical),
543 Transaction::EIP4844Transaction(t) => Some(&t.cached_canonical),
544 Transaction::EIP7702Transaction(t) => Some(&t.cached_canonical),
545 Transaction::PrivilegedL2Transaction(t) => Some(&t.cached_canonical),
546 Transaction::FeeTokenTransaction(t) => Some(&t.cached_canonical),
547 Transaction::FrameTransaction(t) => Some(&t.cached_canonical),
548 }
549 }
550}
551
552impl RLPEncode for Transaction {
553 fn encode(&self, buf: &mut dyn bytes::BufMut) {
558 match self {
559 Transaction::LegacyTransaction(t) => t.encode(buf),
560 _ => {
561 let canonical = self.encode_canonical_to_vec();
562 <[u8] as RLPEncode>::encode(canonical.as_slice(), buf)
563 }
564 };
565 }
566}
567
568impl RLPDecode for Transaction {
569 fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
574 let (is_list, payload, remainder) = decode_rlp_item(rlp)?;
575 if !is_list {
576 let tx_type = *payload.first().ok_or(RLPDecodeError::InvalidLength)?;
577 let tx_encoding = payload.get(1..).ok_or(RLPDecodeError::InvalidLength)?;
578 let tx = match EnvelopeTxType::from_type_byte(tx_type)? {
582 EnvelopeTxType::EIP2930 => {
583 Transaction::EIP2930Transaction(EIP2930Transaction::decode(tx_encoding)?)
584 }
585 EnvelopeTxType::EIP1559 => {
586 Transaction::EIP1559Transaction(EIP1559Transaction::decode(tx_encoding)?)
587 }
588 EnvelopeTxType::EIP4844 => {
589 Transaction::EIP4844Transaction(EIP4844Transaction::decode(tx_encoding)?)
590 }
591 EnvelopeTxType::EIP7702 => {
592 Transaction::EIP7702Transaction(EIP7702Transaction::decode(tx_encoding)?)
593 }
594 EnvelopeTxType::Frame => {
595 Transaction::FrameTransaction(FrameTransaction::decode(tx_encoding)?)
596 }
597 EnvelopeTxType::FeeToken => {
598 Transaction::FeeTokenTransaction(FeeTokenTransaction::decode(tx_encoding)?)
599 }
600 EnvelopeTxType::Privileged => Transaction::PrivilegedL2Transaction(
601 PrivilegedL2Transaction::decode(tx_encoding)?,
602 ),
603 };
604 Ok((tx, remainder))
605 } else {
606 LegacyTransaction::decode_unfinished(rlp)
608 .map(|(tx, rem)| (Transaction::LegacyTransaction(tx), rem))
609 }
610 }
611}
612
613#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
615pub enum TxKind {
616 Call(#[rkyv(with=crate::rkyv_utils::H160Wrapper)] Address),
617 #[default]
618 Create,
619}
620
621impl RLPEncode for TxKind {
622 fn encode(&self, buf: &mut dyn bytes::BufMut) {
623 match self {
624 Self::Call(address) => address.encode(buf),
625 Self::Create => buf.put_u8(RLP_NULL),
626 }
627 }
628}
629
630impl RLPDecode for TxKind {
631 fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
632 let first_byte = rlp.first().ok_or(RLPDecodeError::InvalidLength)?;
633 if *first_byte == RLP_NULL {
634 return Ok((Self::Create, &rlp[1..]));
635 }
636 Address::decode_unfinished(rlp).map(|(t, rest)| (Self::Call(t), rest))
637 }
638}
639
640impl RLPEncode for LegacyTransaction {
641 fn encode(&self, buf: &mut dyn bytes::BufMut) {
642 Encoder::new(buf)
643 .encode_field(&self.nonce)
644 .encode_field(&self.gas_price)
645 .encode_field(&self.gas)
646 .encode_field(&self.to)
647 .encode_field(&self.value)
648 .encode_field(&self.data)
649 .encode_field(&self.v)
650 .encode_field(&self.r)
651 .encode_field(&self.s)
652 .finish();
653 }
654}
655
656impl RLPEncode for EIP2930Transaction {
657 fn encode(&self, buf: &mut dyn bytes::BufMut) {
658 Encoder::new(buf)
659 .encode_field(&self.chain_id)
660 .encode_field(&self.nonce)
661 .encode_field(&self.gas_price)
662 .encode_field(&self.gas_limit)
663 .encode_field(&self.to)
664 .encode_field(&self.value)
665 .encode_field(&self.data)
666 .encode_field(&self.access_list)
667 .encode_field(&self.signature_y_parity)
668 .encode_field(&self.signature_r)
669 .encode_field(&self.signature_s)
670 .finish()
671 }
672}
673
674impl RLPEncode for EIP1559Transaction {
675 fn encode(&self, buf: &mut dyn bytes::BufMut) {
676 Encoder::new(buf)
677 .encode_field(&self.chain_id)
678 .encode_field(&self.nonce)
679 .encode_field(&self.max_priority_fee_per_gas)
680 .encode_field(&self.max_fee_per_gas)
681 .encode_field(&self.gas_limit)
682 .encode_field(&self.to)
683 .encode_field(&self.value)
684 .encode_field(&self.data)
685 .encode_field(&self.access_list)
686 .encode_field(&self.signature_y_parity)
687 .encode_field(&self.signature_r)
688 .encode_field(&self.signature_s)
689 .finish()
690 }
691}
692
693impl RLPEncode for EIP4844Transaction {
694 fn encode(&self, buf: &mut dyn bytes::BufMut) {
695 Encoder::new(buf)
696 .encode_field(&self.chain_id)
697 .encode_field(&self.nonce)
698 .encode_field(&self.max_priority_fee_per_gas)
699 .encode_field(&self.max_fee_per_gas)
700 .encode_field(&self.gas)
701 .encode_field(&self.to)
702 .encode_field(&self.value)
703 .encode_field(&self.data)
704 .encode_field(&self.access_list)
705 .encode_field(&self.max_fee_per_blob_gas)
706 .encode_field(&self.blob_versioned_hashes)
707 .encode_field(&self.signature_y_parity)
708 .encode_field(&self.signature_r)
709 .encode_field(&self.signature_s)
710 .finish()
711 }
712}
713
714impl RLPEncode for EIP7702Transaction {
715 fn encode(&self, buf: &mut dyn bytes::BufMut) {
716 Encoder::new(buf)
717 .encode_field(&self.chain_id)
718 .encode_field(&self.nonce)
719 .encode_field(&self.max_priority_fee_per_gas)
720 .encode_field(&self.max_fee_per_gas)
721 .encode_field(&self.gas_limit)
722 .encode_field(&self.to)
723 .encode_field(&self.value)
724 .encode_field(&self.data)
725 .encode_field(&self.access_list)
726 .encode_field(&self.authorization_list)
727 .encode_field(&self.signature_y_parity)
728 .encode_field(&self.signature_r)
729 .encode_field(&self.signature_s)
730 .finish()
731 }
732}
733
734impl RLPEncode for PrivilegedL2Transaction {
735 fn encode(&self, buf: &mut dyn bytes::BufMut) {
736 Encoder::new(buf)
737 .encode_field(&self.chain_id)
738 .encode_field(&self.nonce)
739 .encode_field(&self.max_priority_fee_per_gas)
740 .encode_field(&self.max_fee_per_gas)
741 .encode_field(&self.gas_limit)
742 .encode_field(&self.to)
743 .encode_field(&self.value)
744 .encode_field(&self.data)
745 .encode_field(&self.access_list)
746 .encode_field(&self.from)
747 .finish()
748 }
749}
750
751impl RLPEncode for FeeTokenTransaction {
752 fn encode(&self, buf: &mut dyn bytes::BufMut) {
753 Encoder::new(buf)
754 .encode_field(&self.chain_id)
755 .encode_field(&self.nonce)
756 .encode_field(&self.max_priority_fee_per_gas)
757 .encode_field(&self.max_fee_per_gas)
758 .encode_field(&self.gas_limit)
759 .encode_field(&self.to)
760 .encode_field(&self.value)
761 .encode_field(&self.data)
762 .encode_field(&self.access_list)
763 .encode_field(&self.fee_token)
764 .encode_field(&self.signature_y_parity)
765 .encode_field(&self.signature_r)
766 .encode_field(&self.signature_s)
767 .finish()
768 }
769}
770
771impl PayloadRLPEncode for Transaction {
772 fn encode_payload(&self, buf: &mut dyn bytes::BufMut) {
773 match self {
774 Transaction::LegacyTransaction(tx) => tx.encode_payload(buf),
775 Transaction::EIP1559Transaction(tx) => tx.encode_payload(buf),
776 Transaction::EIP2930Transaction(tx) => tx.encode_payload(buf),
777 Transaction::EIP4844Transaction(tx) => tx.encode_payload(buf),
778 Transaction::EIP7702Transaction(tx) => tx.encode_payload(buf),
779 Transaction::PrivilegedL2Transaction(tx) => tx.encode_payload(buf),
780 Transaction::FeeTokenTransaction(tx) => tx.encode_payload(buf),
781 Transaction::FrameTransaction(tx) => tx.encode_payload(buf),
782 }
783 }
784}
785
786impl PayloadRLPEncode for LegacyTransaction {
787 fn encode_payload(&self, buf: &mut dyn bytes::BufMut) {
788 Encoder::new(buf)
789 .encode_field(&self.nonce)
790 .encode_field(&self.gas_price)
791 .encode_field(&self.gas)
792 .encode_field(&self.to)
793 .encode_field(&self.value)
794 .encode_field(&self.data)
795 .finish();
796 }
797}
798
799impl PayloadRLPEncode for EIP1559Transaction {
800 fn encode_payload(&self, buf: &mut dyn bytes::BufMut) {
801 Encoder::new(buf)
802 .encode_field(&self.chain_id)
803 .encode_field(&self.nonce)
804 .encode_field(&self.max_priority_fee_per_gas)
805 .encode_field(&self.max_fee_per_gas)
806 .encode_field(&self.gas_limit)
807 .encode_field(&self.to)
808 .encode_field(&self.value)
809 .encode_field(&self.data)
810 .encode_field(&self.access_list)
811 .finish();
812 }
813}
814
815impl PayloadRLPEncode for EIP2930Transaction {
816 fn encode_payload(&self, buf: &mut dyn bytes::BufMut) {
817 Encoder::new(buf)
818 .encode_field(&self.chain_id)
819 .encode_field(&self.nonce)
820 .encode_field(&self.gas_price)
821 .encode_field(&self.gas_limit)
822 .encode_field(&self.to)
823 .encode_field(&self.value)
824 .encode_field(&self.data)
825 .encode_field(&self.access_list)
826 .finish();
827 }
828}
829
830impl PayloadRLPEncode for EIP4844Transaction {
831 fn encode_payload(&self, buf: &mut dyn bytes::BufMut) {
832 Encoder::new(buf)
833 .encode_field(&self.chain_id)
834 .encode_field(&self.nonce)
835 .encode_field(&self.max_priority_fee_per_gas)
836 .encode_field(&self.max_fee_per_gas)
837 .encode_field(&self.gas)
838 .encode_field(&self.to)
839 .encode_field(&self.value)
840 .encode_field(&self.data)
841 .encode_field(&self.access_list)
842 .encode_field(&self.max_fee_per_blob_gas)
843 .encode_field(&self.blob_versioned_hashes)
844 .finish();
845 }
846}
847
848impl PayloadRLPEncode for EIP7702Transaction {
849 fn encode_payload(&self, buf: &mut dyn bytes::BufMut) {
850 Encoder::new(buf)
851 .encode_field(&self.chain_id)
852 .encode_field(&self.nonce)
853 .encode_field(&self.max_priority_fee_per_gas)
854 .encode_field(&self.max_fee_per_gas)
855 .encode_field(&self.gas_limit)
856 .encode_field(&self.to)
857 .encode_field(&self.value)
858 .encode_field(&self.data)
859 .encode_field(&self.access_list)
860 .encode_field(&self.authorization_list)
861 .finish();
862 }
863}
864
865impl PayloadRLPEncode for PrivilegedL2Transaction {
866 fn encode_payload(&self, buf: &mut dyn bytes::BufMut) {
867 Encoder::new(buf)
868 .encode_field(&self.chain_id)
869 .encode_field(&self.nonce)
870 .encode_field(&self.max_priority_fee_per_gas)
871 .encode_field(&self.max_fee_per_gas)
872 .encode_field(&self.gas_limit)
873 .encode_field(&self.to)
874 .encode_field(&self.value)
875 .encode_field(&self.data)
876 .encode_field(&self.access_list)
877 .encode_field(&self.from)
878 .finish();
879 }
880}
881
882impl PayloadRLPEncode for FeeTokenTransaction {
883 fn encode_payload(&self, buf: &mut dyn bytes::BufMut) {
884 Encoder::new(buf)
885 .encode_field(&self.chain_id)
886 .encode_field(&self.nonce)
887 .encode_field(&self.max_priority_fee_per_gas)
888 .encode_field(&self.max_fee_per_gas)
889 .encode_field(&self.gas_limit)
890 .encode_field(&self.to)
891 .encode_field(&self.value)
892 .encode_field(&self.data)
893 .encode_field(&self.access_list)
894 .encode_field(&self.fee_token)
895 .finish();
896 }
897}
898
899fn decode_nonce_field(decoder: Decoder) -> Result<(u64, Decoder), RLPDecodeError> {
909 let wrap =
913 |err| RLPDecodeError::Custom(format!("Error decoding field 'nonce' of type u64: {err}"));
914 let (item, rest) = decoder.get_encoded_item_ref().map_err(wrap)?;
915 if let Ok((content, _)) = decode_bytes(item)
927 && content.len() > 8
928 && content.first() != Some(&0)
929 {
930 return Err(RLPDecodeError::Custom("Nonce is max".into()));
931 }
932 let (nonce, _) = u64::decode_unfinished(item).map_err(wrap)?;
933 Ok((nonce, rest))
934}
935
936impl RLPDecode for LegacyTransaction {
937 fn decode_unfinished(rlp: &[u8]) -> Result<(LegacyTransaction, &[u8]), RLPDecodeError> {
938 let decoder = Decoder::new(rlp)?;
939 let (nonce, decoder) = decode_nonce_field(decoder)?;
940 let (gas_price, decoder) = decoder.decode_field("gas_price")?;
941 let (gas, decoder) = decoder.decode_field("gas")?;
942 let (to, decoder) = decoder.decode_field("to")?;
943 let (value, decoder) = decoder.decode_field("value")?;
944 let (data, decoder) = decoder.decode_field("data")?;
945 let (v, decoder) = decoder.decode_field("v")?;
946 let (r, decoder) = decoder.decode_field("r")?;
947 let (s, decoder) = decoder.decode_field("s")?;
948 let inner_hash = OnceCell::new();
949 let sender_cache = OnceCell::new();
950
951 let tx = LegacyTransaction {
952 nonce,
953 gas_price,
954 gas,
955 to,
956 value,
957 data,
958 v,
959 r,
960 s,
961 inner_hash,
962 sender_cache,
963 };
964 Ok((tx, decoder.finish()?))
965 }
966}
967
968impl RLPDecode for EIP2930Transaction {
969 fn decode_unfinished(rlp: &[u8]) -> Result<(EIP2930Transaction, &[u8]), RLPDecodeError> {
970 let decoder = Decoder::new(rlp)?;
971 let (chain_id, decoder) = decoder.decode_field("chain_id")?;
972 let (nonce, decoder) = decode_nonce_field(decoder)?;
973 let (gas_price, decoder) = decoder.decode_field("gas_price")?;
974 let (gas_limit, decoder) = decoder.decode_field("gas_limit")?;
975 let (to, decoder) = decoder.decode_field("to")?;
976 let (value, decoder) = decoder.decode_field("value")?;
977 let (data, decoder) = decoder.decode_field("data")?;
978 let (access_list, decoder) = decoder.decode_field("access_list")?;
979 let (signature_y_parity, decoder) = decoder.decode_field("signature_y_parity")?;
980 let (signature_r, decoder) = decoder.decode_field("signature_r")?;
981 let (signature_s, decoder) = decoder.decode_field("signature_s")?;
982 let inner_hash = OnceCell::new();
983 let sender_cache = OnceCell::new();
984 let cached_canonical = OnceCell::new();
985
986 let tx = EIP2930Transaction {
987 chain_id,
988 nonce,
989 gas_price,
990 gas_limit,
991 to,
992 value,
993 data,
994 access_list,
995 signature_y_parity,
996 signature_r,
997 signature_s,
998 inner_hash,
999 sender_cache,
1000 cached_canonical,
1001 };
1002 Ok((tx, decoder.finish()?))
1003 }
1004}
1005
1006impl RLPDecode for EIP1559Transaction {
1007 fn decode_unfinished(rlp: &[u8]) -> Result<(EIP1559Transaction, &[u8]), RLPDecodeError> {
1008 let decoder = Decoder::new(rlp)?;
1009 let (chain_id, decoder) = decoder.decode_field("chain_id")?;
1010 let (nonce, decoder) = decode_nonce_field(decoder)?;
1011 let (max_priority_fee_per_gas, decoder) =
1012 decoder.decode_field("max_priority_fee_per_gas")?;
1013 let (max_fee_per_gas, decoder) = decoder.decode_field("max_fee_per_gas")?;
1014 let (gas_limit, decoder) = decoder.decode_field("gas_limit")?;
1015 let (to, decoder) = decoder.decode_field("to")?;
1016 let (value, decoder) = decoder.decode_field("value")?;
1017 let (data, decoder) = decoder.decode_field("data")?;
1018 let (access_list, decoder) = decoder.decode_field("access_list")?;
1019 let (signature_y_parity, decoder) = decoder.decode_field("signature_y_parity")?;
1020 let (signature_r, decoder) = decoder.decode_field("signature_r")?;
1021 let (signature_s, decoder) = decoder.decode_field("signature_s")?;
1022 let inner_hash = OnceCell::new();
1023 let sender_cache = OnceCell::new();
1024 let cached_canonical = OnceCell::new();
1025
1026 let tx = EIP1559Transaction {
1027 chain_id,
1028 nonce,
1029 max_priority_fee_per_gas,
1030 max_fee_per_gas,
1031 gas_limit,
1032 to,
1033 value,
1034 data,
1035 access_list,
1036 signature_y_parity,
1037 signature_r,
1038 signature_s,
1039 inner_hash,
1040 sender_cache,
1041 cached_canonical,
1042 };
1043 Ok((tx, decoder.finish()?))
1044 }
1045}
1046
1047impl RLPDecode for EIP4844Transaction {
1048 fn decode_unfinished(rlp: &[u8]) -> Result<(EIP4844Transaction, &[u8]), RLPDecodeError> {
1049 let decoder = Decoder::new(rlp)?;
1050 let (chain_id, decoder) = decoder.decode_field("chain_id")?;
1051 let (nonce, decoder) = decode_nonce_field(decoder)?;
1052 let (max_priority_fee_per_gas, decoder) =
1053 decoder.decode_field("max_priority_fee_per_gas")?;
1054 let (max_fee_per_gas, decoder) = decoder.decode_field("max_fee_per_gas")?;
1055 let (gas, decoder) = decoder.decode_field("gas")?;
1056 let (to, decoder) = decoder.decode_field("to")?;
1057 let (value, decoder) = decoder.decode_field("value")?;
1058 let (data, decoder) = decoder.decode_field("data")?;
1059 let (access_list, decoder) = decoder.decode_field("access_list")?;
1060 let (max_fee_per_blob_gas, decoder) = decoder.decode_field("max_fee_per_blob_gas")?;
1061 let (blob_versioned_hashes, decoder) = decoder.decode_field("blob_versioned_hashes")?;
1062 let (signature_y_parity, decoder) = decoder.decode_field("signature_y_parity")?;
1063 let (signature_r, decoder) = decoder.decode_field("signature_r")?;
1064 let (signature_s, decoder) = decoder.decode_field("signature_s")?;
1065 let inner_hash = OnceCell::new();
1066 let sender_cache = OnceCell::new();
1067 let cached_canonical = OnceCell::new();
1068
1069 let tx = EIP4844Transaction {
1070 chain_id,
1071 nonce,
1072 max_priority_fee_per_gas,
1073 max_fee_per_gas,
1074 gas,
1075 to,
1076 value,
1077 data,
1078 access_list,
1079 max_fee_per_blob_gas,
1080 blob_versioned_hashes,
1081 signature_y_parity,
1082 signature_r,
1083 signature_s,
1084 inner_hash,
1085 sender_cache,
1086 cached_canonical,
1087 };
1088 Ok((tx, decoder.finish()?))
1089 }
1090}
1091
1092impl RLPDecode for EIP7702Transaction {
1093 fn decode_unfinished(rlp: &[u8]) -> Result<(EIP7702Transaction, &[u8]), RLPDecodeError> {
1094 let decoder = Decoder::new(rlp)?;
1095 let (chain_id, decoder) = decoder.decode_field("chain_id")?;
1096 let (nonce, decoder) = decode_nonce_field(decoder)?;
1097 let (max_priority_fee_per_gas, decoder) =
1098 decoder.decode_field("max_priority_fee_per_gas")?;
1099 let (max_fee_per_gas, decoder) = decoder.decode_field("max_fee_per_gas")?;
1100 let (gas_limit, decoder) = decoder.decode_field("gas_limit")?;
1101 let (to, decoder) = decoder.decode_field("to")?;
1102 let (value, decoder) = decoder.decode_field("value")?;
1103 let (data, decoder) = decoder.decode_field("data")?;
1104 let (access_list, decoder) = decoder.decode_field("access_list")?;
1105 let (authorization_list, decoder) = decoder.decode_field("authorization_list")?;
1106 let (signature_y_parity, decoder) = decoder.decode_field("signature_y_parity")?;
1107 let (signature_r, decoder) = decoder.decode_field("signature_r")?;
1108 let (signature_s, decoder) = decoder.decode_field("signature_s")?;
1109 let inner_hash = OnceCell::new();
1110 let sender_cache = OnceCell::new();
1111 let cached_canonical = OnceCell::new();
1112
1113 let tx = EIP7702Transaction {
1114 chain_id,
1115 nonce,
1116 max_priority_fee_per_gas,
1117 max_fee_per_gas,
1118 gas_limit,
1119 to,
1120 value,
1121 data,
1122 access_list,
1123 authorization_list,
1124 signature_y_parity,
1125 signature_r,
1126 signature_s,
1127 inner_hash,
1128 sender_cache,
1129 cached_canonical,
1130 };
1131 Ok((tx, decoder.finish()?))
1132 }
1133}
1134
1135impl RLPDecode for PrivilegedL2Transaction {
1136 fn decode_unfinished(rlp: &[u8]) -> Result<(PrivilegedL2Transaction, &[u8]), RLPDecodeError> {
1137 let decoder = Decoder::new(rlp)?;
1138 let (chain_id, decoder) = decoder.decode_field("chain_id")?;
1139 let (nonce, decoder) = decode_nonce_field(decoder)?;
1140 let (max_priority_fee_per_gas, decoder) =
1141 decoder.decode_field("max_priority_fee_per_gas")?;
1142 let (max_fee_per_gas, decoder) = decoder.decode_field("max_fee_per_gas")?;
1143 let (gas_limit, decoder) = decoder.decode_field::<u64>("gas_limit")?;
1144 let (to, decoder) = decoder.decode_field("to")?;
1145 let (value, decoder) = decoder.decode_field("value")?;
1146 let (data, decoder) = decoder.decode_field("data")?;
1147 let (access_list, decoder) = decoder.decode_field("access_list")?;
1148 let (from, decoder) = decoder.decode_field("from")?;
1149 let inner_hash = OnceCell::new();
1150 let sender_cache = OnceCell::new();
1151 let cached_canonical = OnceCell::new();
1152
1153 let tx = PrivilegedL2Transaction {
1154 chain_id,
1155 nonce,
1156 max_priority_fee_per_gas,
1157 max_fee_per_gas,
1158 gas_limit,
1159 to,
1160 value,
1161 data,
1162 access_list,
1163 from,
1164 inner_hash,
1165 sender_cache,
1166 cached_canonical,
1167 };
1168 Ok((tx, decoder.finish()?))
1169 }
1170}
1171
1172impl RLPDecode for FeeTokenTransaction {
1173 fn decode_unfinished(rlp: &[u8]) -> Result<(FeeTokenTransaction, &[u8]), RLPDecodeError> {
1174 let decoder = Decoder::new(rlp)?;
1175 let (chain_id, decoder) = decoder.decode_field("chain_id")?;
1176 let (nonce, decoder) = decode_nonce_field(decoder)?;
1177 let (max_priority_fee_per_gas, decoder) =
1178 decoder.decode_field("max_priority_fee_per_gas")?;
1179 let (max_fee_per_gas, decoder) = decoder.decode_field("max_fee_per_gas")?;
1180 let (gas_limit, decoder) = decoder.decode_field("gas_limit")?;
1181 let (to, decoder) = decoder.decode_field("to")?;
1182 let (value, decoder) = decoder.decode_field("value")?;
1183 let (data, decoder) = decoder.decode_field("data")?;
1184 let (access_list, decoder) = decoder.decode_field("access_list")?;
1185 let (fee_token, decoder) = decoder.decode_field("fee_token")?;
1186 let (signature_y_parity, decoder) = decoder.decode_field("signature_y_parity")?;
1187 let (signature_r, decoder) = decoder.decode_field("signature_r")?;
1188 let (signature_s, decoder) = decoder.decode_field("signature_s")?;
1189 let inner_hash = OnceCell::new();
1190 let sender_cache = OnceCell::new();
1191 let cached_canonical = OnceCell::new();
1192
1193 let tx = FeeTokenTransaction {
1194 chain_id,
1195 nonce,
1196 max_priority_fee_per_gas,
1197 max_fee_per_gas,
1198 gas_limit,
1199 to,
1200 value,
1201 data,
1202 access_list,
1203 fee_token,
1204 signature_y_parity,
1205 signature_r,
1206 signature_s,
1207 inner_hash,
1208 sender_cache,
1209 cached_canonical,
1210 };
1211 Ok((tx, decoder.finish()?))
1212 }
1213}
1214
1215pub type SigningPayload = (Vec<u8>, [u8; 65]);
1218
1219fn signature_parity(value: U256) -> Result<u8, CryptoError> {
1220 if value.is_zero() {
1221 Ok(0)
1222 } else if value == U256::one() {
1223 Ok(1)
1224 } else {
1225 Err(CryptoError::InvalidSignature)
1226 }
1227}
1228
1229impl Transaction {
1230 pub fn sender(&self, crypto: &dyn Crypto) -> Result<Address, CryptoError> {
1231 if let Transaction::FrameTransaction(tx) = self {
1233 return Ok(tx.sender);
1234 }
1235 let sender_cache = match self {
1236 Transaction::LegacyTransaction(tx) => &tx.sender_cache,
1237 Transaction::EIP2930Transaction(tx) => &tx.sender_cache,
1238 Transaction::EIP1559Transaction(tx) => &tx.sender_cache,
1239 Transaction::EIP4844Transaction(tx) => &tx.sender_cache,
1240 Transaction::EIP7702Transaction(tx) => &tx.sender_cache,
1241 Transaction::PrivilegedL2Transaction(tx) => &tx.sender_cache,
1242 Transaction::FeeTokenTransaction(tx) => &tx.sender_cache,
1243 Transaction::FrameTransaction(_) => unreachable!(),
1244 };
1245 sender_cache
1246 .get_or_try_init(|| {
1247 let tx_hash = self.hash(crypto);
1248 let mut cache = GLOBAL_SIGNER_CACHE
1250 .lock()
1251 .unwrap_or_else(|e| e.into_inner());
1252 if let Some(&addr) = cache.get(&tx_hash) {
1253 return Ok(addr);
1254 }
1255 drop(cache);
1256 let sender = self.compute_sender(crypto)?;
1258 GLOBAL_SIGNER_CACHE
1260 .lock()
1261 .unwrap_or_else(|e| e.into_inner())
1262 .put(tx_hash, sender);
1263 Ok(sender)
1264 })
1265 .copied()
1266 }
1267
1268 pub fn signing_payload(&self) -> Result<Option<SigningPayload>, CryptoError> {
1277 let (buf, sig) = match self {
1278 Transaction::LegacyTransaction(tx) => {
1279 let chain_id = self.chain_id();
1286 let signature_y_parity = match chain_id {
1287 Some(_) => !tx.v.bit(0),
1290 None if tx.v == U256::from(27) => false,
1291 None if tx.v == U256::from(28) => true,
1292 None => return Err(CryptoError::InvalidSignature),
1293 };
1294 let mut buf = vec![];
1295 match chain_id {
1296 None => Encoder::new(&mut buf)
1297 .encode_field(&tx.nonce)
1298 .encode_field(&tx.gas_price)
1299 .encode_field(&tx.gas)
1300 .encode_field(&tx.to)
1301 .encode_field(&tx.value)
1302 .encode_field(&tx.data)
1303 .finish(),
1304 Some(chain_id) => Encoder::new(&mut buf)
1305 .encode_field(&tx.nonce)
1306 .encode_field(&tx.gas_price)
1307 .encode_field(&tx.gas)
1308 .encode_field(&tx.to)
1309 .encode_field(&tx.value)
1310 .encode_field(&tx.data)
1311 .encode_field(&chain_id)
1312 .encode_field(&0u8)
1313 .encode_field(&0u8)
1314 .finish(),
1315 }
1316 let mut sig = [0u8; 65];
1317 sig[..32].copy_from_slice(&tx.r.to_big_endian());
1318 sig[32..64].copy_from_slice(&tx.s.to_big_endian());
1319 sig[64] = signature_y_parity as u8;
1320 (buf, sig)
1321 }
1322 Transaction::EIP2930Transaction(tx) => {
1323 let mut buf = vec![self.tx_type() as u8];
1324 Encoder::new(&mut buf)
1325 .encode_field(&tx.chain_id)
1326 .encode_field(&tx.nonce)
1327 .encode_field(&tx.gas_price)
1328 .encode_field(&tx.gas_limit)
1329 .encode_field(&tx.to)
1330 .encode_field(&tx.value)
1331 .encode_field(&tx.data)
1332 .encode_field(&tx.access_list)
1333 .finish();
1334 let mut sig = [0u8; 65];
1335 sig[..32].copy_from_slice(&tx.signature_r.to_big_endian());
1336 sig[32..64].copy_from_slice(&tx.signature_s.to_big_endian());
1337 sig[64] = signature_parity(tx.signature_y_parity)?;
1338 (buf, sig)
1339 }
1340 Transaction::EIP1559Transaction(tx) => {
1341 let mut buf = vec![self.tx_type() as u8];
1342 Encoder::new(&mut buf)
1343 .encode_field(&tx.chain_id)
1344 .encode_field(&tx.nonce)
1345 .encode_field(&tx.max_priority_fee_per_gas)
1346 .encode_field(&tx.max_fee_per_gas)
1347 .encode_field(&tx.gas_limit)
1348 .encode_field(&tx.to)
1349 .encode_field(&tx.value)
1350 .encode_field(&tx.data)
1351 .encode_field(&tx.access_list)
1352 .finish();
1353 let mut sig = [0u8; 65];
1354 sig[..32].copy_from_slice(&tx.signature_r.to_big_endian());
1355 sig[32..64].copy_from_slice(&tx.signature_s.to_big_endian());
1356 sig[64] = signature_parity(tx.signature_y_parity)?;
1357 (buf, sig)
1358 }
1359 Transaction::EIP4844Transaction(tx) => {
1360 let mut buf = vec![self.tx_type() as u8];
1361 Encoder::new(&mut buf)
1362 .encode_field(&tx.chain_id)
1363 .encode_field(&tx.nonce)
1364 .encode_field(&tx.max_priority_fee_per_gas)
1365 .encode_field(&tx.max_fee_per_gas)
1366 .encode_field(&tx.gas)
1367 .encode_field(&tx.to)
1368 .encode_field(&tx.value)
1369 .encode_field(&tx.data)
1370 .encode_field(&tx.access_list)
1371 .encode_field(&tx.max_fee_per_blob_gas)
1372 .encode_field(&tx.blob_versioned_hashes)
1373 .finish();
1374 let mut sig = [0u8; 65];
1375 sig[..32].copy_from_slice(&tx.signature_r.to_big_endian());
1376 sig[32..64].copy_from_slice(&tx.signature_s.to_big_endian());
1377 sig[64] = signature_parity(tx.signature_y_parity)?;
1378 (buf, sig)
1379 }
1380 Transaction::EIP7702Transaction(tx) => {
1381 let mut buf = vec![self.tx_type() as u8];
1382 Encoder::new(&mut buf)
1383 .encode_field(&tx.chain_id)
1384 .encode_field(&tx.nonce)
1385 .encode_field(&tx.max_priority_fee_per_gas)
1386 .encode_field(&tx.max_fee_per_gas)
1387 .encode_field(&tx.gas_limit)
1388 .encode_field(&tx.to)
1389 .encode_field(&tx.value)
1390 .encode_field(&tx.data)
1391 .encode_field(&tx.access_list)
1392 .encode_field(&tx.authorization_list)
1393 .finish();
1394 let mut sig = [0u8; 65];
1395 sig[..32].copy_from_slice(&tx.signature_r.to_big_endian());
1396 sig[32..64].copy_from_slice(&tx.signature_s.to_big_endian());
1397 sig[64] = signature_parity(tx.signature_y_parity)?;
1398 (buf, sig)
1399 }
1400 Transaction::PrivilegedL2Transaction(_) | Transaction::FrameTransaction(_) => {
1402 return Ok(None);
1403 }
1404 Transaction::FeeTokenTransaction(tx) => {
1405 let mut buf = vec![self.tx_type() as u8];
1406 Encoder::new(&mut buf)
1407 .encode_field(&tx.chain_id)
1408 .encode_field(&tx.nonce)
1409 .encode_field(&tx.max_priority_fee_per_gas)
1410 .encode_field(&tx.max_fee_per_gas)
1411 .encode_field(&tx.gas_limit)
1412 .encode_field(&tx.to)
1413 .encode_field(&tx.value)
1414 .encode_field(&tx.data)
1415 .encode_field(&tx.access_list)
1416 .encode_field(&tx.fee_token)
1417 .finish();
1418 let mut sig = [0u8; 65];
1419 sig[..32].copy_from_slice(&tx.signature_r.to_big_endian());
1420 sig[32..64].copy_from_slice(&tx.signature_s.to_big_endian());
1421 sig[64] = signature_parity(tx.signature_y_parity)?;
1422 (buf, sig)
1423 }
1424 };
1425 Ok(Some((buf, sig)))
1426 }
1427
1428 fn compute_sender(&self, crypto: &dyn Crypto) -> Result<Address, CryptoError> {
1429 match self {
1430 Transaction::PrivilegedL2Transaction(tx) => return Ok(tx.from),
1431 Transaction::FrameTransaction(tx) => return Ok(tx.sender),
1432 _ => {}
1433 }
1434 let Some((buf, sig)) = self.signing_payload()? else {
1435 return Err(CryptoError::InvalidSignature);
1437 };
1438 let msg = crypto.keccak256(&buf);
1439 crypto.recover_signer(&sig, &msg)
1440 }
1441
1442 pub fn gas_limit(&self) -> u64 {
1443 match self {
1444 Transaction::LegacyTransaction(tx) => tx.gas,
1445 Transaction::EIP2930Transaction(tx) => tx.gas_limit,
1446 Transaction::EIP1559Transaction(tx) => tx.gas_limit,
1447 Transaction::EIP7702Transaction(tx) => tx.gas_limit,
1448 Transaction::EIP4844Transaction(tx) => tx.gas,
1449 Transaction::PrivilegedL2Transaction(tx) => tx.gas_limit,
1450 Transaction::FeeTokenTransaction(tx) => tx.gas_limit,
1451 Transaction::FrameTransaction(tx) => tx.max_gas(),
1452 }
1453 }
1454
1455 pub fn gas_price(&self) -> U256 {
1457 match self {
1458 Transaction::LegacyTransaction(tx) => tx.gas_price,
1459 Transaction::EIP2930Transaction(tx) => tx.gas_price,
1460 Transaction::EIP1559Transaction(tx) => U256::from(tx.max_fee_per_gas),
1461 Transaction::EIP7702Transaction(tx) => U256::from(tx.max_fee_per_gas),
1462 Transaction::EIP4844Transaction(tx) => U256::from(tx.max_fee_per_gas),
1463 Transaction::PrivilegedL2Transaction(tx) => U256::from(tx.max_fee_per_gas),
1464 Transaction::FeeTokenTransaction(tx) => U256::from(tx.max_fee_per_gas),
1465 Transaction::FrameTransaction(tx) => U256::from(tx.max_fee_per_gas),
1466 }
1467 }
1468
1469 pub fn to(&self) -> TxKind {
1470 match self {
1471 Transaction::LegacyTransaction(tx) => tx.to.clone(),
1472 Transaction::EIP2930Transaction(tx) => tx.to.clone(),
1473 Transaction::EIP1559Transaction(tx) => tx.to.clone(),
1474 Transaction::EIP4844Transaction(tx) => TxKind::Call(tx.to),
1475 Transaction::EIP7702Transaction(tx) => TxKind::Call(tx.to),
1476 Transaction::PrivilegedL2Transaction(tx) => tx.to.clone(),
1477 Transaction::FeeTokenTransaction(tx) => tx.to.clone(),
1478 Transaction::FrameTransaction(tx) => TxKind::Call(tx.sender),
1479 }
1480 }
1481
1482 pub fn value(&self) -> U256 {
1483 match self {
1484 Transaction::LegacyTransaction(tx) => tx.value,
1485 Transaction::EIP2930Transaction(tx) => tx.value,
1486 Transaction::EIP1559Transaction(tx) => tx.value,
1487 Transaction::EIP4844Transaction(tx) => tx.value,
1488 Transaction::EIP7702Transaction(tx) => tx.value,
1489 Transaction::PrivilegedL2Transaction(tx) => tx.value,
1490 Transaction::FeeTokenTransaction(tx) => tx.value,
1491 Transaction::FrameTransaction(_) => U256::zero(),
1492 }
1493 }
1494
1495 pub fn max_priority_fee(&self) -> Option<u64> {
1496 match self {
1497 Transaction::LegacyTransaction(_tx) => None,
1498 Transaction::EIP2930Transaction(_tx) => None,
1499 Transaction::EIP1559Transaction(tx) => Some(tx.max_priority_fee_per_gas),
1500 Transaction::EIP4844Transaction(tx) => Some(tx.max_priority_fee_per_gas),
1501 Transaction::EIP7702Transaction(tx) => Some(tx.max_priority_fee_per_gas),
1502 Transaction::PrivilegedL2Transaction(tx) => Some(tx.max_priority_fee_per_gas),
1503 Transaction::FeeTokenTransaction(tx) => Some(tx.max_priority_fee_per_gas),
1504 Transaction::FrameTransaction(tx) => Some(tx.max_priority_fee_per_gas),
1505 }
1506 }
1507
1508 pub fn chain_id(&self) -> Option<u64> {
1509 match self {
1510 Transaction::LegacyTransaction(tx) => derive_legacy_chain_id(tx.v),
1511 Transaction::EIP2930Transaction(tx) => Some(tx.chain_id),
1512 Transaction::EIP1559Transaction(tx) => Some(tx.chain_id),
1513 Transaction::EIP4844Transaction(tx) => Some(tx.chain_id),
1514 Transaction::EIP7702Transaction(tx) => Some(tx.chain_id),
1515 Transaction::PrivilegedL2Transaction(tx) => Some(tx.chain_id),
1516 Transaction::FeeTokenTransaction(tx) => Some(tx.chain_id),
1517 Transaction::FrameTransaction(tx) => Some(tx.chain_id),
1518 }
1519 }
1520
1521 pub fn access_list(&self) -> &AccessList {
1522 static EMPTY_ACCESS_LIST: AccessList = Vec::new();
1523 match self {
1524 Transaction::LegacyTransaction(_tx) => &EMPTY_ACCESS_LIST,
1525 Transaction::EIP2930Transaction(tx) => &tx.access_list,
1526 Transaction::EIP1559Transaction(tx) => &tx.access_list,
1527 Transaction::EIP4844Transaction(tx) => &tx.access_list,
1528 Transaction::EIP7702Transaction(tx) => &tx.access_list,
1529 Transaction::PrivilegedL2Transaction(tx) => &tx.access_list,
1530 Transaction::FeeTokenTransaction(tx) => &tx.access_list,
1531 Transaction::FrameTransaction(_) => &EMPTY_ACCESS_LIST,
1532 }
1533 }
1534 pub fn authorization_list(&self) -> Option<&AuthorizationList> {
1535 match self {
1536 Transaction::LegacyTransaction(_) => None,
1537 Transaction::EIP2930Transaction(_) => None,
1538 Transaction::EIP1559Transaction(_) => None,
1539 Transaction::EIP4844Transaction(_) => None,
1540 Transaction::EIP7702Transaction(tx) => Some(&tx.authorization_list),
1541 Transaction::PrivilegedL2Transaction(_) => None,
1542 Transaction::FeeTokenTransaction(_) => None,
1543 Transaction::FrameTransaction(_) => None,
1544 }
1545 }
1546
1547 pub fn nonce(&self) -> u64 {
1548 match self {
1549 Transaction::LegacyTransaction(tx) => tx.nonce,
1550 Transaction::EIP2930Transaction(tx) => tx.nonce,
1551 Transaction::EIP1559Transaction(tx) => tx.nonce,
1552 Transaction::EIP4844Transaction(tx) => tx.nonce,
1553 Transaction::EIP7702Transaction(tx) => tx.nonce,
1554 Transaction::PrivilegedL2Transaction(tx) => tx.nonce,
1555 Transaction::FeeTokenTransaction(tx) => tx.nonce,
1556 Transaction::FrameTransaction(tx) => tx.nonce,
1557 }
1558 }
1559
1560 pub fn data(&self) -> &Bytes {
1561 match self {
1562 Transaction::LegacyTransaction(tx) => &tx.data,
1563 Transaction::EIP2930Transaction(tx) => &tx.data,
1564 Transaction::EIP1559Transaction(tx) => &tx.data,
1565 Transaction::EIP4844Transaction(tx) => &tx.data,
1566 Transaction::EIP7702Transaction(tx) => &tx.data,
1567 Transaction::PrivilegedL2Transaction(tx) => &tx.data,
1568 Transaction::FeeTokenTransaction(tx) => &tx.data,
1569 Transaction::FrameTransaction(_) => {
1570 static EMPTY_DATA: Bytes = Bytes::new();
1571 &EMPTY_DATA
1572 }
1573 }
1574 }
1575
1576 pub fn blob_versioned_hashes(&self) -> Vec<H256> {
1577 match self {
1578 Transaction::LegacyTransaction(_) => Vec::new(),
1579 Transaction::EIP2930Transaction(_) => Vec::new(),
1580 Transaction::EIP1559Transaction(_) => Vec::new(),
1581 Transaction::EIP4844Transaction(tx) => tx.blob_versioned_hashes.clone(),
1582 Transaction::EIP7702Transaction(_) => Vec::new(),
1583 Transaction::PrivilegedL2Transaction(_) => Vec::new(),
1584 Transaction::FeeTokenTransaction(_) => Vec::new(),
1585 Transaction::FrameTransaction(tx) => tx.blob_versioned_hashes.clone(),
1586 }
1587 }
1588
1589 pub fn max_fee_per_blob_gas(&self) -> Option<U256> {
1590 match self {
1591 Transaction::LegacyTransaction(_) => None,
1592 Transaction::EIP2930Transaction(_) => None,
1593 Transaction::EIP1559Transaction(_) => None,
1594 Transaction::EIP4844Transaction(tx) => Some(tx.max_fee_per_blob_gas),
1595 Transaction::EIP7702Transaction(_) => None,
1596 Transaction::PrivilegedL2Transaction(_) => None,
1597 Transaction::FeeTokenTransaction(_) => None,
1598 Transaction::FrameTransaction(tx) => {
1599 if tx.blob_versioned_hashes.is_empty() {
1600 None
1601 } else {
1602 Some(tx.max_fee_per_blob_gas)
1603 }
1604 }
1605 }
1606 }
1607
1608 pub fn is_blob_carrying(&self) -> bool {
1615 self.max_fee_per_blob_gas().is_some()
1616 }
1617
1618 pub fn is_contract_creation(&self) -> bool {
1619 match &self {
1620 Transaction::LegacyTransaction(t) => matches!(t.to, TxKind::Create),
1621 Transaction::EIP2930Transaction(t) => matches!(t.to, TxKind::Create),
1622 Transaction::EIP1559Transaction(t) => matches!(t.to, TxKind::Create),
1623 Transaction::EIP4844Transaction(_) => false,
1624 Transaction::EIP7702Transaction(_) => false,
1625 Transaction::PrivilegedL2Transaction(t) => matches!(t.to, TxKind::Create),
1626 Transaction::FeeTokenTransaction(t) => matches!(t.to, TxKind::Create),
1627 Transaction::FrameTransaction(_) => false,
1628 }
1629 }
1630
1631 pub fn is_privileged(&self) -> bool {
1632 matches!(self, Transaction::PrivilegedL2Transaction(_))
1633 }
1634
1635 pub fn max_fee_per_gas(&self) -> Option<u64> {
1636 match self {
1637 Transaction::LegacyTransaction(_tx) => None,
1638 Transaction::EIP2930Transaction(_tx) => None,
1639 Transaction::EIP1559Transaction(tx) => Some(tx.max_fee_per_gas),
1640 Transaction::EIP4844Transaction(tx) => Some(tx.max_fee_per_gas),
1641 Transaction::EIP7702Transaction(tx) => Some(tx.max_fee_per_gas),
1642 Transaction::PrivilegedL2Transaction(tx) => Some(tx.max_fee_per_gas),
1643 Transaction::FeeTokenTransaction(tx) => Some(tx.max_fee_per_gas),
1644 Transaction::FrameTransaction(tx) => Some(tx.max_fee_per_gas),
1645 }
1646 }
1647
1648 fn compute_hash(&self, crypto: &dyn Crypto) -> H256 {
1649 if let Transaction::PrivilegedL2Transaction(tx) = self {
1650 return tx.get_privileged_hash().unwrap_or_default();
1651 }
1652 H256(crypto.keccak256(&self.encode_canonical_to_vec()))
1653 }
1654
1655 pub fn hash(&self, crypto: &dyn Crypto) -> H256 {
1656 let inner_hash = match self {
1657 Transaction::LegacyTransaction(tx) => &tx.inner_hash,
1658 Transaction::EIP2930Transaction(tx) => &tx.inner_hash,
1659 Transaction::EIP1559Transaction(tx) => &tx.inner_hash,
1660 Transaction::EIP4844Transaction(tx) => &tx.inner_hash,
1661 Transaction::EIP7702Transaction(tx) => &tx.inner_hash,
1662 Transaction::PrivilegedL2Transaction(tx) => &tx.inner_hash,
1663 Transaction::FeeTokenTransaction(tx) => &tx.inner_hash,
1664 Transaction::FrameTransaction(tx) => &tx.inner_hash,
1665 };
1666
1667 *inner_hash.get_or_init(|| self.compute_hash(crypto))
1668 }
1669
1670 pub fn gas_tip_cap(&self) -> U256 {
1671 self.max_priority_fee()
1672 .map(U256::from)
1673 .unwrap_or_else(|| self.gas_price())
1674 }
1675
1676 pub fn gas_fee_cap(&self) -> U256 {
1677 self.max_fee_per_gas()
1678 .map(U256::from)
1679 .unwrap_or_else(|| self.gas_price())
1680 }
1681
1682 pub fn effective_gas_tip(&self, base_fee: Option<u64>) -> Option<U256> {
1686 let tip_cap = self.gas_tip_cap();
1687 let Some(base_fee) = base_fee else {
1688 return Some(tip_cap);
1689 };
1690 let base_fee = U256::from(base_fee);
1691 let fee_cap = self.gas_fee_cap();
1692 let tip = fee_cap.checked_sub(base_fee)?;
1693 Some(min(tip, tip_cap))
1694 }
1695
1696 pub fn protected(&self) -> bool {
1699 match self {
1700 Transaction::LegacyTransaction(tx) if tx.v.bits() <= 8 => {
1701 let v = tx.v.low_u64();
1702 v != 27 && v != 28 && v != 1 && v != 0
1703 }
1704 _ => true,
1705 }
1706 }
1707}
1708
1709fn derive_legacy_chain_id(v: U256) -> Option<u64> {
1710 let chain_id = v.checked_sub(U256::from(35))? >> 1;
1718 u64::try_from(chain_id).ok()
1719}
1720
1721impl TxType {
1722 pub fn from_u8(value: u8) -> Option<Self> {
1723 match value {
1724 0x00 => Some(Self::Legacy),
1725 0x01 => Some(Self::EIP2930),
1726 0x02 => Some(Self::EIP1559),
1727 0x03 => Some(Self::EIP4844),
1728 0x04 => Some(Self::EIP7702),
1729 0x06 => Some(Self::Frame),
1730 0x7d => Some(Self::FeeToken),
1731 0x7e => Some(Self::Privileged),
1732 _ => None,
1733 }
1734 }
1735
1736 pub fn as_envelope(self) -> Option<EnvelopeTxType> {
1741 match self {
1742 TxType::EIP2930 => Some(EnvelopeTxType::EIP2930),
1743 TxType::EIP1559 => Some(EnvelopeTxType::EIP1559),
1744 TxType::EIP4844 => Some(EnvelopeTxType::EIP4844),
1745 TxType::EIP7702 => Some(EnvelopeTxType::EIP7702),
1746 TxType::Frame => Some(EnvelopeTxType::Frame),
1747 TxType::FeeToken => Some(EnvelopeTxType::FeeToken),
1748 TxType::Privileged => Some(EnvelopeTxType::Privileged),
1749 TxType::Legacy => None,
1750 }
1751 }
1752
1753 pub fn is_l2_only(self) -> bool {
1761 match self {
1762 Self::Legacy
1763 | Self::EIP2930
1764 | Self::EIP1559
1765 | Self::EIP4844
1766 | Self::EIP7702
1767 | Self::Frame => false,
1768 Self::FeeToken | Self::Privileged => true,
1769 }
1770 }
1771}
1772
1773impl PrivilegedL2Transaction {
1774 pub fn get_privileged_hash(&self) -> Option<H256> {
1778 let to = match self.to {
1780 TxKind::Call(to) => to,
1781 _ => return None,
1782 };
1783
1784 let value = self.value.to_big_endian();
1785
1786 let u256_nonce = U256::from(self.nonce);
1789 let nonce = u256_nonce.to_big_endian();
1790
1791 Some(crate::utils::keccak(
1792 [
1793 U256::from(self.chain_id).to_big_endian().as_ref(),
1794 self.from.as_bytes(),
1795 to.as_bytes(),
1796 &nonce,
1797 &value,
1798 &U256::from(self.gas_limit).to_big_endian(),
1799 keccak(&self.data).as_bytes(),
1800 ]
1801 .concat(),
1802 ))
1803 }
1804}
1805
1806#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
1807pub struct FeeTokenTransaction {
1808 pub chain_id: u64,
1809 pub nonce: u64,
1810 pub max_priority_fee_per_gas: u64,
1811 pub max_fee_per_gas: u64,
1812 pub gas_limit: u64,
1813 pub to: TxKind,
1814 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
1815 pub value: U256,
1816 #[rkyv(with=crate::rkyv_utils::BytesWrapper)]
1817 pub data: Bytes,
1818 #[rkyv(with=rkyv::with::Map<crate::rkyv_utils::AccessListItemWrapper>)]
1819 pub access_list: AccessList,
1820 #[rkyv(with=crate::rkyv_utils::H160Wrapper)]
1821 pub fee_token: Address,
1822 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
1823 pub signature_y_parity: U256,
1824 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
1825 pub signature_r: U256,
1826 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
1827 pub signature_s: U256,
1828 #[rkyv(with=rkyv::with::Skip)]
1829 pub inner_hash: OnceCell<H256>,
1830 #[rkyv(with=rkyv::with::Skip)]
1831 pub sender_cache: OnceCell<Address>,
1832 #[rkyv(with=rkyv::with::Skip)]
1833 pub cached_canonical: OnceCell<Vec<u8>>,
1834}
1835
1836#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
1838#[repr(u8)]
1839pub enum FrameMode {
1840 #[default]
1841 Default = 0,
1842 Verify = 1,
1843 Sender = 2,
1844}
1845
1846impl FrameMode {
1847 pub fn from_u8(val: u8) -> Option<Self> {
1850 match val {
1851 0 => Some(FrameMode::Default),
1852 1 => Some(FrameMode::Verify),
1853 2 => Some(FrameMode::Sender),
1854 _ => None,
1855 }
1856 }
1857}
1858
1859impl From<FrameMode> for u8 {
1860 fn from(mode: FrameMode) -> u8 {
1861 match mode {
1862 FrameMode::Default => 0,
1863 FrameMode::Verify => 1,
1864 FrameMode::Sender => 2,
1865 }
1866 }
1867}
1868
1869#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
1875pub struct Frame {
1876 pub mode: u8,
1877 pub flags: u8,
1878 #[rkyv(with=rkyv::with::Map<crate::rkyv_utils::H160Wrapper>)]
1879 pub target: Option<Address>,
1880 pub gas_limit: u64,
1881 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
1885 pub value: U256,
1886 #[rkyv(with=crate::rkyv_utils::BytesWrapper)]
1887 pub data: Bytes,
1888}
1889
1890impl Frame {
1891 pub fn execution_mode(&self) -> FrameMode {
1893 FrameMode::from_u8(self.mode).unwrap_or_default()
1894 }
1895
1896 pub fn scope_restriction(&self) -> u8 {
1898 self.flags & 0x03
1899 }
1900
1901 pub fn is_atomic_batch(&self) -> bool {
1903 (self.flags >> 2) & 1 == 1
1904 }
1905
1906 pub fn is_expiry_verifier(&self) -> bool {
1909 self.execution_mode() == FrameMode::Verify
1910 && self.target == Some(frame_tx_expiry_verifier())
1911 }
1912}
1913
1914impl RLPEncode for Frame {
1915 fn encode(&self, buf: &mut dyn bytes::BufMut) {
1916 let target_kind = match self.target {
1918 Some(addr) => TxKind::Call(addr),
1919 None => TxKind::Create, };
1921 Encoder::new(buf)
1922 .encode_field(&(self.mode as u64))
1923 .encode_field(&(self.flags as u64))
1924 .encode_field(&target_kind)
1925 .encode_field(&self.gas_limit)
1926 .encode_field(&self.value)
1927 .encode_field(&self.data)
1928 .finish();
1929 }
1930}
1931
1932impl RLPDecode for Frame {
1933 fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
1934 let decoder = Decoder::new(rlp)?;
1935 let (mode_u64, decoder): (u64, _) = decoder.decode_field("mode")?;
1936 let mode = u8::try_from(mode_u64)
1937 .map_err(|_| RLPDecodeError::Custom(format!("Frame mode too large: {mode_u64}")))?;
1938 let (flags_u64, decoder): (u64, _) = decoder.decode_field("flags")?;
1939 let flags = u8::try_from(flags_u64)
1940 .map_err(|_| RLPDecodeError::Custom(format!("Frame flags too large: {flags_u64}")))?;
1941 let (target_kind, decoder): (TxKind, _) = decoder.decode_field("target")?;
1942 let target = match target_kind {
1943 TxKind::Call(addr) => Some(addr),
1944 TxKind::Create => None,
1945 };
1946 let (gas_limit, decoder) = decoder.decode_field("gas_limit")?;
1947 let (value, decoder): (U256, _) = decoder.decode_field("value")?;
1948 let (data, decoder) = decoder.decode_field("data")?;
1949 let frame = Frame {
1950 mode,
1951 flags,
1952 target,
1953 gas_limit,
1954 value,
1955 data,
1956 };
1957 Ok((frame, decoder.finish()?))
1958 }
1959}
1960
1961#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
1969pub struct FrameSignature {
1970 pub scheme: u8,
1971 #[rkyv(with=rkyv::with::Map<crate::rkyv_utils::H160Wrapper>)]
1972 pub signer: Option<Address>,
1973 #[rkyv(with=crate::rkyv_utils::BytesWrapper)]
1974 pub msg: Bytes,
1975 #[rkyv(with=crate::rkyv_utils::BytesWrapper)]
1976 pub signature: Bytes,
1977}
1978
1979impl RLPEncode for FrameSignature {
1980 fn encode(&self, buf: &mut dyn bytes::BufMut) {
1981 let signer_kind = match self.signer {
1984 Some(addr) => TxKind::Call(addr),
1985 None => TxKind::Create,
1986 };
1987 Encoder::new(buf)
1988 .encode_field(&self.scheme)
1989 .encode_field(&signer_kind)
1990 .encode_field(&self.msg)
1991 .encode_field(&self.signature)
1992 .finish();
1993 }
1994}
1995
1996impl RLPDecode for FrameSignature {
1997 fn decode_unfinished(rlp: &[u8]) -> Result<(FrameSignature, &[u8]), RLPDecodeError> {
1998 let decoder = Decoder::new(rlp)?;
1999 let (scheme, decoder) = decoder.decode_field("scheme")?;
2000 let (signer_kind, decoder): (TxKind, _) = decoder.decode_field("signer")?;
2001 let signer = match signer_kind {
2002 TxKind::Call(addr) => Some(addr),
2003 TxKind::Create => None,
2004 };
2005 let (msg, decoder) = decoder.decode_field("msg")?;
2006 let (signature, decoder) = decoder.decode_field("signature")?;
2007 Ok((
2008 FrameSignature {
2009 scheme,
2010 signer,
2011 msg,
2012 signature,
2013 },
2014 decoder.finish()?,
2015 ))
2016 }
2017}
2018
2019#[derive(Clone, Debug, PartialEq, Eq, Default, RSerialize, RDeserialize, Archive)]
2023pub struct FrameTransaction {
2024 pub chain_id: u64,
2025 pub nonce: u64,
2026 #[rkyv(with=crate::rkyv_utils::H160Wrapper)]
2027 pub sender: Address,
2028 pub frames: Vec<Frame>,
2029 pub signatures: Vec<FrameSignature>,
2032 pub max_priority_fee_per_gas: u64,
2033 pub max_fee_per_gas: u64,
2034 #[rkyv(with=crate::rkyv_utils::U256Wrapper)]
2035 pub max_fee_per_blob_gas: U256,
2036 #[rkyv(with=rkyv::with::Map<crate::rkyv_utils::H256Wrapper>)]
2037 pub blob_versioned_hashes: Vec<H256>,
2038 #[rkyv(with=rkyv::with::Skip)]
2039 pub inner_hash: OnceCell<H256>,
2040 #[rkyv(with=rkyv::with::Skip)]
2041 pub cached_canonical: OnceCell<Vec<u8>>,
2042}
2043
2044pub const FRAME_TX_INTRINSIC_COST: u64 = 15000;
2046pub const FRAME_TX_PER_FRAME_COST: u64 = 475;
2048pub const FRAME_TX_ENTRY_POINT_U64: u64 = 0xaa;
2050pub const FRAME_TX_MAX_FRAMES: usize = 64;
2052const FRAME_TX_STANDARD_TOKEN_COST: u64 = 4;
2056const FRAME_TX_TOTAL_COST_FLOOR_PER_TOKEN: u64 = 16;
2057pub const FRAME_SIG_SCHEME_ARBITRARY: u8 = 0;
2059pub const FRAME_SIG_SCHEME_SECP256K1: u8 = 1;
2060pub const FRAME_SIG_SCHEME_P256: u8 = 2;
2061pub const FRAME_TX_MAX_VERIFY_GAS: u64 = 100_000;
2067pub const APPROVE_PAYMENT: u8 = 0x1;
2070pub const APPROVE_EXECUTION: u8 = 0x2;
2071pub const APPROVE_EXECUTION_AND_PAYMENT: u8 = 0x3;
2072pub const FRAME_TX_MAX_PENDING_NONCANONICAL_PAYMASTER: u8 = 1;
2077
2078pub fn frame_tx_entry_point() -> Address {
2081 Address::from_low_u64_be(FRAME_TX_ENTRY_POINT_U64)
2082}
2083
2084pub const FRAME_TX_EXPIRY_VERIFIER_U64: u64 = 0x8141;
2086pub const FRAME_TX_EXPIRY_DATA_LENGTH: usize = 8;
2088
2089pub fn frame_tx_expiry_verifier() -> Address {
2091 Address::from_low_u64_be(FRAME_TX_EXPIRY_VERIFIER_U64)
2092}
2093
2094impl FrameTransaction {
2095 pub fn compute_sig_hash(&self) -> H256 {
2101 let mut buf = vec![TxType::Frame as u8];
2102 let elided_signatures: Vec<FrameSignature> = self
2103 .signatures
2104 .iter()
2105 .map(|s| {
2106 if s.msg.is_empty() {
2107 FrameSignature {
2108 scheme: s.scheme,
2109 signer: s.signer,
2110 msg: s.msg.clone(),
2111 signature: Bytes::new(),
2112 }
2113 } else {
2114 s.clone()
2115 }
2116 })
2117 .collect();
2118 Encoder::new(&mut buf)
2120 .encode_field(&self.chain_id)
2121 .encode_field(&self.nonce)
2122 .encode_field(&self.sender)
2123 .encode_field(&self.frames)
2124 .encode_field(&elided_signatures)
2125 .encode_field(&self.max_priority_fee_per_gas)
2126 .encode_field(&self.max_fee_per_gas)
2127 .encode_field(&self.max_fee_per_blob_gas)
2128 .encode_field(&self.blob_versioned_hashes)
2129 .finish();
2130 keccak(&buf)
2131 }
2132
2133 pub fn signature_verification_cost(&self) -> u64 {
2137 self.signatures
2138 .iter()
2139 .map(|s| match s.scheme {
2140 FRAME_SIG_SCHEME_ARBITRARY => 100u64,
2141 FRAME_SIG_SCHEME_SECP256K1 => 2800u64,
2142 FRAME_SIG_SCHEME_P256 => 6700u64,
2143 _ => 0,
2144 })
2145 .sum()
2146 }
2147
2148 fn data_fields(&self) -> impl Iterator<Item = &[u8]> {
2152 const EMPTY: &[u8] = &[];
2153 self.frames
2154 .iter()
2155 .map(|f| f.data.as_ref())
2156 .chain(self.signatures.iter().flat_map(|s| {
2157 [
2158 s.signer.as_ref().map_or(EMPTY, |a| a.as_bytes()),
2159 s.msg.as_ref(),
2160 s.signature.as_ref(),
2161 ]
2162 }))
2163 }
2164
2165 pub fn data_cost(&self) -> u64 {
2168 self.data_fields().flatten().fold(0u64, |acc, byte| {
2169 acc.saturating_add(if *byte == 0 { 4 } else { 16 })
2170 })
2171 }
2172
2173 pub fn calldata_tokens(&self) -> u64 {
2178 self.data_fields()
2179 .fold(0u64, |acc, field| acc.saturating_add(field.len() as u64))
2180 .saturating_mul(FRAME_TX_STANDARD_TOKEN_COST)
2181 }
2182
2183 pub fn calldata_floor_gas(&self) -> u64 {
2186 self.calldata_tokens()
2187 .saturating_mul(FRAME_TX_TOTAL_COST_FLOOR_PER_TOKEN)
2188 }
2189
2190 pub fn mandatory_gas(&self) -> u64 {
2193 FRAME_TX_INTRINSIC_COST
2194 .saturating_add((self.frames.len() as u64).saturating_mul(FRAME_TX_PER_FRAME_COST))
2195 .saturating_add(self.signature_verification_cost())
2196 }
2197
2198 pub fn standard_gas_limit(&self) -> u64 {
2201 self.mandatory_gas()
2202 .saturating_add(self.data_cost())
2203 .saturating_add(
2204 self.frames
2205 .iter()
2206 .map(|f| f.gas_limit)
2207 .fold(0u64, |acc, g| acc.saturating_add(g)),
2208 )
2209 }
2210
2211 pub fn calldata_floor_total(&self) -> u64 {
2215 self.mandatory_gas()
2216 .saturating_add(self.calldata_floor_gas())
2217 }
2218
2219 pub fn max_gas(&self) -> u64 {
2224 self.standard_gas_limit().max(self.calldata_floor_total())
2225 }
2226
2227 pub fn expiry_deadline(&self) -> Option<u64> {
2230 self.frames
2231 .iter()
2232 .find(|f| f.is_expiry_verifier())
2233 .and_then(|f| {
2234 let bytes: [u8; FRAME_TX_EXPIRY_DATA_LENGTH] = f.data.as_ref().try_into().ok()?;
2235 Some(u64::from_be_bytes(bytes))
2236 })
2237 }
2238
2239 pub fn validate_static_constraints(&self) -> Result<(), String> {
2242 if self.sender == Address::zero() {
2244 return Err("tx.sender must not be zero address".to_string());
2245 }
2246 if self.frames.is_empty() || self.frames.len() > FRAME_TX_MAX_FRAMES {
2247 return Err(format!(
2248 "Frame count must be between 1 and {FRAME_TX_MAX_FRAMES}"
2249 ));
2250 }
2251 for (i, hash) in self.blob_versioned_hashes.iter().enumerate() {
2254 if hash.0.first() != Some(&VERSIONED_HASH_VERSION_KZG) {
2255 return Err(format!("Blob versioned hash {i}: wrong version byte"));
2256 }
2257 }
2258 if self.blob_versioned_hashes.is_empty() && !self.max_fee_per_blob_gas.is_zero() {
2259 return Err(
2260 "max_fee_per_blob_gas must be zero when the transaction carries no blobs"
2261 .to_string(),
2262 );
2263 }
2264 for (i, sig) in self.signatures.iter().enumerate() {
2267 match sig.scheme {
2268 FRAME_SIG_SCHEME_ARBITRARY => {
2271 if sig.signer.is_some() {
2272 return Err(format!(
2273 "Signature {i}: ARBITRARY signatures must not name a signer"
2274 ));
2275 }
2276 }
2277 FRAME_SIG_SCHEME_SECP256K1 | FRAME_SIG_SCHEME_P256 => {}
2278 other => {
2279 return Err(format!("Signature {i}: unsupported scheme {other}"));
2280 }
2281 }
2282 match sig.msg.len() {
2283 0 => {}
2284 32 => {
2285 if sig.msg.iter().all(|&b| b == 0) {
2286 return Err(format!(
2287 "Signature {i}: explicit msg must not be zero digest"
2288 ));
2289 }
2290 }
2291 other => {
2292 return Err(format!(
2293 "Signature {i}: msg must be empty or 32 bytes, got {other}"
2294 ));
2295 }
2296 }
2297 }
2298 let mut total_frame_gas: u128 = 0;
2301 let mut expiry_frame_count: usize = 0;
2302 for (i, frame) in self.frames.iter().enumerate() {
2303 if frame.mode >= 3 {
2305 return Err(format!("Frame {i}: reserved execution mode {}", frame.mode));
2306 }
2307 if frame.flags >= 8 {
2309 return Err(format!(
2310 "Frame {i}: reserved flag bits must be zero (flags={:#04x})",
2311 frame.flags
2312 ));
2313 }
2314 if frame.is_expiry_verifier() {
2319 expiry_frame_count = expiry_frame_count.saturating_add(1);
2320 if expiry_frame_count > 1 {
2321 return Err(format!("Frame {i}: more than one expiry verifier frame"));
2322 }
2323 if frame.flags != 0 {
2324 return Err(format!(
2325 "Frame {i}: expiry verifier frame must have flags == 0"
2326 ));
2327 }
2328 if frame.data.len() != FRAME_TX_EXPIRY_DATA_LENGTH {
2329 return Err(format!(
2330 "Frame {i}: expiry verifier frame data must be {FRAME_TX_EXPIRY_DATA_LENGTH} bytes"
2331 ));
2332 }
2333 }
2334 if frame.mode != FrameMode::Sender as u8 && !frame.value.is_zero() {
2338 return Err(format!(
2339 "Frame {i}: non-zero value only allowed in SENDER mode (mode={}, value={})",
2340 frame.mode, frame.value
2341 ));
2342 }
2343 if frame.gas_limit > i64::MAX as u64 {
2351 return Err(format!(
2352 "Frame {i}: gas_limit {} exceeds 2**63-1",
2353 frame.gas_limit
2354 ));
2355 }
2356 total_frame_gas = total_frame_gas
2357 .checked_add(frame.gas_limit as u128)
2358 .ok_or_else(|| format!("Frame {i}: cumulative gas_limit overflow"))?;
2359 if total_frame_gas > i64::MAX as u128 {
2360 return Err(format!(
2361 "Frame {i}: cumulative frame gas_limit {} exceeds 2**63-1",
2362 total_frame_gas
2363 ));
2364 }
2365 if frame.flags & APPROVE_EXECUTION != 0
2368 && frame.target.is_some_and(|target| target != self.sender)
2369 {
2370 return Err(format!(
2371 "Frame {i}: APPROVE_EXECUTION requires an empty target or tx.sender"
2372 ));
2373 }
2374 if frame.is_atomic_batch() {
2379 if frame.mode == FrameMode::Verify as u8 {
2380 return Err(format!("Frame {i}: atomic batch flag on a VERIFY frame"));
2381 }
2382 match self.frames.get(i.saturating_add(1)) {
2383 None => return Err(format!("Frame {i}: atomic batch flag on last frame")),
2384 Some(next) if next.mode == FrameMode::Verify as u8 => {
2385 return Err(format!(
2386 "Frame {i}: atomic batch flag followed by a VERIFY frame"
2387 ));
2388 }
2389 Some(_) => {}
2390 }
2391 }
2392 }
2393 Ok(())
2394 }
2395
2396 pub fn validation_prefix(&self) -> Result<ValidationPrefix, FrameValidationError> {
2412 let non_expiry: Vec<usize> = self
2414 .frames
2415 .iter()
2416 .enumerate()
2417 .filter(|(_, f)| !f.is_expiry_verifier())
2418 .map(|(i, _)| i)
2419 .collect();
2420
2421 let frame = |pos: usize| -> Option<&Frame> {
2423 non_expiry.get(pos).and_then(|&idx| self.frames.get(idx))
2424 };
2425
2426 let is_default = |pos: usize| -> bool {
2427 frame(pos).is_some_and(|f| f.execution_mode() == FrameMode::Default)
2428 };
2429 let is_verify = |pos: usize| -> bool {
2430 frame(pos).is_some_and(|f| f.execution_mode() == FrameMode::Verify)
2431 };
2432 let scope_of = |pos: usize| -> u8 { frame(pos).map_or(0, |f| f.scope_restriction()) };
2433
2434 if non_expiry.is_empty() {
2435 return Err(FrameValidationError::UnrecognizedPrefix);
2436 }
2437
2438 if is_default(0)
2442 && is_verify(1)
2443 && scope_of(1) == APPROVE_EXECUTION
2444 && is_verify(2)
2445 && scope_of(2) == APPROVE_PAYMENT
2446 {
2447 return Ok(ValidationPrefix {
2448 shape: PrefixShape::DeployOnlyVerifyPay,
2449 frame_indices: vec![non_expiry[0], non_expiry[1], non_expiry[2]],
2450 deploy_index: Some(non_expiry[0]),
2451 pay_index: Some(non_expiry[2]),
2452 });
2453 }
2454
2455 if is_default(0) && is_verify(1) && scope_of(1) == APPROVE_EXECUTION_AND_PAYMENT {
2457 return Ok(ValidationPrefix {
2458 shape: PrefixShape::DeploySelfVerify,
2459 frame_indices: vec![non_expiry[0], non_expiry[1]],
2460 deploy_index: Some(non_expiry[0]),
2461 pay_index: Some(non_expiry[1]),
2462 });
2463 }
2464
2465 if is_verify(0)
2467 && scope_of(0) == APPROVE_EXECUTION
2468 && is_verify(1)
2469 && scope_of(1) == APPROVE_PAYMENT
2470 {
2471 return Ok(ValidationPrefix {
2472 shape: PrefixShape::OnlyVerifyPay,
2473 frame_indices: vec![non_expiry[0], non_expiry[1]],
2474 deploy_index: None,
2475 pay_index: Some(non_expiry[1]),
2476 });
2477 }
2478
2479 if is_verify(0) && scope_of(0) == APPROVE_EXECUTION_AND_PAYMENT {
2481 return Ok(ValidationPrefix {
2482 shape: PrefixShape::SelfVerify,
2483 frame_indices: vec![non_expiry[0]],
2484 deploy_index: None,
2485 pay_index: Some(non_expiry[0]),
2486 });
2487 }
2488
2489 Err(FrameValidationError::UnrecognizedPrefix)
2490 }
2491
2492 pub fn validate_prefix_structure(
2506 &self,
2507 prefix: &ValidationPrefix,
2508 ) -> Result<(), FrameValidationError> {
2509 let mut deploy_count = 0usize;
2510
2511 for &idx in &prefix.frame_indices {
2512 let frame = &self.frames[idx];
2513
2514 if frame.is_atomic_batch() {
2515 return Err(FrameValidationError::AtomicBatchInPrefix { frame_index: idx });
2516 }
2517
2518 match prefix.deploy_index {
2519 Some(deploy_idx) if deploy_idx == idx => {
2520 deploy_count += 1;
2522 if deploy_count > 1 {
2523 return Err(FrameValidationError::MultipleDeploys { frame_index: idx });
2524 }
2525 if prefix.frame_indices.first() != Some(&idx) {
2530 return Err(FrameValidationError::DeployNotFirst { frame_index: idx });
2531 }
2532 if frame.execution_mode() != FrameMode::Default {
2533 return Err(FrameValidationError::DeployNotDefaultMode {
2534 frame_index: idx,
2535 });
2536 }
2537 }
2538 _ => {
2539 if frame.execution_mode() != FrameMode::Verify {
2541 return Err(FrameValidationError::VerifyFrameNotVerifyMode {
2542 frame_index: idx,
2543 });
2544 }
2545
2546 let target_ok = match frame.target {
2548 None => true,
2549 Some(addr) => addr == self.sender,
2550 };
2551 if !target_ok {
2552 return Err(FrameValidationError::VerifyTargetNotSender {
2553 frame_index: idx,
2554 });
2555 }
2556
2557 let expected_scope = match prefix.shape {
2559 PrefixShape::SelfVerify | PrefixShape::DeploySelfVerify => {
2560 APPROVE_EXECUTION_AND_PAYMENT
2561 }
2562 PrefixShape::OnlyVerifyPay | PrefixShape::DeployOnlyVerifyPay => {
2563 if prefix.pay_index == Some(idx) {
2565 APPROVE_PAYMENT
2566 } else {
2567 APPROVE_EXECUTION
2568 }
2569 }
2570 };
2571 if frame.scope_restriction() != expected_scope {
2572 return Err(FrameValidationError::WrongScopeRestriction {
2573 frame_index: idx,
2574 expected: expected_scope,
2575 actual: frame.scope_restriction(),
2576 });
2577 }
2578 }
2579 }
2580 }
2581
2582 let prefix_gas: u64 = prefix
2584 .frame_indices
2585 .iter()
2586 .map(|&i| self.frames[i].gas_limit)
2587 .fold(0u64, |acc, g| acc.saturating_add(g));
2588 let total_verify_gas = prefix_gas.saturating_add(self.signature_verification_cost());
2589 if total_verify_gas > FRAME_TX_MAX_VERIFY_GAS {
2590 return Err(FrameValidationError::VerifyGasBudgetExceeded {
2591 actual: total_verify_gas,
2592 limit: FRAME_TX_MAX_VERIFY_GAS,
2593 });
2594 }
2595
2596 Ok(())
2597 }
2598}
2599
2600#[derive(Clone, Debug, PartialEq, Eq)]
2602pub enum PrefixShape {
2603 SelfVerify,
2605 DeploySelfVerify,
2607 OnlyVerifyPay,
2609 DeployOnlyVerifyPay,
2611}
2612
2613#[derive(Clone, Debug, PartialEq, Eq)]
2615pub struct ValidationPrefix {
2616 pub shape: PrefixShape,
2618 pub frame_indices: Vec<usize>,
2621 pub deploy_index: Option<usize>,
2623 pub pay_index: Option<usize>,
2625}
2626
2627#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
2630pub enum FrameValidationError {
2631 #[error("frame transaction validation prefix does not match any recognized shape")]
2632 UnrecognizedPrefix,
2633 #[error("frame {frame_index}: prefix has more than one DEFAULT deploy frame")]
2634 MultipleDeploys { frame_index: usize },
2635 #[error("frame {frame_index}: deploy frame must be at index 0")]
2636 DeployNotFirst { frame_index: usize },
2637 #[error("frame {frame_index}: deploy frame must use DEFAULT execution mode")]
2638 DeployNotDefaultMode { frame_index: usize },
2639 #[error("frame {frame_index}: prefix VERIFY frame does not use VERIFY execution mode")]
2640 VerifyFrameNotVerifyMode { frame_index: usize },
2641 #[error("frame {frame_index}: VERIFY frame target is not tx.sender")]
2642 VerifyTargetNotSender { frame_index: usize },
2643 #[error("frame {frame_index}: scope restriction is {actual:#04x}, expected {expected:#04x}")]
2644 WrongScopeRestriction {
2645 frame_index: usize,
2646 expected: u8,
2647 actual: u8,
2648 },
2649 #[error("frame {frame_index}: prefix frame has atomic-batch flag set")]
2650 AtomicBatchInPrefix { frame_index: usize },
2651 #[error("prefix gas budget exceeded: {actual} > {limit} (MAX_VERIFY_GAS)")]
2652 VerifyGasBudgetExceeded { actual: u64, limit: u64 },
2653}
2654
2655impl RLPEncode for FrameTransaction {
2656 fn encode(&self, buf: &mut dyn bytes::BufMut) {
2657 Encoder::new(buf)
2658 .encode_field(&self.chain_id)
2659 .encode_field(&self.nonce)
2660 .encode_field(&self.sender)
2661 .encode_field(&self.frames)
2662 .encode_field(&self.signatures)
2663 .encode_field(&self.max_priority_fee_per_gas)
2664 .encode_field(&self.max_fee_per_gas)
2665 .encode_field(&self.max_fee_per_blob_gas)
2666 .encode_field(&self.blob_versioned_hashes)
2667 .finish();
2668 }
2669}
2670
2671impl RLPDecode for FrameTransaction {
2672 fn decode_unfinished(rlp: &[u8]) -> Result<(FrameTransaction, &[u8]), RLPDecodeError> {
2673 let decoder = Decoder::new(rlp)?;
2674 let (chain_id, decoder) = decoder.decode_field("chain_id")?;
2675 let (nonce, decoder) = decode_nonce_field(decoder)?;
2676 let (sender, decoder) = decoder.decode_field("sender")?;
2677 let (frames, decoder) = decoder.decode_field("frames")?;
2678 let (signatures, decoder) = decoder.decode_field("signatures")?;
2679 let (max_priority_fee_per_gas, decoder) =
2680 decoder.decode_field("max_priority_fee_per_gas")?;
2681 let (max_fee_per_gas, decoder) = decoder.decode_field("max_fee_per_gas")?;
2682 let (max_fee_per_blob_gas, decoder) = decoder.decode_field("max_fee_per_blob_gas")?;
2683 let (blob_versioned_hashes, decoder) = decoder.decode_field("blob_versioned_hashes")?;
2684 let tx = FrameTransaction {
2685 chain_id,
2686 nonce,
2687 sender,
2688 frames,
2689 signatures,
2690 max_priority_fee_per_gas,
2691 max_fee_per_gas,
2692 max_fee_per_blob_gas,
2693 blob_versioned_hashes,
2694 inner_hash: OnceCell::new(),
2695 cached_canonical: OnceCell::new(),
2696 };
2697 Ok((tx, decoder.finish()?))
2698 }
2699}
2700
2701impl PayloadRLPEncode for FrameTransaction {
2702 fn encode_payload(&self, buf: &mut dyn bytes::BufMut) {
2703 buf.put_u8(TxType::Frame as u8);
2704 self.encode(buf);
2705 }
2706}
2707
2708mod canonic_encoding {
2714 use super::*;
2715
2716 impl Transaction {
2717 pub fn decode_canonical(bytes: &[u8]) -> Result<Self, RLPDecodeError> {
2723 match bytes.first() {
2725 Some(tx_type) if *tx_type < 0x7f => {
2727 let tx_bytes = &bytes[1..];
2731 match EnvelopeTxType::from_type_byte(*tx_type)? {
2732 EnvelopeTxType::EIP2930 => EIP2930Transaction::decode(tx_bytes)
2733 .map(Transaction::EIP2930Transaction),
2734 EnvelopeTxType::EIP1559 => EIP1559Transaction::decode(tx_bytes)
2735 .map(Transaction::EIP1559Transaction),
2736 EnvelopeTxType::EIP4844 => EIP4844Transaction::decode(tx_bytes)
2737 .map(Transaction::EIP4844Transaction),
2738 EnvelopeTxType::EIP7702 => EIP7702Transaction::decode(tx_bytes)
2739 .map(Transaction::EIP7702Transaction),
2740 EnvelopeTxType::Frame => {
2741 FrameTransaction::decode(tx_bytes).map(Transaction::FrameTransaction)
2742 }
2743 EnvelopeTxType::FeeToken => FeeTokenTransaction::decode(tx_bytes)
2744 .map(Transaction::FeeTokenTransaction),
2745 EnvelopeTxType::Privileged => PrivilegedL2Transaction::decode(tx_bytes)
2746 .map(Transaction::PrivilegedL2Transaction),
2747 }
2748 }
2749 _ => LegacyTransaction::decode(bytes).map(Transaction::LegacyTransaction),
2751 }
2752 }
2753
2754 pub fn encode_canonical(&self, buf: &mut dyn bytes::BufMut) {
2760 match self {
2761 Transaction::LegacyTransaction(_) => {}
2763 _ => buf.put_u8(self.tx_type() as u8),
2764 }
2765 match self {
2766 Transaction::LegacyTransaction(t) => t.encode(buf),
2767 Transaction::EIP2930Transaction(t) => t.encode(buf),
2768 Transaction::EIP1559Transaction(t) => t.encode(buf),
2769 Transaction::EIP4844Transaction(t) => t.encode(buf),
2770 Transaction::EIP7702Transaction(t) => t.encode(buf),
2771 Transaction::FeeTokenTransaction(t) => t.encode(buf),
2772 Transaction::PrivilegedL2Transaction(t) => t.encode(buf),
2773 Transaction::FrameTransaction(t) => t.encode(buf),
2774 };
2775 }
2776
2777 pub fn encode_canonical_to_vec(&self) -> Vec<u8> {
2783 if let Some(cell) = self.cached_canonical_cell() {
2784 return cell
2785 .get_or_init(|| {
2786 let mut buf = Vec::new();
2787 self.encode_canonical(&mut buf);
2788 buf
2789 })
2790 .clone();
2791 }
2792 let mut buf = Vec::new();
2793 self.encode_canonical(&mut buf);
2794 buf
2795 }
2796
2797 pub fn encode_canonical_len(&self) -> usize {
2802 let prefix_len = match self {
2803 Transaction::LegacyTransaction(_) => 0,
2804 _ => 1,
2805 };
2806 let inner_len = match self {
2807 Transaction::LegacyTransaction(t) => t.length(),
2808 Transaction::EIP2930Transaction(t) => t.length(),
2809 Transaction::EIP1559Transaction(t) => t.length(),
2810 Transaction::EIP4844Transaction(t) => t.length(),
2811 Transaction::EIP7702Transaction(t) => t.length(),
2812 Transaction::FeeTokenTransaction(t) => t.length(),
2813 Transaction::PrivilegedL2Transaction(t) => t.length(),
2814 Transaction::FrameTransaction(t) => t.length(),
2815 };
2816 prefix_len + inner_len
2817 }
2818 }
2819
2820 impl P2PTransaction {
2821 pub fn tx_type(&self) -> TxType {
2822 match self {
2823 P2PTransaction::LegacyTransaction(_) => TxType::Legacy,
2824 P2PTransaction::EIP2930Transaction(_) => TxType::EIP2930,
2825 P2PTransaction::EIP1559Transaction(_) => TxType::EIP1559,
2826 P2PTransaction::EIP4844TransactionWithBlobs(_) => TxType::EIP4844,
2827 P2PTransaction::EIP7702Transaction(_) => TxType::EIP7702,
2828 P2PTransaction::FeeTokenTransaction(_) => TxType::FeeToken,
2829 P2PTransaction::FrameTransaction(_) => TxType::Frame,
2830 }
2831 }
2832
2833 pub fn encode_canonical(&self, buf: &mut dyn bytes::BufMut) {
2834 match self {
2835 P2PTransaction::LegacyTransaction(_) => {}
2837 _ => buf.put_u8(self.tx_type() as u8),
2838 }
2839 match self {
2840 P2PTransaction::LegacyTransaction(t) => t.encode(buf),
2841 P2PTransaction::EIP2930Transaction(t) => t.encode(buf),
2842 P2PTransaction::EIP1559Transaction(t) => t.encode(buf),
2843 P2PTransaction::EIP4844TransactionWithBlobs(t) => t.encode(buf),
2844 P2PTransaction::EIP7702Transaction(t) => t.encode(buf),
2845 P2PTransaction::FeeTokenTransaction(t) => t.encode(buf),
2846 P2PTransaction::FrameTransaction(t) => t.encode(buf),
2847 };
2848 }
2849
2850 pub fn encode_canonical_to_vec(&self) -> Vec<u8> {
2851 let mut buf = Vec::new();
2852 self.encode_canonical(&mut buf);
2853 buf
2854 }
2855
2856 pub fn encode_canonical_len(&self) -> usize {
2861 let prefix_len = match self {
2862 P2PTransaction::LegacyTransaction(_) => 0,
2863 _ => 1,
2864 };
2865 let inner_len = match self {
2866 P2PTransaction::LegacyTransaction(t) => t.length(),
2867 P2PTransaction::EIP2930Transaction(t) => t.length(),
2868 P2PTransaction::EIP1559Transaction(t) => t.length(),
2869 P2PTransaction::EIP4844TransactionWithBlobs(t) => t.length(),
2870 P2PTransaction::EIP7702Transaction(t) => t.length(),
2871 P2PTransaction::FeeTokenTransaction(t) => t.length(),
2872 P2PTransaction::FrameTransaction(t) => t.length(),
2873 };
2874 prefix_len + inner_len
2875 }
2876
2877 pub fn compute_hash(&self) -> H256 {
2878 match self {
2879 P2PTransaction::LegacyTransaction(t) => {
2880 Transaction::LegacyTransaction(t.clone()).compute_hash(&NativeCrypto)
2881 }
2882 P2PTransaction::EIP2930Transaction(t) => {
2883 Transaction::EIP2930Transaction(t.clone()).compute_hash(&NativeCrypto)
2884 }
2885 P2PTransaction::EIP1559Transaction(t) => {
2886 Transaction::EIP1559Transaction(t.clone()).compute_hash(&NativeCrypto)
2887 }
2888 P2PTransaction::EIP4844TransactionWithBlobs(t) => {
2889 Transaction::EIP4844Transaction(t.tx.clone()).compute_hash(&NativeCrypto)
2890 }
2891 P2PTransaction::EIP7702Transaction(t) => {
2892 Transaction::EIP7702Transaction(t.clone()).compute_hash(&NativeCrypto)
2893 }
2894 P2PTransaction::FeeTokenTransaction(t) => {
2895 Transaction::FeeTokenTransaction(t.clone()).compute_hash(&NativeCrypto)
2896 }
2897 P2PTransaction::FrameTransaction(t) => {
2898 Transaction::FrameTransaction(t.clone()).compute_hash(&NativeCrypto)
2899 }
2900 }
2901 }
2902 }
2903}
2904
2905mod serde_impl {
2909 use ethereum_types::H160;
2910 use serde::Deserialize;
2911 use serde::{Deserializer, de::Error};
2912 use serde_json::Value;
2913 use std::{collections::HashMap, str::FromStr};
2914
2915 #[cfg(feature = "c-kzg")]
2916 use crate::types::BYTES_PER_BLOB;
2917 use crate::types::{AccessListItem, AuthorizationTuple, BlobsBundleError};
2918
2919 use super::*;
2920
2921 impl Serialize for TxKind {
2922 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2923 where
2924 S: serde::Serializer,
2925 {
2926 match self {
2927 TxKind::Call(address) => serializer.serialize_str(&format!("{address:#x}")),
2928 TxKind::Create => serializer.serialize_none(),
2929 }
2930 }
2931 }
2932
2933 impl<'de> Deserialize<'de> for TxKind {
2934 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2935 where
2936 D: serde::Deserializer<'de>,
2937 {
2938 let str_option = Option::<String>::deserialize(deserializer)?;
2939 match str_option {
2940 Some(str) if !str.is_empty() => Ok(TxKind::Call(
2941 Address::from_str(str.trim_start_matches("0x")).map_err(|_| {
2942 serde::de::Error::custom(format!("Failed to deserialize hex value {str}"))
2943 })?,
2944 )),
2945 _ => Ok(TxKind::Create),
2946 }
2947 }
2948 }
2949
2950 impl Serialize for TxType {
2951 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2952 where
2953 S: serde::Serializer,
2954 {
2955 serializer.serialize_str(&format!("{:#x}", *self as u8))
2956 }
2957 }
2958
2959 impl<'de> Deserialize<'de> for TxType {
2960 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2961 where
2962 D: serde::Deserializer<'de>,
2963 {
2964 let str = String::deserialize(deserializer)?;
2965 let tx_num = u8::from_str_radix(str.trim_start_matches("0x"), 16).map_err(|_| {
2966 serde::de::Error::custom(format!("Failed to deserialize hex value {str}"))
2967 })?;
2968 TxType::from_u8(tx_num).ok_or_else(|| {
2969 serde::de::Error::custom(format!("Invalid transaction type {tx_num}"))
2970 })
2971 }
2972 }
2973
2974 #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
2975 #[serde(rename_all = "camelCase")]
2976 pub struct AccessListEntry {
2977 pub address: Address,
2978 pub storage_keys: Vec<H256>,
2979 }
2980
2981 impl From<&AccessListItem> for AccessListEntry {
2982 fn from(value: &AccessListItem) -> AccessListEntry {
2983 AccessListEntry {
2984 address: value.0,
2985 storage_keys: value.1.clone(),
2986 }
2987 }
2988 }
2989
2990 #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
2991 #[serde(rename_all = "camelCase")]
2992 pub struct AuthorizationTupleEntry {
2993 pub chain_id: U256,
2994 pub address: Address,
2995 #[serde(default, with = "crate::serde_utils::u64::hex_str")]
2996 pub nonce: u64,
2997 pub y_parity: U256,
2998 pub r: U256,
2999 pub s: U256,
3000 }
3001
3002 impl From<&AuthorizationTuple> for AuthorizationTupleEntry {
3003 fn from(value: &AuthorizationTuple) -> AuthorizationTupleEntry {
3004 AuthorizationTupleEntry {
3005 chain_id: value.chain_id,
3006 address: value.address,
3007 nonce: value.nonce,
3008 y_parity: value.y_parity,
3009 r: value.r_signature,
3010 s: value.s_signature,
3011 }
3012 }
3013 }
3014
3015 impl From<AuthorizationTupleEntry> for AuthorizationTuple {
3016 fn from(entry: AuthorizationTupleEntry) -> AuthorizationTuple {
3017 AuthorizationTuple {
3018 chain_id: entry.chain_id,
3019 address: entry.address,
3020 nonce: entry.nonce,
3021 y_parity: entry.y_parity,
3022 r_signature: entry.r,
3023 s_signature: entry.s,
3024 }
3025 }
3026 }
3027
3028 #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
3029 #[serde(rename_all = "camelCase")]
3030 pub struct FrameEntry {
3031 #[serde(with = "crate::serde_utils::u64::hex_str")]
3032 pub mode: u64,
3033 #[serde(with = "crate::serde_utils::u64::hex_str")]
3034 pub flags: u64,
3035 pub to: Option<Address>,
3036 #[serde(with = "crate::serde_utils::u64::hex_str")]
3037 pub gas_limit: u64,
3038 #[serde(
3039 default,
3040 serialize_with = "serialize_u256_hex",
3041 deserialize_with = "crate::serde_utils::u256::deser_hex_str"
3042 )]
3043 pub value: U256,
3044 #[serde(with = "crate::serde_utils::bytes")]
3045 pub data: Bytes,
3046 }
3047
3048 #[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
3050 #[serde(rename_all = "camelCase")]
3051 pub struct SignatureEntry {
3052 #[serde(with = "crate::serde_utils::u64::hex_str")]
3053 pub scheme: u64,
3054 pub signer: Option<Address>,
3055 #[serde(with = "crate::serde_utils::bytes")]
3056 pub msg: Bytes,
3057 #[serde(with = "crate::serde_utils::bytes")]
3058 pub signature: Bytes,
3059 }
3060
3061 impl From<&FrameSignature> for SignatureEntry {
3062 fn from(value: &FrameSignature) -> SignatureEntry {
3063 SignatureEntry {
3064 scheme: value.scheme as u64,
3065 signer: value.signer,
3066 msg: value.msg.clone(),
3067 signature: value.signature.clone(),
3068 }
3069 }
3070 }
3071
3072 fn serialize_u256_hex<S: serde::Serializer>(value: &U256, s: S) -> Result<S::Ok, S::Error> {
3073 s.serialize_str(&format!("{value:#x}"))
3074 }
3075
3076 impl From<&Frame> for FrameEntry {
3077 fn from(value: &Frame) -> FrameEntry {
3078 FrameEntry {
3079 mode: value.mode as u64,
3080 flags: value.flags as u64,
3081 to: value.target,
3082 gas_limit: value.gas_limit,
3083 value: value.value,
3084 data: value.data.clone(),
3085 }
3086 }
3087 }
3088
3089 impl From<FrameEntry> for Frame {
3090 fn from(entry: FrameEntry) -> Frame {
3091 Frame {
3092 mode: entry.mode as u8,
3093 flags: entry.flags as u8,
3094 target: entry.to,
3095 gas_limit: entry.gas_limit,
3096 value: entry.value,
3097 data: entry.data,
3098 }
3099 }
3100 }
3101
3102 impl Serialize for LegacyTransaction {
3103 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3104 where
3105 S: serde::Serializer,
3106 {
3107 let mut struct_serializer = serializer.serialize_struct("LegacyTransaction", 11)?;
3108 struct_serializer.serialize_field("type", &TxType::Legacy)?;
3109 struct_serializer.serialize_field("nonce", &format!("{:#x}", self.nonce))?;
3110 struct_serializer.serialize_field("to", &self.to)?;
3111 struct_serializer.serialize_field("gas", &format!("{:#x}", self.gas))?;
3112 struct_serializer.serialize_field("value", &self.value)?;
3113 struct_serializer.serialize_field("input", &format!("0x{:x}", self.data))?;
3114 struct_serializer.serialize_field("gasPrice", &format!("{:#x}", self.gas_price))?;
3115 struct_serializer.serialize_field(
3116 "chainId",
3117 &format!("{:#x}", derive_legacy_chain_id(self.v).unwrap_or_default()),
3118 )?;
3119 struct_serializer.serialize_field("v", &self.v)?;
3120 struct_serializer.serialize_field("r", &self.r)?;
3121 struct_serializer.serialize_field("s", &self.s)?;
3122 struct_serializer.end()
3123 }
3124 }
3125
3126 impl Serialize for EIP2930Transaction {
3127 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3128 where
3129 S: serde::Serializer,
3130 {
3131 let mut struct_serializer = serializer.serialize_struct("Eip2930Transaction", 12)?;
3132 struct_serializer.serialize_field("type", &TxType::EIP2930)?;
3133 struct_serializer.serialize_field("nonce", &format!("{:#x}", self.nonce))?;
3134 struct_serializer.serialize_field("to", &self.to)?;
3135 struct_serializer.serialize_field("gas", &format!("{:#x}", self.gas_limit))?;
3136 struct_serializer.serialize_field("value", &self.value)?;
3137 struct_serializer.serialize_field("input", &format!("0x{:x}", self.data))?;
3138 struct_serializer.serialize_field("gasPrice", &format!("{:#x}", self.gas_price))?;
3139 struct_serializer.serialize_field(
3140 "accessList",
3141 &self
3142 .access_list
3143 .iter()
3144 .map(AccessListEntry::from)
3145 .collect::<Vec<_>>(),
3146 )?;
3147 struct_serializer.serialize_field("chainId", &format!("{:#x}", self.chain_id))?;
3148 struct_serializer
3149 .serialize_field("yParity", &format!("{:#x}", self.signature_y_parity))?;
3150 struct_serializer.serialize_field("v", &format!("{:#x}", self.signature_y_parity))?; struct_serializer.serialize_field("r", &self.signature_r)?;
3152 struct_serializer.serialize_field("s", &self.signature_s)?;
3153 struct_serializer.end()
3154 }
3155 }
3156
3157 impl Serialize for EIP1559Transaction {
3158 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3159 where
3160 S: serde::Serializer,
3161 {
3162 let mut struct_serializer = serializer.serialize_struct("Eip1559Transaction", 14)?;
3163 struct_serializer.serialize_field("type", &TxType::EIP1559)?;
3164 struct_serializer.serialize_field("nonce", &format!("{:#x}", self.nonce))?;
3165 struct_serializer.serialize_field("to", &self.to)?;
3166 struct_serializer.serialize_field("gas", &format!("{:#x}", self.gas_limit))?;
3167 struct_serializer.serialize_field("value", &self.value)?;
3168 struct_serializer.serialize_field("input", &format!("0x{:x}", self.data))?;
3169 struct_serializer.serialize_field(
3170 "maxPriorityFeePerGas",
3171 &format!("{:#x}", self.max_priority_fee_per_gas),
3172 )?;
3173 struct_serializer
3174 .serialize_field("maxFeePerGas", &format!("{:#x}", self.max_fee_per_gas))?;
3175 struct_serializer
3176 .serialize_field("gasPrice", &format!("{:#x}", self.max_fee_per_gas))?;
3177 struct_serializer.serialize_field(
3178 "accessList",
3179 &self
3180 .access_list
3181 .iter()
3182 .map(AccessListEntry::from)
3183 .collect::<Vec<_>>(),
3184 )?;
3185 struct_serializer.serialize_field("chainId", &format!("{:#x}", self.chain_id))?;
3186 struct_serializer
3187 .serialize_field("yParity", &format!("{:#x}", self.signature_y_parity))?;
3188 struct_serializer.serialize_field("v", &format!("{:#x}", self.signature_y_parity))?; struct_serializer.serialize_field("r", &self.signature_r)?;
3190 struct_serializer.serialize_field("s", &self.signature_s)?;
3191 struct_serializer.end()
3192 }
3193 }
3194
3195 impl Serialize for EIP4844Transaction {
3196 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3197 where
3198 S: serde::Serializer,
3199 {
3200 let mut struct_serializer = serializer.serialize_struct("Eip4844Transaction", 15)?;
3201 struct_serializer.serialize_field("type", &TxType::EIP4844)?;
3202 struct_serializer.serialize_field("nonce", &format!("{:#x}", self.nonce))?;
3203 struct_serializer.serialize_field("to", &self.to)?;
3204 struct_serializer.serialize_field("gas", &format!("{:#x}", self.gas))?;
3205 struct_serializer.serialize_field("value", &self.value)?;
3206 struct_serializer.serialize_field("input", &format!("0x{:x}", self.data))?;
3207 struct_serializer.serialize_field(
3208 "maxPriorityFeePerGas",
3209 &format!("{:#x}", self.max_priority_fee_per_gas),
3210 )?;
3211 struct_serializer
3212 .serialize_field("maxFeePerGas", &format!("{:#x}", self.max_fee_per_gas))?;
3213 struct_serializer
3214 .serialize_field("gasPrice", &format!("{:#x}", self.max_fee_per_gas))?;
3215 struct_serializer.serialize_field(
3216 "maxFeePerBlobGas",
3217 &format!("{:#x}", self.max_fee_per_blob_gas),
3218 )?;
3219 struct_serializer.serialize_field(
3220 "accessList",
3221 &self
3222 .access_list
3223 .iter()
3224 .map(AccessListEntry::from)
3225 .collect::<Vec<_>>(),
3226 )?;
3227 struct_serializer
3228 .serialize_field("blobVersionedHashes", &self.blob_versioned_hashes)?;
3229 struct_serializer.serialize_field("chainId", &format!("{:#x}", self.chain_id))?;
3230 struct_serializer
3231 .serialize_field("yParity", &format!("{:#x}", self.signature_y_parity))?;
3232 struct_serializer.serialize_field("v", &format!("{:#x}", self.signature_y_parity))?; struct_serializer.serialize_field("r", &self.signature_r)?;
3234 struct_serializer.serialize_field("s", &self.signature_s)?;
3235 struct_serializer.end()
3236 }
3237 }
3238
3239 impl Serialize for EIP7702Transaction {
3240 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3241 where
3242 S: serde::Serializer,
3243 {
3244 let mut struct_serializer = serializer.serialize_struct("Eip7702Transaction", 15)?;
3245 struct_serializer.serialize_field("type", &TxType::EIP7702)?;
3246 struct_serializer.serialize_field("nonce", &format!("{:#x}", self.nonce))?;
3247 struct_serializer.serialize_field("to", &self.to)?;
3248 struct_serializer.serialize_field("gas", &format!("{:#x}", self.gas_limit))?;
3249 struct_serializer.serialize_field("value", &self.value)?;
3250 struct_serializer.serialize_field("input", &format!("0x{:x}", self.data))?;
3251 struct_serializer.serialize_field(
3252 "maxPriorityFeePerGas",
3253 &format!("{:#x}", self.max_priority_fee_per_gas),
3254 )?;
3255 struct_serializer
3256 .serialize_field("maxFeePerGas", &format!("{:#x}", self.max_fee_per_gas))?;
3257 struct_serializer
3258 .serialize_field("gasPrice", &format!("{:#x}", self.max_fee_per_gas))?;
3259 struct_serializer.serialize_field(
3260 "accessList",
3261 &self
3262 .access_list
3263 .iter()
3264 .map(AccessListEntry::from)
3265 .collect::<Vec<_>>(),
3266 )?;
3267 struct_serializer.serialize_field(
3268 "authorizationList",
3269 &self
3270 .authorization_list
3271 .iter()
3272 .map(AuthorizationTupleEntry::from)
3273 .collect::<Vec<_>>(),
3274 )?;
3275 struct_serializer.serialize_field("chainId", &format!("{:#x}", self.chain_id))?;
3276 struct_serializer
3277 .serialize_field("yParity", &format!("{:#x}", self.signature_y_parity))?;
3278 struct_serializer.serialize_field("v", &format!("{:#x}", self.signature_y_parity))?; struct_serializer.serialize_field("r", &self.signature_r)?;
3280 struct_serializer.serialize_field("s", &self.signature_s)?;
3281 struct_serializer.end()
3282 }
3283 }
3284
3285 impl Serialize for PrivilegedL2Transaction {
3286 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3287 where
3288 S: serde::Serializer,
3289 {
3290 let mut struct_serializer = serializer.serialize_struct("Eip1559Transaction", 14)?;
3291 struct_serializer.serialize_field("type", &TxType::Privileged)?;
3292 struct_serializer.serialize_field("nonce", &format!("{:#x}", self.nonce))?;
3293 struct_serializer.serialize_field("to", &self.to)?;
3294 struct_serializer.serialize_field("gas", &format!("{:#x}", self.gas_limit))?;
3295 struct_serializer.serialize_field("value", &self.value)?;
3296 struct_serializer.serialize_field("input", &format!("0x{:x}", self.data))?;
3297 struct_serializer.serialize_field(
3298 "maxPriorityFeePerGas",
3299 &format!("{:#x}", self.max_priority_fee_per_gas),
3300 )?;
3301 struct_serializer
3302 .serialize_field("maxFeePerGas", &format!("{:#x}", self.max_fee_per_gas))?;
3303 struct_serializer
3304 .serialize_field("gasPrice", &format!("{:#x}", self.max_fee_per_gas))?;
3305 struct_serializer.serialize_field(
3306 "accessList",
3307 &self
3308 .access_list
3309 .iter()
3310 .map(AccessListEntry::from)
3311 .collect::<Vec<_>>(),
3312 )?;
3313 struct_serializer.serialize_field("chainId", &format!("{:#x}", self.chain_id))?;
3314 struct_serializer.serialize_field("sender", &self.from)?;
3315 struct_serializer.end()
3316 }
3317 }
3318
3319 impl Serialize for FeeTokenTransaction {
3320 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3321 where
3322 S: serde::Serializer,
3323 {
3324 let mut struct_serializer = serializer.serialize_struct("FeeTokenTransaction", 15)?;
3325 struct_serializer.serialize_field("type", &TxType::FeeToken)?;
3326 struct_serializer.serialize_field("nonce", &format!("{:#x}", self.nonce))?;
3327 struct_serializer.serialize_field("to", &self.to)?;
3328 struct_serializer.serialize_field("gas", &format!("{:#x}", self.gas_limit))?;
3329 struct_serializer.serialize_field("value", &self.value)?;
3330 struct_serializer.serialize_field("input", &format!("0x{:x}", self.data))?;
3331 struct_serializer.serialize_field(
3332 "maxPriorityFeePerGas",
3333 &format!("{:#x}", self.max_priority_fee_per_gas),
3334 )?;
3335 struct_serializer
3336 .serialize_field("maxFeePerGas", &format!("{:#x}", self.max_fee_per_gas))?;
3337 struct_serializer
3338 .serialize_field("gasPrice", &format!("{:#x}", self.max_fee_per_gas))?;
3339 struct_serializer.serialize_field(
3340 "accessList",
3341 &self
3342 .access_list
3343 .iter()
3344 .map(AccessListEntry::from)
3345 .collect::<Vec<_>>(),
3346 )?;
3347 struct_serializer.serialize_field("feeToken", &format!("{:#x}", self.fee_token))?;
3348 struct_serializer.serialize_field("chainId", &format!("{:#x}", self.chain_id))?;
3349 struct_serializer
3350 .serialize_field("yParity", &format!("{:#x}", self.signature_y_parity))?;
3351 struct_serializer.serialize_field("v", &format!("{:#x}", self.signature_y_parity))?;
3352 struct_serializer.serialize_field("r", &self.signature_r)?;
3353 struct_serializer.serialize_field("s", &self.signature_s)?;
3354 struct_serializer.end()
3355 }
3356 }
3357
3358 impl Serialize for FrameTransaction {
3359 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3360 where
3361 S: serde::Serializer,
3362 {
3363 let mut s = serializer.serialize_struct("FrameTransaction", 10)?;
3364 s.serialize_field("type", &TxType::Frame)?;
3365 s.serialize_field("chainId", &format!("{:#x}", self.chain_id))?;
3366 s.serialize_field("nonce", &format!("{:#x}", self.nonce))?;
3367 s.serialize_field("sender", &format!("{:#x}", self.sender))?;
3368 s.serialize_field(
3369 "frames",
3370 &self.frames.iter().map(FrameEntry::from).collect::<Vec<_>>(),
3371 )?;
3372 s.serialize_field(
3373 "signatures",
3374 &self
3375 .signatures
3376 .iter()
3377 .map(SignatureEntry::from)
3378 .collect::<Vec<_>>(),
3379 )?;
3380 s.serialize_field(
3381 "maxPriorityFeePerGas",
3382 &format!("{:#x}", self.max_priority_fee_per_gas),
3383 )?;
3384 s.serialize_field("maxFeePerGas", &format!("{:#x}", self.max_fee_per_gas))?;
3385 s.serialize_field("maxFeePerBlobGas", &self.max_fee_per_blob_gas)?;
3386 s.serialize_field("blobVersionedHashes", &self.blob_versioned_hashes)?;
3387 s.end()
3388 }
3389 }
3390
3391 impl<'de> Deserialize<'de> for Transaction {
3392 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3393 where
3394 D: serde::Deserializer<'de>,
3395 {
3396 let mut map = <HashMap<String, serde_json::Value>>::deserialize(deserializer)?;
3397 let tx_type =
3398 serde_json::from_value::<TxType>(map.remove("type").unwrap_or(Value::default()))
3399 .unwrap_or_else(|_| {
3400 if map.contains_key("tx_type") {
3401 return TxType::Privileged;
3402 }
3403 TxType::EIP1559
3404 });
3405
3406 let iter = map.into_iter();
3407 match tx_type {
3408 TxType::Legacy => {
3409 LegacyTransaction::deserialize(serde::de::value::MapDeserializer::new(iter))
3410 .map(Transaction::LegacyTransaction)
3411 .map_err(|e| {
3412 serde::de::Error::custom(format!("Couldn't Deserialize Legacy {e}"))
3413 })
3414 }
3415 TxType::EIP2930 => {
3416 EIP2930Transaction::deserialize(serde::de::value::MapDeserializer::new(iter))
3417 .map(Transaction::EIP2930Transaction)
3418 .map_err(|e| {
3419 serde::de::Error::custom(format!("Couldn't Deserialize EIP2930 {e}"))
3420 })
3421 }
3422 TxType::EIP1559 => {
3423 EIP1559Transaction::deserialize(serde::de::value::MapDeserializer::new(iter))
3424 .map(Transaction::EIP1559Transaction)
3425 .map_err(|e| {
3426 serde::de::Error::custom(format!("Couldn't Deserialize EIP1559 {e}"))
3427 })
3428 }
3429 TxType::EIP4844 => {
3430 EIP4844Transaction::deserialize(serde::de::value::MapDeserializer::new(iter))
3431 .map(Transaction::EIP4844Transaction)
3432 .map_err(|e| {
3433 serde::de::Error::custom(format!("Couldn't Deserialize EIP4844 {e}"))
3434 })
3435 }
3436 TxType::EIP7702 => {
3437 EIP7702Transaction::deserialize(serde::de::value::MapDeserializer::new(iter))
3438 .map(Transaction::EIP7702Transaction)
3439 .map_err(|e| {
3440 serde::de::Error::custom(format!("Couldn't Deserialize EIP7702 {e}"))
3441 })
3442 }
3443 TxType::Privileged => PrivilegedL2Transaction::deserialize(
3444 serde::de::value::MapDeserializer::new(iter),
3445 )
3446 .map(Transaction::PrivilegedL2Transaction)
3447 .map_err(|e| {
3448 serde::de::Error::custom(format!("Couldn't Deserialize Privileged: {e}"))
3449 }),
3450 TxType::FeeToken => {
3451 FeeTokenTransaction::deserialize(serde::de::value::MapDeserializer::new(iter))
3452 .map(Transaction::FeeTokenTransaction)
3453 .map_err(|e| {
3454 serde::de::Error::custom(format!("Couldn't Deserialize FeeToken {e}"))
3455 })
3456 }
3457 TxType::Frame => Err(serde::de::Error::custom(
3458 "Frame transaction JSON deserialization not supported",
3459 )),
3460 }
3461 }
3462 }
3463
3464 fn deserialize_input_field(
3465 map: &mut std::collections::HashMap<String, Value>,
3466 ) -> Result<Bytes, serde_json::Error> {
3467 let data_str: String = serde_json::from_value(
3468 map.remove("input")
3469 .ok_or_else(|| serde::de::Error::missing_field("input"))?,
3470 )
3471 .map_err(serde::de::Error::custom)?;
3472 if let Some(stripped) = data_str.strip_prefix("0x") {
3473 match hex::decode(stripped) {
3474 Ok(decoded_bytes) => Ok(Bytes::from(decoded_bytes)),
3475 Err(_) => Err(serde::de::Error::custom(
3476 "Invalid hex format in 'input' field",
3477 ))?,
3478 }
3479 } else {
3480 Err(serde::de::Error::custom(
3481 "'input' field must start with '0x'",
3482 ))?
3483 }
3484 }
3485
3486 fn deserialize_field<'de, T, D>(
3487 map: &mut HashMap<String, serde_json::Value>,
3488 key: &str,
3489 ) -> Result<T, D::Error>
3490 where
3491 D: serde::Deserializer<'de>,
3492 T: serde::de::DeserializeOwned,
3493 {
3494 map.remove(key)
3495 .ok_or_else(|| D::Error::custom(format!("Missing field: {key}")))
3496 .and_then(|value| {
3497 serde_json::from_value(value).map_err(|err| D::Error::custom(err.to_string()))
3498 })
3499 }
3500
3501 fn deserialize_u64_field<'de, D>(
3502 map: &mut HashMap<String, serde_json::Value>,
3503 key: &str,
3504 ) -> Result<u64, D::Error>
3505 where
3506 D: serde::Deserializer<'de>,
3507 {
3508 let value = deserialize_field::<U256, D>(map, key)?;
3509 u64::try_from(value).map_err(|_| D::Error::custom(format!("{key} value overflows u64")))
3510 }
3511
3512 impl<'de> Deserialize<'de> for LegacyTransaction {
3513 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3514 where
3515 D: serde::Deserializer<'de>,
3516 {
3517 let mut map = <HashMap<String, serde_json::Value>>::deserialize(deserializer)?;
3518
3519 Ok(LegacyTransaction {
3520 nonce: deserialize_u64_field::<D>(&mut map, "nonce")?,
3521 gas_price: deserialize_field::<U256, D>(&mut map, "gasPrice")?,
3522 gas: deserialize_u64_field::<D>(&mut map, "gas")?,
3523 to: deserialize_field::<TxKind, D>(&mut map, "to")?,
3524 value: deserialize_field::<U256, D>(&mut map, "value")?,
3525 data: deserialize_input_field(&mut map).map_err(serde::de::Error::custom)?,
3526 v: deserialize_field::<U256, D>(&mut map, "v")?,
3527 r: deserialize_field::<U256, D>(&mut map, "r")?,
3528 s: deserialize_field::<U256, D>(&mut map, "s")?,
3529 ..Default::default()
3530 })
3531 }
3532 }
3533
3534 impl<'de> Deserialize<'de> for EIP2930Transaction {
3535 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3536 where
3537 D: serde::Deserializer<'de>,
3538 {
3539 let mut map = <HashMap<String, serde_json::Value>>::deserialize(deserializer)?;
3540
3541 Ok(EIP2930Transaction {
3542 chain_id: deserialize_u64_field::<D>(&mut map, "chainId")?,
3543 nonce: deserialize_u64_field::<D>(&mut map, "nonce")?,
3544 gas_price: deserialize_field::<U256, D>(&mut map, "gasPrice")?,
3545 gas_limit: deserialize_u64_field::<D>(&mut map, "gas")?,
3546 to: deserialize_field::<TxKind, D>(&mut map, "to")?,
3547 value: deserialize_field::<U256, D>(&mut map, "value")?,
3548 data: deserialize_input_field(&mut map).map_err(serde::de::Error::custom)?,
3549 access_list: deserialize_field::<Vec<AccessListEntry>, D>(&mut map, "accessList")?
3550 .into_iter()
3551 .map(|v| (v.address, v.storage_keys))
3552 .collect::<Vec<_>>(),
3553 signature_y_parity: U256::from_str_radix(
3554 deserialize_field::<String, D>(&mut map, "yParity")?.trim_start_matches("0x"),
3555 16,
3556 )
3557 .map_err(serde::de::Error::custom)?,
3558 signature_r: deserialize_field::<U256, D>(&mut map, "r")?,
3559 signature_s: deserialize_field::<U256, D>(&mut map, "s")?,
3560 ..Default::default()
3561 })
3562 }
3563 }
3564
3565 impl<'de> Deserialize<'de> for EIP1559Transaction {
3566 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3567 where
3568 D: serde::Deserializer<'de>,
3569 {
3570 let mut map = <HashMap<String, serde_json::Value>>::deserialize(deserializer)?;
3571 Ok(EIP1559Transaction {
3572 chain_id: deserialize_u64_field::<D>(&mut map, "chainId")?,
3573 nonce: deserialize_u64_field::<D>(&mut map, "nonce")?,
3574 max_priority_fee_per_gas: deserialize_u64_field::<D>(
3575 &mut map,
3576 "maxPriorityFeePerGas",
3577 )?,
3578 max_fee_per_gas: deserialize_u64_field::<D>(&mut map, "maxFeePerGas")?,
3579 gas_limit: deserialize_u64_field::<D>(&mut map, "gas")?,
3580 to: deserialize_field::<TxKind, D>(&mut map, "to")?,
3581 value: deserialize_field::<U256, D>(&mut map, "value")?,
3582 data: deserialize_input_field(&mut map).map_err(serde::de::Error::custom)?,
3583 access_list: deserialize_field::<Vec<AccessListEntry>, D>(&mut map, "accessList")?
3584 .into_iter()
3585 .map(|v| (v.address, v.storage_keys))
3586 .collect::<Vec<_>>(),
3587 signature_y_parity: U256::from_str_radix(
3588 deserialize_field::<String, D>(&mut map, "yParity")?.trim_start_matches("0x"),
3589 16,
3590 )
3591 .map_err(serde::de::Error::custom)?,
3592 signature_r: deserialize_field::<U256, D>(&mut map, "r")?,
3593 signature_s: deserialize_field::<U256, D>(&mut map, "s")?,
3594 ..Default::default()
3595 })
3596 }
3597 }
3598
3599 impl<'de> Deserialize<'de> for EIP4844Transaction {
3600 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3601 where
3602 D: serde::Deserializer<'de>,
3603 {
3604 let mut map = <HashMap<String, serde_json::Value>>::deserialize(deserializer)?;
3605
3606 Ok(EIP4844Transaction {
3607 chain_id: deserialize_u64_field::<D>(&mut map, "chainId")?,
3608 nonce: deserialize_u64_field::<D>(&mut map, "nonce")?,
3609 max_priority_fee_per_gas: deserialize_u64_field::<D>(
3610 &mut map,
3611 "maxPriorityFeePerGas",
3612 )?,
3613 max_fee_per_gas: deserialize_u64_field::<D>(&mut map, "maxFeePerGas")?,
3614 gas: deserialize_u64_field::<D>(&mut map, "gas")?,
3615 to: deserialize_field::<Address, D>(&mut map, "to")?,
3616 value: deserialize_field::<U256, D>(&mut map, "value")?,
3617 data: deserialize_input_field(&mut map).map_err(serde::de::Error::custom)?,
3618 access_list: deserialize_field::<Vec<AccessListEntry>, D>(&mut map, "accessList")?
3619 .into_iter()
3620 .map(|v| (v.address, v.storage_keys))
3621 .collect::<Vec<_>>(),
3622 max_fee_per_blob_gas: deserialize_field::<U256, D>(&mut map, "maxFeePerBlobGas")?,
3623 blob_versioned_hashes: deserialize_field::<Vec<H256>, D>(
3624 &mut map,
3625 "blobVersionedHashes",
3626 )?,
3627 signature_y_parity: U256::from_str_radix(
3628 deserialize_field::<String, D>(&mut map, "yParity")?.trim_start_matches("0x"),
3629 16,
3630 )
3631 .map_err(serde::de::Error::custom)?,
3632 signature_r: deserialize_field::<U256, D>(&mut map, "r")?,
3633 signature_s: deserialize_field::<U256, D>(&mut map, "s")?,
3634 ..Default::default()
3635 })
3636 }
3637 }
3638
3639 impl<'de> Deserialize<'de> for EIP7702Transaction {
3640 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3641 where
3642 D: serde::Deserializer<'de>,
3643 {
3644 let mut map = <HashMap<String, serde_json::Value>>::deserialize(deserializer)?;
3645
3646 Ok(EIP7702Transaction {
3647 chain_id: deserialize_u64_field::<D>(&mut map, "chainId")?,
3648 nonce: deserialize_u64_field::<D>(&mut map, "nonce")?,
3649 max_priority_fee_per_gas: deserialize_u64_field::<D>(
3650 &mut map,
3651 "maxPriorityFeePerGas",
3652 )?,
3653 max_fee_per_gas: deserialize_u64_field::<D>(&mut map, "maxFeePerGas")?,
3654 gas_limit: deserialize_u64_field::<D>(&mut map, "gas")?,
3655 to: deserialize_field::<Address, D>(&mut map, "to")?,
3656 value: deserialize_field::<U256, D>(&mut map, "value")?,
3657 data: deserialize_input_field(&mut map).map_err(serde::de::Error::custom)?,
3658 access_list: deserialize_field::<Vec<AccessListEntry>, D>(&mut map, "accessList")?
3659 .into_iter()
3660 .map(|v| (v.address, v.storage_keys))
3661 .collect::<Vec<_>>(),
3662 authorization_list: deserialize_field::<Vec<AuthorizationTupleEntry>, D>(
3663 &mut map,
3664 "authorizationList",
3665 )?
3666 .into_iter()
3667 .map(AuthorizationTuple::from)
3668 .collect::<Vec<_>>(),
3669 signature_y_parity: U256::from_str_radix(
3670 deserialize_field::<String, D>(&mut map, "yParity")?.trim_start_matches("0x"),
3671 16,
3672 )
3673 .map_err(serde::de::Error::custom)?,
3674 signature_r: deserialize_field::<U256, D>(&mut map, "r")?,
3675 signature_s: deserialize_field::<U256, D>(&mut map, "s")?,
3676 ..Default::default()
3677 })
3678 }
3679 }
3680
3681 impl<'de> Deserialize<'de> for PrivilegedL2Transaction {
3682 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3683 where
3684 D: serde::Deserializer<'de>,
3685 {
3686 let mut map = <HashMap<String, serde_json::Value>>::deserialize(deserializer)?;
3687
3688 Ok(PrivilegedL2Transaction {
3689 chain_id: deserialize_u64_field::<D>(&mut map, "chainId")?,
3690 nonce: deserialize_u64_field::<D>(&mut map, "nonce")?,
3691 max_priority_fee_per_gas: deserialize_u64_field::<D>(
3692 &mut map,
3693 "maxPriorityFeePerGas",
3694 )?,
3695 max_fee_per_gas: deserialize_u64_field::<D>(&mut map, "maxFeePerGas")?,
3696 gas_limit: deserialize_u64_field::<D>(&mut map, "gas")?,
3697 to: deserialize_field::<TxKind, D>(&mut map, "to")?,
3698 value: deserialize_field::<U256, D>(&mut map, "value")?,
3699 data: deserialize_input_field(&mut map).map_err(serde::de::Error::custom)?,
3700 access_list: deserialize_field::<Vec<AccessListEntry>, D>(&mut map, "accessList")?
3701 .into_iter()
3702 .map(|v| (v.address, v.storage_keys))
3703 .collect::<Vec<_>>(),
3704 from: deserialize_field::<Address, D>(&mut map, "sender")?,
3705 ..Default::default()
3706 })
3707 }
3708 }
3709
3710 impl<'de> Deserialize<'de> for FeeTokenTransaction {
3711 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3712 where
3713 D: serde::Deserializer<'de>,
3714 {
3715 let mut map = <HashMap<String, serde_json::Value>>::deserialize(deserializer)?;
3716
3717 Ok(FeeTokenTransaction {
3718 chain_id: deserialize_u64_field::<D>(&mut map, "chainId")?,
3719 nonce: deserialize_u64_field::<D>(&mut map, "nonce")?,
3720 max_priority_fee_per_gas: deserialize_u64_field::<D>(
3721 &mut map,
3722 "maxPriorityFeePerGas",
3723 )?,
3724 max_fee_per_gas: deserialize_u64_field::<D>(&mut map, "maxFeePerGas")?,
3725 gas_limit: deserialize_u64_field::<D>(&mut map, "gas")?,
3726 to: deserialize_field::<TxKind, D>(&mut map, "to")?,
3727 value: deserialize_field::<U256, D>(&mut map, "value")?,
3728 data: deserialize_input_field(&mut map).map_err(serde::de::Error::custom)?,
3729 access_list: deserialize_field::<Vec<AccessListEntry>, D>(&mut map, "accessList")?
3730 .into_iter()
3731 .map(|v| (v.address, v.storage_keys))
3732 .collect::<Vec<_>>(),
3733 fee_token: deserialize_field::<Address, D>(&mut map, "feeToken")?,
3734 signature_y_parity: U256::from_str_radix(
3735 deserialize_field::<String, D>(&mut map, "yParity")?.trim_start_matches("0x"),
3736 16,
3737 )
3738 .map_err(serde::de::Error::custom)?,
3739 signature_r: deserialize_field::<U256, D>(&mut map, "r")?,
3740 signature_s: deserialize_field::<U256, D>(&mut map, "s")?,
3741 ..Default::default()
3742 })
3743 }
3744 }
3745
3746 #[derive(Debug, thiserror::Error)]
3747 pub enum GenericTransactionError {
3748 #[error("Invalid transaction type: {0}")]
3749 InvalidTxType(TxType),
3750 #[error("Blob bundle error: {0}")]
3751 BlobBundleError(#[from] BlobsBundleError),
3752 #[error("Missing field: {0}")]
3753 MissingField(String),
3754 #[error("Invalid field: {0}")]
3755 InvalidField(String),
3756 }
3757
3758 #[derive(Deserialize, Debug, PartialEq, Clone, Default)]
3761 #[serde(rename_all = "camelCase")]
3762 pub struct GenericTransaction {
3763 #[serde(default, deserialize_with = "deserialize_generic_tx_type")]
3764 pub r#type: TxType,
3765 #[serde(default, with = "crate::serde_utils::u64::hex_str_opt")]
3766 pub nonce: Option<u64>,
3767 pub to: TxKind,
3768 #[serde(default)]
3769 pub from: Address,
3770 #[serde(default, with = "crate::serde_utils::u64::hex_str_opt")]
3771 pub gas: Option<u64>,
3772 #[serde(default)]
3773 pub value: U256,
3774 #[serde(default)]
3775 pub gas_price: U256,
3776 #[serde(default, with = "crate::serde_utils::u64::hex_str_opt")]
3777 pub max_priority_fee_per_gas: Option<u64>,
3778 #[serde(default, with = "crate::serde_utils::u64::hex_str_opt")]
3779 pub max_fee_per_gas: Option<u64>,
3780 pub max_fee_per_blob_gas: Option<U256>,
3781 #[serde(default)]
3782 pub access_list: Vec<AccessListEntry>,
3783 #[serde(default)]
3784 pub fee_token: Option<Address>,
3785 #[serde(default)]
3786 pub authorization_list: Option<Vec<AuthorizationTupleEntry>>,
3787 #[serde(default)]
3788 pub blob_versioned_hashes: Vec<H256>,
3789 pub wrapper_version: Option<u8>,
3790 #[serde(default, with = "crate::serde_utils::bytes::vec")]
3791 pub blobs: Vec<Bytes>,
3792 #[serde(default, with = "crate::serde_utils::u64::hex_str_opt")]
3793 pub chain_id: Option<u64>,
3794 #[serde(
3796 flatten,
3797 rename = "input_or_data",
3798 deserialize_with = "deserialize_input",
3799 serialize_with = "crate::serde_utils::bytes::serialize"
3800 )]
3801 pub input: Bytes,
3802 }
3803
3804 fn deserialize_generic_tx_type<'de, D>(deserializer: D) -> Result<TxType, D::Error>
3807 where
3808 D: Deserializer<'de>,
3809 {
3810 let str = String::deserialize(deserializer)?;
3811 let tx_num = u8::from_str_radix(str.trim_start_matches("0x"), 16)
3812 .map_err(|_| D::Error::custom(format!("Failed to deserialize hex value {str}")))?;
3813 Ok(TxType::from_u8(tx_num).unwrap_or_default())
3814 }
3815
3816 pub fn deserialize_input<'de, D>(deserializer: D) -> Result<Bytes, D::Error>
3818 where
3819 D: Deserializer<'de>,
3820 {
3821 let variables = HashMap::<String, Value>::deserialize(deserializer)?;
3824 let data = variables.get("data");
3825 let input = variables.get("input");
3826 let value = match (data, input) {
3827 (None, None) => return Ok(Bytes::new()),
3829 (None, Some(val)) => val,
3830 (Some(val), None) => val,
3831 (Some(val_a), Some(val_b)) => {
3832 if val_a == val_b {
3833 val_a
3834 } else {
3835 return Err(D::Error::custom(
3836 "Transaction has both `data` and `input` fields with different values",
3837 ));
3838 }
3839 }
3840 };
3841 let value = String::deserialize(value).map_err(D::Error::custom)?;
3842 let bytes = hex::decode(value.trim_start_matches("0x"))
3843 .map_err(|e| D::Error::custom(e.to_string()))?;
3844 Ok(Bytes::from(bytes))
3845 }
3846
3847 impl From<EIP1559Transaction> for GenericTransaction {
3848 fn from(value: EIP1559Transaction) -> Self {
3849 Self {
3850 r#type: TxType::EIP1559,
3851 nonce: Some(value.nonce),
3852 to: value.to,
3853 gas: Some(value.gas_limit),
3854 value: value.value,
3855 input: value.data.clone(),
3856 gas_price: U256::from(value.max_fee_per_gas),
3857 max_priority_fee_per_gas: Some(value.max_priority_fee_per_gas),
3858 max_fee_per_gas: Some(value.max_fee_per_gas),
3859 max_fee_per_blob_gas: None,
3860 access_list: value
3861 .access_list
3862 .iter()
3863 .map(AccessListEntry::from)
3864 .collect(),
3865 fee_token: None,
3866 authorization_list: None,
3867 blob_versioned_hashes: vec![],
3868 blobs: vec![],
3869 wrapper_version: None,
3870 chain_id: Some(value.chain_id),
3871 from: Address::default(),
3872 }
3873 }
3874 }
3875
3876 impl TryFrom<GenericTransaction> for EIP1559Transaction {
3877 type Error = GenericTransactionError;
3878
3879 fn try_from(value: GenericTransaction) -> Result<Self, Self::Error> {
3880 if value.r#type != TxType::EIP1559 {
3881 return Err(GenericTransactionError::InvalidTxType(value.r#type));
3882 }
3883
3884 Ok(Self {
3885 nonce: value.nonce.unwrap_or_default(),
3886 to: value.to,
3887 gas_limit: value.gas.unwrap_or_default(),
3888 value: value.value,
3889 data: value.input.clone(),
3890 max_priority_fee_per_gas: value.max_priority_fee_per_gas.unwrap_or_default(),
3891 max_fee_per_gas: value.max_fee_per_gas.unwrap_or(
3892 u64::try_from(value.gas_price).map_err(|_| {
3893 GenericTransactionError::InvalidField("gas_price overflows u64".to_owned())
3894 })?,
3895 ),
3896 access_list: value
3897 .access_list
3898 .into_iter()
3899 .map(|v| (v.address, v.storage_keys))
3900 .collect::<Vec<_>>(),
3901 chain_id: value.chain_id.unwrap_or_default(),
3902 ..Default::default()
3903 })
3904 }
3905 }
3906
3907 impl From<EIP4844Transaction> for GenericTransaction {
3908 fn from(value: EIP4844Transaction) -> Self {
3909 Self {
3910 r#type: TxType::EIP4844,
3911 nonce: Some(value.nonce),
3912 to: TxKind::Call(value.to),
3913 gas: Some(value.gas),
3914 value: value.value,
3915 input: value.data.clone(),
3916 gas_price: U256::from(value.max_fee_per_gas),
3917 max_priority_fee_per_gas: Some(value.max_priority_fee_per_gas),
3918 max_fee_per_gas: Some(value.max_fee_per_gas),
3919 max_fee_per_blob_gas: Some(value.max_fee_per_blob_gas),
3920 access_list: value
3921 .access_list
3922 .iter()
3923 .map(AccessListEntry::from)
3924 .collect(),
3925 fee_token: None,
3926 authorization_list: None,
3927 blob_versioned_hashes: value.blob_versioned_hashes,
3928 blobs: vec![],
3929 wrapper_version: None,
3930 chain_id: Some(value.chain_id),
3931 from: Address::default(),
3932 }
3933 }
3934 }
3935
3936 #[cfg(feature = "c-kzg")]
3937 impl TryFrom<GenericTransaction> for WrappedEIP4844Transaction {
3938 type Error = GenericTransactionError;
3939
3940 fn try_from(value: GenericTransaction) -> Result<Self, Self::Error> {
3941 let blobs = value
3942 .blobs
3943 .iter()
3944 .map(|bytes| {
3945 let slice = bytes.as_ref();
3946 let mut blob = [0u8; BYTES_PER_BLOB];
3947 blob.copy_from_slice(slice);
3948 blob
3949 })
3950 .collect();
3951
3952 let wrapper_version = value.wrapper_version;
3953 Ok(Self {
3954 tx: value.try_into()?,
3955 wrapper_version,
3956 blobs_bundle: BlobsBundle::create_from_blobs(&blobs, wrapper_version)?,
3957 })
3958 }
3959 }
3960
3961 impl TryFrom<GenericTransaction> for EIP4844Transaction {
3962 type Error = GenericTransactionError;
3963
3964 fn try_from(value: GenericTransaction) -> Result<Self, Self::Error> {
3965 if value.r#type != TxType::EIP4844 {
3966 return Err(GenericTransactionError::InvalidTxType(value.r#type));
3967 }
3968 Ok(Self {
3969 nonce: value.nonce.unwrap_or_default(),
3970 to: match value.to {
3971 TxKind::Call(to) => to,
3972 _ => H160::default(),
3973 },
3974 gas: value.gas.unwrap_or_default(),
3975 value: value.value,
3976 data: value.input.clone(),
3977 max_priority_fee_per_gas: value.max_priority_fee_per_gas.unwrap_or_default(),
3978 max_fee_per_gas: value.max_fee_per_gas.unwrap_or(
3979 u64::try_from(value.gas_price).map_err(|_| {
3980 GenericTransactionError::InvalidField("gas_price overflows u64".to_owned())
3981 })?,
3982 ),
3983 max_fee_per_blob_gas: value.max_fee_per_blob_gas.unwrap_or_default(),
3984 access_list: value
3985 .access_list
3986 .into_iter()
3987 .map(|v| (v.address, v.storage_keys))
3988 .collect::<Vec<_>>(),
3989 blob_versioned_hashes: value.blob_versioned_hashes,
3990 chain_id: value.chain_id.unwrap_or_default(),
3991 ..Default::default()
3992 })
3993 }
3994 }
3995
3996 impl From<EIP7702Transaction> for GenericTransaction {
3997 fn from(value: EIP7702Transaction) -> Self {
3998 Self {
3999 r#type: TxType::EIP7702,
4000 nonce: Some(value.nonce),
4001 to: TxKind::Call(value.to),
4002 gas: Some(value.gas_limit),
4003 value: value.value,
4004 input: value.data.clone(),
4005 gas_price: U256::from(value.max_fee_per_gas),
4006 max_priority_fee_per_gas: Some(value.max_priority_fee_per_gas),
4007 max_fee_per_gas: Some(value.max_fee_per_gas),
4008 max_fee_per_blob_gas: None,
4009 access_list: value
4010 .access_list
4011 .iter()
4012 .map(AccessListEntry::from)
4013 .collect(),
4014 fee_token: None,
4015 authorization_list: Some(
4016 value
4017 .authorization_list
4018 .iter()
4019 .map(AuthorizationTupleEntry::from)
4020 .collect(),
4021 ),
4022 blob_versioned_hashes: vec![],
4023 blobs: vec![],
4024 wrapper_version: None,
4025 chain_id: Some(value.chain_id),
4026 from: Address::default(),
4027 }
4028 }
4029 }
4030
4031 impl TryFrom<GenericTransaction> for EIP7702Transaction {
4032 type Error = GenericTransactionError;
4033
4034 fn try_from(value: GenericTransaction) -> Result<Self, Self::Error> {
4035 if value.r#type != TxType::EIP7702 {
4036 return Err(GenericTransactionError::InvalidTxType(value.r#type));
4037 }
4038 let TxKind::Call(to) = value.to else {
4039 return Err(GenericTransactionError::MissingField("to".to_owned()));
4040 };
4041 Ok(Self {
4042 chain_id: value.chain_id.unwrap_or_default(),
4043 nonce: value.nonce.unwrap_or_default(),
4044 max_priority_fee_per_gas: value.max_priority_fee_per_gas.unwrap_or_default(),
4045 max_fee_per_gas: value.max_fee_per_gas.unwrap_or(
4046 u64::try_from(value.gas_price).map_err(|_| {
4047 GenericTransactionError::InvalidField("gas_price overflows u64".to_owned())
4048 })?,
4049 ),
4050 gas_limit: value.gas.unwrap_or_default(),
4051 to,
4052 value: value.value,
4053 data: value.input,
4054 access_list: value
4055 .access_list
4056 .into_iter()
4057 .map(|v| (v.address, v.storage_keys))
4058 .collect::<Vec<_>>(),
4059 authorization_list: value
4060 .authorization_list
4061 .unwrap_or_default()
4062 .into_iter()
4063 .map(AuthorizationTuple::from)
4064 .collect(),
4065 ..Default::default()
4066 })
4067 }
4068 }
4069
4070 impl From<PrivilegedL2Transaction> for GenericTransaction {
4071 fn from(value: PrivilegedL2Transaction) -> Self {
4072 Self {
4073 r#type: TxType::Privileged,
4074 nonce: Some(value.nonce),
4075 to: value.to,
4076 gas: Some(value.gas_limit),
4077 value: value.value,
4078 input: value.data.clone(),
4079 gas_price: U256::from(value.max_fee_per_gas),
4080 max_priority_fee_per_gas: Some(value.max_priority_fee_per_gas),
4081 max_fee_per_gas: Some(value.max_fee_per_gas),
4082 max_fee_per_blob_gas: None,
4083 access_list: value
4084 .access_list
4085 .iter()
4086 .map(AccessListEntry::from)
4087 .collect(),
4088 fee_token: None,
4089 authorization_list: None,
4090 blob_versioned_hashes: vec![],
4091 blobs: vec![],
4092 wrapper_version: None,
4093 chain_id: Some(value.chain_id),
4094 from: value.from,
4095 }
4096 }
4097 }
4098
4099 impl TryFrom<GenericTransaction> for PrivilegedL2Transaction {
4100 type Error = GenericTransactionError;
4101
4102 fn try_from(value: GenericTransaction) -> Result<Self, Self::Error> {
4103 if value.r#type != TxType::Privileged {
4104 return Err(GenericTransactionError::InvalidTxType(value.r#type));
4105 }
4106 Ok(Self {
4107 nonce: value.nonce.unwrap_or_default(),
4108 to: value.to,
4109 gas_limit: value.gas.unwrap_or_default(),
4110 value: value.value,
4111 data: value.input.clone(),
4112 max_priority_fee_per_gas: value.max_priority_fee_per_gas.unwrap_or_default(),
4113 max_fee_per_gas: value.max_fee_per_gas.unwrap_or(
4114 u64::try_from(value.gas_price).map_err(|_| {
4115 GenericTransactionError::InvalidField("gas_price overflows u64".to_owned())
4116 })?,
4117 ),
4118 access_list: value
4119 .access_list
4120 .into_iter()
4121 .map(|v| (v.address, v.storage_keys))
4122 .collect::<Vec<_>>(),
4123 chain_id: value.chain_id.unwrap_or_default(),
4124 from: value.from,
4125 ..Default::default()
4126 })
4127 }
4128 }
4129
4130 impl From<FeeTokenTransaction> for GenericTransaction {
4131 fn from(value: FeeTokenTransaction) -> Self {
4132 Self {
4133 r#type: TxType::FeeToken,
4134 nonce: Some(value.nonce),
4135 to: value.to,
4136 gas: Some(value.gas_limit),
4137 value: value.value,
4138 input: value.data.clone(),
4139 gas_price: U256::from(value.max_fee_per_gas),
4140 max_priority_fee_per_gas: Some(value.max_priority_fee_per_gas),
4141 max_fee_per_gas: Some(value.max_fee_per_gas),
4142 max_fee_per_blob_gas: None,
4143 access_list: value
4144 .access_list
4145 .iter()
4146 .map(AccessListEntry::from)
4147 .collect(),
4148 fee_token: Some(value.fee_token),
4149 authorization_list: None,
4150 blob_versioned_hashes: vec![],
4151 blobs: vec![],
4152 chain_id: Some(value.chain_id),
4153 from: Address::default(),
4154 wrapper_version: None,
4155 }
4156 }
4157 }
4158
4159 impl TryFrom<GenericTransaction> for FeeTokenTransaction {
4160 type Error = GenericTransactionError;
4161
4162 fn try_from(value: GenericTransaction) -> Result<Self, Self::Error> {
4163 if value.r#type != TxType::FeeToken {
4164 return Err(GenericTransactionError::InvalidTxType(value.r#type));
4165 }
4166
4167 Ok(Self {
4168 nonce: value.nonce.unwrap_or_default(),
4169 to: value.to,
4170 gas_limit: value.gas.unwrap_or_default(),
4171 value: value.value,
4172 data: value.input.clone(),
4173 max_priority_fee_per_gas: value.max_priority_fee_per_gas.unwrap_or_default(),
4174 max_fee_per_gas: value.max_fee_per_gas.unwrap_or(
4175 u64::try_from(value.gas_price).map_err(|_| {
4176 GenericTransactionError::InvalidField("gas_price overflows u64".to_owned())
4177 })?,
4178 ),
4179 access_list: value
4180 .access_list
4181 .into_iter()
4182 .map(|v| (v.address, v.storage_keys))
4183 .collect::<Vec<_>>(),
4184 fee_token: value
4185 .fee_token
4186 .ok_or(GenericTransactionError::MissingField(
4187 "fee token".to_owned(),
4188 ))?,
4189 chain_id: value.chain_id.unwrap_or_default(),
4190 ..Default::default()
4191 })
4192 }
4193 }
4194
4195 impl From<LegacyTransaction> for GenericTransaction {
4196 fn from(value: LegacyTransaction) -> Self {
4197 Self {
4198 r#type: TxType::Legacy,
4199 nonce: Some(value.nonce),
4200 to: value.to,
4201 from: Address::default(),
4202 gas: Some(value.gas),
4203 value: value.value,
4204 gas_price: value.gas_price,
4205 max_priority_fee_per_gas: None,
4206 max_fee_per_gas: None,
4207 max_fee_per_blob_gas: None,
4208 access_list: vec![],
4209 fee_token: None,
4210 authorization_list: None,
4211 blob_versioned_hashes: vec![],
4212 blobs: vec![],
4213 wrapper_version: None,
4214 chain_id: None,
4215 input: value.data,
4216 }
4217 }
4218 }
4219
4220 impl From<EIP2930Transaction> for GenericTransaction {
4221 fn from(value: EIP2930Transaction) -> Self {
4222 Self {
4223 r#type: TxType::EIP2930,
4224 nonce: Some(value.nonce),
4225 to: value.to,
4226 from: Address::default(),
4227 gas: Some(value.gas_limit),
4228 value: value.value,
4229 gas_price: value.gas_price,
4230 max_priority_fee_per_gas: None,
4231 max_fee_per_gas: None,
4232 max_fee_per_blob_gas: None,
4233 access_list: value
4234 .access_list
4235 .into_iter()
4236 .map(|(address, storage_keys)| AccessListEntry {
4237 address,
4238 storage_keys,
4239 })
4240 .collect(),
4241 fee_token: None,
4242 authorization_list: None,
4243 blob_versioned_hashes: vec![],
4244 blobs: vec![],
4245 wrapper_version: None,
4246 chain_id: Some(value.chain_id),
4247 input: value.data,
4248 }
4249 }
4250 }
4251
4252 impl From<Transaction> for GenericTransaction {
4253 fn from(value: Transaction) -> Self {
4254 match value {
4255 Transaction::LegacyTransaction(tx) => tx.into(),
4256 Transaction::EIP2930Transaction(tx) => tx.into(),
4257 Transaction::EIP1559Transaction(tx) => tx.into(),
4258 Transaction::EIP4844Transaction(tx) => tx.into(),
4259 Transaction::EIP7702Transaction(tx) => tx.into(),
4260 Transaction::PrivilegedL2Transaction(tx) => tx.into(),
4261 Transaction::FeeTokenTransaction(tx) => tx.into(),
4262 Transaction::FrameTransaction(tx) => tx.into(),
4263 }
4264 }
4265 }
4266
4267 impl From<FrameTransaction> for GenericTransaction {
4268 fn from(value: FrameTransaction) -> Self {
4269 Self {
4270 r#type: TxType::Frame,
4271 nonce: Some(value.nonce),
4272 to: TxKind::Call(value.sender),
4273 from: value.sender,
4274 gas: Some(value.max_gas()),
4275 value: U256::zero(),
4276 gas_price: value.max_fee_per_gas.into(),
4277 max_priority_fee_per_gas: Some(value.max_priority_fee_per_gas),
4278 max_fee_per_gas: Some(value.max_fee_per_gas),
4279 max_fee_per_blob_gas: if value.blob_versioned_hashes.is_empty() {
4280 None
4281 } else {
4282 Some(value.max_fee_per_blob_gas)
4283 },
4284 access_list: vec![],
4285 fee_token: None,
4286 authorization_list: None,
4287 blob_versioned_hashes: value.blob_versioned_hashes,
4288 blobs: vec![],
4289 wrapper_version: None,
4290 chain_id: Some(value.chain_id),
4291 input: Bytes::new(),
4292 }
4293 }
4294 }
4295}
4296
4297mod mempool {
4298 use super::*;
4299 use std::{
4300 cmp::Ordering,
4301 sync::Arc,
4302 time::{SystemTime, UNIX_EPOCH},
4303 };
4304
4305 #[derive(Debug, Clone, PartialEq, Eq)]
4306 pub struct MempoolTransaction {
4307 timestamp: u128,
4309 sender: Address,
4310 inner: Arc<Transaction>,
4311 }
4312
4313 impl MempoolTransaction {
4314 pub fn new(tx: Transaction, sender: Address) -> Self {
4315 Self {
4316 timestamp: SystemTime::now()
4317 .duration_since(UNIX_EPOCH)
4318 .expect("Invalid system time")
4319 .as_micros(),
4320 sender,
4321 inner: Arc::new(tx),
4322 }
4323 }
4324 pub fn time(&self) -> u128 {
4325 self.timestamp
4326 }
4327
4328 pub fn sender(&self) -> Address {
4329 self.sender
4330 }
4331
4332 pub fn transaction(&self) -> &Transaction {
4333 &self.inner
4334 }
4335 }
4336
4337 impl RLPEncode for MempoolTransaction {
4338 fn encode(&self, buf: &mut dyn bytes::BufMut) {
4339 Encoder::new(buf)
4340 .encode_field(&self.timestamp)
4341 .encode_field(&*self.inner)
4342 .finish();
4343 }
4344 }
4345
4346 impl RLPDecode for MempoolTransaction {
4347 fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), RLPDecodeError> {
4348 let decoder = Decoder::new(rlp)?;
4349 let (timestamp, decoder) = decoder.decode_field("timestamp")?;
4350 let (sender, decoder) = decoder.decode_field("sender")?;
4351 let (inner, decoder) = decoder.decode_field("inner")?;
4352 Ok((
4353 Self {
4354 timestamp,
4355 sender,
4356 inner: Arc::new(inner),
4357 },
4358 decoder.finish()?,
4359 ))
4360 }
4361 }
4362
4363 impl std::ops::Deref for MempoolTransaction {
4364 type Target = Transaction;
4365
4366 fn deref(&self) -> &Self::Target {
4367 &self.inner
4368 }
4369 }
4370
4371 impl Ord for MempoolTransaction {
4373 fn cmp(&self, other: &Self) -> Ordering {
4374 match (self.tx_type(), other.tx_type()) {
4375 (TxType::Privileged, TxType::Privileged) => {
4376 return self.nonce().cmp(&other.nonce());
4377 }
4378 (TxType::Privileged, _) => return Ordering::Less,
4379 (_, TxType::Privileged) => return Ordering::Greater,
4380 _ => (),
4381 };
4382 match self.nonce().cmp(&other.nonce()) {
4383 Ordering::Equal => other.time().cmp(&self.time()),
4384 ordering => ordering,
4385 }
4386 }
4387 }
4388
4389 impl PartialOrd for MempoolTransaction {
4390 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
4391 Some(self.cmp(other))
4392 }
4393 }
4394}
4395
4396#[cfg(test)]
4397mod tests {
4398
4399 use super::*;
4400 use crate::types::{
4401 AuthorizationTuple, BlockBody, Receipt, compute_receipts_root, compute_transactions_root,
4402 };
4403 use ethereum_types::H160;
4404 use hex_literal::hex;
4405 use serde_impl::{AccessListEntry, GenericTransaction};
4406 use std::str::FromStr;
4407
4408 #[test]
4409 fn is_blob_carrying_covers_frame_txs_with_blob_hashes() {
4410 let plain_frame = Transaction::FrameTransaction(FrameTransaction::default());
4416 assert!(!plain_frame.is_blob_carrying());
4417
4418 let blob_frame = Transaction::FrameTransaction(FrameTransaction {
4419 max_fee_per_blob_gas: U256::from(7u64),
4420 blob_versioned_hashes: vec![H256::from_low_u64_be(1)],
4421 ..Default::default()
4422 });
4423 assert!(blob_frame.is_blob_carrying());
4424
4425 let blob_tx = Transaction::EIP4844Transaction(EIP4844Transaction {
4426 blob_versioned_hashes: vec![H256::from_low_u64_be(1)],
4427 ..Default::default()
4428 });
4429 assert!(blob_tx.is_blob_carrying());
4430
4431 let plain = Transaction::EIP1559Transaction(EIP1559Transaction::default());
4432 assert!(!plain.is_blob_carrying());
4433 }
4434
4435 #[test]
4436 fn nonce_over_u64_max_maps_to_nonce_is_max() {
4437 let rlp = hex!("ca89010000000000000000");
4440 let decoder = Decoder::new(&rlp).unwrap();
4441 let err = decode_nonce_field(decoder).unwrap_err();
4442 assert!(
4443 err.to_string().contains("Nonce is max"),
4444 "unexpected error: {err}"
4445 );
4446 }
4447
4448 #[test]
4449 fn nonce_at_u64_max_decodes() {
4450 let rlp = hex!("c988ffffffffffffffff");
4452 let decoder = Decoder::new(&rlp).unwrap();
4453 let (nonce, _) = decode_nonce_field(decoder).unwrap();
4454 assert_eq!(nonce, u64::MAX);
4455 }
4456
4457 #[test]
4458 fn legacy_chain_id_handles_out_of_range_v_without_underflow() {
4459 let legacy_chain_id = |v: u64| {
4465 Transaction::LegacyTransaction(LegacyTransaction {
4466 v: U256::from(v),
4467 ..Default::default()
4468 })
4469 .chain_id()
4470 };
4471 for v in [0u64, 1, 26, 27, 28, 34] {
4472 assert_eq!(legacy_chain_id(v), None, "v={v} must yield no chain id");
4473 }
4474 assert_eq!(legacy_chain_id(35), Some(0));
4476 assert_eq!(legacy_chain_id(36), Some(0));
4477 assert_eq!(legacy_chain_id(37), Some(1));
4478 }
4479
4480 #[test]
4486 fn legacy_chain_id_at_the_64_bit_boundary() {
4487 let secret = secp256k1::SecretKey::from_byte_array(&[0x11; 32]).unwrap();
4488 let signed_for = |chain_id: U256| {
4489 let mut tx = LegacyTransaction {
4490 nonce: 7,
4491 gas_price: U256::from(1_000_000_000u64),
4492 gas: 21_000,
4493 to: TxKind::Call(Address::repeat_byte(0xde)),
4494 value: U256::one(),
4495 v: U256::from(35) + chain_id * 2,
4496 ..Default::default()
4497 };
4498 let (payload, _) = Transaction::LegacyTransaction(tx.clone())
4499 .signing_payload()
4500 .unwrap()
4501 .unwrap();
4502 let msg = secp256k1::Message::from_digest(NativeCrypto.keccak256(&payload));
4503 let (recovery_id, signature) = secp256k1::SECP256K1
4504 .sign_ecdsa_recoverable(&msg, &secret)
4505 .serialize_compact();
4506 tx.r = U256::from_big_endian(&signature[..32]);
4507 tx.s = U256::from_big_endian(&signature[32..]);
4508 tx.v += U256::from(i32::from(recovery_id));
4509 Transaction::LegacyTransaction(tx)
4510 };
4511 let signer = signed_for(U256::one()).sender(&NativeCrypto).unwrap();
4512
4513 let largest = signed_for(U256::from(u64::MAX));
4514 let Transaction::LegacyTransaction(legacy) = &largest else {
4515 unreachable!("signed_for builds legacy transactions");
4516 };
4517 assert!(legacy.v > U256::from(u64::MAX), "the case under test");
4518 assert_eq!(largest.chain_id(), Some(u64::MAX));
4519 assert_eq!(largest.sender(&NativeCrypto).unwrap(), signer);
4520
4521 let too_large = Transaction::LegacyTransaction(LegacyTransaction {
4522 v: U256::from(35) + (U256::from(u64::MAX) + 1) * 2,
4523 ..Default::default()
4524 });
4525 assert_eq!(too_large.chain_id(), None);
4526 assert!(too_large.sender(&NativeCrypto).is_err());
4527 }
4528
4529 #[test]
4530 fn test_compute_transactions_root() {
4531 let mut body = BlockBody::empty();
4532 let tx = LegacyTransaction {
4533 nonce: 0,
4534 gas_price: U256::from(0x0a),
4535 gas: 0x05f5e100,
4536 to: TxKind::Call(hex!("1000000000000000000000000000000000000000").into()),
4537 value: 0.into(),
4538 data: Default::default(),
4539 v: U256::from(0x1b),
4540 r: U256::from_big_endian(&hex!(
4541 "7e09e26678ed4fac08a249ebe8ed680bf9051a5e14ad223e4b2b9d26e0208f37"
4542 )),
4543 s: U256::from_big_endian(&hex!(
4544 "5f6e3f188e3e6eab7d7d3b6568f5eac7d687b08d307d3154ccd8c87b4630509b"
4545 )),
4546 ..Default::default()
4547 };
4548 body.transactions.push(Transaction::LegacyTransaction(tx));
4549 let expected_root =
4550 hex!("8151d548273f6683169524b66ca9fe338b9ce42bc3540046c828fd939ae23bcb");
4551 let result = compute_transactions_root(&body.transactions, ðrex_crypto::NativeCrypto);
4552
4553 assert_eq!(result, expected_root.into());
4554 }
4555 #[test]
4556 fn test_compute_hash() {
4557 let tx_eip2930 = EIP2930Transaction {
4559 chain_id: 3503995874084926u64,
4560 nonce: 7,
4561 gas_price: U256::from(0x2dbf1f9a_u64),
4562 gas_limit: 0x186A0,
4563 to: TxKind::Call(hex!("7dcd17433742f4c0ca53122ab541d0ba67fc27df").into()),
4564 value: 2.into(),
4565 data: Bytes::from(&b"\xdbS\x06$\x8e\x03\x13\xe7emit"[..]),
4566 access_list: vec![(
4567 hex!("7dcd17433742f4c0ca53122ab541d0ba67fc27df").into(),
4568 vec![
4569 hex!("0000000000000000000000000000000000000000000000000000000000000000").into(),
4570 hex!("a3d07a7d68fbd49ec2f8e6befdd86c885f86c272819f6f345f365dec35ae6707").into(),
4571 ],
4572 )],
4573 signature_y_parity: 0u8.into(),
4574 signature_r: U256::from_dec_str(
4575 "75813812796588349127366022588733264074091236448495248199152066031778895768879",
4576 )
4577 .unwrap(),
4578 signature_s: U256::from_dec_str(
4579 "25476208226281085290728123165613764315157904411823916642262684106502155457829",
4580 )
4581 .unwrap(),
4582 ..Default::default()
4583 };
4584 let tx = Transaction::EIP2930Transaction(tx_eip2930);
4585
4586 let expected_hash =
4587 hex!("a0762610d794acddd2dca15fb7c437ada3611c886f3bea675d53d8da8a6c41b2");
4588 let hash = tx.compute_hash(&NativeCrypto);
4589 assert_eq!(hash, expected_hash.into());
4590 }
4591
4592 #[test]
4593 fn test_compute_receipts_root() {
4594 let tx_type = TxType::Legacy;
4597 let succeeded = true;
4598 let cumulative_gas_used = 0x5208;
4599 let logs = vec![];
4600 let receipt = Receipt::new(tx_type, succeeded, cumulative_gas_used, logs);
4601
4602 let result = compute_receipts_root(&[receipt], ðrex_crypto::NativeCrypto);
4603 let expected_root =
4604 hex!("056b23fbba480696b65fe5a59b8f2148a1299103c4f57df839233af2cf4ca2d2");
4605 assert_eq!(result, expected_root.into());
4606 }
4607
4608 #[test]
4609 fn legacy_tx_rlp_decode() {
4610 let encoded_tx = "f86d80843baa0c4082f618946177843db3138ae69679a54b95cf345ed759450d870aa87bee538000808360306ba0151ccc02146b9b11adf516e6787b59acae3e76544fdcd75e77e67c6b598ce65da064c5dd5aae2fbb535830ebbdad0234975cd7ece3562013b63ea18cc0df6c97d4";
4611 let encoded_tx_bytes = hex::decode(encoded_tx).unwrap();
4612 let tx = LegacyTransaction::decode(&encoded_tx_bytes).unwrap();
4613 let expected_tx = LegacyTransaction {
4614 nonce: 0,
4615 gas_price: U256::from(1001000000u64),
4616 gas: 63000,
4617 to: TxKind::Call(Address::from_slice(
4618 &hex::decode("6177843db3138ae69679A54b95cf345ED759450d").unwrap(),
4619 )),
4620 value: 3000000000000000_u64.into(),
4621 data: Bytes::new(),
4622 r: U256::from_str_radix(
4623 "151ccc02146b9b11adf516e6787b59acae3e76544fdcd75e77e67c6b598ce65d",
4624 16,
4625 )
4626 .unwrap(),
4627 s: U256::from_str_radix(
4628 "64c5dd5aae2fbb535830ebbdad0234975cd7ece3562013b63ea18cc0df6c97d4",
4629 16,
4630 )
4631 .unwrap(),
4632 v: 6303851.into(),
4633 ..Default::default()
4634 };
4635 assert_eq!(tx, expected_tx);
4636 }
4637
4638 #[test]
4639 fn eip1559_tx_rlp_decode() {
4640 let encoded_tx = "f86c8330182480114e82f618946177843db3138ae69679a54b95cf345ed759450d870aa87bee53800080c080a0151ccc02146b9b11adf516e6787b59acae3e76544fdcd75e77e67c6b598ce65da064c5dd5aae2fbb535830ebbdad0234975cd7ece3562013b63ea18cc0df6c97d4";
4641 let encoded_tx_bytes = hex::decode(encoded_tx).unwrap();
4642 let tx = EIP1559Transaction::decode(&encoded_tx_bytes).unwrap();
4643 let expected_tx = EIP1559Transaction {
4644 nonce: 0,
4645 max_fee_per_gas: 78,
4646 max_priority_fee_per_gas: 17,
4647 to: TxKind::Call(Address::from_slice(
4648 &hex::decode("6177843db3138ae69679A54b95cf345ED759450d").unwrap(),
4649 )),
4650 value: 3000000000000000_u64.into(),
4651 data: Bytes::new(),
4652 signature_r: U256::from_str_radix(
4653 "151ccc02146b9b11adf516e6787b59acae3e76544fdcd75e77e67c6b598ce65d",
4654 16,
4655 )
4656 .unwrap(),
4657 signature_s: U256::from_str_radix(
4658 "64c5dd5aae2fbb535830ebbdad0234975cd7ece3562013b63ea18cc0df6c97d4",
4659 16,
4660 )
4661 .unwrap(),
4662 signature_y_parity: 0u8.into(),
4663 chain_id: 3151908,
4664 gas_limit: 63000,
4665 access_list: vec![],
4666 ..Default::default()
4667 };
4668 assert_eq!(tx, expected_tx);
4669 }
4670
4671 #[test]
4672 fn deserialize_tx_kind() {
4673 let tx_kind_create = r#""""#;
4674 let tx_kind_call = r#""0x6177843db3138ae69679A54b95cf345ED759450d""#;
4675 let deserialized_tx_kind_create = TxKind::Create;
4676 let deserialized_tx_kind_call = TxKind::Call(Address::from_slice(
4677 &hex::decode("6177843db3138ae69679A54b95cf345ED759450d").unwrap(),
4678 ));
4679 assert_eq!(
4680 deserialized_tx_kind_create,
4681 serde_json::from_str(tx_kind_create).unwrap()
4682 );
4683 assert_eq!(
4684 deserialized_tx_kind_call,
4685 serde_json::from_str(tx_kind_call).unwrap()
4686 )
4687 }
4688
4689 #[test]
4690 fn deserialize_tx_type() {
4691 let tx_type_eip2930 = r#""0x01""#;
4692 let tx_type_eip1559 = r#""0x02""#;
4693 let deserialized_tx_type_eip2930 = TxType::EIP2930;
4694 let deserialized_tx_type_eip1559 = TxType::EIP1559;
4695 assert_eq!(
4696 deserialized_tx_type_eip2930,
4697 serde_json::from_str(tx_type_eip2930).unwrap()
4698 );
4699 assert_eq!(
4700 deserialized_tx_type_eip1559,
4701 serde_json::from_str(tx_type_eip1559).unwrap()
4702 )
4703 }
4704
4705 #[test]
4706 fn deserialize_generic_transaction() {
4707 let generic_transaction = r#"{
4708 "type":"0x01",
4709 "nonce":"0x02",
4710 "to":"",
4711 "from":"0x6177843db3138ae69679A54b95cf345ED759450d",
4712 "gas":"0x5208",
4713 "value":"0x01",
4714 "input":"0x010203040506",
4715 "gasPrice":"0x07",
4716 "accessList": [
4717 {
4718 "address": "0x000f3df6d732807ef1319fb7b8bb8522d0beac02",
4719 "storageKeys": [
4720 "0x000000000000000000000000000000000000000000000000000000000000000c",
4721 "0x000000000000000000000000000000000000000000000000000000000000200b"
4722 ]
4723 }
4724 ]
4725 }"#;
4726 let deserialized_generic_transaction = GenericTransaction {
4727 r#type: TxType::EIP2930,
4728 nonce: Some(2),
4729 to: TxKind::Create,
4730 from: Address::from_slice(
4731 &hex::decode("6177843db3138ae69679A54b95cf345ED759450d").unwrap(),
4732 ),
4733 gas: Some(0x5208),
4734 value: U256::from(1),
4735 input: Bytes::from(hex::decode("010203040506").unwrap()),
4736 gas_price: U256::from(7),
4737 max_priority_fee_per_gas: Default::default(),
4738 max_fee_per_gas: Default::default(),
4739 max_fee_per_blob_gas: Default::default(),
4740 access_list: vec![AccessListEntry {
4741 address: Address::from_slice(
4742 &hex::decode("000f3df6d732807ef1319fb7b8bb8522d0beac02").unwrap(),
4743 ),
4744 storage_keys: vec![H256::from_low_u64_be(12), H256::from_low_u64_be(8203)],
4745 }],
4746 fee_token: None,
4747 blob_versioned_hashes: Default::default(),
4748 blobs: Default::default(),
4749 wrapper_version: None,
4750 chain_id: Default::default(),
4751 authorization_list: None,
4752 };
4753 assert_eq!(
4754 deserialized_generic_transaction,
4755 serde_json::from_str(generic_transaction).unwrap()
4756 )
4757 }
4758
4759 #[test]
4760 fn deserialize_generic_transaction_with_unknown_type() {
4761 let generic_transaction: GenericTransaction = serde_json::from_str(
4762 r#"{"type":"0x7f","to":"0x6177843db3138ae69679A54b95cf345ED759450d"}"#,
4763 )
4764 .unwrap();
4765 assert_eq!(generic_transaction.r#type, TxType::default());
4766 assert!(
4767 serde_json::from_str::<GenericTransaction>(
4768 r#"{"type":"0x100","to":"0x6177843db3138ae69679A54b95cf345ED759450d"}"#
4769 )
4770 .is_err()
4771 );
4772 }
4773
4774 #[test]
4775 fn deserialize_generic_transaction_with_data_and_input_fields() {
4776 let generic_transaction = r#"{
4777 "type":"0x01",
4778 "nonce":"0x02",
4779 "to":"",
4780 "from":"0x6177843db3138ae69679A54b95cf345ED759450d",
4781 "gas":"0x5208",
4782 "value":"0x01",
4783 "input":"0x010203040506",
4784 "data":"0x010203040506",
4785 "gasPrice":"0x07",
4786 "accessList": [
4787 {
4788 "address": "0x000f3df6d732807ef1319fb7b8bb8522d0beac02",
4789 "storageKeys": [
4790 "0x000000000000000000000000000000000000000000000000000000000000000c",
4791 "0x000000000000000000000000000000000000000000000000000000000000200b"
4792 ]
4793 }
4794 ]
4795 }"#;
4796 let deserialized_generic_transaction = GenericTransaction {
4797 r#type: TxType::EIP2930,
4798 nonce: Some(2),
4799 to: TxKind::Create,
4800 from: Address::from_slice(
4801 &hex::decode("6177843db3138ae69679A54b95cf345ED759450d").unwrap(),
4802 ),
4803 gas: Some(0x5208),
4804 value: U256::from(1),
4805 input: Bytes::from(hex::decode("010203040506").unwrap()),
4806 gas_price: U256::from(7),
4807 max_priority_fee_per_gas: Default::default(),
4808 max_fee_per_gas: Default::default(),
4809 max_fee_per_blob_gas: Default::default(),
4810 access_list: vec![AccessListEntry {
4811 address: Address::from_slice(
4812 &hex::decode("000f3df6d732807ef1319fb7b8bb8522d0beac02").unwrap(),
4813 ),
4814 storage_keys: vec![H256::from_low_u64_be(12), H256::from_low_u64_be(8203)],
4815 }],
4816 fee_token: None,
4817 blob_versioned_hashes: Default::default(),
4818 blobs: Default::default(),
4819 wrapper_version: None,
4820 chain_id: Default::default(),
4821 authorization_list: None,
4822 };
4823 assert_eq!(
4824 deserialized_generic_transaction,
4825 serde_json::from_str(generic_transaction).unwrap()
4826 )
4827 }
4828
4829 #[test]
4830 fn deserialize_eip4844_transaction() {
4831 let eip4844_transaction = r#"{
4832 "chainId":"0x01",
4833 "nonce":"0x02",
4834 "maxPriorityFeePerGas":"0x01",
4835 "maxFeePerGas":"0x01",
4836 "gas":"0x5208",
4837 "to":"0x6177843db3138ae69679A54b95cf345ED759450d",
4838 "value":"0x01",
4839 "input":"0x3033",
4840 "accessList": [
4841 {
4842 "address": "0x000f3df6d732807ef1319fb7b8bb8522d0beac02",
4843 "storageKeys": [
4844 "0x000000000000000000000000000000000000000000000000000000000000000c",
4845 "0x000000000000000000000000000000000000000000000000000000000000200b"
4846 ]
4847 }
4848 ],
4849 "maxFeePerBlobGas":"0x03",
4850 "blobVersionedHashes": [
4851 "0x0000000000000000000000000000000000000000000000000000000000000001",
4852 "0x0000000000000000000000000000000000000000000000000000000000000002"
4853 ],
4854 "yParity":"0x0",
4855 "r": "0x01",
4856 "s": "0x02"
4857 }"#;
4858 let deserialized_eip4844_transaction = EIP4844Transaction {
4859 chain_id: 0x01,
4860 nonce: 0x02,
4861 to: Address::from_slice(
4862 &hex::decode("6177843db3138ae69679A54b95cf345ED759450d").unwrap(),
4863 ),
4864 max_priority_fee_per_gas: 1,
4865 max_fee_per_gas: 1,
4866 max_fee_per_blob_gas: U256::from(0x03),
4867 gas: 0x5208,
4868 value: U256::from(0x01),
4869 data: Bytes::from_static(b"03"),
4871 access_list: vec![(
4872 Address::from_slice(
4873 &hex::decode("000f3df6d732807ef1319fb7b8bb8522d0beac02").unwrap(),
4874 ),
4875 vec![H256::from_low_u64_be(12), H256::from_low_u64_be(8203)],
4876 )],
4877 blob_versioned_hashes: vec![H256::from_low_u64_be(1), H256::from_low_u64_be(2)],
4878 signature_y_parity: 0u8.into(),
4879 signature_r: U256::from(0x01),
4880 signature_s: U256::from(0x02),
4881 ..Default::default()
4882 };
4883
4884 assert_eq!(
4885 deserialized_eip4844_transaction,
4886 serde_json::from_str(eip4844_transaction).unwrap()
4887 )
4888 }
4889
4890 #[test]
4891 fn serialize_deserialize_transaction() {
4892 let eip1559 = EIP1559Transaction {
4893 chain_id: 65536999,
4894 nonce: 1,
4895 max_priority_fee_per_gas: 1000,
4896 max_fee_per_gas: 2000,
4897 gas_limit: 21000,
4898 to: TxKind::Call(H160::from_str("0x000a52D537c4150ec274dcE3962a0d179B7E71B0").unwrap()),
4899 value: U256::from(100000),
4900 data: Bytes::from_static(b"03"),
4901 access_list: vec![(
4902 H160::from_str("0x000a52D537c4150ec274dcE3962a0d179B7E71B3").unwrap(),
4903 vec![H256::zero()],
4904 )],
4905 signature_y_parity: 1u8.into(),
4906 signature_r: U256::one(),
4907 signature_s: U256::zero(),
4908 ..Default::default()
4909 };
4910 let tx_to_serialize = Transaction::EIP1559Transaction(eip1559.clone());
4911 let serialized = serde_json::to_string(&tx_to_serialize).expect("Failed to serialize");
4912
4913 let deserialized_tx: Transaction =
4914 serde_json::from_str(&serialized).expect("Failed to deserialize");
4915
4916 assert!(deserialized_tx.tx_type() == TxType::EIP1559);
4917
4918 if let Transaction::EIP1559Transaction(tx) = deserialized_tx {
4919 assert_eq!(tx, eip1559);
4920 }
4921 }
4922
4923 #[test]
4924 fn serialize_deserialize_eip7702transaction() {
4925 let eip7702 = EIP7702Transaction {
4926 chain_id: 65536999,
4927 nonce: 1,
4928 max_priority_fee_per_gas: 1000,
4929 max_fee_per_gas: 2000,
4930 gas_limit: 21000,
4931 to: Address::from_str("0x000a52D537c4150ec274dcE3962a0d179B7E71B0").unwrap(),
4932 value: U256::from(100000),
4933 data: Bytes::from_static(b"03"),
4934 access_list: vec![],
4935 signature_y_parity: 1u8.into(),
4936 signature_r: U256::one(),
4937 signature_s: U256::zero(),
4938 authorization_list: vec![AuthorizationTuple {
4939 chain_id: U256::from(65536999),
4940 address: H160::from_str("0x000a52D537c4150ec274dcE3962a0d179B7E71B1").unwrap(),
4941 nonce: 2,
4942 y_parity: U256::one(),
4943 r_signature: U256::from(22),
4944 s_signature: U256::from(37),
4945 }],
4946 ..Default::default()
4947 };
4948 let tx_to_serialize = Transaction::EIP7702Transaction(eip7702.clone());
4949 let serialized = serde_json::to_string(&tx_to_serialize).expect("Failed to serialize");
4950
4951 let deserialized_tx: Transaction =
4952 serde_json::from_str(&serialized).expect("Failed to deserialize");
4953
4954 assert!(deserialized_tx.tx_type() == TxType::EIP7702);
4955
4956 if let Transaction::EIP7702Transaction(tx) = deserialized_tx {
4957 assert_eq!(tx, eip7702);
4958 }
4959 }
4960
4961 #[test]
4962 fn serialize_deserialize_privileged_l2_transaction() -> Result<(), RLPDecodeError> {
4963 let privileged_l2 = PrivilegedL2Transaction {
4964 chain_id: 65536999,
4965 nonce: 0,
4966 max_priority_fee_per_gas: 875000000,
4967 max_fee_per_gas: 875000000,
4968 gas_limit: 42000u64,
4969 to: TxKind::Call(
4970 Address::from_str("0x8943545177806ed17b9f23f0a21ee5948ecaa776").unwrap(),
4971 ),
4972 value: U256::from(500000000000000000000000000u128),
4973 data: Bytes::new(),
4974 access_list: vec![],
4975 from: Address::from_str("0x8943545177806ed17b9f23f0a21ee5948ecaa776").unwrap(),
4976 ..Default::default()
4977 };
4978
4979 let encoded = PrivilegedL2Transaction::encode_to_vec(&privileged_l2);
4980 println!("encoded length: {}", encoded.len());
4981 assert_eq!(encoded.len(), privileged_l2.length());
4982
4983 let deserialized_tx = PrivilegedL2Transaction::decode(&encoded)?;
4984
4985 assert_eq!(deserialized_tx, privileged_l2);
4986
4987 Ok(())
4988 }
4989
4990 #[test]
4991 fn test_legacy_transaction_into_generic() {
4992 let legacy_tx = LegacyTransaction {
4993 nonce: 1,
4994 gas_price: U256::from(20_000_000_000u64),
4995 gas: 21000,
4996 to: TxKind::Call(
4997 Address::from_str("0x742d35Cc6634C0532925a3b844Bc454e4438f44e").unwrap(),
4998 ),
4999 value: U256::from(1_000_000_000_000_000_000u64),
5000 data: Bytes::default(),
5001 v: U256::from(27),
5002 r: U256::from(1),
5003 s: U256::from(1),
5004 ..Default::default()
5005 };
5006
5007 let generic_tx: GenericTransaction = legacy_tx.into();
5008 assert_eq!(generic_tx.r#type, TxType::Legacy);
5009 assert_eq!(generic_tx.nonce, Some(1));
5010 assert_eq!(generic_tx.gas_price, U256::from(20_000_000_000u64));
5011 assert_eq!(generic_tx.gas, Some(21000));
5012 assert_eq!(generic_tx.max_priority_fee_per_gas, None);
5013 assert_eq!(generic_tx.max_fee_per_gas, None);
5014 assert_eq!(generic_tx.access_list.len(), 0);
5015 assert_eq!(generic_tx.chain_id, None);
5016 }
5017
5018 #[test]
5019 fn test_eip2930_transaction_into_generic() {
5020 let access_list = vec![(
5021 Address::from_str("0x742d35Cc6634C0532925a3b844Bc454e4438f44e").unwrap(),
5022 vec![
5023 H256::from_str(
5024 "0x1234567890123456789012345678901234567890123456789012345678901234",
5025 )
5026 .unwrap(),
5027 ],
5028 )];
5029
5030 let eip2930_tx = EIP2930Transaction {
5031 chain_id: 1,
5032 nonce: 1,
5033 gas_price: U256::from(20_000_000_000u64),
5034 gas_limit: 21000,
5035 to: TxKind::Call(
5036 Address::from_str("0x742d35Cc6634C0532925a3b844Bc454e4438f44e").unwrap(),
5037 ),
5038 value: U256::from(1_000_000_000_000_000_000u64),
5039 data: Bytes::default(),
5040 access_list: access_list.clone(),
5041 signature_y_parity: 0u8.into(),
5042 signature_r: U256::from(1),
5043 signature_s: U256::from(1),
5044 ..Default::default()
5045 };
5046
5047 let generic_tx: GenericTransaction = eip2930_tx.into();
5048 assert_eq!(generic_tx.r#type, TxType::EIP2930);
5049 assert_eq!(generic_tx.nonce, Some(1));
5050 assert_eq!(generic_tx.gas_price, U256::from(20_000_000_000u64));
5051 assert_eq!(generic_tx.gas, Some(21000));
5052 assert_eq!(generic_tx.max_priority_fee_per_gas, None);
5053 assert_eq!(generic_tx.max_fee_per_gas, None);
5054 assert_eq!(generic_tx.chain_id, Some(1));
5055 assert_eq!(generic_tx.access_list.len(), 1);
5056 assert_eq!(generic_tx.access_list[0].address, access_list[0].0);
5057 assert_eq!(generic_tx.access_list[0].storage_keys, access_list[0].1);
5058 }
5059
5060 #[test]
5061 fn recover_address_rejects_high_s_signatures() {
5062 use ethrex_crypto::NativeCrypto;
5063 use k256::ecdsa::SigningKey;
5064
5065 let crypto = NativeCrypto;
5066
5067 let private_key = hex!("4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318");
5070 let signing_key = SigningKey::from_bytes(&private_key.into()).expect("Valid private key");
5071
5072 let msg = b"Test message for high-s signature rejection";
5074 let payload = keccak(msg).to_fixed_bytes();
5076
5077 let (signature, recovery_id) = signing_key
5080 .sign_prehash_recoverable(&payload)
5081 .expect("Signing failed");
5082
5083 let mut sig_bytes = [0u8; 65];
5085 sig_bytes[..64].copy_from_slice(&signature.to_bytes());
5086 sig_bytes[64] = recovery_id.to_byte();
5087
5088 let uncompressed_pub = signing_key.verifying_key().to_encoded_point(false);
5091 let pub_hash = ethrex_crypto::keccak::keccak_hash(&uncompressed_pub.as_bytes()[1..]);
5092 let expected_address = Address::from_slice(&pub_hash[12..]);
5093
5094 let recovered = crypto
5095 .recover_signer(&sig_bytes, &payload)
5096 .expect("Valid low-s signature should recover successfully");
5097 assert_eq!(recovered, expected_address, "Recovered address mismatch");
5098
5099 let n = U256::from_big_endian(&hex!(
5102 "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"
5103 ));
5104 let s = U256::from_big_endian(&sig_bytes[32..64]);
5105
5106 let half_n = n / 2;
5108 assert!(
5109 s <= half_n,
5110 "Generated signature was not low-s, cannot test high-s rejection"
5111 );
5112
5113 let s_high = n - s;
5115
5116 let mut sig_high_bytes = sig_bytes;
5117 sig_high_bytes[32..64].copy_from_slice(&s_high.to_big_endian());
5119 sig_high_bytes[64] ^= 1;
5121
5122 assert!(
5125 crypto.recover_signer(&sig_high_bytes, &payload).is_err(),
5126 "High-s signature should be rejected (EIP-2 compliance)"
5127 );
5128 }
5129
5130 #[test]
5131 fn encode_decode_low_size_tx() {
5132 let tx = Transaction::EIP2930Transaction(EIP2930Transaction::default());
5133 let tx_to_encode = tx.clone();
5136 let encoded = tx_to_encode.encode_to_vec();
5137 let decoded_tx = Transaction::decode(&encoded).unwrap();
5138 assert_eq!(tx, decoded_tx);
5139 }
5140
5141 #[test]
5142 fn test_eip1559_simple_transfer_size() {
5143 let tx = Transaction::EIP1559Transaction(EIP1559Transaction::default());
5144 assert_eq!(tx.encode_to_vec().len(), EIP1559_DEFAULT_SERIALIZED_LENGTH);
5145 }
5146
5147 fn make_test_frame_tx() -> FrameTransaction {
5150 FrameTransaction {
5151 chain_id: 1,
5152 nonce: 42,
5153 sender: Address::from_low_u64_be(0xABCD),
5154 frames: vec![
5155 Frame {
5156 mode: FrameMode::Verify as u8,
5157 flags: 0x03, target: Some(Address::from_low_u64_be(0xABCD)),
5159 gas_limit: 100_000,
5160 value: U256::zero(),
5161 data: Bytes::from_static(b"verify_data"),
5162 },
5163 Frame {
5164 mode: FrameMode::Sender as u8,
5165 flags: 0x00,
5166 target: Some(Address::from_low_u64_be(0x1234)),
5167 gas_limit: 200_000,
5168 value: U256::zero(),
5169 data: Bytes::from_static(b"call_data"),
5170 },
5171 ],
5172 signatures: vec![FrameSignature {
5173 scheme: FRAME_SIG_SCHEME_SECP256K1,
5174 signer: Some(Address::from_low_u64_be(0xABCD)),
5175 msg: Bytes::new(),
5176 signature: Bytes::from(vec![0u8; 65]),
5177 }],
5178 max_priority_fee_per_gas: 1_000_000_000,
5179 max_fee_per_gas: 30_000_000_000,
5180 max_fee_per_blob_gas: U256::zero(),
5181 blob_versioned_hashes: vec![],
5182 inner_hash: OnceCell::new(),
5183 cached_canonical: OnceCell::new(),
5184 }
5185 }
5186
5187 #[test]
5188 fn atomic_batch_flag_valid_on_default_and_sender_frames() {
5189 let mut tx = make_test_frame_tx();
5192 tx.frames = vec![
5193 Frame {
5194 mode: FrameMode::Default as u8,
5195 flags: 0x04, target: Some(Address::from_low_u64_be(0xB0B)),
5197 gas_limit: 21_000,
5198 value: U256::zero(),
5199 data: Bytes::new(),
5200 },
5201 Frame {
5202 mode: FrameMode::Sender as u8,
5203 flags: 0x04, target: Some(Address::from_low_u64_be(0xB0B)),
5205 gas_limit: 21_000,
5206 value: U256::zero(),
5207 data: Bytes::new(),
5208 },
5209 Frame {
5210 mode: FrameMode::Sender as u8,
5211 flags: 0x00, target: Some(Address::from_low_u64_be(0xCAFE)),
5213 gas_limit: 21_000,
5214 value: U256::zero(),
5215 data: Bytes::new(),
5216 },
5217 ];
5218 assert!(tx.validate_static_constraints().is_ok());
5219 }
5220
5221 #[test]
5222 fn atomic_batch_flag_on_last_frame_still_invalid() {
5223 let mut tx = make_test_frame_tx();
5224 tx.frames = vec![Frame {
5225 mode: FrameMode::Sender as u8,
5226 flags: 0x04,
5227 target: Some(Address::from_low_u64_be(0xCAFE)),
5228 gas_limit: 21_000,
5229 value: U256::zero(),
5230 data: Bytes::new(),
5231 }];
5232 let err = tx.validate_static_constraints().unwrap_err();
5233 assert!(err.contains("atomic batch flag on last frame"), "{err}");
5234 }
5235
5236 #[test]
5237 fn test_frame_rlp_roundtrip() {
5238 let frame = Frame {
5239 mode: FrameMode::Verify as u8,
5240 flags: 0x03,
5241 target: Some(Address::from_low_u64_be(0x1234)),
5242 gas_limit: 50_000,
5243 value: U256::zero(),
5244 data: Bytes::from_static(b"hello"),
5245 };
5246 let encoded = frame.encode_to_vec();
5247 let decoded = Frame::decode(&encoded).unwrap();
5248 assert_eq!(frame, decoded);
5249 }
5250
5251 #[test]
5252 fn test_frame_null_target_rlp_roundtrip() {
5253 let frame = Frame {
5254 mode: FrameMode::Default as u8,
5255 flags: 0x00,
5256 target: None,
5257 gas_limit: 10_000,
5258 value: U256::zero(),
5259 data: Bytes::from_static(b"deploy"),
5260 };
5261 let encoded = frame.encode_to_vec();
5262 let decoded = Frame::decode(&encoded).unwrap();
5263 assert_eq!(frame, decoded);
5264 }
5265
5266 #[test]
5267 fn test_frame_mode_with_flags_rlp_roundtrip() {
5268 for mode_val in [0u8, 1, 2] {
5270 let frame = Frame {
5271 mode: mode_val,
5272 flags: if mode_val == 1 { 0x03 } else { 0x00 },
5273 target: Some(Address::from_low_u64_be(0x1234)),
5274 gas_limit: 50_000,
5275 value: U256::zero(),
5276 data: Bytes::new(),
5277 };
5278 let encoded = frame.encode_to_vec();
5279 let decoded = Frame::decode(&encoded).unwrap();
5280 assert_eq!(frame, decoded);
5281 }
5282 let frame = Frame {
5284 mode: 2, flags: 0x01 | 0x04, target: Some(Address::from_low_u64_be(0x1234)),
5287 gas_limit: 50_000,
5288 value: U256::zero(),
5289 data: Bytes::new(),
5290 };
5291 assert_eq!(frame.execution_mode(), FrameMode::Sender);
5292 assert_eq!(frame.scope_restriction(), 1);
5293 assert!(frame.is_atomic_batch());
5294 let encoded = frame.encode_to_vec();
5295 let decoded = Frame::decode(&encoded).unwrap();
5296 assert_eq!(frame, decoded);
5297 }
5298
5299 #[test]
5300 fn frame_rlp_roundtrip_preserves_value() {
5301 let frame = Frame {
5302 mode: FrameMode::Sender as u8,
5303 flags: 0x00,
5304 target: Some(Address::from_low_u64_be(0xCAFE)),
5305 gas_limit: 100_000,
5306 value: U256::from(1_000_000_000_000_000u64), data: Bytes::from_static(b"hello"),
5308 };
5309 let encoded = frame.encode_to_vec();
5310 let decoded = Frame::decode(&encoded).unwrap();
5311 assert_eq!(frame, decoded);
5312 assert_eq!(decoded.value, U256::from(1_000_000_000_000_000u64));
5313 }
5314
5315 #[test]
5316 fn test_frame_transaction_rlp_roundtrip() {
5317 let tx = make_test_frame_tx();
5318 let encoded = tx.encode_to_vec();
5319 let decoded = FrameTransaction::decode(&encoded).unwrap();
5320 assert_eq!(tx, decoded);
5321 }
5322
5323 #[test]
5324 fn test_frame_transaction_canonical_roundtrip() {
5325 let tx = Transaction::FrameTransaction(make_test_frame_tx());
5326 let encoded = tx.encode_canonical_to_vec();
5327 let decoded = Transaction::decode_canonical(&encoded).unwrap();
5328 assert_eq!(
5330 tx.hash(ðrex_crypto::NativeCrypto),
5331 decoded.hash(ðrex_crypto::NativeCrypto)
5332 );
5333 assert_eq!(tx.tx_type(), decoded.tx_type());
5335 assert_eq!(tx.nonce(), decoded.nonce());
5336 assert_eq!(tx.chain_id(), decoded.chain_id());
5337 }
5338
5339 #[test]
5340 fn test_frame_transaction_sig_hash_covers_all_frame_data() {
5341 let tx = make_test_frame_tx();
5343 let hash1 = tx.compute_sig_hash();
5344
5345 let mut tx2 = tx.clone();
5347 tx2.frames[0].data = Bytes::from_static(b"completely_different_verify_data");
5348 let hash2 = tx2.compute_sig_hash();
5349 assert_ne!(hash1, hash2);
5350
5351 let mut tx3 = tx;
5353 tx3.frames[1].data = Bytes::from_static(b"different_call_data");
5354 let hash3 = tx3.compute_sig_hash();
5355 assert_ne!(hash1, hash3);
5356 }
5357
5358 #[test]
5359 fn test_frame_transaction_accessor_methods() {
5360 let frame_tx = make_test_frame_tx();
5361 let tx = Transaction::FrameTransaction(frame_tx);
5362
5363 assert_eq!(tx.tx_type(), TxType::Frame);
5364 assert_eq!(tx.nonce(), 42);
5365 assert_eq!(tx.chain_id(), Some(1));
5366 assert_eq!(tx.to(), TxKind::Call(Address::from_low_u64_be(0xABCD)));
5367 assert_eq!(tx.value(), U256::zero());
5368 assert_eq!(tx.data(), &Bytes::new());
5369 assert!(tx.access_list().is_empty());
5370 assert!(tx.authorization_list().is_none());
5371 assert_eq!(tx.max_priority_fee(), Some(1_000_000_000));
5372 assert_eq!(tx.max_fee_per_gas(), Some(30_000_000_000));
5373 assert_eq!(tx.max_fee_per_blob_gas(), None); assert!(!tx.is_contract_creation());
5375 assert_eq!(
5377 tx.sender(ðrex_crypto::NativeCrypto).unwrap(),
5378 Address::from_low_u64_be(0xABCD)
5379 );
5380 assert!(tx.gas_limit() >= 300_000); }
5383
5384 #[test]
5385 fn test_frame_transaction_hash_uses_oncecell() {
5386 let tx = Transaction::FrameTransaction(make_test_frame_tx());
5387 let h1 = tx.hash(ðrex_crypto::NativeCrypto);
5388 let h2 = tx.hash(ðrex_crypto::NativeCrypto);
5389 assert_eq!(h1, h2);
5390 }
5391
5392 #[test]
5393 fn frame_transaction_rlp_roundtrip_preserves_fields() {
5394 let tx = make_test_frame_tx();
5395 let mut buf = Vec::new();
5396 tx.encode(&mut buf);
5397 let (decoded, rest) = FrameTransaction::decode_unfinished(&buf).unwrap();
5398 assert!(rest.is_empty());
5399 assert_eq!(decoded.chain_id, tx.chain_id);
5400 assert_eq!(decoded.nonce, tx.nonce);
5401 assert_eq!(decoded.sender, tx.sender);
5402 }
5403
5404 #[test]
5405 fn frame_transaction_variant_is_exposed_on_transaction_enum() {
5406 let tx = Transaction::FrameTransaction(make_test_frame_tx());
5407 assert!(matches!(tx, Transaction::FrameTransaction(_)));
5408 }
5409
5410 #[test]
5411 fn frame_transaction_serializes_signatures_as_array() {
5412 let tx = make_test_frame_tx();
5414 let json = serde_json::to_value(&tx).unwrap();
5415 let sigs = json
5416 .get("signatures")
5417 .expect("signatures field present")
5418 .as_array()
5419 .expect("signatures serialized as an array");
5420 assert_eq!(sigs.len(), tx.signatures.len());
5421 assert_eq!(sigs[0].get("scheme").unwrap(), "0x1");
5422 assert!(sigs[0].get("signer").is_some());
5423 assert!(sigs[0].get("signature").is_some());
5424 assert!(sigs[0].get("msg").is_some());
5425 }
5426
5427 fn make_frame_tx_with_gas_limits(limits: Vec<u64>) -> FrameTransaction {
5428 let frames = limits
5429 .into_iter()
5430 .map(|gl| Frame {
5431 mode: FrameMode::Sender as u8,
5432 flags: 0x00,
5433 target: Some(Address::from_low_u64_be(0x1234)),
5434 gas_limit: gl,
5435 value: U256::zero(),
5436 data: Bytes::new(),
5437 })
5438 .collect();
5439 FrameTransaction {
5440 chain_id: 1,
5441 nonce: 0,
5442 sender: Address::from_low_u64_be(0xABCD),
5443 frames,
5444 signatures: vec![],
5445 max_priority_fee_per_gas: 1_000_000_000,
5446 max_fee_per_gas: 30_000_000_000,
5447 max_fee_per_blob_gas: U256::zero(),
5448 blob_versioned_hashes: vec![],
5449 inner_hash: OnceCell::new(),
5450 cached_canonical: OnceCell::new(),
5451 }
5452 }
5453
5454 #[test]
5455 fn per_frame_gas_limit_above_i64_max_is_rejected() {
5456 let tx = make_frame_tx_with_gas_limits(vec![(i64::MAX as u64) + 1]);
5457 let err = tx.validate_static_constraints().unwrap_err();
5458 assert!(err.contains("exceeds 2**63-1"), "unexpected error: {err}");
5459 }
5460
5461 #[test]
5462 fn cumulative_frame_gas_limit_above_i64_max_is_rejected() {
5463 let half = (i64::MAX as u64) / 2 + 1;
5464 let tx = make_frame_tx_with_gas_limits(vec![half, half]);
5465 let err = tx.validate_static_constraints().unwrap_err();
5466 assert!(err.contains("cumulative"), "unexpected error: {err}");
5467 }
5468
5469 #[test]
5470 fn cumulative_frame_gas_limit_equal_to_i64_max_is_accepted() {
5471 let a = (i64::MAX as u64) / 2;
5472 let b = i64::MAX as u64 - a;
5473 let tx = make_frame_tx_with_gas_limits(vec![a, b]);
5474 tx.validate_static_constraints()
5475 .expect("exact i64::MAX total should be accepted");
5476 }
5477
5478 #[test]
5479 fn empty_frames_list_is_rejected_by_count_check_not_gas_check() {
5480 let tx = make_frame_tx_with_gas_limits(vec![]);
5483 let err = tx.validate_static_constraints().unwrap_err();
5484 assert!(err.contains("between 1 and"), "unexpected error: {err}");
5485 }
5486
5487 #[test]
5488 fn sig_hash_covers_frame_value() {
5489 let tx = make_test_frame_tx();
5492 let baseline = tx.compute_sig_hash();
5493
5494 let mut with_sender_value = tx.clone();
5495 with_sender_value.frames[1].value = U256::from(1u64);
5496 assert_ne!(
5497 baseline,
5498 with_sender_value.compute_sig_hash(),
5499 "sig_hash must change when a SENDER frame's value changes"
5500 );
5501
5502 let mut with_verify_value = tx.clone();
5503 with_verify_value.frames[0].value = U256::from(1u64);
5504 assert_ne!(
5505 baseline,
5506 with_verify_value.compute_sig_hash(),
5507 "sig_hash must change when a VERIFY frame's value changes"
5508 );
5509
5510 let mut with_verify_data = tx;
5512 with_verify_data.frames[0].data = Bytes::from_static(b"different_verify_data");
5513 assert_ne!(
5514 baseline,
5515 with_verify_data.compute_sig_hash(),
5516 "VERIFY.data is now covered by sig_hash (no longer elided)"
5517 );
5518 }
5519
5520 #[test]
5521 fn validate_static_constraints_rejects_nonzero_value_on_non_sender_frames() {
5522 let verify_tx = FrameTransaction {
5524 chain_id: 1,
5525 nonce: 0,
5526 sender: Address::from_low_u64_be(0xABCD),
5527 frames: vec![Frame {
5528 mode: FrameMode::Verify as u8,
5529 flags: 0x01,
5530 target: None,
5531 gas_limit: 50_000,
5532 value: U256::from(1u64),
5533 data: Bytes::new(),
5534 }],
5535 signatures: vec![],
5536 max_priority_fee_per_gas: 1_000_000_000,
5537 max_fee_per_gas: 30_000_000_000,
5538 max_fee_per_blob_gas: U256::zero(),
5539 blob_versioned_hashes: vec![],
5540 inner_hash: OnceCell::new(),
5541 cached_canonical: OnceCell::new(),
5542 };
5543 let err = verify_tx.validate_static_constraints().unwrap_err();
5544 assert!(
5545 err.contains("non-zero value only allowed in SENDER mode"),
5546 "unexpected error for VERIFY: {err}"
5547 );
5548
5549 let default_tx = FrameTransaction {
5551 frames: vec![Frame {
5552 mode: FrameMode::Default as u8,
5553 flags: 0x00,
5554 target: Some(Address::from_low_u64_be(0x1234)),
5555 gas_limit: 50_000,
5556 value: U256::from(1u64),
5557 data: Bytes::new(),
5558 }],
5559 ..verify_tx
5560 };
5561 let err = default_tx.validate_static_constraints().unwrap_err();
5562 assert!(
5563 err.contains("non-zero value only allowed in SENDER mode"),
5564 "unexpected error for DEFAULT: {err}"
5565 );
5566
5567 let sender_tx = FrameTransaction {
5569 frames: vec![Frame {
5570 mode: FrameMode::Sender as u8,
5571 flags: 0x00,
5572 target: Some(Address::from_low_u64_be(0x1234)),
5573 gas_limit: 50_000,
5574 value: U256::from(1u64),
5575 data: Bytes::new(),
5576 }],
5577 ..default_tx
5578 };
5579 sender_tx
5580 .validate_static_constraints()
5581 .expect("SENDER frames may carry non-zero value");
5582 }
5583
5584 fn chain_config_with_hegota(hegota_time: Option<u64>) -> crate::types::ChainConfig {
5587 crate::types::ChainConfig {
5588 hegota_time,
5589 ..Default::default()
5590 }
5591 }
5592
5593 #[test]
5594 fn test_frame_tx_pre_fork_chain_config_rejects() {
5595 let cfg = chain_config_with_hegota(None);
5596 assert!(!cfg.is_hegota_activated(0));
5597 assert!(!cfg.is_hegota_activated(u64::MAX));
5598 }
5599
5600 #[test]
5601 fn test_frame_tx_post_fork_admits() {
5602 let cfg = chain_config_with_hegota(Some(1000));
5603 assert!(cfg.is_hegota_activated(2000));
5604 }
5605
5606 #[test]
5607 fn test_frame_tx_fork_boundary_admits() {
5608 let activation_time = 1_700_000_000u64;
5609 let cfg = chain_config_with_hegota(Some(activation_time));
5610 assert!(cfg.is_hegota_activated(activation_time));
5611 assert!(!cfg.is_hegota_activated(activation_time - 1));
5612 }
5613
5614 #[test]
5615 fn test_frame_tx_devnet_fork_epoch_zero_admits() {
5616 let cfg = chain_config_with_hegota(Some(0));
5617 assert!(cfg.is_hegota_activated(0));
5618 assert!(cfg.is_hegota_activated(1));
5619 assert!(cfg.is_hegota_activated(u64::MAX));
5620 }
5621
5622 #[test]
5623 fn test_frame_tx_pre_fork_rlp_roundtrip_still_decodes() {
5624 let tx = make_test_frame_tx();
5627 let mut buf = Vec::new();
5628 tx.encode(&mut buf);
5629 let (decoded, rest) = FrameTransaction::decode_unfinished(&buf).unwrap();
5630 assert!(rest.is_empty());
5631 assert_eq!(decoded.chain_id, tx.chain_id);
5632 assert_eq!(decoded.nonce, tx.nonce);
5633 assert_eq!(decoded.sender, tx.sender);
5634 }
5635
5636 fn expiry_frame(deadline: u64) -> Frame {
5639 Frame {
5640 mode: FrameMode::Verify as u8,
5641 flags: 0x00,
5642 target: Some(frame_tx_expiry_verifier()),
5643 gas_limit: 30_000,
5644 value: U256::zero(),
5645 data: Bytes::copy_from_slice(&deadline.to_be_bytes()),
5646 }
5647 }
5648
5649 #[test]
5650 fn expiry_verifier_frame_passes_static_validation() {
5651 let mut tx = make_test_frame_tx();
5652 tx.frames.insert(0, expiry_frame(1_700_000_000));
5653 assert!(tx.validate_static_constraints().is_ok());
5654 }
5655
5656 #[test]
5657 fn expiry_verifier_frame_rejects_bad_data_length() {
5658 let mut tx = make_test_frame_tx();
5659 let mut f = expiry_frame(0);
5660 f.data = Bytes::from_static(b"short");
5661 tx.frames.insert(0, f);
5662 let err = tx.validate_static_constraints().unwrap_err();
5663 assert!(err.contains("8 bytes"), "{err}");
5664 }
5665
5666 #[test]
5667 fn expiry_verifier_frame_rejects_nonzero_flags() {
5668 let mut tx = make_test_frame_tx();
5669 let mut f = expiry_frame(0);
5670 f.flags = 0x01;
5671 tx.frames.insert(0, f);
5672 let err = tx.validate_static_constraints().unwrap_err();
5673 assert!(err.contains("flags == 0"), "{err}");
5674 }
5675
5676 #[test]
5677 fn at_most_one_expiry_verifier_frame() {
5678 let mut tx = make_test_frame_tx();
5679 tx.frames.insert(0, expiry_frame(1));
5680 tx.frames.insert(0, expiry_frame(2));
5681 let err = tx.validate_static_constraints().unwrap_err();
5682 assert!(err.contains("more than one expiry"), "{err}");
5683 }
5684
5685 #[test]
5686 fn verify_frame_with_zero_scope_is_now_statically_valid() {
5687 let mut tx = make_test_frame_tx();
5692 tx.frames[0].flags = 0x00;
5693 assert!(tx.validate_static_constraints().is_ok());
5694 }
5695
5696 #[test]
5697 fn sig_hash_covers_expiry_deadline_and_all_verify_data() {
5698 let mut tx_a = make_test_frame_tx();
5700 tx_a.frames.insert(0, expiry_frame(100));
5701 let mut tx_b = make_test_frame_tx();
5702 tx_b.frames.insert(0, expiry_frame(200));
5703 assert_ne!(tx_a.compute_sig_hash(), tx_b.compute_sig_hash());
5705
5706 let tx_c = make_test_frame_tx();
5708 let mut tx_d = make_test_frame_tx();
5709 tx_d.frames[0].data = Bytes::from_static(b"different_verify_data");
5710 assert_ne!(tx_c.compute_sig_hash(), tx_d.compute_sig_hash());
5711 }
5712
5713 #[test]
5714 fn expiry_deadline_parses_or_none() {
5715 let mut tx = make_test_frame_tx();
5716 assert_eq!(tx.expiry_deadline(), None);
5717 tx.frames.insert(0, expiry_frame(1_700_000_123));
5718 assert_eq!(tx.expiry_deadline(), Some(1_700_000_123));
5719 }
5720
5721 #[test]
5722 fn signature_rlp_roundtrip() {
5723 let sig = FrameSignature {
5724 scheme: FRAME_SIG_SCHEME_P256,
5725 signer: Some(Address::from_low_u64_be(0x1234)),
5726 msg: Bytes::from(vec![7u8; 32]),
5727 signature: Bytes::from(vec![9u8; 128]),
5728 };
5729 let mut buf = Vec::new();
5730 sig.encode(&mut buf);
5731 let (decoded, rest) = FrameSignature::decode_unfinished(&buf).unwrap();
5732 assert!(rest.is_empty());
5733 assert_eq!(decoded, sig);
5734 }
5735
5736 #[test]
5737 fn frame_tx_with_signatures_rlp_roundtrip() {
5738 let tx = make_test_frame_tx();
5739 assert!(!tx.signatures.is_empty());
5740 let mut buf = Vec::new();
5741 tx.encode(&mut buf);
5742 let (decoded, rest) = FrameTransaction::decode_unfinished(&buf).unwrap();
5743 assert!(rest.is_empty());
5744 assert_eq!(decoded.signatures, tx.signatures);
5745 assert_eq!(decoded.frames, tx.frames);
5746 assert_eq!(decoded.nonce, tx.nonce);
5747 }
5748
5749 #[test]
5750 fn p2p_frame_transaction_rlp_roundtrip() {
5751 let ft = make_test_frame_tx();
5754 assert!(!ft.signatures.is_empty());
5755 assert!(!ft.frames.is_empty());
5756 let original = P2PTransaction::FrameTransaction(ft);
5757
5758 let encoded = original.encode_to_vec();
5759 let (decoded, rest) = P2PTransaction::decode_unfinished(&encoded).unwrap();
5760 assert!(rest.is_empty());
5761 assert_eq!(decoded, original);
5762 assert_eq!(decoded.tx_type(), TxType::Frame);
5763
5764 let as_tx: Transaction = decoded.try_into().unwrap();
5767 assert!(matches!(as_tx, Transaction::FrameTransaction(_)));
5768 }
5769
5770 #[test]
5771 fn static_validation_rejects_unknown_scheme() {
5772 let mut tx = make_test_frame_tx();
5773 tx.signatures[0].scheme = 3;
5774 assert!(
5775 tx.validate_static_constraints()
5776 .unwrap_err()
5777 .contains("unsupported scheme"),
5778 );
5779 }
5780
5781 #[test]
5782 fn static_validation_accepts_arbitrary_with_empty_signer() {
5783 let mut tx = make_test_frame_tx();
5784 tx.signatures[0].scheme = FRAME_SIG_SCHEME_ARBITRARY;
5786 tx.signatures[0].signer = None;
5787 assert!(tx.validate_static_constraints().is_ok());
5788 assert_eq!(tx.signature_verification_cost(), 100);
5789 }
5790
5791 #[test]
5792 fn static_validation_rejects_arbitrary_with_signer() {
5793 let mut tx = make_test_frame_tx();
5794 tx.signatures[0].scheme = FRAME_SIG_SCHEME_ARBITRARY;
5795 tx.signatures[0].signer = Some(Address::from_low_u64_be(0xABCD));
5796 assert!(
5797 tx.validate_static_constraints()
5798 .unwrap_err()
5799 .contains("ARBITRARY signatures must not name a signer"),
5800 );
5801 }
5802
5803 #[test]
5804 fn static_validation_rejects_bad_msg_length() {
5805 let mut tx = make_test_frame_tx();
5806 tx.signatures[0].msg = Bytes::from(vec![1u8; 16]);
5807 assert!(
5808 tx.validate_static_constraints()
5809 .unwrap_err()
5810 .contains("32 bytes"),
5811 );
5812 }
5813
5814 #[test]
5815 fn static_validation_rejects_zero_explicit_msg() {
5816 let mut tx = make_test_frame_tx();
5817 tx.signatures[0].msg = Bytes::from(vec![0u8; 32]);
5818 assert!(
5819 tx.validate_static_constraints()
5820 .unwrap_err()
5821 .contains("zero digest"),
5822 );
5823 }
5824
5825 #[test]
5826 fn sig_hash_elides_empty_msg_signature_bytes() {
5827 let mut a = make_test_frame_tx();
5828 let mut b = make_test_frame_tx();
5829 assert!(a.signatures[0].msg.is_empty());
5831 a.signatures[0].signature = Bytes::from(vec![1u8; 65]);
5832 b.signatures[0].signature = Bytes::from(vec![2u8; 65]);
5833 assert_eq!(a.compute_sig_hash(), b.compute_sig_hash());
5834 }
5835
5836 #[test]
5837 fn sig_hash_covers_frame_data_now() {
5838 let mut a = make_test_frame_tx();
5839 let mut b = make_test_frame_tx();
5840 a.frames[0].data = Bytes::from_static(b"aaaa");
5842 b.frames[0].data = Bytes::from_static(b"bbbb");
5843 assert_ne!(a.compute_sig_hash(), b.compute_sig_hash());
5844 }
5845
5846 #[test]
5847 fn sig_hash_covers_explicit_msg_signature_bytes() {
5848 let mut a = make_test_frame_tx();
5849 let mut b = make_test_frame_tx();
5850 a.signatures[0].msg = Bytes::from(vec![9u8; 32]);
5851 b.signatures[0].msg = Bytes::from(vec![9u8; 32]);
5852 a.signatures[0].signature = Bytes::from(vec![1u8; 65]);
5853 b.signatures[0].signature = Bytes::from(vec![2u8; 65]);
5854 assert_ne!(a.compute_sig_hash(), b.compute_sig_hash());
5856 }
5857
5858 #[test]
5859 fn max_gas_includes_signature_costs() {
5860 let mut tx = make_test_frame_tx();
5861 let base = tx.max_gas();
5862 tx.signatures.push(FrameSignature {
5864 scheme: FRAME_SIG_SCHEME_P256,
5865 signer: Some(Address::from_low_u64_be(1)),
5866 msg: Bytes::new(),
5867 signature: Bytes::from(vec![0u8; 128]),
5868 });
5869 assert!(tx.max_gas() >= base + 6700);
5870 assert_eq!(tx.signature_verification_cost(), 2800 + 6700);
5871 }
5872
5873 #[test]
5874 fn golden_frame_tx_rlp_and_sig_hash() {
5875 let tx = FrameTransaction {
5880 chain_id: 1,
5881 nonce: 7,
5882 sender: Address::from_low_u64_be(0xABCD),
5883 frames: vec![
5884 Frame {
5885 mode: 1,
5886 flags: 3,
5887 target: None,
5888 gas_limit: 0x5208,
5889 value: U256::zero(),
5890 data: Bytes::from_static(&[0x11, 0x22]),
5891 },
5892 Frame {
5893 mode: 2,
5894 flags: 0,
5895 target: Some(Address::from_low_u64_be(0x1234)),
5896 gas_limit: 0x9c40,
5897 value: U256::zero(),
5898 data: Bytes::new(),
5899 },
5900 ],
5901 signatures: vec![FrameSignature {
5902 scheme: FRAME_SIG_SCHEME_SECP256K1,
5903 signer: Some(Address::from_low_u64_be(0xABCD)),
5904 msg: Bytes::new(),
5905 signature: Bytes::from(vec![0x01u8; 65]),
5906 }],
5907 max_priority_fee_per_gas: 0x3b9aca00,
5908 max_fee_per_gas: 0x6fc23ac00,
5909 max_fee_per_blob_gas: U256::zero(),
5910 blob_versioned_hashes: vec![],
5911 inner_hash: OnceCell::new(),
5912 cached_canonical: OnceCell::new(),
5913 };
5914
5915 let mut buf = Vec::new();
5916 tx.encode(&mut buf);
5917 let rlp_hex = hex::encode(&buf);
5918 assert_eq!(
5920 rlp_hex,
5921 "f8ab010794000000000000000000000000000000000000abcde8ca01038082520880821122dc0280940000000000000000000000000000000000001234829c408080f85cf85a0194000000000000000000000000000000000000abcd80b8410101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101843b9aca008506fc23ac0080c0"
5922 );
5923
5924 let (decoded, rest) = FrameTransaction::decode_unfinished(&buf).unwrap();
5926 assert!(rest.is_empty());
5927 assert_eq!(decoded, tx);
5928
5929 let sig_hash = tx.compute_sig_hash();
5930 assert_eq!(
5932 format!("{:#x}", sig_hash),
5933 "0xe7dc3f33413fc69c09f9c690be154ded294954e497aeea6ce0010ba513f2f26d",
5934 );
5935
5936 let mut tx2 = tx.clone();
5938 tx2.signatures[0].signature = Bytes::from(vec![0x02u8; 65]);
5939 assert_eq!(
5940 tx.compute_sig_hash(),
5941 tx2.compute_sig_hash(),
5942 "sig_hash must be independent of empty-msg signature bytes",
5943 );
5944 }
5945
5946 #[test]
5947 fn test_cost_without_base_fee_eip4844_includes_blob_gas() {
5948 use crate::constants::GAS_PER_BLOB;
5952
5953 let max_fee_per_gas: u64 = 100;
5954 let gas: u64 = 21_000;
5955 let value = U256::from(7u64);
5956 let max_fee_per_blob_gas = U256::from(50u64);
5957 let blob_count: usize = 1;
5958
5959 let tx = Transaction::EIP4844Transaction(EIP4844Transaction {
5960 max_fee_per_gas,
5961 gas,
5962 value,
5963 max_fee_per_blob_gas,
5964 blob_versioned_hashes: vec![H256::zero(); blob_count],
5965 ..Default::default()
5966 });
5967
5968 let got = tx.cost_without_base_fee().expect("cost is computable");
5969
5970 let gas_cost = U256::from(max_fee_per_gas) * U256::from(gas);
5971 let blob_gas = U256::from(GAS_PER_BLOB) * U256::from(blob_count as u64);
5972 let blob_cost = blob_gas * max_fee_per_blob_gas;
5973 let expected = gas_cost + blob_cost + value;
5974
5975 assert_eq!(
5976 got, expected,
5977 "blob-gas term missing from cost_without_base_fee() for EIP-4844"
5978 );
5979 }
5980}