github.com/theQRL/go-zond@v0.1.1/zond/tracers/logger/logger.go (about) 1 // Copyright 2021 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package logger 18 19 import ( 20 "encoding/hex" 21 "encoding/json" 22 "fmt" 23 "io" 24 "math/big" 25 "strings" 26 "sync/atomic" 27 28 "github.com/holiman/uint256" 29 "github.com/theQRL/go-zond/common" 30 "github.com/theQRL/go-zond/common/hexutil" 31 "github.com/theQRL/go-zond/common/math" 32 "github.com/theQRL/go-zond/core/types" 33 "github.com/theQRL/go-zond/core/vm" 34 "github.com/theQRL/go-zond/params" 35 ) 36 37 // Storage represents a contract's storage. 38 type Storage map[common.Hash]common.Hash 39 40 // Copy duplicates the current storage. 41 func (s Storage) Copy() Storage { 42 cpy := make(Storage, len(s)) 43 for key, value := range s { 44 cpy[key] = value 45 } 46 return cpy 47 } 48 49 // Config are the configuration options for structured logger the EVM 50 type Config struct { 51 EnableMemory bool // enable memory capture 52 DisableStack bool // disable stack capture 53 DisableStorage bool // disable storage capture 54 EnableReturnData bool // enable return data capture 55 Debug bool // print output during capture end 56 Limit int // maximum length of output, but zero means unlimited 57 // Chain overrides, can be used to execute a trace using future fork rules 58 Overrides *params.ChainConfig `json:"overrides,omitempty"` 59 } 60 61 //go:generate go run github.com/fjl/gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go 62 63 // StructLog is emitted to the EVM each cycle and lists information about the current internal state 64 // prior to the execution of the statement. 65 type StructLog struct { 66 Pc uint64 `json:"pc"` 67 Op vm.OpCode `json:"op"` 68 Gas uint64 `json:"gas"` 69 GasCost uint64 `json:"gasCost"` 70 Memory []byte `json:"memory,omitempty"` 71 MemorySize int `json:"memSize"` 72 Stack []uint256.Int `json:"stack"` 73 ReturnData []byte `json:"returnData,omitempty"` 74 Storage map[common.Hash]common.Hash `json:"-"` 75 Depth int `json:"depth"` 76 RefundCounter uint64 `json:"refund"` 77 Err error `json:"-"` 78 } 79 80 // overrides for gencodec 81 type structLogMarshaling struct { 82 Gas math.HexOrDecimal64 83 GasCost math.HexOrDecimal64 84 Memory hexutil.Bytes 85 ReturnData hexutil.Bytes 86 OpName string `json:"opName"` // adds call to OpName() in MarshalJSON 87 ErrorString string `json:"error,omitempty"` // adds call to ErrorString() in MarshalJSON 88 } 89 90 // OpName formats the operand name in a human-readable format. 91 func (s *StructLog) OpName() string { 92 return s.Op.String() 93 } 94 95 // ErrorString formats the log's error as a string. 96 func (s *StructLog) ErrorString() string { 97 if s.Err != nil { 98 return s.Err.Error() 99 } 100 return "" 101 } 102 103 // StructLogger is an EVM state logger and implements EVMLogger. 104 // 105 // StructLogger can capture state based on the given Log configuration and also keeps 106 // a track record of modified storage which is used in reporting snapshots of the 107 // contract their storage. 108 type StructLogger struct { 109 cfg Config 110 env *vm.EVM 111 112 storage map[common.Address]Storage 113 logs []StructLog 114 output []byte 115 err error 116 gasLimit uint64 117 usedGas uint64 118 119 interrupt atomic.Bool // Atomic flag to signal execution interruption 120 reason error // Textual reason for the interruption 121 } 122 123 // NewStructLogger returns a new logger 124 func NewStructLogger(cfg *Config) *StructLogger { 125 logger := &StructLogger{ 126 storage: make(map[common.Address]Storage), 127 } 128 if cfg != nil { 129 logger.cfg = *cfg 130 } 131 return logger 132 } 133 134 // Reset clears the data held by the logger. 135 func (l *StructLogger) Reset() { 136 l.storage = make(map[common.Address]Storage) 137 l.output = make([]byte, 0) 138 l.logs = l.logs[:0] 139 l.err = nil 140 } 141 142 // CaptureStart implements the EVMLogger interface to initialize the tracing operation. 143 func (l *StructLogger) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { 144 l.env = env 145 } 146 147 // CaptureState logs a new structured log message and pushes it out to the environment 148 // 149 // CaptureState also tracks SLOAD/SSTORE ops to track storage change. 150 func (l *StructLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) { 151 // If tracing was interrupted, set the error and stop 152 if l.interrupt.Load() { 153 return 154 } 155 // check if already accumulated the specified number of logs 156 if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) { 157 return 158 } 159 160 memory := scope.Memory 161 stack := scope.Stack 162 contract := scope.Contract 163 // Copy a snapshot of the current memory state to a new buffer 164 var mem []byte 165 if l.cfg.EnableMemory { 166 mem = make([]byte, len(memory.Data())) 167 copy(mem, memory.Data()) 168 } 169 // Copy a snapshot of the current stack state to a new buffer 170 var stck []uint256.Int 171 if !l.cfg.DisableStack { 172 stck = make([]uint256.Int, len(stack.Data())) 173 for i, item := range stack.Data() { 174 stck[i] = item 175 } 176 } 177 stackData := stack.Data() 178 stackLen := len(stackData) 179 // Copy a snapshot of the current storage to a new container 180 var storage Storage 181 if !l.cfg.DisableStorage && (op == vm.SLOAD || op == vm.SSTORE) { 182 // initialise new changed values storage container for this contract 183 // if not present. 184 if l.storage[contract.Address()] == nil { 185 l.storage[contract.Address()] = make(Storage) 186 } 187 // capture SLOAD opcodes and record the read entry in the local storage 188 if op == vm.SLOAD && stackLen >= 1 { 189 var ( 190 address = common.Hash(stackData[stackLen-1].Bytes32()) 191 value = l.env.StateDB.GetState(contract.Address(), address) 192 ) 193 l.storage[contract.Address()][address] = value 194 storage = l.storage[contract.Address()].Copy() 195 } else if op == vm.SSTORE && stackLen >= 2 { 196 // capture SSTORE opcodes and record the written entry in the local storage. 197 var ( 198 value = common.Hash(stackData[stackLen-2].Bytes32()) 199 address = common.Hash(stackData[stackLen-1].Bytes32()) 200 ) 201 l.storage[contract.Address()][address] = value 202 storage = l.storage[contract.Address()].Copy() 203 } 204 } 205 var rdata []byte 206 if l.cfg.EnableReturnData { 207 rdata = make([]byte, len(rData)) 208 copy(rdata, rData) 209 } 210 // create a new snapshot of the EVM. 211 log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, rdata, storage, depth, l.env.StateDB.GetRefund(), err} 212 l.logs = append(l.logs, log) 213 } 214 215 // CaptureFault implements the EVMLogger interface to trace an execution fault 216 // while running an opcode. 217 func (l *StructLogger) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) { 218 } 219 220 // CaptureEnd is called after the call finishes to finalize the tracing. 221 func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, err error) { 222 l.output = output 223 l.err = err 224 if l.cfg.Debug { 225 fmt.Printf("%#x\n", output) 226 if err != nil { 227 fmt.Printf(" error: %v\n", err) 228 } 229 } 230 } 231 232 func (l *StructLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { 233 } 234 235 func (l *StructLogger) CaptureExit(output []byte, gasUsed uint64, err error) { 236 } 237 238 func (l *StructLogger) GetResult() (json.RawMessage, error) { 239 // Tracing aborted 240 if l.reason != nil { 241 return nil, l.reason 242 } 243 failed := l.err != nil 244 returnData := common.CopyBytes(l.output) 245 // Return data when successful and revert reason when reverted, otherwise empty. 246 returnVal := fmt.Sprintf("%x", returnData) 247 if failed && l.err != vm.ErrExecutionReverted { 248 returnVal = "" 249 } 250 return json.Marshal(&ExecutionResult{ 251 Gas: l.usedGas, 252 Failed: failed, 253 ReturnValue: returnVal, 254 StructLogs: formatLogs(l.StructLogs()), 255 }) 256 } 257 258 // Stop terminates execution of the tracer at the first opportune moment. 259 func (l *StructLogger) Stop(err error) { 260 l.reason = err 261 l.interrupt.Store(true) 262 } 263 264 func (l *StructLogger) CaptureTxStart(gasLimit uint64) { 265 l.gasLimit = gasLimit 266 } 267 268 func (l *StructLogger) CaptureTxEnd(restGas uint64) { 269 l.usedGas = l.gasLimit - restGas 270 } 271 272 // StructLogs returns the captured log entries. 273 func (l *StructLogger) StructLogs() []StructLog { return l.logs } 274 275 // Error returns the VM error captured by the trace. 276 func (l *StructLogger) Error() error { return l.err } 277 278 // Output returns the VM return value captured by the trace. 279 func (l *StructLogger) Output() []byte { return l.output } 280 281 // WriteTrace writes a formatted trace to the given writer 282 func WriteTrace(writer io.Writer, logs []StructLog) { 283 for _, log := range logs { 284 fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost) 285 if log.Err != nil { 286 fmt.Fprintf(writer, " ERROR: %v", log.Err) 287 } 288 fmt.Fprintln(writer) 289 290 if len(log.Stack) > 0 { 291 fmt.Fprintln(writer, "Stack:") 292 for i := len(log.Stack) - 1; i >= 0; i-- { 293 fmt.Fprintf(writer, "%08d %s\n", len(log.Stack)-i-1, log.Stack[i].Hex()) 294 } 295 } 296 if len(log.Memory) > 0 { 297 fmt.Fprintln(writer, "Memory:") 298 fmt.Fprint(writer, hex.Dump(log.Memory)) 299 } 300 if len(log.Storage) > 0 { 301 fmt.Fprintln(writer, "Storage:") 302 for h, item := range log.Storage { 303 fmt.Fprintf(writer, "%x: %x\n", h, item) 304 } 305 } 306 if len(log.ReturnData) > 0 { 307 fmt.Fprintln(writer, "ReturnData:") 308 fmt.Fprint(writer, hex.Dump(log.ReturnData)) 309 } 310 fmt.Fprintln(writer) 311 } 312 } 313 314 // WriteLogs writes vm logs in a readable format to the given writer 315 func WriteLogs(writer io.Writer, logs []*types.Log) { 316 for _, log := range logs { 317 fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex) 318 319 for i, topic := range log.Topics { 320 fmt.Fprintf(writer, "%08d %x\n", i, topic) 321 } 322 323 fmt.Fprint(writer, hex.Dump(log.Data)) 324 fmt.Fprintln(writer) 325 } 326 } 327 328 type mdLogger struct { 329 out io.Writer 330 cfg *Config 331 env *vm.EVM 332 } 333 334 // NewMarkdownLogger creates a logger which outputs information in a format adapted 335 // for human readability, and is also a valid markdown table 336 func NewMarkdownLogger(cfg *Config, writer io.Writer) *mdLogger { 337 l := &mdLogger{out: writer, cfg: cfg} 338 if l.cfg == nil { 339 l.cfg = &Config{} 340 } 341 return l 342 } 343 344 func (t *mdLogger) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { 345 t.env = env 346 if !create { 347 fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `%#x`\nGas: `%d`\nValue `%v` wei\n", 348 from.String(), to.String(), 349 input, gas, value) 350 } else { 351 fmt.Fprintf(t.out, "From: `%v`\nCreate at: `%v`\nData: `%#x`\nGas: `%d`\nValue `%v` wei\n", 352 from.String(), to.String(), 353 input, gas, value) 354 } 355 356 fmt.Fprintf(t.out, ` 357 | Pc | Op | Cost | Stack | RStack | Refund | 358 |-------|-------------|------|-----------|-----------|---------| 359 `) 360 } 361 362 // CaptureState also tracks SLOAD/SSTORE ops to track storage change. 363 func (t *mdLogger) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) { 364 stack := scope.Stack 365 fmt.Fprintf(t.out, "| %4d | %10v | %3d |", pc, op, cost) 366 367 if !t.cfg.DisableStack { 368 // format stack 369 var a []string 370 for _, elem := range stack.Data() { 371 a = append(a, elem.Hex()) 372 } 373 b := fmt.Sprintf("[%v]", strings.Join(a, ",")) 374 fmt.Fprintf(t.out, "%10v |", b) 375 } 376 fmt.Fprintf(t.out, "%10v |", t.env.StateDB.GetRefund()) 377 fmt.Fprintln(t.out, "") 378 if err != nil { 379 fmt.Fprintf(t.out, "Error: %v\n", err) 380 } 381 } 382 383 func (t *mdLogger) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) { 384 fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err) 385 } 386 387 func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, err error) { 388 fmt.Fprintf(t.out, "\nOutput: `%#x`\nConsumed gas: `%d`\nError: `%v`\n", 389 output, gasUsed, err) 390 } 391 392 func (t *mdLogger) CaptureEnter(typ vm.OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { 393 } 394 395 func (t *mdLogger) CaptureExit(output []byte, gasUsed uint64, err error) {} 396 397 func (*mdLogger) CaptureTxStart(gasLimit uint64) {} 398 399 func (*mdLogger) CaptureTxEnd(restGas uint64) {} 400 401 // ExecutionResult groups all structured logs emitted by the EVM 402 // while replaying a transaction in debug mode as well as transaction 403 // execution status, the amount of gas used and the return value 404 type ExecutionResult struct { 405 Gas uint64 `json:"gas"` 406 Failed bool `json:"failed"` 407 ReturnValue string `json:"returnValue"` 408 StructLogs []StructLogRes `json:"structLogs"` 409 } 410 411 // StructLogRes stores a structured log emitted by the EVM while replaying a 412 // transaction in debug mode 413 type StructLogRes struct { 414 Pc uint64 `json:"pc"` 415 Op string `json:"op"` 416 Gas uint64 `json:"gas"` 417 GasCost uint64 `json:"gasCost"` 418 Depth int `json:"depth"` 419 Error string `json:"error,omitempty"` 420 Stack *[]string `json:"stack,omitempty"` 421 ReturnData string `json:"returnData,omitempty"` 422 Memory *[]string `json:"memory,omitempty"` 423 Storage *map[string]string `json:"storage,omitempty"` 424 RefundCounter uint64 `json:"refund,omitempty"` 425 } 426 427 // formatLogs formats EVM returned structured logs for json output 428 func formatLogs(logs []StructLog) []StructLogRes { 429 formatted := make([]StructLogRes, len(logs)) 430 for index, trace := range logs { 431 formatted[index] = StructLogRes{ 432 Pc: trace.Pc, 433 Op: trace.Op.String(), 434 Gas: trace.Gas, 435 GasCost: trace.GasCost, 436 Depth: trace.Depth, 437 Error: trace.ErrorString(), 438 RefundCounter: trace.RefundCounter, 439 } 440 if trace.Stack != nil { 441 stack := make([]string, len(trace.Stack)) 442 for i, stackValue := range trace.Stack { 443 stack[i] = stackValue.Hex() 444 } 445 formatted[index].Stack = &stack 446 } 447 if trace.ReturnData != nil && len(trace.ReturnData) > 0 { 448 formatted[index].ReturnData = hexutil.Bytes(trace.ReturnData).String() 449 } 450 if trace.Memory != nil { 451 memory := make([]string, 0, (len(trace.Memory)+31)/32) 452 for i := 0; i+32 <= len(trace.Memory); i += 32 { 453 memory = append(memory, fmt.Sprintf("%x", trace.Memory[i:i+32])) 454 } 455 formatted[index].Memory = &memory 456 } 457 if trace.Storage != nil { 458 storage := make(map[string]string) 459 for i, storageValue := range trace.Storage { 460 storage[fmt.Sprintf("%x", i)] = fmt.Sprintf("%x", storageValue) 461 } 462 formatted[index].Storage = &storage 463 } 464 } 465 return formatted 466 }