logger.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. package vm
  17. import (
  18. "encoding/hex"
  19. "fmt"
  20. "io"
  21. "math/big"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/common/hexutil"
  25. "github.com/ethereum/go-ethereum/common/math"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. )
  28. // Storage represents a contract's storage.
  29. type Storage map[common.Hash]common.Hash
  30. // Copy duplicates the current storage.
  31. func (s Storage) Copy() Storage {
  32. cpy := make(Storage)
  33. for key, value := range s {
  34. cpy[key] = value
  35. }
  36. return cpy
  37. }
  38. // LogConfig are the configuration options for structured logger the EVM
  39. type LogConfig struct {
  40. DisableMemory bool // disable memory capture
  41. DisableStack bool // disable stack capture
  42. DisableStorage bool // disable storage capture
  43. Debug bool // print output during capture end
  44. Limit int // maximum length of output, but zero means unlimited
  45. }
  46. //go:generate gencodec -type StructLog -field-override structLogMarshaling -out gen_structlog.go
  47. // StructLog is emitted to the EVM each cycle and lists information about the current internal state
  48. // prior to the execution of the statement.
  49. type StructLog struct {
  50. Pc uint64 `json:"pc"`
  51. Op OpCode `json:"op"`
  52. Gas uint64 `json:"gas"`
  53. GasCost uint64 `json:"gasCost"`
  54. Memory []byte `json:"memory"`
  55. MemorySize int `json:"memSize"`
  56. Stack []*big.Int `json:"stack"`
  57. Storage map[common.Hash]common.Hash `json:"-"`
  58. Depth int `json:"depth"`
  59. Err error `json:"-"`
  60. }
  61. // overrides for gencodec
  62. type structLogMarshaling struct {
  63. Stack []*math.HexOrDecimal256
  64. Gas math.HexOrDecimal64
  65. GasCost math.HexOrDecimal64
  66. Memory hexutil.Bytes
  67. OpName string `json:"opName"` // adds call to OpName() in MarshalJSON
  68. ErrorString string `json:"error"` // adds call to ErrorString() in MarshalJSON
  69. }
  70. // OpName formats the operand name in a human-readable format.
  71. func (s *StructLog) OpName() string {
  72. return s.Op.String()
  73. }
  74. // ErrorString formats the log's error as a string.
  75. func (s *StructLog) ErrorString() string {
  76. if s.Err != nil {
  77. return s.Err.Error()
  78. }
  79. return ""
  80. }
  81. // Tracer is used to collect execution traces from an EVM transaction
  82. // execution. CaptureState is called for each step of the VM with the
  83. // current VM state.
  84. // Note that reference types are actual VM data structures; make copies
  85. // if you need to retain them beyond the current call.
  86. type Tracer interface {
  87. CaptureStart(from common.Address, to common.Address, call bool, input []byte, gas uint64, value *big.Int) error
  88. CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
  89. CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
  90. CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error
  91. }
  92. // StructLogger is an EVM state logger and implements Tracer.
  93. //
  94. // StructLogger can capture state based on the given Log configuration and also keeps
  95. // a track record of modified storage which is used in reporting snapshots of the
  96. // contract their storage.
  97. type StructLogger struct {
  98. cfg LogConfig
  99. logs []StructLog
  100. changedValues map[common.Address]Storage
  101. output []byte
  102. err error
  103. }
  104. // NewStructLogger returns a new logger
  105. func NewStructLogger(cfg *LogConfig) *StructLogger {
  106. logger := &StructLogger{
  107. changedValues: make(map[common.Address]Storage),
  108. }
  109. if cfg != nil {
  110. logger.cfg = *cfg
  111. }
  112. return logger
  113. }
  114. // CaptureStart implements the Tracer interface to initialize the tracing operation.
  115. func (l *StructLogger) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
  116. return nil
  117. }
  118. // CaptureState logs a new structured log message and pushes it out to the environment
  119. //
  120. // CaptureState also tracks SSTORE ops to track dirty values.
  121. func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
  122. // check if already accumulated the specified number of logs
  123. if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
  124. return ErrTraceLimitReached
  125. }
  126. // initialise new changed values storage container for this contract
  127. // if not present.
  128. if l.changedValues[contract.Address()] == nil {
  129. l.changedValues[contract.Address()] = make(Storage)
  130. }
  131. // capture SSTORE opcodes and determine the changed value and store
  132. // it in the local storage container.
  133. if op == SSTORE && stack.len() >= 2 {
  134. var (
  135. value = common.BigToHash(stack.data[stack.len()-2])
  136. address = common.BigToHash(stack.data[stack.len()-1])
  137. )
  138. l.changedValues[contract.Address()][address] = value
  139. }
  140. // Copy a snapstot of the current memory state to a new buffer
  141. var mem []byte
  142. if !l.cfg.DisableMemory {
  143. mem = make([]byte, len(memory.Data()))
  144. copy(mem, memory.Data())
  145. }
  146. // Copy a snapshot of the current stack state to a new buffer
  147. var stck []*big.Int
  148. if !l.cfg.DisableStack {
  149. stck = make([]*big.Int, len(stack.Data()))
  150. for i, item := range stack.Data() {
  151. stck[i] = new(big.Int).Set(item)
  152. }
  153. }
  154. // Copy a snapshot of the current storage to a new container
  155. var storage Storage
  156. if !l.cfg.DisableStorage {
  157. storage = l.changedValues[contract.Address()].Copy()
  158. }
  159. // create a new snaptshot of the EVM.
  160. log := StructLog{pc, op, gas, cost, mem, memory.Len(), stck, storage, depth, err}
  161. l.logs = append(l.logs, log)
  162. return nil
  163. }
  164. // CaptureFault implements the Tracer interface to trace an execution fault
  165. // while running an opcode.
  166. func (l *StructLogger) CaptureFault(env *EVM, pc uint64, op OpCode, gas, cost uint64, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
  167. return nil
  168. }
  169. // CaptureEnd is called after the call finishes to finalize the tracing.
  170. func (l *StructLogger) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error {
  171. l.output = output
  172. l.err = err
  173. if l.cfg.Debug {
  174. fmt.Printf("0x%x\n", output)
  175. if err != nil {
  176. fmt.Printf(" error: %v\n", err)
  177. }
  178. }
  179. return nil
  180. }
  181. // StructLogs returns the captured log entries.
  182. func (l *StructLogger) StructLogs() []StructLog { return l.logs }
  183. // Error returns the VM error captured by the trace.
  184. func (l *StructLogger) Error() error { return l.err }
  185. // Output returns the VM return value captured by the trace.
  186. func (l *StructLogger) Output() []byte { return l.output }
  187. // WriteTrace writes a formatted trace to the given writer
  188. func WriteTrace(writer io.Writer, logs []StructLog) {
  189. for _, log := range logs {
  190. fmt.Fprintf(writer, "%-16spc=%08d gas=%v cost=%v", log.Op, log.Pc, log.Gas, log.GasCost)
  191. if log.Err != nil {
  192. fmt.Fprintf(writer, " ERROR: %v", log.Err)
  193. }
  194. fmt.Fprintln(writer)
  195. if len(log.Stack) > 0 {
  196. fmt.Fprintln(writer, "Stack:")
  197. for i := len(log.Stack) - 1; i >= 0; i-- {
  198. fmt.Fprintf(writer, "%08d %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32))
  199. }
  200. }
  201. if len(log.Memory) > 0 {
  202. fmt.Fprintln(writer, "Memory:")
  203. fmt.Fprint(writer, hex.Dump(log.Memory))
  204. }
  205. if len(log.Storage) > 0 {
  206. fmt.Fprintln(writer, "Storage:")
  207. for h, item := range log.Storage {
  208. fmt.Fprintf(writer, "%x: %x\n", h, item)
  209. }
  210. }
  211. fmt.Fprintln(writer)
  212. }
  213. }
  214. // WriteLogs writes vm logs in a readable format to the given writer
  215. func WriteLogs(writer io.Writer, logs []*types.Log) {
  216. for _, log := range logs {
  217. fmt.Fprintf(writer, "LOG%d: %x bn=%d txi=%x\n", len(log.Topics), log.Address, log.BlockNumber, log.TxIndex)
  218. for i, topic := range log.Topics {
  219. fmt.Fprintf(writer, "%08d %x\n", i, topic)
  220. }
  221. fmt.Fprint(writer, hex.Dump(log.Data))
  222. fmt.Fprintln(writer)
  223. }
  224. }