gitlab.com/flarenetwork/coreth@v0.1.1/core/vm/logger.go (about) 1 // (c) 2019-2020, Ava Labs, Inc. 2 // 3 // This file is a derived work, based on the go-ethereum library whose original 4 // notices appear below. 5 // 6 // It is distributed under a license compatible with the licensing terms of the 7 // original code from which it is derived. 8 // 9 // Much love to the original authors for their work. 10 // ********** 11 // Copyright 2015 The go-ethereum Authors 12 // This file is part of the go-ethereum library. 13 // 14 // The go-ethereum library is free software: you can redistribute it and/or modify 15 // it under the terms of the GNU Lesser General Public License as published by 16 // the Free Software Foundation, either version 3 of the License, or 17 // (at your option) any later version. 18 // 19 // The go-ethereum library is distributed in the hope that it will be useful, 20 // but WITHOUT ANY WARRANTY; without even the implied warranty of 21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 // GNU Lesser General Public License for more details. 23 // 24 // You should have received a copy of the GNU Lesser General Public License 25 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 26 27 package vm 28 29 import ( 30 "encoding/hex" 31 "fmt" 32 "io" 33 "math/big" 34 "strings" 35 "time" 36 37 "github.com/ethereum/go-ethereum/common" 38 "github.com/ethereum/go-ethereum/common/hexutil" 39 "github.com/ethereum/go-ethereum/common/math" 40 "github.com/holiman/uint256" 41 "gitlab.com/flarenetwork/coreth/core/types" 42 "gitlab.com/flarenetwork/coreth/params" 43 ) 44 45 // Storage represents a contract's storage. 46 type Storage map[common.Hash]common.Hash 47 48 // Copy duplicates the current storage. 49 func (s Storage) Copy() Storage { 50 cpy := make(Storage) 51 for key, value := range s { 52 cpy[key] = value 53 } 54 return cpy 55 } 56 57 // LogConfig are the configuration options for structured logger the EVM 58 type LogConfig struct { 59 DisableMemory bool // disable memory capture 60 DisableStack bool // disable stack capture 61 DisableStorage bool // disable storage capture 62 DisableReturnData bool // disable return data capture 63 Debug bool // print output during capture end 64 Limit int // maximum length of output, but zero means unlimited 65 // Chain overrides, can be used to execute a trace using future fork rules 66 Overrides *params.ChainConfig `json:"overrides,omitempty"` 67 } 68 69 //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go 70 71 // StructLog is emitted to the EVM each cycle and lists information about the current internal state 72 // prior to the execution of the statement. 73 type StructLog struct { 74 Pc uint64 `json:"pc"` 75 Op OpCode `json:"op"` 76 Gas uint64 `json:"gas"` 77 GasCost uint64 `json:"gasCost"` 78 Memory []byte `json:"memory"` 79 MemorySize int `json:"memSize"` 80 Stack []uint256.Int `json:"stack"` 81 ReturnData []byte `json:"returnData"` 82 Storage map[common.Hash]common.Hash `json:"-"` 83 Depth int `json:"depth"` 84 RefundCounter uint64 `json:"refund"` 85 Err error `json:"-"` 86 } 87 88 // overrides for gencodec 89 type structLogMarshaling struct { 90 Gas math.HexOrDecimal64 91 GasCost math.HexOrDecimal64 92 Memory hexutil.Bytes 93 ReturnData hexutil.Bytes 94 OpName string `json:"opName"` // adds call to OpName() in MarshalJSON 95 ErrorString string `json:"error"` // adds call to ErrorString() in MarshalJSON 96 } 97 98 // OpName formats the operand name in a human-readable format. 99 func (s *StructLog) OpName() string { 100 return s.Op.String() 101 } 102 103 // ErrorString formats the log's error as a string. 104 func (s *StructLog) ErrorString() string { 105 if s.Err != nil { 106 return s.Err.Error() 107 } 108 return "" 109 } 110 111 // Tracer is used to collect execution traces from an EVM transaction 112 // execution. CaptureState is called for each step of the VM with the 113 // current VM state. 114 // Note that reference types are actual VM data structures; make copies 115 // if you need to retain them beyond the current call. 116 type Tracer interface { 117 CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) 118 CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) 119 CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) 120 CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) 121 } 122 123 // StructLogger is an EVM state logger and implements Tracer. 124 // 125 // StructLogger can capture state based on the given Log configuration and also keeps 126 // a track record of modified storage which is used in reporting snapshots of the 127 // contract their storage. 128 type StructLogger struct { 129 cfg LogConfig 130 131 storage map[common.Address]Storage 132 logs []StructLog 133 output []byte 134 err error 135 } 136 137 // NewStructLogger returns a new logger 138 func NewStructLogger(cfg *LogConfig) *StructLogger { 139 logger := &StructLogger{ 140 storage: make(map[common.Address]Storage), 141 } 142 if cfg != nil { 143 logger.cfg = *cfg 144 } 145 return logger 146 } 147 148 // Reset clears the data held by the logger. 149 func (l *StructLogger) Reset() { 150 l.storage = make(map[common.Address]Storage) 151 l.output = make([]byte, 0) 152 l.logs = l.logs[:0] 153 l.err = nil 154 } 155 156 // CaptureStart implements the Tracer interface to initialize the tracing operation. 157 func (l *StructLogger) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { 158 } 159 160 // CaptureState logs a new structured log message and pushes it out to the environment 161 // 162 // CaptureState also tracks SLOAD/SSTORE ops to track storage change. 163 func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) { 164 memory := scope.Memory 165 stack := scope.Stack 166 contract := scope.Contract 167 // check if already accumulated the specified number of logs 168 if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) { 169 return 170 } 171 // Copy a snapshot of the current memory state to a new buffer 172 var mem []byte 173 if !l.cfg.DisableMemory { 174 mem = make([]byte, len(memory.Data())) 175 copy(mem, memory.Data()) 176 } 177 // Copy a snapshot of the current stack state to a new buffer 178 var stck []uint256.Int 179 if !l.cfg.DisableStack { 180 stck = make([]uint256.Int, len(stack.Data())) 181 for i, item := range stack.Data() { 182 stck[i] = item 183 } 184 } 185 // Copy a snapshot of the current storage to a new container 186 var storage Storage 187 if !l.cfg.DisableStorage && (op == SLOAD || op == SSTORE) { 188 // initialise new changed values storage container for this contract 189 // if not present. 190 if l.storage[contract.Address()] == nil { 191 l.storage[contract.Address()] = make(Storage) 192 } 193 // capture SLOAD opcodes and record the read entry in the local storage 194 if op == SLOAD && stack.len() >= 1 { 195 var ( 196 address = common.Hash(stack.data[stack.len()-1].Bytes32()) 197 value = env.StateDB.GetState(contract.Address(), address) 198 ) 199 l.storage[contract.Address()][address] = value 200 storage = l.storage[contract.Address()].Copy() 201 } else if op == SSTORE && stack.len() >= 2 { 202 // capture SSTORE opcodes and record the written entry in the local storage. 203 var ( 204 value = common.Hash(stack.data[stack.len()-2].Bytes32()) 205 address = common.Hash(stack.data[stack.len()-1].Bytes32()) 206 ) 207 l.storage[contract.Address()][address] = value 208 storage = l.storage[contract.Address()].Copy() 209 } 210 } 211 var rdata []byte 212 if !l.cfg.DisableReturnData { 213 rdata = make([]byte, len(rData)) 214 copy(rdata, rData) 215 } 216 // create a new snapshot of the EVM. 217 log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, rdata, storage, depth, env.StateDB.GetRefund(), err} 218 l.logs = append(l.logs, log) 219 } 220 221 // CaptureFault implements the Tracer interface to trace an execution fault 222 // while running an opcode. 223 func (l *StructLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) { 224 } 225 226 // CaptureEnd is called after the call finishes to finalize the tracing. 227 func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) { 228 l.output = output 229 l.err = err 230 if l.cfg.Debug { 231 fmt.Printf("0x%x\n", output) 232 if err != nil { 233 fmt.Printf(" error: %v\n", err) 234 } 235 } 236 } 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 } 298 299 // NewMarkdownLogger creates a logger which outputs information in a format adapted 300 // for human readability, and is also a valid markdown table 301 func NewMarkdownLogger(cfg *LogConfig, writer io.Writer) *mdLogger { 302 l := &mdLogger{writer, cfg} 303 if l.cfg == nil { 304 l.cfg = &LogConfig{} 305 } 306 return l 307 } 308 309 func (t *mdLogger) CaptureStart(env *EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { 310 if !create { 311 fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n", 312 from.String(), to.String(), 313 input, gas, value) 314 } else { 315 fmt.Fprintf(t.out, "From: `%v`\nCreate at: `%v`\nData: `0x%x`\nGas: `%d`\nValue `%v` wei\n", 316 from.String(), to.String(), 317 input, gas, value) 318 } 319 320 fmt.Fprintf(t.out, ` 321 | Pc | Op | Cost | Stack | RStack | Refund | 322 |-------|-------------|------|-----------|-----------|---------| 323 `) 324 } 325 326 // CaptureState also tracks SLOAD/SSTORE ops to track storage change. 327 func (t *mdLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, rData []byte, depth int, err error) { 328 stack := scope.Stack 329 fmt.Fprintf(t.out, "| %4d | %10v | %3d |", pc, op, cost) 330 331 if !t.cfg.DisableStack { 332 // format stack 333 var a []string 334 for _, elem := range stack.data { 335 a = append(a, elem.Hex()) 336 } 337 b := fmt.Sprintf("[%v]", strings.Join(a, ",")) 338 fmt.Fprintf(t.out, "%10v |", b) 339 } 340 fmt.Fprintf(t.out, "%10v |", env.StateDB.GetRefund()) 341 fmt.Fprintln(t.out, "") 342 if err != nil { 343 fmt.Fprintf(t.out, "Error: %v\n", err) 344 } 345 } 346 347 func (t *mdLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, scope *ScopeContext, depth int, err error) { 348 fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err) 349 } 350 351 func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) { 352 fmt.Fprintf(t.out, "\nOutput: `0x%x`\nConsumed gas: `%d`\nError: `%v`\n", 353 output, gasUsed, err) 354 }