-
Notifications
You must be signed in to change notification settings - Fork 891
/
mod.rs
1453 lines (1284 loc) · 56.5 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
use crate::{
compression::{TRANSACTION_COMPRESSOR, TRANSACTION_DECOMPRESSOR},
keccak256, Address, Bytes, TxHash, H256,
};
pub use access_list::{AccessList, AccessListItem, AccessListWithGasUsed};
use bytes::{Buf, BytesMut};
use derive_more::{AsRef, Deref};
pub use error::InvalidTransactionError;
pub use meta::TransactionMeta;
use once_cell::sync::Lazy;
use rayon::prelude::{IntoParallelIterator, ParallelIterator};
use reth_codecs::{add_arbitrary_tests, derive_arbitrary, Compact};
use reth_rlp::{Decodable, DecodeError, Encodable, Header, EMPTY_LIST_CODE, EMPTY_STRING_CODE};
use serde::{Deserialize, Serialize};
pub use signature::Signature;
use std::mem;
pub use tx_type::{
TxType, EIP1559_TX_TYPE_ID, EIP2930_TX_TYPE_ID, EIP4844_TX_TYPE_ID, LEGACY_TX_TYPE_ID,
};
pub use eip1559::TxEip1559;
pub use eip2930::TxEip2930;
pub use eip4844::{
BlobTransaction, BlobTransactionSidecar, BlobTransactionValidationError, TxEip4844,
};
pub use legacy::TxLegacy;
pub use pooled::{PooledTransactionsElement, PooledTransactionsElementEcRecovered};
mod access_list;
mod eip1559;
mod eip2930;
mod eip4844;
mod error;
mod legacy;
mod meta;
mod pooled;
mod signature;
mod tx_type;
pub(crate) mod util;
// 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_arbitrary(compact)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
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),
}
// === 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) -> H256 {
match self {
Transaction::Legacy(tx) => tx.signature_hash(),
Transaction::Eip2930(tx) => tx.signature_hash(),
Transaction::Eip1559(tx) => tx.signature_hash(),
Transaction::Eip4844(tx) => tx.signature_hash(),
}
}
/// Get chain_id.
pub fn chain_id(&self) -> Option<u64> {
match self {
Transaction::Legacy(TxLegacy { chain_id, .. }) => *chain_id,
Transaction::Eip2930(TxEip2930 { chain_id, .. }) => Some(*chain_id),
Transaction::Eip1559(TxEip1559 { chain_id, .. }) => Some(*chain_id),
Transaction::Eip4844(TxEip4844 { chain_id, .. }) => Some(*chain_id),
}
}
/// Sets the transaction's chain id to the provided value.
pub fn set_chain_id(&mut self, chain_id: u64) {
match self {
Transaction::Legacy(TxLegacy { chain_id: ref mut c, .. }) => *c = Some(chain_id),
Transaction::Eip2930(TxEip2930 { chain_id: ref mut c, .. }) => *c = chain_id,
Transaction::Eip1559(TxEip1559 { chain_id: ref mut c, .. }) => *c = chain_id,
Transaction::Eip4844(TxEip4844 { chain_id: ref mut c, .. }) => *c = chain_id,
}
}
/// Gets the transaction's [`TransactionKind`], which is the address of the recipient or
/// [`TransactionKind::Create`] if the transaction is a contract creation.
pub fn kind(&self) -> &TransactionKind {
match self {
Transaction::Legacy(TxLegacy { to, .. }) |
Transaction::Eip2930(TxEip2930 { to, .. }) |
Transaction::Eip1559(TxEip1559 { to, .. }) |
Transaction::Eip4844(TxEip4844 { to, .. }) => to,
}
}
/// Get the transaction's nonce.
pub fn to(&self) -> Option<Address> {
self.kind().to()
}
/// Get transaction type
pub fn tx_type(&self) -> TxType {
match self {
Transaction::Legacy(legacy_tx) => legacy_tx.tx_type(),
Transaction::Eip2930(access_list_tx) => access_list_tx.tx_type(),
Transaction::Eip1559(dynamic_fee_tx) => dynamic_fee_tx.tx_type(),
Transaction::Eip4844(blob_tx) => blob_tx.tx_type(),
}
}
/// Gets the transaction's value field.
pub fn value(&self) -> u128 {
*match self {
Transaction::Legacy(TxLegacy { value, .. }) => value,
Transaction::Eip2930(TxEip2930 { value, .. }) => value,
Transaction::Eip1559(TxEip1559 { value, .. }) => value,
Transaction::Eip4844(TxEip4844 { value, .. }) => value,
}
}
/// Get the transaction's nonce.
pub fn nonce(&self) -> u64 {
match self {
Transaction::Legacy(TxLegacy { nonce, .. }) => *nonce,
Transaction::Eip2930(TxEip2930 { nonce, .. }) => *nonce,
Transaction::Eip1559(TxEip1559 { nonce, .. }) => *nonce,
Transaction::Eip4844(TxEip4844 { nonce, .. }) => *nonce,
}
}
/// Get the gas limit of the transaction.
pub fn gas_limit(&self) -> u64 {
match self {
Transaction::Legacy(TxLegacy { gas_limit, .. }) |
Transaction::Eip2930(TxEip2930 { gas_limit, .. }) |
Transaction::Eip1559(TxEip1559 { gas_limit, .. }) |
Transaction::Eip4844(TxEip4844 { gas_limit, .. }) => *gas_limit,
}
}
/// Returns true if the tx supports dynamic fees
pub fn is_dynamic_fee(&self) -> bool {
match self {
Transaction::Legacy(_) | Transaction::Eip2930(_) => false,
Transaction::Eip1559(_) | Transaction::Eip4844(_) => true,
}
}
/// 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 fn max_fee_per_gas(&self) -> u128 {
match self {
Transaction::Legacy(TxLegacy { gas_price, .. }) |
Transaction::Eip2930(TxEip2930 { gas_price, .. }) => *gas_price,
Transaction::Eip1559(TxEip1559 { max_fee_per_gas, .. }) |
Transaction::Eip4844(TxEip4844 { max_fee_per_gas, .. }) => *max_fee_per_gas,
}
}
/// 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 fn max_priority_fee_per_gas(&self) -> Option<u128> {
match self {
Transaction::Legacy(_) => None,
Transaction::Eip2930(_) => None,
Transaction::Eip1559(TxEip1559 { max_priority_fee_per_gas, .. }) |
Transaction::Eip4844(TxEip4844 { max_priority_fee_per_gas, .. }) => {
Some(*max_priority_fee_per_gas)
}
}
}
/// 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 fn max_fee_per_blob_gas(&self) -> Option<u128> {
match self {
Transaction::Eip4844(TxEip4844 { max_fee_per_blob_gas, .. }) => {
Some(*max_fee_per_blob_gas)
}
_ => None,
}
}
/// 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 fn priority_fee_or_price(&self) -> u128 {
match self {
Transaction::Legacy(TxLegacy { gas_price, .. }) |
Transaction::Eip2930(TxEip2930 { gas_price, .. }) => *gas_price,
Transaction::Eip1559(TxEip1559 { max_priority_fee_per_gas, .. }) |
Transaction::Eip4844(TxEip4844 { max_priority_fee_per_gas, .. }) => {
*max_priority_fee_per_gas
}
}
}
/// 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 fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
match self {
Transaction::Legacy(tx) => tx.gas_price,
Transaction::Eip2930(tx) => tx.gas_price,
Transaction::Eip1559(dynamic_tx) => dynamic_tx.effective_gas_price(base_fee),
Transaction::Eip4844(dynamic_tx) => dynamic_tx.effective_gas_price(base_fee),
}
}
// TODO: dedup with effective_tip_per_gas
/// Determine the effective gas limit for the given transaction and base fee.
/// If the base fee is `None`, the `max_priority_fee_per_gas`, or gas price for non-EIP1559
/// transactions is returned.
///
/// If the `max_fee_per_gas` is less than the base fee, `None` returned.
pub fn effective_gas_tip(&self, base_fee: Option<u64>) -> Option<u128> {
if let Some(base_fee) = base_fee {
let max_fee_per_gas = self.max_fee_per_gas();
if max_fee_per_gas < base_fee as u128 {
None
} else {
let effective_max_fee = max_fee_per_gas - base_fee as u128;
Some(std::cmp::min(effective_max_fee, self.priority_fee_or_price()))
}
} else {
Some(self.priority_fee_or_price())
}
}
/// Returns the effective miner gas tip cap (`gasTipCap`) for the given base fee:
/// `min(maxFeePerGas - baseFee, maxPriorityFeePerGas)`
///
/// Returns `None` if the basefee is higher than the [Transaction::max_fee_per_gas].
pub fn effective_tip_per_gas(&self, base_fee: u64) -> Option<u128> {
let base_fee = base_fee as u128;
let max_fee_per_gas = self.max_fee_per_gas();
if max_fee_per_gas < base_fee {
return None
}
// the miner tip is the difference between the max fee and the base fee or the
// max_priority_fee_per_gas, whatever is lower
// SAFETY: max_fee_per_gas >= base_fee
let fee = max_fee_per_gas - base_fee;
if let Some(priority_fee) = self.max_priority_fee_per_gas() {
return Some(fee.min(priority_fee))
}
Some(fee)
}
/// Get the transaction's input field.
pub fn input(&self) -> &Bytes {
match self {
Transaction::Legacy(TxLegacy { input, .. }) => input,
Transaction::Eip2930(TxEip2930 { input, .. }) => input,
Transaction::Eip1559(TxEip1559 { input, .. }) => input,
Transaction::Eip4844(TxEip4844 { input, .. }) => input,
}
}
/// 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 {
Transaction::Legacy(legacy_tx) => {
// do nothing w/ with_header
legacy_tx.encode_with_signature(signature, out)
}
Transaction::Eip2930(access_list_tx) => {
access_list_tx.encode_with_signature(signature, out, with_header)
}
Transaction::Eip1559(dynamic_fee_tx) => {
dynamic_fee_tx.encode_with_signature(signature, out, with_header)
}
Transaction::Eip4844(blob_tx) => {
blob_tx.encode_with_signature(signature, out, with_header)
}
}
}
/// This sets the transaction's nonce.
pub fn set_nonce(&mut self, nonce: u64) {
match self {
Transaction::Legacy(tx) => tx.nonce = nonce,
Transaction::Eip2930(tx) => tx.nonce = nonce,
Transaction::Eip1559(tx) => tx.nonce = nonce,
Transaction::Eip4844(tx) => tx.nonce = nonce,
}
}
/// This sets the transaction's value.
pub fn set_value(&mut self, value: u128) {
match self {
Transaction::Legacy(tx) => tx.value = value,
Transaction::Eip2930(tx) => tx.value = value,
Transaction::Eip1559(tx) => tx.value = value,
Transaction::Eip4844(tx) => tx.value = value,
}
}
/// This sets the transaction's input field.
pub fn set_input(&mut self, input: Bytes) {
match self {
Transaction::Legacy(tx) => tx.input = input,
Transaction::Eip2930(tx) => tx.input = input,
Transaction::Eip1559(tx) => tx.input = input,
Transaction::Eip4844(tx) => tx.input = input,
}
}
/// Calculates a heuristic for the in-memory size of the [Transaction].
#[inline]
fn size(&self) -> usize {
match self {
Transaction::Legacy(tx) => tx.size(),
Transaction::Eip2930(tx) => tx.size(),
Transaction::Eip1559(tx) => tx.size(),
Transaction::Eip4844(tx) => tx.size(),
}
}
/// Returns true if the transaction is a legacy transaction.
#[inline]
pub fn is_legacy(&self) -> bool {
matches!(self, Transaction::Legacy(_))
}
/// Returns true if the transaction is an EIP-2930 transaction.
#[inline]
pub fn is_eip2930(&self) -> bool {
matches!(self, Transaction::Eip2930(_))
}
/// Returns true if the transaction is an EIP-1559 transaction.
#[inline]
pub fn is_eip1559(&self) -> bool {
matches!(self, Transaction::Eip1559(_))
}
/// Returns true if the transaction is an EIP-4844 transaction.
#[inline]
pub fn is_eip4844(&self) -> bool {
matches!(self, Transaction::Eip4844(_))
}
/// Returns the [TxLegacy] variant if the transaction is a legacy transaction.
pub fn as_legacy(&self) -> Option<&TxLegacy> {
match self {
Transaction::Legacy(tx) => Some(tx),
_ => None,
}
}
/// Returns the [TxEip2930] variant if the transaction is an EIP-2930 transaction.
pub fn as_eip2830(&self) -> Option<&TxEip2930> {
match self {
Transaction::Eip2930(tx) => Some(tx),
_ => None,
}
}
/// Returns the [TxEip1559] variant if the transaction is an EIP-1559 transaction.
pub fn as_eip1559(&self) -> Option<&TxEip1559> {
match self {
Transaction::Eip1559(tx) => Some(tx),
_ => None,
}
}
/// Returns the [TxEip4844] variant if the transaction is an EIP-4844 transaction.
pub fn as_eip4844(&self) -> Option<&TxEip4844> {
match self {
Transaction::Eip4844(tx) => Some(tx),
_ => None,
}
}
}
impl Compact for Transaction {
fn to_compact<B>(self, buf: &mut B) -> usize
where
B: bytes::BufMut + AsMut<[u8]>,
{
match self {
Transaction::Legacy(tx) => {
tx.to_compact(buf);
0
}
Transaction::Eip2930(tx) => {
tx.to_compact(buf);
1
}
Transaction::Eip1559(tx) => {
tx.to_compact(buf);
2
}
Transaction::Eip4844(tx) => {
tx.to_compact(buf);
3
}
}
}
fn from_compact(buf: &[u8], identifier: usize) -> (Self, &[u8]) {
match identifier {
0 => {
let (tx, buf) = TxLegacy::from_compact(buf, buf.len());
(Transaction::Legacy(tx), buf)
}
1 => {
let (tx, buf) = TxEip2930::from_compact(buf, buf.len());
(Transaction::Eip2930(tx), buf)
}
2 => {
let (tx, buf) = TxEip1559::from_compact(buf, buf.len());
(Transaction::Eip1559(tx), buf)
}
3 => {
let (tx, buf) = TxEip4844::from_compact(buf, buf.len());
(Transaction::Eip4844(tx), buf)
}
_ => unreachable!("Junk data in database: unknown Transaction variant"),
}
}
}
impl Default for Transaction {
fn default() -> Self {
Self::Legacy(TxLegacy::default())
}
}
/// This encodes the transaction _without_ the signature, and is only suitable for creating a hash
/// intended for signing.
impl Encodable for Transaction {
fn encode(&self, out: &mut dyn bytes::BufMut) {
match self {
Transaction::Legacy(legacy_tx) => {
legacy_tx.encode_for_signing(out);
}
Transaction::Eip2930(access_list_tx) => {
access_list_tx.encode_for_signing(out);
}
Transaction::Eip1559(dynamic_fee_tx) => {
dynamic_fee_tx.encode_for_signing(out);
}
Transaction::Eip4844(blob_tx) => {
blob_tx.encode_for_signing(out);
}
}
}
fn length(&self) -> usize {
match self {
Transaction::Legacy(legacy_tx) => legacy_tx.payload_len_for_signature(),
Transaction::Eip2930(access_list_tx) => access_list_tx.payload_len_for_signature(),
Transaction::Eip1559(dynamic_fee_tx) => dynamic_fee_tx.payload_len_for_signature(),
Transaction::Eip4844(blob_tx) => blob_tx.payload_len_for_signature(),
}
}
}
/// Whether or not the transaction is a contract creation.
#[derive_arbitrary(compact, rlp)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum TransactionKind {
/// A transaction that creates a contract.
#[default]
Create,
/// A transaction that calls a contract or transfer.
Call(Address),
}
impl TransactionKind {
/// Returns the address of the contract that will be called or will receive the transfer.
pub fn to(self) -> Option<Address> {
match self {
TransactionKind::Create => None,
TransactionKind::Call(to) => Some(to),
}
}
/// Calculates a heuristic for the in-memory size of the [TransactionKind].
#[inline]
fn size(self) -> usize {
mem::size_of::<Self>()
}
}
impl Compact for TransactionKind {
fn to_compact<B>(self, buf: &mut B) -> usize
where
B: bytes::BufMut + AsMut<[u8]>,
{
match self {
TransactionKind::Create => 0,
TransactionKind::Call(address) => {
address.to_compact(buf);
1
}
}
}
fn from_compact(buf: &[u8], identifier: usize) -> (Self, &[u8]) {
match identifier {
0 => (TransactionKind::Create, buf),
1 => {
let (addr, buf) = Address::from_compact(buf, buf.len());
(TransactionKind::Call(addr), buf)
}
_ => unreachable!("Junk data in database: unknown TransactionKind variant"),
}
}
}
impl Encodable for TransactionKind {
fn encode(&self, out: &mut dyn reth_rlp::BufMut) {
match self {
TransactionKind::Call(to) => to.encode(out),
TransactionKind::Create => out.put_u8(EMPTY_STRING_CODE),
}
}
fn length(&self) -> usize {
match self {
TransactionKind::Call(to) => to.length(),
TransactionKind::Create => 1, // EMPTY_STRING_CODE is a single byte
}
}
}
impl Decodable for TransactionKind {
fn decode(buf: &mut &[u8]) -> Result<Self, DecodeError> {
if let Some(&first) = buf.first() {
if first == EMPTY_STRING_CODE {
buf.advance(1);
Ok(TransactionKind::Create)
} else {
let addr = <Address as Decodable>::decode(buf)?;
Ok(TransactionKind::Call(addr))
}
} else {
Err(DecodeError::InputTooShort)
}
}
}
/// Signed transaction without its Hash. Used type for inserting into the DB.
///
/// This can by converted to [`TransactionSigned`] by calling [`TransactionSignedNoHash::hash`].
#[derive_arbitrary(compact)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, AsRef, Deref, Default, Serialize, Deserialize)]
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) -> H256 {
let mut buf = Vec::new();
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> {
let signature_hash = self.signature_hash();
self.signature.recover_signer(signature_hash)
}
/// Converts into a transaction type with its hash: [`TransactionSigned`].
pub fn with_hash(self) -> TransactionSigned {
self.into()
}
}
impl 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 {
TRANSACTION_COMPRESSOR.with(|compressor| {
let mut compressor = compressor.borrow_mut();
let mut tmp = bytes::BytesMut::with_capacity(200);
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 (signature, buf) = Signature::from_compact(buf, sig_bit);
let zstd_bit = bitflags >> 3;
let (transaction, buf) = if zstd_bit != 0 {
TRANSACTION_DECOMPRESSOR.with(|decompressor| {
let mut decompressor = decompressor.borrow_mut();
let mut tmp: Vec<u8> = Vec::with_capacity(200);
// `decompress_to_buffer` will return an error if the output buffer doesn't have
// enough capacity. However we don't actually have information on the required
// length. So we hope for the best, and keep trying again with a fairly bigger size
// if it fails.
while let Err(err) = decompressor.decompress_to_buffer(buf, &mut tmp) {
let err = err.to_string();
if !err.contains("Destination buffer is too small") {
panic!("Failed to decompress: {}", err);
}
tmp.reserve(tmp.capacity() + 24_000);
}
// TODO: enforce that zstd is only present at a "top" level type
let transaction_type = (bitflags & 0b110) >> 1;
let (transaction, _) = Transaction::from_compact(tmp.as_slice(), transaction_type);
(transaction, buf)
})
} else {
let transaction_type = bitflags >> 1;
Transaction::from_compact(buf, transaction_type)
};
(TransactionSignedNoHash { signature, transaction }, buf)
}
}
impl From<TransactionSignedNoHash> for TransactionSigned {
fn from(tx: TransactionSignedNoHash) -> Self {
TransactionSigned::from_transaction_and_signature(tx.transaction, tx.signature)
}
}
impl From<TransactionSigned> for TransactionSignedNoHash {
fn from(tx: TransactionSigned) -> Self {
TransactionSignedNoHash { signature: tx.signature, transaction: tx.transaction }
}
}
/// Signed transaction.
#[add_arbitrary_tests(rlp)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, AsRef, Deref, Default, Serialize, Deserialize)]
pub struct TransactionSigned {
/// Transaction hash
pub hash: TxHash,
/// The transaction signature values
pub signature: Signature,
/// Raw transaction info
#[deref]
#[as_ref]
pub transaction: Transaction,
}
impl AsRef<Self> for TransactionSigned {
fn as_ref(&self) -> &Self {
self
}
}
// === impl TransactionSigned ===
impl TransactionSigned {
/// Transaction signature.
pub fn signature(&self) -> &Signature {
&self.signature
}
/// Transaction hash. Used to identify transaction.
pub fn hash(&self) -> TxHash {
self.hash
}
/// Reference to transaction hash. Used to identify transaction.
pub fn hash_ref(&self) -> &TxHash {
&self.hash
}
/// 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> {
let signature_hash = self.signature_hash();
self.signature.recover_signer(signature_hash)
}
/// 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()
}
}
/// Consumes the type, recover signer and return [`TransactionSignedEcRecovered`]
///
/// Returns `None` if the transaction's signature is invalid, see also [Self::recover_signer].
pub fn into_ecrecovered(self) -> Option<TransactionSignedEcRecovered> {
let signer = self.recover_signer()?;
Some(TransactionSignedEcRecovered { signed_transaction: self, signer })
}
/// Tries to recover signer and return [`TransactionSignedEcRecovered`] by cloning the type.
pub fn try_ecrecovered(&self) -> Option<TransactionSignedEcRecovered> {
let signer = self.recover_signer()?;
Some(TransactionSignedEcRecovered { signed_transaction: self.clone(), signer })
}
/// Tries to recover signer and return [`TransactionSignedEcRecovered`].
///
/// Returns `Err(Self)` if the transaction's signature is invalid, see also
/// [Self::recover_signer].
pub fn try_into_ecrecovered(self) -> Result<TransactionSignedEcRecovered, Self> {
match self.recover_signer() {
None => Err(self),
Some(signer) => Ok(TransactionSignedEcRecovered { signed_transaction: self, signer }),
}
}
/// Returns the enveloped encoded transactions.
///
/// See also [TransactionSigned::encode_enveloped]
pub fn envelope_encoded(&self) -> bytes::Bytes {
let mut buf = BytesMut::new();
self.encode_enveloped(&mut buf);
buf.freeze()
}
/// Encodes the transaction into the "raw" format (e.g. `eth_sendRawTransaction`).
/// This format is also referred to as "binary" encoding.
///
/// For legacy transactions, it encodes the RLP of the transaction into the buffer: `rlp(tx)`
/// For EIP-2718 typed it encodes the type of the transaction followed by the rlp of the
/// transaction: `type` + `rlp(tx)`
pub fn encode_enveloped(&self, out: &mut dyn bytes::BufMut) {
self.encode_inner(out, false)
}
/// Inner encoding function that is used for both rlp [`Encodable`] trait and for calculating
/// hash that for eip2718 does not require rlp header
pub(crate) fn encode_inner(&self, out: &mut dyn bytes::BufMut, with_header: bool) {
self.transaction.encode_with_signature(&self.signature, out, with_header);
}
/// Output the length of the encode_inner(out, true). Note to assume that `with_header` is only
/// `true`.
pub(crate) fn payload_len_inner(&self) -> usize {
match &self.transaction {
Transaction::Legacy(legacy_tx) => legacy_tx.payload_len_with_signature(&self.signature),
Transaction::Eip2930(access_list_tx) => {
access_list_tx.payload_len_with_signature(&self.signature)
}
Transaction::Eip1559(dynamic_fee_tx) => {
dynamic_fee_tx.payload_len_with_signature(&self.signature)
}
Transaction::Eip4844(blob_tx) => blob_tx.payload_len_with_signature(&self.signature),
}
}
/// Calculate transaction hash, eip2728 transaction does not contain rlp header and start with
/// tx type.
pub fn recalculate_hash(&self) -> H256 {
let mut buf = Vec::new();
self.encode_inner(&mut buf, false);
keccak256(&buf)
}
/// Create a new signed transaction from a transaction and its signature.
/// This will also calculate the transaction hash using its encoding.
pub fn from_transaction_and_signature(transaction: Transaction, signature: Signature) -> Self {
let mut initial_tx = Self { transaction, hash: Default::default(), signature };
initial_tx.hash = initial_tx.recalculate_hash();
initial_tx
}
/// Calculate a heuristic for the in-memory size of the [TransactionSigned].
#[inline]
pub fn size(&self) -> usize {
mem::size_of::<TxHash>() + self.transaction.size() + self.signature.size()
}
/// Decodes legacy transaction from the data buffer into a tuple.
///
/// This expects `rlp(legacy_tx)`
// TODO: make buf advancement semantics consistent with `decode_enveloped_typed_transaction`,
// so decoding methods do not need to manually advance the buffer
pub(crate) fn decode_rlp_legacy_transaction_tuple(
data: &mut &[u8],
) -> Result<(TxLegacy, TxHash, Signature), DecodeError> {
// keep this around, so we can use it to calculate the hash
let original_encoding = *data;
let header = Header::decode(data)?;
let mut transaction = TxLegacy {
nonce: Decodable::decode(data)?,
gas_price: Decodable::decode(data)?,
gas_limit: Decodable::decode(data)?,
to: Decodable::decode(data)?,
value: Decodable::decode(data)?,
input: Bytes(Decodable::decode(data)?),
chain_id: None,
};
let (signature, extracted_id) = Signature::decode_with_eip155_chain_id(data)?;
transaction.chain_id = extracted_id;
let tx_length = header.payload_length + header.length();
let hash = keccak256(&original_encoding[..tx_length]);
Ok((transaction, hash, signature))
}
/// Decodes legacy transaction from the data buffer.
///
/// This expects `rlp(legacy_tx)`
// TODO: make buf advancement semantics consistent with `decode_enveloped_typed_transaction`,
// so decoding methods do not need to manually advance the buffer
pub fn decode_rlp_legacy_transaction(
data: &mut &[u8],
) -> Result<TransactionSigned, DecodeError> {
let (transaction, hash, signature) =
TransactionSigned::decode_rlp_legacy_transaction_tuple(data)?;
let signed =
TransactionSigned { transaction: Transaction::Legacy(transaction), hash, signature };
Ok(signed)
}
/// Decodes en enveloped EIP-2718 typed transaction.
///
/// CAUTION: this expects that `data` is `[id, rlp(tx)]`
pub fn decode_enveloped_typed_transaction(
data: &mut &[u8],
) -> Result<TransactionSigned, DecodeError> {
// keep this around so we can use it to calculate the hash
let original_encoding = *data;
let tx_type = *data.first().ok_or(DecodeError::InputTooShort)?;
data.advance(1);
// decode the list header for the rest of the transaction
let header = Header::decode(data)?;
if !header.list {
return Err(DecodeError::Custom("typed tx fields must be encoded as a list"))
}
// length of tx encoding = tx type byte (size = 1) + length of header + payload length
let tx_length = 1 + header.length() + header.payload_length;
// decode common fields
let transaction = match tx_type {
1 => Transaction::Eip2930(TxEip2930::decode_inner(data)?),
2 => Transaction::Eip1559(TxEip1559::decode_inner(data)?),
3 => Transaction::Eip4844(TxEip4844::decode_inner(data)?),
_ => return Err(DecodeError::Custom("unsupported typed transaction type")),
};
let signature = Signature::decode(data)?;
let hash = keccak256(&original_encoding[..tx_length]);
let signed = TransactionSigned { transaction, hash, signature };
Ok(signed)
}
/// Decodes the "raw" format of transaction (e.g. `eth_sendRawTransaction`).
///
/// The raw transaction is either a legacy transaction or EIP-2718 typed transaction
/// For legacy transactions, the format is encoded as: `rlp(tx)`
/// For EIP-2718 typed transaction, the format is encoded as the type of the transaction
/// followed by the rlp of the transaction: `type` + `rlp(tx)`
pub fn decode_enveloped(tx: Bytes) -> Result<Self, DecodeError> {
let mut data = tx.as_ref();
if data.is_empty() {
return Err(DecodeError::InputTooShort)
}
// Check if the tx is a list
if data[0] >= EMPTY_LIST_CODE {
// decode as legacy transaction
TransactionSigned::decode_rlp_legacy_transaction(&mut data)
} else {
TransactionSigned::decode_enveloped_typed_transaction(&mut data)
}
}
}
impl From<TransactionSignedEcRecovered> for TransactionSigned {
fn from(recovered: TransactionSignedEcRecovered) -> Self {
recovered.signed_transaction
}
}
impl Encodable for TransactionSigned {