logger.go 8.8 KB

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