logger.go 6.5 KB

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