github.com/klaytn/klaytn@v1.10.2/blockchain/vm/logger.go (about) 1 // Modifications Copyright 2018 The klaytn Authors 2 // Copyright 2015 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // This file is derived from core/vm/logger.go (2018/06/04). 19 // Modified and improved for the klaytn development. 20 21 package vm 22 23 import ( 24 "encoding/hex" 25 "fmt" 26 "io" 27 "math/big" 28 "time" 29 30 "github.com/klaytn/klaytn/blockchain/types" 31 "github.com/klaytn/klaytn/common" 32 "github.com/klaytn/klaytn/common/hexutil" 33 "github.com/klaytn/klaytn/common/math" 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 46 return cpy 47 } 48 49 // LogConfig are the configuration options for structured logger the EVM 50 type LogConfig struct { 51 DisableMemory bool // disable memory capture 52 DisableStack bool // disable stack capture 53 DisableStorage bool // disable storage capture 54 Debug bool // print output during capture end 55 Limit int // maximum length of output, but zero means unlimited 56 } 57 58 //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go 59 60 // StructLog is emitted to the EVM each cycle and lists information about the current internal state 61 // prior to the execution of the statement. 62 type StructLog struct { 63 Pc uint64 `json:"pc"` 64 Op OpCode `json:"op"` 65 Gas uint64 `json:"gas"` 66 GasCost uint64 `json:"gasCost"` 67 Memory []byte `json:"memory"` 68 MemorySize int `json:"memSize"` 69 Stack []*big.Int `json:"stack"` 70 Storage map[common.Hash]common.Hash `json:"-"` 71 Depth int `json:"depth"` 72 RefundCounter uint64 `json:"refund"` 73 Err error `json:"-"` 74 } 75 76 // overrides for gencodec 77 type structLogMarshaling struct { 78 Stack []*math.HexOrDecimal256 79 Gas math.HexOrDecimal64 80 GasCost math.HexOrDecimal64 81 Memory hexutil.Bytes 82 OpName string `json:"opName"` // adds call to OpName() in MarshalJSON 83 ErrorString string `json:"error"` // adds call to ErrorString() in MarshalJSON 84 } 85 86 // OpName formats the operand name in a human-readable format. 87 func (s *StructLog) OpName() string { 88 return s.Op.String() 89 } 90 91 // ErrorString formats the log's error as a string. 92 func (s *StructLog) ErrorString() string { 93 if s.Err != nil { 94 return s.Err.Error() 95 } 96 return "" 97 } 98 99 // Tracer is used to collect execution traces from an EVM transaction 100 // execution. CaptureState is called for each step of the VM with the 101 // current VM state. 102 // Note that reference types are actual VM data structures; make copies 103 // if you need to retain them beyond the current call. 104 type Tracer interface { 105 CaptureStart(from common.Address, to common.Address, call bool, input []byte, gas uint64, value *big.Int) error 106 CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error 107 CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error 108 CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error 109 } 110 111 // StructLogger is an EVM state logger and implements Tracer. 112 // 113 // StructLogger can capture state based on the given Log configuration and also keeps 114 // a track record of modified storage which is used in reporting snapshots of the 115 // contract their storage. 116 type StructLogger struct { 117 cfg LogConfig 118 119 logs []StructLog 120 changedValues map[common.Address]Storage 121 output []byte 122 err error 123 } 124 125 // NewStructLogger returns a new logger 126 func NewStructLogger(cfg *LogConfig) *StructLogger { 127 logger := &StructLogger{ 128 changedValues: make(map[common.Address]Storage), 129 } 130 if cfg != nil { 131 logger.cfg = *cfg 132 } 133 return logger 134 } 135 136 // CaptureStart implements the Tracer interface to initialize the tracing operation. 137 func (l *StructLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error { 138 return nil 139 } 140 141 // CaptureState logs a new structured log message and pushes it out to the environment 142 // 143 // CaptureState also tracks SSTORE ops to track dirty values. 144 func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error { 145 // check if already accumulated the specified number of logs 146 if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) { 147 return ErrTraceLimitReached 148 } 149 150 // initialise new changed values storage container for this contract 151 // if not present. 152 if l.changedValues[contract.Address()] == nil { 153 l.changedValues[contract.Address()] = make(Storage) 154 } 155 156 // capture SSTORE opcodes and determine the changed value and store 157 // it in the local storage container. 158 if op == SSTORE && stack.len() >= 2 { 159 var ( 160 value = common.BigToHash(stack.data[stack.len()-2]) 161 address = common.BigToHash(stack.data[stack.len()-1]) 162 ) 163 l.changedValues[contract.Address()][address] = value 164 } 165 // Copy a snapshot of the current memory state to a new buffer 166 var mem []byte 167 if !l.cfg.DisableMemory { 168 mem = make([]byte, len(memory.Data())) 169 copy(mem, memory.Data()) 170 } 171 // Copy a snapshot of the current stack state to a new buffer 172 var stck []*big.Int 173 if !l.cfg.DisableStack { 174 stck = make([]*big.Int, len(stack.Data())) 175 for i, item := range stack.Data() { 176 stck[i] = new(big.Int).Set(item) 177 } 178 } 179 // Copy a snapshot of the current storage to a new container 180 var storage Storage 181 if !l.cfg.DisableStorage { 182 storage = l.changedValues[contract.Address()].Copy() 183 } 184 // create a new snapshot of the EVM. 185 log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, storage, depth, env.StateDB.GetRefund(), err} 186 187 l.logs = append(l.logs, log) 188 return nil 189 } 190 191 // CaptureFault implements the Tracer interface to trace an execution fault 192 // while running an opcode. 193 func (l *StructLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error { 194 return nil 195 } 196 197 // CaptureEnd is called after the call finishes to finalize the tracing. 198 func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error { 199 l.output = output 200 l.err = err 201 if l.cfg.Debug { 202 fmt.Printf("0x%x\n", output) 203 if err != nil { 204 fmt.Printf(" error: %v\n", err) 205 } 206 } 207 return nil 208 } 209 210 // StructLogs returns the captured log entries. 211 func (l *StructLogger) StructLogs() []StructLog { return l.logs } 212 213 // Error returns the VM error captured by the trace. 214 func (l *StructLogger) Error() error { return l.err } 215 216 // Output returns the VM return value captured by the trace. 217 func (l *StructLogger) Output() []byte { return l.output } 218 219 // WriteTrace writes a formatted trace to the given writer 220 func WriteTrace(writer io.Writer, logs []StructLog) { 221 for _, log := range logs { 222 fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost) 223 if log.Err != nil { 224 fmt.Fprintf(writer, " ERROR: %v", log.Err) 225 } 226 fmt.Fprintln(writer) 227 228 if len(log.Stack) > 0 { 229 fmt.Fprintln(writer, "Stack:") 230 for i := len(log.Stack) - 1; i >= 0; i-- { 231 fmt.Fprintf(writer, "%08d %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32)) 232 } 233 } 234 if len(log.Memory) > 0 { 235 fmt.Fprintln(writer, "Memory:") 236 fmt.Fprint(writer, hex.Dump(log.Memory)) 237 } 238 if len(log.Storage) > 0 { 239 fmt.Fprintln(writer, "Storage:") 240 for h, item := range log.Storage { 241 fmt.Fprintf(writer, "%x: %x\n", h, item) 242 } 243 } 244 fmt.Fprintln(writer) 245 } 246 } 247 248 // WriteLogs writes vm logs in a readable format to the given writer 249 func WriteLogs(writer io.Writer, logs []*types.Log) { 250 for _, log := range logs { 251 fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex) 252 253 for i, topic := range log.Topics { 254 fmt.Fprintf(writer, "%08d %x\n", i, topic) 255 } 256 257 fmt.Fprint(writer, hex.Dump(log.Data)) 258 fmt.Fprintln(writer) 259 } 260 }