logger.go 6.5 KB

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