logger.go 8.1 KB

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