logger.go 6.3 KB

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