-
Notifications
You must be signed in to change notification settings - Fork 533
/
tracer.go
418 lines (344 loc) · 9.35 KB
/
tracer.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
package structtracer
import (
"errors"
"fmt"
"math/big"
"sync"
"github.com/0xPolygon/polygon-edge/helper/hex"
"github.com/0xPolygon/polygon-edge/state/runtime"
"github.com/0xPolygon/polygon-edge/state/runtime/evm"
"github.com/0xPolygon/polygon-edge/state/runtime/tracer"
"github.com/0xPolygon/polygon-edge/types"
)
type Config struct {
EnableMemory bool // enable memory capture
EnableStack bool // enable stack capture
EnableStorage bool // enable storage capture
EnableReturnData bool // enable return data capture
}
type StructLog struct {
Pc uint64 `json:"pc"`
Op string `json:"op"`
Gas uint64 `json:"gas"`
GasCost uint64 `json:"gasCost"`
Memory []byte `json:"memory,omitempty"`
MemorySize int `json:"memSize"`
Stack []*big.Int `json:"stack"`
ReturnData []byte `json:"returnData,omitempty"`
Storage map[types.Hash]types.Hash `json:"storage"`
Depth int `json:"depth"`
RefundCounter uint64 `json:"refund"`
Err error `json:"err"`
}
func (l *StructLog) ErrorString() string {
if l.Err != nil {
return l.Err.Error()
}
return ""
}
type StructTracer struct {
Config Config
cancelLock sync.RWMutex
reason error
interrupt bool
logs []StructLog
gasLimit uint64
consumedGas uint64
output []byte
err error
storage []map[types.Address]map[types.Hash]types.Hash
currentMemory []([]byte)
currentStack []([]*big.Int)
}
func NewStructTracer(config Config) *StructTracer {
storage := make([](map[types.Address]map[types.Hash]types.Hash), 1)
storage[0] = make(map[types.Address]map[types.Hash]types.Hash)
return &StructTracer{
Config: config,
cancelLock: sync.RWMutex{},
storage: storage,
currentMemory: make([]([]byte), 1),
currentStack: make([]([]*big.Int), 1),
}
}
func (t *StructTracer) Cancel(err error) {
t.cancelLock.Lock()
defer t.cancelLock.Unlock()
t.reason = err
t.interrupt = true
}
func (t *StructTracer) cancelled() bool {
t.cancelLock.RLock()
defer t.cancelLock.RUnlock()
return t.interrupt
}
func (t *StructTracer) Clear() {
t.reason = nil
t.interrupt = false
t.logs = t.logs[:0]
t.gasLimit = 0
t.consumedGas = 0
t.output = t.output[:0]
t.err = nil
t.storage = make([](map[types.Address]map[types.Hash]types.Hash), 1)
t.storage[0] = make(map[types.Address]map[types.Hash]types.Hash)
t.currentMemory = make([]([]byte), 1)
t.currentStack = make([]([]*big.Int), 1)
}
func (t *StructTracer) TxStart(gasLimit uint64) {
t.gasLimit = gasLimit
}
func (t *StructTracer) TxEnd(gasLeft uint64) {
t.consumedGas = t.gasLimit - gasLeft
}
func (t *StructTracer) CallStart(
depth int,
from, to types.Address,
callType int,
gas uint64,
value *big.Int,
input []byte,
) {
}
func (t *StructTracer) CallEnd(
depth int,
output []byte,
err error,
) {
if depth == 1 {
t.output = output
t.err = err
}
}
func (t *StructTracer) CaptureState(
memory []byte,
stack []*big.Int,
opCode int,
contractAddress types.Address,
sp int,
host tracer.RuntimeHost,
state tracer.VMState,
) {
if t.cancelled() {
state.Halt()
return
}
t.captureMemory(memory, opCode)
t.captureStack(stack, sp, opCode)
t.captureStorage(
stack,
opCode,
contractAddress,
sp,
host,
)
}
func (t *StructTracer) captureMemory(
memory []byte,
opCode int,
) {
if !t.Config.EnableMemory {
return
}
// always allocate new space to get new reference
currentMemory := make([]byte, len(memory))
copy(currentMemory, memory)
t.currentMemory[len(t.currentMemory)-1] = currentMemory
if opCode == evm.CALL || opCode == evm.STATICCALL {
t.currentMemory = append(t.currentMemory, make([]byte, len(memory)))
}
}
func (t *StructTracer) captureStack(
stack []*big.Int,
sp int,
opCode int,
) {
if !t.Config.EnableStack {
return
}
currentStack := make([]*big.Int, sp)
for i, v := range stack {
if i >= sp {
break
}
currentStack[i] = new(big.Int).Set(v)
}
t.currentStack[len(t.currentStack)-1] = currentStack
if opCode == evm.CALL || opCode == evm.STATICCALL {
t.currentStack = append(t.currentStack, make([]*big.Int, sp))
}
}
func (t *StructTracer) captureStorage(
stack []*big.Int,
opCode int,
contractAddress types.Address,
sp int,
host tracer.RuntimeHost,
) {
if opCode == evm.CALL || opCode == evm.STATICCALL {
t.storage = append(t.storage, make(map[types.Address]map[types.Hash]types.Hash))
}
if !t.Config.EnableStorage || (opCode != evm.SLOAD && opCode != evm.SSTORE) {
return
}
storage := &t.storage[len(t.storage)-1]
_, initialized := (*storage)[contractAddress]
switch opCode {
case evm.SLOAD:
if sp < 1 {
return
}
if !initialized {
(*storage)[contractAddress] = make(map[types.Hash]types.Hash)
}
slot := types.BytesToHash(stack[sp-1].Bytes())
value := host.GetStorage(contractAddress, slot)
(*storage)[contractAddress][slot] = value
case evm.SSTORE:
if sp < 2 {
return
}
if !initialized {
(*storage)[contractAddress] = make(map[types.Hash]types.Hash)
}
slot := types.BytesToHash(stack[sp-1].Bytes())
value := types.BytesToHash(stack[sp-2].Bytes())
(*storage)[contractAddress][slot] = value
}
}
func (t *StructTracer) ExecuteState(
contractAddress types.Address,
ip uint64,
opCode string,
availableGas uint64,
cost uint64,
lastReturnData []byte,
depth int,
err error,
host tracer.RuntimeHost,
) {
var (
memory []byte
memorySize int
stack []*big.Int
returnData []byte
storage map[types.Hash]types.Hash
)
if t.Config.EnableMemory {
if opCode == evm.OpCode(evm.CALL).String() || opCode == evm.OpCode(evm.STATICCALL).String() {
t.currentMemory = t.currentMemory[:len(t.currentMemory)-1]
}
memorySize = len(t.currentMemory[len(t.currentMemory)-1])
memory = make([]byte, memorySize)
copy(memory, t.currentMemory[len(t.currentMemory)-1])
}
if t.Config.EnableStack {
if opCode == evm.OpCode(evm.CALL).String() || opCode == evm.OpCode(evm.STATICCALL).String() {
t.currentStack = t.currentStack[:len(t.currentStack)-1]
}
stack = make([]*big.Int, len(t.currentStack[len(t.currentStack)-1]))
for i, v := range t.currentStack[len(t.currentStack)-1] {
stack[i] = new(big.Int).Set(v)
}
}
if t.Config.EnableReturnData {
returnData = make([]byte, len(lastReturnData))
copy(returnData, lastReturnData)
}
if t.Config.EnableStorage {
if opCode == evm.OpCode(evm.CALL).String() || opCode == evm.OpCode(evm.STATICCALL).String() {
t.storage = t.storage[:len(t.storage)-1]
}
contractStorage, ok := t.storage[len(t.storage)-1][contractAddress]
if ok {
storage = make(map[types.Hash]types.Hash, len(contractStorage))
for k, v := range contractStorage {
storage[k] = v
}
}
}
t.logs = append(
t.logs,
StructLog{
Pc: ip,
Op: opCode,
Gas: availableGas,
GasCost: cost,
Memory: memory,
MemorySize: memorySize,
Stack: stack,
ReturnData: returnData,
Storage: storage,
Depth: depth,
RefundCounter: host.GetRefund(),
Err: err,
},
)
}
type StructTraceResult struct {
Failed bool `json:"failed"`
Gas uint64 `json:"gas"`
ReturnValue string `json:"returnValue"`
StructLogs []StructLogRes `json:"structLogs"`
}
type StructLogRes struct {
Pc uint64 `json:"pc"`
Op string `json:"op"`
Gas uint64 `json:"gas"`
GasCost uint64 `json:"gasCost"`
Depth int `json:"depth"`
Error string `json:"error,omitempty"`
Stack []string `json:"stack"`
Memory []string `json:"memory"`
Storage map[string]string `json:"storage"`
RefundCounter uint64 `json:"refund,omitempty"`
}
func (t *StructTracer) GetResult() (interface{}, error) {
if t.reason != nil {
return nil, t.reason
}
var returnValue string
if t.err != nil && !errors.Is(t.err, runtime.ErrExecutionReverted) {
returnValue = ""
} else {
returnValue = fmt.Sprintf("%x", t.output)
}
return &StructTraceResult{
Failed: t.err != nil,
Gas: t.consumedGas,
ReturnValue: returnValue,
StructLogs: formatStructLogs(t.logs),
}, nil
}
func formatStructLogs(originalLogs []StructLog) []StructLogRes {
res := make([]StructLogRes, len(originalLogs))
for index, log := range originalLogs {
res[index] = StructLogRes{
Pc: log.Pc,
Op: log.Op,
Gas: log.Gas,
GasCost: log.GasCost,
Depth: log.Depth,
Error: log.ErrorString(),
RefundCounter: log.RefundCounter,
}
res[index].Stack = make([]string, len(log.Stack))
for i, value := range log.Stack {
res[index].Stack[i] = hex.EncodeBig(value)
}
res[index].Memory = make([]string, 0, (len(log.Memory)+31)/32)
if log.Memory != nil {
for i := 0; i+32 <= len(log.Memory); i += 32 {
res[index].Memory = append(
res[index].Memory,
hex.EncodeToString(log.Memory[i:i+32]),
)
}
}
res[index].Storage = make(map[string]string)
for key, value := range log.Storage {
res[index].Storage[hex.EncodeToString(key.Bytes())] = hex.EncodeToString(value.Bytes())
}
}
return res
}