This repository was archived by the owner on Apr 18, 2025. It is now read-only.
forked from privacy-scaling-explorations/zkevm-circuits
-
Notifications
You must be signed in to change notification settings - Fork 391
/
Copy pathlib.rs
1182 lines (1091 loc) · 37.2 KB
/
lib.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
//! Ethereum and Evm types used to deserialize responses from web3 / geth.
#![cfg_attr(docsrs, feature(doc_cfg))]
// Temporary until we have more of the crate implemented.
#![allow(dead_code)]
#![allow(incomplete_features)]
// We want to have UPPERCASE idents sometimes.
#![allow(non_snake_case)]
#![allow(incomplete_features)]
// Catch documentation errors caused by code changes.
#![deny(rustdoc::broken_intra_doc_links)]
// GasCost is used as type parameter
#![feature(adt_const_params)]
#![feature(lazy_cell)]
#![deny(missing_docs)]
//#![deny(unsafe_code)] Allowed now until we find a
// better way to handle downcasting from Operation into it's variants.
#![allow(clippy::upper_case_acronyms)] // Too pedantic
#![allow(clippy::let_and_return)]
#[macro_use]
pub mod macros;
#[macro_use]
pub mod error;
#[macro_use]
pub mod bytecode;
pub mod constants;
pub mod evm_types;
pub mod forks;
pub mod geth_types;
/// L2 system contracts
pub mod l2_predeployed;
pub mod l2_types;
pub mod sign_types;
pub mod state_db;
pub mod utils;
use crate::evm_types::{Gas, GasCost, OpcodeId, ProgramCounter};
pub use bytecode::Bytecode;
pub use error::Error;
use ethers_core::types;
pub use ethers_core::{
abi::ethereum_types::{BigEndianHash, U512},
types::{
transaction::{
eip2930::{AccessList, AccessListItem},
response::Transaction,
},
Address, Block, Bytes, Signature, H160, H256, H64, U256, U64,
},
};
use serde::{de, Deserialize, Deserializer, Serialize};
use std::{
collections::{HashMap, HashSet},
fmt,
fmt::{Display, Formatter},
str::FromStr,
sync::LazyLock,
};
#[cfg(feature = "enable-memory")]
use crate::evm_types::Memory;
#[cfg(feature = "enable-stack")]
use crate::evm_types::Stack;
#[cfg(feature = "enable-storage")]
use crate::evm_types::Storage;
/// Main Block type
pub type EthBlock = Block<Transaction>;
/// Used for FFI with Golang. Bytes in golang will be serialized as base64 by default.
pub mod base64 {
use base64::{decode, encode};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// serialize bytes as base64
pub fn serialize<S>(data: &[u8], s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
String::serialize(&encode(data), s)
}
/// deserialize base64 to bytes
pub fn deserialize<'de, D>(d: D) -> Result<Vec<u8>, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(d)?;
decode(s.as_bytes()).map_err(serde::de::Error::custom)
}
}
/// Trait used to convert a type to a [`Word`].
pub trait ToWord {
/// Convert the type to a [`Word`].
fn to_word(&self) -> Word;
}
/// Trait used to convert a type to a [`Address`].
pub trait ToAddress {
/// Convert the type to a [`Address`].
fn to_address(&self) -> Address;
}
/// Trait used do convert a scalar value to a 32 byte array in big endian.
pub trait ToBigEndian {
/// Convert the value to a 32 byte array in big endian.
fn to_be_bytes(&self) -> [u8; 32];
}
/// Trait used to convert a scalar value to a 32 byte array in little endian.
pub trait ToLittleEndian {
/// Convert the value to a 32 byte array in little endian.
fn to_le_bytes(&self) -> [u8; 32];
}
/// Trait used to convert a scalar value to a 16x u16 array in little endian.
pub trait ToU16LittleEndian {
/// Convert the value to a 16x u16 array in little endian.
fn to_le_u16_array(&self) -> [u16; 16];
}
// We use our own declaration of another U256 in order to implement a custom
// deserializer that can parse U256 when returned by structLogs fields in geth
// debug_trace* methods, which don't contain the `0x` prefix.
#[allow(clippy::all)]
mod uint_types {
uint::construct_uint! {
/// 256-bit unsigned integer.
pub struct DebugU256(4);
}
}
pub use uint_types::DebugU256;
impl<'de> Deserialize<'de> for DebugU256 {
fn deserialize<D>(deserializer: D) -> Result<DebugU256, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
DebugU256::from_str(&s).map_err(de::Error::custom)
}
}
impl ToBigEndian for DebugU256 {
/// Encode the value as byte array in big endian.
fn to_be_bytes(&self) -> [u8; 32] {
let mut bytes = [0u8; 32];
self.to_big_endian(&mut bytes);
bytes
}
}
impl ToWord for DebugU256 {
fn to_word(&self) -> Word {
U256(self.0)
}
}
/// Ethereum Word (256 bits).
pub type Word = U256;
impl ToBigEndian for U256 {
/// Encode the value as byte array in big endian.
fn to_be_bytes(&self) -> [u8; 32] {
let mut bytes = [0u8; 32];
self.to_big_endian(&mut bytes);
bytes
}
}
impl ToLittleEndian for U256 {
/// Encode the value as byte array in little endian.
fn to_le_bytes(&self) -> [u8; 32] {
let mut bytes = [0u8; 32];
self.to_little_endian(&mut bytes);
bytes
}
}
impl ToU16LittleEndian for U256 {
/// Encode the value as 16x u16 array in little endian.
///
/// eg. 0xaabb_ccdd_eeff_0011_2233_4455_6677_8899_bbaa_ddcc_ffee_1100_3322_5544_7766_9988
/// -> [
/// 0x9988, 0x7766, 0x5544, 0x3322, 0x1100, 0xffee, 0xddcc, 0xbbaa,
/// 0x8899, 0x6677, 0x4455, 0x2233, 0x0011, 0xeeff, 0xccdd, 0xaabb,
/// ]
fn to_le_u16_array(&self) -> [u16; 16] {
let mut u16_array: [u16; 16] = [0; 16];
for (idx, u64_cell) in self.0.into_iter().enumerate() {
u16_array[idx * 4] = (u64_cell & 0xffff) as u16;
u16_array[idx * 4 + 1] = ((u64_cell >> 16) & 0xffff) as u16;
u16_array[idx * 4 + 2] = ((u64_cell >> 32) & 0xffff) as u16;
u16_array[idx * 4 + 3] = ((u64_cell >> 48) & 0xffff) as u16;
}
u16_array
}
}
impl ToAddress for U256 {
fn to_address(&self) -> Address {
Address::from_slice(&self.to_be_bytes()[12..])
}
}
/// Ethereum Hash (256 bits).
pub type Hash = types::H256;
impl ToWord for Hash {
fn to_word(&self) -> Word {
Word::from(self.as_bytes())
}
}
impl ToWord for Address {
fn to_word(&self) -> Word {
let mut bytes = [0u8; 32];
bytes[32 - Self::len_bytes()..].copy_from_slice(self.as_bytes());
Word::from(bytes)
}
}
impl ToWord for bool {
fn to_word(&self) -> Word {
if *self {
Word::one()
} else {
Word::zero()
}
}
}
impl ToWord for u64 {
fn to_word(&self) -> Word {
Word::from(*self)
}
}
impl ToWord for u128 {
fn to_word(&self) -> Word {
Word::from(*self)
}
}
impl ToWord for usize {
fn to_word(&self) -> Word {
u64::try_from(*self)
.expect("usize bigger than u64")
.to_word()
}
}
impl ToWord for i32 {
fn to_word(&self) -> Word {
let value = Word::from(self.unsigned_abs() as u64);
if self.is_negative() {
value.overflowing_neg().0
} else {
value
}
}
}
impl ToWord for Word {
fn to_word(&self) -> Word {
*self
}
}
/// Code hash related
/// the empty keccak code hash
pub static KECCAK_CODE_HASH_EMPTY: LazyLock<Hash> = LazyLock::new(|| {
Hash::from_str("0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap()
});
/// the empty poseidon code hash
pub static POSEIDON_CODE_HASH_EMPTY: LazyLock<Hash> = LazyLock::new(|| {
Hash::from_str("0x2098f5fb9e239eab3ceac3f27b81e481dc3124d55ffed523a839ee8446b64864").unwrap()
});
/// Struct used to define the storage proof
#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize)]
pub struct StorageProof {
/// Storage key
pub key: U256,
/// Storage Value
pub value: U256,
/// Storage proof: rlp-encoded trie nodes from root to value.
pub proof: Vec<Bytes>,
}
/// Struct used to define the result of `eth_getProof` call
#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EIP1186ProofResponse {
/// Account address
pub address: Address,
/// The balance of the account
pub balance: U256,
/// The keccak hash of the code of the account
#[serde(default)]
pub keccak_code_hash: H256,
/// The poseidon hash of the code of the account
#[serde(alias = "poseidonCodeHash")]
pub code_hash: H256,
/// Size of the code, i.e. code length
#[serde(default)]
pub code_size: U256,
/// The nonce of the account
pub nonce: U256,
/// SHA3 of the StorageRoot
pub storage_hash: H256,
/// Array of rlp-serialized MerkleTree-Nodes
pub account_proof: Vec<Bytes>,
/// Array of storage-entries as requested
pub storage_proof: Vec<StorageProof>,
}
#[derive(Deserialize)]
#[doc(hidden)]
struct GethExecStepInternal {
pc: ProgramCounter,
op: OpcodeId,
gas: Gas,
#[serde(default)]
refund: Gas,
#[serde(rename = "gasCost")]
gas_cost: GasCost,
depth: u16,
error: Option<GethExecError>,
// stack is in hex 0x prefixed
#[cfg(feature = "enable-stack")]
#[serde(default)]
stack: Vec<DebugU256>,
// memory is in chunks of 32 bytes, in hex
#[cfg(feature = "enable-memory")]
#[serde(default)]
memory: Vec<DebugU256>,
// storage is hex -> hex
#[cfg(feature = "enable-storage")]
#[serde(default)]
storage: HashMap<DebugU256, DebugU256>,
}
/// The execution step type returned by geth RPC debug_trace* methods.
/// Corresponds to `StructLogRes` in `go-ethereum/internal/ethapi/api.go`.
#[derive(Clone, Eq, PartialEq, Serialize)]
#[doc(hidden)]
pub struct GethExecStep {
pub pc: ProgramCounter,
pub op: OpcodeId,
pub gas: Gas,
pub gas_cost: GasCost,
pub refund: Gas,
pub depth: u16,
pub error: Option<GethExecError>,
// stack is in hex 0x prefixed
#[cfg(feature = "enable-stack")]
pub stack: Stack,
// memory is in chunks of 32 bytes, in hex
#[cfg(feature = "enable-memory")]
pub memory: Memory,
// storage is hex -> hex
#[cfg(feature = "enable-storage")]
pub storage: Storage,
}
/// Errors of StructLogger Result from Geth
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum GethExecError {
/// out of gas
OutOfGas,
/// contract creation code storage out of gas
CodeStoreOutOfGas,
/// max call depth exceeded
Depth,
/// insufficient balance for transfer
InsufficientBalance,
/// contract address collision
ContractAddressCollision,
/// execution reverted
ExecutionReverted,
/// max initcode size exceeded
MaxInitCodeSizeExceeded,
/// max code size exceeded
MaxCodeSizeExceeded,
/// invalid jump destination
InvalidJump,
/// write protection
WriteProtection,
/// return data out of bounds
ReturnDataOutOfBounds,
/// gas uint64 overflow
GasUintOverflow,
/// invalid code: must not begin with 0xef
InvalidCode,
/// nonce uint64 overflow
NonceUintOverflow,
/// stack underflow
StackUnderflow {
/// stack length
stack_len: u64,
/// required length
required: u64,
},
/// stack limit reached
StackOverflow {
/// stack length
stack_len: u64,
/// stack limit
limit: u64,
},
/// invalid opcode
InvalidOpcode(OpcodeId),
}
impl GethExecError {
/// Returns the error as a string constant.
pub fn error(self) -> &'static str {
match self {
GethExecError::OutOfGas => "out of gas",
GethExecError::CodeStoreOutOfGas => "contract creation code storage out of gas",
GethExecError::Depth => "max call depth exceeded",
GethExecError::InsufficientBalance => "insufficient balance for transfer",
GethExecError::ContractAddressCollision => "contract address collision",
GethExecError::ExecutionReverted => "execution reverted",
GethExecError::MaxInitCodeSizeExceeded => "max initcode size exceeded",
GethExecError::MaxCodeSizeExceeded => "max code size exceeded",
GethExecError::InvalidJump => "invalid jump destination",
GethExecError::WriteProtection => "write protection",
GethExecError::ReturnDataOutOfBounds => "return data out of bounds",
GethExecError::GasUintOverflow => "gas uint64 overflow",
GethExecError::InvalidCode => "invalid code: must not begin with 0xef",
GethExecError::NonceUintOverflow => "nonce uint64 overflow",
GethExecError::StackUnderflow { .. } => "stack underflow",
GethExecError::StackOverflow { .. } => "stack limit reached",
GethExecError::InvalidOpcode(_) => "invalid opcode",
}
}
/// Returns if the error is related to precheck fail
pub fn is_precheck_failed(&self) -> bool {
matches!(
self,
GethExecError::ContractAddressCollision
| GethExecError::InsufficientBalance
| GethExecError::Depth
| GethExecError::NonceUintOverflow
)
}
}
impl Display for GethExecError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
GethExecError::StackUnderflow {
stack_len,
required,
} => {
write!(f, "stack underflow ({stack_len} <=> {required})")
}
GethExecError::StackOverflow { stack_len, limit } => {
write!(f, "stack limit reached {stack_len} ({limit})")
}
GethExecError::InvalidOpcode(op) => {
write!(f, "invalid opcode: {op}")
}
_ => f.write_str(self.error()),
}
}
}
impl FromStr for GethExecError {
type Err = ();
fn from_str(v: &str) -> Result<Self, Self::Err> {
static STACK_UNDERFLOW_RE: LazyLock<regex::Regex> =
LazyLock::new(|| regex::Regex::new(r"^stack underflow \((\d+) <=> (\d+)\)$").unwrap());
static STACK_OVERFLOW_RE: LazyLock<regex::Regex> =
LazyLock::new(|| regex::Regex::new(r"^stack limit reached (\d+) \((\d+)\)$").unwrap());
let e = match v {
"out of gas" => GethExecError::OutOfGas,
"contract creation code storage out of gas" => GethExecError::CodeStoreOutOfGas,
"max call depth exceeded" => GethExecError::Depth,
"insufficient balance for transfer" => GethExecError::InsufficientBalance,
"contract address collision" => GethExecError::ContractAddressCollision,
"execution reverted" => GethExecError::ExecutionReverted,
"max initcode size exceeded" => GethExecError::MaxInitCodeSizeExceeded,
"max code size exceeded" => GethExecError::MaxCodeSizeExceeded,
"invalid jump destination" => GethExecError::InvalidJump,
"write protection" => GethExecError::WriteProtection,
"return data out of bounds" => GethExecError::ReturnDataOutOfBounds,
"gas uint64 overflow" => GethExecError::GasUintOverflow,
"invalid code: must not begin with 0xef" => GethExecError::InvalidCode,
"nonce uint64 overflow" => GethExecError::NonceUintOverflow,
_ if v.starts_with("stack underflow") => {
let caps = STACK_UNDERFLOW_RE.captures(v).unwrap();
let stack_len = caps.get(1).unwrap().as_str().parse::<u64>().unwrap();
let required = caps.get(2).unwrap().as_str().parse::<u64>().unwrap();
GethExecError::StackUnderflow {
stack_len,
required,
}
}
_ if v.starts_with("stack limit reached") => {
let caps = STACK_OVERFLOW_RE.captures(v).unwrap();
let stack_len = caps.get(1).unwrap().as_str().parse::<u64>().unwrap();
let limit = caps.get(2).unwrap().as_str().parse::<u64>().unwrap();
GethExecError::StackOverflow { stack_len, limit }
}
_ if v.starts_with("invalid opcode") => v
.strip_prefix("invalid opcode: ")
.map(|s| OpcodeId::from_str(s).unwrap())
.map(GethExecError::InvalidOpcode)
.unwrap(),
_ => {
log::warn!("unknown geth error: {}", v);
return Err(());
}
};
Ok(e)
}
}
impl Serialize for GethExecError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
// We serialize the error as a string constant.
let e = match self {
GethExecError::StackUnderflow {
stack_len,
required,
} => format!("stack underflow ({stack_len} <=> {required})"),
GethExecError::StackOverflow { stack_len, limit } => {
format!("stack limit reached {stack_len} ({limit})")
}
GethExecError::InvalidOpcode(op) => format!("invalid opcode: {op}"),
_ => self.error().to_string(),
};
serializer.serialize_str(&e)
}
}
impl<'de> Deserialize<'de> for GethExecError {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct GethExecErrorVisitor;
impl<'de> de::Visitor<'de> for GethExecErrorVisitor {
type Value = GethExecError;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
write!(formatter, "a geth struct logger error string constant")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
v.parse()
.map_err(|_| E::invalid_value(de::Unexpected::Str(v), &self))
}
}
deserializer.deserialize_str(GethExecErrorVisitor)
}
}
// Wrapper over u8 that provides formats the byte in hex for [`fmt::Debug`].
pub(crate) struct DebugByte(pub(crate) u8);
impl fmt::Debug for DebugByte {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("{:02x}", self.0))
}
}
// Wrapper over Word reference that provides formats the word in hex for
// [`fmt::Debug`].
pub(crate) struct DebugWord<'a>(pub(crate) &'a Word);
impl<'a> fmt::Debug for DebugWord<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("0x{:x}", self.0))
}
}
impl fmt::Debug for GethExecStep {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut f = f.debug_struct("Step");
f.field("pc", &format_args!("0x{:04x}", self.pc.0))
.field("op", &self.op)
.field("gas", &format_args!("{}", self.gas.0))
.field("gas_cost", &format_args!("{}", self.gas_cost.0))
.field("refund", &format_args!("{}", self.refund.0))
.field("depth", &self.depth)
.field("error", &self.error);
#[cfg(feature = "enable-stack")]
f.field("stack", &self.stack);
#[cfg(feature = "enable-memory")]
f.field("memory", &self.memory);
#[cfg(feature = "enable-storage")]
f.field("storage", &self.storage);
f.finish()
}
}
impl<'de> Deserialize<'de> for GethExecStep {
fn deserialize<D>(deserializer: D) -> Result<GethExecStep, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = GethExecStepInternal::deserialize(deserializer)?;
Ok(Self {
pc: s.pc,
op: s.op,
gas: s.gas,
refund: s.refund,
gas_cost: s.gas_cost,
depth: s.depth,
error: s.error,
#[cfg(feature = "enable-stack")]
stack: Stack(s.stack.iter().map(|dw| dw.to_word()).collect::<Vec<Word>>()),
#[cfg(feature = "enable-memory")]
memory: Memory::from(
s.memory
.iter()
.map(|dw| dw.to_word())
.collect::<Vec<Word>>(),
),
#[cfg(feature = "enable-storage")]
storage: Storage(
s.storage
.iter()
.map(|(k, v)| (k.to_word(), v.to_word()))
.collect(),
),
})
}
}
/// Helper type built to deal with the weird `result` field added between
/// `GethExecutionTrace`s in `debug_traceBlockByHash` and
/// `debug_traceBlockByNumber` Geth JSON-RPC calls.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
#[doc(hidden)]
pub struct ResultGethExecTraces(pub Vec<ResultGethExecTrace>);
/// Helper type built to deal with the weird `result` field added between
/// `GethExecutionTrace`s in `debug_traceBlockByHash` and
/// `debug_traceBlockByNumber` Geth JSON-RPC calls.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
#[doc(hidden)]
pub struct ResultGethExecTrace {
pub result: GethExecTrace,
}
/// The execution trace type returned by geth RPC debug_trace* methods.
/// Corresponds to `ExecutionResult` in `go-ethereum/internal/ethapi/api.go`.
/// The deserialization truncates the memory of each step in `struct_logs` to
/// the memory size before the expansion, so that it corresponds to the memory
/// before the step is executed.
#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct GethExecTrace {
/// L1 fee
#[serde(default)]
pub l1_fee: u64,
/// Used gas
pub gas: Gas,
/// True when the transaction has failed.
pub failed: bool,
/// Return value of execution which is a hex encoded byte array
#[serde(rename = "returnValue")]
pub return_value: String,
/// Vector of geth execution steps of the trace.
#[serde(rename = "structLogs")]
pub struct_logs: Vec<GethExecStep>,
#[serde(
rename = "accountAfter",
default,
deserialize_with = "parse_account_after"
)]
/// List of accounts' (coinbase etc) status AFTER execution
/// Only viable for scroll mode
pub account_after: Vec<crate::l2_types::AccountTrace>,
/// prestate trace
pub prestate: HashMap<Address, GethPrestateTrace>,
/// call trace
#[serde(rename = "callTrace")]
pub call_trace: GethCallTrace,
}
fn parse_account_after<'de, D>(d: D) -> Result<Vec<crate::l2_types::AccountTrace>, D::Error>
where
D: Deserializer<'de>,
{
Deserialize::deserialize(d).map(|x: Option<_>| x.unwrap_or_default())
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
#[doc(hidden)]
pub struct ResultGethPrestateTraces(pub Vec<ResultGethPrestateTrace>);
#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
#[doc(hidden)]
pub struct ResultGethPrestateTrace {
#[serde(rename = "txHash", default)]
pub tx_hash: H256,
pub result: HashMap<Address, GethPrestateTrace>,
}
/// The prestate trace returned by geth RPC debug_trace* methods.
#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct GethPrestateTrace {
/// balance
pub balance: Option<U256>,
/// nonce
pub nonce: Option<u64>,
/// code
pub code: Option<Bytes>,
/// storage
pub storage: Option<HashMap<U256, U256>>,
}
/// The call trace returned by geth RPC debug_trace* methods.
/// using callTracer
#[derive(Deserialize, Serialize, Clone, Debug, Eq, PartialEq)]
pub struct GethCallTrace {
#[serde(default)]
calls: Vec<GethCallTrace>,
error: Option<String>,
from: Address,
// gas: U256,
#[serde(rename = "gasUsed")]
gas_used: U256,
// input: Bytes,
output: Option<Bytes>,
to: Option<Address>,
#[serde(rename = "type")]
call_type: String,
// value: U256,
}
/// Flattened Call Trace
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FlatGethCallTrace {
// error: Option<String>,
/// from
pub from: Address,
// gas: U256,
/// gas used
pub gas_used: U256,
// input: Bytes,
/// is callee code empty
pub is_callee_code_empty: bool,
/// to
pub to: Option<Address>,
/// call type
pub call_type: OpcodeId,
// value: U256,
}
impl GethCallTrace {
fn is_precheck_failed(&self) -> bool {
self.error
.as_ref()
.and_then(|e| e.parse::<GethExecError>().ok())
.map(|e| e.is_precheck_failed())
.unwrap_or(false)
}
/// generate the call_is_success vec
pub fn gen_call_is_success(&self, mut call_is_success: Vec<bool>) -> Vec<bool> {
// ignore the call if precheck failed
// https://github.com/ethereum/go-ethereum/issues/21438
if self.is_precheck_failed() {
return call_is_success;
}
if self.error.as_deref() == Some(GethExecError::InsufficientBalance.error()) {
return call_is_success;
}
if self.error.as_deref() == Some(GethExecError::Depth.error()) {
return call_is_success;
}
if self.error.as_deref() == Some(GethExecError::NonceUintOverflow.error()) {
return call_is_success;
}
call_is_success.push(self.error.is_none());
for call in &self.calls {
call_is_success = call.gen_call_is_success(call_is_success);
}
call_is_success
}
/// flatten the call trace as it is.
pub fn flatten_trace(
&self,
prestate: &HashMap<Address, GethPrestateTrace>,
) -> Vec<FlatGethCallTrace> {
let mut trace = vec![];
// store the code that created in this tx, which is not include in prestate
let mut created = HashSet::new();
self.flatten_trace_inner(prestate, &mut trace, &mut created);
trace
}
fn flatten_trace_inner(
&self,
prestate: &HashMap<Address, GethPrestateTrace>,
trace: &mut Vec<FlatGethCallTrace>,
created: &mut HashSet<Address>,
) {
// ignore the call if precheck failed
// https://github.com/ethereum/go-ethereum/issues/21438
if self.is_precheck_failed() {
return;
}
let call_type = OpcodeId::from_str(&self.call_type).unwrap();
let is_callee_code_empty = self
.to
.as_ref()
.map(|addr| {
!created.contains(addr)
&& prestate
.get(addr)
.unwrap()
.code
.as_ref()
.unwrap()
.is_empty()
})
.unwrap_or(false);
trace.push(FlatGethCallTrace {
from: self.from,
to: self.to,
is_callee_code_empty,
gas_used: self.gas_used,
call_type,
});
for call in &self.calls {
call.flatten_trace_inner(prestate, trace, created);
}
let has_output = self.output.as_ref().map(|x| !x.is_empty()).unwrap_or(false);
if call_type.is_create() && has_output {
created.insert(self.to.unwrap());
}
}
}
#[macro_export]
/// Create an [`Address`] from a hex string. Panics on invalid input.
macro_rules! address {
($addr_hex:expr) => {{
use std::str::FromStr;
$crate::Address::from_str(&$addr_hex).expect("invalid hex Address")
}};
}
#[macro_export]
/// Create a [`Word`] from a hex string. Panics on invalid input.
macro_rules! word {
($word_hex:expr) => {
$crate::Word::from_str_radix(&$word_hex, 16).expect("invalid hex Word")
};
}
#[macro_export]
/// Create a [`Word`] to [`Word`] HashMap from pairs of hex strings. Panics on
/// invalid input.
macro_rules! word_map {
() => {
std::collections::HashMap::new()
};
($($key_hex:expr => $value_hex:expr),*) => {
{
std::collections::HashMap::from_iter([(
$(word!($key_hex), word!($value_hex)),*
)])
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::evm_types::opcode_ids::OpcodeId;
#[cfg(feature = "enable-memory")]
use crate::evm_types::memory::Memory;
#[cfg(feature = "enable-stack")]
use crate::evm_types::stack::Stack;
#[test]
fn test_to_u16_array() {
assert_eq!(
U256::from_str("0xaabbccddeeff00112233445566778899bbaaddccffee11003322554477669988")
.unwrap()
.to_le_u16_array(),
[
0x9988, 0x7766, 0x5544, 0x3322, 0x1100, 0xffee, 0xddcc, 0xbbaa, 0x8899, 0x6677,
0x4455, 0x2233, 0x0011, 0xeeff, 0xccdd, 0xaabb
]
);
}
#[test]
fn deserialize_geth_exec_trace2() {
let trace_json = r#"
{
"gas": 26809,
"failed": false,
"returnValue": "",
"structLogs": [
{
"pc": 0,
"op": "PUSH1",
"gas": 22705,
"gasCost": 3,
"refund": 0,
"depth": 1,
"stack": []
},
{
"pc": 163,
"op": "SLOAD",
"gas": 5217,
"gasCost": 2100,
"refund": 0,
"depth": 1,
"stack": [
"0x1003e2d2",
"0x2a",
"0x0"
],
"storage": {
"0000000000000000000000000000000000000000000000000000000000000000": "000000000000000000000000000000000000000000000000000000000000006f"
},
"memory": [
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000080"
]
},
{
"pc": 189,
"op": "KECCAK256",
"gas": 178805,
"gasCost": 42,
"refund": 0,
"depth": 1,
"stack": [
"0x3635c9adc5dea00000",
"0x40",
"0x0"
],
"memory": [
"000000000000000000000000b8f67472dcc25589672a61905f7fd63f09e5d470",
"0000000000000000000000000000000000000000000000000000000000000000",
"00000000000000000000000000000000000000000000000000000000000000a0",
"0000000000000000000000000000000000000000000000000000000000000000",
"00000000000000000000000000000000000000000000003635c9adc5dea00000",
"00000000000000000000000000000000000000000000003635c9adc5dea00000"
]
}
],
"prestate": {},
"callTrace": {
"calls": [],
"error": null,
"from": "0x000000000000000000000000000000000cafe001",
"to": null,
"gasUsed": "0x0",
"type": "CALL",
"output": "0x00"
}
}
"#;
let trace: GethExecTrace =
serde_json::from_str(trace_json).expect("json-deserialize GethExecTrace");
assert_eq!(
trace,
GethExecTrace {
l1_fee: 0,
gas: Gas(26809),
failed: false,
return_value: "".to_owned(),
account_after: Vec::new(),
struct_logs: vec![
GethExecStep {
pc: ProgramCounter(0),