-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathtrace_adhoc.go
1249 lines (1166 loc) · 38.3 KB
/
trace_adhoc.go
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
package jsonrpc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math"
"strings"
"github.com/holiman/uint256"
"github.com/ledgerwatch/log/v3"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/hexutility"
"github.com/ledgerwatch/erigon-lib/kv"
types2 "github.com/ledgerwatch/erigon-lib/types"
"github.com/ledgerwatch/erigon/common"
"github.com/ledgerwatch/erigon/common/hexutil"
math2 "github.com/ledgerwatch/erigon/common/math"
"github.com/ledgerwatch/erigon/core"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/state"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/core/types/accounts"
"github.com/ledgerwatch/erigon/core/vm"
"github.com/ledgerwatch/erigon/rpc"
"github.com/ledgerwatch/erigon/turbo/rpchelper"
"github.com/ledgerwatch/erigon/turbo/shards"
"github.com/ledgerwatch/erigon/turbo/transactions"
)
const (
CALL = "call"
CALLCODE = "callcode"
DELEGATECALL = "delegatecall"
STATICCALL = "staticcall"
CREATE = "create"
SUICIDE = "suicide"
REWARD = "reward"
TraceTypeTrace = "trace"
TraceTypeStateDiff = "stateDiff"
TraceTypeVmTrace = "vmTrace"
)
// TraceCallParam (see SendTxArgs -- this allows optional prams plus don't use MixedcaseAddress
type TraceCallParam struct {
From *libcommon.Address `json:"from"`
To *libcommon.Address `json:"to"`
Gas *hexutil.Uint64 `json:"gas"`
GasPrice *hexutil.Big `json:"gasPrice"`
MaxPriorityFeePerGas *hexutil.Big `json:"maxPriorityFeePerGas"`
MaxFeePerGas *hexutil.Big `json:"maxFeePerGas"`
MaxFeePerDataGas *hexutil.Big `json:"maxFeePerDataGas"`
Value *hexutil.Big `json:"value"`
Data hexutility.Bytes `json:"data"`
AccessList *types2.AccessList `json:"accessList"`
txHash *libcommon.Hash
traceTypes []string
}
// TraceCallResult is the response to `trace_call` method
type TraceCallResult struct {
Output hexutility.Bytes `json:"output"`
StateDiff map[libcommon.Address]*StateDiffAccount `json:"stateDiff"`
Trace []*ParityTrace `json:"trace"`
VmTrace *VmTrace `json:"vmTrace"`
TransactionHash *libcommon.Hash `json:"transactionHash,omitempty"`
}
// StateDiffAccount is the part of `trace_call` response that is under "stateDiff" tag
type StateDiffAccount struct {
Balance interface{} `json:"balance"` // Can be either string "=" or mapping "*" => {"from": "hex", "to": "hex"}
Code interface{} `json:"code"`
Nonce interface{} `json:"nonce"`
Storage map[libcommon.Hash]map[string]interface{} `json:"storage"`
}
type StateDiffBalance struct {
From *hexutil.Big `json:"from"`
To *hexutil.Big `json:"to"`
}
type StateDiffCode struct {
From hexutility.Bytes `json:"from"`
To hexutility.Bytes `json:"to"`
}
type StateDiffNonce struct {
From hexutil.Uint64 `json:"from"`
To hexutil.Uint64 `json:"to"`
}
type StateDiffStorage struct {
From libcommon.Hash `json:"from"`
To libcommon.Hash `json:"to"`
}
// VmTrace is the part of `trace_call` response that is under "vmTrace" tag
type VmTrace struct {
Code hexutility.Bytes `json:"code"`
Ops []*VmTraceOp `json:"ops"`
}
// VmTraceOp is one element of the vmTrace ops trace
type VmTraceOp struct {
Cost int `json:"cost"`
Ex *VmTraceEx `json:"ex"`
Pc int `json:"pc"`
Sub *VmTrace `json:"sub"`
Op string `json:"op,omitempty"`
Idx string `json:"idx,omitempty"`
}
type VmTraceEx struct {
Mem *VmTraceMem `json:"mem"`
Push []string `json:"push"`
Store *VmTraceStore `json:"store"`
Used int `json:"used"`
}
type VmTraceMem struct {
Data string `json:"data"`
Off int `json:"off"`
}
type VmTraceStore struct {
Key string `json:"key"`
Val string `json:"val"`
}
// ToMessage converts CallArgs to the Message type used by the core evm
func (args *TraceCallParam) ToMessage(globalGasCap uint64, baseFee *uint256.Int) (types.Message, error) {
// Set sender address or use zero address if none specified.
var addr libcommon.Address
if args.From != nil {
addr = *args.From
}
// Set default gas & gas price if none were set
gas := globalGasCap
if gas == 0 {
gas = uint64(math.MaxUint64 / 2)
}
if args.Gas != nil {
gas = uint64(*args.Gas)
}
if globalGasCap != 0 && globalGasCap < gas {
log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
gas = globalGasCap
}
var (
gasPrice *uint256.Int
gasFeeCap *uint256.Int
gasTipCap *uint256.Int
maxFeePerDataGas *uint256.Int
)
if baseFee == nil {
// If there's no basefee, then it must be a non-1559 execution
gasPrice = new(uint256.Int)
if args.GasPrice != nil {
overflow := gasPrice.SetFromBig(args.GasPrice.ToInt())
if overflow {
return types.Message{}, fmt.Errorf("args.GasPrice higher than 2^256-1")
}
}
gasFeeCap, gasTipCap = gasPrice, gasPrice
} else {
// A basefee is provided, necessitating 1559-type execution
if args.GasPrice != nil {
var overflow bool
// User specified the legacy gas field, convert to 1559 gas typing
gasPrice, overflow = uint256.FromBig(args.GasPrice.ToInt())
if overflow {
return types.Message{}, fmt.Errorf("args.GasPrice higher than 2^256-1")
}
gasFeeCap, gasTipCap = gasPrice, gasPrice
} else {
// User specified 1559 gas feilds (or none), use those
gasFeeCap = new(uint256.Int)
if args.MaxFeePerGas != nil {
overflow := gasFeeCap.SetFromBig(args.MaxFeePerGas.ToInt())
if overflow {
return types.Message{}, fmt.Errorf("args.GasPrice higher than 2^256-1")
}
}
gasTipCap = new(uint256.Int)
if args.MaxPriorityFeePerGas != nil {
overflow := gasTipCap.SetFromBig(args.MaxPriorityFeePerGas.ToInt())
if overflow {
return types.Message{}, fmt.Errorf("args.GasPrice higher than 2^256-1")
}
}
// Backfill the legacy gasPrice for EVM execution, unless we're all zeroes
gasPrice = new(uint256.Int)
if !gasFeeCap.IsZero() || !gasTipCap.IsZero() {
gasPrice = math2.U256Min(new(uint256.Int).Add(gasTipCap, baseFee), gasFeeCap)
} else {
// This means gasFeeCap == 0, gasTipCap == 0
gasPrice.Set(baseFee)
gasFeeCap, gasTipCap = gasPrice, gasPrice
}
}
if args.MaxFeePerDataGas != nil {
maxFeePerDataGas.SetFromBig(args.MaxFeePerDataGas.ToInt())
}
}
value := new(uint256.Int)
if args.Value != nil {
overflow := value.SetFromBig(args.Value.ToInt())
if overflow {
return types.Message{}, fmt.Errorf("args.Value higher than 2^256-1")
}
}
var data []byte
if args.Data != nil {
data = args.Data
}
var accessList types2.AccessList
if args.AccessList != nil {
accessList = *args.AccessList
}
msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, gasFeeCap, gasTipCap, data, accessList, false /* checkNonce */, false /* isFree */, maxFeePerDataGas)
return msg, nil
}
// OpenEthereum-style tracer
type OeTracer struct {
r *TraceCallResult
traceAddr []int
traceStack []*ParityTrace
precompile bool // Whether the last CaptureStart was called with `precompile = true`
compat bool // Bug for bug compatibility mode
lastVmOp *VmTraceOp
lastOp vm.OpCode
lastMemOff uint64
lastMemLen uint64
memOffStack []uint64
memLenStack []uint64
lastOffStack *VmTraceOp
vmOpStack []*VmTraceOp // Stack of vmTrace operations as call depth increases
idx []string // Prefix for the "idx" inside operations, for easier navigation
}
func (ot *OeTracer) CaptureTxStart(gasLimit uint64) {}
func (ot *OeTracer) CaptureTxEnd(restGas uint64) {}
func (ot *OeTracer) captureStartOrEnter(deep bool, typ vm.OpCode, from libcommon.Address, to libcommon.Address, precompile bool, create bool, input []byte, gas uint64, value *uint256.Int, code []byte) {
//fmt.Printf("captureStartOrEnter deep %t, typ %s, from %x, to %x, create %t, input %x, gas %d, value %d, precompile %t\n", deep, typ.String(), from, to, create, input, gas, value, precompile)
if ot.r.VmTrace != nil {
var vmTrace *VmTrace
if deep {
var vmT *VmTrace
if len(ot.vmOpStack) > 0 {
vmT = ot.vmOpStack[len(ot.vmOpStack)-1].Sub
} else {
vmT = ot.r.VmTrace
}
if !ot.compat {
ot.idx = append(ot.idx, fmt.Sprintf("%d-", len(vmT.Ops)-1))
}
}
if ot.lastVmOp != nil {
vmTrace = &VmTrace{Ops: []*VmTraceOp{}}
ot.lastVmOp.Sub = vmTrace
ot.vmOpStack = append(ot.vmOpStack, ot.lastVmOp)
} else {
vmTrace = ot.r.VmTrace
}
if create {
vmTrace.Code = common.CopyBytes(input)
if ot.lastVmOp != nil {
ot.lastVmOp.Cost += int(gas)
}
} else {
vmTrace.Code = code
}
}
if precompile && deep && (value == nil || value.IsZero()) {
ot.precompile = true
return
}
if gas > 500000000 {
gas = 500000001 - (0x8000000000000000 - gas)
}
trace := &ParityTrace{}
if create {
trResult := &CreateTraceResult{}
trace.Type = CREATE
trResult.Address = new(libcommon.Address)
copy(trResult.Address[:], to.Bytes())
trace.Result = trResult
} else {
trace.Result = &TraceResult{}
trace.Type = CALL
}
if deep {
topTrace := ot.traceStack[len(ot.traceStack)-1]
traceIdx := topTrace.Subtraces
ot.traceAddr = append(ot.traceAddr, traceIdx)
topTrace.Subtraces++
if typ == vm.DELEGATECALL {
switch action := topTrace.Action.(type) {
case *CreateTraceAction:
value, _ = uint256.FromBig(action.Value.ToInt())
case *CallTraceAction:
value, _ = uint256.FromBig(action.Value.ToInt())
}
}
if typ == vm.STATICCALL {
value = uint256.NewInt(0)
}
}
trace.TraceAddress = make([]int, len(ot.traceAddr))
copy(trace.TraceAddress, ot.traceAddr)
if create {
action := CreateTraceAction{}
action.From = from
action.Gas.ToInt().SetUint64(gas)
action.Init = common.CopyBytes(input)
action.Value.ToInt().Set(value.ToBig())
trace.Action = &action
} else if typ == vm.SELFDESTRUCT {
trace.Type = SUICIDE
trace.Result = nil
action := &SuicideTraceAction{}
action.Address = from
action.RefundAddress = to
action.Balance.ToInt().Set(value.ToBig())
trace.Action = action
} else {
action := CallTraceAction{}
switch typ {
case vm.CALL:
action.CallType = CALL
case vm.CALLCODE:
action.CallType = CALLCODE
case vm.DELEGATECALL:
action.CallType = DELEGATECALL
case vm.STATICCALL:
action.CallType = STATICCALL
}
action.From = from
action.To = to
action.Gas.ToInt().SetUint64(gas)
action.Input = common.CopyBytes(input)
action.Value.ToInt().Set(value.ToBig())
trace.Action = &action
}
ot.r.Trace = append(ot.r.Trace, trace)
ot.traceStack = append(ot.traceStack, trace)
}
func (ot *OeTracer) CaptureStart(env vm.VMInterface, from libcommon.Address, to libcommon.Address, precompile bool, create bool, input []byte, gas uint64, value *uint256.Int, code []byte) {
ot.captureStartOrEnter(false /* deep */, vm.CALL, from, to, precompile, create, input, gas, value, code)
}
func (ot *OeTracer) CaptureEnter(typ vm.OpCode, from libcommon.Address, to libcommon.Address, precompile bool, create bool, input []byte, gas uint64, value *uint256.Int, code []byte) {
ot.captureStartOrEnter(true /* deep */, typ, from, to, precompile, create, input, gas, value, code)
}
func (ot *OeTracer) captureEndOrExit(deep bool, output []byte, usedGas uint64, err error) {
if ot.r.VmTrace != nil {
if len(ot.vmOpStack) > 0 {
ot.lastOffStack = ot.vmOpStack[len(ot.vmOpStack)-1]
ot.vmOpStack = ot.vmOpStack[:len(ot.vmOpStack)-1]
}
if !ot.compat && deep {
ot.idx = ot.idx[:len(ot.idx)-1]
}
if deep {
ot.lastMemOff = ot.memOffStack[len(ot.memOffStack)-1]
ot.memOffStack = ot.memOffStack[:len(ot.memOffStack)-1]
ot.lastMemLen = ot.memLenStack[len(ot.memLenStack)-1]
ot.memLenStack = ot.memLenStack[:len(ot.memLenStack)-1]
}
}
if ot.precompile {
ot.precompile = false
return
}
if !deep {
ot.r.Output = common.CopyBytes(output)
}
ignoreError := false
topTrace := ot.traceStack[len(ot.traceStack)-1]
if ot.compat {
ignoreError = !deep && topTrace.Type == CREATE
}
if err != nil && !ignoreError {
if err == vm.ErrExecutionReverted {
topTrace.Error = "Reverted"
switch topTrace.Type {
case CALL:
topTrace.Result.(*TraceResult).GasUsed = new(hexutil.Big)
topTrace.Result.(*TraceResult).GasUsed.ToInt().SetUint64(usedGas)
topTrace.Result.(*TraceResult).Output = common.CopyBytes(output)
case CREATE:
topTrace.Result.(*CreateTraceResult).GasUsed = new(hexutil.Big)
topTrace.Result.(*CreateTraceResult).GasUsed.ToInt().SetUint64(usedGas)
topTrace.Result.(*CreateTraceResult).Code = common.CopyBytes(output)
}
} else {
topTrace.Result = nil
topTrace.Error = err.Error()
}
} else {
if len(output) > 0 {
switch topTrace.Type {
case CALL:
topTrace.Result.(*TraceResult).Output = common.CopyBytes(output)
case CREATE:
topTrace.Result.(*CreateTraceResult).Code = common.CopyBytes(output)
}
}
switch topTrace.Type {
case CALL:
topTrace.Result.(*TraceResult).GasUsed = new(hexutil.Big)
topTrace.Result.(*TraceResult).GasUsed.ToInt().SetUint64(usedGas)
case CREATE:
topTrace.Result.(*CreateTraceResult).GasUsed = new(hexutil.Big)
topTrace.Result.(*CreateTraceResult).GasUsed.ToInt().SetUint64(usedGas)
}
}
ot.traceStack = ot.traceStack[:len(ot.traceStack)-1]
if deep {
ot.traceAddr = ot.traceAddr[:len(ot.traceAddr)-1]
}
}
func (ot *OeTracer) CaptureEnd(output []byte, usedGas uint64, err error) {
ot.captureEndOrExit(false /* deep */, output, usedGas, err)
}
func (ot *OeTracer) CaptureExit(output []byte, usedGas uint64, err error) {
ot.captureEndOrExit(true /* deep */, output, usedGas, err)
}
func (ot *OeTracer) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, opDepth int, err error) {
memory := scope.Memory
st := scope.Stack
if ot.r.VmTrace != nil {
var vmTrace *VmTrace
if len(ot.vmOpStack) > 0 {
vmTrace = ot.vmOpStack[len(ot.vmOpStack)-1].Sub
} else {
vmTrace = ot.r.VmTrace
}
if ot.lastVmOp != nil && ot.lastVmOp.Ex != nil {
// Set the "push" of the last operation
var showStack int
switch {
case ot.lastOp >= vm.PUSH1 && ot.lastOp <= vm.PUSH32:
showStack = 1
case ot.lastOp >= vm.SWAP1 && ot.lastOp <= vm.SWAP16:
showStack = int(ot.lastOp-vm.SWAP1) + 2
case ot.lastOp >= vm.DUP1 && ot.lastOp <= vm.DUP16:
showStack = int(ot.lastOp-vm.DUP1) + 2
}
switch ot.lastOp {
case vm.CALLDATALOAD, vm.SLOAD, vm.MLOAD, vm.CALLDATASIZE, vm.LT, vm.GT, vm.DIV, vm.SDIV, vm.SAR, vm.AND, vm.EQ, vm.CALLVALUE, vm.ISZERO,
vm.ADD, vm.EXP, vm.CALLER, vm.KECCAK256, vm.SUB, vm.ADDRESS, vm.GAS, vm.MUL, vm.RETURNDATASIZE, vm.NOT, vm.SHR, vm.SHL,
vm.EXTCODESIZE, vm.SLT, vm.OR, vm.NUMBER, vm.PC, vm.TIMESTAMP, vm.BALANCE, vm.SELFBALANCE, vm.MULMOD, vm.ADDMOD, vm.BASEFEE,
vm.BLOCKHASH, vm.BYTE, vm.XOR, vm.ORIGIN, vm.CODESIZE, vm.MOD, vm.SIGNEXTEND, vm.GASLIMIT, vm.DIFFICULTY, vm.SGT, vm.GASPRICE,
vm.MSIZE, vm.EXTCODEHASH, vm.SMOD, vm.CHAINID, vm.COINBASE:
showStack = 1
}
for i := showStack - 1; i >= 0; i-- {
if st.Len() > i {
ot.lastVmOp.Ex.Push = append(ot.lastVmOp.Ex.Push, st.Back(i).String())
}
}
// Set the "mem" of the last operation
var setMem bool
switch ot.lastOp {
case vm.MSTORE, vm.MSTORE8, vm.MLOAD, vm.RETURNDATACOPY, vm.CALLDATACOPY, vm.CODECOPY:
setMem = true
}
if setMem && ot.lastMemLen > 0 {
cpy := memory.GetCopy(int64(ot.lastMemOff), int64(ot.lastMemLen))
if len(cpy) == 0 {
cpy = make([]byte, ot.lastMemLen)
}
ot.lastVmOp.Ex.Mem = &VmTraceMem{Data: fmt.Sprintf("0x%0x", cpy), Off: int(ot.lastMemOff)}
}
}
if ot.lastOffStack != nil {
ot.lastOffStack.Ex.Used = int(gas)
if st.Len() > 0 {
ot.lastOffStack.Ex.Push = []string{st.Back(0).String()}
} else {
ot.lastOffStack.Ex.Push = []string{}
}
if ot.lastMemLen > 0 && memory != nil {
cpy := memory.GetCopy(int64(ot.lastMemOff), int64(ot.lastMemLen))
if len(cpy) == 0 {
cpy = make([]byte, ot.lastMemLen)
}
ot.lastOffStack.Ex.Mem = &VmTraceMem{Data: fmt.Sprintf("0x%0x", cpy), Off: int(ot.lastMemOff)}
}
ot.lastOffStack = nil
}
if ot.lastOp == vm.STOP && op == vm.STOP && len(ot.vmOpStack) == 0 {
// Looks like OE is "optimising away" the second STOP
return
}
ot.lastVmOp = &VmTraceOp{Ex: &VmTraceEx{}}
vmTrace.Ops = append(vmTrace.Ops, ot.lastVmOp)
if !ot.compat {
var sb strings.Builder
sb.Grow(len(ot.idx))
for _, idx := range ot.idx {
sb.WriteString(idx)
}
ot.lastVmOp.Idx = fmt.Sprintf("%s%d", sb.String(), len(vmTrace.Ops)-1)
}
ot.lastOp = op
ot.lastVmOp.Cost = int(cost)
ot.lastVmOp.Pc = int(pc)
ot.lastVmOp.Ex.Push = []string{}
ot.lastVmOp.Ex.Used = int(gas) - int(cost)
if !ot.compat {
ot.lastVmOp.Op = op.String()
}
switch op {
case vm.MSTORE, vm.MLOAD:
if st.Len() > 0 {
ot.lastMemOff = st.Back(0).Uint64()
ot.lastMemLen = 32
}
case vm.MSTORE8:
if st.Len() > 0 {
ot.lastMemOff = st.Back(0).Uint64()
ot.lastMemLen = 1
}
case vm.RETURNDATACOPY, vm.CALLDATACOPY, vm.CODECOPY:
if st.Len() > 2 {
ot.lastMemOff = st.Back(0).Uint64()
ot.lastMemLen = st.Back(2).Uint64()
}
case vm.STATICCALL, vm.DELEGATECALL:
if st.Len() > 5 {
ot.memOffStack = append(ot.memOffStack, st.Back(4).Uint64())
ot.memLenStack = append(ot.memLenStack, st.Back(5).Uint64())
}
case vm.CALL, vm.CALLCODE:
if st.Len() > 6 {
ot.memOffStack = append(ot.memOffStack, st.Back(5).Uint64())
ot.memLenStack = append(ot.memLenStack, st.Back(6).Uint64())
}
case vm.CREATE, vm.CREATE2, vm.SELFDESTRUCT:
// Effectively disable memory output
ot.memOffStack = append(ot.memOffStack, 0)
ot.memLenStack = append(ot.memLenStack, 0)
case vm.SSTORE:
if st.Len() > 1 {
ot.lastVmOp.Ex.Store = &VmTraceStore{Key: st.Back(0).String(), Val: st.Back(1).String()}
}
}
if ot.lastVmOp.Ex.Used < 0 {
ot.lastVmOp.Ex = nil
}
}
}
func (ot *OeTracer) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, opDepth int, err error) {
}
// Implements core/state/StateWriter to provide state diffs
type StateDiff struct {
sdMap map[libcommon.Address]*StateDiffAccount
}
func (sd *StateDiff) UpdateAccountData(address libcommon.Address, original, account *accounts.Account) error {
if _, ok := sd.sdMap[address]; !ok {
sd.sdMap[address] = &StateDiffAccount{Storage: make(map[libcommon.Hash]map[string]interface{})}
}
return nil
}
func (sd *StateDiff) UpdateAccountCode(address libcommon.Address, incarnation uint64, codeHash libcommon.Hash, code []byte) error {
if _, ok := sd.sdMap[address]; !ok {
sd.sdMap[address] = &StateDiffAccount{Storage: make(map[libcommon.Hash]map[string]interface{})}
}
return nil
}
func (sd *StateDiff) DeleteAccount(address libcommon.Address, original *accounts.Account) error {
if _, ok := sd.sdMap[address]; !ok {
sd.sdMap[address] = &StateDiffAccount{Storage: make(map[libcommon.Hash]map[string]interface{})}
}
return nil
}
func (sd *StateDiff) WriteAccountStorage(address libcommon.Address, incarnation uint64, key *libcommon.Hash, original, value *uint256.Int) error {
if *original == *value {
return nil
}
accountDiff := sd.sdMap[address]
if accountDiff == nil {
accountDiff = &StateDiffAccount{Storage: make(map[libcommon.Hash]map[string]interface{})}
sd.sdMap[address] = accountDiff
}
m := make(map[string]interface{})
m["*"] = &StateDiffStorage{From: libcommon.BytesToHash(original.Bytes()), To: libcommon.BytesToHash(value.Bytes())}
accountDiff.Storage[*key] = m
return nil
}
func (sd *StateDiff) CreateContract(address libcommon.Address) error {
if _, ok := sd.sdMap[address]; !ok {
sd.sdMap[address] = &StateDiffAccount{Storage: make(map[libcommon.Hash]map[string]interface{})}
}
return nil
}
// CompareStates uses the addresses accumulated in the sdMap and compares balances, nonces, and codes of the accounts, and fills the rest of the sdMap
func (sd *StateDiff) CompareStates(initialIbs, ibs *state.IntraBlockState) {
var toRemove []libcommon.Address
for addr, accountDiff := range sd.sdMap {
initialExist := initialIbs.Exist(addr)
exist := ibs.Exist(addr)
if initialExist {
if exist {
var allEqual = len(accountDiff.Storage) == 0
fromBalance := initialIbs.GetBalance(addr).ToBig()
toBalance := ibs.GetBalance(addr).ToBig()
if fromBalance.Cmp(toBalance) == 0 {
accountDiff.Balance = "="
} else {
m := make(map[string]*StateDiffBalance)
m["*"] = &StateDiffBalance{From: (*hexutil.Big)(fromBalance), To: (*hexutil.Big)(toBalance)}
accountDiff.Balance = m
allEqual = false
}
fromCode := initialIbs.GetCode(addr)
toCode := ibs.GetCode(addr)
if bytes.Equal(fromCode, toCode) {
accountDiff.Code = "="
} else {
m := make(map[string]*StateDiffCode)
m["*"] = &StateDiffCode{From: fromCode, To: toCode}
accountDiff.Code = m
allEqual = false
}
fromNonce := initialIbs.GetNonce(addr)
toNonce := ibs.GetNonce(addr)
if fromNonce == toNonce {
accountDiff.Nonce = "="
} else {
m := make(map[string]*StateDiffNonce)
m["*"] = &StateDiffNonce{From: hexutil.Uint64(fromNonce), To: hexutil.Uint64(toNonce)}
accountDiff.Nonce = m
allEqual = false
}
if allEqual {
toRemove = append(toRemove, addr)
}
} else {
{
m := make(map[string]*hexutil.Big)
m["-"] = (*hexutil.Big)(initialIbs.GetBalance(addr).ToBig())
accountDiff.Balance = m
}
{
m := make(map[string]hexutility.Bytes)
m["-"] = initialIbs.GetCode(addr)
accountDiff.Code = m
}
{
m := make(map[string]hexutil.Uint64)
m["-"] = hexutil.Uint64(initialIbs.GetNonce(addr))
accountDiff.Nonce = m
}
}
} else if exist {
{
m := make(map[string]*hexutil.Big)
m["+"] = (*hexutil.Big)(ibs.GetBalance(addr).ToBig())
accountDiff.Balance = m
}
{
m := make(map[string]hexutility.Bytes)
m["+"] = ibs.GetCode(addr)
accountDiff.Code = m
}
{
m := make(map[string]hexutil.Uint64)
m["+"] = hexutil.Uint64(ibs.GetNonce(addr))
accountDiff.Nonce = m
}
// Transform storage
for _, sm := range accountDiff.Storage {
str := sm["*"].(*StateDiffStorage)
delete(sm, "*")
sm["+"] = &str.To
}
} else {
toRemove = append(toRemove, addr)
}
}
for _, addr := range toRemove {
delete(sd.sdMap, addr)
}
}
func (api *TraceAPIImpl) ReplayTransaction(ctx context.Context, txHash libcommon.Hash, traceTypes []string, gasBailOut *bool) (*TraceCallResult, error) {
if gasBailOut == nil {
gasBailOut = new(bool) // false by default
}
tx, err := api.kv.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
chainConfig, err := api.chainConfig(tx)
if err != nil {
return nil, err
}
blockNum, ok, err := api.txnLookup(ctx, tx, txHash)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
// Private API returns 0 if transaction is not found.
if blockNum == 0 && chainConfig.Bor != nil {
blockNumPtr, err := rawdb.ReadBorTxLookupEntry(tx, txHash)
if err != nil {
return nil, err
}
if blockNumPtr == nil {
return nil, nil
}
blockNum = *blockNumPtr
}
block, err := api.blockByNumberWithSenders(ctx, tx, blockNum)
if err != nil {
return nil, err
}
if block == nil {
return nil, nil
}
var txnIndex uint64
for i, transaction := range block.Transactions() {
if transaction.Hash() == txHash {
txnIndex = uint64(i)
break
}
}
signer := types.MakeSigner(chainConfig, blockNum, block.Time())
// Returns an array of trace arrays, one trace array for each transaction
traces, _, err := api.callManyTransactions(ctx, tx, block, traceTypes, int(txnIndex), *gasBailOut, signer, chainConfig)
if err != nil {
return nil, err
}
var traceTypeTrace, traceTypeStateDiff, traceTypeVmTrace bool
for _, traceType := range traceTypes {
switch traceType {
case TraceTypeTrace:
traceTypeTrace = true
case TraceTypeStateDiff:
traceTypeStateDiff = true
case TraceTypeVmTrace:
traceTypeVmTrace = true
default:
return nil, fmt.Errorf("unrecognized trace type: %s", traceType)
}
}
result := &TraceCallResult{}
for txno, trace := range traces {
// We're only looking for a specific transaction
if txno == int(txnIndex) {
result.Output = trace.Output
if traceTypeTrace {
result.Trace = trace.Trace
}
if traceTypeStateDiff {
result.StateDiff = trace.StateDiff
}
if traceTypeVmTrace {
result.VmTrace = trace.VmTrace
}
return trace, nil
}
}
return result, nil
}
func (api *TraceAPIImpl) ReplayBlockTransactions(ctx context.Context, blockNrOrHash rpc.BlockNumberOrHash, traceTypes []string, gasBailOut *bool) ([]*TraceCallResult, error) {
if gasBailOut == nil {
gasBailOut = new(bool) // false by default
}
tx, err := api.kv.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
chainConfig, err := api.chainConfig(tx)
if err != nil {
return nil, err
}
blockNumber, blockHash, _, err := rpchelper.GetBlockNumber(blockNrOrHash, tx, api.filters)
if err != nil {
return nil, err
}
// Extract transactions from block
block, bErr := api.blockWithSenders(ctx, tx, blockHash, blockNumber)
if bErr != nil {
return nil, bErr
}
if block == nil {
return nil, fmt.Errorf("could not find block %d", blockNumber)
}
var traceTypeTrace, traceTypeStateDiff, traceTypeVmTrace bool
for _, traceType := range traceTypes {
switch traceType {
case TraceTypeTrace:
traceTypeTrace = true
case TraceTypeStateDiff:
traceTypeStateDiff = true
case TraceTypeVmTrace:
traceTypeVmTrace = true
default:
return nil, fmt.Errorf("unrecognized trace type: %s", traceType)
}
}
signer := types.MakeSigner(chainConfig, blockNumber, block.Time())
// Returns an array of trace arrays, one trace array for each transaction
traces, _, err := api.callManyTransactions(ctx, tx, block, traceTypes, -1 /* all tx indices */, *gasBailOut, signer, chainConfig)
if err != nil {
return nil, err
}
result := make([]*TraceCallResult, len(traces))
for i, trace := range traces {
tr := &TraceCallResult{}
tr.Output = trace.Output
if traceTypeTrace {
tr.Trace = trace.Trace
} else {
tr.Trace = []*ParityTrace{}
}
if traceTypeStateDiff {
tr.StateDiff = trace.StateDiff
}
if traceTypeVmTrace {
tr.VmTrace = trace.VmTrace
}
result[i] = tr
txhash := block.Transactions()[i].Hash()
tr.TransactionHash = &txhash
}
return result, nil
}
// Call implements trace_call.
func (api *TraceAPIImpl) Call(ctx context.Context, args TraceCallParam, traceTypes []string, blockNrOrHash *rpc.BlockNumberOrHash) (*TraceCallResult, error) {
tx, err := api.kv.BeginRo(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
chainConfig, err := api.chainConfig(tx)
if err != nil {
return nil, err
}
engine := api.engine()
if blockNrOrHash == nil {
var num = rpc.LatestBlockNumber
blockNrOrHash = &rpc.BlockNumberOrHash{BlockNumber: &num}
}
blockNumber, hash, _, err := rpchelper.GetBlockNumber(*blockNrOrHash, tx, api.filters)
if err != nil {
return nil, err
}
stateReader, err := rpchelper.CreateStateReader(ctx, tx, *blockNrOrHash, 0, api.filters, api.stateCache, api.historyV3(tx), chainConfig.ChainName)
if err != nil {
return nil, err
}
ibs := state.New(stateReader)
block, err := api.blockWithSenders(ctx, tx, hash, blockNumber)
if err != nil {
return nil, err
}
if block == nil {
return nil, fmt.Errorf("block %d(%x) not found", blockNumber, hash)
}
header := block.Header()
// Setup context so it may be cancelled the call has completed
// or, in case of unmetered gas, setup a context with a timeout.
var cancel context.CancelFunc
if api.evmCallTimeout > 0 {
ctx, cancel = context.WithTimeout(ctx, api.evmCallTimeout)
} else {
ctx, cancel = context.WithCancel(ctx)
}
// Make sure the context is cancelled when the call has completed
// this makes sure resources are cleaned up.
defer cancel()
traceResult := &TraceCallResult{Trace: []*ParityTrace{}}
var traceTypeTrace, traceTypeStateDiff, traceTypeVmTrace bool
for _, traceType := range traceTypes {
switch traceType {
case TraceTypeTrace:
traceTypeTrace = true
case TraceTypeStateDiff:
traceTypeStateDiff = true
case TraceTypeVmTrace:
traceTypeVmTrace = true
default:
return nil, fmt.Errorf("unrecognized trace type: %s", traceType)
}
}
if traceTypeVmTrace {
traceResult.VmTrace = &VmTrace{Ops: []*VmTraceOp{}}
}
var ot OeTracer
ot.compat = api.compatibility
if traceTypeTrace || traceTypeVmTrace {
ot.r = traceResult
ot.traceAddr = []int{}
}
// Get a new instance of the EVM.
var baseFee *uint256.Int
if header != nil && header.BaseFee != nil {
var overflow bool
baseFee, overflow = uint256.FromBig(header.BaseFee)
if overflow {
return nil, fmt.Errorf("header.BaseFee uint256 overflow")
}
}
msg, err := args.ToMessage(api.gasCap, baseFee)
if err != nil {
return nil, err
}
blockCtx := transactions.NewEVMBlockContext(engine, header, blockNrOrHash.RequireCanonical, tx, api._blockReader)
txCtx := core.NewEVMTxContext(msg)
blockCtx.GasLimit = math.MaxUint64
blockCtx.MaxGasLimit = true
evm := vm.NewEVM(blockCtx, txCtx, ibs, chainConfig, vm.Config{Debug: traceTypeTrace, Tracer: &ot})
// Wait for the context to be done and cancel the evm. Even if the
// EVM has finished, cancelling may be done (repeatedly)
go func() {
<-ctx.Done()
evm.Cancel()
}()
gp := new(core.GasPool).AddGas(msg.Gas()).AddDataGas(msg.DataGas())
var execResult *core.ExecutionResult
ibs.SetTxContext(libcommon.Hash{}, libcommon.Hash{}, 0)
execResult, err = core.ApplyMessage(evm, msg, gp, true /* refunds */, true /* gasBailout */)
if err != nil {
return nil, err
}
traceResult.Output = common.CopyBytes(execResult.ReturnData)
if traceTypeStateDiff {
sdMap := make(map[libcommon.Address]*StateDiffAccount)
traceResult.StateDiff = sdMap
sd := &StateDiff{sdMap: sdMap}
if err = ibs.FinalizeTx(evm.ChainRules(), sd); err != nil {
return nil, err
}
// Create initial IntraBlockState, we will compare it with ibs (IntraBlockState after the transaction)
initialIbs := state.New(stateReader)
sd.CompareStates(initialIbs, ibs)
}
// If the timer caused an abort, return an appropriate error message
if evm.Cancelled() {
return nil, fmt.Errorf("execution aborted (timeout = %v)", api.evmCallTimeout)
}