github.com/haliliceylan/bsc@v1.1.10-0.20220501224556-eb78d644ebcb/core/vm/logger.go (about) 1 // Copyright 2015 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 vm 18 19 import ( 20 "encoding/hex" 21 "fmt" 22 "io" 23 "math/big" 24 "strings" 25 "time" 26 27 "github.com/holiman/uint256" 28 29 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/common/hexutil" 31 "github.com/ethereum/go-ethereum/common/math" 32 "github.com/ethereum/go-ethereum/core/types" 33 "github.com/ethereum/go-ethereum/params" 34 ) 35 36 // Storage represents a contract's storage. 37 type Storage map[common.Hash]common.Hash 38 39 // Copy duplicates the current storage. 40 func (s Storage) Copy() Storage { 41 cpy := make(Storage) 42 for key, value := range s { 43 cpy[key] = value 44 } 45 return cpy 46 } 47 48 // LogConfig are the configuration options for structured logger the EVM 49 type LogConfig struct { 50 EnableMemory bool // enable memory capture 51 DisableStack bool // disable stack capture 52 DisableStorage bool // disable storage capture 53 EnableReturnData bool // enable return data capture 54 Debug bool // print output during capture end 55 Limit int // maximum length of output, but zero means unlimited 56 // Chain overrides, can be used to execute a trace using future fork rules 57 Overrides *params.ChainConfig `json:"overrides,omitempty"` 58 } 59 60 //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go 61 62 // StructLog is emitted to the EVM each cycle and lists information about the current internal state 63 // prior to the execution of the statement. 64 type StructLog struct { 65 Pc uint64 `json:"pc"` 66 Op OpCode `json:"op"` 67 Gas uint64 `json:"gas"` 68 GasCost uint64 `json:"gasCost"` 69 Memory []byte `json:"memory"` 70 MemorySize int `json:"memSize"` 71 Stack []uint256.Int `json:"stack"` 72 ReturnData []byte `json:"returnData"` 73 Storage map[common.Hash]common.Hash `json:"-"` 74 Depth int `json:"depth"` 75 RefundCounter uint64 `json:"refund"` 76 Err error `json:"-"` 77 } 78 79 // overrides for gencodec 80 type structLogMarshaling struct { 81 Gas math.HexOrDecimal64 82 GasCost math.HexOrDecimal64 83 Memory hexutil.Bytes 84 ReturnData hexutil.Bytes 85 OpName string `json:"opName"` // adds call to OpName() in MarshalJSON 86 ErrorString string `json:"error"` // adds call to ErrorString() in MarshalJSON 87 } 88 89 // OpName formats the operand name in a human-readable format. 90 func (s *StructLog) OpName() string { 91 return s.Op.String() 92 } 93 94 // ErrorString formats the log's error as a string. 95 func (s *StructLog) ErrorString() string { 96 if s.Err != nil { 97 return s.Err.Error() 98 } 99 return "" 100 } 101 102 // EVMLogger is used to collect execution traces from an EVM transaction 103 // execution. CaptureState is called for each step of the VM with the 104 // current VM state. 105 // Note that reference types are actual VM data structures; make copies 106 // if you need to retain them beyond the current call. 107 type EVMLogger interface { 108 CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) 109 CaptureState(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) 110 CaptureEnter(typ OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) 111 CaptureExit(output []byte, gasUsed uint64, err error) 112 CaptureFault(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) 113 CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) 114 } 115 116 // StructLogger is an EVM state logger and implements EVMLogger. 117 // 118 // StructLogger can capture state based on the given Log configuration and also keeps 119 // a track record of modified storage which is used in reporting snapshots of the 120 // contract their storage. 121 type StructLogger struct { 122 cfg LogConfig 123 env *EVM 124 125 storage map[common.Address]Storage 126 logs []StructLog 127 output []byte 128 err error 129 } 130 131 // NewStructLogger returns a new logger 132 func NewStructLogger(cfg *LogConfig) *StructLogger { 133 logger := &StructLogger{ 134 storage: make(map[common.Address]Storage), 135 } 136 if cfg != nil { 137 logger.cfg = *cfg 138 } 139 return logger 140 } 141 142 // Reset clears the data held by the logger. 143 func (l *StructLogger) Reset() { 144 l.storage = make(map[common.Address]Storage) 145 l.output = make([]byte, 0) 146 l.logs = l.logs[:0] 147 l.err = nil 148 } 149 150 // CaptureStart implements the EVMLogger interface to initialize the tracing operation. 151 func (l *StructLogger) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { 152 l.env = env 153 } 154 155 // CaptureState logs a new structured log message and pushes it out to the environment 156 // 157 // CaptureState also tracks SLOAD/SSTORE ops to track storage change. 158 func (l *StructLogger) CaptureState(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) { 159 memory := scope.Memory 160 stack := scope.Stack 161 contract := scope.Contract 162 // check if already accumulated the specified number of logs 163 if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) { 164 return 165 } 166 // Copy a snapshot of the current memory state to a new buffer 167 var mem []byte 168 if l.cfg.EnableMemory { 169 mem = make([]byte, len(memory.Data())) 170 copy(mem, memory.Data()) 171 } 172 // Copy a snapshot of the current stack state to a new buffer 173 var stck []uint256.Int 174 if !l.cfg.DisableStack { 175 stck = make([]uint256.Int, len(stack.Data())) 176 for i, item := range stack.Data() { 177 stck[i] = item 178 } 179 } 180 // Copy a snapshot of the current storage to a new container 181 var storage Storage 182 if !l.cfg.DisableStorage && (op == SLOAD || op == SSTORE) { 183 // initialise new changed values storage container for this contract 184 // if not present. 185 if l.storage[contract.Address()] == nil { 186 l.storage[contract.Address()] = make(Storage) 187 } 188 // capture SLOAD opcodes and record the read entry in the local storage 189 if op == SLOAD && stack.len() >= 1 { 190 var ( 191 address = common.Hash(stack.data[stack.len()-1].Bytes32()) 192 value = l.env.StateDB.GetState(contract.Address(), address) 193 ) 194 l.storage[contract.Address()][address] = value 195 storage = l.storage[contract.Address()].Copy() 196 } else if op == SSTORE && stack.len() >= 2 { 197 // capture SSTORE opcodes and record the written entry in the local storage. 198 var ( 199 value = common.Hash(stack.data[stack.len()-2].Bytes32()) 200 address = common.Hash(stack.data[stack.len()-1].Bytes32()) 201 ) 202 l.storage[contract.Address()][address] = value 203 storage = l.storage[contract.Address()].Copy() 204 } 205 } 206 var rdata []byte 207 if l.cfg.EnableReturnData { 208 rdata = make([]byte, len(rData)) 209 copy(rdata, rData) 210 } 211 // create a new snapshot of the EVM. 212 log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, rdata, storage, depth, l.env.StateDB.GetRefund(), err} 213 l.logs = append(l.logs, log) 214 } 215 216 // CaptureFault implements the EVMLogger interface to trace an execution fault 217 // while running an opcode. 218 func (l *StructLogger) CaptureFault(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) { 219 } 220 221 // CaptureEnd is called after the call finishes to finalize the tracing. 222 func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) { 223 l.output = output 224 l.err = err 225 if l.cfg.Debug { 226 fmt.Printf("0x%x\n", output) 227 if err != nil { 228 fmt.Printf(" error: %v\n", err) 229 } 230 } 231 } 232 233 func (l *StructLogger) CaptureEnter(typ OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { 234 } 235 236 func (l *StructLogger) CaptureExit(output []byte, gasUsed uint64, err error) {} 237 238 // StructLogs returns the captured log entries. 239 func (l *StructLogger) StructLogs() []StructLog { return l.logs } 240 241 // Error returns the VM error captured by the trace. 242 func (l *StructLogger) Error() error { return l.err } 243 244 // Output returns the VM return value captured by the trace. 245 func (l *StructLogger) Output() []byte { return l.output } 246 247 // WriteTrace writes a formatted trace to the given writer 248 func WriteTrace(writer io.Writer, logs []StructLog) { 249 for _, log := range logs { 250 fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost) 251 if log.Err != nil { 252 fmt.Fprintf(writer, " ERROR: %v", log.Err) 253 } 254 fmt.Fprintln(writer) 255 256 if len(log.Stack) > 0 { 257 fmt.Fprintln(writer, "Stack:") 258 for i := len(log.Stack) - 1; i >= 0; i-- { 259 fmt.Fprintf(writer, "%08d %s\n", len(log.Stack)-i-1, log.Stack[i].Hex()) 260 } 261 } 262 if len(log.Memory) > 0 { 263 fmt.Fprintln(writer, "Memory:") 264 fmt.Fprint(writer, hex.Dump(log.Memory)) 265 } 266 if len(log.Storage) > 0 { 267 fmt.Fprintln(writer, "Storage:") 268 for h, item := range log.Storage { 269 fmt.Fprintf(writer, "%x: %x\n", h, item) 270 } 271 } 272 if len(log.ReturnData) > 0 { 273 fmt.Fprintln(writer, "ReturnData:") 274 fmt.Fprint(writer, hex.Dump(log.ReturnData)) 275 } 276 fmt.Fprintln(writer) 277 } 278 } 279 280 // WriteLogs writes vm logs in a readable format to the given writer 281 func WriteLogs(writer io.Writer, logs []*types.Log) { 282 for _, log := range logs { 283 fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex) 284 285 for i, topic := range log.Topics { 286 fmt.Fprintf(writer, "%08d %x\n", i, topic) 287 } 288 289 fmt.Fprint(writer, hex.Dump(log.Data)) 290 fmt.Fprintln(writer) 291 } 292 } 293 294 type mdLogger struct { 295 out io.Writer 296 cfg *LogConfig 297 env *EVM 298 } 299 300 // NewMarkdownLogger creates a logger which outputs information in a format adapted 301 // for human readability, and is also a valid markdown table 302 func NewMarkdownLogger(cfg *LogConfig, writer io.Writer) *mdLogger { 303 l := &mdLogger{out: writer, cfg: cfg} 304 if l.cfg == nil { 305 l.cfg = &LogConfig{} 306 } 307 return l 308 } 309 310 func (t *mdLogger) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { 311 t.env = env 312 if !create { 313 fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n", 314 from.String(), to.String(), 315 input, gas, value) 316 } else { 317 fmt.Fprintf(t.out, "From: `%v`\nCreate at: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n", 318 from.String(), to.String(), 319 input, gas, value) 320 } 321 322 fmt.Fprintf(t.out, ` 323 | Pc | Op | Cost | Stack | RStack | Refund | 324 |-------|-------------|------|-----------|-----------|---------| 325 `) 326 } 327 328 // CaptureState also tracks SLOAD/SSTORE ops to track storage change. 329 func (t *mdLogger) CaptureState(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) { 330 stack := scope.Stack 331 fmt.Fprintf(t.out, "| %4d | %10v | %3d |", pc, op, cost) 332 333 if !t.cfg.DisableStack { 334 // format stack 335 var a []string 336 for _, elem := range stack.data { 337 a = append(a, elem.Hex()) 338 } 339 b := fmt.Sprintf("[%v]", strings.Join(a, ",")) 340 fmt.Fprintf(t.out, "%10v |", b) 341 } 342 fmt.Fprintf(t.out, "%10v |", t.env.StateDB.GetRefund()) 343 fmt.Fprintln(t.out, "") 344 if err != nil { 345 fmt.Fprintf(t.out, "Error: %v\n", err) 346 } 347 } 348 349 func (t *mdLogger) CaptureFault(pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) { 350 fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err) 351 } 352 353 func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) { 354 fmt.Fprintf(t.out, "\nOutput: `0x%x`\nConsumed gas: `%d`\nError: `%v`\n", 355 output, gasUsed, err) 356 } 357 358 func (t *mdLogger) CaptureEnter(typ OpCode, from common.Address, to common.Address, input []byte, gas uint64, value *big.Int) { 359 } 360 361 func (t *mdLogger) CaptureExit(output []byte, gasUsed uint64, err error) {}