-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
mod.rs
1355 lines (1246 loc) · 47.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 related data
use crate::eth::{
receipt::Log,
utils::{enveloped, to_access_list},
};
use bytes::Buf;
use ethers_core::{
types::{
transaction::eip2930::{AccessList, AccessListItem},
Address, Bloom, Bytes, Signature, SignatureError, TxHash, H256, U256,
},
utils::{
keccak256, rlp,
rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream},
},
};
use fastrlp::{length_of_length, Header, RlpDecodable, RlpEncodable};
use foundry_evm::trace::CallTraceArena;
use revm::{CreateScheme, Return, TransactTo, TxEnv};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
/// compatibility with `ethers-rs` types
mod ethers_compat;
/// Container type for various Ethereum transaction requests
///
/// Its variants correspond to specific allowed transactions:
/// 1. Legacy (pre-EIP2718) [`LegacyTransactionRequest`]
/// 2. EIP2930 (state access lists) [`EIP2930TransactionRequest`]
/// 3. EIP1559 [`EIP1559TransactionRequest`]
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TypedTransactionRequest {
Legacy(LegacyTransactionRequest),
EIP2930(EIP2930TransactionRequest),
EIP1559(EIP1559TransactionRequest),
}
/// Represents _all_ transaction requests received from RPC
#[derive(Clone, Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "camelCase")]
pub struct EthTransactionRequest {
/// from address
pub from: Option<Address>,
/// to address
pub to: Option<Address>,
/// legacy, gas Price
#[serde(default)]
pub gas_price: Option<U256>,
/// max base fee per gas sender is willing to pay
#[serde(default)]
pub max_fee_per_gas: Option<U256>,
/// miner tip
#[serde(default)]
pub max_priority_fee_per_gas: Option<U256>,
/// gas
pub gas: Option<U256>,
/// value of th tx in wei
pub value: Option<U256>,
/// Any additional data sent
pub data: Option<Bytes>,
/// Transaction nonce
pub nonce: Option<U256>,
/// warm storage access pre-payment
#[serde(default)]
pub access_list: Option<Vec<AccessListItem>>,
/// EIP-2718 type
#[serde(rename = "type")]
pub transaction_type: Option<U256>,
}
// == impl EthTransactionRequest ==
impl EthTransactionRequest {
/// Converts the request into a [TypedTransactionRequest]
pub fn into_typed_request(self) -> Option<TypedTransactionRequest> {
let EthTransactionRequest {
to,
gas_price,
max_fee_per_gas,
max_priority_fee_per_gas,
gas,
value,
data,
nonce,
mut access_list,
..
} = self;
match (gas_price, max_fee_per_gas, access_list.take()) {
// legacy transaction
(Some(_), None, None) => {
Some(TypedTransactionRequest::Legacy(LegacyTransactionRequest {
nonce: nonce.unwrap_or(U256::zero()),
gas_price: gas_price.unwrap_or_default(),
gas_limit: gas.unwrap_or_default(),
value: value.unwrap_or(U256::zero()),
input: data.unwrap_or_default(),
kind: match to {
Some(to) => TransactionKind::Call(to),
None => TransactionKind::Create,
},
chain_id: None,
}))
}
// EIP2930
(_, None, Some(access_list)) => {
Some(TypedTransactionRequest::EIP2930(EIP2930TransactionRequest {
nonce: nonce.unwrap_or(U256::zero()),
gas_price: gas_price.unwrap_or_default(),
gas_limit: gas.unwrap_or_default(),
value: value.unwrap_or(U256::zero()),
input: data.unwrap_or_default(),
kind: match to {
Some(to) => TransactionKind::Call(to),
None => TransactionKind::Create,
},
chain_id: 0,
access_list,
}))
}
// EIP1559
(None, Some(_), access_list) | (None, None, access_list @ None) => {
// Empty fields fall back to the canonical transaction schema.
Some(TypedTransactionRequest::EIP1559(EIP1559TransactionRequest {
nonce: nonce.unwrap_or(U256::zero()),
max_fee_per_gas: max_fee_per_gas.unwrap_or_default(),
max_priority_fee_per_gas: max_priority_fee_per_gas.unwrap_or(U256::zero()),
gas_limit: gas.unwrap_or_default(),
value: value.unwrap_or(U256::zero()),
input: data.unwrap_or_default(),
kind: match to {
Some(to) => TransactionKind::Call(to),
None => TransactionKind::Create,
},
chain_id: 0,
access_list: access_list.unwrap_or_default(),
}))
}
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TransactionKind {
Call(Address),
Create,
}
// == impl TransactionKind ==
impl TransactionKind {
/// If this transaction is a call this returns the address of the callee
pub fn as_call(&self) -> Option<&Address> {
match self {
TransactionKind::Call(to) => Some(to),
TransactionKind::Create => None,
}
}
}
impl Encodable for TransactionKind {
fn rlp_append(&self, s: &mut RlpStream) {
match self {
TransactionKind::Call(address) => {
s.encoder().encode_value(&address[..]);
}
TransactionKind::Create => s.encoder().encode_value(&[]),
}
}
}
impl Decodable for TransactionKind {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
if rlp.is_empty() {
if rlp.is_data() {
Ok(TransactionKind::Create)
} else {
Err(DecoderError::RlpExpectedToBeData)
}
} else {
Ok(TransactionKind::Call(rlp.as_val()?))
}
}
}
impl fastrlp::Encodable for TransactionKind {
fn length(&self) -> usize {
match self {
TransactionKind::Call(to) => to.length(),
TransactionKind::Create => ([]).length(),
}
}
fn encode(&self, out: &mut dyn fastrlp::BufMut) {
match self {
TransactionKind::Call(to) => to.encode(out),
TransactionKind::Create => ([]).encode(out),
}
}
}
impl fastrlp::Decodable for TransactionKind {
fn decode(buf: &mut &[u8]) -> Result<Self, fastrlp::DecodeError> {
if let Some(&first) = buf.first() {
if first == 0x80 {
buf.advance(1);
Ok(TransactionKind::Create)
} else {
let addr = <Address as fastrlp::Decodable>::decode(buf)?;
Ok(TransactionKind::Call(addr))
}
} else {
Err(fastrlp::DecodeError::InputTooShort)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
pub struct EIP2930TransactionRequest {
pub chain_id: u64,
pub nonce: U256,
pub gas_price: U256,
pub gas_limit: U256,
pub kind: TransactionKind,
pub value: U256,
pub input: Bytes,
pub access_list: Vec<AccessListItem>,
}
impl EIP2930TransactionRequest {
pub fn hash(&self) -> H256 {
let encoded = rlp::encode(self);
let mut out = vec![0; 1 + encoded.len()];
out[0] = 1;
out[1..].copy_from_slice(&encoded);
H256::from_slice(keccak256(&out).as_slice())
}
}
impl From<EIP2930Transaction> for EIP2930TransactionRequest {
fn from(tx: EIP2930Transaction) -> Self {
Self {
chain_id: tx.chain_id,
nonce: tx.nonce,
gas_price: tx.gas_price,
gas_limit: tx.gas_limit,
kind: tx.kind,
value: tx.value,
input: tx.input,
access_list: tx.access_list.0,
}
}
}
impl Encodable for EIP2930TransactionRequest {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(8);
s.append(&self.chain_id);
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas_limit);
s.append(&self.kind);
s.append(&self.value);
s.append(&self.input.as_ref());
s.append_list(&self.access_list);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LegacyTransactionRequest {
pub nonce: U256,
pub gas_price: U256,
pub gas_limit: U256,
pub kind: TransactionKind,
pub value: U256,
pub input: Bytes,
pub chain_id: Option<u64>,
}
// == impl LegacyTransactionRequest ==
impl LegacyTransactionRequest {
pub fn hash(&self) -> H256 {
H256::from_slice(keccak256(&rlp::encode(self)).as_slice())
}
}
impl From<LegacyTransaction> for LegacyTransactionRequest {
fn from(tx: LegacyTransaction) -> Self {
let chain_id = tx.chain_id();
Self {
nonce: tx.nonce,
gas_price: tx.gas_price,
gas_limit: tx.gas_limit,
kind: tx.kind,
value: tx.value,
input: tx.input,
chain_id,
}
}
}
impl Encodable for LegacyTransactionRequest {
fn rlp_append(&self, s: &mut RlpStream) {
if let Some(chain_id) = self.chain_id {
s.begin_list(9);
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas_limit);
s.append(&self.kind);
s.append(&self.value);
s.append(&self.input.as_ref());
s.append(&chain_id);
s.append(&0u8);
s.append(&0u8);
} else {
s.begin_list(6);
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas_limit);
s.append(&self.kind);
s.append(&self.value);
s.append(&self.input.as_ref());
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, RlpEncodable, RlpDecodable)]
pub struct EIP1559TransactionRequest {
pub chain_id: u64,
pub nonce: U256,
pub max_priority_fee_per_gas: U256,
pub max_fee_per_gas: U256,
pub gas_limit: U256,
pub kind: TransactionKind,
pub value: U256,
pub input: Bytes,
pub access_list: Vec<AccessListItem>,
}
// == impl EIP1559TransactionRequest ==
impl EIP1559TransactionRequest {
pub fn hash(&self) -> H256 {
let encoded = rlp::encode(self);
let mut out = vec![0; 1 + encoded.len()];
out[0] = 2;
out[1..].copy_from_slice(&encoded);
H256::from_slice(keccak256(&out).as_slice())
}
}
impl From<EIP1559Transaction> for EIP1559TransactionRequest {
fn from(t: EIP1559Transaction) -> Self {
Self {
chain_id: t.chain_id,
nonce: t.nonce,
max_priority_fee_per_gas: t.max_priority_fee_per_gas,
max_fee_per_gas: t.max_fee_per_gas,
gas_limit: t.gas_limit,
kind: t.kind,
value: t.value,
input: t.input,
access_list: t.access_list.0,
}
}
}
impl Encodable for EIP1559TransactionRequest {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(9);
s.append(&self.chain_id);
s.append(&self.nonce);
s.append(&self.max_priority_fee_per_gas);
s.append(&self.max_fee_per_gas);
s.append(&self.gas_limit);
s.append(&self.kind);
s.append(&self.value);
s.append(&self.input.as_ref());
s.append_list(&self.access_list);
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum TypedTransaction {
/// Legacy transaction type
Legacy(LegacyTransaction),
/// EIP-2930 transaction
EIP2930(EIP2930Transaction),
/// EIP-1559 transaction
EIP1559(EIP1559Transaction),
}
// == impl TypedTransaction ==
impl TypedTransaction {
pub fn gas_price(&self) -> U256 {
match self {
TypedTransaction::Legacy(tx) => tx.gas_price,
TypedTransaction::EIP2930(tx) => tx.gas_price,
TypedTransaction::EIP1559(tx) => tx.max_fee_per_gas,
}
}
pub fn gas_limit(&self) -> U256 {
match self {
TypedTransaction::Legacy(tx) => tx.gas_limit,
TypedTransaction::EIP2930(tx) => tx.gas_limit,
TypedTransaction::EIP1559(tx) => tx.gas_limit,
}
}
pub fn value(&self) -> U256 {
match self {
TypedTransaction::Legacy(tx) => tx.value,
TypedTransaction::EIP2930(tx) => tx.value,
TypedTransaction::EIP1559(tx) => tx.value,
}
}
pub fn data(&self) -> &Bytes {
match self {
TypedTransaction::Legacy(tx) => &tx.input,
TypedTransaction::EIP2930(tx) => &tx.input,
TypedTransaction::EIP1559(tx) => &tx.input,
}
}
/// Max cost of the transaction
pub fn max_cost(&self) -> U256 {
self.gas_limit().saturating_mul(self.gas_price())
}
/// Returns a helper type that contains commonly used values as fields
pub fn essentials(&self) -> TransactionEssentials {
match self {
TypedTransaction::Legacy(t) => TransactionEssentials {
kind: t.kind,
input: t.input.clone(),
nonce: t.nonce,
gas_limit: t.gas_limit,
gas_price: Some(t.gas_price),
max_fee_per_gas: None,
max_priority_fee_per_gas: None,
value: t.value,
chain_id: t.chain_id(),
access_list: Default::default(),
},
TypedTransaction::EIP2930(t) => TransactionEssentials {
kind: t.kind,
input: t.input.clone(),
nonce: t.nonce,
gas_limit: t.gas_limit,
gas_price: Some(t.gas_price),
max_fee_per_gas: None,
max_priority_fee_per_gas: None,
value: t.value,
chain_id: Some(t.chain_id),
access_list: t.access_list.clone(),
},
TypedTransaction::EIP1559(t) => TransactionEssentials {
kind: t.kind,
input: t.input.clone(),
nonce: t.nonce,
gas_limit: t.gas_limit,
gas_price: None,
max_fee_per_gas: Some(t.max_fee_per_gas),
max_priority_fee_per_gas: Some(t.max_priority_fee_per_gas),
value: t.value,
chain_id: Some(t.chain_id),
access_list: t.access_list.clone(),
},
}
}
pub fn nonce(&self) -> &U256 {
match self {
TypedTransaction::Legacy(t) => t.nonce(),
TypedTransaction::EIP2930(t) => t.nonce(),
TypedTransaction::EIP1559(t) => t.nonce(),
}
}
pub fn chain_id(&self) -> Option<u64> {
match self {
TypedTransaction::Legacy(t) => t.chain_id(),
TypedTransaction::EIP2930(t) => Some(t.chain_id),
TypedTransaction::EIP1559(t) => Some(t.chain_id),
}
}
pub fn as_legacy(&self) -> Option<&LegacyTransaction> {
match self {
TypedTransaction::Legacy(tx) => Some(tx),
_ => None,
}
}
/// Returns true whether this tx is a legacy transaction
pub fn is_legacy(&self) -> bool {
matches!(self, TypedTransaction::Legacy(_))
}
/// Returns true whether this tx is a EIP1559 transaction
pub fn is_eip1559(&self) -> bool {
matches!(self, TypedTransaction::EIP1559(_))
}
pub fn hash(&self) -> H256 {
match self {
TypedTransaction::Legacy(t) => t.hash(),
TypedTransaction::EIP2930(t) => t.hash(),
TypedTransaction::EIP1559(t) => t.hash(),
}
}
/// Recovers the Ethereum address which was used to sign the transaction.
pub fn recover(&self) -> Result<Address, SignatureError> {
match self {
TypedTransaction::Legacy(tx) => tx.recover(),
TypedTransaction::EIP2930(tx) => tx.recover(),
TypedTransaction::EIP1559(tx) => tx.recover(),
}
}
/// Returns what kind of transaction this is
pub fn kind(&self) -> &TransactionKind {
match self {
TypedTransaction::Legacy(tx) => &tx.kind,
TypedTransaction::EIP2930(tx) => &tx.kind,
TypedTransaction::EIP1559(tx) => &tx.kind,
}
}
/// Returns the callee if this transaction is a call
pub fn to(&self) -> Option<&Address> {
self.kind().as_call()
}
/// Returns the Signature of the transaction
pub fn signature(&self) -> Signature {
match self {
TypedTransaction::Legacy(tx) => tx.signature,
TypedTransaction::EIP2930(tx) => {
let v = tx.odd_y_parity as u8;
let r = U256::from_big_endian(&tx.r[..]);
let s = U256::from_big_endian(&tx.s[..]);
Signature { r, s, v: v.into() }
}
TypedTransaction::EIP1559(tx) => {
let v = tx.odd_y_parity as u8;
let r = U256::from_big_endian(&tx.r[..]);
let s = U256::from_big_endian(&tx.s[..]);
Signature { r, s, v: v.into() }
}
}
}
}
impl Encodable for TypedTransaction {
fn rlp_append(&self, s: &mut RlpStream) {
match self {
TypedTransaction::Legacy(tx) => tx.rlp_append(s),
TypedTransaction::EIP2930(tx) => enveloped(1, tx, s),
TypedTransaction::EIP1559(tx) => enveloped(2, tx, s),
}
}
}
impl Decodable for TypedTransaction {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
let data = rlp.data()?;
let first = *data.first().ok_or(DecoderError::Custom("empty slice"))?;
if rlp.is_list() {
return Ok(TypedTransaction::Legacy(rlp.as_val()?))
}
let s = data.get(1..).ok_or(DecoderError::Custom("no tx body"))?;
if first == 0x01 {
return rlp::decode(s).map(TypedTransaction::EIP2930)
}
if first == 0x02 {
return rlp::decode(s).map(TypedTransaction::EIP1559)
}
Err(DecoderError::Custom("invalid tx type"))
}
}
impl fastrlp::Encodable for TypedTransaction {
fn length(&self) -> usize {
match self {
TypedTransaction::Legacy(tx) => tx.length(),
tx => {
let payload_len = match tx {
TypedTransaction::EIP2930(tx) => tx.length() + 1,
TypedTransaction::EIP1559(tx) => tx.length() + 1,
_ => unreachable!("legacy tx length already matched"),
};
// we include a string header for signed types txs, so include the length here
payload_len + length_of_length(payload_len)
}
}
}
fn encode(&self, out: &mut dyn fastrlp::BufMut) {
match self {
TypedTransaction::Legacy(tx) => tx.encode(out),
tx => {
let payload_len = match tx {
TypedTransaction::EIP2930(tx) => tx.length() + 1,
TypedTransaction::EIP1559(tx) => tx.length() + 1,
_ => unreachable!("legacy tx length already matched"),
};
match tx {
TypedTransaction::EIP2930(tx) => {
let tx_string_header = Header { list: false, payload_length: payload_len };
tx_string_header.encode(out);
out.put_u8(0x01);
tx.encode(out);
}
TypedTransaction::EIP1559(tx) => {
let tx_string_header = Header { list: false, payload_length: payload_len };
tx_string_header.encode(out);
out.put_u8(0x02);
tx.encode(out);
}
_ => unreachable!("legacy tx encode already matched"),
}
}
}
}
}
impl fastrlp::Decodable for TypedTransaction {
fn decode(buf: &mut &[u8]) -> Result<Self, fastrlp::DecodeError> {
let first = *buf.first().ok_or(fastrlp::DecodeError::Custom("empty slice"))?;
// a signed transaction is either encoded as a string (non legacy) or a list (legacy).
// We should not consume the buffer if we are decoding a legacy transaction, so let's
// check if the first byte is between 0x80 and 0xbf.
match first.cmp(&fastrlp::EMPTY_LIST_CODE) {
Ordering::Less => {
// strip out the string header
// NOTE: typed transaction encodings either contain a "rlp header" which contains
// the type of the payload and its length, or they do not contain a header and
// start with the tx type byte.
//
// This line works for both types of encodings because byte slices starting with
// 0x01 and 0x02 return a Header { list: false, payload_length: 1 } when input to
// Header::decode.
// If the encoding includes a header, the header will be properly decoded and
// consumed.
// Otherwise, header decoding will succeed but nothing is consumed.
let _header = Header::decode(buf)?;
let tx_type = *buf.first().ok_or(fastrlp::DecodeError::Custom(
"typed tx cannot be decoded from an empty slice",
))?;
if tx_type == 0x01 {
buf.advance(1);
<EIP2930Transaction as fastrlp::Decodable>::decode(buf)
.map(TypedTransaction::EIP2930)
} else if tx_type == 0x02 {
buf.advance(1);
<EIP1559Transaction as fastrlp::Decodable>::decode(buf)
.map(TypedTransaction::EIP1559)
} else {
Err(fastrlp::DecodeError::Custom("invalid tx type"))
}
}
Ordering::Equal => Err(fastrlp::DecodeError::Custom(
"an empty list is not a valid transaction encoding",
)),
Ordering::Greater => {
<LegacyTransaction as fastrlp::Decodable>::decode(buf).map(TypedTransaction::Legacy)
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash, RlpEncodable, RlpDecodable)]
pub struct LegacyTransaction {
pub nonce: U256,
pub gas_price: U256,
pub gas_limit: U256,
pub kind: TransactionKind,
pub value: U256,
pub input: Bytes,
pub signature: Signature,
}
impl LegacyTransaction {
pub fn nonce(&self) -> &U256 {
&self.nonce
}
pub fn hash(&self) -> H256 {
H256::from_slice(keccak256(&rlp::encode(self)).as_slice())
}
/// Recovers the Ethereum address which was used to sign the transaction.
pub fn recover(&self) -> Result<Address, SignatureError> {
self.signature.recover(LegacyTransactionRequest::from(self.clone()).hash())
}
pub fn chain_id(&self) -> Option<u64> {
if self.signature.v > 36 {
Some((self.signature.v - 35) / 2)
} else {
None
}
}
/// See <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md>
/// > If you do, then the v of the signature MUST be set to {0,1} + CHAIN_ID * 2 + 35 where
/// > {0,1} is the parity of the y value of the curve point for which r is the x-value in the
/// > secp256k1 signing process.
pub fn meets_eip155(&self, chain_id: u64) -> bool {
let double_chain_id = chain_id.saturating_mul(2);
let v = self.signature.v;
v == double_chain_id + 35 || v == double_chain_id + 36
}
}
impl Encodable for LegacyTransaction {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(9);
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas_limit);
s.append(&self.kind);
s.append(&self.value);
s.append(&self.input.as_ref());
s.append(&self.signature.v);
s.append(&self.signature.r);
s.append(&self.signature.s);
}
}
impl Decodable for LegacyTransaction {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
if rlp.item_count()? != 9 {
return Err(DecoderError::RlpIncorrectListLen)
}
let v = rlp.val_at(6)?;
let r = rlp.val_at::<U256>(7)?;
let s = rlp.val_at::<U256>(8)?;
Ok(Self {
nonce: rlp.val_at(0)?,
gas_price: rlp.val_at(1)?,
gas_limit: rlp.val_at(2)?,
kind: rlp.val_at(3)?,
value: rlp.val_at(4)?,
input: rlp.val_at::<Vec<u8>>(5)?.into(),
signature: Signature { v, r, s },
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash, RlpEncodable, RlpDecodable)]
pub struct EIP2930Transaction {
pub chain_id: u64,
pub nonce: U256,
pub gas_price: U256,
pub gas_limit: U256,
pub kind: TransactionKind,
pub value: U256,
pub input: Bytes,
pub access_list: AccessList,
pub odd_y_parity: bool,
pub r: H256,
pub s: H256,
}
impl EIP2930Transaction {
pub fn nonce(&self) -> &U256 {
&self.nonce
}
pub fn hash(&self) -> H256 {
let encoded = rlp::encode(self);
let mut out = vec![0; 1 + encoded.len()];
out[0] = 1;
out[1..].copy_from_slice(&encoded);
H256::from_slice(keccak256(&out).as_slice())
}
/// Recovers the Ethereum address which was used to sign the transaction.
pub fn recover(&self) -> Result<Address, SignatureError> {
let mut sig = [0u8; 65];
sig[0..32].copy_from_slice(&self.r[..]);
sig[32..64].copy_from_slice(&self.s[..]);
sig[64] = self.odd_y_parity as u8;
let signature = Signature::try_from(&sig[..])?;
signature.recover(EIP2930TransactionRequest::from(self.clone()).hash())
}
}
impl Encodable for EIP2930Transaction {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(11);
s.append(&self.chain_id);
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas_limit);
s.append(&self.kind);
s.append(&self.value);
s.append(&self.input.as_ref());
s.append(&self.access_list);
s.append(&self.odd_y_parity);
s.append(&U256::from_big_endian(&self.r[..]));
s.append(&U256::from_big_endian(&self.s[..]));
}
}
impl Decodable for EIP2930Transaction {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
if rlp.item_count()? != 11 {
return Err(DecoderError::RlpIncorrectListLen)
}
Ok(Self {
chain_id: rlp.val_at(0)?,
nonce: rlp.val_at(1)?,
gas_price: rlp.val_at(2)?,
gas_limit: rlp.val_at(3)?,
kind: rlp.val_at(4)?,
value: rlp.val_at(5)?,
input: rlp.val_at::<Vec<u8>>(6)?.into(),
access_list: rlp.val_at(7)?,
odd_y_parity: rlp.val_at(8)?,
r: {
let mut rarr = [0u8; 32];
rlp.val_at::<U256>(9)?.to_big_endian(&mut rarr);
H256::from(rarr)
},
s: {
let mut sarr = [0u8; 32];
rlp.val_at::<U256>(10)?.to_big_endian(&mut sarr);
H256::from(sarr)
},
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Hash, RlpEncodable, RlpDecodable)]
pub struct EIP1559Transaction {
pub chain_id: u64,
pub nonce: U256,
pub max_priority_fee_per_gas: U256,
pub max_fee_per_gas: U256,
pub gas_limit: U256,
pub kind: TransactionKind,
pub value: U256,
pub input: Bytes,
pub access_list: AccessList,
pub odd_y_parity: bool,
pub r: H256,
pub s: H256,
}
impl EIP1559Transaction {
pub fn nonce(&self) -> &U256 {
&self.nonce
}
pub fn hash(&self) -> H256 {
let encoded = rlp::encode(self);
let mut out = vec![0; 1 + encoded.len()];
out[0] = 2;
out[1..].copy_from_slice(&encoded);
H256::from_slice(keccak256(&out).as_slice())
}
/// Recovers the Ethereum address which was used to sign the transaction.
pub fn recover(&self) -> Result<Address, SignatureError> {
let mut sig = [0u8; 65];
sig[0..32].copy_from_slice(&self.r[..]);
sig[32..64].copy_from_slice(&self.s[..]);
sig[64] = self.odd_y_parity as u8;
let signature = Signature::try_from(&sig[..])?;
signature.recover(EIP1559TransactionRequest::from(self.clone()).hash())
}
}
impl Encodable for EIP1559Transaction {
fn rlp_append(&self, s: &mut RlpStream) {
s.begin_list(12);
s.append(&self.chain_id);
s.append(&self.nonce);
s.append(&self.max_priority_fee_per_gas);
s.append(&self.max_fee_per_gas);
s.append(&self.gas_limit);
s.append(&self.kind);
s.append(&self.value);
s.append(&self.input.as_ref());
s.append(&self.access_list);
s.append(&self.odd_y_parity);
s.append(&U256::from_big_endian(&self.r[..]));
s.append(&U256::from_big_endian(&self.s[..]));
}
}
impl Decodable for EIP1559Transaction {
fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
if rlp.item_count()? != 12 {
return Err(DecoderError::RlpIncorrectListLen)
}
Ok(Self {
chain_id: rlp.val_at(0)?,
nonce: rlp.val_at(1)?,
max_priority_fee_per_gas: rlp.val_at(2)?,
max_fee_per_gas: rlp.val_at(3)?,
gas_limit: rlp.val_at(4)?,
kind: rlp.val_at(5)?,
value: rlp.val_at(6)?,
input: rlp.val_at::<Vec<u8>>(7)?.into(),
access_list: rlp.val_at(8)?,
odd_y_parity: rlp.val_at(9)?,
r: {
let mut rarr = [0u8; 32];
rlp.val_at::<U256>(10)?.to_big_endian(&mut rarr);
H256::from(rarr)
},
s: {
let mut sarr = [0u8; 32];
rlp.val_at::<U256>(11)?.to_big_endian(&mut sarr);
H256::from(sarr)
},
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TransactionEssentials {
pub kind: TransactionKind,
pub input: Bytes,
pub nonce: U256,
pub gas_limit: U256,
pub gas_price: Option<U256>,
pub max_fee_per_gas: Option<U256>,
pub max_priority_fee_per_gas: Option<U256>,
pub value: U256,
pub chain_id: Option<u64>,
pub access_list: AccessList,
}
/// Queued transaction
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingTransaction {
/// The actual transaction
pub transaction: TypedTransaction,
/// the recovered sender of this transaction
sender: Address,
/// hash of `transaction`, so it can easily be reused with encoding and hashing agan
hash: TxHash,
}
// == impl PendingTransaction ==
impl PendingTransaction {
/// Creates a new pending transaction and tries to verify transaction and recover sender.
pub fn new(transaction: TypedTransaction) -> Result<Self, SignatureError> {
let sender = transaction.recover()?;
Ok(Self::with_sender(transaction, sender))
}
/// Creates a new transaction with the given sender
pub fn with_sender(transaction: TypedTransaction, sender: Address) -> Self {
Self { hash: transaction.hash(), transaction, sender }
}
pub fn nonce(&self) -> &U256 {
self.transaction.nonce()
}
pub fn hash(&self) -> &TxHash {
&self.hash
}
pub fn sender(&self) -> &Address {
&self.sender
}
/// Converts the [PendingTransaction] into the [TxEnv] context that [`revm`](foundry_evm)
/// expects.
pub fn to_revm_tx_env(&self) -> TxEnv {
fn transact_to(kind: &TransactionKind) -> TransactTo {
match kind {
TransactionKind::Call(c) => TransactTo::Call(*c),
TransactionKind::Create => TransactTo::Create(CreateScheme::Create),
}
}
let caller = *self.sender();