logger.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. "fmt"
  19. "math/big"
  20. "os"
  21. "unicode"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/math"
  24. )
  25. type Storage map[common.Hash]common.Hash
  26. func (self Storage) Copy() Storage {
  27. cpy := make(Storage)
  28. for key, value := range self {
  29. cpy[key] = value
  30. }
  31. return cpy
  32. }
  33. // LogConfig are the configuration options for structured logger the EVM
  34. type LogConfig struct {
  35. DisableMemory bool // disable memory capture
  36. DisableStack bool // disable stack capture
  37. DisableStorage bool // disable storage capture
  38. FullStorage bool // show full storage (slow)
  39. Limit int // maximum length of output, but zero means unlimited
  40. }
  41. // StructLog is emitted to the EVM each cycle and lists information about the current internal state
  42. // prior to the execution of the statement.
  43. type StructLog struct {
  44. Pc uint64
  45. Op OpCode
  46. Gas *big.Int
  47. GasCost *big.Int
  48. Memory []byte
  49. Stack []*big.Int
  50. Storage map[common.Hash]common.Hash
  51. Depth int
  52. Err error
  53. }
  54. // Tracer is used to collect execution traces from an EVM transaction
  55. // execution. CaptureState is called for each step of the VM with the
  56. // current VM state.
  57. // Note that reference types are actual VM data structures; make copies
  58. // if you need to retain them beyond the current call.
  59. type Tracer interface {
  60. CaptureState(env *EVM, pc uint64, op OpCode, gas, cost *big.Int, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error
  61. }
  62. // StructLogger is an EVM state logger and implements Tracer.
  63. //
  64. // StructLogger can capture state based on the given Log configuration and also keeps
  65. // a track record of modified storage which is used in reporting snapshots of the
  66. // contract their storage.
  67. type StructLogger struct {
  68. cfg LogConfig
  69. logs []StructLog
  70. changedValues map[common.Address]Storage
  71. }
  72. // NewLogger returns a new logger
  73. func NewStructLogger(cfg *LogConfig) *StructLogger {
  74. logger := &StructLogger{
  75. changedValues: make(map[common.Address]Storage),
  76. }
  77. if cfg != nil {
  78. logger.cfg = *cfg
  79. }
  80. return logger
  81. }
  82. // captureState logs a new structured log message and pushes it out to the environment
  83. //
  84. // captureState also tracks SSTORE ops to track dirty values.
  85. func (l *StructLogger) CaptureState(env *EVM, pc uint64, op OpCode, gas, cost *big.Int, memory *Memory, stack *Stack, contract *Contract, depth int, err error) error {
  86. // check if already accumulated the specified number of logs
  87. if l.cfg.Limit != 0 && l.cfg.Limit <= len(l.logs) {
  88. return ErrTraceLimitReached
  89. }
  90. // initialise new changed values storage container for this contract
  91. // if not present.
  92. if l.changedValues[contract.Address()] == nil {
  93. l.changedValues[contract.Address()] = make(Storage)
  94. }
  95. // capture SSTORE opcodes and determine the changed value and store
  96. // it in the local storage container. NOTE: we do not need to do any
  97. // range checks here because that's already handler prior to calling
  98. // this function.
  99. switch op {
  100. case SSTORE:
  101. var (
  102. value = common.BigToHash(stack.data[stack.len()-2])
  103. address = common.BigToHash(stack.data[stack.len()-1])
  104. )
  105. l.changedValues[contract.Address()][address] = value
  106. }
  107. // copy a snapstot of the current memory state to a new buffer
  108. var mem []byte
  109. if !l.cfg.DisableMemory {
  110. mem = make([]byte, len(memory.Data()))
  111. copy(mem, memory.Data())
  112. }
  113. // copy a snapshot of the current stack state to a new buffer
  114. var stck []*big.Int
  115. if !l.cfg.DisableStack {
  116. stck = make([]*big.Int, len(stack.Data()))
  117. for i, item := range stack.Data() {
  118. stck[i] = new(big.Int).Set(item)
  119. }
  120. }
  121. // Copy the storage based on the settings specified in the log config. If full storage
  122. // is disabled (default) we can use the simple Storage.Copy method, otherwise we use
  123. // the state object to query for all values (slow process).
  124. var storage Storage
  125. if !l.cfg.DisableStorage {
  126. if l.cfg.FullStorage {
  127. storage = make(Storage)
  128. // Get the contract account and loop over each storage entry. This may involve looping over
  129. // the trie and is a very expensive process.
  130. env.StateDB.ForEachStorage(contract.Address(), func(key, value common.Hash) bool {
  131. storage[key] = value
  132. // Return true, indicating we'd like to continue.
  133. return true
  134. })
  135. } else {
  136. // copy a snapshot of the current storage to a new container.
  137. storage = l.changedValues[contract.Address()].Copy()
  138. }
  139. }
  140. // create a new snaptshot of the EVM.
  141. log := StructLog{pc, op, new(big.Int).Set(gas), cost, mem, stck, storage, env.depth, err}
  142. l.logs = append(l.logs, log)
  143. return nil
  144. }
  145. // StructLogs returns a list of captured log entries
  146. func (l *StructLogger) StructLogs() []StructLog {
  147. return l.logs
  148. }
  149. // StdErrFormat formats a slice of StructLogs to human readable format
  150. func StdErrFormat(logs []StructLog) {
  151. fmt.Fprintf(os.Stderr, "VM STAT %d OPs\n", len(logs))
  152. for _, log := range logs {
  153. fmt.Fprintf(os.Stderr, "PC %08d: %s GAS: %v COST: %v", log.Pc, log.Op, log.Gas, log.GasCost)
  154. if log.Err != nil {
  155. fmt.Fprintf(os.Stderr, " ERROR: %v", log.Err)
  156. }
  157. fmt.Fprintf(os.Stderr, "\n")
  158. fmt.Fprintln(os.Stderr, "STACK =", len(log.Stack))
  159. for i := len(log.Stack) - 1; i >= 0; i-- {
  160. fmt.Fprintf(os.Stderr, "%04d: %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32))
  161. }
  162. const maxMem = 10
  163. addr := 0
  164. fmt.Fprintln(os.Stderr, "MEM =", len(log.Memory))
  165. for i := 0; i+16 <= len(log.Memory) && addr < maxMem; i += 16 {
  166. data := log.Memory[i : i+16]
  167. str := fmt.Sprintf("%04d: % x ", addr*16, data)
  168. for _, r := range data {
  169. if r == 0 {
  170. str += "."
  171. } else if unicode.IsPrint(rune(r)) {
  172. str += fmt.Sprintf("%s", string(r))
  173. } else {
  174. str += "?"
  175. }
  176. }
  177. addr++
  178. fmt.Fprintln(os.Stderr, str)
  179. }
  180. fmt.Fprintln(os.Stderr, "STORAGE =", len(log.Storage))
  181. for h, item := range log.Storage {
  182. fmt.Fprintf(os.Stderr, "%x: %x\n", h, item)
  183. }
  184. fmt.Fprintln(os.Stderr)
  185. }
  186. }