github.com/core-coin/go-core/v2@v2.1.9/core/vm/logger.go (about) 1 // Copyright 2015 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 package vm 18 19 import ( 20 "encoding/hex" 21 "errors" 22 "fmt" 23 "io" 24 "math/big" 25 "strings" 26 "time" 27 28 "github.com/core-coin/go-core/v2/common" 29 "github.com/core-coin/go-core/v2/common/hexutil" 30 "github.com/core-coin/go-core/v2/common/math" 31 "github.com/core-coin/go-core/v2/core/types" 32 ) 33 34 var errTraceLimitReached = errors.New("the number of logs reached the specified limit") 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 CVM 49 type LogConfig struct { 50 DisableMemory bool // disable memory capture 51 DisableStack bool // disable stack capture 52 DisableStorage bool // disable storage capture 53 DisableReturnData bool // disable return data 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 CVM 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 Energy uint64 `json:"energy"` 66 EnergyCost uint64 `json:"energyCost"` 67 Memory []byte `json:"memory"` 68 MemorySize int `json:"memSize"` 69 Stack []*big.Int `json:"stack"` 70 ReturnStack []uint32 `json:"returnStack"` 71 ReturnData []byte `json:"returnData"` 72 Storage map[common.Hash]common.Hash `json:"-"` 73 Depth int `json:"depth"` 74 RefundCounter uint64 `json:"refund"` 75 Err error `json:"-"` 76 } 77 78 // overrides for gencodec 79 type structLogMarshaling struct { 80 Stack []*math.HexOrDecimal256 81 ReturnStack []math.HexOrDecimal64 82 Energy math.HexOrDecimal64 83 EnergyCost 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"` // 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 // Tracer is used to collect execution traces from an CVM transaction 104 // execution. CaptureState is called for each step of the VM with the 105 // current VM state. 106 // Note that reference types are actual VM data structures; make copies 107 // if you need to retain them beyond the current call. 108 type Tracer interface { 109 CaptureStart(from common.Address, to common.Address, create bool, input []byte, energy uint64, value *big.Int) error 110 CaptureState(env *CVM, pc uint64, op OpCode, energy, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, rData []byte, contract *Contract, depth int, err error) error 111 CaptureFault(env *CVM, pc uint64, op OpCode, energy, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, contract *Contract, depth int, err error) error 112 CaptureEnd(output []byte, energyUsed uint64, t time.Duration, err error) error 113 } 114 115 // StructLogger is an CVM state logger and implements Tracer. 116 // 117 // StructLogger can capture state based on the given Log configuration and also keeps 118 // a track record of modified storage which is used in reporting snapshots of the 119 // contract their storage. 120 type StructLogger struct { 121 cfg LogConfig 122 123 storage map[common.Address]Storage 124 logs []StructLog 125 output []byte 126 err error 127 } 128 129 // NewStructLogger returns a new logger 130 func NewStructLogger(cfg *LogConfig) *StructLogger { 131 logger := &StructLogger{ 132 storage: make(map[common.Address]Storage), 133 } 134 if cfg != nil { 135 logger.cfg = *cfg 136 } 137 return logger 138 } 139 140 // CaptureStart implements the Tracer interface to initialize the tracing operation. 141 func (l *StructLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, energy uint64, value *big.Int) error { 142 return nil 143 } 144 145 // CaptureState logs a new structured log message and pushes it out to the environment 146 // 147 // CaptureState also tracks SLOAD/SSTORE ops to track storage change. 148 func (l *StructLogger) CaptureState(env *CVM, pc uint64, op OpCode, energy, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, rData []byte, contract *Contract, depth int, err error) error { 149 // check if already accumulated the specified number of logs 150 if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) { 151 return errTraceLimitReached 152 } 153 // Copy a snapshot of the current memory state to a new buffer 154 var mem []byte 155 if !l.cfg.DisableMemory { 156 mem = make([]byte, len(memory.Data())) 157 copy(mem, memory.Data()) 158 } 159 // Copy a snapshot of the current stack state to a new buffer 160 var stck []*big.Int 161 if !l.cfg.DisableStack { 162 stck = make([]*big.Int, len(stack.Data())) 163 for i, item := range stack.Data() { 164 stck[i] = new(big.Int).Set(item.ToBig()) 165 } 166 } 167 var rstack []uint32 168 if !l.cfg.DisableStack && rStack != nil { 169 rstck := make([]uint32, len(rStack.data)) 170 copy(rstck, rStack.data) 171 } 172 // Copy a snapshot of the current storage to a new container 173 var storage Storage 174 if !l.cfg.DisableStorage { 175 // initialise new changed values storage container for this contract 176 // if not present. 177 if l.storage[contract.Address()] == nil { 178 l.storage[contract.Address()] = make(Storage) 179 } 180 // capture SLOAD opcodes and record the read entry in the local storage 181 if op == SLOAD && stack.len() >= 1 { 182 var ( 183 address = common.Hash(stack.data[stack.len()-1].Bytes32()) 184 value = env.StateDB.GetState(contract.Address(), address) 185 ) 186 l.storage[contract.Address()][address] = value 187 } 188 // capture SSTORE opcodes and record the written entry in the local storage. 189 if op == SSTORE && stack.len() >= 2 { 190 var ( 191 value = common.Hash(stack.data[stack.len()-2].Bytes32()) 192 address = common.Hash(stack.data[stack.len()-1].Bytes32()) 193 ) 194 l.storage[contract.Address()][address] = value 195 } 196 storage = l.storage[contract.Address()].Copy() 197 } 198 var rdata []byte 199 if !l.cfg.DisableReturnData { 200 rdata = make([]byte, len(rData)) 201 copy(rdata, rData) 202 } 203 // create a new snapshot of the CVM. 204 log := StructLog{pc, op, energy, cost, mem, memory.Len(), stck, rstack, rdata, storage, depth, env.StateDB.GetRefund(), err} 205 l.logs = append(l.logs, log) 206 return nil 207 } 208 209 // CaptureFault implements the Tracer interface to trace an execution fault 210 // while running an opcode. 211 func (l *StructLogger) CaptureFault(env *CVM, pc uint64, op OpCode, energy, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, contract *Contract, depth int, err error) error { 212 return nil 213 } 214 215 // CaptureEnd is called after the call finishes to finalize the tracing. 216 func (l *StructLogger) CaptureEnd(output []byte, energyUsed uint64, t time.Duration, err error) error { 217 l.output = output 218 l.err = err 219 if l.cfg.Debug { 220 fmt.Printf("0x%x\n", output) 221 if err != nil { 222 fmt.Printf(" error: %v\n", err) 223 } 224 } 225 return nil 226 } 227 228 // StructLogs returns the captured log entries. 229 func (l *StructLogger) StructLogs() []StructLog { return l.logs } 230 231 // Error returns the VM error captured by the trace. 232 func (l *StructLogger) Error() error { return l.err } 233 234 // Output returns the VM return value captured by the trace. 235 func (l *StructLogger) Output() []byte { return l.output } 236 237 // WriteTrace writes a formatted trace to the given writer 238 func WriteTrace(writer io.Writer, logs []StructLog) { 239 for _, log := range logs { 240 fmt.Fprintf(writer, "%-16spc=%08d energy=%v cost=%v", log.Op, log.Pc, log.Energy, log.EnergyCost) 241 if log.Err != nil { 242 fmt.Fprintf(writer, " ERROR: %v", log.Err) 243 } 244 fmt.Fprintln(writer) 245 246 if len(log.Stack) > 0 { 247 fmt.Fprintln(writer, "Stack:") 248 for i := len(log.Stack) - 1; i >= 0; i-- { 249 fmt.Fprintf(writer, "%08d %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32)) 250 } 251 } 252 if len(log.ReturnStack) > 0 { 253 fmt.Fprintln(writer, "ReturnStack:") 254 for i := len(log.Stack) - 1; i >= 0; i-- { 255 fmt.Fprintf(writer, "%08d 0x%x (%d)\n", len(log.Stack)-i-1, log.ReturnStack[i], log.ReturnStack[i]) 256 } 257 } 258 if len(log.Memory) > 0 { 259 fmt.Fprintln(writer, "Memory:") 260 fmt.Fprint(writer, hex.Dump(log.Memory)) 261 } 262 if len(log.Storage) > 0 { 263 fmt.Fprintln(writer, "Storage:") 264 for h, item := range log.Storage { 265 fmt.Fprintf(writer, "%x: %x\n", h, item) 266 } 267 } 268 if len(log.ReturnData) > 0 { 269 fmt.Fprintln(writer, "ReturnData:") 270 fmt.Fprint(writer, hex.Dump(log.ReturnData)) 271 } 272 fmt.Fprintln(writer) 273 } 274 } 275 276 // WriteLogs writes vm logs in a readable format to the given writer 277 func WriteLogs(writer io.Writer, logs []*types.Log) { 278 for _, log := range logs { 279 fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex) 280 281 for i, topic := range log.Topics { 282 fmt.Fprintf(writer, "%08d %x\n", i, topic) 283 } 284 285 fmt.Fprint(writer, hex.Dump(log.Data)) 286 fmt.Fprintln(writer) 287 } 288 } 289 290 type mdLogger struct { 291 out io.Writer 292 cfg *LogConfig 293 } 294 295 // NewMarkdownLogger creates a logger which outputs information in a format adapted 296 // for human readability, and is also a valid markdown table 297 func NewMarkdownLogger(cfg *LogConfig, writer io.Writer) *mdLogger { 298 l := &mdLogger{writer, cfg} 299 if l.cfg == nil { 300 l.cfg = &LogConfig{} 301 } 302 return l 303 } 304 305 func (t *mdLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, energy uint64, value *big.Int) error { 306 if !create { 307 fmt.Fprintf(t.out, "From: `%v`\nTo: `%v`\nData: `0x%x`\nEnergy: `%d`\nValue `%v` ore\n", 308 from.String(), to.String(), 309 input, energy, value) 310 } else { 311 fmt.Fprintf(t.out, "From: `%v`\nCreate at: `%v`\nData: `0x%x`\nEnergy: `%d`\nValue `%v` ore\n", 312 from.String(), to.String(), 313 input, energy, value) 314 } 315 316 fmt.Fprintf(t.out, ` 317 | Pc | Op | Cost | Stack | RStack | 318 |-------|-------------|------|-----------|-----------| 319 `) 320 return nil 321 } 322 323 func (t *mdLogger) CaptureState(env *CVM, pc uint64, op OpCode, energy, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, rData []byte, contract *Contract, depth int, err error) error { 324 fmt.Fprintf(t.out, "| %4d | %10v | %3d |", pc, op, cost) 325 326 if !t.cfg.DisableStack { 327 // format stack 328 var a []string 329 for _, elem := range stack.data { 330 a = append(a, fmt.Sprintf("%d", elem)) 331 } 332 b := fmt.Sprintf("[%v]", strings.Join(a, ",")) 333 fmt.Fprintf(t.out, "%10v |", b) 334 335 // format return stack 336 a = a[:0] 337 for _, elem := range rStack.data { 338 a = append(a, fmt.Sprintf("%2d", elem)) 339 } 340 b = fmt.Sprintf("[%v]", strings.Join(a, ",")) 341 fmt.Fprintf(t.out, "%10v |", b) 342 } 343 fmt.Fprintln(t.out, "") 344 if err != nil { 345 fmt.Fprintf(t.out, "Error: %v\n", err) 346 } 347 return nil 348 } 349 350 func (t *mdLogger) CaptureFault(env *CVM, pc uint64, op OpCode, energy, cost uint64, memory *Memory, stack *Stack, rStack *ReturnStack, contract *Contract, depth int, err error) error { 351 352 fmt.Fprintf(t.out, "\nError: at pc=%d, op=%v: %v\n", pc, op, err) 353 354 return nil 355 } 356 357 func (t *mdLogger) CaptureEnd(output []byte, gasUsed uint64, tm time.Duration, err error) error { 358 fmt.Fprintf(t.out, ` 359 Output: 0x%x 360 Consumed gas: %d 361 Error: %v 362 `, 363 output, gasUsed, err) 364 return nil 365 }