logger.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. // StructLogCollector is the basic interface to capture emited logs by the EVM logger.
  33. type StructLogCollector interface {
  34. // Adds the structured log to the collector.
  35. AddStructLog(StructLog)
  36. }
  37. // LogConfig are the configuration options for structured logger the EVM
  38. type LogConfig struct {
  39. DisableMemory bool // disable memory capture
  40. DisableStack bool // disable stack capture
  41. DisableStorage bool // disable storage capture
  42. FullStorage bool // show full storage (slow)
  43. Collector StructLogCollector // the log collector
  44. }
  45. // StructLog is emitted to the Environment 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
  49. Op OpCode
  50. Gas *big.Int
  51. GasCost *big.Int
  52. Memory []byte
  53. Stack []*big.Int
  54. Storage map[common.Hash]common.Hash
  55. Depth int
  56. Err error
  57. }
  58. // Logger is an EVM state logger and implements VmLogger.
  59. //
  60. // Logger can capture state based on the given Log configuration and also keeps
  61. // a track record of modified storage which is used in reporting snapshots of the
  62. // contract their storage.
  63. type Logger struct {
  64. cfg LogConfig
  65. env Environment
  66. changedValues map[common.Address]Storage
  67. }
  68. // newLogger returns a new logger
  69. func newLogger(cfg LogConfig, env Environment) *Logger {
  70. return &Logger{
  71. cfg: cfg,
  72. env: env,
  73. changedValues: make(map[common.Address]Storage),
  74. }
  75. }
  76. // captureState logs a new structured log message and pushes it out to the environment
  77. //
  78. // captureState also tracks SSTORE ops to track dirty values.
  79. func (l *Logger) captureState(pc uint64, op OpCode, gas, cost *big.Int, memory *Memory, stack *stack, contract *Contract, err error) {
  80. // short circuit if no log collector is present
  81. if l.cfg.Collector == nil {
  82. return
  83. }
  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. l.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, l.env.Depth(), err}
  136. // Add the log to the collector
  137. l.cfg.Collector.AddStructLog(log)
  138. }
  139. // StdErrFormat formats a slice of StructLogs to human readable format
  140. func StdErrFormat(logs []StructLog) {
  141. fmt.Fprintf(os.Stderr, "VM STAT %d OPs\n", len(logs))
  142. for _, log := range logs {
  143. fmt.Fprintf(os.Stderr, "PC %08d: %s GAS: %v COST: %v", log.Pc, log.Op, log.Gas, log.GasCost)
  144. if log.Err != nil {
  145. fmt.Fprintf(os.Stderr, " ERROR: %v", log.Err)
  146. }
  147. fmt.Fprintf(os.Stderr, "\n")
  148. fmt.Fprintln(os.Stderr, "STACK =", len(log.Stack))
  149. for i := len(log.Stack) - 1; i >= 0; i-- {
  150. fmt.Fprintf(os.Stderr, "%04d: %x\n", len(log.Stack)-i-1, common.LeftPadBytes(log.Stack[i].Bytes(), 32))
  151. }
  152. const maxMem = 10
  153. addr := 0
  154. fmt.Fprintln(os.Stderr, "MEM =", len(log.Memory))
  155. for i := 0; i+16 <= len(log.Memory) && addr < maxMem; i += 16 {
  156. data := log.Memory[i : i+16]
  157. str := fmt.Sprintf("%04d: % x ", addr*16, data)
  158. for _, r := range data {
  159. if r == 0 {
  160. str += "."
  161. } else if unicode.IsPrint(rune(r)) {
  162. str += fmt.Sprintf("%s", string(r))
  163. } else {
  164. str += "?"
  165. }
  166. }
  167. addr++
  168. fmt.Fprintln(os.Stderr, str)
  169. }
  170. fmt.Fprintln(os.Stderr, "STORAGE =", len(log.Storage))
  171. for h, item := range log.Storage {
  172. fmt.Fprintf(os.Stderr, "%x: %x\n", h, item)
  173. }
  174. fmt.Fprintln(os.Stderr)
  175. }
  176. }