-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
mod.rs
2130 lines (1889 loc) · 86.9 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Transaction types.
use crate::{
eip7702::SignedAuthorization, keccak256, Address, BlockHashOrNumber, Bytes, TxHash, TxKind,
B256, U256,
};
use alloy_consensus::SignableTransaction;
use alloy_primitives::Parity;
use alloy_rlp::{
Decodable, Encodable, Error as RlpError, Header, EMPTY_LIST_CODE, EMPTY_STRING_CODE,
};
use bytes::Buf;
use core::mem;
use derive_more::{AsRef, Deref};
use once_cell::sync::Lazy;
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
use serde::{Deserialize, Serialize};
use signature::{decode_with_eip155_chain_id, with_eip155_parity};
pub use access_list::{AccessList, AccessListItem, AccessListResult};
pub use alloy_consensus::{TxEip1559, TxEip2930, TxEip4844, TxEip7702, TxLegacy};
pub use error::{
InvalidTransactionError, TransactionConversionError, TryFromRecoveredTransactionError,
};
pub use meta::TransactionMeta;
pub use pooled::{PooledTransactionsElement, PooledTransactionsElementEcRecovered};
#[cfg(all(feature = "c-kzg", any(test, feature = "arbitrary")))]
pub use sidecar::generate_blob_sidecar;
#[cfg(feature = "c-kzg")]
pub use sidecar::BlobTransactionValidationError;
pub use sidecar::{BlobTransaction, BlobTransactionSidecar};
pub use compat::FillTxEnv;
pub use signature::{
extract_chain_id, legacy_parity, recover_signer, recover_signer_unchecked, Signature,
};
pub use tx_type::{
TxType, EIP1559_TX_TYPE_ID, EIP2930_TX_TYPE_ID, EIP4844_TX_TYPE_ID, EIP7702_TX_TYPE_ID,
LEGACY_TX_TYPE_ID,
};
pub use variant::TransactionSignedVariant;
pub(crate) mod access_list;
mod compat;
mod error;
mod meta;
mod pooled;
mod sidecar;
mod signature;
mod tx_type;
pub(crate) mod util;
mod variant;
#[cfg(feature = "optimism")]
pub use op_alloy_consensus::TxDeposit;
#[cfg(feature = "optimism")]
pub use reth_optimism_chainspec::optimism_deposit_tx_signature;
#[cfg(feature = "optimism")]
pub use tx_type::DEPOSIT_TX_TYPE_ID;
#[cfg(any(test, feature = "reth-codec"))]
use tx_type::{
COMPACT_EXTENDED_IDENTIFIER_FLAG, COMPACT_IDENTIFIER_EIP1559, COMPACT_IDENTIFIER_EIP2930,
COMPACT_IDENTIFIER_LEGACY,
};
#[cfg(test)]
use reth_codecs::Compact;
use alloc::vec::Vec;
/// Either a transaction hash or number.
pub type TxHashOrNumber = BlockHashOrNumber;
// Expected number of transactions where we can expect a speed-up by recovering the senders in
// parallel.
pub(crate) static PARALLEL_SENDER_RECOVERY_THRESHOLD: Lazy<usize> =
Lazy::new(|| match rayon::current_num_threads() {
0..=1 => usize::MAX,
2..=8 => 10,
_ => 5,
});
/// A raw transaction.
///
/// Transaction types were introduced in [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, derive_more::From)]
#[cfg_attr(any(test, feature = "reth-codec"), reth_codecs::add_arbitrary_tests(compact))]
pub enum Transaction {
/// Legacy transaction (type `0x0`).
///
/// Traditional Ethereum transactions, containing parameters `nonce`, `gasPrice`, `gasLimit`,
/// `to`, `value`, `data`, `v`, `r`, and `s`.
///
/// These transactions do not utilize access lists nor do they incorporate EIP-1559 fee market
/// changes.
Legacy(TxLegacy),
/// Transaction with an [`AccessList`] ([EIP-2930](https://eips.ethereum.org/EIPS/eip-2930)), type `0x1`.
///
/// The `accessList` specifies an array of addresses and storage keys that the transaction
/// plans to access, enabling gas savings on cross-contract calls by pre-declaring the accessed
/// contract and storage slots.
Eip2930(TxEip2930),
/// A transaction with a priority fee ([EIP-1559](https://eips.ethereum.org/EIPS/eip-1559)), type `0x2`.
///
/// Unlike traditional transactions, EIP-1559 transactions use an in-protocol, dynamically
/// changing base fee per gas, adjusted at each block to manage network congestion.
///
/// - `maxPriorityFeePerGas`, specifying the maximum fee above the base fee the sender is
/// willing to pay
/// - `maxFeePerGas`, setting the maximum total fee the sender is willing to pay.
///
/// The base fee is burned, while the priority fee is paid to the miner who includes the
/// transaction, incentivizing miners to include transactions with higher priority fees per
/// gas.
Eip1559(TxEip1559),
/// Shard Blob Transactions ([EIP-4844](https://eips.ethereum.org/EIPS/eip-4844)), type `0x3`.
///
/// Shard Blob Transactions introduce a new transaction type called a blob-carrying transaction
/// to reduce gas costs. These transactions are similar to regular Ethereum transactions but
/// include additional data called a blob.
///
/// Blobs are larger (~125 kB) and cheaper than the current calldata, providing an immutable
/// and read-only memory for storing transaction data.
///
/// EIP-4844, also known as proto-danksharding, implements the framework and logic of
/// danksharding, introducing new transaction formats and verification rules.
Eip4844(TxEip4844),
/// EOA Set Code Transactions ([EIP-7702](https://eips.ethereum.org/EIPS/eip-7702)), type `0x4`.
///
/// EOA Set Code Transactions give the ability to temporarily set contract code for an
/// EOA for a single transaction. This allows for temporarily adding smart contract
/// functionality to the EOA.
Eip7702(TxEip7702),
/// Optimism deposit transaction.
#[cfg(feature = "optimism")]
Deposit(TxDeposit),
}
#[cfg(any(test, feature = "arbitrary"))]
impl<'a> arbitrary::Arbitrary<'a> for Transaction {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let mut tx = match TxType::arbitrary(u)? {
TxType::Legacy => {
let mut tx = TxLegacy::arbitrary(u)?;
tx.gas_limit = (tx.gas_limit as u64).into();
Self::Legacy(tx)
}
TxType::Eip2930 => {
let mut tx = TxEip2930::arbitrary(u)?;
tx.gas_limit = (tx.gas_limit as u64).into();
Self::Eip2930(tx)
}
TxType::Eip1559 => {
let mut tx = TxEip1559::arbitrary(u)?;
tx.gas_limit = (tx.gas_limit as u64).into();
Self::Eip1559(tx)
}
TxType::Eip4844 => {
let mut tx = TxEip4844::arbitrary(u)?;
tx.gas_limit = (tx.gas_limit as u64).into();
Self::Eip4844(tx)
}
TxType::Eip7702 => {
let mut tx = TxEip7702::arbitrary(u)?;
tx.gas_limit = (tx.gas_limit as u64).into();
Self::Eip7702(tx)
}
#[cfg(feature = "optimism")]
TxType::Deposit => {
let mut tx = TxDeposit::arbitrary(u)?;
tx.gas_limit = (tx.gas_limit as u64).into();
Self::Deposit(tx)
}
};
// Otherwise we might overflow when calculating `v` on `recalculate_hash`
if let Some(chain_id) = tx.chain_id() {
tx.set_chain_id(chain_id % (u64::MAX / 2 - 36));
}
Ok(tx)
}
}
// === impl Transaction ===
impl Transaction {
/// Heavy operation that return signature hash over rlp encoded transaction.
/// It is only for signature signing or signer recovery.
pub fn signature_hash(&self) -> B256 {
match self {
Self::Legacy(tx) => tx.signature_hash(),
Self::Eip2930(tx) => tx.signature_hash(),
Self::Eip1559(tx) => tx.signature_hash(),
Self::Eip4844(tx) => tx.signature_hash(),
Self::Eip7702(tx) => tx.signature_hash(),
#[cfg(feature = "optimism")]
Self::Deposit(_) => B256::ZERO,
}
}
/// Get `chain_id`.
pub const fn chain_id(&self) -> Option<u64> {
match self {
Self::Legacy(TxLegacy { chain_id, .. }) => *chain_id,
Self::Eip2930(TxEip2930 { chain_id, .. }) |
Self::Eip1559(TxEip1559 { chain_id, .. }) |
Self::Eip4844(TxEip4844 { chain_id, .. }) |
Self::Eip7702(TxEip7702 { chain_id, .. }) => Some(*chain_id),
#[cfg(feature = "optimism")]
Self::Deposit(_) => None,
}
}
/// Sets the transaction's chain id to the provided value.
pub fn set_chain_id(&mut self, chain_id: u64) {
match self {
Self::Legacy(TxLegacy { chain_id: ref mut c, .. }) => *c = Some(chain_id),
Self::Eip2930(TxEip2930 { chain_id: ref mut c, .. }) |
Self::Eip1559(TxEip1559 { chain_id: ref mut c, .. }) |
Self::Eip4844(TxEip4844 { chain_id: ref mut c, .. }) |
Self::Eip7702(TxEip7702 { chain_id: ref mut c, .. }) => *c = chain_id,
#[cfg(feature = "optimism")]
Self::Deposit(_) => { /* noop */ }
}
}
/// Gets the transaction's [`TxKind`], which is the address of the recipient or
/// [`TxKind::Create`] if the transaction is a contract creation.
pub const fn kind(&self) -> TxKind {
match self {
Self::Legacy(TxLegacy { to, .. }) |
Self::Eip2930(TxEip2930 { to, .. }) |
Self::Eip1559(TxEip1559 { to, .. }) => *to,
Self::Eip4844(TxEip4844 { to, .. }) | Self::Eip7702(TxEip7702 { to, .. }) => {
TxKind::Call(*to)
}
#[cfg(feature = "optimism")]
Self::Deposit(TxDeposit { to, .. }) => *to,
}
}
/// Get the transaction's address of the contract that will be called, or the address that will
/// receive the transfer.
///
/// Returns `None` if this is a `CREATE` transaction.
pub fn to(&self) -> Option<Address> {
self.kind().to().copied()
}
/// Get the transaction's type
pub const fn tx_type(&self) -> TxType {
match self {
Self::Legacy(_) => TxType::Legacy,
Self::Eip2930(_) => TxType::Eip2930,
Self::Eip1559(_) => TxType::Eip1559,
Self::Eip4844(_) => TxType::Eip4844,
Self::Eip7702(_) => TxType::Eip7702,
#[cfg(feature = "optimism")]
Self::Deposit(_) => TxType::Deposit,
}
}
/// Gets the transaction's value field.
pub const fn value(&self) -> U256 {
*match self {
Self::Legacy(TxLegacy { value, .. }) |
Self::Eip2930(TxEip2930 { value, .. }) |
Self::Eip1559(TxEip1559 { value, .. }) |
Self::Eip4844(TxEip4844 { value, .. }) |
Self::Eip7702(TxEip7702 { value, .. }) => value,
#[cfg(feature = "optimism")]
Self::Deposit(TxDeposit { value, .. }) => value,
}
}
/// Get the transaction's nonce.
pub const fn nonce(&self) -> u64 {
match self {
Self::Legacy(TxLegacy { nonce, .. }) |
Self::Eip2930(TxEip2930 { nonce, .. }) |
Self::Eip1559(TxEip1559 { nonce, .. }) |
Self::Eip4844(TxEip4844 { nonce, .. }) |
Self::Eip7702(TxEip7702 { nonce, .. }) => *nonce,
// Deposit transactions do not have nonces.
#[cfg(feature = "optimism")]
Self::Deposit(_) => 0,
}
}
/// Returns the [`AccessList`] of the transaction.
///
/// Returns `None` for legacy transactions.
pub const fn access_list(&self) -> Option<&AccessList> {
match self {
Self::Legacy(_) => None,
Self::Eip2930(tx) => Some(&tx.access_list),
Self::Eip1559(tx) => Some(&tx.access_list),
Self::Eip4844(tx) => Some(&tx.access_list),
Self::Eip7702(tx) => Some(&tx.access_list),
#[cfg(feature = "optimism")]
Self::Deposit(_) => None,
}
}
/// Returns the [`SignedAuthorization`] list of the transaction.
///
/// Returns `None` if this transaction is not EIP-7702.
pub fn authorization_list(&self) -> Option<&[SignedAuthorization]> {
match self {
Self::Eip7702(tx) => Some(&tx.authorization_list),
_ => None,
}
}
/// Get the gas limit of the transaction.
pub const fn gas_limit(&self) -> u64 {
match self {
Self::Legacy(TxLegacy { gas_limit, .. }) |
Self::Eip1559(TxEip1559 { gas_limit, .. }) |
Self::Eip4844(TxEip4844 { gas_limit, .. }) |
Self::Eip7702(TxEip7702 { gas_limit, .. }) |
Self::Eip2930(TxEip2930 { gas_limit, .. }) => *gas_limit as u64,
#[cfg(feature = "optimism")]
Self::Deposit(TxDeposit { gas_limit, .. }) => *gas_limit as u64,
}
}
/// Returns true if the tx supports dynamic fees
pub const fn is_dynamic_fee(&self) -> bool {
match self {
Self::Legacy(_) | Self::Eip2930(_) => false,
Self::Eip1559(_) | Self::Eip4844(_) | Self::Eip7702(_) => true,
#[cfg(feature = "optimism")]
Self::Deposit(_) => false,
}
}
/// Max fee per gas for eip1559 transaction, for legacy transactions this is `gas_price`.
///
/// This is also commonly referred to as the "Gas Fee Cap" (`GasFeeCap`).
pub const fn max_fee_per_gas(&self) -> u128 {
match self {
Self::Legacy(TxLegacy { gas_price, .. }) |
Self::Eip2930(TxEip2930 { gas_price, .. }) => *gas_price,
Self::Eip1559(TxEip1559 { max_fee_per_gas, .. }) |
Self::Eip4844(TxEip4844 { max_fee_per_gas, .. }) |
Self::Eip7702(TxEip7702 { max_fee_per_gas, .. }) => *max_fee_per_gas,
// Deposit transactions buy their L2 gas on L1 and, as such, the L2 gas is not
// refundable.
#[cfg(feature = "optimism")]
Self::Deposit(_) => 0,
}
}
/// Max priority fee per gas for eip1559 transaction, for legacy and eip2930 transactions this
/// is `None`
///
/// This is also commonly referred to as the "Gas Tip Cap" (`GasTipCap`).
pub const fn max_priority_fee_per_gas(&self) -> Option<u128> {
match self {
Self::Legacy(_) | Self::Eip2930(_) => None,
Self::Eip1559(TxEip1559 { max_priority_fee_per_gas, .. }) |
Self::Eip4844(TxEip4844 { max_priority_fee_per_gas, .. }) |
Self::Eip7702(TxEip7702 { max_priority_fee_per_gas, .. }) => {
Some(*max_priority_fee_per_gas)
}
#[cfg(feature = "optimism")]
Self::Deposit(_) => None,
}
}
/// Blob versioned hashes for eip4844 transaction, for legacy, eip1559, eip2930 and eip7702
/// transactions this is `None`
///
/// This is also commonly referred to as the "blob versioned hashes" (`BlobVersionedHashes`).
pub fn blob_versioned_hashes(&self) -> Option<Vec<B256>> {
match self {
Self::Legacy(_) | Self::Eip2930(_) | Self::Eip1559(_) | Self::Eip7702(_) => None,
Self::Eip4844(TxEip4844 { blob_versioned_hashes, .. }) => {
Some(blob_versioned_hashes.clone())
}
#[cfg(feature = "optimism")]
Self::Deposit(_) => None,
}
}
/// Max fee per blob gas for eip4844 transaction [`TxEip4844`].
///
/// Returns `None` for non-eip4844 transactions.
///
/// This is also commonly referred to as the "Blob Gas Fee Cap" (`BlobGasFeeCap`).
pub const fn max_fee_per_blob_gas(&self) -> Option<u128> {
match self {
Self::Eip4844(TxEip4844 { max_fee_per_blob_gas, .. }) => Some(*max_fee_per_blob_gas),
_ => None,
}
}
/// Returns the blob gas used for all blobs of the EIP-4844 transaction if it is an EIP-4844
/// transaction.
///
/// This is the number of blobs times the
/// [`DATA_GAS_PER_BLOB`](crate::constants::eip4844::DATA_GAS_PER_BLOB) a single blob consumes.
pub fn blob_gas_used(&self) -> Option<u64> {
self.as_eip4844().map(TxEip4844::blob_gas)
}
/// Return the max priority fee per gas if the transaction is an EIP-1559 transaction, and
/// otherwise return the gas price.
///
/// # Warning
///
/// This is different than the `max_priority_fee_per_gas` method, which returns `None` for
/// non-EIP-1559 transactions.
pub const fn priority_fee_or_price(&self) -> u128 {
match self {
Self::Legacy(TxLegacy { gas_price, .. }) |
Self::Eip2930(TxEip2930 { gas_price, .. }) => *gas_price,
Self::Eip1559(TxEip1559 { max_priority_fee_per_gas, .. }) |
Self::Eip4844(TxEip4844 { max_priority_fee_per_gas, .. }) |
Self::Eip7702(TxEip7702 { max_priority_fee_per_gas, .. }) => *max_priority_fee_per_gas,
#[cfg(feature = "optimism")]
Self::Deposit(_) => 0,
}
}
/// Returns the effective gas price for the given base fee.
///
/// If the transaction is a legacy or EIP2930 transaction, the gas price is returned.
pub const fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
match self {
Self::Legacy(tx) => tx.gas_price,
Self::Eip2930(tx) => tx.gas_price,
Self::Eip1559(dynamic_tx) => dynamic_tx.effective_gas_price(base_fee),
Self::Eip4844(dynamic_tx) => dynamic_tx.effective_gas_price(base_fee),
Self::Eip7702(dynamic_tx) => dynamic_tx.effective_gas_price(base_fee),
#[cfg(feature = "optimism")]
Self::Deposit(_) => 0,
}
}
/// Returns the effective miner gas tip cap (`gasTipCap`) for the given base fee:
/// `min(maxFeePerGas - baseFee, maxPriorityFeePerGas)`
///
/// If the base fee is `None`, the `max_priority_fee_per_gas`, or gas price for non-EIP1559
/// transactions is returned.
///
/// Returns `None` if the basefee is higher than the [`Transaction::max_fee_per_gas`].
pub fn effective_tip_per_gas(&self, base_fee: Option<u64>) -> Option<u128> {
let base_fee = match base_fee {
Some(base_fee) => base_fee as u128,
None => return Some(self.priority_fee_or_price()),
};
let max_fee_per_gas = self.max_fee_per_gas();
// Check if max_fee_per_gas is less than base_fee
if max_fee_per_gas < base_fee {
return None
}
// Calculate the difference between max_fee_per_gas and base_fee
let fee = max_fee_per_gas - base_fee;
// Compare the fee with max_priority_fee_per_gas (or gas price for non-EIP1559 transactions)
if let Some(priority_fee) = self.max_priority_fee_per_gas() {
Some(fee.min(priority_fee))
} else {
Some(fee)
}
}
/// Get the transaction's input field.
pub const fn input(&self) -> &Bytes {
match self {
Self::Legacy(TxLegacy { input, .. }) |
Self::Eip2930(TxEip2930 { input, .. }) |
Self::Eip1559(TxEip1559 { input, .. }) |
Self::Eip4844(TxEip4844 { input, .. }) |
Self::Eip7702(TxEip7702 { input, .. }) => input,
#[cfg(feature = "optimism")]
Self::Deposit(TxDeposit { input, .. }) => input,
}
}
/// Returns the source hash of the transaction, which uniquely identifies its source.
/// If not a deposit transaction, this will always return `None`.
#[cfg(feature = "optimism")]
pub const fn source_hash(&self) -> Option<B256> {
match self {
Self::Deposit(TxDeposit { source_hash, .. }) => Some(*source_hash),
_ => None,
}
}
/// Returns the amount of ETH locked up on L1 that will be minted on L2. If the transaction
/// is not a deposit transaction, this will always return `None`.
#[cfg(feature = "optimism")]
pub const fn mint(&self) -> Option<u128> {
match self {
Self::Deposit(TxDeposit { mint, .. }) => *mint,
_ => None,
}
}
/// Returns whether or not the transaction is a system transaction. If the transaction
/// is not a deposit transaction, this will always return `false`.
#[cfg(feature = "optimism")]
pub const fn is_system_transaction(&self) -> bool {
match self {
Self::Deposit(TxDeposit { is_system_transaction, .. }) => *is_system_transaction,
_ => false,
}
}
/// Returns whether or not the transaction is an Optimism Deposited transaction.
#[cfg(feature = "optimism")]
pub const fn is_deposit(&self) -> bool {
matches!(self, Self::Deposit(_))
}
/// This encodes the transaction _without_ the signature, and is only suitable for creating a
/// hash intended for signing.
pub fn encode_without_signature(&self, out: &mut dyn bytes::BufMut) {
Encodable::encode(self, out);
}
/// Inner encoding function that is used for both rlp [`Encodable`] trait and for calculating
/// hash that for eip2718 does not require rlp header
pub fn encode_with_signature(
&self,
signature: &Signature,
out: &mut dyn bytes::BufMut,
with_header: bool,
) {
match self {
Self::Legacy(legacy_tx) => {
// do nothing w/ with_header
legacy_tx.encode_with_signature_fields(
&with_eip155_parity(signature, legacy_tx.chain_id),
out,
)
}
Self::Eip2930(access_list_tx) => {
access_list_tx.encode_with_signature(signature, out, with_header)
}
Self::Eip1559(dynamic_fee_tx) => {
dynamic_fee_tx.encode_with_signature(signature, out, with_header)
}
Self::Eip4844(blob_tx) => blob_tx.encode_with_signature(signature, out, with_header),
Self::Eip7702(set_code_tx) => {
set_code_tx.encode_with_signature(signature, out, with_header)
}
#[cfg(feature = "optimism")]
Self::Deposit(deposit_tx) => deposit_tx.encode_inner(out, with_header),
}
}
/// This sets the transaction's gas limit.
pub fn set_gas_limit(&mut self, gas_limit: u64) {
match self {
Self::Legacy(tx) => tx.gas_limit = gas_limit.into(),
Self::Eip2930(tx) => tx.gas_limit = gas_limit.into(),
Self::Eip1559(tx) => tx.gas_limit = gas_limit.into(),
Self::Eip4844(tx) => tx.gas_limit = gas_limit.into(),
Self::Eip7702(tx) => tx.gas_limit = gas_limit.into(),
#[cfg(feature = "optimism")]
Self::Deposit(tx) => tx.gas_limit = gas_limit.into(),
}
}
/// This sets the transaction's nonce.
pub fn set_nonce(&mut self, nonce: u64) {
match self {
Self::Legacy(tx) => tx.nonce = nonce,
Self::Eip2930(tx) => tx.nonce = nonce,
Self::Eip1559(tx) => tx.nonce = nonce,
Self::Eip4844(tx) => tx.nonce = nonce,
Self::Eip7702(tx) => tx.nonce = nonce,
#[cfg(feature = "optimism")]
Self::Deposit(_) => { /* noop */ }
}
}
/// This sets the transaction's value.
pub fn set_value(&mut self, value: U256) {
match self {
Self::Legacy(tx) => tx.value = value,
Self::Eip2930(tx) => tx.value = value,
Self::Eip1559(tx) => tx.value = value,
Self::Eip4844(tx) => tx.value = value,
Self::Eip7702(tx) => tx.value = value,
#[cfg(feature = "optimism")]
Self::Deposit(tx) => tx.value = value,
}
}
/// This sets the transaction's input field.
pub fn set_input(&mut self, input: Bytes) {
match self {
Self::Legacy(tx) => tx.input = input,
Self::Eip2930(tx) => tx.input = input,
Self::Eip1559(tx) => tx.input = input,
Self::Eip4844(tx) => tx.input = input,
Self::Eip7702(tx) => tx.input = input,
#[cfg(feature = "optimism")]
Self::Deposit(tx) => tx.input = input,
}
}
/// Calculates a heuristic for the in-memory size of the [Transaction].
#[inline]
pub fn size(&self) -> usize {
match self {
Self::Legacy(tx) => tx.size(),
Self::Eip2930(tx) => tx.size(),
Self::Eip1559(tx) => tx.size(),
Self::Eip4844(tx) => tx.size(),
Self::Eip7702(tx) => tx.size(),
#[cfg(feature = "optimism")]
Self::Deposit(tx) => tx.size(),
}
}
/// Returns true if the transaction is a legacy transaction.
#[inline]
pub const fn is_legacy(&self) -> bool {
matches!(self, Self::Legacy(_))
}
/// Returns true if the transaction is an EIP-2930 transaction.
#[inline]
pub const fn is_eip2930(&self) -> bool {
matches!(self, Self::Eip2930(_))
}
/// Returns true if the transaction is an EIP-1559 transaction.
#[inline]
pub const fn is_eip1559(&self) -> bool {
matches!(self, Self::Eip1559(_))
}
/// Returns true if the transaction is an EIP-4844 transaction.
#[inline]
pub const fn is_eip4844(&self) -> bool {
matches!(self, Self::Eip4844(_))
}
/// Returns true if the transaction is an EIP-7702 transaction.
#[inline]
pub const fn is_eip7702(&self) -> bool {
matches!(self, Self::Eip7702(_))
}
/// Returns the [`TxLegacy`] variant if the transaction is a legacy transaction.
pub const fn as_legacy(&self) -> Option<&TxLegacy> {
match self {
Self::Legacy(tx) => Some(tx),
_ => None,
}
}
/// Returns the [`TxEip2930`] variant if the transaction is an EIP-2930 transaction.
pub const fn as_eip2930(&self) -> Option<&TxEip2930> {
match self {
Self::Eip2930(tx) => Some(tx),
_ => None,
}
}
/// Returns the [`TxEip1559`] variant if the transaction is an EIP-1559 transaction.
pub const fn as_eip1559(&self) -> Option<&TxEip1559> {
match self {
Self::Eip1559(tx) => Some(tx),
_ => None,
}
}
/// Returns the [`TxEip4844`] variant if the transaction is an EIP-4844 transaction.
pub const fn as_eip4844(&self) -> Option<&TxEip4844> {
match self {
Self::Eip4844(tx) => Some(tx),
_ => None,
}
}
/// Returns the [`TxEip7702`] variant if the transaction is an EIP-7702 transaction.
pub const fn as_eip7702(&self) -> Option<&TxEip7702> {
match self {
Self::Eip7702(tx) => Some(tx),
_ => None,
}
}
}
#[cfg(any(test, feature = "reth-codec"))]
impl reth_codecs::Compact for Transaction {
// Serializes the TxType to the buffer if necessary, returning 2 bits of the type as an
// identifier instead of the length.
fn to_compact<B>(&self, buf: &mut B) -> usize
where
B: bytes::BufMut + AsMut<[u8]>,
{
let identifier = self.tx_type().to_compact(buf);
match self {
Self::Legacy(tx) => {
tx.to_compact(buf);
}
Self::Eip2930(tx) => {
tx.to_compact(buf);
}
Self::Eip1559(tx) => {
tx.to_compact(buf);
}
Self::Eip4844(tx) => {
tx.to_compact(buf);
}
Self::Eip7702(tx) => {
tx.to_compact(buf);
}
#[cfg(feature = "optimism")]
Self::Deposit(tx) => {
tx.to_compact(buf);
}
}
identifier
}
// For backwards compatibility purposes, only 2 bits of the type are encoded in the identifier
// parameter. In the case of a [`COMPACT_EXTENDED_IDENTIFIER_FLAG`], the full transaction type
// is read from the buffer as a single byte.
//
// # Panics
//
// A panic will be triggered if an identifier larger than 3 is passed from the database. For
// optimism a identifier with value [`DEPOSIT_TX_TYPE_ID`] is allowed.
fn from_compact(mut buf: &[u8], identifier: usize) -> (Self, &[u8]) {
match identifier {
COMPACT_IDENTIFIER_LEGACY => {
let (tx, buf) = TxLegacy::from_compact(buf, buf.len());
(Self::Legacy(tx), buf)
}
COMPACT_IDENTIFIER_EIP2930 => {
let (tx, buf) = TxEip2930::from_compact(buf, buf.len());
(Self::Eip2930(tx), buf)
}
COMPACT_IDENTIFIER_EIP1559 => {
let (tx, buf) = TxEip1559::from_compact(buf, buf.len());
(Self::Eip1559(tx), buf)
}
COMPACT_EXTENDED_IDENTIFIER_FLAG => {
// An identifier of 3 indicates that the transaction type did not fit into
// the backwards compatible 2 bit identifier, their transaction types are
// larger than 2 bits (eg. 4844 and Deposit Transactions). In this case,
// we need to read the concrete transaction type from the buffer by
// reading the full 8 bits (single byte) and match on this transaction type.
let identifier = buf.get_u8();
match identifier {
EIP4844_TX_TYPE_ID => {
let (tx, buf) = TxEip4844::from_compact(buf, buf.len());
(Self::Eip4844(tx), buf)
}
EIP7702_TX_TYPE_ID => {
let (tx, buf) = TxEip7702::from_compact(buf, buf.len());
(Self::Eip7702(tx), buf)
}
#[cfg(feature = "optimism")]
DEPOSIT_TX_TYPE_ID => {
let (tx, buf) = TxDeposit::from_compact(buf, buf.len());
(Self::Deposit(tx), buf)
}
_ => unreachable!("Junk data in database: unknown Transaction variant"),
}
}
_ => unreachable!("Junk data in database: unknown Transaction variant"),
}
}
}
impl Default for Transaction {
fn default() -> Self {
Self::Legacy(TxLegacy::default())
}
}
impl Encodable for Transaction {
/// This encodes the transaction _without_ the signature, and is only suitable for creating a
/// hash intended for signing.
fn encode(&self, out: &mut dyn bytes::BufMut) {
match self {
Self::Legacy(legacy_tx) => {
legacy_tx.encode_for_signing(out);
}
Self::Eip2930(access_list_tx) => {
access_list_tx.encode_for_signing(out);
}
Self::Eip1559(dynamic_fee_tx) => {
dynamic_fee_tx.encode_for_signing(out);
}
Self::Eip4844(blob_tx) => {
blob_tx.encode_for_signing(out);
}
Self::Eip7702(set_code_tx) => {
set_code_tx.encode_for_signing(out);
}
#[cfg(feature = "optimism")]
Self::Deposit(deposit_tx) => {
deposit_tx.encode_inner(out, true);
}
}
}
fn length(&self) -> usize {
match self {
Self::Legacy(legacy_tx) => legacy_tx.payload_len_for_signature(),
Self::Eip2930(access_list_tx) => access_list_tx.payload_len_for_signature(),
Self::Eip1559(dynamic_fee_tx) => dynamic_fee_tx.payload_len_for_signature(),
Self::Eip4844(blob_tx) => blob_tx.payload_len_for_signature(),
Self::Eip7702(set_code_tx) => set_code_tx.payload_len_for_signature(),
#[cfg(feature = "optimism")]
Self::Deposit(deposit_tx) => deposit_tx.encoded_len(true),
}
}
}
/// Signed transaction without its Hash. Used type for inserting into the DB.
///
/// This can by converted to [`TransactionSigned`] by calling [`TransactionSignedNoHash::hash`].
#[derive(Debug, Clone, PartialEq, Eq, Hash, AsRef, Deref, Serialize, Deserialize)]
#[cfg_attr(any(test, feature = "reth-codec"), reth_codecs::add_arbitrary_tests(compact))]
pub struct TransactionSignedNoHash {
/// The transaction signature values
pub signature: Signature,
/// Raw transaction info
#[deref]
#[as_ref]
pub transaction: Transaction,
}
impl TransactionSignedNoHash {
/// Calculates the transaction hash. If used more than once, it's better to convert it to
/// [`TransactionSigned`] first.
pub fn hash(&self) -> B256 {
// pre-allocate buffer for the transaction
let mut buf = Vec::with_capacity(128 + self.transaction.input().len());
self.transaction.encode_with_signature(&self.signature, &mut buf, false);
keccak256(&buf)
}
/// Recover signer from signature and hash.
///
/// Returns `None` if the transaction's signature is invalid, see also [`Self::recover_signer`].
pub fn recover_signer(&self) -> Option<Address> {
// Optimism's Deposit transaction does not have a signature. Directly return the
// `from` address.
#[cfg(feature = "optimism")]
if let Transaction::Deposit(TxDeposit { from, .. }) = self.transaction {
return Some(from)
}
let signature_hash = self.signature_hash();
recover_signer(&self.signature, signature_hash)
}
/// Recover signer from signature and hash _without ensuring that the signature has a low `s`
/// value_.
///
/// Re-uses a given buffer to avoid numerous reallocations when recovering batches. **Clears the
/// buffer before use.**
///
/// Returns `None` if the transaction's signature is invalid, see also
/// [`recover_signer_unchecked`].
///
/// # Optimism
///
/// For optimism this will return [`Address::ZERO`] if the Signature is empty, this is because pre bedrock (on OP mainnet), relay messages to the L2 Cross Domain Messenger were sent as legacy transactions from the zero address with an empty signature, e.g.: <https://optimistic.etherscan.io/tx/0x1bb352ff9215efe5a4c102f45d730bae323c3288d2636672eb61543ddd47abad>
/// This makes it possible to import pre bedrock transactions via the sender recovery stage.
pub fn encode_and_recover_unchecked(&self, buffer: &mut Vec<u8>) -> Option<Address> {
buffer.clear();
self.transaction.encode_without_signature(buffer);
// Optimism's Deposit transaction does not have a signature. Directly return the
// `from` address.
#[cfg(feature = "optimism")]
{
if let Transaction::Deposit(TxDeposit { from, .. }) = self.transaction {
return Some(from)
}
// pre bedrock system transactions were sent from the zero address as legacy
// transactions with an empty signature
//
// NOTE: this is very hacky and only relevant for op-mainnet pre bedrock
if self.is_legacy() && self.signature == optimism_deposit_tx_signature() {
return Some(Address::ZERO)
}
}
recover_signer_unchecked(&self.signature, keccak256(buffer))
}
/// Converts into a transaction type with its hash: [`TransactionSigned`].
///
/// Note: This will recalculate the hash of the transaction.
#[inline]
pub fn with_hash(self) -> TransactionSigned {
let Self { signature, transaction } = self;
TransactionSigned::from_transaction_and_signature(transaction, signature)
}
/// Recovers a list of signers from a transaction list iterator
///
/// Returns `None`, if some transaction's signature is invalid, see also
/// [`Self::recover_signer`].
pub fn recover_signers<'a, T>(txes: T, num_txes: usize) -> Option<Vec<Address>>
where
T: IntoParallelIterator<Item = &'a Self> + IntoIterator<Item = &'a Self> + Send,
{
if num_txes < *PARALLEL_SENDER_RECOVERY_THRESHOLD {
txes.into_iter().map(|tx| tx.recover_signer()).collect()
} else {
txes.into_par_iter().map(|tx| tx.recover_signer()).collect()
}
}
}
impl Default for TransactionSignedNoHash {
fn default() -> Self {
Self { signature: Signature::test_signature(), transaction: Default::default() }
}
}
#[cfg(any(test, feature = "arbitrary"))]
impl<'a> arbitrary::Arbitrary<'a> for TransactionSignedNoHash {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let tx_signed = TransactionSigned::arbitrary(u)?;
Ok(Self { signature: tx_signed.signature, transaction: tx_signed.transaction })
}
}
#[cfg(any(test, feature = "reth-codec"))]
impl reth_codecs::Compact for TransactionSignedNoHash {
fn to_compact<B>(&self, buf: &mut B) -> usize
where
B: bytes::BufMut + AsMut<[u8]>,
{
let start = buf.as_mut().len();
// Placeholder for bitflags.
// The first byte uses 4 bits as flags: IsCompressed[1bit], TxType[2bits], Signature[1bit]
buf.put_u8(0);
let sig_bit = self.signature.to_compact(buf) as u8;
let zstd_bit = self.transaction.input().len() >= 32;
let tx_bits = if zstd_bit {
crate::compression::TRANSACTION_COMPRESSOR.with(|compressor| {
let mut compressor = compressor.borrow_mut();
let mut tmp = Vec::with_capacity(256);
let tx_bits = self.transaction.to_compact(&mut tmp);
buf.put_slice(&compressor.compress(&tmp).expect("Failed to compress"));
tx_bits as u8
})
} else {
self.transaction.to_compact(buf) as u8
};
// Replace bitflags with the actual values
buf.as_mut()[start] = sig_bit | (tx_bits << 1) | ((zstd_bit as u8) << 3);
buf.as_mut().len() - start
}
fn from_compact(mut buf: &[u8], _len: usize) -> (Self, &[u8]) {
// The first byte uses 4 bits as flags: IsCompressed[1], TxType[2], Signature[1]
let bitflags = buf.get_u8() as usize;
let sig_bit = bitflags & 1;
let (mut signature, buf) = Signature::from_compact(buf, sig_bit);
let zstd_bit = bitflags >> 3;
let (transaction, buf) = if zstd_bit != 0 {
crate::compression::TRANSACTION_DECOMPRESSOR.with(|decompressor| {
let mut decompressor = decompressor.borrow_mut();
// TODO: enforce that zstd is only present at a "top" level type
let transaction_type = (bitflags & 0b110) >> 1;
let (transaction, _) =
Transaction::from_compact(decompressor.decompress(buf), transaction_type);
(transaction, buf)