logger.go 8.7 KB

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